diff --git a/admin/src/api/mobileRecording.ts b/admin/src/api/mobileRecording.ts new file mode 100644 index 000000000..7d51cd659 --- /dev/null +++ b/admin/src/api/mobileRecording.ts @@ -0,0 +1,28 @@ +import request from '@/utils/request' + +export interface MobileRecordingMetadata { + id: number + diagnosis_id: number + source_platform: 'android_bcr' + recorded_at: number + duration_ms: number + bound_by: string + playback_location: 'original_device' + created_at: number + updated_at: number +} + +export interface MobileRecordingPage { + lists: MobileRecordingMetadata[] + count: number + page_no: number + page_size: number +} + +export function mobileRecordingPatientLists(params: { + diagnosis_id: number + page_no: number + page_size: number +}): Promise { + return request.get({ url: '/tcm.mobileRecording/patientLists', params }) +} diff --git a/admin/src/views/tcm/diagnosis/components/MobileRecordingPanel.vue b/admin/src/views/tcm/diagnosis/components/MobileRecordingPanel.vue new file mode 100644 index 000000000..be228c84a --- /dev/null +++ b/admin/src/views/tcm/diagnosis/components/MobileRecordingPanel.vue @@ -0,0 +1,102 @@ + + + + + diff --git a/admin/src/views/tcm/diagnosis/edit.vue b/admin/src/views/tcm/diagnosis/edit.vue index 70229bacc..6ace0de38 100644 --- a/admin/src/views/tcm/diagnosis/edit.vue +++ b/admin/src/views/tcm/diagnosis/edit.vue @@ -800,6 +800,19 @@ + + + @@ -840,6 +853,7 @@ import DailyMatrix from './components/DailyMatrix.vue' import FollowupAudioPanel from './components/FollowupAudioPanel.vue' import { followupAudioCapabilities, type FollowupCapabilities } from '@/api/followupAudio' import CaseRecordList from './components/CaseRecordList.vue' +import MobileRecordingPanel from './components/MobileRecordingPanel.vue' import CallRecordPanel from './components/CallRecordPanel.vue' import ConsultationTranscriptPanel from './components/ConsultationTranscriptPanel.vue' import ImChatRecordPanel from './components/ImChatRecordPanel.vue' diff --git a/admin/src/views/tcm/diagnosis/readonly.vue b/admin/src/views/tcm/diagnosis/readonly.vue index e177b2c21..1bbf74a8c 100644 --- a/admin/src/views/tcm/diagnosis/readonly.vue +++ b/admin/src/views/tcm/diagnosis/readonly.vue @@ -98,6 +98,16 @@ +
+
手机录音关联
+
+ +
+
视频录制回放记录
@@ -176,6 +186,7 @@ import { import PatientInfoCard from './components/PatientInfoCard.vue' import PatientCaseCard from './components/PatientCaseCard.vue' import DailyMatrix from './components/DailyMatrix.vue' +import MobileRecordingPanel from './components/MobileRecordingPanel.vue' import CallRecordPanel from './components/CallRecordPanel.vue' import ImChatRecordPanel from './components/ImChatRecordPanel.vue' import AssignLogPanel from './components/AssignLogPanel.vue' diff --git a/app/packaging/doctor_workstation.spec b/app/packaging/doctor_workstation.spec index 7fa9d3f4e..51a42e071 100644 --- a/app/packaging/doctor_workstation.spec +++ b/app/packaging/doctor_workstation.spec @@ -115,6 +115,25 @@ qt_multimedia_hiddenimports = [ if importlib.util.find_spec("opencc") is None: raise SystemExit("Install the project dependencies before packaging (missing opencc)") transcript_datas, transcript_binaries, transcript_hiddenimports = collect_all("opencc") +# The realtime path remains Tencent. This explicit build profile adds offline +# recovery for uploaded recordings whose realtime text is missing/incomplete. +# It never installs dependencies or downloads a model during build/runtime. +if os.environ.get("DOCTOR_INCLUDE_AUDIO_RECOVERY") == "1": + for package in ("faster_whisper", "ctranslate2", "onnxruntime", "av", "tokenizers"): + if importlib.util.find_spec(package) is None: + raise SystemExit(f"Audio recovery requires the local-asr extra: missing {package}") + data, binaries, imports = collect_all(package) + transcript_datas += data + transcript_binaries += binaries + transcript_hiddenimports += imports + recovery_model = Path(os.environ.get("DOCTOR_ASR_MODEL_PATH") or RESOURCES / "local-asr" / "model") + required = ("model.bin", "config.json", "tokenizer.json") + if (not all((recovery_model / name).is_file() and (recovery_model / name).stat().st_size > 0 + for name in required) + or not any((recovery_model / name).is_file() and (recovery_model / name).stat().st_size > 0 + for name in ("vocabulary.txt", "vocabulary.json"))): + raise SystemExit("Audio recovery requires a complete, already installed local model") + transcript_datas.append((str(recovery_model.resolve()), "resources/local-asr/model")) client_resources = [ (str(entry), f"resources/{entry.name}" if entry.is_dir() else "resources") for entry in RESOURCES.iterdir() diff --git a/app/research/recording-transcript-recovery.md b/app/research/recording-transcript-recovery.md new file mode 100644 index 000000000..9da409a16 --- /dev/null +++ b/app/research/recording-transcript-recovery.md @@ -0,0 +1,32 @@ +# 录音已上传但文字缺失:修复及生效(2026-11-06) + +录音上传和实时文字保存原本是两条独立流程。个别客户端发生识别中断或文字请求失败时,音频仍会正常上传。本次不改变腾讯云实时识别通路;增加失败收尾重试,以及通话结束后用本机保留录音补全文字的独立恢复队列。 + +## 用户操作 + +新录音上传后自动检查同一通话的文字;已有完整文字直接保留。若通话还在收尾,有界等待结束后继续。打开「视频录制回放 → 本机录音文件」也会接管旧的待处理记录。上传和文字各有状态;文字失败可以点「重试文字」,不重传录音。保存成功后,在诊单「视频录制回放 → 查看文字」查看。 + +识别完成但网络保存失败时,文字暂存在本机队列,重试复用相同恢复编号和文字;成功后清除本地文字草稿,原录音仍保留。补转写不猜测说话人,服务端标为未知说话人。音频识别上限为 250 MB、2 小时,文字上限 100000 字符,超限或未识别到语音会明确失败,不保存截断结果。 + +## 服务端同步 + +部署以下四个运行文件;沿用已有通话文字表,不新增数据库字段: + +- `server/app/adminapi/controller/tcm/DiagnosisController.php` +- `server/app/adminapi/logic/tcm/DiagnosisLogic.php` +- `server/app/adminapi/http/middleware/AuthMiddleware.php` +- `server/app/adminapi/service/LocalAudioTranscriptRecovery.php` + +新接口 `POST tcm.diagnosis/saveLocalAudioTranscript` 要求账号具备现有 start/upsert/finish 三项转写权限,同时验证当前医生是该通话发起者、通话已结束且上传音频绑定一致。原 session/status 变化时拒绝旧结果;完整文字不覆盖,旧会话分段保留。接口未部署或权限缺失时,客户端不会误报文字已保存。 + +## 客户端生效 + +源码测试版需在结束通话后退出并重新打开整个应用。本轮已构建 `video_companion/dist`。冻结安装包需要重新构建,单独替换网页资源无法更新原生重试和队列代码。 + +补转写使用已有可选 `local-asr` 组件和完整本地模型,不会自动下载安装。当前开发机已验证可用;其他电脑缺少组件会在「文字状态」显示失败原因,录音保持已上传。安装方法见 `local-transcription-setup.md` 的开发环境安装命令;该文其他历史实时通路说明不适用于当前腾讯云模式。 + +如需把补转写能力提供给冻结客户端,在构建 Python 环境中安装 `.[build,local-asr]`,准备完整模型,再设置 `DOCTOR_INCLUDE_AUDIO_RECOVERY=1` 后运行现有打包脚本。模型默认取 `app/resources/local-asr/model`,也支持 `DOCTOR_ASR_MODEL_PATH`。此显式配置将打包运行库、VAD 和模型;缺少文件会中止构建。默认安装包仍采用原有腾讯云依赖配置。本轮未生成或验收新 exe。 + +## 验证范围 + +使用合成通话验证上传与文字状态分离、上传先于挂断、重复提交、保存失败后跨重启复用草稿、原文字保护、身份与音频绑定、服务端事务和迟到实时写入。使用仓库已有公开中文样本运行真实本地模型,验证期间禁网且未输出对话原文。未改写线上通话文字,线上修复效果仍需部署后验证。 diff --git a/app/src/doctor_workstation/__init__.py b/app/src/doctor_workstation/__init__.py index 8e9d851cb..b818a967f 100644 --- a/app/src/doctor_workstation/__init__.py +++ b/app/src/doctor_workstation/__init__.py @@ -3,7 +3,7 @@ __all__ = ["DEBUG_MODE", "ONLINE_API_BASE_URL", "__version__"] # Single source of truth for runtime, package, installer, and executable versions. -__version__ = "1.5.2" +__version__ = "1.5.3" # 调试模式开启时,登录页显示“演示模式”和“服务器设置”。 # 正式发布请保持 False;此时程序只使用下面配置的线上域名。 diff --git a/app/src/doctor_workstation/services/local_audio_queue.py b/app/src/doctor_workstation/services/local_audio_queue.py index eaeb58699..68baf79f4 100644 --- a/app/src/doctor_workstation/services/local_audio_queue.py +++ b/app/src/doctor_workstation/services/local_audio_queue.py @@ -7,6 +7,7 @@ audio file after a successful upload as well as after a failed one. from __future__ import annotations +import json import queue import sqlite3 import threading @@ -22,7 +23,12 @@ from uuid import uuid4 from platformdirs import user_data_path +from ..core.errors import ApiBusinessError, ApiTransportError, AuthenticationExpiredError +from ..video.local_transcription import LocalTranscriptionError +from ..video.recording_transcription import RecordingTranscriber, RecordingTranscriptionError + _MAX_UPLOAD_WORKERS = 3 +_TRANSCRIPTION_END_RETRY_DELAYS = (2, 5, 10, 20, 30, 60, 60) _RETRYABLE_STATUSES = {"pending", "failed"} _RECOVERY_LOCK = threading.Lock() _RECOVERED_DATABASES: set[Path] = set() @@ -30,6 +36,10 @@ _MANAGER_LOCK = threading.Lock() _MANAGERS: dict[tuple[int, Path], LocalAudioUploadManager] = {} +class _CallStillEnding(RuntimeError): + """An upload can finish before the realtime transcript and call end drain.""" + + def _utc_now() -> str: return datetime.now(UTC).isoformat(timespec="seconds") @@ -79,6 +89,9 @@ class LocalAudioRecord: created_at: str updated_at: str uploaded_at: str + transcription_status: str = "pending" + transcription_error: str = "" + transcription_recovery_id: str = "" @property def exists(self) -> bool: @@ -139,6 +152,17 @@ class LocalAudioQueueStore: "ALTER TABLE local_audio_uploads " "ADD COLUMN room_id TEXT NOT NULL DEFAULT ''" ) + for name, default in ( + ("transcription_status", "pending"), + ("transcription_error", ""), + ("transcription_recovery_id", ""), + ("transcription_draft", ""), + ): + if name not in columns: + connection.execute( + f"ALTER TABLE local_audio_uploads ADD COLUMN {name} " + f"TEXT NOT NULL DEFAULT '{default}'" + ) connection.execute( "CREATE INDEX IF NOT EXISTS idx_local_audio_diagnosis " "ON local_audio_uploads(diagnosis_id, id DESC)" @@ -151,6 +175,11 @@ class LocalAudioQueueStore: return with self._connect() as connection: now = _utc_now() + connection.execute( + "UPDATE local_audio_uploads SET transcription_status = 'pending', " + "transcription_error = '上次文字处理未完成,将继续处理。' " + "WHERE transcription_status = 'transcribing'" + ) connection.execute( """ UPDATE local_audio_uploads @@ -194,6 +223,9 @@ class LocalAudioQueueStore: created_at=str(row["created_at"]), updated_at=str(row["updated_at"]), uploaded_at=str(row["uploaded_at"] or ""), + transcription_status=str(row["transcription_status"] or "pending"), + transcription_error=str(row["transcription_error"] or ""), + transcription_recovery_id=str(row["transcription_recovery_id"] or ""), ) def begin_recording( @@ -433,6 +465,62 @@ class LocalAudioQueueStore: ) return self.require(record_id) + def claim_transcription(self, record_id: int) -> LocalAudioRecord | None: + with self._connect() as connection: + cursor = connection.execute( + """ + UPDATE local_audio_uploads + SET transcription_status = 'transcribing', transcription_error = '', + transcription_recovery_id = CASE + WHEN transcription_recovery_id = '' THEN ? + ELSE transcription_recovery_id END, + updated_at = ? + WHERE id = ? AND status = 'uploaded' + AND transcription_status IN ('pending', 'failed') + """, + (f"audio-{uuid4().hex}", _utc_now(), int(record_id)), + ) + if cursor.rowcount != 1: + return None + return self.require(record_id) + + def transcription_draft(self, record_id: int) -> str: + with self._connect() as connection: + row = connection.execute( + "SELECT transcription_draft FROM local_audio_uploads WHERE id = ?", + (int(record_id),), + ).fetchone() + return str(row[0] or "") if row else "" + + def save_transcription_draft(self, record_id: int, text: str) -> None: + # Keep recognized text until the server confirms persistence. A network + # retry/restart must not need to run speech recognition a second time. + with self._connect() as connection: + connection.execute( + "UPDATE local_audio_uploads SET transcription_draft = ? WHERE id = ?", + (text, int(record_id)), + ) + + def finish_transcription(self, record_id: int, *, error: str = "") -> None: + with self._connect() as connection: + connection.execute( + """ + UPDATE local_audio_uploads + SET transcription_status = ?, transcription_error = ?, updated_at = ?, + transcription_draft = CASE WHEN ? = '' THEN '' ELSE transcription_draft END + WHERE id = ? + """, + ("failed" if error else "completed", error[:1000], _utc_now(), error, int(record_id)), + ) + + def defer_transcription(self, record_id: int) -> None: + with self._connect() as connection: + connection.execute( + "UPDATE local_audio_uploads SET transcription_status = 'pending', " + "transcription_error = '等待通话结束后自动补全文字。' WHERE id = ?", + (int(record_id),), + ) + def _upload_url(result: Any) -> str: if not isinstance(result, dict): @@ -455,6 +543,7 @@ class LocalAudioUploadManager: store: LocalAudioQueueStore, *, max_workers: int = _MAX_UPLOAD_WORKERS, + transcriber: Callable[[Path], str] | None = None, ) -> None: self.repository = repository self.store = store @@ -463,6 +552,11 @@ class LocalAudioUploadManager: self._active: dict[int, Future[bool]] = {} self._upload_listeners: set[Callable[[LocalAudioRecord], None]] = set() self._lock = threading.Lock() + self._transcriber = transcriber or RecordingTranscriber() + self._transcription_jobs: queue.Queue[tuple[int, Future[bool]]] = queue.Queue() + self._transcription_active: dict[int, Future[bool]] = {} + self._transcription_waits: dict[int, int] = {} + self._transcription_worker_started = False for index in range(self.max_workers): threading.Thread( target=self._worker, @@ -522,6 +616,147 @@ class LocalAudioUploadManager: if record.status == "pending" ] + def submit_pending_transcriptions( + self, *, diagnosis_id: int | None = None + ) -> list[Future[bool]]: + if not callable(getattr(self.repository, "save_local_audio_transcript", None)): + return [] + return [ + self.submit_transcription(record.id) + for record in self.store.list_records(diagnosis_id=diagnosis_id) + if record.status == "uploaded" and record.transcription_status == "pending" + ] + + def submit_transcription(self, record_id: int) -> Future[bool]: + record_id = int(record_id) + with self._lock: + existing = self._transcription_active.get(record_id) + if existing is not None: + return existing + future: Future[bool] = Future() + self._transcription_active[record_id] = future + if not self._transcription_worker_started: + self._transcription_worker_started = True + threading.Thread( + target=self._transcribe_worker, name="local-audio-text", daemon=True + ).start() + self._transcription_jobs.put((record_id, future)) + return future + + def _transcribe_worker(self) -> None: + while True: + record_id, future = self._transcription_jobs.get() + try: + try: + succeeded = self._transcribe(record_id) + except _CallStillEnding: + waited = self._transcription_waits.get(record_id, 0) + try: + if waited < len(_TRANSCRIPTION_END_RETRY_DELAYS): + self.store.defer_transcription(record_id) + self._transcription_waits[record_id] = waited + 1 + # Leave this Future active so repeated clicks coalesce. + # A timer requeues the job without blocking other files. + timer = threading.Timer( + _TRANSCRIPTION_END_RETRY_DELAYS[waited], + self._transcription_jobs.put, + args=((record_id, future),), + ) + timer.daemon = True + timer.start() + continue + except Exception: + pass # Resolve the Future even if a local queue write fails. + with suppress(Exception): + self.store.finish_transcription( + record_id, error="通话结束状态尚未同步,请稍后重试文字。" + ) + succeeded = False + except Exception as error: + if isinstance(error, (RecordingTranscriptionError, LocalTranscriptionError)): + message = str(error) + elif isinstance(error, AuthenticationExpiredError): + message = "登录已失效,请重新登录后重试文字;本机录音和已识别文字已保留。" + elif isinstance(error, ApiTransportError): + message = "文字同步失败,请检查网络及服务端版本后重试文字;录音无需重传。" + elif isinstance(error, ApiBusinessError): + message = "服务端未接受文字,请检查转写权限、通话状态及服务端版本后重试。" + else: + message = "文字处理未完成,请检查本地转写安装及服务端接口后重试文字。" + with suppress(Exception): + self.store.finish_transcription(record_id, error=message) + succeeded = False + with self._lock: + self._transcription_active.pop(record_id, None) + self._transcription_waits.pop(record_id, None) + if not future.done(): + future.set_result(succeeded) + finally: + self._transcription_jobs.task_done() + + def _transcribe(self, record_id: int) -> bool: + record = self.store.claim_transcription(record_id) + if record is None: + current = self.store.get(record_id) + return bool(current and current.transcription_status == "completed") + save = getattr(self.repository, "save_local_audio_transcript", None) + if not callable(save): + raise RecordingTranscriptionError("当前服务未提供文字补全接口,请更新应用及服务端。") + records = self.repository.list_call_records(record.diagnosis_id) + call = next( + (row for row in records if isinstance(row, dict) + and str(row.get("id")) == str(record.call_record_id)), + None, + ) + if call is None: + raise RecordingTranscriptionError("未找到对应通话记录,请检查账号和诊单后重试文字。") + if call.get("transcription_status") == "completed" and str(call.get("transcript_text") or "").strip(): + self.store.finish_transcription(record.id) + self._notify_uploaded(record.id) + return True + user = self.repository.get_current_user() + if (int(getattr(user, "id", 0) or 0) <= 0 + or str(call.get("caller_id")) != str(user.id) + or call.get("caller_type") != "doctor"): + raise RecordingTranscriptionError("请使用发起这次通话的医生账号补全文字。") + if int(call.get("status") or 0) == 1: + raise _CallStillEnding() + if int(call.get("status") or 0) != 2: + raise RecordingTranscriptionError("通话尚未结束,请结束通话后重试文字。") + if not record.uploaded_url or int(call.get("local_audio_status") or 0) != 2: + raise RecordingTranscriptionError("服务端尚未确认录音上传,请刷新后重试文字。") + audio_urls = call.get("local_audio_urls_list") + if not isinstance(audio_urls, list): + try: + audio_urls = json.loads(str(call.get("local_audio_urls") or "[]")) + except (TypeError, ValueError): + audio_urls = [] + if not isinstance(audio_urls, list) or record.uploaded_url not in audio_urls: + raise RecordingTranscriptionError("上传录音与通话记录不匹配,请刷新后核实。") + text = self.store.transcription_draft(record.id) + if not text: + text = self._transcriber(record.file_path) + if not isinstance(text, str) or not text.strip() or len(text) > 100_000: + raise RecordingTranscriptionError("未生成可保存的文字,请检查录音及本地模型后重试。") + self.store.save_transcription_draft(record.id, text) + result = save( + diagnosis_id=record.diagnosis_id, + call_record_id=record.call_record_id, + recovery_id=record.transcription_recovery_id, + expected_session_id=str(call.get("transcription_session_id") or ""), + expected_status=str(call.get("transcription_status") or ""), + audio_url=record.uploaded_url, + transcript_text=text, + ) + if (not isinstance(result, dict) + or str(result.get("call_record_id")) != str(record.call_record_id) + or result.get("transcription_status") != "completed" + or not (result.get("saved") is True or result.get("already_complete") is True)): + raise RecordingTranscriptionError("服务端未确认文字保存,已识别文字已保留,请重试文字。") + self.store.finish_transcription(record.id) + self._notify_uploaded(record.id) + return True + def _worker(self) -> None: while True: record_id, future = self._jobs.get() @@ -573,6 +808,8 @@ class LocalAudioUploadManager: return False self.store.mark_uploaded(record.id, uploaded_url) self._notify_uploaded(record.id) + if callable(getattr(self.repository, "save_local_audio_transcript", None)): + self.submit_transcription(record.id) return True diff --git a/app/src/doctor_workstation/services/repository.py b/app/src/doctor_workstation/services/repository.py index 869af9cc3..85200053a 100644 --- a/app/src/doctor_workstation/services/repository.py +++ b/app/src/doctor_workstation/services/repository.py @@ -3092,6 +3092,41 @@ class RemoteDoctorRepository: ) return self.client.post("tcm.diagnosis/finishCallTranscription", body) + def save_local_audio_transcript( + self, + *, + diagnosis_id: int, + call_record_id: int, + recovery_id: str, + expected_session_id: str, + expected_status: str, + audio_url: str, + transcript_text: str, + ) -> dict[str, Any]: + """Atomically persist offline text for an uploaded, ended call only.""" + if (isinstance(diagnosis_id, bool) or diagnosis_id <= 0 + or isinstance(call_record_id, bool) or call_record_id <= 0): + raise ValueError("diagnosis_id and call_record_id must be positive") + if not re.fullmatch(r"audio-[0-9a-f]{32}", recovery_id): + raise ValueError("invalid audio recovery id") + if len(expected_session_id) > 128 or expected_status not in { + "", "pending", "running", "partial", "failed", "completed", + }: + raise ValueError("invalid expected transcription state") + if not audio_url.strip() or len(audio_url) > 2000: + raise ValueError("uploaded audio URL is required") + if not transcript_text.strip() or len(transcript_text) > 100_000: + raise ValueError("recording transcript is empty or too long") + return self.client.post("tcm.diagnosis/saveLocalAudioTranscript", { + "diagnosis_id": diagnosis_id, + "call_record_id": call_record_id, + "recovery_id": recovery_id, + "expected_session_id": expected_session_id, + "expected_status": expected_status, + "audio_url": audio_url, + "transcript_text": transcript_text.strip(), + }) + # Compatibility aliases keep UI naming independent from endpoint history. def my_self(self) -> Session: """Compatibility alias for :meth:`get_session`.""" diff --git a/app/src/doctor_workstation/ui/diagnosis_drawer.py b/app/src/doctor_workstation/ui/diagnosis_drawer.py index 38dae4767..c2028ea74 100644 --- a/app/src/doctor_workstation/ui/diagnosis_drawer.py +++ b/app/src/doctor_workstation/ui/diagnosis_drawer.py @@ -68,6 +68,7 @@ from .design_system import PALETTE, clinical_stylesheet from .diagnosis_editors import FlowLayout from .diagnosis_media import shared_image_manager from .diagnosis_terms import FIELD_DICTIONARIES, format_timestamp, shared_terms +from .image_drop import can_drop_images, capture_image_drop DIAGNOSIS_QSS = r""" QDialog#DiagnosisDialogRoot { @@ -994,6 +995,11 @@ QDialog#DiagnosisPrescriptionEditor QSpinBox:focus, QDialog#DiagnosisPrescriptionEditor QDoubleSpinBox:focus { border-color: #8B9AD9; } +QWidget#DiagnosisNotesTimeline QPushButton[imageDropActive="true"] { + background-color: #EEF1FA; + border: 2px dashed #4F63D9; + color: #4F63D9; +} """ # Normalize the legacy component palette in one place. Keeping the selectors @@ -2833,6 +2839,8 @@ class NotesTimeline(QWidget): add_requested = Signal() upload_requested = Signal(str) + images_dropped = Signal(object, str) + image_drop_failed = Signal(str) delete_attachment_requested = Signal(int, str, str) open_attachment_requested = Signal(str) preview_images_requested = Signal(object, int) @@ -2842,6 +2850,9 @@ class NotesTimeline(QWidget): self.setObjectName("DiagnosisNotesTimeline") self._editable = editable self._can_delete = editable + self._upload_available = True + self._upload_busy = False + self._drop_targets: dict[QWidget, str] = {} self._image_generation = 0 self.root = QVBoxLayout(self) self.root.setContentsMargins(0, 0, 0, 0) @@ -2862,6 +2873,10 @@ class NotesTimeline(QWidget): self.tongue_button.clicked.connect(lambda: self.upload_requested.emit("tongue_images")) self.report_button.clicked.connect(lambda: self.upload_requested.emit("report_files")) self.root.addWidget(self.toolbar) + self.drop_hint = QLabel("可拖入图片;拖到“上传舌象”或“上传报告”按钮可直接分类。") + self.drop_hint.setObjectName("DiagnosisDialogGuidance") + self.drop_hint.setWordWrap(True) + self.root.addWidget(self.drop_hint) self.nodes = QWidget() self.nodes_layout = QVBoxLayout(self.nodes) self.nodes_layout.setContentsMargins(22, 0, 0, 0) @@ -2872,12 +2887,89 @@ class NotesTimeline(QWidget): self.empty.setAlignment(Qt.AlignmentFlag.AlignCenter) self.empty.setMinimumHeight(80) self.root.addWidget(self.empty) + self.register_image_drop_target(self) + self.register_image_drop_target(self.tongue_button, "tongue_images") + self.register_image_drop_target(self.report_button, "report_files") + self.tongue_button.setToolTip("点击选择文件,或把图片拖到此处上传为舌象") + self.report_button.setToolTip("点击选择报告,或把图片拖到此处上传为报告") self.set_editable(editable) def set_editable(self, editable: bool, *, can_delete: bool | None = None) -> None: self._editable = editable self._can_delete = editable if can_delete is None else bool(can_delete) self.toolbar.setVisible(self._editable) + self.drop_hint.setVisible(self._editable and self._upload_available) + self._sync_image_drop_targets() + + def set_upload_available(self, available: bool) -> None: + self._upload_available = bool(available) + self.drop_hint.setVisible(self._editable and self._upload_available) + self._sync_image_drop_targets() + + def set_upload_busy(self, busy: bool) -> None: + self._upload_busy = bool(busy) + self._sync_image_drop_targets() + + def register_image_drop_target(self, widget: QWidget, image_type: str = "") -> None: + """Include scroll viewport blank space as well as the note timeline.""" + self._drop_targets[widget] = image_type + widget.installEventFilter(self) + self._sync_image_drop_targets() + + def _sync_image_drop_targets(self) -> None: + enabled = self._editable and self._upload_available and not self._upload_busy + for widget in self._drop_targets: + widget.setAcceptDrops(enabled) + self.tongue_button.setEnabled(enabled) + self.report_button.setEnabled(enabled) + self.add_button.setEnabled(self._editable and not self._upload_busy) + if not enabled: + self._highlight_drop_target(None) + + def _highlight_drop_target(self, active: QWidget | None) -> None: + for button in (self.tongue_button, self.report_button): + highlighted = button is active + if bool(button.property("imageDropActive")) != highlighted: + button.setProperty("imageDropActive", highlighted) + repolish(button) + text = ( + "松开鼠标上传图片;未指定类别时可选择舌象或报告。" + if active is not None else "可拖入图片;拖到“上传舌象”或“上传报告”按钮可直接分类。" + ) + self.drop_hint.setText(text) + + def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802 - Qt API + if watched in self._drop_targets and event.type() in { + QEvent.Type.DragEnter, QEvent.Type.DragMove, QEvent.Type.DragLeave, QEvent.Type.Drop, + }: + if event.type() == QEvent.Type.DragLeave: + self._highlight_drop_target(None) + event.accept() + return True + if (not self._editable or not self._upload_available or self._upload_busy + or not (event.possibleActions() & Qt.DropAction.CopyAction) + or not can_drop_images(event.mimeData())): + self._highlight_drop_target(None) + event.ignore() + return True + if event.type() == QEvent.Type.Drop: + self._highlight_drop_target(None) + try: + payload = capture_image_drop(event.mimeData()) + except ValueError as error: + self.image_drop_failed.emit(str(error)) + event.ignore() + return True + # Copy semantics are essential: uploading never moves the source. + event.setDropAction(Qt.DropAction.CopyAction) + event.accept() + self.images_dropped.emit(payload, self._drop_targets[watched]) + else: + self._highlight_drop_target(watched) + event.setDropAction(Qt.DropAction.CopyAction) + event.accept() + return True + return super().eventFilter(watched, event) def set_state(self, text: str) -> None: self.empty.setText(text) diff --git a/app/src/doctor_workstation/ui/dialogs/diagnosis.py b/app/src/doctor_workstation/ui/dialogs/diagnosis.py index 8f749273e..99129ee5d 100644 --- a/app/src/doctor_workstation/ui/dialogs/diagnosis.py +++ b/app/src/doctor_workstation/ui/dialogs/diagnosis.py @@ -6,7 +6,8 @@ import mimetypes import re import sqlite3 from collections.abc import Mapping, Sequence -from contextlib import suppress +from contextlib import nullcontext, suppress +from dataclasses import dataclass from pathlib import Path from typing import Any @@ -84,6 +85,7 @@ from ..diagnosis_media import ( RecordingPlayerDialog, safe_image_sources, ) +from ..image_drop import ImageDrop, materialize_image_drop from ..infinite_list import InfiniteList from ..theme import main_window_target_rect from ..widgets import ( @@ -110,6 +112,13 @@ class _UploadProgressRelay(QObject): processing = Signal() +@dataclass(frozen=True) +class _NoteAttachmentUploadResult: + saved_count: int + total_count: int + error: str = "" + + _PHONE_PERMISSION = "tcm.diagnosis/phonePlain" _PATIENT_ORDERS_PERMISSION = "tcm.diagnosis/patientOrders" _ORDER_DETAIL_PERMISSION = "tcm.prescriptionOrder/detail" @@ -880,6 +889,8 @@ class DiagnosisDialog(QDialog): self._order_detail_generation = 0 self._daily_mutation_generation = 0 self._notes_mutation_generation = 0 + self._notes_mutation_busy = False + self._notes_refresh_message: tuple[str, str] | None = None self._media_generation = 0 self._prescription_detail_generation = 0 self._prescription_detail_target = 0 @@ -1506,12 +1517,17 @@ class DiagnosisDialog(QDialog): timeline = NotesTimeline(editable=True) timeline.add_requested.connect(self._add_doctor_note) timeline.upload_requested.connect(self._upload_doctor_note_material) + timeline.images_dropped.connect(self._drop_doctor_note_images) + timeline.image_drop_failed.connect(lambda text: self._show_message(text, "warning")) timeline.delete_attachment_requested.connect(self._delete_doctor_note_attachment) timeline.open_attachment_requested.connect(self._open_safe_resource) timeline.preview_images_requested.connect(self._preview_note_images) self.drawer_notes_timeline = timeline self._notes_timelines.append(timeline) - return self._wrap_tab("DiagnosisTabNotes", timeline) + scroll = self._wrap_tab("DiagnosisTabNotes", timeline) + timeline.register_image_drop_target(scroll.viewport()) + timeline.register_image_drop_target(scroll.widget()) + return scroll def _build_prescription_tab(self) -> QWidget: page = QWidget() @@ -1836,6 +1852,8 @@ class DiagnosisDialog(QDialog): and self._can_note_delete ), ) + timeline.set_upload_available(callable(getattr(self.repository, "upload_material", None))) + timeline.set_upload_busy(self._notes_mutation_busy) self.prescribe_button.setVisible(self._editable and self._can_prescribe) self.video_upload_button.setVisible(self._editable and self._can_video_upload) self.local_audio_queue_button.setVisible(self._can_video_upload) @@ -2140,6 +2158,8 @@ class DiagnosisDialog(QDialog): self._order_detail_generation += 1 self._daily_mutation_generation += 1 self._notes_mutation_generation += 1 + self._notes_mutation_busy = False + self._notes_refresh_message = None self._media_generation += 1 self._prescription_detail_generation += 1 self._offset_generation += 1 @@ -2506,6 +2526,8 @@ class DiagnosisDialog(QDialog): self._order_detail_generation += 1 self._daily_mutation_generation += 1 self._notes_mutation_generation += 1 + self._notes_mutation_busy = False + self._notes_refresh_message = None self._media_generation += 1 self._prescription_detail_generation += 1 self._offset_generation += 1 @@ -2940,7 +2962,12 @@ class DiagnosisDialog(QDialog): for panel in self._chat_panels: panel.set_messages(rows) if not self._standalone_readonly and self._current_tab_key() == key: - self._clear_message() + if key == "notes" and self._notes_refresh_message is not None: + self._show_message(*self._notes_refresh_message) + else: + self._clear_message() + if key == "notes": + self._notes_refresh_message = None if key == "video": self._flush_video_reload_if_pending(diagnosis_id) @@ -3245,18 +3272,19 @@ class DiagnosisDialog(QDialog): self._show_message(friendly_error(error), "danger") def _add_doctor_note(self) -> None: - if not self._editable or not self._can_note_add: + if not self._editable or not self._can_note_add or self._notes_mutation_busy: return content, accepted = QInputDialog.getMultiLineText( self, "新增 / 追加诊疗笔记", "笔记内容(最多 500 字)" ) if not accepted: return + diagnosis_id = self._diagnosis_id self._run_notes_mutation( lambda: invoke( self.repository, "add_doctor_note", - diagnosis_id=self._diagnosis_id, + diagnosis_id=diagnosis_id, content=content, ), "诊疗笔记已保存。", @@ -3267,6 +3295,7 @@ class DiagnosisDialog(QDialog): image_type not in {"tongue_images", "report_files"} or not self._editable or not self._can_note_add + or self._notes_mutation_busy ): return if not all( @@ -3284,21 +3313,84 @@ class DiagnosisDialog(QDialog): path, _selected = QFileDialog.getOpenFileName(self, caption, "", file_filter) if not path: return + image_file = Path(path).suffix.lower() in {".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico"} + self._upload_note_attachments( + image_type, lambda: nullcontext([Path(path)]), + upload_type="image" if image_file else image_type, + ) + + def _drop_doctor_note_images(self, payload: ImageDrop, image_type: str) -> None: + if (not self._editable or not self._can_note_add or self._diagnosis_id <= 0 + or self._notes_mutation_busy): + return + diagnosis_id, generation = self._diagnosis_id, self._generation + # End the OS drag before displaying a category chooser. Capture identity + # now so a queued drop cannot attach files to a newly opened patient. + QTimer.singleShot(0, self, lambda: self._accept_dropped_note_images( + payload, image_type, diagnosis_id, generation + )) + + def _choose_dropped_image_type(self, count: int) -> str: + chooser = QMessageBox(self) + chooser.setWindowTitle("选择图片类别") + chooser.setText(f"已拖入 {count} 张图片,请选择保存类别。") + tongue = chooser.addButton("上传为舌象", QMessageBox.ButtonRole.AcceptRole) + report = chooser.addButton("上传为报告", QMessageBox.ButtonRole.ActionRole) + chooser.addButton("取消", QMessageBox.ButtonRole.RejectRole) + chooser.exec() + return "tongue_images" if chooser.clickedButton() is tongue else ( + "report_files" if chooser.clickedButton() is report else "" + ) + + def _accept_dropped_note_images( + self, payload: ImageDrop, image_type: str, diagnosis_id: int, generation: int + ) -> None: + if (diagnosis_id != self._diagnosis_id or generation != self._generation + or not self._editable or not self._can_note_add or self._notes_mutation_busy): + return + if not image_type: + image_type = self._choose_dropped_image_type(payload.count) + # A modal chooser can process a patient change or permissions refresh. + if (image_type not in {"tongue_images", "report_files"} + or diagnosis_id != self._diagnosis_id or generation != self._generation): + return + self._upload_note_attachments( + image_type, lambda: materialize_image_drop(payload), upload_type="image" + ) + + def _upload_note_attachments(self, image_type: str, sources: Any, *, upload_type: str) -> None: + if (not self._editable or not self._can_note_add or self._diagnosis_id <= 0 + or self._notes_mutation_busy or image_type not in {"tongue_images", "report_files"}): + return + if not all(callable(getattr(self.repository, name, None)) + for name in ("upload_material", "add_doctor_note")): + self._show_message("附件上传接口不可用。", "warning") + return diagnosis_id = self._diagnosis_id + repository = self.repository def operation() -> Any: - reference = invoke( - self.repository, - "upload_material", - path=path, - material_type=image_type, - ) - kwargs: dict[str, Any] = { - "diagnosis_id": diagnosis_id, - "content": "", - image_type: [str(reference)], - } - return invoke(self.repository, "add_doctor_note", **kwargs) + with sources() as paths: + references: list[str] = [] + error_text = "" + for path in paths: + try: + reference = invoke(repository, "upload_material", path=str(path), material_type=upload_type) + if not reference: + raise ValueError("服务器未返回图片地址。") + references.append(str(reference)) + except Exception as error: + if not references: + raise + error_text = friendly_error(error) + break + if not references: + raise ValueError("没有可上传的图片。") + # Persist successful images even if a later upload failed, then + # report the exact partial result instead of silently losing it. + invoke(repository, "add_doctor_note", diagnosis_id=diagnosis_id, + content="", **{image_type: references}) + return _NoteAttachmentUploadResult(len(references), len(paths), error_text) self._run_notes_mutation(operation, "附件已上传并写入诊疗笔记。") @@ -3308,6 +3400,7 @@ class DiagnosisDialog(QDialog): if ( not self._editable or not self._can_note_delete + or self._notes_mutation_busy or note_id <= 0 or image_type not in {"tongue_images", "report_files"} or not callable(getattr(self.repository, "delete_doctor_note_image", None)) @@ -3334,22 +3427,47 @@ class DiagnosisDialog(QDialog): ) def _run_notes_mutation(self, operation: Any, success_text: str) -> None: + if self._notes_mutation_busy: + self._show_message("正在上传或保存诊疗笔记,请稍候。", "info") + return + self._notes_mutation_busy = True + self._notes_refresh_message = None + for timeline in self._notes_timelines: + timeline.set_upload_busy(True) self._notes_mutation_generation += 1 generation = self._notes_mutation_generation diagnosis_id = self._diagnosis_id self._show_message("正在更新诊疗笔记…", "info") run_async( operation, - on_success=lambda _result: self._notes_mutation_success( - success_text, diagnosis_id, generation + on_success=lambda result: self._notes_mutation_success( + success_text, diagnosis_id, generation, result ), on_error=lambda error: self._mutation_error(error, diagnosis_id, generation, "notes"), + on_finished=lambda: self._notes_mutation_finished(diagnosis_id, generation), ) - def _notes_mutation_success(self, text: str, diagnosis_id: int, generation: int) -> None: + def _notes_mutation_finished(self, diagnosis_id: int, generation: int) -> None: if generation != self._notes_mutation_generation or diagnosis_id != self._diagnosis_id: return - self._show_message(text, "success") + self._notes_mutation_busy = False + for timeline in self._notes_timelines: + timeline.set_upload_busy(False) + + def _notes_mutation_success( + self, text: str, diagnosis_id: int, generation: int, result: Any = None + ) -> None: + if generation != self._notes_mutation_generation or diagnosis_id != self._diagnosis_id: + return + if isinstance(result, _NoteAttachmentUploadResult) and result.error: + message = ( + f"已保存 {result.saved_count}/{result.total_count} 张。第 {result.saved_count + 1} 张上传失败:" + f"{result.error} 请只重试未成功的图片。", "warning" + ) + else: + message = (text, "success") + self._notes_refresh_message = message + self._show_message(*message) self._loaded_tabs.discard("notes") self._ensure_tab_loaded("notes", force=True) diff --git a/app/src/doctor_workstation/ui/dialogs/local_audio_queue.py b/app/src/doctor_workstation/ui/dialogs/local_audio_queue.py index 0f21c06ee..221504361 100644 --- a/app/src/doctor_workstation/ui/dialogs/local_audio_queue.py +++ b/app/src/doctor_workstation/ui/dialogs/local_audio_queue.py @@ -48,6 +48,18 @@ _STATUS_COLORS = { "failed": "#BE4B58", "invalid": "#606163", } +_TRANSCRIPTION_LABELS = { + "pending": "待生成", + "transcribing": "生成中", + "completed": "已保存", + "failed": "生成失败", +} +_TRANSCRIPTION_COLORS = { + "pending": "#A9691D", + "transcribing": "#1A1C1F", + "completed": "#287B65", + "failed": "#BE4B58", +} _BUSINESS_TIMEZONE = timezone(timedelta(hours=8)) _LOCAL_AUDIO_QSS = """ @@ -140,7 +152,7 @@ def _display_time(value: str) -> str: class LocalAudioQueueDialog(QDialog): - """Persistent local-audio list with concurrent upload and retry.""" + """Persistent local-audio list with separate upload and transcription status.""" def __init__( self, @@ -174,7 +186,7 @@ class LocalAudioQueueDialog(QDialog): ) self.setModal(True) self.setMinimumSize(760, 480) - self.resize(1160, 620) + self.resize(1280, 620) self.setStyleSheet(clinical_stylesheet(_LOCAL_AUDIO_QSS)) self._build_ui() @@ -183,6 +195,9 @@ class LocalAudioQueueDialog(QDialog): self.poll_timer.timeout.connect(self.refresh_records) self.poll_timer.start() self.manager.submit_pending(diagnosis_id=self.diagnosis_id) + resume_transcriptions = getattr(self.manager, "submit_pending_transcriptions", None) + if callable(resume_transcriptions): + resume_transcriptions(diagnosis_id=self.diagnosis_id) self.refresh_records(force=True) def _build_ui(self) -> None: @@ -226,12 +241,15 @@ class LocalAudioQueueDialog(QDialog): self.summary_uploading = self._summary_label() self.summary_uploaded = self._summary_label() self.summary_failed = self._summary_label() + self.summary_transcription = self._summary_label() + self.summary_transcription.setToolTip("已上传但文字尚未生成或保存的录音数量。") for label in ( self.summary_total, self.summary_pending, self.summary_uploading, self.summary_uploaded, self.summary_failed, + self.summary_transcription, ): summary_layout.addWidget(label) summary_layout.addStretch(1) @@ -265,6 +283,7 @@ class LocalAudioQueueDialog(QDialog): "音频文件", "大小", "上传状态", + "文字状态", "失败原因", "操作", ] @@ -275,8 +294,9 @@ class LocalAudioQueueDialog(QDialog): self._file_column = 4 if self._global_scope else 3 self._size_column = 5 if self._global_scope else 4 self._status_column = 6 if self._global_scope else 5 - self._error_column = 7 if self._global_scope else 6 - self._action_column = 8 if self._global_scope else 7 + self._transcription_column = 7 if self._global_scope else 6 + self._error_column = 8 if self._global_scope else 7 + self._action_column = 9 if self._global_scope else 8 self.table = QTableWidget(0, len(headers)) self.table.setObjectName("LocalAudioQueueTable") @@ -302,7 +322,8 @@ class LocalAudioQueueDialog(QDialog): self.table.setColumnWidth(self._room_column, 180) self.table.setColumnWidth(self._size_column, 88) self.table.setColumnWidth(self._status_column, 100) - self.table.setColumnWidth(self._action_column, 190) + self.table.setColumnWidth(self._transcription_column, 100) + self.table.setColumnWidth(self._action_column, 230) card_layout.addWidget(self.table) root.addWidget(card, 1) @@ -310,8 +331,12 @@ class LocalAudioQueueDialog(QDialog): footer.setObjectName("LocalAudioQueueFooter") footer_layout = QHBoxLayout(footer) footer_layout.setContentsMargins(14, 9, 14, 9) - hint = QLabel("已上传文件仍保留在本机;请按机构的数据保留制度定期归档。") + hint = QLabel( + "文字保存至对应诊单「视频录制回放 → 查看文字」;原始录音转写未分离说话人。\n" + "已上传文件仍保留在本机,请按机构的数据保留制度定期归档。" + ) hint.setObjectName("LocalAudioQueueHint") + hint.setWordWrap(True) footer_layout.addWidget(hint, 1) close_button = QPushButton("关闭") close_button.setObjectName("LocalAudioQueueCloseButton") @@ -344,6 +369,8 @@ class LocalAudioQueueDialog(QDialog): record.uploaded_url, record.exists, record.attempts, + getattr(record, "transcription_status", "pending"), + getattr(record, "transcription_error", ""), self._room_fetch_state(record), ) for record in records @@ -377,10 +404,33 @@ class LocalAudioQueueDialog(QDialog): f"已尝试 {record.attempts} 次" + (f"\nCOS:{record.uploaded_url}" if record.uploaded_url else "") ) - error_item = self._set_item( - row, self._error_column, record.error_text or "—" + transcription_status = getattr(record, "transcription_status", "pending") + transcription_item = self._set_item( + row, + self._transcription_column, + _TRANSCRIPTION_LABELS.get(transcription_status, transcription_status) + if record.status == "uploaded" + else "等待上传", ) - error_item.setToolTip(record.error_text) + transcription_item.setForeground( + QColor( + _TRANSCRIPTION_COLORS.get(transcription_status, "#606163") + if record.status == "uploaded" + else "#606163" + ) + ) + transcription_item.setToolTip( + getattr(record, "transcription_error", "") + or "文字保存在对应诊单「视频录制回放 → 查看文字」;原始录音转写未分离说话人。" + ) + reasons = [] + if record.error_text: + reasons.append(f"上传:{record.error_text}") + transcription_error = getattr(record, "transcription_error", "") + if transcription_error: + reasons.append(f"文字:{transcription_error}") + error_item = self._set_item(row, self._error_column, ";".join(reasons) or "—") + error_item.setToolTip("\n".join(reasons)) self.table.setCellWidget(row, self._action_column, self._actions(record)) def _room_fetch_state(self, record: LocalAudioRecord) -> str: @@ -548,6 +598,12 @@ class LocalAudioQueueDialog(QDialog): self.summary_uploading.setText(f"上传中 {counts['uploading']}") self.summary_uploaded.setText(f"已上传 {counts['uploaded']}") self.summary_failed.setText(f"失败 {counts['failed']}") + transcription_pending = sum( + record.status == "uploaded" + and getattr(record, "transcription_status", "pending") != "completed" + for record in records + ) + self.summary_transcription.setText(f"文字未完成 {transcription_pending}") self.upload_pending_button.setEnabled(counts["pending"] > 0) self.retry_failed_button.setEnabled(counts["failed"] > 0) @@ -571,6 +627,23 @@ class LocalAudioQueueDialog(QDialog): busy = QPushButton("上传中") busy.setEnabled(False) layout.addWidget(busy) + elif record.status == "uploaded": + transcription_status = getattr(record, "transcription_status", "pending") + if transcription_status in {"pending", "failed"}: + text_action = "重试文字" if transcription_status == "failed" else "补全文字" + transcribe = QPushButton(text_action) + transcribe.setAccessibleName(f"{text_action} {record.file_path.name}") + if transcription_status == "failed": + transcribe.setProperty("variant", "danger") + transcribe.setEnabled(callable(getattr(self.manager, "submit_transcription", None))) + transcribe.clicked.connect( + lambda _checked=False, record_id=record.id: self._transcribe_one(record_id) + ) + layout.addWidget(transcribe) + elif transcription_status == "transcribing": + busy = QPushButton("文字生成中") + busy.setEnabled(False) + layout.addWidget(busy) if record.exists: reveal = QPushButton("打开位置") reveal.setAccessibleName(f"打开录音文件位置 {record.file_path.name}") @@ -598,6 +671,18 @@ class LocalAudioQueueDialog(QDialog): self.manager.submit(record_id) self.refresh_records(force=True) + def _transcribe_one(self, record_id: int) -> None: + submit = getattr(self.manager, "submit_transcription", None) + if not callable(submit): + return + try: + submit(record_id) + except (OSError, RuntimeError, LookupError, ValueError) as error: + self.summary_transcription.setText("文字重试失败") + self.summary_transcription.setToolTip(str(error)) + return + self.refresh_records(force=True) + def _retry_all_failed(self) -> None: for record in self._records(): if record.status != "failed": diff --git a/app/src/doctor_workstation/ui/image_drop.py b/app/src/doctor_workstation/ui/image_drop.py new file mode 100644 index 000000000..c82fed902 --- /dev/null +++ b/app/src/doctor_workstation/ui/image_drop.py @@ -0,0 +1,299 @@ +"""Copy drag data on the GUI thread, then resolve images in an upload worker.""" + +from __future__ import annotations + +import base64 +import binascii +from collections.abc import Iterator +from contextlib import contextmanager +from dataclasses import dataclass +from html.parser import HTMLParser +from pathlib import Path +from tempfile import TemporaryDirectory +from typing import Literal +from urllib.parse import urljoin, urlsplit + +import httpx +from PySide6.QtCore import QBuffer, QByteArray, QIODevice, QMimeData +from PySide6.QtGui import QImage, QImageReader, QPixmap + +MAX_IMAGE_COUNT = 20 +MAX_IMAGE_BYTES = 10 * 1024 * 1024 +MAX_IMAGE_PIXELS = 40_000_000 +_RASTER_FORMATS = { + "png", "jpeg", "jpg", "webp", "gif", "bmp", "tiff", "tif", "ico", "avif", "heic", +} +# Match server/config/project.php's file_image whitelist without a backend change. +_UPLOAD_IMAGE_FORMATS = {"png", "jpeg", "jpg", "webp", "gif", "ico"} +_IMAGE_MIMES = tuple(f"image/{name}" for name in _RASTER_FORMATS) +_SAVE_LOCALLY = "无法读取此图片链接,链接可能需要登录或已过期,请先保存本地再拖入。" + + +@dataclass(frozen=True) +class _ImageSource: + kind: Literal["local", "url", "data", "bytes"] + value: str | bytes + + +@dataclass(frozen=True) +class ImageDrop: + """Immutable, Qt-object-free snapshot safe to pass to an upload worker.""" + + sources: tuple[_ImageSource, ...] + + @property + def count(self) -> int: + return len(self.sources) + + +def can_drop_images(mime: QMimeData) -> bool: + """Cheap hover check; never open files, fetch URLs or decode an image.""" + + if mime.hasImage() or any(mime.hasFormat(name) for name in _IMAGE_MIMES): + return True + if mime.hasUrls() and any( + url.isLocalFile() or url.scheme().lower() in {"http", "https", "data"} + for url in mime.urls() + ): + return True + if mime.hasHtml(): + return " None: + super().__init__(convert_charrefs=True) + self.sources: list[str] = [] + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + if tag == "img": + self.sources.append(dict(attrs).get("src") or "") + _check_count(len(self.sources)) + + +def _check_count(count: int) -> None: + if not 1 <= count <= MAX_IMAGE_COUNT: + raise ValueError(f"请一次拖入 1 至 {MAX_IMAGE_COUNT} 张图片。") + + +def _check_bytes(content: bytes) -> None: + if not content: + raise ValueError("拖入的图片内容为空。") + if len(content) > MAX_IMAGE_BYTES: + raise ValueError("每张图片不能超过 10 MiB,请压缩后再拖入。") + + +def _http_url(value: str) -> str: + try: + parsed = urlsplit(value) + valid = ( + parsed.scheme.lower() in {"http", "https"} + and bool(parsed.hostname) + and parsed.username is None + and parsed.password is None + and not any(character.isspace() or ord(character) < 32 for character in value) + ) + # Accessing port also rejects malformed/non-numeric ports before networking. + _ = parsed.port + except ValueError: + valid = False + if not valid: + raise ValueError("仅支持 HTTP/HTTPS 图片链接,请先保存本地再拖入。") + return value + + +def _reference(value: str) -> _ImageSource: + value = value.strip() + if value.lower().startswith("data:image/"): + # Bound encoded content before retaining or decoding another copy. + if len(value) > ((MAX_IMAGE_BYTES + 2) // 3) * 4 + 256: + raise ValueError("每张图片不能超过 10 MiB,请压缩后再拖入。") + return _ImageSource("data", value) + return _ImageSource("url", _http_url(value)) + + +def capture_image_drop(mime: QMimeData) -> ImageDrop: + """Snapshot while the drop event owns its MIME data; retain no Qt objects.""" + + urls = mime.urls() if mime.hasUrls() else [] + if any(url.isLocalFile() for url in urls): + _check_count(len(urls)) + return ImageDrop(tuple( + _ImageSource("local", url.toLocalFile()) + if url.isLocalFile() else _reference(url.toString()) + for url in urls + )) + + # Multiple formats describe the same picture. Keep only one representation. + for name in ("image/png", "image/jpeg", *_IMAGE_MIMES): + if mime.hasFormat(name): + content = bytes(mime.data(name)) + _check_bytes(content) + return ImageDrop((_ImageSource("bytes", content),)) + + if mime.hasImage(): + image = mime.imageData() + if isinstance(image, QPixmap): + image = image.toImage() + if not isinstance(image, QImage) or image.isNull(): + raise ValueError("无法读取拖入的图片,请先保存本地再拖入。") + _check_pixels(image.width(), image.height()) + buffer = QBuffer() + if not buffer.open(QIODevice.OpenModeFlag.WriteOnly) or not image.save(buffer, "PNG"): + raise ValueError("无法复制拖入的图片,请先保存本地再拖入。") + content = bytes(buffer.data()) + buffer.close() + _check_bytes(content) + return ImageDrop((_ImageSource("bytes", content),)) + + if mime.hasHtml(): + parser = _ImageTags() + parser.feed(mime.html()) + if parser.sources: + return ImageDrop(tuple(_reference(value) for value in parser.sources)) + + if urls: + _check_count(len(urls)) + return ImageDrop(tuple(_reference(url.toString()) for url in urls)) + if mime.hasText(): + text = mime.text().strip() + if text.lower().startswith(("https://", "http://", "data:image/")): + return ImageDrop((_reference(text),)) + raise ValueError("请拖入图片文件或图片内容,不支持此拖拽内容。") + + +def _check_pixels(width: int, height: int) -> None: + if width <= 0 or height <= 0: + raise ValueError("无法识别图片尺寸,请更换有效图片。") + if width * height > MAX_IMAGE_PIXELS: + raise ValueError("图片像素过大(最多 4000 万像素),请缩小后再拖入。") + + +def _prepare_image(content: bytes) -> tuple[bytes, str]: + """Validate the raster and convert formats unsupported by the upload endpoint.""" + + _check_bytes(content) + buffer = QBuffer() + buffer.setData(QByteArray(content)) + buffer.open(QIODevice.OpenModeFlag.ReadOnly) + reader = QImageReader(buffer) + reader.setDecideFormatFromContent(True) + image_format = bytes(reader.format()).decode("ascii", errors="replace").lower() + if image_format not in _RASTER_FORMATS: + raise ValueError("拖入内容不是受支持的图片,不支持 SVG、网页或其他文件。") + size = reader.size() + _check_pixels(size.width(), size.height()) + image = reader.read() + if image.isNull(): + raise ValueError("图片内容损坏或不完整,请更换有效图片。") + _check_pixels(image.width(), image.height()) + if image_format not in _UPLOAD_IMAGE_FORMATS: + output = QBuffer() + if not output.open(QIODevice.OpenModeFlag.WriteOnly) or not image.save(output, "PNG"): + raise ValueError("无法转换拖入的图片,请先保存为 PNG 或 JPG 再拖入。") + content = bytes(output.data()) + output.close() + # A small source can expand when converted, so enforce the upload limit again. + _check_bytes(content) + image_format = "png" + return content, "jpg" if image_format == "jpeg" else image_format + + +def _new_download_client() -> httpx.Client: + # This client is deliberately unrelated to the authenticated business API. + return httpx.Client( + timeout=httpx.Timeout(15.0, connect=5.0), + follow_redirects=False, + trust_env=False, + headers={"Accept": "image/*"}, + ) + + +def _download_image(url: str) -> bytes: + try: + with _new_download_client() as client: + for _ in range(6): + url = _http_url(url) + client.cookies.clear() + with client.stream("GET", url) as response: + if response.is_redirect: + location = response.headers.get("location") + if not location: + raise ValueError(_SAVE_LOCALLY) + url = _http_url(urljoin(url, location)) + continue + response.raise_for_status() + content_type = response.headers.get("content-type", "").split(";")[0].lower() + if content_type == "image/svg+xml": + raise ValueError("不支持 SVG 图片,请先保存为 PNG 或 JPG 再拖入。") + if content_type and not ( + content_type.startswith("image/") + or content_type == "application/octet-stream" + ): + raise ValueError(_SAVE_LOCALLY) + length = response.headers.get("content-length", "") + if length.isdigit() and int(length) > MAX_IMAGE_BYTES: + raise ValueError("每张图片不能超过 10 MiB,请压缩后再拖入。") + content = bytearray() + for chunk in response.iter_bytes(chunk_size=64 * 1024): + if len(content) + len(chunk) > MAX_IMAGE_BYTES: + raise ValueError("每张图片不能超过 10 MiB,请压缩后再拖入。") + content.extend(chunk) + return bytes(content) + except httpx.InvalidURL as exc: + raise ValueError("图片链接无效,仅支持 HTTP/HTTPS 图片链接,请先保存本地再拖入。") from exc + except httpx.HTTPError as exc: + raise ValueError(_SAVE_LOCALLY) from exc + raise ValueError("图片链接重定向次数过多,请先保存本地再拖入。") + + +def _decode_data_url(value: str) -> bytes: + header, separator, encoded = value.partition(",") + mime_type = header[5:].split(";")[0].lower() + if not separator or not header.lower().endswith(";base64") or mime_type not in _IMAGE_MIMES: + raise ValueError("仅支持 PNG、JPG 等图片的 base64 内容,不支持 SVG。") + try: + content = base64.b64decode(encoded, validate=True) + except (ValueError, binascii.Error) as exc: + raise ValueError("拖入的图片编码无效,请先保存本地再拖入。") from exc + _check_bytes(content) + return content + + +def _source_bytes(source: _ImageSource) -> bytes: + if source.kind == "bytes": + assert isinstance(source.value, bytes) + return source.value + assert isinstance(source.value, str) + if source.kind == "data": + return _decode_data_url(source.value) + if source.kind == "url": + return _download_image(source.value) + path = Path(source.value) + try: + if not path.is_file(): + raise ValueError("请拖入图片文件,不能拖入文件夹或不存在的文件。") + with path.open("rb") as stream: + content = stream.read(MAX_IMAGE_BYTES + 1) + except OSError as exc: + raise ValueError(f"无法读取图片文件“{path.name}”,请确认文件仍存在且可访问。") from exc + _check_bytes(content) + return content + + +@contextmanager +def materialize_image_drop(drop: ImageDrop) -> Iterator[list[Path]]: + """Validate every item before yielding; clean up copies even when uploading fails.""" + + _check_count(drop.count) + with TemporaryDirectory(prefix="doctor-image-drop-") as directory: + paths: list[Path] = [] + for index, source in enumerate(drop.sources, start=1): + content = _source_bytes(source) + content, image_format = _prepare_image(content) + path = Path(directory) / f"dropped-image-{index:02d}.{image_format}" + path.write_bytes(content) + paths.append(path) + yield paths diff --git a/app/src/doctor_workstation/video/lifecycle.py b/app/src/doctor_workstation/video/lifecycle.py index be11dbfd8..9089d5c52 100644 --- a/app/src/doctor_workstation/video/lifecycle.py +++ b/app/src/doctor_workstation/video/lifecycle.py @@ -651,14 +651,26 @@ class OrderedCallLifecycle: return future def finish_transcription(self, *, status: str = "completed") -> Future[bool]: - """Flush and finalize the current transcript exactly once.""" + """Finalize once successfully, allowing retries of a failed same-session write.""" clean_status = str(status or "completed").strip().lower() if clean_status not in {"completed", "partial", "failed"}: raise ValueError("transcription status is invalid") with self._lock: - if self._transcription_finish_future is not None: - return self._transcription_finish_future + previous = self._transcription_finish_future + if previous is not None and ( + not previous.done() + or ( + not previous.cancelled() + and previous.exception() is None + and previous.result() is True + ) + ): + return previous + if self._end_future is not None: + raise RuntimeError("video call has already ended") + # Retain the finish marker after failures so neither new capture nor + # new segments can reopen this session. Only this final write retries. if self._transcription_start_future is None or not self._transcription_session_id: return _settled_future(False) method = getattr(self.repository, "finish_call_transcription", None) @@ -675,7 +687,7 @@ class OrderedCallLifecycle: return False if record_id is None: raise ValueError("server did not return the current call_record_id") - _call_repository_method( + result = _call_repository_method( method, { "diagnosis_id": self.request.diagnosis_id, @@ -685,6 +697,14 @@ class OrderedCallLifecycle: "status": clean_status, }, ) + if result is False: + raise RuntimeError("call transcription finalization failed") + if isinstance(result, Mapping): + saved_status = result.get("status") + if saved_status == "failed": + raise RuntimeError("本次通话未保存到完整文字,请在本机录音文件中重试文字。") + if saved_status == "partial" and clean_status == "completed": + raise RuntimeError("本次通话文字仅部分保存,请在本机录音文件中补全文字。") with self._lock: self._transcription_active = False self.logger.info( @@ -706,10 +726,9 @@ class OrderedCallLifecycle: with self._lock: if self._end_future is not None: return self._end_future - if ( - self._transcription_start_future is not None - and self._transcription_finish_future is None - ): + if self._transcription_start_future is not None: + # A failed earlier finish must not suppress the final fallback. + # In-flight and successful finishes remain deduplicated. self.finish_transcription(status="partial") method = getattr(self.repository, "end_call", None) diff --git a/app/src/doctor_workstation/video/recording_transcription.py b/app/src/doctor_workstation/video/recording_transcription.py new file mode 100644 index 000000000..4cb727855 --- /dev/null +++ b/app/src/doctor_workstation/video/recording_transcription.py @@ -0,0 +1,91 @@ +"""Offline recovery of retained call recordings, without uploading audio again.""" + +from __future__ import annotations + +from collections.abc import Iterator +from pathlib import Path + +from ..core.transcript_text import simplified_transcript +from .local_transcription import ( + MAX_PCM_BYTES, + SAMPLE_RATE, + FasterWhisperEngine, + SpeechEngine, +) + +MAX_RECORDING_SECONDS = 2 * 60 * 60 +MAX_RECORDING_BYTES = 250 * 1024 * 1024 +MAX_RECORDING_TEXT = 100_000 + + +class RecordingTranscriptionError(RuntimeError): + """Fixed messages which never include audio, transcript or decoder details.""" + + +def recording_pcm(path: Path) -> Iterator[bytes]: + """Decode in bounded blocks; reject oversized/corrupt input without a partial save.""" + if not path.is_file() or not 0 < path.stat().st_size <= MAX_RECORDING_BYTES: + raise RecordingTranscriptionError("本机录音不存在、为空或超过 250 MB,无法补转写。") + try: + import av + + with av.open(str(path)) as container: + if not container.streams.audio: + raise RecordingTranscriptionError("录音中没有音频轨道。") + resampler = av.AudioResampler(format="s16", layout="mono", rate=SAMPLE_RATE) + pending = bytearray() + decoded_bytes = 0 + + def append_frames(frames): + nonlocal decoded_bytes + for frame in frames: + pcm = frame.to_ndarray().tobytes() + decoded_bytes += len(pcm) + if decoded_bytes > MAX_RECORDING_SECONDS * SAMPLE_RATE * 2: + raise RecordingTranscriptionError("录音超过 2 小时,无法自动补转写。") + pending.extend(pcm) + while len(pending) >= MAX_PCM_BYTES: + yield bytes(pending[:MAX_PCM_BYTES]) + del pending[:MAX_PCM_BYTES] + + for frame in container.decode(audio=0): + yield from append_frames(resampler.resample(frame)) + yield from append_frames(resampler.resample(None)) + if pending: + yield bytes(pending) + if not decoded_bytes: + raise RecordingTranscriptionError("录音中没有可读取的音频。") + except RecordingTranscriptionError: + raise + except ImportError: + raise RecordingTranscriptionError("本地音频解码组件未安装,请修复本地转写安装。") from None + except Exception: + raise RecordingTranscriptionError("录音解码失败,请检查本机文件是否完整。") from None + + +class RecordingTranscriber: + """Used by one queue worker; the installed local model is reused between jobs.""" + + def __init__(self, engine: SpeechEngine | None = None) -> None: + self._engine = engine + + def __call__(self, path: Path) -> str: + if self._engine is None: + self._engine = FasterWhisperEngine() + parts: list[str] = [] + total = 0 + for pcm in recording_pcm(path): + raw = self._engine.transcribe(pcm) + if not isinstance(raw, str): + raise RecordingTranscriptionError("录音转写失败,尚未保存文字。") + text = simplified_transcript(raw.strip()) + if not text: + continue + total += len(text) + bool(parts) + if total > MAX_RECORDING_TEXT: + raise RecordingTranscriptionError("转写文字超过保存上限,尚未保存,请联系管理员处理。") + parts.append(text) + if not parts: + raise RecordingTranscriptionError("未识别到语音文字,请检查录音内容后重试。") + # Mixed call audio cannot establish which person spoke. Do not invent roles. + return "\n".join(parts) diff --git a/app/tests/test_diagnosis_image_drop.py b/app/tests/test_diagnosis_image_drop.py new file mode 100644 index 000000000..1ad4e4501 --- /dev/null +++ b/app/tests/test_diagnosis_image_drop.py @@ -0,0 +1,247 @@ +"""OS drag events use the existing note upload/save path and stay patient-scoped.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import httpx +import pytest +from PySide6.QtCore import QMimeData, QPoint, QPointF, Qt, QUrl +from PySide6.QtGui import QDragEnterEvent, QDropEvent, QImage +from PySide6.QtWidgets import QApplication +from test_diagnosis_drawer_visual import ActionRepository, _open_dialog, _select_tab + +from doctor_workstation.services.api_client import ApiClient +from doctor_workstation.services.repository import RemoteDoctorRepository +from doctor_workstation.ui.dialogs import diagnosis as diagnosis_module +from doctor_workstation.ui.image_drop import capture_image_drop + + +@pytest.fixture(scope="module") +def application(): + return QApplication.instance() or QApplication([]) + + +@pytest.fixture(autouse=True) +def immediate_async(monkeypatch): + def run(function, *args, on_success=None, on_error=None, on_finished=None, **_kwargs): + try: + result = function(*args) + except Exception as error: + if on_error: + on_error(error) + else: + if on_success: + on_success(result) + finally: + if on_finished: + on_finished() + return object() + + monkeypatch.setattr(diagnosis_module, "run_async", run) + + +class UploadRepository(ActionRepository): + def __init__(self): + super().__init__() + self.uploads = [] + self.fail_at = 0 + + def get_doctor_notes(self, diagnosis_id): + self.notes_calls += 1 + return [] + + def upload_material(self, path, material_type): + assert Path(path).is_file() + assert not QImage(path).isNull() + self.uploads.append((path, material_type)) + if len(self.uploads) == self.fail_at: + raise RuntimeError("图片上传失败") + return f"https://media.example.invalid/{len(self.uploads)}.png" + + +@pytest.fixture +def workspace(application): + repository = UploadRepository() + dialog = _open_dialog(application, (1280, 900), mode="edit", repository=repository) + _select_tab(dialog, "notes") + try: + yield dialog, repository + finally: + dialog.close() + application.processEvents() + + +def image_mime(tmp_path, count=1): + paths = [] + for index in range(count): + path = tmp_path / f"image-{index}.png" + picture = QImage(12, 12, QImage.Format.Format_RGB32) + picture.fill(Qt.GlobalColor.blue) + assert picture.save(str(path)) + paths.append(path) + mime = QMimeData() + mime.setUrls([QUrl.fromLocalFile(str(path)) for path in paths]) + return mime, paths + + +def send_drop(target, mime): + actions = Qt.DropAction.CopyAction | Qt.DropAction.MoveAction + enter = QDragEnterEvent(QPoint(8, 8), actions, mime, Qt.MouseButton.LeftButton, + Qt.KeyboardModifier.NoModifier) + QApplication.sendEvent(target, enter) + if not enter.isAccepted(): + return False + event = QDropEvent(QPointF(8, 8), actions, mime, Qt.MouseButton.LeftButton, + Qt.KeyboardModifier.NoModifier) + event.setDropAction(Qt.DropAction.MoveAction) + QApplication.sendEvent(target, event) + QApplication.processEvents() + assert event.dropAction() == Qt.DropAction.CopyAction + return event.isAccepted() + + +@pytest.mark.parametrize("kind", ["tongue_images", "report_files"]) +def test_drop_multiple_files_on_button_uploads_then_saves_one_note(workspace, tmp_path, kind): + dialog, repository = workspace + mime, original_paths = image_mime(tmp_path, 2) + timeline = dialog.drawer_notes_timeline + target = timeline.tongue_button if kind == "tongue_images" else timeline.report_button + assert send_drop(target, mime) + assert [item[1] for item in repository.uploads] == ["image", "image"] + note = [payload for name, payload in repository.action_calls if name == "note"] + assert note == [(501, "", {kind: [ + "https://media.example.invalid/1.png", "https://media.example.invalid/2.png", + ]})] + assert all(path.exists() for path in original_paths) + assert all(not Path(path).exists() for path, _kind in repository.uploads) + assert not dialog._notes_mutation_busy + assert repository.notes_calls >= 2 + + +def test_drop_memory_image_on_blank_scroll_area_chooses_report(workspace, monkeypatch): + dialog, repository = workspace + selected = [] + monkeypatch.setattr(dialog, "_choose_dropped_image_type", lambda count: selected.append(count) or "report_files") + mime = QMimeData() + image = QImage(10, 10, QImage.Format.Format_RGB32) + image.fill(Qt.GlobalColor.red) + mime.setImageData(image) + assert send_drop(dialog._tab_pages["notes"].viewport(), mime) + assert selected == [1] + assert repository.uploads[0][1] == "image" + assert any("report_files" in payload[2] for name, payload in repository.action_calls if name == "note") + + +def test_cancel_category_does_not_upload_or_save(workspace, tmp_path, monkeypatch): + dialog, repository = workspace + mime, _paths = image_mime(tmp_path) + monkeypatch.setattr(dialog, "_choose_dropped_image_type", lambda _count: "") + assert send_drop(dialog.drawer_notes_timeline, mime) + assert not repository.uploads + assert not any(name == "note" for name, _payload in repository.action_calls) + + +def test_readonly_or_missing_note_permission_rejects_drop(workspace, tmp_path): + dialog, repository = workspace + mime, _paths = image_mime(tmp_path) + timeline = dialog.drawer_notes_timeline + for editable, permitted in ((False, True), (True, False)): + dialog._editable, dialog._can_note_add = editable, permitted + timeline.set_editable(editable and permitted) + assert not timeline.acceptDrops() + assert not send_drop(timeline, mime) + dialog._drop_doctor_note_images(capture_image_drop(mime), "tongue_images") + QApplication.processEvents() + assert not repository.uploads + + +def test_upload_busy_rejects_second_drop_and_does_not_cross_patient(workspace, tmp_path, monkeypatch): + dialog, repository = workspace + mime, _paths = image_mime(tmp_path) + pending = [] + monkeypatch.setattr(diagnosis_module, "run_async", lambda operation, **callbacks: pending.append((operation, callbacks))) + assert send_drop(dialog.drawer_notes_timeline.tongue_button, mime) + assert dialog._notes_mutation_busy + assert not send_drop(dialog.drawer_notes_timeline, mime) + assert len(pending) == 1 + operation, callbacks = pending[0] + dialog._diagnosis_id = 777 + dialog._generation += 1 + dialog._notes_mutation_generation += 1 + result = operation() + callbacks["on_success"](result) + callbacks["on_finished"]() + notes = [payload for name, payload in repository.action_calls if name == "note"] + assert notes[0][0] == 501 + assert dialog._diagnosis_id == 777 + + +def test_queued_drop_does_not_attach_after_patient_switch(workspace, tmp_path): + dialog, repository = workspace + mime, _paths = image_mime(tmp_path) + dialog._drop_doctor_note_images(capture_image_drop(mime), "tongue_images") + dialog._diagnosis_id = 777 + dialog._generation += 1 + QApplication.processEvents() + assert not repository.uploads + + +def test_later_upload_failure_saves_prior_images_and_reports_partial_result(workspace, tmp_path): + dialog, repository = workspace + repository.fail_at = 2 + mime, _paths = image_mime(tmp_path, 3) + assert send_drop(dialog.drawer_notes_timeline.tongue_button, mime) + notes = [payload for name, payload in repository.action_calls if name == "note"] + assert notes == [(501, "", {"tongue_images": ["https://media.example.invalid/1.png"]})] + assert len(repository.uploads) == 2 + assert "已保存 1/3 张" in dialog.drawer_banner.label.text() + assert "只重试未成功" in dialog.drawer_banner.label.text() + assert not dialog._notes_mutation_busy + + +def test_move_only_drag_is_rejected_to_preserve_original(workspace, tmp_path): + dialog, repository = workspace + mime, paths = image_mime(tmp_path) + target = dialog.drawer_notes_timeline.tongue_button + enter = QDragEnterEvent(QPoint(8, 8), Qt.DropAction.MoveAction, mime, + Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier) + QApplication.sendEvent(target, enter) + assert not enter.isAccepted() + event = QDropEvent(QPointF(8, 8), Qt.DropAction.MoveAction, mime, + Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier) + assert dialog.drawer_notes_timeline.eventFilter(target, event) + assert not event.isAccepted() + QApplication.processEvents() + assert not repository.uploads + assert paths[0].exists() + + +def test_report_picture_uses_image_upload_endpoint_but_saves_as_report(workspace, tmp_path): + dialog, _repository = workspace + calls = [] + + def api(request): + endpoint = request.url.path.removeprefix("/adminapi/") + calls.append(endpoint) + if endpoint == "upload/image": + assert request.method == "POST" + assert b"image/png" in request.content + result = {"uri": "https://media.example.invalid/report.png"} + elif endpoint == "doctor.appointment/addDoctorNote": + assert json.loads(request.content) == { + "diagnosis_id": 501, "content": "", + "report_files": ["https://media.example.invalid/report.png"], + } + result = {"id": 123} + else: + assert endpoint == "doctor.appointment/doctorNotes" + result = [] + return httpx.Response(200, json={"code": 1, "data": result}) + + client = ApiClient("https://example.test/adminapi/", transport=httpx.MockTransport(api)) + dialog.repository = RemoteDoctorRepository(client) + mime, _paths = image_mime(tmp_path) + assert send_drop(dialog.drawer_notes_timeline.report_button, mime) + assert calls == ["upload/image", "doctor.appointment/addDoctorNote", "doctor.appointment/doctorNotes"] diff --git a/app/tests/test_image_drop.py b/app/tests/test_image_drop.py new file mode 100644 index 000000000..2e7b9bf92 --- /dev/null +++ b/app/tests/test_image_drop.py @@ -0,0 +1,430 @@ +from __future__ import annotations + +import base64 +import os +from concurrent.futures import ThreadPoolExecutor +from dataclasses import FrozenInstanceError +from pathlib import Path +from tempfile import TemporaryDirectory + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +import httpx +import pytest +import shiboken6 +from PySide6.QtCore import QBuffer, QIODevice, QMimeData, QUrl +from PySide6.QtGui import QImage, QPixmap +from PySide6.QtWidgets import QApplication + +from doctor_workstation.ui import image_drop +from doctor_workstation.ui.image_drop import ( + can_drop_images, + capture_image_drop, + materialize_image_drop, +) + + +@pytest.fixture(scope="module") +def application() -> QApplication: + return QApplication.instance() or QApplication([]) + + +def _image(width: int = 12, height: int = 8) -> QImage: + image = QImage(width, height, QImage.Format.Format_RGB32) + image.fill(0xFF668877) + return image + + +def _image_bytes(image_format: str, width: int = 12, height: int = 8) -> bytes: + buffer = QBuffer() + assert buffer.open(QIODevice.OpenModeFlag.WriteOnly) + assert _image(width, height).save(buffer, image_format) + return bytes(buffer.data()) + + +def _png(width: int = 12, height: int = 8) -> bytes: + return _image_bytes("PNG", width, height) + + +def _local_mime(*paths: Path) -> QMimeData: + mime = QMimeData() + mime.setUrls([QUrl.fromLocalFile(str(path)) for path in paths]) + return mime + + +def _raw_mime(payload: bytes, media_type: str = "image/png") -> QMimeData: + mime = QMimeData() + mime.setData(media_type, payload) + return mime + + +def _mock_download(monkeypatch: pytest.MonkeyPatch, handler: object) -> None: + monkeypatch.setattr( + image_drop, + "_new_download_client", + lambda: httpx.Client(transport=httpx.MockTransport(handler), follow_redirects=False), + ) + + +def test_local_images_are_validated_by_content_and_copied_without_touching_originals( + tmp_path: Path, +) -> None: + first = tmp_path / "第一张 图片.jpg" + second = tmp_path / "second.png" + first.write_bytes(_png()) + second.write_bytes(_png(10, 20)) + mime = _local_mime(first, second) + assert can_drop_images(mime) + drop = capture_image_drop(mime) + assert drop.count == 2 + with materialize_image_drop(drop) as paths: + assert len(paths) == 2 + assert all(path.suffix == ".png" for path in paths) + assert paths[0].read_bytes() == first.read_bytes() + assert paths[1].read_bytes() == second.read_bytes() + assert all(path.parent != tmp_path for path in paths) + assert all(not path.exists() for path in paths) + assert first.exists() and second.exists() + + +@pytest.mark.parametrize("source_kind", ["local", "raw"]) +def test_bmp_is_converted_to_server_supported_png(tmp_path: Path, source_kind: str) -> None: + original = tmp_path / "image.bmp" + content = _image_bytes("BMP") + original.write_bytes(content) + mime = _local_mime(original) if source_kind == "local" else _raw_mime(content, "image/bmp") + with materialize_image_drop(capture_image_drop(mime)) as paths: + assert paths[0].suffix == ".png" + assert paths[0].read_bytes().startswith(b"\x89PNG\r\n\x1a\n") + converted = QImage(str(paths[0])) + assert converted.size() == _image().size() + assert converted.pixelColor(0, 0) == _image().pixelColor(0, 0) + assert original.read_bytes() == content + assert not paths[0].exists() + + +def test_conversion_rechecks_byte_limit_and_cleans_up( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + # A genuine 1-pixel BMP is smaller than its genuine PNG representation. + content = _image_bytes("BMP", 1, 1) + assert len(content) < len(_png(1, 1)) + monkeypatch.setattr(image_drop, "MAX_IMAGE_BYTES", len(content)) + monkeypatch.setattr( + image_drop, "TemporaryDirectory", + lambda prefix: TemporaryDirectory(prefix=prefix, dir=tmp_path), + ) + drop = capture_image_drop(_raw_mime(content, "image/bmp")) + with pytest.raises(ValueError, match="10 MiB"), materialize_image_drop(drop): + pytest.fail("converted image exceeded upload limit") + assert list(tmp_path.iterdir()) == [] + + +def test_hover_never_reads_files_downloads_or_decodes( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + def unexpected(*args: object, **kwargs: object) -> None: + pytest.fail("hover must not access images") + + monkeypatch.setattr(Path, "is_file", unexpected) + monkeypatch.setattr(image_drop, "_download_image", unexpected) + monkeypatch.setattr(image_drop, "QImageReader", unexpected) + assert can_drop_images(_local_mime(tmp_path / "not-yet-existing.png")) + assert can_drop_images(_raw_mime(b"undecodable")) + mime = QMimeData() + mime.setHtml('') + assert can_drop_images(mime) + + +@pytest.mark.parametrize("pixmap", [False, True]) +def test_memory_snapshot_survives_mime_deletion_and_works_in_worker( + application: QApplication, pixmap: bool, +) -> None: + original = _image() + mime = QMimeData() + mime.setImageData(QPixmap.fromImage(original) if pixmap else original) + drop = capture_image_drop(mime) + original.fill(0) + shiboken6.delete(mime) + assert drop.count == 1 + with pytest.raises(FrozenInstanceError): + drop.sources = () + + def resolve() -> bytes: + with materialize_image_drop(drop) as paths: + return paths[0].read_bytes() + + with ThreadPoolExecutor(max_workers=1) as worker: + content = worker.submit(resolve).result(timeout=10) + assert content == _png() + + +def test_local_files_take_precedence_over_duplicate_memory_picture(tmp_path: Path) -> None: + path = tmp_path / "image.png" + path.write_bytes(_png()) + mime = _local_mime(path) + mime.setImageData(_image(3, 3)) + drop = capture_image_drop(mime) + assert drop.count == 1 + with materialize_image_drop(drop) as paths: + assert paths[0].read_bytes() == path.read_bytes() + + +def test_raw_image_snapshot_keeps_no_mime_reference() -> None: + payload = _png() + mime = _raw_mime(payload) + drop = capture_image_drop(mime) + mime.setData("image/png", b"modified") + shiboken6.delete(mime) + with materialize_image_drop(drop) as paths: + assert paths[0].read_bytes() == payload + + +def test_browser_image_src_wins_over_enclosing_link_and_uri_list( + monkeypatch: pytest.MonkeyPatch, +) -> None: + urls: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + urls.append(str(request.url)) + assert "authorization" not in request.headers + assert "cookie" not in request.headers + return httpx.Response(200, content=_png(), headers={"Content-Type": "image/png"}) + + _mock_download(monkeypatch, handler) + mime = QMimeData() + mime.setUrls([QUrl("https://site.invalid/article")]) + mime.setHtml( + '' + '' + ) + with materialize_image_drop(capture_image_drop(mime)) as paths: + assert len(paths) == 1 + assert urls == ["https://cdn.invalid/a.png?width=2&height=3"] + + +def test_multiple_html_images_and_base64_data_are_preserved() -> None: + payload = _png() + encoded = base64.b64encode(payload).decode("ascii") + mime = QMimeData() + mime.setHtml(f'' * 2) + drop = capture_image_drop(mime) + assert drop.count == 2 + with materialize_image_drop(drop) as paths: + assert [path.read_bytes() for path in paths] == [payload, payload] + + +@pytest.mark.parametrize("representation", ["text", "url"]) +def test_remote_image_url_can_be_dropped( + monkeypatch: pytest.MonkeyPatch, representation: str, +) -> None: + _mock_download(monkeypatch, lambda _: httpx.Response(200, content=_png())) + mime = QMimeData() + if representation == "url": + mime.setUrls([QUrl("https://cdn.invalid/image?id=123")]) + else: + mime.setText("https://cdn.invalid/image?id=123") + assert can_drop_images(mime) + with materialize_image_drop(capture_image_drop(mime)) as paths: + assert paths[0].read_bytes() == _png() + + +@pytest.mark.parametrize("text", ["C:/private/photo.png", "file:///C:/private/photo.png", "hello"]) +def test_plain_text_is_not_interpreted_as_local_file(text: str) -> None: + mime = QMimeData() + mime.setText(text) + assert not can_drop_images(mime) + with pytest.raises(ValueError, match="请拖入图片"): + capture_image_drop(mime) + + +def test_mixed_valid_and_invalid_files_fail_before_yield_and_clean_up( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + good, bad = tmp_path / "good.png", tmp_path / "fake.png" + good.write_bytes(_png()) + bad.write_text("not a real image", encoding="utf-8") + monkeypatch.setattr( + image_drop, "TemporaryDirectory", + lambda prefix: TemporaryDirectory(prefix=prefix, dir=tmp_path), + ) + with ( + pytest.raises(ValueError, match="不是受支持的图片"), + materialize_image_drop(capture_image_drop(_local_mime(good, bad))), + ): + pytest.fail("must validate the full batch before uploading anything") + assert sorted(path.name for path in tmp_path.iterdir()) == ["fake.png", "good.png"] + + +def test_temp_files_are_cleaned_when_upload_raises() -> None: + with ( + pytest.raises(RuntimeError, match="upload failed"), + materialize_image_drop(capture_image_drop(_raw_mime(_png()))) as paths, + ): + raise RuntimeError("upload failed") + assert not paths[0].parent.exists() + + +@pytest.mark.parametrize("kind", ["local", "html"]) +def test_batch_limit_is_checked_without_io(tmp_path: Path, kind: str) -> None: + if kind == "local": + mime = _local_mime(*(tmp_path / f"{index}.png" for index in range(21))) + else: + mime = QMimeData() + mime.setHtml('' * 21) + with pytest.raises(ValueError, match="20"): + capture_image_drop(mime) + + +def test_exactly_twenty_images_are_allowed(tmp_path: Path) -> None: + path = tmp_path / "image.png" + path.write_bytes(_png()) + with materialize_image_drop(capture_image_drop(_local_mime(*([path] * 20)))) as paths: + assert len(paths) == 20 + + +def test_local_byte_limit(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(image_drop, "MAX_IMAGE_BYTES", 100) + path = tmp_path / "large.png" + path.write_bytes(b"a" * 101) + with ( + pytest.raises(ValueError, match="10 MiB"), + materialize_image_drop(capture_image_drop(_local_mime(path))), + ): + pytest.fail("oversized image accepted") + + +def test_raw_byte_limit_is_checked_during_capture(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(image_drop, "MAX_IMAGE_BYTES", 10) + with pytest.raises(ValueError, match="10 MiB"): + capture_image_drop(_raw_mime(b"a" * 11)) + + +def test_pixel_limit_is_checked_for_encoded_and_memory_images( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(image_drop, "MAX_IMAGE_PIXELS", 50) + with ( + pytest.raises(ValueError, match="像素过大"), + materialize_image_drop(capture_image_drop(_raw_mime(_png()))), + ): + pytest.fail("large raster accepted") + mime = QMimeData() + mime.setImageData(_image()) + with pytest.raises(ValueError, match="像素过大"): + capture_image_drop(mime) + + +@pytest.mark.parametrize("payload", [ + b'', + b"login", + b"not an image", +]) +def test_non_raster_content_cannot_masquerade_as_png(payload: bytes) -> None: + with ( + pytest.raises(ValueError, match="不是受支持的图片"), + materialize_image_drop(capture_image_drop(_raw_mime(payload))), + ): + pytest.fail("invalid image accepted") + + +@pytest.mark.parametrize("value", [ + "data:image/svg+xml;base64,PHN2Zy8+", + "data:image/png;base64,not-base64!", + "data:image/png,not-base64", +]) +def test_invalid_data_images_fail(value: str) -> None: + mime = QMimeData() + mime.setText(value) + with pytest.raises(ValueError), materialize_image_drop(capture_image_drop(mime)): + pytest.fail("invalid data image accepted") + + +@pytest.mark.parametrize("redirect", ["file:///C:/private/image.png", "javascript:alert(1)"]) +def test_unsafe_redirects_are_never_requested( + monkeypatch: pytest.MonkeyPatch, redirect: str, +) -> None: + requests: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + requests.append(str(request.url)) + return httpx.Response(302, headers={"Location": redirect}) + + _mock_download(monkeypatch, handler) + mime = QMimeData() + mime.setText("https://cdn.invalid/a.png") + with ( + pytest.raises(ValueError, match="HTTP/HTTPS"), + materialize_image_drop(capture_image_drop(mime)), + ): + pytest.fail("unsafe redirect accepted") + assert requests == ["https://cdn.invalid/a.png"] + + +def test_redirects_do_not_forward_cookies(monkeypatch: pytest.MonkeyPatch) -> None: + requests: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + requests.append(str(request.url)) + assert "cookie" not in request.headers + assert "authorization" not in request.headers + if len(requests) == 1: + return httpx.Response(302, headers={"Location": "/b.png", "Set-Cookie": "token=secret"}) + return httpx.Response(200, content=_png()) + + _mock_download(monkeypatch, handler) + mime = QMimeData() + mime.setText("https://cdn.invalid/a.png") + with materialize_image_drop(capture_image_drop(mime)) as paths: + assert paths[0].read_bytes() == _png() + assert len(requests) == 2 + + +@pytest.mark.parametrize("status,headers", [ + (401, {}), + (403, {}), + (200, {"Content-Type": "text/html"}), +]) +def test_login_and_webpage_sources_explain_save_locally( + monkeypatch: pytest.MonkeyPatch, status: int, headers: dict[str, str], +) -> None: + _mock_download(monkeypatch, lambda _: httpx.Response(status, headers=headers, content=b"login")) + mime = QMimeData() + mime.setText("https://site.invalid/private.png") + with ( + pytest.raises(ValueError, match="先保存本地再拖入"), + materialize_image_drop(capture_image_drop(mime)), + ): + pytest.fail("login page accepted") + + +@pytest.mark.parametrize("declared_length", [True, False]) +def test_download_size_limit_uses_headers_and_actual_stream( + monkeypatch: pytest.MonkeyPatch, declared_length: bool, +) -> None: + monkeypatch.setattr(image_drop, "MAX_IMAGE_BYTES", 100) + + class OversizedStream(httpx.SyncByteStream): + def __iter__(self): + yield b"a" * 60 + yield b"b" * 60 + + def handler(_: httpx.Request) -> httpx.Response: + headers = {"Content-Length": "120"} if declared_length else {} + return httpx.Response(200, headers=headers, stream=OversizedStream()) + + _mock_download(monkeypatch, handler) + mime = QMimeData() + mime.setText("https://cdn.invalid/a.png") + with ( + pytest.raises(ValueError, match="10 MiB"), + materialize_image_drop(capture_image_drop(mime)), + ): + pytest.fail("oversized response accepted") + + +def test_embedded_url_credentials_are_rejected() -> None: + mime = QMimeData() + mime.setText("https://token:secret@cdn.invalid/a.png") + with pytest.raises(ValueError, match="HTTP/HTTPS"): + capture_image_drop(mime) diff --git a/app/tests/test_local_audio_queue.py b/app/tests/test_local_audio_queue.py index 63119aee4..77d0a1bdc 100644 --- a/app/tests/test_local_audio_queue.py +++ b/app/tests/test_local_audio_queue.py @@ -342,7 +342,7 @@ def test_local_audio_dialog_lists_status_and_retry_controls(tmp_path: Path) -> N application.processEvents() try: assert dialog.objectName() == "LocalAudioQueueDialog" - assert dialog.table.columnCount() == 8 + assert dialog.table.columnCount() == 9 assert dialog.table.rowCount() == 2 assert dialog.summary_failed.text() == "失败 1" assert dialog.summary_uploaded.text() == "已上传 1" @@ -350,7 +350,8 @@ def test_local_audio_dialog_lists_status_and_retry_controls(tmp_path: Path) -> N assert dialog.table.horizontalHeaderItem(1).text() == "通话记录 ID" assert dialog.table.horizontalHeaderItem(2).text() == "房间号" assert dialog.table.horizontalHeaderItem(5).text() == "上传状态" - assert dialog.table.horizontalHeaderItem(6).text() == "失败原因" + assert dialog.table.horizontalHeaderItem(6).text() == "文字状态" + assert dialog.table.horizontalHeaderItem(7).text() == "失败原因" assert dialog.table.columnWidth(dialog._room_column) == 180 rooms = { dialog.table.item(row, 2).text() for row in range(dialog.table.rowCount()) @@ -400,7 +401,7 @@ def test_global_local_audio_dialog_lists_all_diagnoses_and_outcomes( application.processEvents() try: assert dialog.title_label.text() == "本机录音上传管理" - assert dialog.table.columnCount() == 9 + assert dialog.table.columnCount() == 10 assert dialog.table.rowCount() == 2 assert dialog.table.horizontalHeaderItem(1).text() == "诊单 ID" assert dialog.table.horizontalHeaderItem(2).text() == "通话记录 ID" diff --git a/app/tests/test_local_audio_transcription_ui.py b/app/tests/test_local_audio_transcription_ui.py new file mode 100644 index 000000000..850222608 --- /dev/null +++ b/app/tests/test_local_audio_transcription_ui.py @@ -0,0 +1,226 @@ +from __future__ import annotations + +from concurrent.futures import Future +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest +from PySide6.QtCore import Qt +from PySide6.QtTest import QTest +from PySide6.QtWidgets import QApplication, QLabel, QPushButton + +from doctor_workstation.ui.dialogs.local_audio_queue import LocalAudioQueueDialog + + +@pytest.fixture +def application() -> QApplication: + return QApplication.instance() or QApplication([]) + + +def _record( + tmp_path: Path, + *, + status: str = "uploaded", + transcription_status: str = "pending", + transcription_error: str = "", +) -> SimpleNamespace: + return SimpleNamespace( + id=1, + diagnosis_id=8169, + call_record_id=901, + room_id="12345678", + file_path=tmp_path / "synthetic-recording.webm", + size_bytes=2048, + status=status, + error_text="", + uploaded_url="cos://recordings/synthetic.webm" if status == "uploaded" else "", + attempts=1, + created_at="2026-11-06T01:00:00+00:00", + exists=False, + transcription_status=transcription_status, + transcription_error=transcription_error, + ) + + +class _Store: + def __init__(self, record: SimpleNamespace) -> None: + self.record = record + self.upload_retries: list[int] = [] + + def list_records(self, *, diagnosis_id: int | None) -> list[Any]: + if diagnosis_id is None or diagnosis_id == self.record.diagnosis_id: + return [self.record] + return [] + + def retry(self, record_id: int) -> None: + self.upload_retries.append(record_id) + + +class _LegacyManager: + def __init__(self, store: _Store) -> None: + self.store = store + self.uploads: list[int] = [] + self.pending_upload_scopes: list[int | None] = [] + + def submit_pending(self, *, diagnosis_id: int | None) -> list[Future[bool]]: + self.pending_upload_scopes.append(diagnosis_id) + return [] + + def submit(self, record_id: int) -> Future[bool]: + self.uploads.append(record_id) + return Future() + + +class _Manager(_LegacyManager): + def __init__(self, store: _Store) -> None: + super().__init__(store) + self.transcriptions: list[int] = [] + self.pending_transcription_scopes: list[int | None] = [] + + def submit_pending_transcriptions( + self, *, diagnosis_id: int | None + ) -> list[Future[bool]]: + self.pending_transcription_scopes.append(diagnosis_id) + return [] + + def submit_transcription(self, record_id: int) -> Future[bool]: + self.transcriptions.append(record_id) + self.store.record.transcription_status = "transcribing" + self.store.record.transcription_error = "" + return Future() + + +def _buttons(dialog: LocalAudioQueueDialog) -> dict[str, QPushButton]: + host = dialog.table.cellWidget(0, dialog._action_column) + assert host is not None + return {button.text(): button for button in host.findChildren(QPushButton)} + + +def test_uploaded_record_with_failed_text_can_retry_without_uploading_again( + application: QApplication, tmp_path: Path +) -> None: + record = _record( + tmp_path, + transcription_status="failed", + transcription_error="文字保存失败,请稍后重试", + ) + store = _Store(record) + manager = _Manager(store) + dialog = LocalAudioQueueDialog(object(), 8169, store=store, manager=manager) + dialog.show() + application.processEvents() + try: + assert dialog.table.item(0, dialog._status_column).text() == "已上传" + assert dialog.table.item(0, dialog._transcription_column).text() == "生成失败" + assert dialog.table.item(0, dialog._error_column).text() == ( + "文字:文字保存失败,请稍后重试" + ) + assert dialog.summary_uploaded.text() == "已上传 1" + assert dialog.summary_failed.text() == "失败 0" + assert dialog.summary_transcription.text() == "文字未完成 1" + assert not dialog.retry_failed_button.isEnabled() + + QTest.mouseClick(_buttons(dialog)["重试文字"], Qt.MouseButton.LeftButton) + application.processEvents() + + assert manager.transcriptions == [record.id] + assert manager.uploads == [] + assert store.upload_retries == [] + assert record.status == "uploaded" + assert dialog.table.item(0, dialog._status_column).text() == "已上传" + assert dialog.table.item(0, dialog._transcription_column).text() == "生成中" + assert not _buttons(dialog)["文字生成中"].isEnabled() + finally: + dialog.close() + + +def test_transcribing_controls_are_disabled_and_polling_detects_completion( + application: QApplication, tmp_path: Path +) -> None: + record = _record(tmp_path, transcription_status="transcribing") + store = _Store(record) + manager = _Manager(store) + dialog = LocalAudioQueueDialog(object(), 8169, store=store, manager=manager) + try: + assert not _buttons(dialog)["文字生成中"].isEnabled() + QTest.mouseClick(_buttons(dialog)["文字生成中"], Qt.MouseButton.LeftButton) + assert manager.transcriptions == [] + + record.transcription_status = "completed" + dialog.refresh_records() + + assert dialog.table.item(0, dialog._transcription_column).text() == "已保存" + assert dialog.summary_transcription.text() == "文字未完成 0" + assert _buttons(dialog) == {} + hint = dialog.findChild(QLabel, "LocalAudioQueueHint") + assert hint is not None + assert "视频录制回放 → 查看文字" in hint.text() + assert "未分离说话人" in hint.text() + finally: + dialog.close() + + +@pytest.mark.parametrize("diagnosis_id", [8169, None]) +def test_pending_text_resumes_for_dialog_scope_and_has_separate_action( + application: QApplication, tmp_path: Path, diagnosis_id: int | None +) -> None: + record = _record(tmp_path) + store = _Store(record) + manager = _Manager(store) + dialog = LocalAudioQueueDialog(object(), diagnosis_id, store=store, manager=manager) + try: + assert manager.pending_transcription_scopes == [diagnosis_id] + assert dialog.table.horizontalHeaderItem(dialog._transcription_column).text() == ( + "文字状态" + ) + assert dialog.table.item(0, dialog._transcription_column).text() == "待生成" + assert _buttons(dialog)["补全文字"].isEnabled() + finally: + dialog.close() + + +def test_unuploaded_record_waits_for_upload_and_keeps_upload_retry( + application: QApplication, tmp_path: Path +) -> None: + record = _record(tmp_path, status="failed") + record.error_text = "上传连接中断" + store = _Store(record) + dialog = LocalAudioQueueDialog(object(), 8169, store=store, manager=_Manager(store)) + try: + assert dialog.table.item(0, dialog._transcription_column).text() == "等待上传" + assert dialog.table.item(0, dialog._error_column).text() == "上传:上传连接中断" + assert set(_buttons(dialog)) == {"重试"} + assert dialog.summary_transcription.text() == "文字未完成 0" + finally: + dialog.close() + + +def test_polling_detects_text_error_changes_without_upload_changes( + application: QApplication, tmp_path: Path +) -> None: + record = _record(tmp_path, transcription_status="failed", transcription_error="请求失败") + store = _Store(record) + dialog = LocalAudioQueueDialog(object(), 8169, store=store, manager=_Manager(store)) + try: + record.transcription_error = "转写服务暂不可用" + dialog.refresh_records() + assert dialog.table.item(0, dialog._error_column).text() == "文字:转写服务暂不可用" + assert dialog.table.item(0, dialog._transcription_column).toolTip() == ( + "转写服务暂不可用" + ) + finally: + dialog.close() + + +def test_dialog_accepts_legacy_manager_without_transcription_methods( + application: QApplication, tmp_path: Path +) -> None: + store = _Store(_record(tmp_path)) + manager = _LegacyManager(store) + dialog = LocalAudioQueueDialog(object(), 8169, store=store, manager=manager) + try: + assert manager.pending_upload_scopes == [8169] + assert not _buttons(dialog)["补全文字"].isEnabled() + finally: + dialog.close() diff --git a/app/tests/test_recording_transcript_recovery.py b/app/tests/test_recording_transcript_recovery.py new file mode 100644 index 000000000..6f397ab2b --- /dev/null +++ b/app/tests/test_recording_transcript_recovery.py @@ -0,0 +1,294 @@ +"""Synthetic recording recovery: durable text, exact call binding, no duplicate upload.""" + +from __future__ import annotations + +import json +import threading +import wave +from pathlib import Path +from types import SimpleNamespace + +import httpx +import pytest + +from doctor_workstation.core.errors import ApiTransportError +from doctor_workstation.services import local_audio_queue as queue_module +from doctor_workstation.services.api_client import ApiClient +from doctor_workstation.services.local_audio_queue import ( + LocalAudioQueueStore, + LocalAudioUploadManager, +) +from doctor_workstation.services.repository import RemoteDoctorRepository +from doctor_workstation.video import recording_transcription as recording + + +class Repository: + def __init__(self): + self.call = { + "id": 71, "caller_id": 5, "caller_type": "doctor", "status": 2, + "local_audio_status": 2, "transcription_status": "partial", + "local_audio_urls_list": ["https://audio.example.test/recording.webm"], + "transcription_session_id": "live-session", "transcript_text": "旧的片段", + } + self.uploads = 0 + self.saves = [] + self.fail_save = False + self.ack_id = 71 + + def get_current_user(self): + return SimpleNamespace(id=5) + + def list_call_records(self, _diagnosis_id): + return [self.call.copy()] + + def upload_call_recording(self, **kwargs): + self.uploads += 1 + return {"file_url": "https://audio.example.test/recording.webm"} + + def save_local_audio_transcript(self, **payload): + self.saves.append(payload) + if self.fail_save: + raise ApiTransportError("synthetic network failure") + return {"call_record_id": self.ack_id, "transcription_status": "completed", "saved": True} + + +def ready(store, *, uploaded=True): + record = store.begin_recording( + session_id="synthetic-local", diagnosis_id=9, call_record_id=71, mime_type="audio/webm" + ) + record.file_path.write_bytes(b"synthetic audio") + store.finalize_recording(record.id, size_bytes=15) + if uploaded: + store.mark_uploaded(record.id, "https://audio.example.test/recording.webm") + return record.id + + +def test_upload_automatically_recovers_missing_text_without_reupload(tmp_path): + store = LocalAudioQueueStore(tmp_path) + record_id = ready(store, uploaded=False) + repository = Repository() + saved = threading.Event() + manager = LocalAudioUploadManager(repository, store, transcriber=lambda _path: "合成测试文字") + manager.add_upload_listener( + lambda row: saved.set() if row.transcription_status == "completed" else None + ) + assert manager.submit(record_id).result(3) + assert saved.wait(3) + assert repository.uploads == 1 + assert repository.saves[0]["call_record_id"] == 71 + assert repository.saves[0]["expected_session_id"] == "live-session" + assert repository.saves[0]["expected_status"] == "partial" + assert store.require(record_id).transcription_status == "completed" + assert store.require(record_id).exists + + +def test_failed_save_keeps_draft_and_id_across_restart(tmp_path): + store = LocalAudioQueueStore(tmp_path) + record_id = ready(store) + repository = Repository() + repository.fail_save = True + recognized = [] + + def transcribe(path): + recognized.append(path) + return "保留原始文字,0.5 毫克。" + + manager = LocalAudioUploadManager(repository, store, transcriber=transcribe) + assert not manager.submit_transcription(record_id).result(3) + first = store.require(record_id) + assert first.status == "uploaded" + assert first.transcription_status == "failed" + assert store.transcription_draft(record_id) == "保留原始文字,0.5 毫克。" + repository.fail_save = False + restarted = LocalAudioQueueStore(tmp_path) + retry = LocalAudioUploadManager(repository, restarted, transcriber=transcribe) + assert retry.submit_transcription(record_id).result(3) + assert len(recognized) == 1 + assert repository.uploads == 0 + assert repository.saves[0]["recovery_id"] == repository.saves[1]["recovery_id"] + assert not restarted.transcription_draft(record_id) + + +def test_existing_complete_text_skips_recognition_and_save(tmp_path): + store = LocalAudioQueueStore(tmp_path) + record_id = ready(store) + repository = Repository() + repository.call["transcription_status"] = "completed" + + def forbidden(_path): + pytest.fail("must not overwrite an existing completed transcript") + + manager = LocalAudioUploadManager(repository, store, transcriber=forbidden) + assert manager.submit_transcription(record_id).result(3) + assert not repository.saves + + +@pytest.mark.parametrize("changes", [ + {"caller_id": 6}, {"status": 0}, {"local_audio_status": 0}, {"id": 72}, + {"local_audio_urls_list": ["https://audio.example.test/other-call.webm"]}, +]) +def test_wrong_owner_active_or_missing_call_does_not_transcribe(tmp_path, changes): + store = LocalAudioQueueStore(tmp_path) + record_id = ready(store) + repository = Repository() + repository.call.update(changes) + recognized = [] + manager = LocalAudioUploadManager(repository, store, transcriber=lambda path: recognized.append(path)) + assert not manager.submit_transcription(record_id).result(3) + assert not recognized + assert not repository.saves + assert store.require(record_id).status == "uploaded" + + +@pytest.mark.parametrize("text", ["", " ", "x" * 100_001], ids=["empty", "blank", "oversized"]) +def test_empty_or_oversized_asr_is_never_marked_saved(tmp_path, text): + store = LocalAudioQueueStore(tmp_path) + record_id = ready(store) + repository = Repository() + manager = LocalAudioUploadManager(repository, store, transcriber=lambda _path: text) + assert not manager.submit_transcription(record_id).result(3) + assert store.require(record_id).transcription_status == "failed" + assert not repository.saves + + +def test_wrong_call_ack_preserves_draft_as_failed(tmp_path): + store = LocalAudioQueueStore(tmp_path) + record_id = ready(store) + repository = Repository() + repository.ack_id = 72 + manager = LocalAudioUploadManager(repository, store, transcriber=lambda _path: "合成文字") + assert not manager.submit_transcription(record_id).result(3) + assert store.transcription_draft(record_id) == "合成文字" + assert store.require(record_id).transcription_status == "failed" + + +def test_duplicate_submit_recognizes_once(tmp_path): + store = LocalAudioQueueStore(tmp_path) + record_id = ready(store) + repository = Repository() + entered, release = threading.Event(), threading.Event() + + def transcribe(_path): + entered.set() + assert release.wait(3) + return "合成文字" + + manager = LocalAudioUploadManager(repository, store, transcriber=transcribe) + first = manager.submit_transcription(record_id) + assert entered.wait(3) + assert manager.submit_transcription(record_id) is first + release.set() + assert first.result(3) + assert len(repository.saves) == 1 + + +def test_interrupted_work_resumes_with_saved_draft(tmp_path): + store = LocalAudioQueueStore(tmp_path) + record_id = ready(store) + claimed = store.claim_transcription(record_id) + store.save_transcription_draft(record_id, "识别已完成但进程意外退出") + queue_module._RECOVERED_DATABASES.discard(store.database_path) + restarted = LocalAudioQueueStore(tmp_path) + assert restarted.require(record_id).transcription_status == "pending" + assert restarted.require(record_id).transcription_recovery_id == claimed.transcription_recovery_id + manager = LocalAudioUploadManager(Repository(), restarted) + assert manager.submit_pending_transcriptions(diagnosis_id=9)[0].result(3) + assert restarted.require(record_id).transcription_status == "completed" + + +def test_upload_finishes_before_call_end_then_text_recovers_automatically(tmp_path, monkeypatch): + monkeypatch.setattr(queue_module, "_TRANSCRIPTION_END_RETRY_DELAYS", (0.01, 0.01)) + store = LocalAudioQueueStore(tmp_path) + record_id = ready(store, uploaded=False) + repository = Repository() + calls = [] + saved = threading.Event() + + def call_state(_diagnosis_id): + calls.append(True) + return [{**repository.call, "status": 1 if len(calls) == 1 else 2}] + + repository.list_call_records = call_state + manager = LocalAudioUploadManager(repository, store, transcriber=lambda _path: "合成文字") + manager.add_upload_listener( + lambda row: saved.set() if row.transcription_status == "completed" else None + ) + assert manager.submit(record_id).result(3) + assert saved.wait(3) + assert len(calls) == 2 + assert repository.uploads == 1 + assert len(repository.saves) == 1 + + +def test_waiting_for_call_end_is_bounded_and_retry_remains_available(tmp_path, monkeypatch): + monkeypatch.setattr(queue_module, "_TRANSCRIPTION_END_RETRY_DELAYS", (0.01, 0.01)) + store = LocalAudioQueueStore(tmp_path) + record_id = ready(store) + repository = Repository() + repository.call["status"] = 1 + recognized = [] + manager = LocalAudioUploadManager(repository, store, transcriber=lambda path: recognized.append(path)) + assert not manager.submit_transcription(record_id).result(3) + assert not recognized + assert store.require(record_id).transcription_status == "failed" + repository.call["status"] = 2 + manager._transcriber = lambda _path: "合成文字" + assert manager.submit_transcription(record_id).result(3) + + +def wav(path: Path, samples: int, *, rate=16_000, channels=1): + with wave.open(str(path), "wb") as output: + output.setnchannels(channels) + output.setsampwidth(2) + output.setframerate(rate) + output.writeframes(b"\x10\x00" * samples * channels) + + +def test_decoder_keeps_tail_and_resamples_stereo(tmp_path): + pytest.importorskip("av") + source = tmp_path / "synthetic.wav" + wav(source, 48_000 * 25, rate=48_000, channels=2) + chunks = list(recording.recording_pcm(source)) + assert [len(chunk) for chunk in chunks] == [384_000, 384_000, 32_000] + + +def test_decoder_rejects_corrupt_or_overlong_audio(tmp_path, monkeypatch): + pytest.importorskip("av") + source = tmp_path / "synthetic.wav" + source.write_bytes(b"not audio") + with pytest.raises(recording.RecordingTranscriptionError, match="解码失败"): + list(recording.recording_pcm(source)) + wav(source, 32_000) + monkeypatch.setattr(recording, "MAX_RECORDING_SECONDS", 1) + with pytest.raises(recording.RecordingTranscriptionError, match="超过"): + list(recording.recording_pcm(source)) + + +def test_recording_transcriber_preserves_text_and_never_labels_speakers(tmp_path): + pytest.importorskip("av") + source = tmp_path / "synthetic.wav" + wav(source, 16_000 * 13) + responses = iter(["沒有過敏,0.5 mg。", "不是 5 mg。"]) + engine = SimpleNamespace(transcribe=lambda _pcm: next(responses)) + assert recording.RecordingTranscriber(engine)(source) == "没有过敏,0.5 mg。\n不是 5 mg。" + + +def test_repository_sends_exact_binding_and_compare_state(): + calls = [] + + def handle(request): + assert request.url.path == "/adminapi/tcm.diagnosis/saveLocalAudioTranscript" + calls.append(json.loads(request.content)) + return httpx.Response(200, json={"code": 1, "data": { + "call_record_id": 71, "transcription_status": "completed", "saved": True, + }}) + + client = ApiClient("https://example.test/adminapi/", transport=httpx.MockTransport(handle)) + repository = RemoteDoctorRepository(client) + payload = dict( + diagnosis_id=9, call_record_id=71, recovery_id="audio-" + "a" * 32, + expected_session_id="live-session", expected_status="partial", + audio_url="https://audio.example.test/recording.webm", transcript_text="合成测试文字", + ) + assert repository.save_local_audio_transcript(**payload)["saved"] + assert calls == [payload] diff --git a/app/tests/test_transcription_finish_retry.py b/app/tests/test_transcription_finish_retry.py new file mode 100644 index 000000000..408ea021a --- /dev/null +++ b/app/tests/test_transcription_finish_retry.py @@ -0,0 +1,162 @@ +"""Finalization retries retain one sealed capture session and one call identity.""" + +from __future__ import annotations + +import logging +import threading +from concurrent.futures import ThreadPoolExecutor + +import pytest + +from doctor_workstation.video.launcher import VideoCallRequest +from doctor_workstation.video.lifecycle import OrderedCallLifecycle + + +class Repository: + def __init__(self, outcomes=(), block_attempt=0): + self.outcomes = list(outcomes) + self.block_attempt = block_attempt + self.attempts = [] + self.events = [] + self.entered = threading.Event() + self.release = threading.Event() + + def start_call(self, **_payload): + return {"call_record_id": 71} + + def start_call_transcription(self, **_payload): + return True + + def upsert_call_transcript_segments(self, **_payload): + return True + + def finish_call_transcription(self, **payload): + self.attempts.append(payload) + self.events.append("finish") + if len(self.attempts) == self.block_attempt: + self.entered.set() + assert self.release.wait(3), "test did not release finalization" + outcome = self.outcomes.pop(0) if self.outcomes else True + if isinstance(outcome, Exception): + raise outcome + return outcome + + def end_call(self, **_payload): + self.events.append("end") + return True + + +@pytest.fixture +def make_lifecycle(): + lifecycles = [] + + def make(**options): + repository = Repository(**options) + request = VideoCallRequest( + sdk_app_id=1400123456, + user_id="doctor-test", + user_sig="test-ticket", + target_user_id="patient-test", + diagnosis_id=12, + ) + lifecycle = OrderedCallLifecycle(request, repository, logging.getLogger(__name__)) + lifecycles.append((lifecycle, repository)) + assert lifecycle.start_transcription("tr-finish-retry").result(timeout=2) + assert lifecycle.save_transcript_segment( + {"segment_id": "synthetic-1", "text": "synthetic fixture"} + ).result(timeout=2) + return lifecycle, repository + + yield make + for lifecycle, repository in lifecycles: + repository.release.set() + lifecycle.end("test-cleanup").result(timeout=3) + assert lifecycle.wait(3) + + +@pytest.mark.parametrize("failure", [ + RuntimeError("temporary storage failure"), False, + {"status": "failed", "segment_count": 0}, + {"status": "partial", "segment_count": 1}, +]) +def test_failed_finish_retries_same_snapshot_without_reopening_capture(make_lifecycle, failure): + lifecycle, repository = make_lifecycle(outcomes=[failure, True]) + failed = lifecycle.finish_transcription() + with pytest.raises(RuntimeError): + failed.result(timeout=2) + with pytest.raises(RuntimeError, match="already stopped"): + lifecycle.start_transcription("tr-finish-retry") + with pytest.raises(RuntimeError, match="already stopped"): + lifecycle.save_transcript_segment({"segment_id": "late", "text": "synthetic fixture"}) + + retry = lifecycle.finish_transcription() + assert retry is not failed + assert retry.result(timeout=2) + assert lifecycle.finish_transcription() is retry + assert repository.attempts == [ + {"diagnosis_id": 12, "call_record_id": 71, + "transcription_session_id": "tr-finish-retry", + "expected_segment_count": 1, "status": "completed"}, + ] * 2 + + +def test_concurrent_finish_retries_share_one_running_write(make_lifecycle): + lifecycle, repository = make_lifecycle( + outcomes=[RuntimeError("temporary storage failure"), True], block_attempt=2, + ) + with pytest.raises(RuntimeError): + lifecycle.finish_transcription().result(timeout=2) + try: + with ThreadPoolExecutor(max_workers=4) as callers: + futures = list(callers.map(lambda _: lifecycle.finish_transcription(), range(4))) + assert repository.entered.wait(2) + assert all(future is futures[0] for future in futures) + assert len(repository.attempts) == 2 + finally: + repository.release.set() + assert futures[0].result(timeout=2) + + +def test_cancelled_finish_can_retry_without_reopening_capture(make_lifecycle): + lifecycle, repository = make_lifecycle() + entered, release = threading.Event(), threading.Event() + + def occupy_worker(): + entered.set() + assert release.wait(3) + + lifecycle._worker.submit("test-block", occupy_worker) + try: + assert entered.wait(2) + cancelled = lifecycle.finish_transcription() + assert cancelled.cancel() + retry = lifecycle.finish_transcription() + assert retry is not cancelled + finally: + release.set() + assert retry.result(timeout=2) + assert len(repository.attempts) == 1 + + +def test_end_retries_failed_finish_before_ending_exact_call(make_lifecycle): + lifecycle, repository = make_lifecycle(outcomes=[RuntimeError("temporary failure"), True]) + with pytest.raises(RuntimeError): + lifecycle.finish_transcription().result(timeout=2) + assert lifecycle.end("synthetic-hangup").result(timeout=2) + assert repository.events == ["finish", "finish", "end"] + assert repository.attempts[-1]["status"] == "partial" + assert repository.attempts[-1]["transcription_session_id"] == "tr-finish-retry" + assert lifecycle.finish_transcription().result(timeout=2) + assert len(repository.attempts) == 2 + + +def test_failed_finish_cannot_submit_after_end_worker_has_stopped(make_lifecycle): + lifecycle, repository = make_lifecycle( + outcomes=[RuntimeError("first failure"), RuntimeError("fallback failure")], + ) + with pytest.raises(RuntimeError): + lifecycle.finish_transcription().result(timeout=2) + assert lifecycle.end("synthetic-hangup").result(timeout=2) + with pytest.raises(RuntimeError, match="already ended"): + lifecycle.finish_transcription() + assert len(repository.attempts) == 2 diff --git a/app/video_companion/dist/assets/index-BSFyyCww.js b/app/video_companion/dist/assets/index-B6TT7yDM.js similarity index 96% rename from app/video_companion/dist/assets/index-BSFyyCww.js rename to app/video_companion/dist/assets/index-B6TT7yDM.js index f2be2d2f1..c06bb0140 100644 --- a/app/video_companion/dist/assets/index-BSFyyCww.js +++ b/app/video_companion/dist/assets/index-B6TT7yDM.js @@ -1,4 +1,4 @@ -(function(){const i=document.createElement("link").relList;if(i&&i.supports&&i.supports("modulepreload"))return;for(const I of document.querySelectorAll('link[rel="modulepreload"]'))c(I);new MutationObserver(I=>{for(const C of I)if(C.type==="childList")for(const m of C.addedNodes)m.tagName==="LINK"&&m.rel==="modulepreload"&&c(m)}).observe(document,{childList:!0,subtree:!0});function n(I){const C={};return I.integrity&&(C.integrity=I.integrity),I.referrerPolicy&&(C.referrerPolicy=I.referrerPolicy),I.crossOrigin==="use-credentials"?C.credentials="include":I.crossOrigin==="anonymous"?C.credentials="omit":C.credentials="same-origin",C}function c(I){if(I.ep)return;I.ep=!0;const C=n(I);fetch(I.href,C)}})();var Dg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function i4(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function $U(e){if(e.__esModule)return e;var i=e.default;if(typeof i=="function"){var n=function c(){return this instanceof c?Reflect.construct(i,arguments,this.constructor):i.apply(this,arguments)};n.prototype=i.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(c){var I=Object.getOwnPropertyDescriptor(e,c);Object.defineProperty(n,c,I.get?I:{enumerable:!0,get:function(){return e[c]}})}),n}var hY={exports:{}},YnA=hY.exports,V8;function VnA(){return V8||(V8=1,function(e,i){(function(n,c){e.exports=c()})(YnA,function(){const n=s=>s===void 0,c=s=>typeof s=="string",I=s=>{var r;return(r=Object.prototype.toString.call(s).match(/^\[object (.*)\]$/))===null||r===void 0?void 0:r[1].toLowerCase()},C=s=>typeof Array.isArray=="function"?Array.isArray(s):I(s)==="array",m=s=>s!==null&&typeof s=="object",R=s=>C(s)||m(s),_=s=>{if(typeof s!="string")return!1;const r=s[0];return!/[^a-zA-Z0-9]/.test(r)},T=s=>{if(typeof s!="object"||s===null)return!1;const r=Object.getPrototypeOf(s);if(r===null)return!0;let g=r;for(;Object.getPrototypeOf(g)!==null;)g=Object.getPrototypeOf(g);return r===g};function b(s=99999999){return Math.round(Math.random()*s)}const J=(s,r,g,u)=>{if(!R(s)||!R(r))return 0;let E=0;const f=Object.keys(r);let D;for(let v=0,N=f.length;v"u"&&typeof uni.requireNativePlugin=="function",Ji=Xe&&typeof wx.miniapp=="object",Vi=typeof uni<"u",wn=pt&&typeof tt.enterChat=="function",Fi=Xe||Je||pt||Pt||ii||ao||ki,en=typeof window>"u"&&!Fi&&typeof Dg<"u"&&Dg.NativeScriptGlobals!==void 0,Ro=typeof Dg<"u"&&(Dg.nativeModuleProxy!==void 0||Dg.ReactNative!==void 0),oo=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,Ai=typeof uni<"u"?!Fi:typeof window<"u"&&!Fi&&!Ro,no=Je?qq:pt?tt:Pt?swan:ii?my:Xe?wx:ao?uni:ki?jd:{},Ri=Ai&&window&&window.navigator&&window.navigator.userAgent||"",pn=/(micromessenger|webbrowser)/i.test(Ri),jA=function(){let s="WEB";return pn?s="WEB":Je?s="QQ_MP":pt?s="TT_MP":Pt?s="BAIDU_MP":ii?s="ALI_MP":Xe?s=Ji?"DONUT_NATIVE_APP":"WX_MP":ao?s="UNI_NATIVE_APP":en?s="NS_NATIVE_APP":Ro&&(s="RN_NATIVE_APP"),eA[s]}(),ue=/iPad/i.test(Ri),He=/iPhone/i.test(Ri)&&!ue,Lt=/iPod/i.test(Ri),ct=He||ue||Lt,Ct=function(){const s=Ri.match(/OS (\d+)_/i);return s&&s[1]?s[1]:null}(),ei=/Android/i.test(Ri),Ht=function(){const s=Ri.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!s)return null;const r=s[1]&&parseFloat(s[1]),g=s[2]&&parseFloat(s[2]);return r&&g?parseFloat(`${s[1]}.${s[2]}`):r||null}(),Le=/Firefox/i.test(Ri),it=/Edge/i.test(Ri),Tt=!it&&/Chrome/i.test(Ri),Gt=/MSIE/.test(Ri)||Ri.indexOf("Trident")>-1&&Ri.indexOf("rv:11.0")>-1,Hi=function(){const s=/MSIE\s(\d+)\.\d/.exec(Ri);let r=s&&parseFloat(s[1]);return!r&&/Trident\/7.0/i.test(Ri)&&/rv:11.0/.test(Ri)&&(r=11),r}(),po=/Safari/i.test(Ri)&&!Tt&&!ei&&!it,To=/Windows/i.test(Ri),Zi=/MAC OS X/i.test(Ri),wo=Ai&&typeof Worker<"u"&&!Gt,Cn=ei||ct,an=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:s}=window.navigator;return!(!ct||s||po)}();function Vo(){let s="unknown";if(Zi&&(s="mac"),To&&(s="windows"),ct&&(s="ios"),ei&&(s="android"),Fi)try{const{platform:r}=no.getSystemInfoSync();r!==void 0&&(s=r)}catch(r){console.error(r)}return s}const jn=typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0&&typeof window>"u";function vo(s,r){var g={};for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&r.indexOf(u)<0&&(g[u]=s[u]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function"){var E=0;for(u=Object.getOwnPropertySymbols(s);E{no.request({url:g,data:u,method:r,timeout:E,header:{"content-type":Fr},success:v=>f(v.data),fail:()=>D(new Error(`{"message":"Network error","code":${xs}}`))})}):jn?void 0:new Promise((f,D)=>{const v=new XMLHttpRequest,N=setTimeout(()=>{v.abort(),D(new Error(`{"message":"Request timeout","code":${Zs}}`))},E);v.onreadystatechange=function(){if(v.readyState===4)if(clearTimeout(N),v.status===200||v.status===304)try{f(v.responseText?JSON.parse(v.responseText):null)}catch{f(v.responseText)}else D(new Error(`{"message":"Network error","code":${xs}}`))},v.open(r,g,!0),v.setRequestHeader("Content-type",Fr),v.send(u||null)})})}function tn(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(T(s)){for(const r in s)if(Object.prototype.hasOwnProperty.call(s,r))return!1;return!0}return(Object.prototype.toString.call(s)==="[object Map]"||Object.prototype.toString.call(s)==="[object Set]"||Object.prototype.toString.call(s)==="[object File]")&&s.size===0}function Ks(s,r){if(s===null||typeof s!="object")return s;const g=r||new WeakMap;if(g.has(s))return g.get(s);if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s.source,s.flags);if(s instanceof Map){const f=new Map;return g.set(s,f),s.forEach((D,v)=>{f.set(Ks(v,g),Ks(D,g))}),f}if(s instanceof Set){const f=new Set;return g.set(s,f),s.forEach(D=>{f.add(Ks(D,g))}),f}if(Array.isArray(s)){const f=[];return g.set(s,f),s.forEach(D=>{f.push(Ks(D,g))}),f}const u=Object.getPrototypeOf(s),E=Object.create(u);return g.set(s,E),[...Object.getOwnPropertyNames(s),...Object.getOwnPropertySymbols(s)].forEach(f=>{if(f==="__ob__"||f==="__v_skip"||f==="__v_isRef"||f==="__v_isReadonly")return;const D=Object.getOwnPropertyDescriptor(s,f);D&&(D.get||D.set?Object.defineProperty(E,f,D):E[f]=Ks(s[f],g))}),E}function _n(s,r,g){const u=new WeakSet,E=(f,D)=>{if(r&&(D=r(f,D)),D===void 0)return"undefined";if(D===null)return null;if(Number.isNaN(D))return"NaN";if(D===1/0)return"Infinity";if(D===-1/0)return"-Infinity";if(typeof D=="function")return`[Function: ${D.name||"anonymous"}]`;if(typeof D=="symbol")return D.toString();if(typeof D=="bigint")return`${D.toString()}n`;if(typeof D=="object"&&D!==null){if(u.has(D))return"[Circular]";u.add(D)}return D instanceof Date?D.toISOString():D instanceof Error?{name:D.name,message:D.message}:D instanceof Map?{dataType:"Map",value:Array.from(D.entries())}:D instanceof Set?{dataType:"Set",value:Array.from(D.values())}:D};try{return JSON.stringify(s,E,g)}catch(f){return console.error("Failed to stringify:",f),""}}function Is(){let s,r;return{promise:new Promise((g,u)=>{s=g,r=u}),resolve:s,reject:r}}var qt,$a=Object.freeze({__proto__:null,ANDROID_VERSION:Ht,IE_VERSION:Hi,IN_ALIPAY_MINI_APP:ii,IN_BAIDU_MINI_APP:Pt,IN_BROWSER:Ai,IN_DONUT_NATIVE_APP:Ji,IN_FEISHU_MINI_APP:wn,IN_JD_MINI_APP:ki,IN_MINI_APP:Fi,IN_NODE:jn,IN_NS_NATIVE_APP:en,IN_QQ_MINI_APP:Je,IN_RN_APP:Ro,IN_TT_MINI_APP:pt,IN_TT_MINI_GAME:$t,IN_UNI_APP:Vi,IN_UNI_NATIVE_APP:ao,IN_WX_MINI_APP:Xe,IN_WX_MINI_APP_DESK:et,IN_WX_MINI_GAME:ae,IN_WX_MINI_PLUGIN:oo,IOS_VERSION:Ct,IS_ANDROID:ei,IS_CHROME:Tt,IS_EDGE:it,IS_FIREFOX:Le,IS_IE:Gt,IS_IOS:ct,IS_IPAD:ue,IS_IPHONE:He,IS_IPOD:Lt,IS_MAC:Zi,IS_SAFARI:po,IS_WECHAT:pn,IS_WIN:To,IS_WORKER_AVAILABLE:wo,MINI_APP_NAMESPACE:no,USER_AGENT:Ri,base16EncodeBinaryString:cA,deepCopyWithMethods:Ks,deepMerge:J,generatePromise:Is,getPlatformType:Vo,getType:I,httpRequest:qi,isArray:C,isArrayOrObject:R,isEmpty:tn,isH5:Cn,isIOSWebView:an,isNumber:s=>s!==null&&(typeof s=="number"&&!Number.isNaN(s-0)||typeof s=="object"&&s.constructor===Number),isObject:m,isPlainObject:T,isString:c,isUndefined:n,isUniIOSApp:function(){return ao&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:_,platform:jA,randomInt:b,randomString:function(){const s="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let r="";for(let g=32;g>0;--g)r+=s[Math.floor(62*Math.random())];return r},safeStringify:_n});class Ls{constructor(){this.listeners={}}on(r,g,u){this.listeners[r]||(this.listeners[r]=[]),this.listeners[r].push({fn:g,context:u})}off(r,g,u){var E;g&&(this.listeners[r]=(E=this.listeners[r])===null||E===void 0?void 0:E.filter(f=>{const D=f.fn===g,v=!u||f.context===u;return!(D&&v)}))}emit(r,...g){const u=this.listeners[r];u&&u.forEach(E=>{const{fn:f,context:D}=E;try{f.apply(D,g)}catch(v){console.warn(`Error in event handler for ${r} error: ${_n(v)}`)}})}once(r,g,u){const E=(...f)=>{g.apply(u,f),this.off(r,E)};this.on(r,E)}}(function(s){s.BUSINESS_COMMAND="business_command",s.C2C_REALTIME_MESSAGE="c2c_realtime_message",s.C2C_MESSAGE_MODIFIED="c2c_message_modified",s.C2C_REVOKED_MESSAGE="c2c_message_revoked",s.GROUP_REALTIME_MESSAGE="group_realtime_message",s.GROUP_MESSAGE_MODIFIED="group_message_modified",s.GROUP_MESSAGE_REVOKED="group_message_revoked",s.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",s.MESSAGE_REACTION_UPDATED="message_reaction_updated",s.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",s.GROUP_AT_TIPS="group_at_tips",s.USER_STATUS_UPDATE="user_status_update",s.FRIEND_LIST_MODIFIED="friend_list_modified",s.PROFILE_MODIFIED="profile_modified",s.CONV_MODIFIED="conversation_modified",s.GROUP_TIPS_NOTIFICATION="group_tips_notification",s.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",s.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",s.GROUP_SYSTEM_NOTIFICATION="group_system_notification",s.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",s.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",s.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",s.FOLLOW_LIST_UPDATED="follow_list_updated",s.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",s.ALL_MESSAGE_READ="all_message_read",s.CONVERSATION_MARK_UPDATED="conversation_mark_updated",s.CONVERSATION_GROUP_ADD="conversation_group_add",s.CONVERSATION_GROUP_DELETED="conversation_group_deleted",s.CONVERSATION_GROUP_UPDATED="conversation_group_updated",s.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",s.TOPIC_AT_TIPS="topic_at_tips",s.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",s.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",s.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",s.TOPIC_LATEST_MESSAGE="topic_latest_message",s.GROUP_MESSAGE_PINNED="group_message_pinned"})(qt||(qt={}));const Bs=[16,17];function Un(s){var r;const g=[];return(r=s?.GroupTips)===null||r===void 0||r.forEach(u=>{var E;u.GroupInfo.MillionGroupFlag===2?g.push(qt.TOPIC_TIPS_NOTIFICATION):Bs.includes((E=u?.MsgBody)===null||E===void 0?void 0:E.OpType)?g.push(qt.GROUP_MESSAGE_PINNED):g.push(qt.GROUP_TIPS_NOTIFICATION)}),g}const Ir=[{conditions:[{type:"event",value:100}],subType:qt.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:qt.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:qt.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:qt.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:qt.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:qt.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:qt.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:qt.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:qt.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:qt.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(s){var r;const g=[];return(r=s?.C2cNotifyMsgArray)===null||r===void 0||r.forEach(u=>{u.WithdrawC2cMsgNotify&&g.push(qt.C2C_REVOKED_MESSAGE),u.C2cReadedReceipt&&g.push(qt.C2C_MESSAGE_PEER_READ),u.ReadC2cMsgNotify&&g.push(qt.C2C_MESSAGE_READ_SYNC),u.MuteNotificationsSync&&g.push(qt.C2C_REMIND_TYPE_SYNC)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Un},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(s){var r;const g=[];return(r=s?.GroupTips)===null||r===void 0||r.forEach(u=>{Array.isArray(u.MsgBody.GroupWithdrawInfoArray)?g.push(qt.GROUP_MESSAGE_REVOKED):Array.isArray(u.MsgBody.GroupMsgReceiptList)?g.push(qt.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(u.MsgBody.GroupReadInfoArray)?u.MsgBody.GroupReadInfoArray[0].TopicId?g.push(qt.TOPIC_MESSAGE_READ_SYNC):g.push(qt.GROUP_MESSAGE_READ_SYNC):u.GroupInfo.MillionGroupFlag===2?g.push(qt.TOPIC_SYSTEM_NOTIFICATION):g.push(qt.GROUP_SYSTEM_NOTIFICATION)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:Un},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(s){var r;const g=[];return(r=s?.GroupTips)===null||r===void 0||r.forEach(u=>{const{GroupAtTips:{TopicId:E}}=u;E?g.push(qt.TOPIC_AT_TIPS):g.push(qt.GROUP_AT_TIPS)}),g}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(s){var r;const g=[];return(r=s?.RecentContactMod)===null||r===void 0||r.forEach(u=>{switch(u.PushType){case Pe.CONV_MARK_UPDATED:g.push(qt.CONVERSATION_MARK_UPDATED);break;case Pe.CONV_GROUP_ADDED:g.push(qt.CONVERSATION_GROUP_ADD);break;case Pe.CONV_GROUP_DELETED:g.push(qt.CONVERSATION_GROUP_DELETED);break;case Pe.CONV_GROUP_UPDATED:g.push(qt.CONVERSATION_GROUP_UPDATED);break;default:g.push(qt.CONV_MODIFIED)}}),g}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:qt.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:qt.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:qt.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:qt.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:qt.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:qt.ALL_MESSAGE_READ}];var Fn;function rr(s){var r;const g=Array.isArray((r=s?.body)===null||r===void 0?void 0:r.EventArray)?s.body.EventArray:[],u=[];return g.forEach(E=>{E.Flag=s.body.Flag;const f=Ir.find(v=>v.conditions.every(N=>{switch(N.type){case"event":return E.Event===N.value;case"hasKey":return Object.prototype.hasOwnProperty.call(E,N.value);default:return!1}}));if(!f)return null;let D=[];typeof f.subTypeParser=="function"?D=f.subTypeParser(E):f.subType&&(D=f.subType),Array.isArray(D)?D.forEach(v=>{u.push({type:`${Fn.SERVER_PUSH_MESSAGE}:${v}`,data:E})}):u.push({type:`${Fn.SERVER_PUSH_MESSAGE}:${D}`,data:E})}),u}(function(s){s.SERVER_PUSH_MESSAGE="im_open_push.msg_push",s.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",s.ERROR="error"})(Fn||(Fn={}));const fo={[Fn.SERVER_PUSH_MESSAGE]:rr,[Fn.SERVER_PUSH_MESSAGE_MULTIPLE]:rr,[Fn.ERROR]:function(s){const{errorCode:r}=s;return[{type:`error:${r}`,data:s}]}},es=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._filteredCallbackMap=new Map,this._outerEventEmitter=new Ls,this._innerEventEmitter=new Ls,this.InnerEventSubType=qt}subscribeInnerEvent(s,r,g,u,E){var f;let D,v,N,P;["string","number"].includes(typeof r)?(N=`${s}:${r}`,P=g,v=u,D=E):(N=s,P=r,v=g,D=typeof u=="function"?u:void 0),D?this._subscribeWithFilter(N,P,v,D):(f=this._innerEventEmitter)===null||f===void 0||f.on(N,P,v)}emitInnerEvent(s,r){var g,u;if((g=this._innerEventEmitter)===null||g===void 0||g.emit(s,r),Object.keys(fo).includes(s)){const E=(u=fo[s])===null||u===void 0?void 0:u.call(fo,r);E?.forEach(f=>{var D;f&&((D=this._innerEventEmitter)===null||D===void 0||D.emit(f.type,f.data))})}}subscribeOuterEvent(s,r,g){var u;(u=this._outerEventEmitter)===null||u===void 0||u.on(s,r,g)}unSubscribeOuterEvent(s,r,g){var u;(u=this._outerEventEmitter)===null||u===void 0||u.off(s,r,g)}unSubscribeInnerEvent(s,r,g,u){if(["string","number"].includes(typeof r)){const E=g,f=`${s}:${r}`;this._unsubscribeEvent(f,E,u)}else{const E=r;this._unsubscribeEvent(s,E,g)}}emitOuterEvent(s,r){var g;(g=this._outerEventEmitter)===null||g===void 0||g.emit(s,r)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}_subscribeWithFilter(s,r,g,u){var E;const f=D=>{u.call(g,D)&&r.call(g,D)};this._filteredCallbackMap.has(s)||this._filteredCallbackMap.set(s,[]),this._filteredCallbackMap.get(s).push({originalCallback:r,filteredCallback:f,filter:u,context:g}),(E=this._innerEventEmitter)===null||E===void 0||E.on(s,f,g)}_unsubscribeEvent(s,r,g){var u,E;const f=this._filteredCallbackMap.get(s);if(f){const D=f.findIndex(v=>v.originalCallback===r&&v.context===g);if(D!==-1){const{filteredCallback:v}=f[D];return(u=this._innerEventEmitter)===null||u===void 0||u.off(s,v,g),f.splice(D,1),void(f.length===0&&this._filteredCallbackMap.delete(s))}}(E=this._innerEventEmitter)===null||E===void 0||E.off(s,r,g)}};class vc{constructor(){this._socket=null}connectSocket(r){return this._socket=new WebSocket(r),this._socket}send(r){var g,u;try{(g=this._socket)===null||g===void 0||g.send(r)}catch(E){(u=this._onSendFail)===null||u===void 0||u.call(this,E)}}bindSocketHandlers(r){const{onOpen:g,onMessage:u,onClose:E,onError:f,onSendFail:D}=r;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=g,this._socket.onmessage=u,this._socket.onclose=E,this._socket.onerror=f,this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class ts{constructor(r){this._onError=r.onError}connectSocket(r){const g=this;return this._socket=no.connectSocket({url:r,header:{"content-type":"application/json"},complete:()=>{},fail:u=>g._onError(u)}),this._socket}send(r){var g;(g=this._socket)===null||g===void 0||g.send({data:r,fail:this._onSendFail})}bindSocketHandlers(r){const{onOpen:g,onMessage:u,onClose:E,onError:f,onSendFail:D}=r;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(u),this._socket.onError(f),this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const ur="CONNECT",On="SEND",vg="DISCONNECT",yn="OPEN",ce="MESSAGE",ot="CLOSE",Zt="ERROR",Ho="SEND_FAIL";class Ba{constructor(){this._worker=null,this._blobUrl=null}connectSocket(r){const g=new Blob([` +(function(){const i=document.createElement("link").relList;if(i&&i.supports&&i.supports("modulepreload"))return;for(const I of document.querySelectorAll('link[rel="modulepreload"]'))c(I);new MutationObserver(I=>{for(const C of I)if(C.type==="childList")for(const m of C.addedNodes)m.tagName==="LINK"&&m.rel==="modulepreload"&&c(m)}).observe(document,{childList:!0,subtree:!0});function n(I){const C={};return I.integrity&&(C.integrity=I.integrity),I.referrerPolicy&&(C.referrerPolicy=I.referrerPolicy),I.crossOrigin==="use-credentials"?C.credentials="include":I.crossOrigin==="anonymous"?C.credentials="omit":C.credentials="same-origin",C}function c(I){if(I.ep)return;I.ep=!0;const C=n(I);fetch(I.href,C)}})();var Sg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function i4(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function $U(e){if(e.__esModule)return e;var i=e.default;if(typeof i=="function"){var n=function c(){return this instanceof c?Reflect.construct(i,arguments,this.constructor):i.apply(this,arguments)};n.prototype=i.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(c){var I=Object.getOwnPropertyDescriptor(e,c);Object.defineProperty(n,c,I.get?I:{enumerable:!0,get:function(){return e[c]}})}),n}var hY={exports:{}},YnA=hY.exports,V8;function VnA(){return V8||(V8=1,function(e,i){(function(n,c){e.exports=c()})(YnA,function(){const n=s=>s===void 0,c=s=>typeof s=="string",I=s=>{var r;return(r=Object.prototype.toString.call(s).match(/^\[object (.*)\]$/))===null||r===void 0?void 0:r[1].toLowerCase()},C=s=>typeof Array.isArray=="function"?Array.isArray(s):I(s)==="array",m=s=>s!==null&&typeof s=="object",R=s=>C(s)||m(s),_=s=>{if(typeof s!="string")return!1;const r=s[0];return!/[^a-zA-Z0-9]/.test(r)},T=s=>{if(typeof s!="object"||s===null)return!1;const r=Object.getPrototypeOf(s);if(r===null)return!0;let g=r;for(;Object.getPrototypeOf(g)!==null;)g=Object.getPrototypeOf(g);return r===g};function b(s=99999999){return Math.round(Math.random()*s)}const J=(s,r,g,u)=>{if(!R(s)||!R(r))return 0;let E=0;const f=Object.keys(r);let D;for(let v=0,N=f.length;v"u"&&typeof uni.requireNativePlugin=="function",Ji=Xe&&typeof wx.miniapp=="object",Vi=typeof uni<"u",wn=pt&&typeof tt.enterChat=="function",Fi=Xe||Je||pt||Pt||ii||ao||ki,en=typeof window>"u"&&!Fi&&typeof Sg<"u"&&Sg.NativeScriptGlobals!==void 0,Ro=typeof Sg<"u"&&(Sg.nativeModuleProxy!==void 0||Sg.ReactNative!==void 0),oo=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,Ai=typeof uni<"u"?!Fi:typeof window<"u"&&!Fi&&!Ro,no=Je?qq:pt?tt:Pt?swan:ii?my:Xe?wx:ao?uni:ki?jd:{},Ri=Ai&&window&&window.navigator&&window.navigator.userAgent||"",pn=/(micromessenger|webbrowser)/i.test(Ri),jA=function(){let s="WEB";return pn?s="WEB":Je?s="QQ_MP":pt?s="TT_MP":Pt?s="BAIDU_MP":ii?s="ALI_MP":Xe?s=Ji?"DONUT_NATIVE_APP":"WX_MP":ao?s="UNI_NATIVE_APP":en?s="NS_NATIVE_APP":Ro&&(s="RN_NATIVE_APP"),eA[s]}(),ue=/iPad/i.test(Ri),He=/iPhone/i.test(Ri)&&!ue,Lt=/iPod/i.test(Ri),ct=He||ue||Lt,Ct=function(){const s=Ri.match(/OS (\d+)_/i);return s&&s[1]?s[1]:null}(),ei=/Android/i.test(Ri),Ht=function(){const s=Ri.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!s)return null;const r=s[1]&&parseFloat(s[1]),g=s[2]&&parseFloat(s[2]);return r&&g?parseFloat(`${s[1]}.${s[2]}`):r||null}(),Le=/Firefox/i.test(Ri),it=/Edge/i.test(Ri),Tt=!it&&/Chrome/i.test(Ri),Gt=/MSIE/.test(Ri)||Ri.indexOf("Trident")>-1&&Ri.indexOf("rv:11.0")>-1,Hi=function(){const s=/MSIE\s(\d+)\.\d/.exec(Ri);let r=s&&parseFloat(s[1]);return!r&&/Trident\/7.0/i.test(Ri)&&/rv:11.0/.test(Ri)&&(r=11),r}(),po=/Safari/i.test(Ri)&&!Tt&&!ei&&!it,To=/Windows/i.test(Ri),Zi=/MAC OS X/i.test(Ri),wo=Ai&&typeof Worker<"u"&&!Gt,Cn=ei||ct,an=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:s}=window.navigator;return!(!ct||s||po)}();function Vo(){let s="unknown";if(Zi&&(s="mac"),To&&(s="windows"),ct&&(s="ios"),ei&&(s="android"),Fi)try{const{platform:r}=no.getSystemInfoSync();r!==void 0&&(s=r)}catch(r){console.error(r)}return s}const jn=typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0&&typeof window>"u";function vo(s,r){var g={};for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&r.indexOf(u)<0&&(g[u]=s[u]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function"){var E=0;for(u=Object.getOwnPropertySymbols(s);E{no.request({url:g,data:u,method:r,timeout:E,header:{"content-type":Fr},success:v=>f(v.data),fail:()=>D(new Error(`{"message":"Network error","code":${xs}}`))})}):jn?void 0:new Promise((f,D)=>{const v=new XMLHttpRequest,N=setTimeout(()=>{v.abort(),D(new Error(`{"message":"Request timeout","code":${Zs}}`))},E);v.onreadystatechange=function(){if(v.readyState===4)if(clearTimeout(N),v.status===200||v.status===304)try{f(v.responseText?JSON.parse(v.responseText):null)}catch{f(v.responseText)}else D(new Error(`{"message":"Network error","code":${xs}}`))},v.open(r,g,!0),v.setRequestHeader("Content-type",Fr),v.send(u||null)})})}function tn(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(T(s)){for(const r in s)if(Object.prototype.hasOwnProperty.call(s,r))return!1;return!0}return(Object.prototype.toString.call(s)==="[object Map]"||Object.prototype.toString.call(s)==="[object Set]"||Object.prototype.toString.call(s)==="[object File]")&&s.size===0}function Ks(s,r){if(s===null||typeof s!="object")return s;const g=r||new WeakMap;if(g.has(s))return g.get(s);if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s.source,s.flags);if(s instanceof Map){const f=new Map;return g.set(s,f),s.forEach((D,v)=>{f.set(Ks(v,g),Ks(D,g))}),f}if(s instanceof Set){const f=new Set;return g.set(s,f),s.forEach(D=>{f.add(Ks(D,g))}),f}if(Array.isArray(s)){const f=[];return g.set(s,f),s.forEach(D=>{f.push(Ks(D,g))}),f}const u=Object.getPrototypeOf(s),E=Object.create(u);return g.set(s,E),[...Object.getOwnPropertyNames(s),...Object.getOwnPropertySymbols(s)].forEach(f=>{if(f==="__ob__"||f==="__v_skip"||f==="__v_isRef"||f==="__v_isReadonly")return;const D=Object.getOwnPropertyDescriptor(s,f);D&&(D.get||D.set?Object.defineProperty(E,f,D):E[f]=Ks(s[f],g))}),E}function _n(s,r,g){const u=new WeakSet,E=(f,D)=>{if(r&&(D=r(f,D)),D===void 0)return"undefined";if(D===null)return null;if(Number.isNaN(D))return"NaN";if(D===1/0)return"Infinity";if(D===-1/0)return"-Infinity";if(typeof D=="function")return`[Function: ${D.name||"anonymous"}]`;if(typeof D=="symbol")return D.toString();if(typeof D=="bigint")return`${D.toString()}n`;if(typeof D=="object"&&D!==null){if(u.has(D))return"[Circular]";u.add(D)}return D instanceof Date?D.toISOString():D instanceof Error?{name:D.name,message:D.message}:D instanceof Map?{dataType:"Map",value:Array.from(D.entries())}:D instanceof Set?{dataType:"Set",value:Array.from(D.values())}:D};try{return JSON.stringify(s,E,g)}catch(f){return console.error("Failed to stringify:",f),""}}function Is(){let s,r;return{promise:new Promise((g,u)=>{s=g,r=u}),resolve:s,reject:r}}var qt,$a=Object.freeze({__proto__:null,ANDROID_VERSION:Ht,IE_VERSION:Hi,IN_ALIPAY_MINI_APP:ii,IN_BAIDU_MINI_APP:Pt,IN_BROWSER:Ai,IN_DONUT_NATIVE_APP:Ji,IN_FEISHU_MINI_APP:wn,IN_JD_MINI_APP:ki,IN_MINI_APP:Fi,IN_NODE:jn,IN_NS_NATIVE_APP:en,IN_QQ_MINI_APP:Je,IN_RN_APP:Ro,IN_TT_MINI_APP:pt,IN_TT_MINI_GAME:$t,IN_UNI_APP:Vi,IN_UNI_NATIVE_APP:ao,IN_WX_MINI_APP:Xe,IN_WX_MINI_APP_DESK:et,IN_WX_MINI_GAME:ae,IN_WX_MINI_PLUGIN:oo,IOS_VERSION:Ct,IS_ANDROID:ei,IS_CHROME:Tt,IS_EDGE:it,IS_FIREFOX:Le,IS_IE:Gt,IS_IOS:ct,IS_IPAD:ue,IS_IPHONE:He,IS_IPOD:Lt,IS_MAC:Zi,IS_SAFARI:po,IS_WECHAT:pn,IS_WIN:To,IS_WORKER_AVAILABLE:wo,MINI_APP_NAMESPACE:no,USER_AGENT:Ri,base16EncodeBinaryString:gA,deepCopyWithMethods:Ks,deepMerge:J,generatePromise:Is,getPlatformType:Vo,getType:I,httpRequest:qi,isArray:C,isArrayOrObject:R,isEmpty:tn,isH5:Cn,isIOSWebView:an,isNumber:s=>s!==null&&(typeof s=="number"&&!Number.isNaN(s-0)||typeof s=="object"&&s.constructor===Number),isObject:m,isPlainObject:T,isString:c,isUndefined:n,isUniIOSApp:function(){return ao&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:_,platform:jA,randomInt:b,randomString:function(){const s="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let r="";for(let g=32;g>0;--g)r+=s[Math.floor(62*Math.random())];return r},safeStringify:_n});class Ls{constructor(){this.listeners={}}on(r,g,u){this.listeners[r]||(this.listeners[r]=[]),this.listeners[r].push({fn:g,context:u})}off(r,g,u){var E;g&&(this.listeners[r]=(E=this.listeners[r])===null||E===void 0?void 0:E.filter(f=>{const D=f.fn===g,v=!u||f.context===u;return!(D&&v)}))}emit(r,...g){const u=this.listeners[r];u&&u.forEach(E=>{const{fn:f,context:D}=E;try{f.apply(D,g)}catch(v){console.warn(`Error in event handler for ${r} error: ${_n(v)}`)}})}once(r,g,u){const E=(...f)=>{g.apply(u,f),this.off(r,E)};this.on(r,E)}}(function(s){s.BUSINESS_COMMAND="business_command",s.C2C_REALTIME_MESSAGE="c2c_realtime_message",s.C2C_MESSAGE_MODIFIED="c2c_message_modified",s.C2C_REVOKED_MESSAGE="c2c_message_revoked",s.GROUP_REALTIME_MESSAGE="group_realtime_message",s.GROUP_MESSAGE_MODIFIED="group_message_modified",s.GROUP_MESSAGE_REVOKED="group_message_revoked",s.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",s.MESSAGE_REACTION_UPDATED="message_reaction_updated",s.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",s.GROUP_AT_TIPS="group_at_tips",s.USER_STATUS_UPDATE="user_status_update",s.FRIEND_LIST_MODIFIED="friend_list_modified",s.PROFILE_MODIFIED="profile_modified",s.CONV_MODIFIED="conversation_modified",s.GROUP_TIPS_NOTIFICATION="group_tips_notification",s.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",s.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",s.GROUP_SYSTEM_NOTIFICATION="group_system_notification",s.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",s.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",s.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",s.FOLLOW_LIST_UPDATED="follow_list_updated",s.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",s.ALL_MESSAGE_READ="all_message_read",s.CONVERSATION_MARK_UPDATED="conversation_mark_updated",s.CONVERSATION_GROUP_ADD="conversation_group_add",s.CONVERSATION_GROUP_DELETED="conversation_group_deleted",s.CONVERSATION_GROUP_UPDATED="conversation_group_updated",s.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",s.TOPIC_AT_TIPS="topic_at_tips",s.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",s.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",s.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",s.TOPIC_LATEST_MESSAGE="topic_latest_message",s.GROUP_MESSAGE_PINNED="group_message_pinned"})(qt||(qt={}));const Bs=[16,17];function Un(s){var r;const g=[];return(r=s?.GroupTips)===null||r===void 0||r.forEach(u=>{var E;u.GroupInfo.MillionGroupFlag===2?g.push(qt.TOPIC_TIPS_NOTIFICATION):Bs.includes((E=u?.MsgBody)===null||E===void 0?void 0:E.OpType)?g.push(qt.GROUP_MESSAGE_PINNED):g.push(qt.GROUP_TIPS_NOTIFICATION)}),g}const ur=[{conditions:[{type:"event",value:100}],subType:qt.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:qt.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:qt.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:qt.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:qt.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:qt.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:qt.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:qt.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:qt.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:qt.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(s){var r;const g=[];return(r=s?.C2cNotifyMsgArray)===null||r===void 0||r.forEach(u=>{u.WithdrawC2cMsgNotify&&g.push(qt.C2C_REVOKED_MESSAGE),u.C2cReadedReceipt&&g.push(qt.C2C_MESSAGE_PEER_READ),u.ReadC2cMsgNotify&&g.push(qt.C2C_MESSAGE_READ_SYNC),u.MuteNotificationsSync&&g.push(qt.C2C_REMIND_TYPE_SYNC)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Un},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(s){var r;const g=[];return(r=s?.GroupTips)===null||r===void 0||r.forEach(u=>{Array.isArray(u.MsgBody.GroupWithdrawInfoArray)?g.push(qt.GROUP_MESSAGE_REVOKED):Array.isArray(u.MsgBody.GroupMsgReceiptList)?g.push(qt.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(u.MsgBody.GroupReadInfoArray)?u.MsgBody.GroupReadInfoArray[0].TopicId?g.push(qt.TOPIC_MESSAGE_READ_SYNC):g.push(qt.GROUP_MESSAGE_READ_SYNC):u.GroupInfo.MillionGroupFlag===2?g.push(qt.TOPIC_SYSTEM_NOTIFICATION):g.push(qt.GROUP_SYSTEM_NOTIFICATION)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:Un},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(s){var r;const g=[];return(r=s?.GroupTips)===null||r===void 0||r.forEach(u=>{const{GroupAtTips:{TopicId:E}}=u;E?g.push(qt.TOPIC_AT_TIPS):g.push(qt.GROUP_AT_TIPS)}),g}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(s){var r;const g=[];return(r=s?.RecentContactMod)===null||r===void 0||r.forEach(u=>{switch(u.PushType){case Pe.CONV_MARK_UPDATED:g.push(qt.CONVERSATION_MARK_UPDATED);break;case Pe.CONV_GROUP_ADDED:g.push(qt.CONVERSATION_GROUP_ADD);break;case Pe.CONV_GROUP_DELETED:g.push(qt.CONVERSATION_GROUP_DELETED);break;case Pe.CONV_GROUP_UPDATED:g.push(qt.CONVERSATION_GROUP_UPDATED);break;default:g.push(qt.CONV_MODIFIED)}}),g}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:qt.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:qt.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:qt.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:qt.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:qt.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:qt.ALL_MESSAGE_READ}];var Fn;function rr(s){var r;const g=Array.isArray((r=s?.body)===null||r===void 0?void 0:r.EventArray)?s.body.EventArray:[],u=[];return g.forEach(E=>{E.Flag=s.body.Flag;const f=ur.find(v=>v.conditions.every(N=>{switch(N.type){case"event":return E.Event===N.value;case"hasKey":return Object.prototype.hasOwnProperty.call(E,N.value);default:return!1}}));if(!f)return null;let D=[];typeof f.subTypeParser=="function"?D=f.subTypeParser(E):f.subType&&(D=f.subType),Array.isArray(D)?D.forEach(v=>{u.push({type:`${Fn.SERVER_PUSH_MESSAGE}:${v}`,data:E})}):u.push({type:`${Fn.SERVER_PUSH_MESSAGE}:${D}`,data:E})}),u}(function(s){s.SERVER_PUSH_MESSAGE="im_open_push.msg_push",s.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",s.ERROR="error"})(Fn||(Fn={}));const fo={[Fn.SERVER_PUSH_MESSAGE]:rr,[Fn.SERVER_PUSH_MESSAGE_MULTIPLE]:rr,[Fn.ERROR]:function(s){const{errorCode:r}=s;return[{type:`error:${r}`,data:s}]}},es=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._filteredCallbackMap=new Map,this._outerEventEmitter=new Ls,this._innerEventEmitter=new Ls,this.InnerEventSubType=qt}subscribeInnerEvent(s,r,g,u,E){var f;let D,v,N,P;["string","number"].includes(typeof r)?(N=`${s}:${r}`,P=g,v=u,D=E):(N=s,P=r,v=g,D=typeof u=="function"?u:void 0),D?this._subscribeWithFilter(N,P,v,D):(f=this._innerEventEmitter)===null||f===void 0||f.on(N,P,v)}emitInnerEvent(s,r){var g,u;if((g=this._innerEventEmitter)===null||g===void 0||g.emit(s,r),Object.keys(fo).includes(s)){const E=(u=fo[s])===null||u===void 0?void 0:u.call(fo,r);E?.forEach(f=>{var D;f&&((D=this._innerEventEmitter)===null||D===void 0||D.emit(f.type,f.data))})}}subscribeOuterEvent(s,r,g){var u;(u=this._outerEventEmitter)===null||u===void 0||u.on(s,r,g)}unSubscribeOuterEvent(s,r,g){var u;(u=this._outerEventEmitter)===null||u===void 0||u.off(s,r,g)}unSubscribeInnerEvent(s,r,g,u){if(["string","number"].includes(typeof r)){const E=g,f=`${s}:${r}`;this._unsubscribeEvent(f,E,u)}else{const E=r;this._unsubscribeEvent(s,E,g)}}emitOuterEvent(s,r){var g;(g=this._outerEventEmitter)===null||g===void 0||g.emit(s,r)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}_subscribeWithFilter(s,r,g,u){var E;const f=D=>{u.call(g,D)&&r.call(g,D)};this._filteredCallbackMap.has(s)||this._filteredCallbackMap.set(s,[]),this._filteredCallbackMap.get(s).push({originalCallback:r,filteredCallback:f,filter:u,context:g}),(E=this._innerEventEmitter)===null||E===void 0||E.on(s,f,g)}_unsubscribeEvent(s,r,g){var u,E;const f=this._filteredCallbackMap.get(s);if(f){const D=f.findIndex(v=>v.originalCallback===r&&v.context===g);if(D!==-1){const{filteredCallback:v}=f[D];return(u=this._innerEventEmitter)===null||u===void 0||u.off(s,v,g),f.splice(D,1),void(f.length===0&&this._filteredCallbackMap.delete(s))}}(E=this._innerEventEmitter)===null||E===void 0||E.off(s,r,g)}};class vc{constructor(){this._socket=null}connectSocket(r){return this._socket=new WebSocket(r),this._socket}send(r){var g,u;try{(g=this._socket)===null||g===void 0||g.send(r)}catch(E){(u=this._onSendFail)===null||u===void 0||u.call(this,E)}}bindSocketHandlers(r){const{onOpen:g,onMessage:u,onClose:E,onError:f,onSendFail:D}=r;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=g,this._socket.onmessage=u,this._socket.onclose=E,this._socket.onerror=f,this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class ts{constructor(r){this._onError=r.onError}connectSocket(r){const g=this;return this._socket=no.connectSocket({url:r,header:{"content-type":"application/json"},complete:()=>{},fail:u=>g._onError(u)}),this._socket}send(r){var g;(g=this._socket)===null||g===void 0||g.send({data:r,fail:this._onSendFail})}bindSocketHandlers(r){const{onOpen:g,onMessage:u,onClose:E,onError:f,onSendFail:D}=r;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(u),this._socket.onError(f),this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const Er="CONNECT",On="SEND",Mg="DISCONNECT",yn="OPEN",ce="MESSAGE",ot="CLOSE",Zt="ERROR",Ho="SEND_FAIL";class Ba{constructor(){this._worker=null,this._blobUrl=null}connectSocket(r){const g=new Blob([` let _socket = null; self.onmessage = (event) => { @@ -95,26 +95,26 @@ _socket = null; } } -`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(g)),this._worker.postMessage({type:ur,url:r})}send(r){var g,u;try{(g=this._worker)===null||g===void 0||g.postMessage({type:On,data:r})}catch(E){(u=this._onSendFail)===null||u===void 0||u.call(this,E)}}bindSocketHandlers(r){const{onOpen:g,onMessage:u,onClose:E,onError:f,onSendFail:D}=r;if(this._worker){const v={[yn]:g,[ce]:u,[ot]:E,[Zt]:f,[Ho]:D};this._onSendFail=D,this._worker.onmessage=N=>{var P;const{type:W}=N?.data||{};typeof v[W]=="function"&&((P=v[W])===null||P===void 0||P.call(v,N?.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:vg}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class WI{}var gn,ro=new class{constructor(){this._store=new Map}get(s){return this._store.get(s)}getStorage(s){return Fi?ii?my.getStorageSync({key:s}).data:no.getStorageSync(s):this._canUseLocalStorage()?localStorage.getItem(s):{}}set(s,r){const g=this._store.get(s)||{};r instanceof Map?this._store.set(s,r):this._store.set(s,Object.assign(Object.assign({},g),r))}setStorage(s,r){Fi?ii?my.setStorageSync({key:s,data:JSON.stringify(r)}):no.setStorageSync(s,JSON.stringify(r)):this._canUseLocalStorage()&&localStorage.setItem(s,JSON.stringify(r))}clear(s){typeof s=="string"?this._store.set(s,{}):this._store.clear()}clearLocalStorage(s){this._canUseLocalStorage()&&(typeof s=="string"?localStorage.setItem(s,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return typeof window<"u"&&navigator&&navigator.cookieEnabled&&localStorage}};class Mc{connectSocket(r){return this._socket=no.connectSocket({url:r,header:{"content-type":"application/json"},multiple:!0,complete:()=>{}}),this._socket}send(r){var g;(g=this._socket)===null||g===void 0||g.send({data:r,fail:this._onSendFail})}bindSocketHandlers(r){const{onOpen:g,onMessage:u,onClose:E,onError:f,onSendFail:D}=r;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(v=>u(v?.data)),this._socket.onError(()=>f),this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}(function(s){s[s.CONNECTED=0]="CONNECTED",s[s.CONNECTING=1]="CONNECTING",s[s.DISCONNECTED=2]="DISCONNECTED"})(gn||(gn={}));class gg{constructor(r){this._url="",this._readyState=gn.DISCONNECTED,this._url=r,this._id=b(),this._emitter=new Ls,ii?this._socket=new Mc:Xe||ao||pt||Je||ki||Pt?this._socket=new ts({onError:this._onError.bind(this)}):jn?this._socket=new WI:this._canUseWebWorker()?this._socket=new Ba:this._socket=new vc,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[gn.CONNECTED,gn.CONNECTING].includes(this._readyState)||(this._readyState=gn.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(r){this._readyState!==gn.CONNECTED?this.reconnect():this._socket.send(r)}reconnect(){[gn.CONNECTED,gn.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(r,g,u){this._emitter.on(r,g,u)}off(r,g,u){this._emitter.off(r,g,u)}isConnected(){return this._readyState===gn.CONNECTED}disconnect(){this._readyState=gn.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(r){this._readyState===gn.CONNECTING&&(this._readyState=gn.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:r}))}_onMessage(r){this._emitter.emit("message",r)}_onClose(r){this._readyState=gn.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:r})}_onError(r){this._readyState=gn.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:r})}_onSendFail(r){this._readyState=gn.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:r})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}_canUseWebWorker(){const r=ro.get("cloudConfig")||{};return(n(r.isWorkerEnabled)||r.isWorkerEnabled==="1")&&wo}}const Mg={[Ye.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[Ye.KOREA]:[[3e7,4e7],[173e7,174e7]],[Ye.GERMANY]:[[4e7,5e7],[174e7,175e7]],[Ye.IND]:[[5e7,6e7],[175e7,176e7]],[Ye.JPN]:[[6e7,7e7],[176e7,177e7]],[Ye.USA]:[[7e7,8e7],[177e7,178e7]],[Ye.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[Ye.KSA]:[[9e7,1e8],[179e7,18e8]]};function Qa(s){var r;if(!((r=ro.get("instance"))===null||r===void 0)&&r.oversea)return Ye.OVERSEA;for(const g of Object.keys(Mg))for(const[u,E]of Mg[g])if(s>=u&&s`${nA}=${W[nA]}`).join("&"));var W;return g?`${s}/binfo?${P}&compress=gzip`:`${s}/info?${P}`}function is(s){const r=ro.get("instance"),{sdkAppId:g,testEnv:u,proxyServer:E}=r,f=Qa(g);if(u)return Xs(We.TEST[f].DEFAULT,{isBinary:s});if(!tn(E))return Xs(E,{isBinary:s});const D=We.PRODUCTION[f],v=Ai&&D.ANYCAST,N=Ai,P=!!D.BACKUP_CN;return Xs({[Fo.INITIAL]:()=>(Uo=Fo.DEFAULT,D.DEFAULT),[Fo.DEFAULT]:()=>(Uo=Fo.IPV6,D.IPV6),[Fo.IPV6]:()=>(Uo=Fo.BACKUP,D.BACKUP),[Fo.BACKUP]:()=>N?(Uo=Fo.BACKUP_WEB_ONLY,function(W){const nA=Math.floor(10001*Math.random())+1e4;return W.replace("*",String(nA))}(D.BACKUP_WEB_ONLY)):P?(Uo=Fo.BACKUP_CN,D.BACKUP_CN):v?(Uo=Fo.ANYCAST,D.ANYCAST):D.DEFAULT,[Fo.BACKUP_WEB_ONLY]:()=>P?(Uo=Fo.BACKUP_CN,D.BACKUP_CN):v?(Uo=Fo.ANYCAST,D.ANYCAST):D.DEFAULT,[Fo.BACKUP_CN]:()=>(Uo=v?Fo.ANYCAST:Fo.DEFAULT,D[Uo]),[Fo.ANYCAST]:()=>(Uo=Fo.DEFAULT,D.ANYCAST="",D.DEFAULT)}[Uo](),{isBinary:s})}var Rg=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(s,r){const g=Date.now(),u=g-s;this._timeOffsetWithServer=r+u-g}};const Rc=16;var ws=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(s){const{id:r}=s;this.removeTask(r),this._tasks.push(s),this._taskMap.set(r,s),this._sort(),this._scheduleNextTask()}_createTask(s){const{id:r,callback:g,context:u,isOnce:E=!1,intervalMs:f=Rc}=s,D=Math.max(f,Rc);return{id:r,nextExecuteTime:Date.now()+D,intervalMs:f,callback:g,context:u,isOnce:E}}addTask(s){const r=this._createTask(s);this._addTaskToScheduler(r)}addOnceTask(s){const r=this._createTask(Object.assign(Object.assign({},s),{isOnce:!0}));this._addTaskToScheduler(r)}removeTask(s){const r=this._tasks.findIndex(g=>g.id===s);r>-1&&(this._tasks.splice(r,1),this._taskMap.delete(s),this._scheduleNextTask())}updateTaskInterval(s,r){const g=this._taskMap.get(s);g&&(g.intervalMs=r,g.nextExecuteTime=Date.now()+r,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((s,r)=>s.nextExecuteTime-r.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const s=this._tasks[0];if(s){const r=Math.max(0,s.nextExecuteTime-Date.now());this._timer=setTimeout(()=>this._execute(),r)}}_execute(){const s=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=s;){const r=this._tasks[0];try{r.context?r.callback.call(r.context):r.callback(),r.isOnce?this.removeTask(r.id):(r.nextExecuteTime=s+r.intervalMs,this._sort())}catch(g){console.warn(`Task ${r.id} execution failed:`,g),r.isOnce&&this.removeTask(r.id)}}this._scheduleNextTask()}};function Fa(s){const r=[];for(let g=0;g=55296&&u<=56319){const E=s.charCodeAt(++g)-56320+(u-55296<<10)+65536;r.push(240|E>>18,128|E>>12&63,128|E>>6&63,128|63&E)}else u<=127?r.push(u):u<=2047?r.push(192|u>>6,128|63&u):r.push(224|u>>12,128|u>>6&63,128|63&u)}return new Uint8Array(r)}function Qs(s){const r=Array.isArray(s)?[]:Object.create(null);for(const g in s)Object.prototype.hasOwnProperty.call(s,g)&&_(g)&&s[g]!=null&&(s[g]===null||typeof s[g]!="object"?r[g]=s[g]:r[g]=Qs(s[g]));return r}function Tn(s,r){if(CA.includes(s))return 0;const g=Fa(JSON.stringify(r));let u=4294967295;const{length:E}=g;for(let f=0;f>>=1:u=u>>>1^3988292384}return(4294967295^u)>>>0}function pa(s){const{servcmd:r,data:g}=s,u=function(f){const D=ro.get("login")||{},v=ro.get("instance")||{};return{servcmd:f,ver:"v4",platform:jA,websdkappid:537048168,websdkversion:"1.7.3",a2:D.a2Key||void 0,tinyid:D.tinyID||void 0,status_instid:D.statusInstanceId||0,sdkappid:v.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:D.a2Key?void 0:D.userId,usersig:D.a2Key?void 0:D.userSig,sdkability:478343027,sdkability_ext:cA(""),cappid:v.applicationID||0,tjgID:"",seq:Ta(),cs:0}}(r),E=Qs(g);return u.cs=Tn(r,E),{head:u,body:E}}function _s(s){const{servcmd:r,data:g}=s,u=function(f){const D=ro.get("login")||{},v=ro.get("instance")||{};return{servcmd:f,ver:"v4",platform:jA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:v.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:D.statusInstanceId||0,sdkability:478343027,sdkability_ext:cA(""),cappid:v.applicationID||0,seq:Ta(),cs:0}}(r),E=Qs(g);return u.cs=Tn(r,E),{head:u,body:E}}let Oa=b();function Ta(){return Oa=Oa<2415919103?Oa+1:b(),Oa}function $(){var s;const r=ro.get("login")||{},g=ro.get("instance")||{};return{sdk_type:30,sdk_app_id:g.sdkAppId,sdk_version:"1.6.18",tiny_id:Number(r.tinyID),user_id:r.userId||((s=ro.get("webPush"))===null||s===void 0?void 0:s.userId),platform:jA,instance_id:g.instanceId,trace_id:new Date().getTime()}}var j,RA=Object.freeze({__proto__:null,calcBodyCRC:Tn,filterProtocolDataInvalidFields:Qs,generateCosSpecifiedData:function(s){const{servcmd:r,data:g}=s,u=function(f){const D=ro.get("login")||{},v=ro.get("instance")||{};return{servcmd:f,ver:"v4",platform:jA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:v.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:D.userId,usersig:D.userSig,status_instid:D.statusInstanceId||0,sdkability:478343027,sdkability_ext:cA(""),cappid:v.applicationID||0,seq:Ta(),cs:0}}(r),E=Qs(g);return u.cs=Tn(r,E),{head:u,body:E}},generateProtocolData:pa,generateSSOLogProtocolData:_s,generateSequence:Ta,getCommonHead:$,getHostSite:Qa,taskScheduler:ws,timeManager:Rg});(function(s){s[s.info=4]="info",s[s.warning=5]="warning",s[s.error=6]="error"})(j||(j={}));const ZA={method:"extension",networkType:"network_type",eventType:"event_type",code:"error_code",message:"error_message",moreMessage:"more_message",duplicate:"duplicate",costTime:"cost_time",level:"level",uiPlatform:"ui_platform",timestamp:"timestamp"};class ne{constructor(r){this.level=j.info,this._canSendLog=!0,this._logCreatedAt=Rg.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();const{method:g,eventType:u=0,message:E="",costTime:f=0,error:D,uiPlatform:v,moreMessage:N="",code:P=0,startTime:W=0}=r||{};this.eventType=u,this.method=g,this.message=E,this.costTime=f,this.moreMessage=`${N} startTime:${W}`,this.code=P,D&&this.setError(D),tn(v)||(this.uiPlatform=v)}setMoreMessage(r){this.moreMessage=`${this.moreMessage} ${r}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Rg.getTimeOffsetWithServer()}end(r=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=Rg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),r&&this._ssoLogModule.uploadSSOLogData())}setError(r){var g;return r instanceof Error?this._canSendLog?(!((g=ro.get("netWorkMonitor"))===null||g===void 0)&&g.isNetworkOnline&&(r.errorCode&&(this.code=r.errorCode),r.errorMessage&&this.setMoreMessage(r.errorMessage)),this.level=j.error,this):this:(console.warn("SSOLogData.setError value not instanceof Error, please check!"),this)}setLogInfo(r){return Object.keys(r).forEach(g=>{Object.keys(ZA).includes(g)&&(this[g]=r[g])}),this}setSSOLogModule(r){this._ssoLogModule=r}_convertSSOLogDataKeyToServe(){const r={};return Object.keys(this).forEach(g=>{const u=g;ZA[u]&&(r[ZA[u]]=this[u])}),r}_getUiPlatform(){var r;const g=(r=ro.get("instance"))===null||r===void 0?void 0:r.scene;if(typeof g=="string"){const u=Number(g);return isNaN(u)?void 0:u}}_getSDKEdition(){var r;return(r=ro.get("instance"))===null||r===void 0?void 0:r.sdkEdition}}var De;(function(s){s.RECONNECTED="reconnected",s.CLOUD_CONFIG_UPDATE="cloud_config_update",s.SOCKET_DISCONNECTED="socket_disconnected"})(De||(De={}));var Ke=De;const qe=20,Et=6e4,ft=[4,5,6],Nt="report-logger";var Kt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=qe,this._maxThreshold=100,this._waitingTime=Et,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=IA.DEBUG,this._throttleConfig={global:{throttleTime:se,maxCount:WA},single:{throttleTime:Ae,maxCount:HA}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,es.subscribeInnerEvent(Ke.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),ws.addTask({id:Nt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(s){const{evt_rpt_threshold:r=qe,evt_rpt_waiting:g=Et,evt_rpt_level:u=ft,evt_rpt_sdkappid_bl:E="",evt_rpt_tinyid_wl:f="",evt_rpt_global_throttle_time:D=se,evt_rpt_global_throttle_count:v=WA,evt_rpt_single_throttle_time:N=Ae,evt_rpt_single_throttle_count:P=HA}=s||{};this._sdkAppIdBlackList=E.split(",").map(W=>Number(W)),this._waitingTime=Number(g),this._minThreshold=r,this._reportLevel=u,this._tinyIdWhiteList=f.split(","),this._throttleConfig={global:{throttleTime:D,maxCount:v},single:{throttleTime:N,maxCount:P}}}createSSOLogData(s){const r=new ne(s);return r.setSSOLogModule(this),this._ssoLogMap.set(s.method,r),r}getSSOLogData(s){return this._ssoLogMap.get(s)||{}}pushToLogQueue(s){s&&(this._logQueue.push(s),this._shouldUploadImmediately()&&this.uploadSSOLogData())}setLogLevel(s){[IA.DEBUG,IA.ERROR,IA.INFO,IA.NONE,IA.WARN].includes(s)&&(this._logLevel=s)}debug(s,r="",g){this._log(IA.DEBUG,s,r,g)}info(s,r="",g){this._log(IA.INFO,s,r,g)}warn(s,r="",g){this._log(IA.WARN,s,r,g)}error(s,r="",g){this._log(IA.ERROR,s,r,g)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this.uploadSSOLogData()}uploadSSOLogData(){return mA(this,void 0,void 0,function*(){if(this._logQueue.length===0)return;const s=this._logQueue.slice();this._logQueue=[];try{const r=this._filterLogs(s);if(r.length===0)return void(this._lastReportAt=Date.now());const g={Header:$(),Event:r};tn(g.Header.user_id)||(yield function(u){const E="imopenstat.tim_web_report_v2",f=_s({servcmd:E,data:u}),D=`${f.head.seq}${E}`;return ve.sendPacket(f,{requestId:D})}(g))}catch(r){this._requeueFailedLogs(s),this.debug("uploadSSOLogData",_n(r))}finally{this._lastReportAt=Date.now()}})}_requeueFailedLogs(s){this._logQueue=s.concat(this._logQueue);const r=this._logQueue.length-200;r>0&&(this._logQueue.splice(0,r),this.debug("uploadSSOLogData",`log queue overflow, dropped ${r} oldest logs`))}_savePlatFormInfo(){var s,r;if(Xe){const g=(r=(s=wx.getAccountInfoSync)===null||s===void 0?void 0:s.call(wx))===null||r===void 0?void 0:r.miniProgram;if(g){const{appId:u,envVersion:E}=g;ro.set("instance",{appId:u,envVersion:E})}}else Ai&&ro.set("instance",{href:window.location.href})}_filterLogs(s){const{tinyID:r}=ro.get("login")||{},{sdkAppId:g}=ro.get("instance")||{};return this._sdkAppIdBlackList.includes(g)&&!this._tinyIdWhiteList.includes(r)?[]:s.filter(u=>this._reportLevel.includes(u.level))}_checkThrottle(s){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(s)}_checkGlobalThrottle(){const s=Date.now();if(s-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=s;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(s){const r=Date.now(),g=this._singleThrottleMap.get(s);return g?r-g.startTime>=this._throttleConfig.single.throttleTime?(g.count=1,g.startTime=r,!1):g.count>=this._throttleConfig.single.maxCount||(g.count++,!1):(this._singleThrottleMap.set(s,{count:1,startTime:r}),!1)}_shouldLog(s){return s>=this._logLevel&&this._logLevel!==IA.NONE}_shouldReport(s){return this._reportLevel.includes(qA[s])}_formatLog(s,r,g,u){const E=new Date,f=`${E.getHours()}:${E.getMinutes()}:${E.getSeconds()}:${E.getMilliseconds()}`,D=`<${IA[s]}>`;return Gt||Fi?[`${oA} [${f}] ${D} [${r}] ${g}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",oA,"",`[${f}] ${D} [${r}] ${g} params: ${_n(u)}`]}_log(s,r,g,u){if(this._shouldLog(s)){const E=this._formatLog(s,r,g,u);vA[s].apply(console,E)}if(this._shouldReport(s)){const E=this._getThrottleKey(r,g,u);this._checkThrottle(E)||this.createSSOLogData(Object.assign(Object.assign({message:g},u),{method:r})).end()}}_getThrottleKey(s,r,g){const u=`${s}${r}${_n(Object.assign(Object.assign({},g),{costTime:""}))}`,E=Fa(JSON.stringify(u));let f=4294967295;const{length:D}=E;for(let v=0;v>>=1:f=f>>>1^3988292384}return`${(4294967295^f)>>>0}`}reset(){console.log("SSO_LOG_MODULE.reset"),ws.removeTask(Nt),es.unSubscribeInnerEvent(Ke.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=qe,this._maxThreshold=100,this._waitingTime=Et,this._logQueue=[],this._logLevel=IA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const di=15e3,Bt="Channel",Jt="channel_schedule_task",$i="channel_reconnect_task",eo="connected",os="connecting",Ti="disconnected",on=1e3,wg="network_status_change",Er="activity_status_change",Mr="send_fail",js="reconnect_failed",Tl="socket_error",ns="socket_close";function uI(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function ec(s){return ec=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(r){return typeof r}:function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},ec(s)}function wc(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Tu,Na={exports:{}},Nl=(Tu||(Tu=1,function(s){s.exports=function r(g,u,E){function f(N,P){if(!u[N]){if(!g[N]){if(!P&&wc)return wc(N);if(D)return D(N,!0);var W=new Error("Cannot find module '"+N+"'");throw W.code="MODULE_NOT_FOUND",W}var nA=u[N]={exports:{}};g[N][0].call(nA.exports,function(EA){return f(g[N][1][EA]||EA)},nA,nA.exports,r,g,u,E)}return u[N].exports}for(var D=wc,v=0;v>>6:(EA<65536?nA[VA++]=224|EA>>>12:(nA[VA++]=240|EA>>>18,nA[VA++]=128|EA>>>12&63),nA[VA++]=128|EA>>>6&63),nA[VA++]=128|63&EA);return nA},u.buf2binstring=function(W){return P(W,W.length)},u.binstring2buf=function(W){for(var nA=new E.Buf8(W.length),EA=0,wA=nA.length;EA>10&1023,SA[wA++]=56320|1023&kA)}return P(SA,wA)},u.utf8border=function(W,nA){var EA;for((nA=nA||W.length)>W.length&&(nA=W.length),EA=nA-1;0<=EA&&(192&W[EA])==128;)EA--;return EA<0||EA===0?nA:EA+v[W[EA]]>nA?EA:nA}},{"./common":1}],3:[function(r,g,u){g.exports=function(E,f,D,v){for(var N=65535&E,P=E>>>16&65535,W=0;D!==0;){for(D-=W=2e3>>1:f>>>1;D[v]=f}return D}();g.exports=function(f,D,v,N){var P=E,W=N+v;f^=-1;for(var nA=N;nA>>8^P[255&(f^D[nA])];return-1^f}},{}],6:[function(r,g,u){g.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(r,g,u){g.exports=function(E,f){var D,v,N,P,W,nA,EA,wA,kA,VA,LA,SA,PA,zA,Ee,Ie,Li,Ui,Yt,Oi,Bn,Re,Mt,FA,ci;D=E.state,v=E.next_in,FA=E.input,N=v+(E.avail_in-5),P=E.next_out,ci=E.output,W=P-(f-E.avail_out),nA=P+(E.avail_out-257),EA=D.dmax,wA=D.wsize,kA=D.whave,VA=D.wnext,LA=D.window,SA=D.hold,PA=D.bits,zA=D.lencode,Ee=D.distcode,Ie=(1<>>=Yt=Ui>>>24,PA-=Yt,(Yt=Ui>>>16&255)==0)ci[P++]=65535&Ui;else{if(!(16&Yt)){if(!(64&Yt)){Ui=zA[(65535&Ui)+(SA&(1<>>=Yt,PA-=Yt),PA<15&&(SA+=FA[v++]<>>=Yt=Ui>>>24,PA-=Yt,!(16&(Yt=Ui>>>16&255))){if(!(64&Yt)){Ui=Ee[(65535&Ui)+(SA&(1<>>=Yt,PA-=Yt,(Yt=P-W)>3,SA&=(1<<(PA-=Oi<<3))-1,E.next_in=v,E.next_out=P,E.avail_in=v>>24&255)+(Re>>>8&65280)+((65280&Re)<<8)+((255&Re)<<24)}function SA(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new E.Buf16(320),this.work=new E.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function PA(Re){var Mt;return Re&&Re.state?(Mt=Re.state,Re.total_in=Re.total_out=Mt.total=0,Re.msg="",Mt.wrap&&(Re.adler=1&Mt.wrap),Mt.mode=wA,Mt.last=0,Mt.havedict=0,Mt.dmax=32768,Mt.head=null,Mt.hold=0,Mt.bits=0,Mt.lencode=Mt.lendyn=new E.Buf32(kA),Mt.distcode=Mt.distdyn=new E.Buf32(VA),Mt.sane=1,Mt.back=-1,nA):EA}function zA(Re){var Mt;return Re&&Re.state?((Mt=Re.state).wsize=0,Mt.whave=0,Mt.wnext=0,PA(Re)):EA}function Ee(Re,Mt){var FA,ci;return Re&&Re.state?(ci=Re.state,Mt<0?(FA=0,Mt=-Mt):(FA=1+(Mt>>4),Mt<48&&(Mt&=15)),Mt&&(Mt<8||15=Pi.wsize?(E.arraySet(Pi.window,Mt,FA-Pi.wsize,Pi.wsize,0),Pi.wnext=0,Pi.whave=Pi.wsize):(ci<(xn=Pi.wsize-Pi.wnext)&&(xn=ci),E.arraySet(Pi.window,Mt,FA-ci,xn,Pi.wnext),(ci-=xn)?(E.arraySet(Pi.window,Mt,FA-ci,ci,0),Pi.wnext=ci,Pi.whave=Pi.wsize):(Pi.wnext+=xn,Pi.wnext===Pi.wsize&&(Pi.wnext=0),Pi.whave>>8&255,FA.check=D(FA.check,Bg,2,0),Ft=Ut=0,FA.mode=2;break}if(FA.flags=0,FA.head&&(FA.head.done=!1),!(1&FA.wrap)||(((255&Ut)<<8)+(Ut>>8))%31){Re.msg="incorrect header check",FA.mode=30;break}if((15&Ut)!=8){Re.msg="unknown compression method",FA.mode=30;break}if(Ft-=4,ja=8+(15&(Ut>>>=4)),FA.wbits===0)FA.wbits=ja;else if(ja>FA.wbits){Re.msg="invalid window size",FA.mode=30;break}FA.dmax=1<>8&1),512&FA.flags&&(Bg[0]=255&Ut,Bg[1]=Ut>>>8&255,FA.check=D(FA.check,Bg,2,0)),Ft=Ut=0,FA.mode=3;case 3:for(;Ft<32;){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>>8&255,Bg[2]=Ut>>>16&255,Bg[3]=Ut>>>24&255,FA.check=D(FA.check,Bg,4,0)),Ft=Ut=0,FA.mode=4;case 4:for(;Ft<16;){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>8),512&FA.flags&&(Bg[0]=255&Ut,Bg[1]=Ut>>>8&255,FA.check=D(FA.check,Bg,2,0)),Ft=Ut=0,FA.mode=5;case 5:if(1024&FA.flags){for(;Ft<16;){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>>8&255,FA.check=D(FA.check,Bg,2,0)),Ft=Ut=0}else FA.head&&(FA.head.extra=null);FA.mode=6;case 6:if(1024&FA.flags&&(ji<(Do=FA.length)&&(Do=ji),Do&&(FA.head&&(ja=FA.head.extra_len-FA.length,FA.head.extra||(FA.head.extra=new Array(FA.head.extra_len)),E.arraySet(FA.head.extra,ci,Pi,Do,ja)),512&FA.flags&&(FA.check=D(FA.check,ci,Do,Pi)),ji-=Do,Pi+=Do,FA.length-=Do),FA.length))break A;FA.length=0,FA.mode=7;case 7:if(2048&FA.flags){if(ji===0)break A;for(Do=0;ja=ci[Pi+Do++],FA.head&&ja&&FA.length<65536&&(FA.head.name+=String.fromCharCode(ja)),ja&&Do>9&1,FA.head.done=!0),Re.adler=FA.check=0,FA.mode=12;break;case 10:for(;Ft<32;){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>>=7&Ft,Ft-=7&Ft,FA.mode=27;break}for(;Ft<3;){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>>=1)){case 0:FA.mode=14;break;case 1:if(Oi(FA),FA.mode=20,Mt!==6)break;Ut>>>=2,Ft-=2;break A;case 2:FA.mode=17;break;case 3:Re.msg="invalid block type",FA.mode=30}Ut>>>=2,Ft-=2;break;case 14:for(Ut>>>=7&Ft,Ft-=7&Ft;Ft<32;){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>>16^65535)){Re.msg="invalid stored block lengths",FA.mode=30;break}if(FA.length=65535&Ut,Ft=Ut=0,FA.mode=15,Mt===6)break A;case 15:FA.mode=16;case 16:if(Do=FA.length){if(ji>>=5,Ft-=5,FA.ndist=1+(31&Ut),Ut>>>=5,Ft-=5,FA.ncode=4+(15&Ut),Ut>>>=4,Ft-=4,286>>=3,Ft-=3}for(;FA.have<19;)FA.lens[CS[FA.have++]]=0;if(FA.lencode=FA.lendyn,FA.lenbits=7,kI={bits:FA.lenbits},Kl=N(0,FA.lens,0,19,FA.lencode,0,FA.work,kI),FA.lenbits=kI.bits,Kl){Re.msg="invalid code lengths set",FA.mode=30;break}FA.have=0,FA.mode=19;case 19:for(;FA.have>>16&255,bI=65535&Jg,!((Gr=Jg>>>24)<=Ft);){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>>=Gr,Ft-=Gr,FA.lens[FA.have++]=bI;else{if(bI===16){for(nE=Gr+2;Ft>>=Gr,Ft-=Gr,FA.have===0){Re.msg="invalid bit length repeat",FA.mode=30;break}ja=FA.lens[FA.have-1],Do=3+(3&Ut),Ut>>>=2,Ft-=2}else if(bI===17){for(nE=Gr+3;Ft>>=Gr)),Ut>>>=3,Ft-=3}else{for(nE=Gr+7;Ft>>=Gr)),Ut>>>=7,Ft-=7}if(FA.have+Do>FA.nlen+FA.ndist){Re.msg="invalid bit length repeat",FA.mode=30;break}for(;Do--;)FA.lens[FA.have++]=ja}}if(FA.mode===30)break;if(FA.lens[256]===0){Re.msg="invalid code -- missing end-of-block",FA.mode=30;break}if(FA.lenbits=9,kI={bits:FA.lenbits},Kl=N(P,FA.lens,0,FA.nlen,FA.lencode,0,FA.work,kI),FA.lenbits=kI.bits,Kl){Re.msg="invalid literal/lengths set",FA.mode=30;break}if(FA.distbits=6,FA.distcode=FA.distdyn,kI={bits:FA.distbits},Kl=N(W,FA.lens,FA.nlen,FA.ndist,FA.distcode,0,FA.work,kI),FA.distbits=kI.bits,Kl){Re.msg="invalid distances set",FA.mode=30;break}if(FA.mode=20,Mt===6)break A;case 20:FA.mode=21;case 21:if(6<=ji&&258<=Br){Re.next_out=Vr,Re.avail_out=Br,Re.next_in=Pi,Re.avail_in=ji,FA.hold=Ut,FA.bits=Ft,v(Re,hs),Vr=Re.next_out,xn=Re.output,Br=Re.avail_out,Pi=Re.next_in,ci=Re.input,ji=Re.avail_in,Ut=FA.hold,Ft=FA.bits,FA.mode===12&&(FA.back=-1);break}for(FA.back=0;Hg=(Jg=FA.lencode[Ut&(1<>>16&255,bI=65535&Jg,!((Gr=Jg>>>24)<=Ft);){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>Ec)])>>>16&255,bI=65535&Jg,!(Ec+(Gr=Jg>>>24)<=Ft);){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>>=Ec,Ft-=Ec,FA.back+=Ec}if(Ut>>>=Gr,Ft-=Gr,FA.back+=Gr,FA.length=bI,Hg===0){FA.mode=26;break}if(32&Hg){FA.back=-1,FA.mode=12;break}if(64&Hg){Re.msg="invalid literal/length code",FA.mode=30;break}FA.extra=15&Hg,FA.mode=22;case 22:if(FA.extra){for(nE=FA.extra;Ft>>=FA.extra,Ft-=FA.extra,FA.back+=FA.extra}FA.was=FA.length,FA.mode=23;case 23:for(;Hg=(Jg=FA.distcode[Ut&(1<>>16&255,bI=65535&Jg,!((Gr=Jg>>>24)<=Ft);){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>Ec)])>>>16&255,bI=65535&Jg,!(Ec+(Gr=Jg>>>24)<=Ft);){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>>=Ec,Ft-=Ec,FA.back+=Ec}if(Ut>>>=Gr,Ft-=Gr,FA.back+=Gr,64&Hg){Re.msg="invalid distance code",FA.mode=30;break}FA.offset=bI,FA.extra=15&Hg,FA.mode=24;case 24:if(FA.extra){for(nE=FA.extra;Ft>>=FA.extra,Ft-=FA.extra,FA.back+=FA.extra}if(FA.offset>FA.dmax){Re.msg="invalid distance too far back",FA.mode=30;break}FA.mode=25;case 25:if(Br===0)break A;if(Do=hs-Br,FA.offset>Do){if((Do=FA.offset-Do)>FA.whave&&FA.sane){Re.msg="invalid distance too far back",FA.mode=30;break}Do>FA.wnext?(Do-=FA.wnext,Bl=FA.wsize-Do):Bl=FA.wnext-Do,Do>FA.length&&(Do=FA.length),GC=FA.window}else GC=xn,Bl=Vr-FA.offset,Do=FA.length;for(BrLi?(Yt=Bl[GC+VA[Mt]],Oi=Ft[oE+VA[Mt]]):(Yt=96,Oi=0),SA=1<>Vr)+(PA-=SA)]=Ui<<24|Yt<<16|Oi,PA!==0;);for(SA=1<>=1;if(SA!==0?(Ut&=SA-1,Ut+=SA):Ut=0,Mt++,--hs[Re]==0){if(Re===ci)break;Re=W[nA+VA[Mt]]}if(xn{const v=new Uint8Array(D).slice(4);let N;try{N=Nl.inflate(v,{to:"string"})}catch(P){console.error("inflate error",P)}return N})(s.data):function(D){const v=new Uint8Array(D);let N="",P=0;const{length:W}=v;for(;P0)for(let kA=0;kA{var u;const{uplinkData:E,canResend:f,resolve:D,reject:v,timeout:N}=r;if(f){this._pendingRequests.set(g,{resolve:D,reject:v,timestamp:Date.now(),uplinkData:E,timeout:N,canResend:f});const P=this._isBinarySupported?Fa(E).buffer:E;(u=this._socketAdapter)===null||u===void 0||u.send(P)}else this._pendingRequests.delete(g)})}_onConnect(s){const{socketId:r,event:g={}}=s||{};this._connectionId=r,this._connectionEstablishedTime=Date.now();const u=Date.now()-this._connectionStartTime,E=`${Bt}.onConnect cost:${u} ms. socketID:${r} res:${JSON.stringify(g)}`;if(this._ssoLog({method:"onConnect",message:E}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const f=`${Bt}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:f}),es.emitInnerEvent(Ke.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:eo,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(s){const r=pa({servcmd:"openim.ws_msg_push_ack",data:{SessionData:s}});this.sendPacket(r)}_executeScheduledTaskIfReady(){return mA(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var s;return((s=this._socketAdapter)===null||s===void 0?void 0:s.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return mA(this,void 0,void 0,function*(){var s;const r=pa({servcmd:"heartbeat.alive",data:{}});try{const g=`${r.head.seq}${r.head.servcmd}`;yield this.sendPacket(r,{requestId:g,timeout:3e3})}catch(g){const u=(s=ro.get("netWorkMonitor"))===null||s===void 0?void 0:s.isNetworkOnline,E=`${Bt}.sendHeartbeat failed. isNetWorkOnline:${u} error: ${_n(g)}`;this._ssoLog({method:"sendHeartbeatError",message:E}),this._handleConnectStateChange({state:Ti,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return mA(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=ao?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(s){const r=`${Bt}.networkStatusChange ${JSON.stringify(s)}`;this._ssoLog({method:"networkStatusChange",message:r});const{isNetworkOnline:g,networkType:u}=s;g&&u!=="none"?this._handleConnectStateChange({state:eo,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:wg}):this._handleConnectStateChange({state:Ti,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:wg})}isPrivateNetWork(){const s=ro.get("instance")||{};return s.proxyServer&&!s.fileDownloadProxy}_handleConnectStateChange(s){const{state:r,shouldAttemptReconnect:g,shouldEmitEvent:u,reason:E}=s,f=`${Bt}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${g} shouldEmitEvent: ${u} reason: ${E}`;this._currentConnectState!==r&&(this._ssoLog({method:"handleConnectStateChange",message:f}),u&&(Kt.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${r}`),es.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:r}}),this._currentConnectState=r,r===Ti&&es.emitInnerEvent(Ke.SOCKET_DISCONNECTED)),g&&(this._resetReconnectDelay(),ws.addTask({id:$i,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(s){var r,g;const u=(g=(r=this._socketAdapter)===null||r===void 0?void 0:r._ws)===null||g===void 0?void 0:g.readyState,E=`${Bt}.activityStatusChange ${JSON.stringify(s)} readyState: ${u}`;Kt.debug("activityStatusChange",E),u===3&&this._handleConnectStateChange({state:Ti,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Er})}_resetReconnectDelay(){var s;Kt.debug(`${Bt}._resetReconnectDelay`),ws.removeTask($i);const r=(s=ro.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=r?on:1e3}_scheduleReconnectWithBackoff(){var s;const r=(s=ro.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=r?Math.min(5e3,Math.max(on,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const g=new Date().toTimeString().slice(0,8),u=`${Bt}.scheduleReconnectWithBackoff timeStr: ${g} intendedDelay: ${this._intendedDelay}`;Kt.debug(u),this.reconnect(),ws.updateTaskInterval($i,this._intendedDelay)}_ssoLog(s){const{method:r,message:g}=s;Kt.info(r,g)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(s){mA(this,void 0,void 0,function*(){const r=s.split("/")[2];if(!r.startsWith("ws"))return;const g=`https://${r}/v3/netcheck/getconninfo?${s.slice(s.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield qi({method:"GET",url:g,data:{}})}catch(u){Kt.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${u.message}`)}})}(this._url),function(s){mA(this,void 0,void 0,function*(){const r=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${s.slice(s.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield qi({method:"GET",url:r,data:{}})}catch(g){Kt.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${g.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[s,r]of this._pendingRequests.entries()){const{reject:g,timestamp:u,timeout:E}=r;Date.now()-u>=E&&(this._pendingRequests.delete(s),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),g({errorCode:Zs,errorInfo:"NETWORK_TIMEOUT",data:{requestId:s}}))}}_updateIsBinarySupported(){var s;if(!((s=ro.get("instance"))===null||s===void 0)&&s.devMode)return void(this._isBinarySupported=!1);const r=Vo();if((ii||Xe&&r==="windows"||wn)&&(this._isBinarySupported=!1),ao){const{uniRuntimeVersion:g=""}=no.getSystemInfoSync();(function(u){const E=u.split(".").map(Number),[f=0,D=0,v=0]=E;return f>2||!(f<2)&&(D>2||!(D<2)&&v>=6)})(g)||(this._isBinarySupported=!1)}}_isCompressedData(s){const r=new Uint8Array(s);return r[0]===67&&r[1]===79&&r[2]===77&&r[3]===80}};const Se={init:function(s){ro.set("instance",s),ve.init()},destroy:function(){ve.dispose(),ro.clear(),ws.dispose()},notificationCenter:es,channel:ve,store:ro,ssoLog:Kt,utils:$a,common:RA,constants:we},_g=s=>typeof s=="function";function cg(s,r,g){const u=g||[];if(!s||!r)return!1;const E=Object.keys(s).filter(D=>!u.includes(D)),f=Object.keys(r).filter(D=>!u.includes(D));return E.length===f.length&&E.every(D=>!!r.hasOwnProperty(D)&&(typeof s[D]=="object"&&s[D]!==null?cg(s[D],r[D],g):s[D]===r[D]))}var Tg;(function(s){s.SDK_READY="sdkStateReady",s.SDK_NOT_READY="sdkStateNotReady",s.SDK_DESTROY="sdkDestroy",s.MESSAGE_RECEIVED="onMessageReceived",s.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",s.MESSAGE_MODIFIED="onMessageModified",s.MESSAGE_REVOKED="onMessageRevoked",s.MESSAGE_READ_BY_PEER="onMessageReadByPeer",s.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",s.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",s.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",s.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",s.CONVERSATION_LIST_UPDATED="onConversationListUpdated",s.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",s.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",s.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",s.GROUP_LIST_UPDATED="onGroupListUpdated",s.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",s.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",s.TOPIC_CREATED="onTopicCreated",s.TOPIC_DELETED="onTopicDeleted",s.TOPIC_UPDATED="onTopicUpdated",s.PROFILE_UPDATED="onProfileUpdated",s.USER_STATUS_UPDATED="onUserStatusUpdated",s.BLACKLIST_UPDATED="blacklistUpdated",s.FRIEND_LIST_UPDATED="onFriendListUpdated",s.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",s.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",s.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",s.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",s.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",s.KICKED_OUT="kickedOut",s.ERROR="error",s.NET_STATE_CHANGE="netStateChange",s.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",s.SERVER_CONFIG_UPDATED="onServerConfigUpdated",s.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated",s.WEB_PUSH_MESSAGE_RECEIVED="onWebPushMessageReceived",s.GROUP_ONLINE_MEMBER_COUNT_CHANGED="onGroupOnlineMemberCountChanged",s.RICH_STATUS_CHANGED="onRichStatusChanged"})(Tg||(Tg={}));var Ts,Rr=Tg;(function(s){s.LOGOUT="logout",s.DESTROY="destroy",s.CLOUD_CONFIG_UPDATE="cloud_config_update",s.PROFILE_UPDATE="profile_updated",s.ERROR="error",s.RECONNECTED="reconnected",s.FORCE_OFFLINE="im_open_status.stat_forceoffline",s.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",s.OVERLOAD_PUSH="OverLoadPush.notify2",s.NEW_MESSAGE="new_message",s.MESSAGE_PUSH="im_open_push.msg_push",s.MESSAGE_DELETED="message_deleted",s.MESSAGE_REVOKED="message_revoked",s.MESSAGE_MODIFIED="message_modified",s.SOCKET_DISCONNECTED="socket_disconnected",s.CONVERSATION_UPDATED="conversation_updated",s.TOPIC_MESSAGE_DELETED="topic_message_deleted",s.TOPIC_MESSAGE_REVOKED="topic_message_revoked",s.TOPIC_MESSAGE_MODIFIED="topic_message_modified",s.TOPIC_NEW_MESSAGE="topic_new_message",s.QUALITY_STAT="quality_stat",s.SYNC_CONVERSATION_LIST="sync_conversation_list",s.HISTORY_MESSAGE_FETCHED="history_message_fetched"})(Ts||(Ts={}));var Ci,lo=Ts;(function(s){s.NEW_INVITATION_RECEIVED="newInvitationReceived",s.INVITEE_ACCEPTED="ts_invitee_accepted",s.INVITEE_REJECTED="ts_invitee_rejected",s.INVITATION_CANCELLED="ts_invitation_cancelled",s.INVITATION_TIMEOUT="ts_invitation_timeout",s.INVITATION_MODIFIED="ts_invitation_modified"})(Ci||(Ci={}));var Xc=Ci;const tc=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),Ng={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem",MSG_STREAM:"TIMStreamElem"};var qr;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(qr||(qr={}));const _c={modify:lo.MESSAGE_MODIFIED,delete:lo.MESSAGE_DELETED,revoke:lo.MESSAGE_REVOKED};var $c;(function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"})($c||($c={}));const lg=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Ng),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:qr,Direction:$c}),Nu={[_c.modify]:lo.TOPIC_MESSAGE_MODIFIED,[_c.delete]:lo.TOPIC_MESSAGE_DELETED,[_c.revoke]:lo.TOPIC_MESSAGE_REVOKED},ME={GENDER_UNKNOWN:"Gender_Type_Unknown",GENDER_FEMALE:"Gender_Type_Female",GENDER_MALE:"Gender_Type_Male",USER_STATUS_UNKNOWN:0,USER_STATUS_ONLINE:1,USER_STATUS_OFFLINE:2,USER_STATUS_UNLOGINED:3,USER_NOT_FOUND:"@TLS#NOT_FOUND"},Gg=Object.assign({},ME),Pa={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},Tc=Object.assign(Object.assign(Object.assign(Object.assign({},Pa),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),RE=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),xa={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},ga={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},bg={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},EI=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},xa),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),{GROUP_ID_PREFIX:ga,GROUP_TIPS_OPERATION_TYPE:bg}),Sn={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},Po=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},tc),lg),Gg),Tc),RE),EI),Sn),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),ma={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},dr={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},jt={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message",RECEIVE_GROUP_TIPS_NOTIFICATION:"receive-group-tips-notification"},Xt={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover",HANDLE_GROUP_TIPS_NOTIFICATION:"handle-group-tips-notification",C2C_HISTORY_MESSAGE_RECOVER:"c2c-history-message-recover",FRIEND_APPLICATION_LIST_RECOVER:"friend-application-list-recover",EMIT_GROUP_TIPS_EVENT:"emit-group-tips-event",STREAM_MESSAGE_RECOVER:"stream-message-recover"},kg={[jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:Xt.USER_STATUS_UPDATE},{stepId:Xt.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:Xt.UNREAD_MESSAGE_SYNC,dependency:Xt.C2C_HISTORY_MESSAGE_RECOVER},{stepId:Xt.CONVERSATION_RECOVER},{stepId:Xt.HISTORY_MESSAGE_RECOVER,dependency:Xt.CONVERSATION_RECOVER},{stepId:Xt.BLACKLIST_RECOVER},{stepId:Xt.FRIEND_RECOVER},{stepId:Xt.FRIEND_APPLICATION_LIST_RECOVER},{stepId:Xt.GROUP_REVOKED_NOTICE_RECOVER,dependency:Xt.HISTORY_MESSAGE_RECOVER},{stepId:Xt.GROUP_TIPS_RECOVER,dependency:Xt.HISTORY_MESSAGE_RECOVER},{stepId:Xt.TOPIC_REQUEST_INFO_RESET},{stepId:Xt.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:Xt.UNREAD_MESSAGE_SYNC},{stepId:Xt.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:Xt.UNREAD_MESSAGE_SYNC},{stepId:Xt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Xt.UNREAD_MESSAGE_SYNC,Xt.CONVERSATION_RECOVER]},{stepId:Xt.EMIT_C2C_MESSAGE_EVENT,dependency:[Xt.UNREAD_MESSAGE_SYNC,Xt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:Xt.C2C_HISTORY_MESSAGE_RECOVER,dependency:Xt.CONVERSATION_RECOVER},{stepId:Xt.STREAM_MESSAGE_RECOVER}],[jt.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:Xt.COMMERCIAL_CONFIG_UPDATE},{stepId:Xt.CLOUD_CONFIG_SYNC},{stepId:Xt.USER_PROFILE_SYNC},{stepId:Xt.UNREAD_MESSAGE_SYNC},{stepId:Xt.FRIEND_AND_BLACKLIST_SYNC},{stepId:Xt.GROUP_LIST_SYNC},{stepId:Xt.CONVERSATION_LIST_SYNC},{stepId:Xt.SIGNALING_MESSAGE_RECOVER,dependency:Xt.UNREAD_MESSAGE_SYNC},{stepId:Xt.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[Xt.UNREAD_MESSAGE_SYNC]},{stepId:Xt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Xt.UNREAD_MESSAGE_SYNC,Xt.CONVERSATION_LIST_SYNC]},{stepId:Xt.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[Xt.GROUP_LIST_SYNC,Xt.CONVERSATION_LIST_SYNC]},{stepId:Xt.CONVERSATION_GROUP_LIST_SYNC},{stepId:Xt.CONVERSATION_GROUP_UPDATE,dependency:[Xt.CONVERSATION_LIST_SYNC,Xt.CONVERSATION_GROUP_LIST_SYNC]},{stepId:Xt.QUALITY_REPORT}],[jt.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:Xt.HANDLE_C2C_NEW_MESSAGE},{stepId:Xt.UNREAD_MESSAGE_SYNC},{stepId:Xt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Xt.HANDLE_C2C_NEW_MESSAGE},{stepId:Xt.EMIT_C2C_MESSAGE_EVENT,dependency:[Xt.HANDLE_C2C_NEW_MESSAGE,Xt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:Xt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Xt.UNREAD_MESSAGE_SYNC]}],[jt.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:Xt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Xt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Xt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Xt.UPDATE_GROUP_NEXT_SEQUENCE,dependency:Xt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Xt.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:Xt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Xt.EMIT_GROUP_MESSAGE_EVENT,dependency:[Xt.HANDLE_GROUP_NEW_MESSAGE,Xt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[jt.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:Xt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Xt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Xt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Xt.EMIT_GROUP_TIPS_EVENT,dependency:[Xt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,Xt.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},dI={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},Cr={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},zI=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","sendMessageReadReceipt","getMessageReadReceiptList","getGroupMessageReadMemberList","createMergerMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var Ag=Object.freeze({__proto__:null,ERROR_CODE:ma,InnerEvent:lo,NEED_LOG_API:zI,OuterConstant:Po,OuterEvent:Rr,PUSH:Sn,QUALITY_METRICS:dI,SDK_EDITION:dr,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:Cr,SignalingEvent:Xc,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:kg,WORKFLOW_NAME:jt,WORKFLOW_STEP:Xt}),ca,ps,Ns;(function(s){s[s.USER_INITIATED=0]="USER_INITIATED",s[s.KICKED_OUT=1]="KICKED_OUT"})(ca||(ca={})),function(s){s[s.multipleAccount=1]="multipleAccount",s[s.multipleDevice=2]="multipleDevice",s[s.restApi=3]="restApi"}(ps||(ps={})),function(s){s[s.multipleDevice=3002]="multipleDevice",s[s.multipleAccount=3003]="multipleAccount",s[s.usersigExpired=70001]="usersigExpired",s[s.restApi=20002]="restApi"}(Ns||(Ns={}));const Gu={[ps.multipleAccount]:"multipleAccount",[ps.multipleDevice]:"multipleDevice",[ps.restApi]:"REST_API_Kick",[Ns.multipleAccount]:"multipleAccount",[Ns.multipleDevice]:"multipleDevice",[Ns.restApi]:"REST_API_Kick",[Ns.usersigExpired]:"userSigExpired"},Lg="login_online_presence_task",{ERROR:Ya,DESTROY:Al,FORCE_OFFLINE:ZI}=lo,{KICKED_OUT_MULT_ACCOUNT:wE,KICKED_OUT_MULT_DEVICE:CI,KICKED_OUT_REST_API:bu,ACCOUNT_A2KEY_EXPIRED:Gl,MSG_A2KEY_EXPIRED:Nc}=ma;class ku{init(){const{notificationCenter:r}=Se;r.subscribeInnerEvent(ZI,this._handleForceOfflineFromServerPush,this),r.subscribeInnerEvent(Ya,Nc,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),r.subscribeInnerEvent(Ya,Gl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),r.subscribeInnerEvent(Ya,wE,this._handleForceOfflineFromResponse,this),r.subscribeInnerEvent(Ya,CI,this._handleForceOfflineFromResponse,this),r.subscribeInnerEvent(Ya,bu,this._handleForceOfflineFromResponse,this),r.subscribeInnerEvent(Al,this._dispose,this)}_handleForceOfflineFromServerPush(r){var g;if(((g=Se.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)===!0){const{EventArray:u=[]}=r?.body||{};this._extractKickedOutMessages(u).forEach(E=>{const{KickoutMsgNotify:{KickType:f,NewInstInfo:D,Instid:v}}=E;this._isCurrentInstanceKickedOut(v)&&this._processKickedOutReasonInfo({kickedOutReasonCode:f,newInstanceInfo:D})})}}_extractKickedOutMessages(r){return r.reduce((g,u)=>[...g,...u.C2cNotifyMsgArray||[]],[]).filter(g=>{var u;return this._isKickedOut((u=g?.KickoutMsgNotify)===null||u===void 0?void 0:u.KickType)})}_handleForceOfflineFromResponse(r){const{errorCode:g}=r;this._processKickedOutReasonInfo({kickedOutReasonCode:g})}_processKickedOutReasonInfo(r){return mA(this,void 0,void 0,function*(){const{kickedOutReasonCode:g}=r,{ssoLog:u,utils:{safeStringify:E}}=Se;try{this._logKickedOutEvent(r),this._shouldLogoutAfterKickedOut(g)?yield Se.login.loginAction.logout(ca.KICKED_OUT):Se.login.loginAction.handleLogoutCompleted()}catch(f){u.debug("_processKickedOutReasonInfo",` fail ${E(f)}`)}finally{Se.notificationCenter.emitOuterEvent(Rr.KICKED_OUT,{data:{type:Gu[g]},name:Rr.KICKED_OUT})}})}_logKickedOutEvent(r){const{kickedOutReasonCode:g,newInstanceInfo:u={}}=r,E=`type:${Gu[g]} newInstanceInfo: ${JSON.stringify(u)}`;Se.ssoLog.warn("kickedOut",E)}_isKickedOut(r){return[ps.multipleAccount,ps.multipleDevice,ps.restApi].includes(r)}_isChatLoginEvent(r){const{requestHead:g}=r||{};return g?.idtype!==1}_shouldLogoutAfterKickedOut(r){return![Ns.usersigExpired,ps.restApi].includes(r)}_isCurrentInstanceKickedOut(r){const{isLoggedIn:g,statusInstanceId:u}=Se.store.get("login")||{};return g===!0&&r===u}_dispose(){const{notificationCenter:r}=Se;r.unSubscribeInnerEvent(ZI,this._handleForceOfflineFromServerPush,this),r.unSubscribeInnerEvent(Ya,Gl,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Ya,Nc,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Ya,wE,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Ya,CI,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Ya,bu,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Al,this._dispose,this)}}function Lu(s){return mA(this,void 0,void 0,function*(){const r="im_open_status.wslogin",g=Se.common.generateProtocolData({servcmd:r,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:s}}),u=`${g.head.seq}${r}`,E=yield Se.channel.sendPacket(g,{timeout:9e4,requestId:u});if(E){const{HelloInterval:f,InstId:D,TinyId:v,TimeStamp:N,CustomStatus:P,PurchaseBits:W,A2Key:nA,RichMsgAuthKey:EA,ErrorCode:wA,ErrorInfo:kA,ActionStatus:VA}=E;return{helloInterval:f,instanceID:D,tinyID:v,timeStamp:N,customStatus:P,purchaseBits:W,a2Key:nA,authKey:EA,errorCode:wA,errorInfo:kA,actionStatus:VA}}})}function bl(){const{store:s}=Se;return Qa(s.get("instance").sdkAppId)!==Ye.CHINA}function dn(s){var r;try{const g=ro.getStorage("errorMessage");if(!s||!g)return"";const u=((r=JSON.parse(g))===null||r===void 0?void 0:r.errorMessage)||{},{code:E,replacement1:f="",replacement2:D=""}=s;if(!E)return"";const v=bl()?`${E}_en`:`${E}_cn`;let N=u[u[v]?v:E]||"";return N&&(f&&(N=N.replace("$replacement1",f)),D&&(N=N.replace("$replacement2",D))),N}catch(g){return console.warn("Error parsing stored error messages:",g),""}}class hn extends Error{constructor(r={}){r.code=r.code||r.errorCode;let{functionName:g="Unknown",code:u,message:E="",data:f="",moreMessage:D="",errorMessage:v=""}=r;v=(u?dn(r):"")||v||E;let N=u?`${g} failed. error: {"message": ${v}, "code": ${u}}`:`${g} failed. error: {"message": ${v}}`;N=`${N} ${D}`,super(),this.code=u,this.errorCode=u,this.errorMessage=v,this.message=N,this.data=f}}function dd(s,r){var g;if(s&&((g=Se.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)!==!0)throw new hn({code:ma.USER_NOT_LOGGED_IN,functionName:r})}function hI(s,r,g){if(Array.isArray(s))for(let u=0;u{return P===(W=u,Object.prototype.toString.call(W).match(/^\[object (.*)\]$/)[1].toLowerCase());var W})){for(let W=0;W{const{interceptor:E,context:f}=u;E.apply(f,[g])})}(s)}function Gc(s,r){_E.push({interceptor:s,context:r})}function el(s){const{params:r,auth:g}=s;r&&typeof r=="object"&&Object.assign(kl,r),g&&typeof g=="object"&&Object.assign(Cd,g)}function us(s){return Se.store.get("commercialConfig").get(s)}class Pn{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(r,g)=>{const u=Date.now();g?(this._stepStartTimes.set(`${r}-${g}`,u),Se.ssoLog.debug("_executeWorkflowStep",`[Workflow ${r}] Step ${g} started at ${new Date(u).toISOString()}`)):(this._workflowStartTimes.set(r,u),Se.ssoLog.debug("_executeWorkflowStep",`[Workflow ${r}] started at ${new Date(u).toISOString()}`))},success:(r,g)=>{const u=Date.now();if(g){const E=this._stepStartTimes.get(`${r}-${g}`),f=E?u-E:0;this._stepStartTimes.delete(`${r}-${g}`),Se.ssoLog.debug("_executeWorkflowStep",`[Workflow ${r}] Step ${g} completed successfully at ${new Date(u).toISOString()} (${f}ms)`)}else{const E=this._workflowStartTimes.get(r),f=E?u-E:0;this._workflowStartTimes.delete(r),Se.ssoLog.debug("_executeWorkflowStep",`[Workflow ${r}] completed successfully at ${new Date(u).toISOString()} (${f}ms)`)}},error:(r,g,u)=>{const{ssoLog:E,utils:{safeStringify:f}}=Se,D=Date.now();if(g){const v=this._stepStartTimes.get(`${r}-${g}`),N=v?D-v:0;this._stepStartTimes.delete(`${r}-${g}`),E.error("_executeWorkflowStep",`[Workflow ${r}] Step ${g} failed at ${new Date(D).toISOString()} (${N}ms) ${f(u)}`,{error:u})}else{const v=this._workflowStartTimes.get(r),N=v?D-v:0;this._workflowStartTimes.delete(r),E.error("_executeWorkflowStep",`[Workflow ${r}] failed at ${new Date(D).toISOString()} (${N}ms) ${f(u)}`,{error:u})}}}}static getInstance(){return Pn._instance||(Pn._instance=new Pn),Pn._instance}static setInstance(r){Pn._instance=r}init(){this._initializeWorkflows()}registerWorkflowStep(r,g,u,E){if(!this._handlers.has(r))return void Se.ssoLog.debug("registerWorkflowStep",`Workflow '${r}' not defined in core`);if(!kg[r].find(D=>D.stepId===g))return void Se.ssoLog.debug("registerWorkflowStep",`Step '${g}' not defined in workflow '${r}'`);const f=this._handlers.get(r);f.has(g)||f.set(g,E?u.bind(E):u)}executeWorkflow(r,g){return mA(this,void 0,void 0,function*(){if(!this._validateWorkflow(r))return;Se.ssoLog.debug("executeWorkflow",`[Workflow ${r}] Started execution at ${new Date().toISOString()}`);const u=kg[r],E={},f={cancelled:!1};this._activeWorkflows.set(r,{cancelToken:f});try{const D=new Map;u.forEach(N=>{D.set(N.stepId,N)});const v={workflowName:r,pendingSteps:new Set(u.map(N=>N.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:D,stepResults:E,data:g,cancelToken:f};yield new Promise((N,P)=>{const W=()=>{if(f.cancelled)return void N();this._getExecutableSteps({pendingSteps:v.pendingSteps,completedSteps:v.completedSteps,stepMap:v.stepMap,workflowName:r}).filter(nA=>!v.runningSteps.has(nA)).forEach(nA=>{v.completedSteps.has(nA)||v.runningSteps.has(nA)||this._executeWorkflowStep(nA,v,{onComplete:()=>{if(v.pendingSteps.size===0)return void N();this._getExecutableSteps({pendingSteps:v.pendingSteps,completedSteps:v.completedSteps,stepMap:v.stepMap,workflowName:r}).filter(EA=>!v.runningSteps.has(EA)).length===0&&v.runningSteps.size===0&&(Se.ssoLog.debug("executeWorkflow",`Workflow ${r} completed with some steps skipped due to dependency failures`),N())},onError:P,onStepComplete:W})})};W()}),Se.ssoLog.debug("executeWorkflow",`[Workflow ${r}] Completed execution at ${new Date().toISOString()}`)}catch(D){Se.ssoLog.error("executeWorkflow",`[Workflow ${r}] Failed execution at ${new Date().toISOString()}`,{error:D})}finally{this._activeWorkflows.delete(r)}})}_executeWorkflowStep(r,g,u){return mA(this,void 0,void 0,function*(){const{workflowName:E,runningSteps:f,stepMap:D,stepResults:v,data:N}=g;f.add(r),this._logWorkflowExecution(E,r,"start");try{const P=D.get(r);let W=null;P?.dependency&&(c(P.dependency)?W=v[P.dependency]:Array.isArray(P.dependency)&&(W={},P.dependency.forEach(EA=>{W[EA]=v[EA]})));const nA=this._handlers.get(E).get(r);if(nA){const EA=yield Promise.resolve(nA({data:N,result:W}));v[r]=EA,this._logWorkflowExecution(E,r,"success")}g.completedSteps.add(r)}catch(P){const W=`[Workflow].${E}.${r}`,{errorCode:nA,errorInfo:EA=`${W} failed`}=P||{},wA=new hn({functionName:W,code:nA,message:EA});Se.ssoLog.error(W,EA,{error:wA}),this._logWorkflowExecution(E,r,"error",P),u.onError(P)}finally{f.delete(r),g.pendingSteps.delete(r),u.onStepComplete(),u.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(kg).forEach(r=>{this._handlers.has(r)||this._handlers.set(r,new Map)})}_cancelWorkFlow(r){const g=this._activeWorkflows.get(r);if(!g)return;const{cancelToken:u}=g;u.cancelled=!0,this._activeWorkflows.delete(r)}_cancelAllWorkflows(){Object.keys(kg).forEach(r=>{this._cancelWorkFlow(r)})}_validateWorkflow(r){return kg[r]?!!this._handlers.get(r):!1}_getExecutableSteps(r){const{pendingSteps:g,completedSteps:u,stepMap:E,workflowName:f}=r;return Array.from(g).filter(D=>{const v=E.get(D)||{},{dependency:N,skipIfDependencyMissing:P=!0}=v;if(!N)return!0;if(c(N))return this._isStepRegistered({workflowName:f,stepId:N})?u.has(N):!P;if(C(N)){if(N.filter(W=>!this._isStepRegistered({workflowName:f,stepId:W})).length>0&&P)return!1;for(const W of N)if(!u.has(W))return!1;return!0}return!1})}_isStepRegistered(r){var g;const{workflowName:u,stepId:E}=r;return(g=this._handlers.get(u))===null||g===void 0?void 0:g.has(E)}_logWorkflowExecution(r,g,u,E){this._logHandlers[u](r,g)}}const fa=new Map,ea=({type:s,groupID:r})=>s===Po.GRP_COMMUNITY||`${r}`.startsWith(ga.COMMUNITY)&&!`${r}`.includes(ga.TOPIC),tl=(s="")=>{const r=s.startsWith("GROUP")?s.replace("GROUP",""):s;return r.startsWith(ga.COMMUNITY)&&`${r}`.includes(ga.TOPIC)},hd="openim",ic="million_group_open_http_svc";function Ig(s){return mA(this,void 0,void 0,function*(){const{servcmd:r,data:g}=function(f){const{data:D}=f;return TE(D)||oc(D)}(s)?function(f){let{servcmd:D,data:v}=f;return oc(v)?function(N){const{servcmd:P,data:W}=N;let{GroupId:nA=""}=W;const EA=nA;return[nA]=EA.split(ga.TOPIC),{servcmd:$s(P),data:Object.assign(Object.assign({},W),{GroupId:nA,TopicId:EA})}}(f):(TE(v)&&(D=$s(D)),{servcmd:D,data:v})}(s):s,u=Se.common.generateProtocolData({servcmd:r,data:g}),E=`${u.head.seq}${r}`;return Se.channel.sendPacket(u,{requestId:E,timeout:s.timeout})})}function TE(s){const{Type:r,GroupId:g,GroupIdList:u=[]}=s,E=g||u[0]||"";return ea({type:r,groupID:E})}function oc(s){const{GroupId:r=""}=s;return tl(r)}function $s(s){if(s.includes(hd))return s;const r=s.split(".")[1];return`${ic}.${r}`}function ar(){var s;return(s=Se.store.get("login"))===null||s===void 0?void 0:s.userId}const Va=s=>C(s)||m(s),Bd=(s,r,g,u)=>{if(!Va(s)||!Va(r))return 0;let E=0;const f=Object.keys(r);let D;for(let v=0,N=f.length;v{if(n(r))return"";if(s===Po.MSG_TEXT)return r.text||"";const g=XI[s];return g?Uu(g):""},ol=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],$I="im_sdk_config_mgr.fetch_config",QI="im_sdk_config_mgr.push_configv2",nl="cloud-config",sl=2996,Ga=new class{init(s){this.core=s}};function Ug(s){return mA(this,void 0,void 0,function*(){const{sdkAppId:r}=Ga.core.store.get("instance")||{},g=Ga.core.helper.generateProtocolData({servcmd:$I,data:{uint32_sdkappid:r,uint64_version:s}}),u=`${g.head.seq}${$I}`;return Ga.core.channel.sendPacket(g,{requestId:u})})}var Nn=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(s){this._core=s;const{notificationCenter:r,InnerEvent:g,helper:u,constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:f},channel:D}=s;r.subscribeInnerEvent(QI,this._handlePushedConfig,this),u.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,f.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),r.subscribeInnerEvent(g.LOGOUT,this._reset,this),r.subscribeInnerEvent(g.DESTROY,this._dispose,this),u.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(ol),D.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(s){return mA(this,void 0,void 0,function*(){var r;const g={code:0,data:""};return s&&(g.data=((r=this._core.store.get("cloudConfig"))===null||r===void 0?void 0:r[s])||""),g})}checkMethodCallOverLimit(s){if(!this._cmdFrequencyLimitMap.has(s))return;if(!this._methodCallFrequencyMap.has(s))return void this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});const{count:r,interval:g}=this._cmdFrequencyLimitMap.get(s);let{startTime:u,methodCallCounter:E}=this._methodCallFrequencyMap.get(s);if(Date.now()-u>1e3*g)this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});else if(E+=1,this._methodCallFrequencyMap.set(s,{startTime:u,methodCallCounter:E}),E>r)throw new this._core.helper.ChatError({code:sl,replacement1:s})}_handlePushedConfig(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;r.info("_handlePushedConfig",g(s)),yield this._updateCloudConfig(s)})}_handleLoginSuccess(){return mA(this,void 0,void 0,function*(){const{ssoLog:s,utils:{safeStringify:r}}=this._core;try{if(this._canFetch()){const g=yield Ug(this._version);s.info("_fetchCloudConfigIfLogin",r(g)),yield this._updateCloudConfig(g)}this._core.helper.taskScheduler.addTask({id:nl,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(g){s.debug("_fetchCloudConfigIfLogin",r(g))}})}_fetchCloudConfigIfReady(){return mA(this,void 0,void 0,function*(){const{ssoLog:s,utils:{safeStringify:r}}=this._core;if(this._canFetch())try{const g=yield Ug(this._version);s.info("_fetchCloudConfigIfReady",r(g)),yield this._updateCloudConfig(g)}catch(g){s.error("_fetchCloudConfigIfReady",r(g))}})}_updateCloudConfig(s){return mA(this,void 0,void 0,function*(){const r=this._parseCloudConfig(s);r&&(this._core.store.set("cloudConfig",r),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,r),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:r}}))})}_canFetch(){const{isLoggedIn:s}=this._core.store.get("login")||{};return s&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(s){const{int32_error_code:r,str_error_message:g,str_json_config:u,uint32_expired_time:E,uint32_sdkappid:f,uint64_version:D}=s;let v=null;if(r===0){if(this._version!==D)try{v=JSON.parse(u),this._version=D}catch{}this._expirationTime=Date.now()+1e3*E}else this._expirationTime=r===void 0?Date.now()+36e5:Date.now()+12e4;return v}_parseCmdFreqLimit(){return mA(this,void 0,void 0,function*(){var s;let r=(s=yield this.getServerConfig("cmd_frequency_limit"))===null||s===void 0?void 0:s.data;const{isEmpty:g}=this._core.utils;if(!g(r))try{r=JSON.parse(r),this._updateCmdFreqLimitMap(r)}catch(u){console.warn(u)}})}_updateCmdFreqLimitMap(s){s.forEach(r=>{this._cmdFrequencyLimitMap.set(r.cmd,{interval:r.interval,count:r.count})})}_reset(){this._core.helper.taskScheduler.removeTask(nl),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(ol),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(QI,this._handlePushedConfig,this),s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this),this._reset()}};class Ar{constructor(r=0,g=0){this.high=r,this.low=g}equal(r){return r!==null&&this.low===r.low&&this.high===r.high}toString(){const r=Number(this.high).toString(16);let g=Number(this.low).toString(16);if(g.length<8){let u=8-g.length;for(;u;)g=`0${g}`,u--}return r+g}}const bc={SEARCH_GRP_SNS:new Ar(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Ar(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Ar(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Ar(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Ar(0,Math.pow(2,6)).toString(),USER_STATUS:new Ar(0,Math.pow(2,7)).toString(),CONV_MARK:new Ar(0,Math.pow(2,9)).toString(),CONV_GROUP:new Ar(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Ar(0,Math.pow(2,11)).toString(),MSG_EXT:new Ar(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Ar(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Ar(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Ar(Math.pow(2,7)).toString(),PLUGIN_CS:new Ar(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Ar(Math.pow(2,9)).toString(),PLUGIN_BOT:new Ar(Math.pow(2,10)).toString(),MSG_REACTION:new Ar(Math.pow(2,16)).toString(),FOLLOW:new Ar(Math.pow(2,20)).toString()},Au="CommercialConfig",eu="commercial-config";var NE=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(s){this._core=s;const{helper:r,notificationCenter:g,constants:{WORKFLOW_NAME:u,WORKFLOW_STEP:E,InnerEvent:f}}=s;g.subscribeInnerEvent(f.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),g.subscribeInnerEvent(f.LOGOUT,this._handleLogout,this),g.subscribeInnerEvent(f.DESTROY,this._dispose,this),r.registerWorkflowStep(u.SYNC_SERVER_INFO_AFTER_LOGIN,E.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),s.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),s.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(s){return mA(this,void 0,void 0,function*(){const r=parseInt(s,10).toString(2),{length:g}=r;let u,E=!0;for(let f=g-1,D=0;f>=0;f--,D++)if(r.charAt(f)==="1"&&(u=D<32?new Ar(0,2**D).toString():new Ar(2**(D-32),0).toString(),!this._featureMap.get(u))){E=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${Au}.isFeatureEnabled decimalNumber:${s} key:${u} ret:${E}`),{code:0,data:{enabled:E}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return mA(this,void 0,void 0,function*(){var s;const{ssoLog:r,utils:{safeStringify:g},common:{buildAndSendPacket:u}}=this._core;try{this._isFetching=!0;const E=yield u({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:(s=this._core.store.get("instance"))===null||s===void 0?void 0:s.sdkAppId}});E&&(this._parseCommercialConfig(E),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(E){r.error("_fetchAndParseCommercialConfig",g(E))}finally{this._isFetching=!1}})}_syncCommercialConfig(s){return mA(this,void 0,void 0,function*(){const{purchaseBits:r}=s?.data||{};r&&(this._parsePurchaseBits(r),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:eu,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var s;const r=(s=this._core.store.get("login"))===null||s===void 0?void 0:s.isLoggedIn,g=Date.now()>=this._expirationTime;return r&&!this._isFetching&&g}_handlePushedConfig(s){s?.body&&(this._parseCommercialConfig(s.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return mA(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(s){const{ssoLog:r}=this._core;if(typeof s!="object")return;const{int32_error_code:g,str_error_message:u,str_purchase_bits:E,uint32_expired_time:f}=s;g===0?(this._parsePurchaseBits(E),this._expirationTime=Date.now()+1e3*f):g===void 0?(r.warn("_parseCommercialConfig",`${Au}._parseCommercialConfig failed. Invalid message format:`,s),this._expirationTime=Date.now()+36e5):(r.warn("_parseCommercialConfig",`${Au}._parseCommercialConfig errorCode:${g} errorMessage:${u}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(s){return s&&typeof s=="string"&&s.length>=1&&s.length<=64&&/[01]{1,64}/.test(s)}_parsePurchaseBits(s){const{ssoLog:r,utils:{safeStringify:g}}=this._core;if(this._isValidPurchaseBits(s)){this._purchaseBits=s,this._featureMap.clear(),this._methodKeyMap.clear();let u=null;for(let E=s.length-1,f=0;E>=0;E--,f++)if(u=f<32?new Ar(0,2**f).toString():new Ar(2**(f-32),0).toString(),s[E]==="1"){this._featureMap.set(u,!0);const D=this._getKeyByValue(bc,u);D&&this._methodKeyMap.set(D,!0)}else{this._featureMap.set(u,!1);const D=this._getKeyByValue(bc,u);D&&this._methodKeyMap.set(D,!1)}}else r.warn("_parsePurchaseBits",`${Au}.parsePurchaseBits invalid purchases:${g(s)}`)}_getKeyByValue(s,r){const g=Object.entries(s).find(([u,E])=>E===r);return g?g[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(eu),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},lh=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(s){this._core=s;const{notificationCenter:r,InnerEvent:g,channel:u}=this._core;r.subscribeInnerEvent(g.OVERLOAD_PUSH,this._handleOverLoadPush,this),r.subscribeInnerEvent(g.LOGOUT,this._reset,this),r.subscribeInnerEvent(g.DESTROY,this._dispose,this),u.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(s){if(!this._serverOverloadInfoMap.has(s))return;const{overloadStartTimestamp:r,delaySeconds:g}=this._serverOverloadInfoMap.get(s);if(Date.now()-r<=1e3*g)throw new this._core.helper.ChatError({functionName:s,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(s)}_handleOverLoadPush(s){const{OverLoadServCmd:r,DelaySecs:g}=s;this._serverOverloadInfoMap.set(r,{overloadStartTimestamp:Date.now(),delaySeconds:g})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.OVERLOAD_PUSH,this._handleOverLoadPush,this),s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}},dC=new class{constructor(){this.name="ConfigCenter"}install(s){Ga.init(s),Nn.install(s),NE.install(s),lh.install(s)}},Ih=new class{constructor(){this.name="ErrorMessage",this._core=null}install(s){return mA(this,void 0,void 0,function*(){if(this._core=s,this._canFetch()){const r=yield this._fetchErrorMessage();if(!r)return;const g=this._parseResponse(r);this._saveErrorMessage(g)}})}_canFetch(){const s=this._core.store.getStorage("errorMessage");return!s||this._isExpired(s)}_saveErrorMessage(s){this._core.store.setStorage("errorMessage",{errorMessage:s,errorMessageSavedTime:new Date().getTime()})}_fetchErrorMessage(){return mA(this,void 0,void 0,function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(s){console.error(s)}})}_isExpired(s){if(!s)return!0;const{errorMessageSavedTime:r}=s;return r&&new Date().getTime()-r>=6048e5}_parseResponse(s){if(typeof s=="string"){const r=s.split(`; -`),g={},u=new RegExp(/'/g);for(let E=0;E{var zA,Ee,Ie;const Li=function(Ui,Yt){const{From_Account:Oi,From_AccountHeadurl:Bn,From_AccountNick:Re,IsNeedReadReceipt:Mt,MsgBody:FA,MsgClientTime:ci,MsgRandom:xn,MsgSeq:Pi,MsgTimeStamp:Vr,SendMsgControl:ji,SupportMessageExtension:Br,To_Account:Ut,TinyId:Ft,MsgCheckResult:oE,CloudCustomData:hs,IsPeerRead:Do,MsgFlagBits:Bl,MsgVersion:GC,EventArray:Gr}=Ui;return{from:Oi,avatar:Bn,nick:Re,needReadReceipt:Mt===1,readReceiptSentByPeer:Do,clientTime:ci,messageFlagBits:Bl,random:xn,sequence:Pi,time:Vr,messageControlInfo:ji,isSupportExtension:Br,to:Ut,tinyID:Ft,checkResult:oE,cloudCustomData:hs,messageVersion:GC,eventArray:Gr,elements:Yt.message.messageHelper.parseServerPushMessageElement(FA)}}(PA,VA);if(!((Ie=(Ee=(zA=PA?.EventArray)===null||zA===void 0?void 0:zA[0])===null||Ee===void 0?void 0:Ee.hasOwnProperty)===null||Ie===void 0)&&Ie.call(Ee,"C2cNotifyMsgArray"))SA.push(...function(Ui){var Yt;const Oi=[];return(Yt=Ui.EventArray)===null||Yt===void 0||Yt.forEach(Bn=>{var Re,Mt;const{C2cNotifyMsgArray:FA}=Bn,ci=(Mt=(Re=FA?.[0])===null||Re===void 0?void 0:Re.WithdrawC2cMsgNotify)===null||Mt===void 0?void 0:Mt.C2cWithdrawInfoArray;Array.isArray(ci)&&Oi.push(...ci)}),Oi}(PA));else{const Ui=VA.message.messageFactory.createMessage(Object.assign(Object.assign({},Li),{conversationType:"C2C",flow:"in"})),{elements:Yt}=Li;Ui.setElement(Yt),LA.push(Ui)}}),{unreadMessageList:LA,revokedMessageList:SA}}(N.MsgList,r);return{syncFlag:N?.SyncFlag,unreadMessageList:EA,revokedMessageList:wA,unreadCountList:P,overflowUnreadCountList:W,cookie:N?.Cookie,groupTipList:nA}}catch(N){console.warn(N)}})}var Fg,Io;(function(s){s[s.START_SYNC=0]="START_SYNC",s[s.SYNCING=1]="SYNCING",s[s.SYNC_COMPLETE=2]="SYNC_COMPLETE"})(Fg||(Fg={})),function(s){s[s.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",s[s.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(Io||(Io={}));var CC=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie="",this._localConversationIDListBeforeDisconnect=[]}install(s){this._core=s;const{constants:r}=s;s.helper.registerWorkflowStep(r.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),s.helper.registerWorkflowStep(r.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,r.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),s.helper.registerWorkflowStep(r.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,r.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.SOCKET_DISCONNECTED,this._handleDisconnect,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(s){return mA(this,void 0,void 0,function*(){const{isAfterReOnline:r=!1,isAfterNewMessageReceived:g=!1,isAfterLogin:u=!1}=s||{};let E=Fg.START_SYNC;const f=[],D=[],v=[],N=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:E});){const P=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:E,syncTriggerEvent:g?Io.NEW_MESSAGE_RECEIVED:Io.LOGIN_SUCCESS});if(!P)break;const{unreadMessageList:W=[],revokedMessageList:nA=[],overflowUnreadCountList:EA,unreadCountList:wA,groupTipList:kA}=P;if(this._cookie=P?.cookie||"",E=P?.syncFlag,this._parseAndSaveUnreadMessageList(W),v.push(...nA),this._updateConversationUnreadOptions({unreadCountList:wA,overflowUnreadCountList:EA,conversationUpdateFieldList:f}),Array.isArray(kA)&&D.push(...kA),r){const{messages:VA}=this._handleNewMessageList(W);N.push(...VA)}}return r?{conversationUpdateFieldList:f,revokedMessageList:v,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D,messages:N,isUnreadC2CMessage:!0}:{conversationUpdateFieldList:f,isInstantMessage:!u,isUnreadC2CMessage:!0,revokedMessageList:v,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D}})}_syncUnreadDBMessageAfterLogin(){return mA(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(s){return mA(this,void 0,void 0,function*(){if(s.data.Flag===1)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(s){const{unreadCountList:r,overflowUnreadCountList:g,conversationUpdateFieldList:u}=s,{constants:{OuterConstant:{CONV_C2C:E,CONV_SYSTEM:f}}}=this._core;r?.forEach(D=>{const{From_Account:v,UnreadCount:N}=D;if(v!==f){const P=u.find(({conversationID:W})=>W===`${E}${v}`);P?P.unreadCount=N:u.push({conversationID:`${E}${v}`,unreadCount:N,type:E})}}),g?.forEach(D=>{const{From_Account:v,LastMsgTime:N}=D;v!==f&&(u.find(({conversationID:P})=>P===`${E}${v}`)||u.push({conversationID:`${E}${v}`,type:E,lastMsgTime:N}))})}_syncUnreadDBMessageAfterReOnline(){return mA(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(s){var r;const{messageDataHandler:g}=this._core.message||{},u=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,{from:E,nick:f,avatar:D,conversationID:v=""}=s;if(E!==u){const N=g.getLatestMsgSentByPeer(v);if(N){const{nick:P,avatar:W}=N;f&&D?f===P&&D===W||g.updateNickAndAvatarOfSentMessage({conversationID:v,latestNick:f,latestAvatar:D,isSentByMe:!1}):(s.nick=P,s.avatar=W)}}else{const N=g.getLatestMsgSentByMe(v);!N||f===N.nick&&D===N.avatar||g.updateNickAndAvatarOfSentMessage({conversationID:v,latestNick:f,latestAvatar:D,isSentByMe:!0})}}_handleNewMessageList(s){const{messageDataHandler:r}=this._core.message||{},g=new Map,u=[];return s.forEach(E=>{this._updateMessageProfile(E);let f=E.isModified===1;if(r.isMessageSentByCurrentInstance(E)?E.isModified=f:f=!1,E.isOnlineMessage())E._onlineOnlyFlag=!0,r.isMessageSentByCurrentInstance(E)||u.push(E);else if(this._shouldStoreUnreadMessage(E)){if(r.storeConversationMessage(E)){const{conversationID:D,conversationType:v,conversationSubType:N,flow:P,_isExcludedFromUnreadCount:W,_isExcludedFromLastMessage:nA}=E,EA=nA?"":E;g.has(D)?(g.get(D).lastMessage=EA,P==="in"&&(W||g.get(D).unreadCount++)):g.set(D,{conversationID:D,type:v,subType:N,unreadCount:W||P!=="in"?0:1,lastMessage:EA})}r.isMessageSentByCurrentInstance(E)&&!f||u.push(E)}}),{messages:u,conversationOptions:g}}_shouldStoreUnreadMessage(s){var r;const{conversationID:g}=s,{message:u,appStore:E,utils:{isEmpty:f}}=this._core||{},D=Array.from(((r=E.conversationStore.getConversationMap())===null||r===void 0?void 0:r.keys())||[]),v=this._getLocalLastMessageTime(g);return!u.messageDataHandler.isInMessageList(s)&&D.includes(g)&&this._localConversationIDListBeforeDisconnect.includes(g)&&!f(v)}_fetchUnreadDBMessage(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;try{r.debug("_fetchUnreadDBMessage",`unread-message-synchronizer._fetchUnreadDBMessage options:${g(s)}`);const E=yield rl(s,this._core);if(!E)return null;const{syncFlag:f,unreadMessageList:D,revokedMessageList:v,cookie:N,unreadCountList:P,overflowUnreadCountList:W,groupTipList:nA}=E;return this._parseAndSaveUnreadMessageList(D),{syncFlag:f,cookie:N,unreadMessageList:D,revokedMessageList:v,unreadCountList:P,overflowUnreadCountList:W,groupTipList:nA}}catch(u){console.log(u)}})}_canContinueSync({cookie:s,syncFlag:r}){var g;return r===Fg.START_SYNC||r===Fg.SYNCING&&!(!((g=this._core)===null||g===void 0)&&g.helper.isEmpty(s))}_parseAndSaveUnreadMessageList(s){s.forEach(r=>{const{ID:g}=r;this._unreadDBMessageMap.set(g,r)})}_handleDisconnect(){var s;const{appStore:r}=this._core;this._localConversationIDListBeforeDisconnect=Array.from(((s=r.conversationStore.getConversationMap())===null||s===void 0?void 0:s.keys())||[])}_getLocalLastMessageTime(s){const{message:r}=this._core,g=r.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.time}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var s,r;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},GE=new class{init(s){var r;this._core=s,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),document?.addEventListener("visibilitychange",this._visibilityChangeHandler),(r=this._core)===null||r===void 0||r.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var s,r;const g=document?.visibilityState==="visible";(s=this._core)===null||s===void 0||s.store.set("activityMonitor",{isActive:g}),(r=this._core)===null||r===void 0||r.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:g})}_reset(){var s;(s=this._core)===null||s===void 0||s.store.clear("activityMonitor")}_dispose(){document?.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this),this._reset()}},bE=new class{init(s){var r;this._core=s,this._bindAppActivityEvent(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),(r=this._core)===null||r===void 0||r.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var s,r,g,u,E;const{MINI_APP_NAMESPACE:f,IN_TT_MINI_GAME:D,IN_WX_MINI_GAME:v}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};D||v?((r=f?.onShow)===null||r===void 0||r.call(f,()=>{var N,P;(N=this._core)===null||N===void 0||N.store.set("activityMonitor",{isActive:!0}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(g=f?.onHide)===null||g===void 0||g.call(f,()=>{var N,P;(N=this._core)===null||N===void 0||N.store.set("activityMonitor",{isActive:!1}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):((u=f?.onAppShow)===null||u===void 0||u.call(f,()=>{var N,P;(N=this._core)===null||N===void 0||N.store.set("activityMonitor",{isActive:!0}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(E=f?.onAppHide)===null||E===void 0||E.call(f,()=>{var N,P;(N=this._core)===null||N===void 0||N.store.set("activityMonitor",{isActive:!1}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var s;(s=this._core)===null||s===void 0||s.store.clear("activityMonitor")}_dispose(){const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this),this._reset()}},Qd=new class{init(s){const{IN_MINI_APP:r,IN_WX_MINI_PLUGIN:g}=s.helper;g||(r?bE.init(s):GE.init(s))}};const kE="none",al="online";var pI=new class{init(s){this._core=s,this._activateNetworkMonitoring(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return mA(this,void 0,void 0,function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)})}_deactivateNetworkMonitoring(){this._onOnlineCallback!==null&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),this._onOfflineCallback!==null&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(s){var r,g;const{isConnected:u,networkType:E}=s;(r=this._core)===null||r===void 0||r.store.set("netWorkMonitor",{isNetworkOnline:u,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:u,networkType:E})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:al})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:kE})}_reset(){var s;this._deactivateNetworkMonitoring(),(s=this._core)===null||s===void 0||s.store.clear("netWorkMonitor")}_dispose(){var s,r;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent((r=this._core)===null||r===void 0?void 0:r.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Fu=new class{init(s){this._core=s,this._activateNetworkMonitoring(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return mA(this,void 0,void 0,function*(){try{const{utils:{MINI_APP_NAMESPACE:s}}=this._core;this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),s.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(s){console.error(s)}})}_deactivateNetworkMonitoring(){if(this._mpNetworkStatusCallback!==null){const{utils:{MINI_APP_NAMESPACE:s}}=this._core;s.offNetworkStatusChange&&s.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null}}_onNetworkStatusChange(s){var r,g;const{isConnected:u,networkType:E}=s;(r=this._core)===null||r===void 0||r.store.set("netWorkMonitor",{isNetworkOnline:u,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:u,networkType:E})}_reset(){var s;this._deactivateNetworkMonitoring(),(s=this._core)===null||s===void 0||s.store.clear("netWorkMonitor")}_dispose(){var s,r;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent((r=this._core)===null||r===void 0?void 0:r.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Ou=new class{init(s){const{IN_MINI_APP:r}=s.utils;r?Fu.init(s):pI.init(s)}},hC=new class{constructor(){this.name="SystemStateMonitor"}install(s){Qd.init(s),Ou.init(s)}};const Tr=new Set(["tui_room_svr.*","callkit_records_svr.*","room_engine_srv.*","room_engine_http_srv.*","room_engine_mic.*","live_engine_srv.*","live_engine_http_srv.*","live_engine_pk.*","trtc_ai_service.*","call_engine_srv.*"]),ug="tui_room_svr.*";var kc=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=Tr}install(s){this._core=s;const{notificationCenter:r,InnerEvent:g,helper:u}=s;r.subscribeInnerEvent(g.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),r.subscribeInnerEvent(g.LOGOUT,this._reset,this),r.subscribeInnerEvent(g.DESTROY,this._dispose,this),r.subscribeInnerEvent("im_open_push.msg_push",r.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),u.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),u.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(s){return mA(this,void 0,void 0,function*(){const r="transferBusinessCommand";try{const{serviceCommand:g=ug}=s||{};if(!this._isValidTransferredCommand(g))throw new this._core.helper.ChatError({code:2995,functionName:r});return{code:0,data:(yield function(E,f){return mA(this,void 0,void 0,function*(){const{helper:D,channel:v}=f,{serviceCommand:N=ug,data:P}=E||{};let W={};try{W=typeof P=="string"?JSON.parse(P):P}catch(wA){console.warn(wA)}const nA=D.generateProtocolData({servcmd:N,data:W}),EA=`${nA.head.seq}${N}`;return v.sendPacket(nA,{requestId:EA,shouldRejectOnError:!1})})}(s,this._core))||{}}}catch(g){throw console.warn(g),new this._core.helper.ChatError({code:g?.errorCode,message:g?.errorInfo,data:{},functionName:r})}})}_onCloudConfigUpdate(s={}){try{if(typeof s.rtc_cmd!="string")return;const r=JSON.parse(s.rtc_cmd);Array.isArray(r)&&(this._transferredCommands=new Set([...this._transferredCommands,...r]))}catch(r){console.log(r)}}_isValidTransferredCommand(s=""){const r=`${s?.split(".")[0]}.*`;return this._transferredCommands.has(r)}_onServerPushBusinessCommand(s){const{OuterEvent:r,notificationCenter:g}=this._core,{MsgContent:u}=s||{},{ROOM_CUSTOM_DATA_RECEIVED:E}=r;g.emitOuterEvent(E,{name:E,data:u})}_reset(){this._transferredCommands=Tr}_dispose(){const{notificationCenter:s,InnerEvent:r}=this._core;this._reset(),s.unSubscribeInnerEvent(r.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this),s.unSubscribeInnerEvent("im_open_push.msg_push",s.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const Pu=1,Ll=2,pd=3,ta=4,mI=5,Us="TIMCustomElem",BC="C2C",gl="GROUP",md="invite",fI="accept",Ha="cancel",QC="reject",Ja="modifyInvitation",fr="signaling",fd=8010,xu="signaling-timeout";function yr(s){return s.filter(r=>{if(r.type===Us){const{cloudCustomData:g="",payload:{data:u=""}={}}=r,E=g.match(/"type":"tsignaling"/),f=u.match(/inviteID/),D=u.match(/actionType/);return E||f&&D}return!1})}function Lc(s){const{data:r}=s.payload;try{return JSON.parse(r)}catch(g){return console.error(g),null}}function cl(s,r){return s.toString(16).padStart(r,"0")}function Og(s){if(s<0||s>53)throw new Error("Number of digits must be between 0 and 53");if(s<=30)return Math.floor(Math.random()*(1<0;const v=this._core.common.getCurrentUserID();return D.includes(v)}return!0}updateSignaling(s){const r=`${fr}.updateSignaling`,{inviteID:g,inviter:u,inviteeList:E,groupID:f}=s;if(console.log(`${r} inviteID:${g} inviter:${u} groupID:${f}`),f&&this.hasSignaling(g)){const D=E[0],{inviteeList:v}=this._onlineSignalingMap.get(g);v.includes(D)&&(v.splice(v.indexOf(D),1),console.log(`${r} remove ${D}. localInviteeList.length:${v.length}`)),v.length===0&&this.removeSignaling(g)}else this.removeSignaling(g)}setSignalingListenStatus(s){this._isSignalingListening=s}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var s,r;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},nc=new class{init(s){this._core=s}createInviteSignaling(s){const r=this._generateInviteID(),g=this._createInviteSignalingData(Object.assign(Object.assign({},s),{inviteID:r})),{groupID:u,inviteeList:E}=g,f=u||E[0];return{signaling:this._createSignaling(g,f),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createAcceptSignaling(s){const r=this._createAcceptSignalingData(s),{groupID:g,inviter:u}=r,E=g||u;return{signaling:this._createSignaling(r,E),signalingData:r,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createCancelSignaling(s){const r=this._createCancelSignalingData(s),{groupID:g,inviteeList:u}=r,E=g||u[0];return{signaling:this._createSignaling(r,E),signalingData:r,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createRejectSignaling(s){const r=this._createRejectSignalingData(s),{groupID:g,inviter:u}=r,E=g||u;return{signaling:this._createSignaling(r,E),signalingData:r,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createTimeoutSignaling(s){const{isInviter:r=!1}=s,g=this._createTimeoutSignalingData(s),{groupID:u,inviteeList:E,inviter:f}=g,D=u||(r?E[0]:f);return{signaling:this._createSignaling(g,D),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(g)}}_createSignalingExtensionOptions(s){var r,g;const{data:u="",onlineUserOnly:E,inviteID:f="",offlinePushInfo:D,actionType:v}=s,N=((g=(r=Jo.getSignaling(f))===null||r===void 0?void 0:r.signaling)===null||g===void 0?void 0:g._onlineOnlyFlag)||!1;return{onlineUserOnly:E||N,offlinePushInfo:D,messageControlInfo:this._createMessageControlInfo(u,v)}}_createMessageControlInfo(s,r){const g=r===mI&&!!s.match(/excludeTimeoutSignalingFromHistoryMessage/),u=!!s.match(/excludeFromHistoryMessage/)||!!s.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:g||u,excludedFromLastMessage:g||u}}_createInviteSignalingData(s){const r=`${fr}._createInviteSignalingData`,{userID:g,timeout:u=0,groupID:E="",inviteeList:f=[]}=s,D=this._core.common.getCurrentUserID(),v=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Pu,inviter:D,inviteeList:E?f:[g],timeout:u});return console.log(`${r} signalingData:`,v),v}_createAcceptSignalingData(s){const r=`${fr}._createAcceptSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviter:E,groupID:f}=Jo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:pd,groupID:f,inviter:E,inviteeList:[u]});return console.log(`${r} signalingData:`,D),D}_createCancelSignalingData(s){const r=`${fr}._createCancelSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviteeList:E,groupID:f}=Jo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Ll,groupID:f,inviter:u,inviteeList:E});return console.log(`${r} signalingData:`,D),D}_createRejectSignalingData(s){const r=`${fr}._createRejectSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviter:E,groupID:f}=Jo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:ta,groupID:f,inviter:E,inviteeList:[u]});return console.log(`${r} signalingData:`,D),D}_createTimeoutSignalingData(s){const r=`${fr}._createTimeoutSignalingData`,{isInviter:g=!1,inviteID:u}=s,{inviteeList:E,inviter:f}=Jo.getSignaling(u),D=this._core.common.getCurrentUserID(),v=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:mI,inviter:f,inviteeList:g?E:[D]});return console.log(`${r} signalingData:`,v),v}_createSignaling(s,r){var g,u,E;const{groupID:f=""}=s,D={to:r,conversationType:f?gl:BC,priority:"High",payload:{data:JSON.stringify(s)}};return(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(D)}_generateInviteID(){return[cl(Og(32),8),cl(Og(16),4),cl(16384|Og(12),4),cl(32768|Og(14),4),cl(Og(48),12)].join("-")}_generateBaseSignalData(s){const{data:r="",inviteID:g="",groupID:u=""}=s;return{businessID:1,timeout:0,data:r,inviteID:g,groupID:u}}},eg=new class{constructor(){this._isProcessingSignaling=!1}init(s){this._core=s,s.helper.registerApi({apiName:"invite",context:this}),s.helper.registerApi({apiName:"accept",context:this}),s.helper.registerApi({apiName:"cancel",context:this}),s.helper.registerApi({apiName:"reject",context:this}),s.helper.registerApi({apiName:"modifyInvitation",context:this}),s.helper.registerApi({apiName:"getSignalingInfo",context:this}),s.helper.registerApi({apiName:"addSignalingListener",context:this}),s.helper.registerApi({apiName:"removeSignalingListener",context:this}),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this)}invite(s){return mA(this,void 0,void 0,function*(){var r;try{this._validateBeforeInvite(s);const{signaling:g,signalingData:u,signalingExtensionOptions:E}=nc.createInviteSignaling(s),f=yield this._sendSignaling(g,E);if(f?.code===0){const{inviteID:D,timeout:v}=u;return Jo.saveSignaling(D,Object.assign(Object.assign({},u),{signaling:g})),v>0&&((r=this._core)===null||r===void 0||r.helper.taskScheduler.addOnceTask({id:`${xu}-${D}`,intervalMs:1e3*(v+5),callback:this.handleInvitationExpiryTimer.bind(this,D)})),Object.assign(Object.assign({},f),{inviteID:D})}return f}catch(g){throw g}})}accept(s){return mA(this,void 0,void 0,function*(){try{const{inviteID:r}=s;this._validateBeforeAccept(r),this._isProcessingSignaling=!0;const{signaling:g,signalingData:u,signalingExtensionOptions:E}=nc.createAcceptSignaling(s),f=yield this._sendSignaling(g,E);return f?.code===0?(Jo.updateSignaling(u),Object.assign(Object.assign({},f),{inviteID:r})):f}catch(r){throw r}finally{this._isProcessingSignaling=!1}})}cancel(s){return mA(this,void 0,void 0,function*(){try{const{inviteID:r}=s;this._validateBeforeCancel(r),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:u}=nc.createCancelSignaling(s),E=yield this._sendSignaling(g,u);return E?.code===0?(Jo.removeSignaling(r),Object.assign(Object.assign({},E),{inviteID:r})):E}catch(r){throw r}finally{this._isProcessingSignaling=!1}})}reject(s){return mA(this,void 0,void 0,function*(){try{const{inviteID:r}=s;this._validateBeforeReject(r),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:u}=nc.createRejectSignaling(s),E=yield this._sendSignaling(g,u);return E?.code===0?(Jo.removeSignaling(r),Object.assign(Object.assign({},E),{inviteID:r})):E}catch(r){throw r}finally{this._isProcessingSignaling=!1}})}modifyInvitation(s){return mA(this,void 0,void 0,function*(){var r,g;const{inviteID:u,data:E}=s;let f="";try{this._validateBeforeModifyInvitation(u);const D=Jo.getSignaling(u),{signaling:v}=D,N=vo(D,["signaling"]);f=v.payload.data,N.data=E,v.payload.data=JSON.stringify(N);const P=yield(g=(r=this._core)===null||r===void 0?void 0:r.message.messageAction)===null||g===void 0?void 0:g.modifyMessage(v);return Jo.hasSignaling(u)&&Jo.saveSignaling(u,Object.assign(Object.assign({},N),{signaling:v})),P}catch(D){if(f){const{signaling:v}=Jo.getSignaling(u);v.payload.data=f}throw D}})}getSignalingInfo(s){const{ssoLog:r,utils:{safeStringify:g}}=this._core;if(yr([s]).length===0)return;const u=Lc(s),E={businessID:u.businessID||1,inviteID:u.inviteID,groupID:u.groupID||"",inviter:u.inviter||"",inviteeList:u.inviteeList||[],data:u.data||"",actionType:u.actionType||Pu,timeout:u.timeout||0};return r.debug(`${fr} getSignalingInfo ${g(E)}`),E}addSignalingListener(s,r,g){var u,E;s===((u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED)&&Jo.setSignalingListenStatus(!0),(E=this._core)===null||E===void 0||E.notificationCenter.subscribeOuterEvent(s,r,g)}removeSignalingListener(s,r,g){var u,E;s===((u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED)&&Jo.setSignalingListenStatus(!1),(E=this._core)===null||E===void 0||E.notificationCenter.unSubscribeOuterEvent(s,r,g)}handleInvitationExpiryTimer(s){const r=Jo.getOnlineSignalingMap(),g=this._core.common.getCurrentUserID();if(!r.has(s))return;const u=r.get(s).inviter===g;this._sendTimeoutNotice({inviteID:s,isInviter:u})}_sendSignaling(s,r){return mA(this,void 0,void 0,function*(){var g,u,E;return(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(s,r)})}_sendTimeoutNotice(s){return mA(this,void 0,void 0,function*(){var r,g,u;this._core.ssoLog.debug("_sendTimeoutNotice",`${fr}._sendTimeoutNotice params:${JSON.stringify(s)}`);const{isInviter:E,inviteID:f}=s,{signaling:D,signalingData:v,signalingExtensionOptions:N}=nc.createTimeoutSignaling(s),P=yield this._sendSignaling(D,N);if(P?.code===0){const{data:W,groupID:nA,inviteeList:EA,inviter:wA}=v;(r=this._core)===null||r===void 0||r.notificationCenter.emitOuterEvent((g=this._core)===null||g===void 0?void 0:g.SignalingEvent.INVITATION_TIMEOUT,{name:(u=this._core)===null||u===void 0?void 0:u.SignalingEvent.INVITATION_TIMEOUT,data:{data:W,groupID:nA,inviteID:f,inviteeList:EA,inviter:wA,isSelfTimeout:!0,message:D}}),E?Jo.removeSignaling(f):Jo.updateSignaling(v)}})}_validateInviteId(s,r){if(!Jo.hasSignaling(r))throw new this._core.helper.ChatError({functionName:s,code:fd})}_validateProcessStatus(s){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:s,message:"processing other signaling operations"})}_validateBeforeInvite(s){const r=md,{userID:g}=s,u=this._core.common.getCurrentUserID();if(g===u)throw new this._core.helper.ChatError({functionName:r,message:`cannot invite yourself, currentUserId:${u}, inviteeId:${g}`})}_validateBeforeAccept(s){const r=fI;this._validateInviteId(r,s),this._validateProcessStatus(r);const g=this._core.common.getCurrentUserID(),{inviteeList:u}=Jo.getSignaling(s);if(!u.includes(g)){const E=`userID:${g} not in inviteeList. inviteID:${s}`;throw new this._core.helper.ChatError({functionName:r,message:E})}}_validateBeforeCancel(s){const r=Ha;this._validateInviteId(r,s),this._validateProcessStatus(r);const g=this._core.common.getCurrentUserID(),{inviter:u}=Jo.getSignaling(s);if(u!==g){const E=`unmatched inviter:${u} and my userID:${g}`;throw new this._core.helper.ChatError({functionName:r,message:E})}}_validateBeforeReject(s){const r=QC;this._validateInviteId(r,s),this._validateProcessStatus(r);const g=this._core.common.getCurrentUserID(),{inviteeList:u}=Jo.getSignaling(s);if(!u.includes(g)){const E=`userID:${g} not in inviteeList. inviteID:${s}`;throw new this._core.helper.ChatError({functionName:r,message:E})}}_validateBeforeModifyInvitation(s){const r=Ja;this._validateInviteId(r,s)}_dispose(){var s,r;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},Ul=new class{constructor(){this._actionProcessor=new Map([[Pu,this._onNewInvitationReceived.bind(this)],[ta,this._onInviteeRejected.bind(this)],[pd,this._onInviteeAccepted.bind(this)],[Ll,this._onInvitationCancelled.bind(this)],[mI,this._onInvitationTimeout.bind(this)]])}init(s){this._core=s,s.notificationCenter.subscribeOuterEvent(s.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),s.notificationCenter.subscribeOuterEvent(s.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(s){s.forEach(r=>{const g=Lc(r);if(g){const u=this._actionProcessor.get(g.actionType);u?.(g,r)}})}_handleMessageReceived(s){if(!Jo.getSignalingListenStatus())return;const r=yr(s.data);r.length!==0&&this.handleActionSignaling(r)}_handleMessageModified(s){if(!Jo.getSignalingListenStatus())return;const r=yr(s.data);r.length>0&&r.forEach(g=>{const u=Lc(g);u&&this._onInvitationModified(u,g)})}_onNewInvitationReceived(s,r){var g,u;const E=`${fr}._onNewInvitationReceived`,{inviteID:f,inviteeList:D,groupID:v}=s,N=this._core.common.getCurrentUserID();if(this._core.ssoLog.debug("_onNewInvitationReceived",`${E} signalingData:${JSON.stringify(s)}}`),v&&!D.includes(N))return;let{timeout:P}=s;const W=Date.now()/1e3-r.time;P>0&&W>0&&P>W&&(P-=W);const nA=Jo.getSignaling(f);nA!==s&&(nA||Jo.saveSignaling(f,Object.assign(Object.assign({},s),{signaling:r})),P>0&&((g=this._core)===null||g===void 0||g.helper.taskScheduler.addOnceTask({id:`${xu}-${f}`,intervalMs:1e3*P,callback:eg.handleInvitationExpiryTimer.bind(eg,f)})),this._emitEvent({name:(u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:D})}))}_onInviteeRejected(s){var r;const g=`${fr}._onInviteeRejected`,{inviteID:u,inviter:E,groupID:f,inviteeList:D}=s,v=Jo.hasSignaling(u);this._core.ssoLog.debug("_onInviteeRejected",`${g} inviteID:${u} hasInviteID:${v} inviter:${E} groupID:${f}`),v&&(Jo.updateSignaling(s),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{invitee:D[0]})}))}_onInviteeAccepted(s){var r;const g=`${fr}._onInviteeAccepted`,{inviteID:u,inviter:E,groupID:f,inviteeList:D}=s,v=Jo.hasSignaling(u);this._core.ssoLog.debug("_onInviteeAccepted",`${g} inviteID:${u} hasInviteID:${v} inviter:${E} groupID:${f}`),v&&(Jo.updateSignaling(s),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{invitee:D[0]})}))}_onInvitationCancelled(s){var r;const g=`${fr}._onInvitationCancelled`,{inviteID:u,inviter:E,groupID:f}=s,D=Jo.hasSignaling(u);this._core.ssoLog.debug("_onInvitationCancelled",`${g} inviteID:${u} hasInviteID:${D} inviter:${E} groupID:${f}`),D&&(Jo.removeSignaling(u),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(s)}))}_onInvitationTimeout(s){var r;const g=`${fr}._onInvitationTimeout`,{inviteID:u,inviteeList:E}=s,f=Jo.hasSignaling(u);this._core.ssoLog.debug("_onInvitationTimeout",`${g} inviteID:${u} hasInviteID:${f} data:${s.data}`),f&&(Jo.updateSignaling(s),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:E,isSelfTimeout:!1})}))}_onInvitationModified(s,r){var g;const u=`${fr}._onInvitationModified`,{inviteID:E,data:f}=s,D=Jo.hasSignaling(E);this._core.ssoLog.debug("_onInvitationModified",`${u} inviteID:${E} data:${f}`),D&&(Jo.saveSignaling(E,Object.assign(Object.assign({},s),{signaling:r})),this._emitEvent({name:(g=this._core)===null||g===void 0?void 0:g.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:E,data:f}}))}_emitEvent(s){var r;(r=this._core)===null||r===void 0||r.notificationCenter.emitOuterEvent(s.name,s)}_generateBaseEmitData(s){const{inviteID:r,inviter:g,groupID:u,data:E}=s;return{inviteID:r,inviter:g,groupID:u,data:E||""}}_dispose(){var s,r,g;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),(g=this._core)===null||g===void 0||g.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},ia=new class{constructor(){this._offlineSignalingMap=new Map}init(s){this._core=s;const{notificationCenter:r,helper:g,constants:{InnerEvent:u,WORKFLOW_STEP:E,WORKFLOW_NAME:f}}=s;r.subscribeInnerEvent(u.DESTROY,this._dispose,this),r.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.registerWorkflowStep(f.SYNC_SERVER_INFO_AFTER_LOGIN,E.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(s){const{result:{unreadMessageMap:r}={}}=s||{};if(!(r?.size!==0&&Jo.getSignalingListenStatus()))return;const g=yr([...r.values()]);if(g.length!==0&&(g.forEach(u=>{this._handleC2CActionType(u)}),this._offlineSignalingMap.size>0)){const u=this._sortOfflineSignalingByTime();Ul.handleActionSignaling(u)}}_handleC2CActionType(s){const r=Lc(s);if(!r)return;const{actionType:g}=r;g===Pu?this._saveValidOfflineInvite(r,s):this._removeOfflineInvite(r)}_saveValidOfflineInvite(s,r){const{inviteID:g,inviteeList:u=[],timeout:E=0}=s,f=this._core.common.getCurrentUserID();if(!u.includes(f))return;const D=Date.now()/1e3-r.time;E>0&&D>E&&E!==0||this._offlineSignalingMap.set(g,Object.assign(Object.assign({},s),{signalingList:[r]}))}_removeOfflineInvite(s){const{inviteID:r=""}=s;this._offlineSignalingMap.has(r)&&this._offlineSignalingMap.delete(r)}_sortOfflineSignalingByTime(){let s=[];return this._offlineSignalingMap.forEach(r=>{s=[...s,...r.signalingList]}),s.sort((r,g)=>r.time-g.time)}_dispose(){var s,r;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};const uh={invite:{userID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0},timeout:{required:!1,rules:["number"],allowEmpty:!1},onlineUserOnly:{required:!1,rules:["boolean"],allowEmpty:!1},offlinePushInfo:{required:!1,rules:["object"],allowEmpty:!1}},cancel:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},accept:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},reject:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},modifyInvitation:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}}},ss={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var tu=new class{constructor(){this.name="Signaling"}install(s){eg.init(s),Ul.init(s),nc.init(s),Jo.init(s),ia.init(s),s.helper.registerValidateConfig({auth:ss,params:uh})}};const Wn=new class{init(s){this.core=s}};function Uc(s){let r;const{message:g}=Wn.core,{conversationID:u,messageID:E}=s;return r=g.messageDataHandler.getLocalMessageList(u).find(f=>f.ID===E),!r&&(r=g.messageDataHandler.getSparseMessageList(u).find(f=>f.ID===E)),r}function sc(s){return s.map(r=>{const{from:g,to:u,cloudCustomData:E,avatar:f,nick:D,ID:v,clientSequence:N,clientTime:P,messageRandom:W,messageSequence:nA,time:EA}=r;return{ClientSeq:N,CloudCustomData:E,From_Account:g,From_AccountHeadurl:f,From_AccountNick:D,Id:v,MsgBody:JSON.parse(JSON.stringify(r.transformElementsToServerFormat())),MsgClientTime:P,MsgRandom:W,Random:W,MsgSeq:nA,MsgTimeStamp:EA,ReceiverId:u,SenderId:g,To_Account:u}})}function Dr(s){var r;const{From_Account:g,From_AccountHeadurl:u,From_AccountNick:E,GroupId:f,MsgClientTime:D,ClientSeq:v,To_Account:N,MsgTimeStamp:P,TinyId:W,MsgRandom:nA,MsgSeq:EA}=s;return{from:g,avatar:u,nick:E,clientTime:D,time:P,tinyID:W,random:nA,sequence:EA,to:N,groupID:f,clientSequence:v,_elements:(r=s.MsgBody)===null||r===void 0?void 0:r.map(wA=>{const{MsgType:kA}=wA;return Wn.core.message.messageFactory.getElementClass(kA).parseServerPushElement(wA)})}}var Kr,tg;(function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_STREAM="TIMStreamElem"})(Kr||(Kr={})),function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"}(tg||(tg={}));const LE="MSG_REACTION",pC="MSG_EXT",Eh=0,uo=1,Fc={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},Fl="16k_zh",mC="16k_en",fC="16k_yue",Ol="16k_ja",iu="16k_zh-PY",yI={[Fc.ZH_CN]:Fl,[Fc.EN_US]:mC,[Fc.YUE_HK]:fC,[Fc.JA_JP]:Ol,[Fc.ZH_PY]:iu},DI=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,UE={READ:0,UNREAD:1},Pl=1,xl=2,Pg=3;var rc;(function(s){s.IN="in",s.OUT="out"})(rc||(rc={}));const yd=16,FE=17;var Oc;(function(s){s[s.DATA=0]="DATA",s[s.REVOKED=1]="REVOKED"})(Oc||(Oc={}));var ou;(function(s){s[s.NORMAL=0]="NORMAL",s[s.TIMEOUT=1]="TIMEOUT"})(ou||(ou={}));const ho="StreamMsg.PushStreamHttp";var OE=new class{constructor(){this._reactionsMap=new Map}init(s){this._core=s;const{helper:r,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:u},InnerEventSubType:{MESSAGE_REACTION_UPDATED:E,MESSAGE_REACTION_UPDATED_SYNC:f}}=s;r.registerApi({apiName:"addMessageReaction",context:this}),r.registerApi({apiName:"removeMessageReaction",context:this}),r.registerApi({apiName:"getMessageReactions",context:this}),r.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),g.subscribeInnerEvent(u,E,this._handleReactionUpdated,this),g.subscribeInnerEvent(u,f,this._handleReactionSync,this)}addMessageReaction(s,r){return mA(this,void 0,void 0,function*(){const{OuterConstant:g,ssoLog:u,helper:E}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:f,ID:D,conversationType:v,from:N,to:P,clientSequence:W,random:nA,time:EA,sequence:wA}=s,kA=`conversationID:${f} messageID:${D} reactionID:${r}`;try{return this._recordMessageReactedByMe(D,r),v===g.CONV_C2C?yield function(VA,LA){return mA(this,void 0,void 0,function*(){var SA;const{from:PA,to:zA,clientSequence:Ee,random:Ie,time:Li,reactionID:Ui}=VA,Yt={From_Account:PA,To_Account:zA,MsgKey:`${Ee}_${Ie}_${Li}`,Reaction:Ui,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Wn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:Yt})})}({from:N,to:P,clientSequence:W,random:nA,time:EA,reactionID:r},this._core):v===g.CONV_GROUP&&(yield function(VA,LA){return mA(this,void 0,void 0,function*(){var SA;const{to:PA,reactionID:zA,sequence:Ee}=VA,Ie={GroupId:PA,MsgSeq:Ee,Reaction:zA,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Wn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:Ie})})}({to:P,reactionID:r,sequence:wA},this._core)),{code:0,successLog:{message:kA}}}catch(VA){this._removeMyReactionRecord(D,r);const{errorCode:LA}=VA||{};throw new E.ChatError({functionName:"addMessageReaction",code:LA,moreMessage:kA})}})}removeMessageReaction(s,r){return mA(this,void 0,void 0,function*(){const{OuterConstant:g,helper:u}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:E,ID:f,conversationType:D,from:v,to:N,clientSequence:P,random:W,time:nA,sequence:EA}=s,wA=`conversationID:${E} messageID:${f} reactionID:${r}`;try{return this._removeMyReactionRecord(f,r),D===g.CONV_C2C?yield function(kA,VA){return mA(this,void 0,void 0,function*(){var LA;const{from:SA,to:PA,clientSequence:zA,random:Ee,time:Ie,reactionID:Li}=kA,Ui={From_Account:SA,To_Account:PA,MsgKey:`${zA}_${Ee}_${Ie}`,Reaction:Li,Del_Account:[(LA=VA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Wn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:Ui})})}({from:v,to:N,clientSequence:P,random:W,time:nA,reactionID:r},this._core):D===g.CONV_GROUP&&(yield function(kA,VA){return mA(this,void 0,void 0,function*(){var LA;const{to:SA,reactionID:PA,sequence:zA}=kA,Ee={GroupId:SA,MsgSeq:zA,Reaction:PA,Del_Account:[(LA=VA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Wn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:Ee},VA)})}({to:N,reactionID:r,sequence:EA},this._core)),{code:0,successLog:{message:wA}}}catch(kA){const{errorCode:VA}=kA||{};throw new u.ChatError({functionName:"removeMessageReaction",code:VA,moreMessage:wA})}})}getAllUserListOfMessageReaction(s){return mA(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();const{message:r,reactionID:g,nextSeq:u=0}=s,E=s.count>100?100:s.count,{conversationID:f}=r,{ssoLog:D,helper:v,constants:N}=this._core;try{let P=null;if(P=f.startsWith(N.OuterConstant.CONV_C2C)?yield function(W){return mA(this,void 0,void 0,function*(){const{message:nA,nextSeq:EA,reactionID:wA,count:kA}=W,{from:VA,to:LA,clientSequence:SA,random:PA,time:zA}=nA,Ee={Reaction:wA,NextSeq:EA,Count:kA,From_Account:VA,To_Account:LA,MsgKey:`${SA}_${PA}_${zA}`};return Wn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:Ee})})}({message:r,reactionID:g,nextSeq:u,count:E}):yield function(W){return mA(this,void 0,void 0,function*(){const{message:nA,nextSeq:EA,reactionID:wA,count:kA}=W,{sequence:VA,to:LA}=nA,SA={Reaction:wA,NextSeq:EA,GroupId:LA,Count:kA,MsgSeq:VA};return Wn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:SA})})}({message:r,reactionID:g,nextSeq:u,count:E}),P){const{Reaction_Account:W,NextSeq:nA}=P,EA=yield this._getUserProfileList(W);return{code:0,data:{nextSeq:nA,isCompleted:u===0,userList:EA}}}}catch(P){const{errorCode:W}=P||{};throw new v.ChatError({functionName:"getAllUserListOfMessageReaction",code:W})}})}getMessageReactions(s){return mA(this,void 0,void 0,function*(){const{constants:r}=this._core;this._validateMessageReactionBusinessCapability();const{messageList:g,maxUserCountPerReaction:u=10}=s,E=g[0];let f=null;const D=new Map,{from:v,to:N,conversationType:P}=E,W=this._generateMessageKeyList(g,D);P===r.OuterConstant.CONV_C2C?f=yield function(kA){return mA(this,void 0,void 0,function*(){const{from:VA,to:LA,messageKeyList:SA,maxUserCountPerReaction:PA}=kA,zA={From_Account:VA,To_Account:LA,MsgKeyList:SA,Count:PA};return Wn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:zA})})}({from:v,to:N,messageKeyList:W,maxUserCountPerReaction:u}):P===r.OuterConstant.CONV_GROUP&&(f=yield function(kA){return mA(this,void 0,void 0,function*(){const{groupId:VA,messageSequenceList:LA,maxUserCountPerReaction:SA}=kA,PA={GroupId:VA,MsgSeqList:LA,Count:SA};return Wn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:PA})})}({groupId:N,messageSequenceList:W,maxUserCountPerReaction:u}));const{Results:nA=[]}=f||{},EA=this._extractUserIDsFromReactionResults(nA),wA=yield this._getUserProfileMap(EA);return{code:0,data:{resultList:nA.map(kA=>{const{ReactionList:VA,MsgSeq:LA,MsgKey:SA}=kA;return{messageID:this._generateMessageID({messageSequence:LA,messageKey:SA,messageIDMap:D}),reactionList:VA.map(PA=>{const{Reaction:zA,Count:Ee,Reaction_Account:Ie,ReactedByMe:Li}=PA;return{reactionID:zA,totalUserCount:Ee,partialUserList:this._generatePartialUserInfo({userIDList:Ie,userProfileMap:wA}),reactedByMyself:Li===1}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(s){const r=[];return s?.forEach(g=>{const{ReactionList:u=[]}=g;u.forEach(E=>{E.Reaction_Account&&r.push(...E.Reaction_Account)})}),r}_getUserProfileList(s){return mA(this,void 0,void 0,function*(){var r;try{const g=yield(r=this._core.user.userProfile)===null||r===void 0?void 0:r.getUserProfile({userIDList:s});return g?g.data:[]}catch{return[]}})}_getUserProfileMap(s){return mA(this,void 0,void 0,function*(){const r=new Map;return(yield this._getUserProfileList(s)).forEach(g=>{const{nick:u,avatar:E,userID:f}=g;r.set(f,{nick:u,avatar:E,userID:f})}),r})}_recordMessageReactedByMe(s,r){const g=`${s}-${r}`;this._reactionsMap.has(g)?this._reactionsMap.get(g).reactedByMe=!0:this._reactionsMap.set(g,{reactedByMe:!0})}_removeMyReactionRecord(s,r){const g=`${s}-${r}`;this._reactionsMap.has(g)&&(this._reactionsMap.get(g).reactedByMe=!1)}_recordMessageReactionInfo(s){const{messageID:r,reactionID:g,reactionInfo:u}=s,E=`${r}-${g}`,f=this._reactionsMap.get(E)||{};this._reactionsMap.set(E,Object.assign(Object.assign({},f),u))}_validateMessageReactionBusinessCapability(){const{helper:s,constants:r}=this._core;if(!s.checkBusinessCapabilityBits(LE))throw new s.ChatError({functionName:"addMessageReaction",code:r.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(s){const{MsgReactionNotifyList:r}=s,{notificationCenter:g,constants:u}=this._core;r.forEach(E=>mA(this,void 0,void 0,function*(){const{C2CMsgInfo:f,GroupMsgInfo:D,MsgReactionSummary:v}=E,{TinyId:N,MsgClientTime:P,MsgRandom:W}=Object.assign(Object.assign({},f),D),nA=`${N}-${P}-${W}`,EA=this._extractUserIDsFromReactionResults([{ReactionList:v}]),wA=yield this._getUserProfileMap(EA),kA=v.map(VA=>{var LA;const{Reaction:SA,Reaction_Account:PA}=VA,zA=this._generatePartialUserInfo({userIDList:PA,userProfileMap:wA}),Ee=PA?VA.Count:0,Ie=((LA=this._reactionsMap.get(`${nA}-${SA}`))===null||LA===void 0?void 0:LA.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:nA,reactionID:SA,reactionInfo:{reactionID:SA,totalUserCount:Ee,partialUserList:zA}}),{reactionID:SA,totalUserCount:Ee,partialUserList:zA,reactedByMyself:Ie}});g.emitOuterEvent(u.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:u.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:nA,reactionList:kA}})}))}_handleReactionSync(s){var r;const{notificationCenter:g,constants:u}=this._core,{C2CMsgInfo:E={},GroupMsgInfo:f={},Reaction:D,OperateType:v}=s.MsgReactionNotify,{TinyId:N="",MsgClientTime:P=0,MsgRandom:W=0}=Object.assign(Object.assign({},E),f),nA=`${N}-${P}-${W}`,EA=`${nA}-${D}`;if(v===1?this._recordMessageReactedByMe(nA,D):this._removeMyReactionRecord(nA,D),(r=this._reactionsMap.get(EA))===null||r===void 0?void 0:r.reactionID){const wA=this._reactionsMap.get(EA);wA.reactedByMyself=v===1,g.emitOuterEvent(u.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:u.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:nA,reactionList:[wA]}})}}_generatePartialUserInfo({userIDList:s,userProfileMap:r}){const g=[];return s?.forEach(u=>{r.has(u)&&g.push(r.get(u))}),g}_generateMessageID(s){const{messageSequence:r,messageKey:g,messageIDMap:u}=s;return g?u.get(g):u.get(r)}_generateMessageKeyList(s,r){const{constants:g}=this._core,u=s[0],{conversationType:E}=u;let f=[];return E===g.OuterConstant.CONV_C2C?f=s.map(D=>{const{clientSequence:v,random:N,time:P,ID:W}=D,nA=`${v}_${N}_${P}`;return r.set(nA,W),nA}):E===g.OuterConstant.CONV_GROUP&&(f=s.map(D=>{const{ID:v,sequence:N}=D;return r.set(N,v),N})),f}},ig=new class{init(s){this._core=s;const{helper:r,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:u,GROUP_MESSAGE_READ_RECEIPT:E},notificationCenter:f}=s;r.registerApi({apiName:"sendMessageReadReceipt",context:this}),r.registerApi({apiName:"getMessageReadReceiptList",context:this}),r.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),f.subscribeInnerEvent(g,u,this._handleC2CMessageReadReceipt,this),f.subscribeInnerEvent(g,E,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(s){return mA(this,void 0,void 0,function*(){var r;const{common:g,constants:u}=this._core,E=this._filterValidMessageSendByOther(s);if(E.length===0)throw new g.ChatError({code:u.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:f}=E[0];return f===u.OuterConstant.CONV_C2C?yield function(D){return mA(this,void 0,void 0,function*(){const{common:v,constants:N}=Wn.core,P=D[0].conversationID.replace(N.OuterConstant.CONV_C2C,""),W=D.map(EA=>{const{from:wA,to:kA,sequence:VA,random:LA,time:SA,clientTime:PA}=EA;return{From_Account:wA,To_Account:kA,MsgSeq:VA,MsgRandom:LA,MsgTime:SA,MsgClientTime:PA}}),nA={Peer_Account:P,C2CMsgInfo:W};return v.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:nA})})}(E):yield function(D){return mA(this,void 0,void 0,function*(){const{common:v,constants:N}=Wn.core,P={GroupId:D[0].conversationID.replace(N.OuterConstant.CONV_GROUP,""),MsgSeqList:D.map(W=>({MsgSeq:W.sequence}))};return v.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:P})})}(E),{code:0,data:{}}}catch(f){const{errorCode:D,errorInfo:v}=f;throw new g.ChatError({code:D,message:v,moreMessage:`peerAccount:${(r=E?.[0])===null||r===void 0?void 0:r.conversationID}`})}})}getMessageReadReceiptList(s){return mA(this,void 0,void 0,function*(){const{common:r,constants:g}=this._core;try{const{conversationType:u}=s[0];if(u===g.OuterConstant.CONV_GROUP){const E=this._filterValidMessageSendByMe(s);if(E?.length>0){const f=yield function(v){return mA(this,void 0,void 0,function*(){const{common:N,constants:P}=Wn.core,W={GroupId:v[0].conversationID.replace(P.OuterConstant.CONV_GROUP,""),MsgSeqList:v.map(nA=>({MsgSeq:nA.sequence}))};return N.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:W})})}(E),{GroupMsgReceiptList:D}=f||{};this._updateGroupMessagesReadReceiptInfo({messageList:s,readReceiptList:D})}}return{code:0,data:{messageList:s}}}catch(u){const{errorCode:E,errorInfo:f}=u;throw new r.ChatError({code:E,message:f})}})}getGroupMessageReadMemberList(s){return mA(this,void 0,void 0,function*(){const{constants:r,common:g}=this._core,{message:u,filter:E=UE.READ,cursor:f=""}=s,{conversationID:D,sequence:v,ID:N}=u,P=D.replace(r.OuterConstant.CONV_GROUP,""),W=s.count>=100?100:s.count;try{const nA=yield function(EA){return mA(this,void 0,void 0,function*(){const{sequence:wA,groupID:kA,filter:VA,cursor:LA,count:SA}=EA,PA={MsgSeq:wA,GroupId:kA,Filter:VA,Cursor:LA,Num:SA};return Wn.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:PA})})}({groupID:P,sequence:v,filter:E,cursor:f,count:W});if(nA){const{Cursor:EA,IsFinish:wA,UnreadList:kA,ReadList:VA}=nA,LA={cursor:EA,isCompleted:wA===1,messageID:N,unreadUserIDList:[],readUserIDList:[]};return E===UE.READ?LA.readUserIDList=VA.map(SA=>SA.Read_Account):E===UE.UNREAD&&(LA.unreadUserIDList=kA.map(SA=>SA.Unread_Account)),{code:0,data:LA}}}catch(nA){const{errorCode:EA,errorInfo:wA}=nA;throw new g.ChatError({code:EA,message:wA})}})}_handleC2CMessageReadReceipt(s){const r=[],{constants:g,helper:u}=this._core,{C2cMsgInfo:E,PeerReadTime:f,Peer_Account:D}=s;if(u.isEmpty(E))return;const v=`${g.OuterConstant.CONV_C2C}${D}`;E?.forEach(N=>{const{TinyId:P,MsgClientTime:W,MsgRandom:nA}=N,EA=`${P}-${W}-${nA}`,wA=Uc({conversationID:v,messageID:EA});wA&&!wA.readReceiptInfo.isPeerRead&&(wA.readReceiptInfo.isPeerRead=!0,wA.readReceiptInfo.timestamp=f,r.push({userID:D,messageID:EA,isPeerRead:!0,timestamp:f}))}),this._emitReadReceiptEventIfNeed(r)}_updateGroupMessagesReadReceiptInfo(s){const{messageList:r,readReceiptList:g}=s,u=new Map;r.forEach(E=>{u.set(E.sequence,E)}),g?.forEach(E=>{if(E.Code===0){const{MsgSeq:f,ReadNum:D,UnreadNum:v}=E,N=u.get(f);N&&(N.readReceiptInfo.readCount=D,N.readReceiptInfo.unreadCount=v)}})}_handleGroupMessageReadReceipt(s){const r=[],{constants:g}=this._core,{GroupTips:u}=s;u.forEach(E=>{const{MsgBody:{GroupMsgReceiptList:f},GroupInfo:{GroupId:D}}=E,v=`${g.OuterConstant.CONV_GROUP}${D}`;f?.forEach(N=>{const{TinyId:P,MsgClientTime:W,MsgRandom:nA,ReadNum:EA,UnreadNum:wA}=N,kA=`${P}-${W}-${nA}`,VA=Uc({conversationID:v,messageID:kA}),LA={groupID:D,messageID:kA,readCount:0,unreadCount:0};VA&&(typeof EA=="number"&&(VA.readReceiptInfo.readCount=EA,LA.readCount=EA),typeof wA=="number"&&(VA.readReceiptInfo.unreadCount=wA,LA.unreadCount=wA),r.push(LA))})}),this._emitReadReceiptEventIfNeed(r)}_emitReadReceiptEventIfNeed(s){const{notificationCenter:r,OuterEvent:g}=this._core;s.length>0&&r.emitOuterEvent(g.MESSAGE_READ_RECEIPT_RECEIVED,{name:g.MESSAGE_READ_RECEIPT_RECEIVED,data:s})}_filterValidMessageSendByOther(s){return this._filterNeedReadReceiptMessages(s).filter(r=>{const{from:g}=r;return g!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(s){const{OuterConstant:r}=this._core.constants;return this._filterNeedReadReceiptMessages(s).filter(g=>{const{from:u,status:E}=g;return u===this._core.common.getCurrentUserID()&&E===r.MessageStatus.SUCCESS})}_filterNeedReadReceiptMessages(s){return s.filter(r=>r.needReadReceipt===!0)}dispose(){const{InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:r,GROUP_MESSAGE_READ_RECEIPT:g},notificationCenter:u}=this._core;u.unSubscribeInnerEvent(s,r,this._handleC2CMessageReadReceipt,this),u.unSubscribeInnerEvent(s,g,this._handleGroupMessageReadReceipt,this)}};function nu(s,r,g){return mA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:u}}=Wn.core,{from:E,to:f,clientSequence:D,random:v,time:N}=s;return u({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:E,To_Account:f,MsgKey:`${D}_${v}_${N}`,OperateType:g,ExtensionList:r}})})}function Yu(s,r,g){return mA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:u}}=Wn.core,{to:E,sequence:f}=s;return u({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:E,MsgSeq:f,OperateType:g,ExtensionList:r}})})}var Pc=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(s){this._core=s;const{notificationCenter:r,helper:{registerApi:g},InnerEvent:{MESSAGE_PUSH:u,LOGOUT:E},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:f}}=s;g({apiName:"setMessageExtensions",context:this}),g({apiName:"getMessageExtensions",context:this}),g({apiName:"deleteMessageExtensions",context:this}),r.subscribeInnerEvent(u,f,this._handleMessageExtensionsNotify,this),r.subscribeInnerEvent(E,this.reset,this)}setMessageExtensions(s,r){return mA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");const{constants:{OuterConstant:g},ssoLog:u}=this._core,{ID:E,conversationID:f,sequence:D,time:v,conversationType:N}=s;let P=r;r.length>20&&(P=r.slice(0,20),u.warn("setMessageExtensions","the length of extensions cannot exceed 20"));const W=this._generateServerExtensions(s,P),nA=`convID:${f} messageID:${E} sequence:${D} time:${v} count:${P.length}`;try{let EA;if(N===g.CONV_C2C?EA=yield nu(s,W,Pl):N===g.CONV_GROUP&&(EA=yield Yu(s,W,Pl)),EA){const{resultList:wA,successCount:kA,failureCount:VA}=this._handleModifyMessageExtensions(s,EA);return{code:0,data:{extensions:wA},successLog:{message:`${nA} successCount:${kA} failCount:${VA}`}}}return{code:0,data:{extensions:[]}}}catch(EA){const{errorCode:wA}=EA;throw new this._core.helper.ChatError({functionName:"setMessageExtensions",code:wA,moreMessage:nA})}})}getMessageExtensions(s){return mA(this,void 0,void 0,function*(){const{utils:{isUndefined:r}}=this._core;this._validateMessageExtensionBusinessCapability("getMessageExtensions");const{conversationID:g,ID:u,sequence:E,time:f}=s,D=`convID:${g} messageID:${u} sequence:${E} time:${f}`;try{let v;this._completedFetchExtensions.has(u)&&(v=this._extensionsLatestSequenceMap.get(u));const N=yield this._fetchMessageExtensions(s,v);return r(v)&&N.length>1&&this._completedFetchExtensions.add(u),{code:0,data:{extensions:N},successLog:{message:D}}}catch(v){const{errorCode:N,errorInfo:P=""}=v||{};throw new this._core.common.ChatError({code:N,message:P,moreMessage:D})}})}deleteMessageExtensions(s,r){return mA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");const{utils:{isEmpty:g},constants:{OuterConstant:u}}=this._core,{conversationType:E,conversationID:f,sequence:D,ID:v,time:N}=s;let P=Pg;const W=[];g(r)||(P=xl,r?.forEach(wA=>{W.push({key:wA,value:"",seq:0})}));const nA=`convID:${f} messageID:${v} sequence:${D} time:${N} operateType:${P}`,EA=this._generateServerExtensions(s,W);try{let wA;if(E===u.CONV_C2C?wA=yield nu(s,EA,P):E===u.CONV_GROUP&&(wA=yield Yu(s,EA,P)),wA){const{resultList:kA,successCount:VA,failureCount:LA}=this._handleModifyMessageExtensions(s,wA);return{code:0,data:{extensions:kA},successLog:{message:`${nA}successCount:${VA} failCount:${LA}`}}}return{code:0,data:{extensions:[]}}}catch(wA){const{errorCode:kA}=wA;throw new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:kA,moreMessage:nA})}})}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:r,LOGOUT:g},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:u}}=this._core;s.unSubscribeInnerEvent(r,u,this._handleMessageExtensionsNotify,this),s.subscribeInnerEvent(g,this.reset,this)}_handleModifyMessageExtensions(s,r){const{ID:g}=s,{Seq:u}=r,E=r.ExtensionList||[],f=[];let D=0,v=0,N=[];return E.forEach(P=>{const{ErrorCode:W,Extension:nA}=P,{Key:EA,Value:wA,Seq:kA}=nA;f.push({code:W,key:EA,value:wA}),W===0?D++:v++,N.push({key:EA,value:wA,seq:kA})}),this._extensionsLatestSequenceMap.set(g,u),N.length>0&&this._updateLocalExtensions(s.ID,N),{resultList:f,successCount:D,failureCount:v}}_updateLocalExtensions(s,r){this._messageExtensionsMap.has(s)||this._messageExtensionsMap.set(s,new Map);const g=this._messageExtensionsMap.get(s);r?.forEach(u=>{const{key:E,seq:f,value:D=""}=u;g?.set(E,{value:D,seq:f})})}_fetchMessageExtensions(s,r){return mA(this,void 0,void 0,function*(){const{constants:{OuterConstant:g},utils:{isEmpty:u}}=this._core;try{let E;const{conversationType:f,ID:D}=s;if(f===g.CONV_C2C?E=yield function(v,N){const{common:{buildAndSendPacket:P}}=Wn.core,{from:W,to:nA,clientSequence:EA,random:wA,time:kA}=v;return P({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:W,To_Account:nA,MsgKey:`${EA}_${wA}_${kA}`,StartSeq:N}})}(s,r):f===g.CONV_GROUP&&(E=yield function(v,N){const{common:{buildAndSendPacket:P}}=Wn.core,{to:W,sequence:nA}=v;return P({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:W,MsgSeq:nA,StartSeq:N}})}(s,r)),E){const{LatestSeq:v,ClearSeq:N,CompleteFlag:P}=E,W=(E.ExtensionList||[]).map(EA=>({key:EA.Key,value:EA.Value,seq:EA.Seq}));if(this._updateLocalExtensions(D,W),this._clearLocationExtensions(D,N),this._extensionsLatestSequenceMap.set(D,v),P!==1){const EA=W[W.length-1].seq+1;return this._fetchMessageExtensions(s,EA)}const nA=[];if(this._messageExtensionsMap.has(D)){const EA=this._messageExtensionsMap.get(D);EA?.forEach((wA,kA)=>{const{value:VA}=wA;u(VA)||nA.push({key:kA,value:VA})})}return nA}}catch(E){throw E}})}_clearLocationExtensions(s,r){if(!(r<=0)&&this._messageExtensionsMap.has(s)){const g=this._messageExtensionsMap.get(s);g?.forEach((u,E)=>{u.seq<=r&&g.delete(E)})}}_generateServerExtensions(s,r){const{ID:g}=s;if(this._messageExtensionsMap.has(g)){const u=this._messageExtensionsMap.get(g);return r.map(E=>{var f;const{key:D,value:v}=E;let N=0;return u?.has(D)&&(N=(f=u.get(D))===null||f===void 0?void 0:f.seq),{Key:D,Value:v,Seq:N}})}return r.map(u=>({Key:u.key,Value:u.value,Seq:0}))}_validateMessageExtensionBusinessCapability(s){const{helper:r,constants:g}=this._core;if(!r.checkBusinessCapabilityBits(pC))throw new r.ChatError({functionName:s,code:g.ERROR_CODE.NO_USE,replacement1:s})}_handleMessageExtensionsNotify(s){const{SetKVInfo:r,DeleteKVInfo:g,ClearKVInfo:u,MsgOptType:E,TinyId:f,MsgLastSeq:D,ExtensionC2cMsgInfo:v,ExtensionGroupMsgInfo:N}=s?.MsgExtensionNotify||{},P=v||N||{},{MsgClientTime:W,MsgRandom:nA}=P,EA=`${f}-${W}-${nA}`;this._extensionsLatestSequenceMap.set(EA,D),E===Pl?this._handleMessageExtensionsUpdated({messageID:EA,updateMessageExtensionsInfo:r}):E===xl?this._handleMessageExtensionsDeleted({messageID:EA,deleteMessageExtensionsInfo:g}):E===Pg&&this._handleMessageExtensionsCleared({messageID:EA,clearMessageExtensionsInfo:u})}_handleMessageExtensionsUpdated(s){const{notificationCenter:r,OuterEvent:g}=this._core,{messageID:u,updateMessageExtensionsInfo:E=[]}=s,f=[];E.forEach(D=>{const{MsgKeyValue:v=[]}=D,N=v.map(P=>(f.push({key:P.Key,value:P.Value}),{key:P.Key,value:P.Value,seq:P.Seq}));this._updateLocalExtensions(u,N)}),r.emitOuterEvent(g.MESSAGE_EXTENSIONS_UPDATED,{name:g.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:u,extensions:f}})}_handleMessageExtensionsDeleted(s){const{notificationCenter:r,OuterEvent:g}=this._core,{messageID:u,deleteMessageExtensionsInfo:E=[]}=s,f=[];E.forEach(D=>{const{MsgKeyValue:v=[]}=D,N=v.map(P=>(f.push(P.Key),{key:P.Key,seq:P.Seq}));this._updateLocalExtensions(u,N)}),r.emitOuterEvent(g.MESSAGE_EXTENSIONS_DELETED,{name:g.MESSAGE_EXTENSIONS_DELETED,data:{messageID:u,keyList:f}})}_handleMessageExtensionsCleared(s){const{notificationCenter:r,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:g},utils:{isEmpty:u}}=this._core,{messageID:E,clearMessageExtensionsInfo:f=[]}=s,D=[];f.forEach(v=>{const{ClearMsgSeq:N}=v;this._messageExtensionsMap.has(E)&&(this._messageExtensionsMap.get(E)||[]).forEach((P,W)=>{P.seq<=N&&!u(P.value)&&D.push(W)}),this._clearLocationExtensions(E,N)}),r.emitOuterEvent(g,{name:g,data:{messageID:E,keyList:D}})}};const SI={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{constants:{OuterConstant:r}}=Wn.core;return s.status!==r.MessageStatus.SUCCESS?"message is not success":s.isSupportExtension===!0||"message is not support extension"}},ll={setMessageExtensions:[SI,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[SI],deleteMessageExtensions:[SI]},Il=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const r=function(g){var u;return typeof g?.text!="string"||typeof g.text=="string"&&((u=g?.text)===null||u===void 0?void 0:u.length)===0?"payload.text is invalid.":!0}(s);return r!==!0?r:!(s?.atUserList&&!Array.isArray(s.atUserList))||"atUserList should be an array or undefind."}}},findMessage:[{required:!0,rules:["string"],allowEmpty:!1}],translateText:{sourceTextList:{required:!0,rules:["array"],allowEmpty:!1},sourceLanguage:{required:!0,rules:["string"],allowEmpty:!1},targetLanguage:{required:!0,rules:["string"],allowEmpty:!1}},createForwardMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!s.startsWith("C2C")&&!s.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1}},createLocationMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{utils:{isString:r,isNumber:g}}=Wn.core;return r(s?.description)?g(s?.longitude)?!!g(s?.latitude)||"payload.latitude must be a number.":"payload.longitude must be a number.":"payload.description must be a string."}}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s!="number"?"maxUserCountPerReaction is invalid.":!(s<0||s>10)||"maxUserCountPerReaction should between [0, 10]."}},getAllUserListOfMessageReaction:{message:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>s.status==="success"||"message is invalid."},reactionID:{required:!0,rules:["string"],allowEmpty:!1},nextSeq:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["object"],allowEmpty:!1},filter:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),ll),{pinGroupMessage:{groupID:{required:!0,rules:["string"],allowEmpty:!1},message:{required:!0,rules:["object"],allowEmpty:!1},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},getPinnedGroupMessageList:[{key:"groupID",required:!0,rules:["string"],allowEmpty:!1}]}),{createQuoteMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"quotedMessage",required:!0,rules:["object"],allowEmpty:!1}]}),qa=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0,createLocationMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0,getAllUserListOfMessageReaction:!0}),{sendMessageReadReceipt:!0,getMessageReadReceiptList:!0,getGroupMessageReadMemberList:!0}),{setMessageExtensions:!0,getMessageExtensions:!0,deleteMessageExtensions:!0}),{pinGroupMessage:!0,getPinnedGroupMessageList:!0}),{createQuoteMessage:!0});class PE{constructor(r){this._core=r}deleteMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:u}=r,E={From_Account:this._core.common.getCurrentUserID(),To_Account:g,MsgKeyList:u};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:E})})}revokeMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,from:u,sequence:E,time:f,random:D}=r,v={MsgInfo:{From_Account:u,To_Account:g,MsgSeq:E,MsgRandom:D,MsgTimeStamp:f}};return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:v})})}}class la{constructor(r){this._core=r}deleteMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:u}=r,E={GroupId:g,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:u};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:E})})}revokeMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,sequence:u}=r,E={GroupId:g,MsgSeqList:[{MsgSeq:u}]};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:E})})}}const Gs=2116;class Or{constructor(r){this._core=r}generateRevokeMessage(r){const{conversationID:g,sequence:u,random:E,tinyID:f,clientTime:D,revokeReason:v,revoker:N}=r;let P={};const{messageDataHandler:W}=this._core.message;return P=W.revokeMessage({conversationID:g,sequence:u,random:E,revoker:N}),P||(P={conversationID:g,sequence:u},f&&D&&E&&(P.ID=`${f}-${D}-${E}`)),P.revoker=N,P.revokeReason=v,P.revokerInfo={userID:N,nick:"",avatar:""},P}updateRevokerInfo(r){return mA(this,void 0,void 0,function*(){const g=r.map(u=>u.revoker);try{const u=yield this._fetchUserInfos(g);u&&r.forEach(E=>{const{revoker:f}=E;u[f]&&(E.revokerInfo.nick=u[f].nick||"",E.revokerInfo.avatar=u[f].avatar||"",E.revokerInfo.userID=f)})}catch(u){console.debug(u)}})}_fetchUserInfos(r){return mA(this,void 0,void 0,function*(){var g,u;const E=yield(g=this._core.user.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:r});return E?.data?(u=E.data)===null||u===void 0?void 0:u.reduce((f,{userID:D,nick:v,avatar:N})=>(f[D]={nick:v||"",avatar:N||""},f),{}):null})}}var ul=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(s){this._core=s,this._groupMessageAction=new la(s),this._c2cMessageAction=new PE(s),this._messageHelper=new Or(s);const{helper:r}=s;r.registerApi({apiName:"deleteMessage",context:this}),r.registerApi({apiName:"revokeMessage",context:this}),r.registerApi({apiName:"resendMessage",context:this}),r.registerApi({apiName:"findMessage",context:this}),r.registerApi({apiName:"createQuoteMessage",context:this})}deleteMessage(s){return mA(this,void 0,void 0,function*(){let r=[],g=[];const{conversationID:u,conversationType:E}=s[0],f=u.replace(E,"");if(E==="@TIM#SYSTEM")throw new this._core.helper.ChatError({code:Gs});if(s.forEach(D=>{const{conversationID:v,conversationType:N,status:P,_onlineOnlyFlag:W,sequence:nA,random:EA,time:wA}=D||{};if(P==="success"&&v===u&&N===E){if(!W){const kA=N==="C2C"?`${nA}_${EA}_${wA}`:String(nA);r.push(kA)}g.push(D)}}),r.length===0)return this._handleDeleteMessageSuccess(g),{code:0,data:{messageList:g}};r.length>30&&(r=r.slice(0,30),g=g.slice(0,30));try{return E==="C2C"?yield this._c2cMessageAction.deleteMessage({to:f,messageIdentifiers:r}):yield this._groupMessageAction.deleteMessage({to:f,messageIdentifiers:r}),this._handleDeleteMessageSuccess(g),{code:0,data:{messageList:g}}}catch(D){const{utils:{safeStringify:v}}=this._core,{errorCode:N,errorInfo:P}=D;throw new this._core.helper.ChatError({functionName:"deleteMessage",code:N,message:P,moreMessage:`messageIdentifiers: ${v(r)}`})}})}revokeMessage(s){return mA(this,void 0,void 0,function*(){var r;const{conversationType:g,isRevoked:u,ID:E,type:f,from:D,to:v}=s;let N=null;const P=`type:${f} from:${D} to:${v} ID:${E}`;if(g==="@TIM#SYSTEM")throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(u)throw new this._core.helper.ChatError({message:"message has been revoked",moreMessage:P});try{if(N=g==="C2C"?yield this._c2cMessageAction.revokeMessage(s):yield this._groupMessageAction.revokeMessage(s),N){const{RecallRetList:W}=N,nA=((r=W?.[0])===null||r===void 0?void 0:r.RetCode)||0;if(nA!==0)throw new this._core.helper.ChatError({code:nA,moreMessage:P});return s.isRevoked=!0,yield this._handleRevokeMessageSuccess(s),{code:0,data:{message:s},successLog:{message:P}}}}catch(W){const{errorCode:nA}=W;throw new this._core.helper.ChatError({functionName:"revokeMessage",code:nA,moreMessage:P})}})}resendMessage(s,r){return mA(this,void 0,void 0,function*(){var g,u;return s.isResend=!0,s.status="unSend",(u=(g=this._core)===null||g===void 0?void 0:g.apiMap)===null||u===void 0?void 0:u.sendMessage(s,r)})}findMessage(s){return this._core.message.messageDataHandler.findMessage(s)}createQuoteMessage(s,r){const{ID:g,time:u,sequence:E}=r;return s.quoteInfo={msgID:g,messageTime:u,messageSequence:E},s}_handleDeleteMessageSuccess(s){if(s.length===0)return;const{message:{messageDataHandler:r},common:{isTopic:g},notificationCenter:u,InnerEvent:E}=this._core;s.forEach(D=>{D.isDeleted=!0;const v=r.getLocalMessageList(D.conversationID);v?.forEach(N=>{N.ID===D.ID&&(N.isDeleted=!0)})});const{conversationID:f=""}=s[0];g(f)?u.emitInnerEvent(E.TOPIC_MESSAGE_DELETED,f):u.emitInnerEvent(E.MESSAGE_DELETED,f)}_handleRevokeMessageSuccess(s){return mA(this,void 0,void 0,function*(){var r;const g=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,{conversationID:u,sequence:E,random:f}=s;this._core.message.messageDataHandler.revokeMessage({conversationID:u,sequence:E,random:f,revoker:g}),yield this._messageHelper.updateRevokerInfo([s])})}};class Yl{static parseServerPushElement(r){const{MsgContent:g={}}=r,{Index:u,Data:E}=g;return new Yl({index:u,data:E})}constructor(r){this.type=Kr.MSG_FACE;const{index:g,data:u}=r;this.content={index:g,data:u}}validateBeforeSend(){var r,g;return typeof((r=this.content)===null||r===void 0?void 0:r.index)=="number"&&typeof((g=this.content)===null||g===void 0?void 0:g.data)=="string"?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{index:E,data:f}=u;return{MsgType:this.type,MsgContent:{Index:E,Data:f}}}}class xc{static parseServerPushElement(r){const{MsgContent:g={}}=r,{Desc:u,Longitude:E,Latitude:f}=g;return new xc({description:u,longitude:E,latitude:f})}constructor(r){this.type=Kr.MSG_LOCATION;const{description:g,longitude:u,latitude:E}=r;this.content={description:g,longitude:u,latitude:E}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{description:E,longitude:f,latitude:D}=u;return{MsgType:this.type,MsgContent:{Desc:E,Longitude:f,Latitude:D}}}}class xE{static parseServerPushElement(r){const{MsgContent:g={}}=r,{StreamMsgID:u,CompatibleText:E,Markdown:f,BinaryData:D,ErrorCode:v,ErrorMsg:N}=g;return new xE({streamMessageID:u,compatibleText:E,markdown:f,binaryData:D,errorCode:v,errorMessage:N})}constructor(r){this.type=Kr.MSG_STREAM,this.content={streamMessageID:"",compatibleText:"",errorCode:0,errorMessage:"",isStreamEnded:!1},this._chunks=[],this._latestIndex=0;const{streamMessageID:g,compatibleText:u,markdown:E,binaryData:f,errorCode:D=0,errorMessage:v="",isStreamEnded:N=!1,chunks:P=[],latestIndex:W=0}=r;this.content.streamMessageID=g,this.content.compatibleText=u,this.content.markdown=E,this.content.binaryData=f,this.content.errorCode=D,this.content.errorMessage=v,this.content.isStreamEnded=N,this.content.chunks=P,this.content.latestIndex=W}updateChunks(r){if(!r||r.length===0)return;const g=r.sort((f,D)=>f.index-D.index),u=this._getMaxRevokedChunkIndex(g);u>=0&&(this._chunks=[],this._latestIndex=u,this._updateContent());const E=this._getValidChunks(g);if(E.length!==0&&(this._mergeAndSortChunks(E),this._chunks.length>0)){const f=this._chunks[this._chunks.length-1];this._latestIndex=f.index,this._updateContent(),this.content.isStreamEnded=f.isLast}}getLatestIndex(){return this._latestIndex}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{streamMessageID:E,chunks:f}=u,D=f?.map(v=>({EventType:v.eventType||"data",Index:v.index,Markdown:v.markdown,IsLast:v.isLast}));return{MsgType:this.type,MsgContent:{StreamMsgID:E,Chunks:D}}}validateBeforeSend(){var r,g;return((g=(r=this.content)===null||r===void 0?void 0:r.chunks)===null||g===void 0?void 0:g.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}_filterContinuousChunks(r,g){if(r.length===0)return[];const u=[];let E=g;for(const f of r){if(f.index>E)break;f.index===E&&(u.push(f),E++)}return u}_mergeAndSortChunks(r){const g=new Map;this._chunks.forEach(u=>{g.set(u.index,u)}),r.forEach(u=>{g.set(u.index,u)}),this._chunks=Array.from(g.values()).sort((u,E)=>u.index-E.index)}_updateContent(){this.content.markdown=this._chunks.map(g=>g.markdown).join("");const r=this._chunks.map(g=>g.binaryData).filter(g=>g?.length>0);if(r.length===0)this.content.binaryData=new Uint8Array(0);else if(r.length===1)this.content.binaryData=r[0];else{const g=r.reduce((f,D)=>f+D.length,0),u=new Uint8Array(g);let E=0;for(const f of r)u.set(f,E),E+=f.length;this.content.binaryData=u}}_getMaxRevokedChunkIndex(r){let g=-1;for(let u=0;ug&&(g=E.index)}return g}_getValidChunks(r){const g=r.filter(u=>u.eventType===Oc.DATA&&u.index>this._latestIndex);return this._filterContinuousChunks(g,this._latestIndex+1)}}var Yc=new class{init(s){this._core=s,s.message.messageFactory.registerElementClass(Kr.MSG_FACE,Yl),s.message.messageFactory.registerElementClass(Kr.MSG_LOCATION,xc),s.message.messageFactory.registerElementClass(Kr.MSG_STREAM,xE),s.helper.registerApi({apiName:"createFaceMessage",context:this}),s.helper.registerApi({apiName:"createTextAtMessage",context:this}),s.helper.registerApi({apiName:"createForwardMessage",context:this}),s.helper.registerApi({apiName:"createLocationMessage",context:this})}createFaceMessage(s){if(!s)return null;const{index:r,data:g}=s?.payload||{},u=new Yl({index:r,data:g}),E=this._core.common.getCurrentUserID(),f=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return f.setElement(u),f}createTextAtMessage(s){const{atUserList:r}=s?.payload||{},g=this._core.apiMap.createTextMessage(s),{OuterConstant:u}=this._core;if(!g)return null;if(Array.isArray(r)){const E=[],f=[];r.forEach(D=>{D!==u.MSG_AT_ALL?(E.push({GroupAtAllFlag:Eh,GroupAt_Account:D}),f.push(D)):(E.push({GroupAtAllFlag:uo}),f.push(u.MSG_AT_ALL))}),g._groupAtInfoList=E,g.atUserList=f}return g}createForwardMessage(s){const{helper:r,OuterConstant:g}=this._core,{to:u,conversationType:E,priority:f,payload:D,needReadReceipt:v,receiverList:N,cloudCustomData:P="",isSupportExtension:W=!1}=s;if(!Array.isArray(D._elements))throw new r.ChatError({functionName:"createForwardMessage",code:2454});if(D.type===g.MSG_GRP_TIP)throw new r.ChatError({functionName:"createForwardMessage",code:2453});const nA=this._core.common.getCurrentUserID(),EA=this._core.message.messageFactory.createMessage({to:u,from:nA,conversationType:E,isPlaceMessage:0,priority:f,payload:D,needReadReceipt:v,isSupportExtension:W,cloudCustomData:P,receiverList:N});return EA.setRelayFlag(!0),EA.setElement(D._elements[0]),EA}createLocationMessage(s){if(!s)return null;const{description:r,longitude:g,latitude:u}=s?.payload||{},E=new xc({description:r,longitude:g,latitude:u}),f=this._core.common.getCurrentUserID(),D=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:f}));return D.setElement(E),D}};let Vu=class{init(s){this._messageHelper=new Or(s),this._core=s;const{notificationCenter:r,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_REVOKED_MESSAGE:u},helper:{registerWorkflowStep:E},constants:{WORKFLOW_NAME:f,WORKFLOW_STEP:D}}=s;r.subscribeInnerEvent(g,u,this._handleC2CNotifyMessage,this),E(f.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(s){const{C2cNotifyMsgArray:r}=s;r?.forEach(g=>{Object.keys(g).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(g)})}_handleC2CRevokeMessage(s){return mA(this,void 0,void 0,function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:r}}=s;yield this._parseAndEmitC2CRevokedMessages(r)}catch(r){console.debug(r)}})}_parseAndEmitC2CRevokedMessages(s){return mA(this,void 0,void 0,function*(){const r=[],{notificationCenter:g,OuterEvent:u,common:{getCurrentUserID:E}}=this._core;s.forEach(f=>{var D;const{MsgRand:v,MsgSeq:N,To_Account:P,From_Account:W,RevokerInfo:{Revoker_Account:nA,Revoke_Reason:EA}}=f,wA=E()===W?`C2C${P}`:`C2C${W}`,kA=((D=f?.RevokerInfo)===null||D===void 0?void 0:D.Reason)||EA,VA=this._messageHelper.generateRevokeMessage({conversationID:wA,sequence:N,random:v,revoker:nA,revokeReason:kA});r.push(VA)}),r.length>0&&(yield this._messageHelper.updateRevokerInfo(r),g.emitOuterEvent(u.MESSAGE_REVOKED,{name:u.MESSAGE_REVOKED,data:r}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(s){return mA(this,void 0,void 0,function*(){const{revokedMessageList:r}=s.result;yield this._parseAndEmitC2CRevokedMessages(r)})}dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:r},InnerEventSubType:{C2C_REVOKED_MESSAGE:g}}=this._core;s.unSubscribeInnerEvent(r,g,this._handleC2CNotifyMessage,this)}},yC=class{init(s){this._messageHelper=new Or(s),this._core=s;const{notificationCenter:r,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{GROUP_MESSAGE_REVOKED:u}}=s;r.subscribeInnerEvent(g,u,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(s){const{GroupTips:r}=s;r?.forEach(g=>{var u;Array.isArray((u=g?.MsgBody)===null||u===void 0?void 0:u.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(g)})}_handleGroupRevokeMessage(s){return mA(this,void 0,void 0,function*(){try{const{RevokerInfo:r,MsgBody:{GroupWithdrawInfoArray:g},GroupInfo:u}=s,E=[],f=[],{notificationCenter:D,OuterEvent:v,utils:{isEmpty:N},common:{isCommunity:P}}=this._core;let W=!1;u&&(W=P({groupID:u.GroupId})||!N(u.TopicId)),g.forEach(nA=>{const{Random:EA,MsgSeq:wA,GroupId:kA,MsgClientTime:VA,TinyId:LA,TopicId:SA,RevokerInfo:{Revoker_Account:PA=r?.Revoker_Account||"",Reason:zA=r?.Reason||""}}=nA,Ee=SA?`GROUP${SA}`:`GROUP${kA}`,Ie=this._messageHelper.generateRevokeMessage({conversationID:Ee,sequence:wA,random:EA,tinyID:LA,clientTime:VA,revoker:PA,revokeReason:zA});W?(Ie.revokerInfo.nick=u.From_AccountNick,Ie.revokerInfo.avatar=u.From_AccountHeadurl,E.push(Ie)):f.push(Ie)}),f.length>0&&(yield this._messageHelper.updateRevokerInfo(f),E.push(...f)),E.length!==0&&D.emitOuterEvent(v.MESSAGE_REVOKED,{name:v.MESSAGE_REVOKED,data:E})}catch(r){console.debug(r)}})}dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:r},InnerEventSubType:{GROUP_MESSAGE_REVOKED:g}}=this._core;s.unSubscribeInnerEvent(r,g,this._handleGroupNotifyMessage,this)}};var su=new class{constructor(){this._c2cMessageReceiver=new Vu,this._groupMessageReceiver=new yC}init(s){this._c2cMessageReceiver.init(s),this._groupMessageReceiver.init(s)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}},dh=new class{constructor(){this._core=null}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"translateText",context:this})}translateText(s){return mA(this,void 0,void 0,function*(){try{const{sourceLanguage:r,sourceTextList:g,targetLanguage:u}=s,E=yield function(f,D){return mA(this,void 0,void 0,function*(){var v,N;const{sourceTextList:P,sourceLanguage:W,targetLanguage:nA}=f,{store:EA,common:wA}=D,kA={SourceText:P,Source:W,Target:nA,FromAccount:(v=EA.get("login"))===null||v===void 0?void 0:v.tinyID,SDKAppID:(N=EA.get("instance"))===null||N===void 0?void 0:N.sdkAppId},VA=yield wA.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:kA});if(VA){const{CmdErrorCode:LA,TargetText:SA}=VA;return{cmdErrorCode:LA,translatedTextList:SA}}})}({sourceLanguage:r,sourceTextList:g,targetLanguage:u},this._core);if(E){const{cmdErrorCode:{ErrorCode:f,ErrorInfo:D},translatedTextList:v}=E;if(f===0)return{code:0,data:{translatedTextList:v}};throw{errorCode:f,errorInfo:D,message:D}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};throw new this._core.helper.ChatError({functionName:"translateText",code:g,message:u})}})}},Hu=new class{init(s){this._core=s,s.helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(s){return mA(this,void 0,void 0,function*(){var r;const{message:g,language:u=Fc.ZH_PY}=s;let{url:E}=g.payload||{};const f=this._core.common.getCurrentUserID();g.from===f&&g.flow==="out"&&(E=g.payload.remoteAudioUrl),this._validateVoiceFormat(E);const D=((r=DI.exec(E))===null||r===void 0?void 0:r[1])||"mp3",v=yI[u]||iu;try{const N=yield function(P){var W;const{store:nA,common:EA}=Wn.core,{url:wA,format:kA,serverLanguageType:VA}=P,LA={BytesUrl:wA,BytesEngServiceType:VA,BytesVoiceFormat:kA,Uint32Sdkappid:(W=nA.get("instance"))===null||W===void 0?void 0:W.sdkAppId,Uint64SourceType:0};return EA.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:LA})}({url:E,format:D,serverLanguageType:v});if(N){const{CmdErrorCode:P,BytesResult:W}=N;if(P.ErrorCode===0)return{code:0,data:{result:W}};throw{code:P.ErrorCode,message:P.ErrorInfo}}}catch(N){const{code:P,message:W}=N||{};throw new this._core.common.ChatError({functionName:"convertVoiceToText",code:P,message:W})}})}_validateVoiceFormat(s){if(!DI.test(s))throw new this._core.common.ChatError({code:2119})}};class vI{constructor(r){const{constants:g,common:u,utils:E}=Wn.core,{CONV_C2C:f,CONV_GROUP:D}=g.OuterConstant,{ID:v,tinyID:N,from:P,to:W,clientTime:nA=u.timeManager.getServerTimeSeconds()||0,random:EA,sequence:wA,cloudCustomData:kA="",nick:VA="",avatar:LA="",clientSequence:SA,conversationType:PA,groupID:zA,_elements:Ee,time:Ie}=r;this.ID=v||`${N}-${nA}-${EA}`,this.messageRandom=EA,this.from=P,this.messageSender=P,this.time=Ie,this.messageSequence=wA,this.clientSequence=SA||wA,this.clientTime=nA,this.cloudCustomData=kA,this.messageReceiver=W,this.avatar=LA,this.nick=VA;const Li=E.deepCopyWithMethods(Ee);Li.forEach(Ui=>{Ui.payload=Ui.content,delete Ui.content}),this.messageBody=Li,v?PA.startsWith(f)?this.receiverUserID=W:PA.startsWith(D)&&(this.receiverGroupID=W):zA?(this.receiverGroupID=zA,this.messageReceiver=zA):W&&(this.receiverUserID=W,this.messageReceiver=W)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(r=>r.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class El{static parseServerPushElement(r){const{MsgContent:g}=r,{MsgList:u=[],CompatibleText:E,AbstractList:f,Title:D,PbMsgKey:v,JsonMsgKey:N}=g||{},P=u.map(W=>Dr(W));return new El({messageList:P,title:D,abstractList:f,compatibleText:E,pbDownloadKey:v,downloadKey:N})}constructor(r){this.type=Wn.core.constants.OuterConstant.MSG_MERGER;const{messageList:g,title:u,abstractList:E,compatibleText:f,pbDownloadKey:D="",downloadKey:v="",version:N=0,layersOverLimit:P=!1}=r,W=[];g.forEach(nA=>{if(nA){const EA=new vI(nA);W.push(EA)}}),this.content={messageList:W,title:u,abstractList:E,compatibleText:f,version:N,downloadKey:v,pbDownloadKey:D,layersOverLimit:P}}validateBeforeSend(){const{isEmpty:r}=Wn.core.helper;return r(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{abstractList:E,compatibleText:f,downloadKey:D,layersOverLimit:v,pbDownloadKey:N,title:P,version:W,messageList:nA}=u;return{MsgType:this.type,MsgContent:{AbstractList:E,CompatibleText:f,JsonMsgKey:D,LayersOverLimit:v,PbMsgKey:N,Title:P,Version:W,MsgList:sc(nA)}}}}var DC=new class{init(s){this._core=s;const{message:r,helper:g,constants:{OuterConstant:u}}=s;r.messageFactory.registerElementClass(u.MSG_MERGER,El),g.registerApi({apiName:"createMergerMessage",context:this}),g.registerApi({apiName:"sendMessage",context:this,matcher:E=>E[0].type===u.MSG_MERGER}),g.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(s){const{common:r}=this._core;if(!s)return null;const g=new El(s.payload),u=r.getCurrentUserID(),E=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:u}));return E.setRelayFlag(!0),E.setElement(g),E}sendMessage(s,r){return mA(this,void 0,void 0,function*(){var g,u,E;try{const f=function(P){let W="utf-8";Wn.core.helper.IN_BROWSER&&document&&(W=document.charset.toLowerCase());let nA,EA=0,wA=0;if(wA=P.length,W==="utf-8"||W==="utf8")for(let kA=0;kA11264){D=this._core.utils.deepCopyWithMethods(s);try{const{JsonMsgKey:P,PbMsgKey:W}=yield function(EA){return mA(this,void 0,void 0,function*(){const{payload:{messageList:wA}}=EA,kA={MsgList:sc(wA)};return Wn.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:kA})})}(D),{payload:nA}=D;v=new El(Object.assign(Object.assign({},nA),{messageList:[],downloadKey:P,pbDownloadKey:W})),D.setElement(v)}catch(P){console.error(P)}}const{data:{message:N}}=yield(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(D,r);return v&&N.setElement(s._elements),{code:0,data:{message:N}}}catch(f){const{errorCode:D}=f;throw new this._core.helper.ChatError({code:D})}})}downloadMergerMessage(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r}=this._core,g=s.payload,{downloadKey:u,pbDownload:E,type:f,messageList:D}=g,v=vo(g,["downloadKey","pbDownload","type","messageList"]);try{const N=yield function(nA){return mA(this,void 0,void 0,function*(){return Wn.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:nA}})})}(u),{MsgList:P}=N||{},W=P?.map(nA=>{const EA=Dr(nA);return new vI(EA)});return typeof s.isOnlineMessage=="function"?s.setElement({type:s.type,content:Object.assign({messageList:W},v)}):(s.payload.messageList=W,s.payload.downloadKey="",s.payload.pbDownloadKey=""),r.info("downloadMergerMessage",` success downloadKey:${u}`),s}catch(N){const{errorCode:P}=N;throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:P,moreMessage:u})}})}},Ia=new class{init(s){this._core=s,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(s){return mA(this,void 0,void 0,function*(){const{appStore:r,message:g,common:{getCurrentUserID:u},utils:{isArray:E}}=this._core,{GroupId:f,To_Account:D}=s;s.From_Account=s.From_Account||u();let v=null;if(f){v=this._generateGroupMessage(Object.assign(Object.assign({},s),{ToGroupId:f}));const N=r.userStore.getUserProfile(u());v.level=N?.level||0,E(D)&&D.length>0&&(v._receiverList=D)}else D&&(v=this._generateC2CMessage(s));return g.messageSender.sendMessage(v,s)})}_generateC2CMessage(s){const{message:r,OuterConstant:{CONV_C2C:g}}=this._core,u=g,E=r.messageHelper.parseServerPushMessage(s),f=r.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:u,flow:rc.OUT})),{elements:D}=E;return f.setElement(D),f}_generateGroupMessage(s){const{message:r,OuterConstant:{CONV_GROUP:g}}=this._core,u=g,E=r.messageHelper.parseServerGroupMessage(s),f=r.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:u,flow:rc.OUT})),{elements:D}=E;return f.setElement(D),f}},ac=new class{init(s){this._core=s;const{helper:r,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:u},InnerEventSubType:{GROUP_MESSAGE_PINNED:E}}=s;g.subscribeInnerEvent(u,E,this._handleGroupMessagePinned,this),r.registerApi({apiName:"pinGroupMessage",context:this}),r.registerApi({apiName:"getPinnedGroupMessageList",context:this})}pinGroupMessage(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,common:{isTopic:g},OuterConstant:{GROUP_ID_PREFIX:u},helper:{ChatError:E}}=this._core;let{groupID:f,message:D,isPinned:v}=s;const{sequence:N}=D;try{return yield function(P){return mA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:W,getCurrentUserID:nA}}=Wn.core,{groupID:EA,sequence:wA,isPinned:kA}=P,VA=nA(),LA=kA?"group_open_http_svc.pin_message":"group_open_http_svc.unpin_message",SA={GroupId:EA,MsgSeq:wA};return kA?SA.Pinner_Account=VA:SA.UnPinner_Account=VA,W({servcmd:LA,data:SA})})}({groupID:f,sequence:N,isPinned:v}),{code:0,data:{}}}catch(P){const{errorCode:W,errorInfo:nA}=P||{};throw new E({code:W,message:nA})}})}getPinnedGroupMessageList(s){return mA(this,void 0,void 0,function*(){let r=[];try{const g=yield function(u){return mA(this,void 0,void 0,function*(){const{groupID:E}=u,{common:{buildAndSendPacket:f}}=Wn.core;return f({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:E}})})}({groupID:s});if(g){const{PinnedMsgList:u=[]}=g;r=yield this._updatePinnedMessageInfo({serverPinnedMessageList:u,groupID:s})}return{code:0,data:{messageList:r}}}catch(g){throw g}})}_handleGroupMessagePinned(s){const{message:{messageHelper:r,messageFactory:g},notificationCenter:u,OuterEvent:E,OuterConstant:f}=this._core;s.GroupTips.forEach(D=>{const{ToGroupId:v,MsgBody:{PinnedMsg:N,OpType:P,MsgOperatorMemberExtraInfo:W,SdkGroupMessageId:nA}}=D,{UserId:EA,NickName:wA="",ImageUrl:kA=""}=W;let VA=null,LA=!1;if(P===yd){LA=!0;const SA=r.parseServerGroupMessage(N);VA=g.createMessage(Object.assign(Object.assign({},SA),{conversationType:f.CONV_GROUP,flow:"in"})),VA.setElement(SA.elements),VA.pinnerInfo={userID:EA,nick:wA,avatar:kA}}else if(P===FE){const{ClientTime:SA,Random:PA,SenderTinyId:zA,ServerTime:Ee,MsgSeq:Ie}=nA;VA={ID:`${zA}-${SA}-${PA}`,sequence:Ie,random:PA,time:Ee,clientTime:SA}}VA&&u.emitOuterEvent(E.PINNED_GROUP_MESSAGE_UPDATED,{name:E.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:v,message:VA,isPinned:LA,operatorInfo:{userID:EA,nick:wA,avatar:kA}}})})}_findMessageBySequence(s,r){const{message:{messageDataHandler:g}}=this._core;return[...g.getLocalMessageList(s),...g.getSparseMessageList(s)].find(u=>u.sequence===r)}_updatePinnedMessageInfo(s){return mA(this,arguments,void 0,function*({serverPinnedMessageList:r,groupID:g}){const{OuterConstant:{CONV_GROUP:u},utils:{isEmpty:E}}=this._core,f=[],D=[],v=[],N=new Map,P=`${u}${g}`;for(let nA=0;nA{const{sequence:kA}=wA,VA=N.get(kA),LA=nA[VA]||{userID:VA,nick:"",avatar:""};wA.pinnerInfo=LA}),f.sort((wA,kA)=>wA.sequence-kA.sequence),f}return[]})}_fetchPinnedMessageInfo(s){return mA(this,void 0,void 0,function*(){var r,g;const{message:{messageHistory:u},user:{userProfile:E},utils:{isArray:f}}=this._core,{conversationID:D,messageSequenceList:v,pinnerIDList:N}=s,P=yield Promise.all([this._fetchMessageBySequence({conversationID:D,messageSequenceList:v}),E?.getUserProfile({userIDList:N})]);if(f(P)){const W={};return(((r=P[1])===null||r===void 0?void 0:r.data)||[]).forEach(nA=>{const{userID:EA,nick:wA="",avatar:kA=""}=nA;W[EA]={userID:EA,nick:wA,avatar:kA}}),{messageList:((g=P[0])===null||g===void 0?void 0:g.messageList)||[],pinnerInfoMap:W}}})}_fetchMessageBySequence(s){return mA(this,void 0,void 0,function*(){const{utils:{isEmpty:r},message:{messageHistory:g}}=this._core,{conversationID:u,messageSequenceList:E}=s;return r(E)?[]:g.getGroupRoamingMessagesByAnchor({conversationID:u,messageSequenceList:E,getType:3})})}};class Eg{constructor(r){this.eventType=Oc.DATA,this.index=0,this.markdown="",this.isLast=!1,this.binaryData=null;const{EventType:g,Index:u,Markdown:E,IsLast:f,BinaryData:D}=r;this.eventType=g,this.index=u,this.markdown=E,this.isLast=f,this.binaryData=D}}var MI=new class{constructor(){this._messageMap=new Map,this._retryCountMap=new Map}init(s){this._core=s;const{notificationCenter:r,OuterEvent:{MESSAGE_RECEIVED:g},InnerEvent:{HISTORY_MESSAGE_FETCHED:u},common:{workflowManager:E},constants:{WORKFLOW_NAME:f,WORKFLOW_STEP:D}}=s;r.subscribeInnerEvent(ho,this._handleStreamMessageChunkPush,this),r.subscribeOuterEvent(g,this._handleMessageReceived,this),r.subscribeInnerEvent(u,this.processHistoryMessage,this),E.registerWorkflowStep(f.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.STREAM_MESSAGE_RECOVER,this._recoverStreamMessage,this)}processHistoryMessage(s){const{utils:{isEmpty:r,safeStringify:g},ssoLog:u}=this._core;try{s?.forEach(E=>{var f;if(this._isValidStreamMessage(E)){const D=(f=E?._elements)===null||f===void 0?void 0:f[0],{streamMessageID:v,markdown:N,binaryData:P}=D?.content||{};r(N)&&r(P)?(this._messageMap.set(v,E),this._fetchStreamMessageChunks(E)):D.content.isStreamEnded=!0}})}catch(E){u.error("processHistoryMessage.error",g(E))}}_handleMessageReceived(s){const r=s.data;r?.forEach(g=>{var u,E;if(this._isValidStreamMessage(g)){const{streamMessageID:f}=((E=(u=g?._elements)===null||u===void 0?void 0:u[0])===null||E===void 0?void 0:E.content)||{};f&&(this._messageMap.set(f,g),this._fetchStreamMessageChunks(g))}})}_isValidStreamMessage(s){var r,g;const{utils:{isEmpty:u}}=this._core,{streamMessageID:E}=((g=(r=s?._elements)===null||r===void 0?void 0:r[0])===null||g===void 0?void 0:g.content)||{};return s.type===Kr.MSG_STREAM&&!u(E)}_fetchStreamMessageChunks(s){return mA(this,void 0,void 0,function*(){var r,g;const{constants:{ERROR_CODE:u},ssoLog:E,utils:{safeStringify:f}}=this._core,D=(r=s._elements)===null||r===void 0?void 0:r[0],v=(g=D?.content)===null||g===void 0?void 0:g.streamMessageID;try{const{from:N,to:P}=s,W=D.getLatestIndex();if(D.content.isStreamEnded)return;const nA=yield function(EA){return mA(this,void 0,void 0,function*(){const{from:wA,to:kA,streamMessageID:VA,index:LA}=EA,SA={From_Account:wA,To_Account:kA,StreamMsgID:VA,AckIndex:LA};return Wn.core.common.buildAndSendPacket({servcmd:"StreamMsg.GetStreamHttp",data:SA,timeout:5e3})})}({from:N,to:P,streamMessageID:v,index:W});if(nA){const{ErrorCode:EA,ErrorInfo:wA}=nA;if(EA!==0)throw D.content.errorCode=EA,D.content.errorMessage=wA,{errorCode:EA,errorMessage:wA}}}catch(N){if(N.errorCode===u.NETWORK_TIMEOUT&&this._shouldRetryFetch(v)){const P=this._retryCountMap.get(v)||0;E.debug("_fetchStreamMessageChunks.timeout",`error: ${f(N)} retried: ${P}`),this._retryCountMap.set(v,P+1),this._fetchStreamMessageChunks(s)}else E.error("_fetchStreamMessageChunks.error",f(N))}})}_shouldRetryFetch(s){const{utils:{isNumber:r}}=this._core;if(!this._retryCountMap.has(s))return this._retryCountMap.set(s,1),!0;const g=this._retryCountMap.get(s);return!!(r(g)&&g<=3)}_onStreamEnded(s,r,g){const{ssoLog:u}=this._core;g.content.isStreamEnded=!0,g.stopReason=r,this._messageMap.delete(s),u.debug("_onStreamEnded",`streamMessage end, StopReason: ${r}`)}_handleStreamMessageChunkPush(s){var r;const{ssoLog:g}=this._core,{StopReason:u,Chunks:E,StreamID:f}=s?.body||{},D=this._messageMap.get(f);if(!D)return void g.warn(`_handleStreamMessageChunkPush, unfounded message: ${f}`);const v=(r=D._elements)===null||r===void 0?void 0:r[0];if(v&&this._validateExpectedChunk(v,E)){if(E.length>0){const N=E.map(P=>new Eg(P));v.updateChunks(N)}this._emitMessageModify(D),function(N,P){mA(this,void 0,void 0,function*(){const{common:{generateProtocolData:W},utils:{safeStringify:nA},ssoLog:EA,channel:wA}=Wn.core,kA={StreamMsgID:N,AckIndex:P};try{const VA=W({servcmd:"StreamMsg.AckHttp",data:kA});wA.sendPacket(VA)}catch(VA){EA.debug("sendStreamChunkAck",nA(VA))}})}(f,v.getLatestIndex()),v.content.isStreamEnded&&this._onStreamEnded(f,u,v)}}_emitMessageModify(s){const{notificationCenter:r,OuterEvent:{MESSAGE_MODIFIED:g}}=this._core;r.emitOuterEvent(g,{name:g,data:[s]})}_validateExpectedChunk(s,r){const g=s.getLatestIndex()+1;let u=!1;for(let E=0;Ef.Index).join(", ")}]`),!1}return!0}_recoverStreamMessage(){this._retryCountMap.clear();const{ssoLog:s,utils:{safeStringify:r}}=this._core;try{const g=Array.from(this._messageMap.entries());for(let u=Math.max(0,g.length-300);u{const LA=this._getResponseBody(kA,E,nA&&EA),SA=this._buildResponse(kA,LA);if(kA.status===200)r(null,SA);else{if(EA&&!wA.includes(EA))return s.url=this._domainName2IP(wA,EA),s.uploadByIP=!0,this.request(s,r);r({code:kA.status,message:JSON.stringify(kA.responseText)},SA)}},kA.onerror=()=>{const LA=this._getResponseBody(kA,E,nA&&EA),SA=this._buildResponse(kA,LA),PA={code:kA.status,message:kA.status===0?"CORS blocked or network error":JSON.stringify(kA.responseText)};r(PA,SA)},s.onProgress&&kA.upload&&(kA.upload.onprogress=LA=>{const{total:SA,loaded:PA}=LA,zA=Math.min(Math.floor(100*PA/SA),100);s.onProgress({total:SA,loaded:PA,percent:zA/100})}),kA.send(P),kA})}_buildResponse(s,r){const g={};return s.getAllResponseHeaders().trim().split(` -`).forEach(u=>{if(u){const[E,f]=u.split(":").map(D=>D.trim());g[E.toLowerCase()]=f}}),{statusCode:s.status,statusMessage:s.statusText,headers:g,data:r}}_getResponseBody(s,r,g){return s.status===200&&r?{location:r,uploadIP:g}:{response:s.responseText,uploadIP:g}}_queryString(s,r="&",g="="){var u;const{isEmpty:E,isPlainObject:f}=(u=this._core)===null||u===void 0?void 0:u.utils;return E(s)?"":f(s)?Object.keys(s).map(D=>{const v=encodeURIComponent(D)+g;return Array.isArray(s[D])?s[D].map(N=>v+encodeURIComponent(N)).join(r):v+encodeURIComponent(s[D])}).filter(Boolean).join(r):void 0}_domainName2IP(s,r){return s.replace(/^http(s)?:\/\/(.*?)\//,`https://${r}/`)}};const qu=["unknown","image","video","audio","log"];var RI=new class{init(s){this._core=s}request(s,r){var g;const{MINI_APP_NAMESPACE:u,IN_ALIPAY_MINI_APP:E,isUniIOSApp:f}=(g=this._core)===null||g===void 0?void 0:g.utils,{resources:D="",headers:v={},url:N,downloadUrl:P=""}=s;let W=N,nA=null;const EA=P?P.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!EA)return void console.warn("message Invalid download URL format");const wA=decodeURIComponent(EA[3]),kA=wA.includes("?")?wA.split("?")[0]:wA||"",VA={key:s.fileKey||kA,success_action_status:200,"Content-Type":""},LA={};if(f()){const[PA,zA]=N.split("?sign=");zA&&(W=`${PA}?sign=${encodeURIComponent(zA)}`,LA.sign=decodeURIComponent(zA),LA.signature=decodeURIComponent(zA))}let SA={url:W,header:v,name:"file",filePath:D,formData:Object.assign(Object.assign({},VA),LA),timeout:s.timeout||3e5};if(E){const{name:PA}=SA,zA=vo(SA,["name"]);SA=Object.assign(Object.assign({},zA),{fileName:"file",fileType:s.fileType?qu[s.fileType]:"image"})}return nA=u.uploadFile(Object.assign(Object.assign({},SA),{success:PA=>{this._handleResponse({response:PA,downloadUrl:P,callback:r})},fail:PA=>{this._handleResponse({response:PA,downloadUrl:P,callback:r})}})),nA.onProgressUpdate&&nA.onProgressUpdate(PA=>{s.onProgress&&s.onProgress({total:PA.totalBytesExpectedToSend||0,loaded:PA.totalBytesSent||0,percent:PA.progress?Math.floor(PA.progress)/100:0})}),nA}_handleResponse(s){const{downloadUrl:r,response:g,callback:u}=s,E={};if(g.header)for(const D in g.header)g.header.hasOwnProperty(D)&&(E[D.toLowerCase()]=g.header[D]);const f=+g.statusCode;f===200?u(null,{statusCode:f,headers:E,data:Object.assign(Object.assign({},g.data),{location:r})}):u({code:f,message:JSON.stringify(g.data)},{statusCode:f,headers:E,data:void 0})}};function dl(s){return function(r){return Object.prototype.toString.call(r).match(/^\[object (.*)\]$/)[1].toLowerCase()}(s)==="file"}function Pr(s){const r=s||99999999;return Math.round(Math.random()*r)}function xr(s,r=!0,g=!0){const u=Date.now();return r?g?u-s+" ms":`${Math.round((u-s)/1e3)} s`:g?u-s:Math.round((u-s)/1e3)}function dg(s){return`${Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")}-${s}`}function hr(s,r){return Math.round(Number(s)*10**r)/10**r}function Nr(s){return s<=1048576?`${hr(s/1024,1)}KB/s`:`${hr(s/1048576,1)}MB/s`}const gc="TIMImageElem",xg="TIMSoundElem",Ka="TIMFileElem",Vl="TIMVideoFileElem",ya="RichMediaMessagePlugin",wI=["rich.my-imcloud.com","imrich.qcloud.com"],ru=1,Da=2,Cl=3,VE=255;var au;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(au||(au={}));const HE={wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/},jr=Symbol("isCustomUpload");var gu,Vt=new class{init(s){this._core=s}addAuthToUrl(s=""){if(this._isMiniProgramTempFile(s))return s;const r=function(g){return g?g.startsWith("https://")?g:g.startsWith("http://")?g.replace("http://","https://"):g:""}(s);return this.processResourceUrl(r)}removeAuthToUrl(s){return function(r,g){const[u,E]=r.split("?");if(!E)return u;const f=E.split("&").reduce((v,N)=>{const[P,W]=N.split("=");return P&&P!==g&&(v[P]=W||""),v},{}),D=Object.keys(f).map(v=>`${v}${f[v]?`=${f[v]}`:""}`).join("&");return D?`${u}?${D}`:u}(s,"authKey")}_isMiniProgramTempFile(s){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(HE).some(r=>r.test(s))}extractFileFromInput(s){const{utils:{isArray:r}}=this._core;return dl(s)?s:function(g){if(typeof g!="object"||g===null)return!1;const u=Object.getPrototypeOf(g);if(u===null)return!0;let E=u;for(;Object.getPrototypeOf(E)!==null;)E=Object.getPrototypeOf(E);return u===E}(s)&&typeof uni<"u"?r(s.tempFiles)&&s.tempFiles.length>0?s.tempFiles[0]:r(s.files)?s.files[0]:s.tempFile?s.tempFile:null:s instanceof HTMLInputElement&&s.files&&s.files.length>0?s.files[0]:null}probeImageWidthHeight(s){return mA(this,void 0,void 0,function*(){var r;const{IN_MINI_APP:g,IN_BROWSER:u}=((r=this._core)===null||r===void 0?void 0:r.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:u?this._probeImageDimensionsWeb(s):g?this._probeImageDimensionsMiniApp(s):void 0})}isSimpleCos(){var s;const r=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{simple_cos:g}=r;return g!=="0"}getFileDNList(){var s;let r=wI;const g=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{file_dn_list:u}=g;if(u===void 0)return r;try{JSON.parse(u).forEach(E=>{r.includes(E)||r.push(E)})}catch(E){console.warn(E),r=wI}return r}getPlatform(){var s;return(s=this._core)===null||s===void 0?void 0:s.utils.platform}generateUUID(s,r){var g;let u=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${(g=this._core)===null||g===void 0?void 0:g.utils.randomString()}`;if(r)return`${u}.${r}`;const E=s.name||s.value||s.url||s.tempFilePath,f=E&&E.slice(E.lastIndexOf(".")+1);return f&&(u=`${u}.${f}`),u}processResourceUrl(s){if(!s)return"";let r=s;const g=this.getFileDownloadProxy(),u=this.getAuthKey(),E=this.getFileDNList();return g&&(s.startsWith("http://")?r=s.replace(/^http:\/\/[^/]+/,g):s.startsWith("https://")&&(r=s.replace(/^https:\/\/[^/]+/,g))),u&&r.indexOf("authKey=")===-1&&function(D,v){let N=!1;if(D){const P=D.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),W=P&&P[2]||"";if(W.includes("rich-dev"))return!0;for(let nA=0;nA-1?`${r}&authKey=${u}`:`${r}?authKey=${u}`),r}getCurrentUserID(){var s,r;return(r=(s=this._core)===null||s===void 0?void 0:s.store.get("login"))===null||r===void 0?void 0:r.userId}getSDKAppID(){var s,r;return(r=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||r===void 0?void 0:r.sdkAppId}getFileDownloadProxy(){var s,r;return((r=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||r===void 0?void 0:r.fileDownloadProxy)||""}getFileUploadProxy(){var s,r;return((r=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||r===void 0?void 0:r.fileUploadProxy)||""}getAuthKey(){var s,r;return((r=(s=this._core)===null||s===void 0?void 0:s.store.get("login"))===null||r===void 0?void 0:r.authKey)||""}isPrivateNetWork(){var s,r;return(r=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||r===void 0?void 0:r.proxyServer}getPlatformFlags(){var s;const{IN_BROWSER:r,IN_MINI_APP:g,IN_RN_APP:u,IN_UNI_NATIVE_APP:E}=(s=this._core)===null||s===void 0?void 0:s.utils;return{IN_BROWSER:r,IN_MINI_APP:g,IN_RN_APP:u,IN_UNI_NATIVE_APP:E}}isEmpty(s){var r;const{isEmpty:g}=(r=this._core)===null||r===void 0?void 0:r.utils;return g(s)}generateURL(s,r){const{needAddAuthToUrl:g=!0}=r||{};return g?this.addAuthToUrl(s):s}_probeImageDimensionsMiniApp(s){var r;const{MINI_APP_NAMESPACE:g}=((r=this._core)===null||r===void 0?void 0:r.utils)||{};return new Promise(u=>{g.getImageInfo({src:s,success:E=>u({width:E.width,height:E.height}),fail:()=>u({width:0,height:0})})})}_shouldSkipProbing(){var s;const{IN_RN_APP:r,IS_IE:g,IE_VERSION:u,IN_WX_MINI_GAME:E}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};return r||g&&u===9||E}_probeImageDimensionsWeb(s){return new Promise(r=>{const g=new Image,u=()=>{g.onload=null,g.onerror=null,g.src=""};g.onload=()=>{r({width:g.width,height:g.height}),u()},g.onerror=()=>{r({width:0,height:0}),u()},g.src=s})}},Ku={exports:{}},ju=(gu||(gu=1,function(s){s.exports=function(r){var g=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function u(LA,SA){var PA=LA[0],zA=LA[1],Ee=LA[2],Ie=LA[3];zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA&Ee|~zA&Ie)+SA[0]-680876936|0)<<7|PA>>>25)+zA|0)&zA|~PA&Ee)+SA[1]-389564586|0)<<12|Ie>>>20)+PA|0)&PA|~Ie&zA)+SA[2]+606105819|0)<<17|Ee>>>15)+Ie|0)&Ie|~Ee&PA)+SA[3]-1044525330|0)<<22|zA>>>10)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA&Ee|~zA&Ie)+SA[4]-176418897|0)<<7|PA>>>25)+zA|0)&zA|~PA&Ee)+SA[5]+1200080426|0)<<12|Ie>>>20)+PA|0)&PA|~Ie&zA)+SA[6]-1473231341|0)<<17|Ee>>>15)+Ie|0)&Ie|~Ee&PA)+SA[7]-45705983|0)<<22|zA>>>10)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA&Ee|~zA&Ie)+SA[8]+1770035416|0)<<7|PA>>>25)+zA|0)&zA|~PA&Ee)+SA[9]-1958414417|0)<<12|Ie>>>20)+PA|0)&PA|~Ie&zA)+SA[10]-42063|0)<<17|Ee>>>15)+Ie|0)&Ie|~Ee&PA)+SA[11]-1990404162|0)<<22|zA>>>10)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA&Ee|~zA&Ie)+SA[12]+1804603682|0)<<7|PA>>>25)+zA|0)&zA|~PA&Ee)+SA[13]-40341101|0)<<12|Ie>>>20)+PA|0)&PA|~Ie&zA)+SA[14]-1502002290|0)<<17|Ee>>>15)+Ie|0)&Ie|~Ee&PA)+SA[15]+1236535329|0)<<22|zA>>>10)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA&Ie|Ee&~Ie)+SA[1]-165796510|0)<<5|PA>>>27)+zA|0)&Ee|zA&~Ee)+SA[6]-1069501632|0)<<9|Ie>>>23)+PA|0)&zA|PA&~zA)+SA[11]+643717713|0)<<14|Ee>>>18)+Ie|0)&PA|Ie&~PA)+SA[0]-373897302|0)<<20|zA>>>12)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA&Ie|Ee&~Ie)+SA[5]-701558691|0)<<5|PA>>>27)+zA|0)&Ee|zA&~Ee)+SA[10]+38016083|0)<<9|Ie>>>23)+PA|0)&zA|PA&~zA)+SA[15]-660478335|0)<<14|Ee>>>18)+Ie|0)&PA|Ie&~PA)+SA[4]-405537848|0)<<20|zA>>>12)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA&Ie|Ee&~Ie)+SA[9]+568446438|0)<<5|PA>>>27)+zA|0)&Ee|zA&~Ee)+SA[14]-1019803690|0)<<9|Ie>>>23)+PA|0)&zA|PA&~zA)+SA[3]-187363961|0)<<14|Ee>>>18)+Ie|0)&PA|Ie&~PA)+SA[8]+1163531501|0)<<20|zA>>>12)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA&Ie|Ee&~Ie)+SA[13]-1444681467|0)<<5|PA>>>27)+zA|0)&Ee|zA&~Ee)+SA[2]-51403784|0)<<9|Ie>>>23)+PA|0)&zA|PA&~zA)+SA[7]+1735328473|0)<<14|Ee>>>18)+Ie|0)&PA|Ie&~PA)+SA[12]-1926607734|0)<<20|zA>>>12)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA^Ee^Ie)+SA[5]-378558|0)<<4|PA>>>28)+zA|0)^zA^Ee)+SA[8]-2022574463|0)<<11|Ie>>>21)+PA|0)^PA^zA)+SA[11]+1839030562|0)<<16|Ee>>>16)+Ie|0)^Ie^PA)+SA[14]-35309556|0)<<23|zA>>>9)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA^Ee^Ie)+SA[1]-1530992060|0)<<4|PA>>>28)+zA|0)^zA^Ee)+SA[4]+1272893353|0)<<11|Ie>>>21)+PA|0)^PA^zA)+SA[7]-155497632|0)<<16|Ee>>>16)+Ie|0)^Ie^PA)+SA[10]-1094730640|0)<<23|zA>>>9)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA^Ee^Ie)+SA[13]+681279174|0)<<4|PA>>>28)+zA|0)^zA^Ee)+SA[0]-358537222|0)<<11|Ie>>>21)+PA|0)^PA^zA)+SA[3]-722521979|0)<<16|Ee>>>16)+Ie|0)^Ie^PA)+SA[6]+76029189|0)<<23|zA>>>9)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA^Ee^Ie)+SA[9]-640364487|0)<<4|PA>>>28)+zA|0)^zA^Ee)+SA[12]-421815835|0)<<11|Ie>>>21)+PA|0)^PA^zA)+SA[15]+530742520|0)<<16|Ee>>>16)+Ie|0)^Ie^PA)+SA[2]-995338651|0)<<23|zA>>>9)+Ee|0,zA=((zA+=((Ie=((Ie+=(zA^((PA=((PA+=(Ee^(zA|~Ie))+SA[0]-198630844|0)<<6|PA>>>26)+zA|0)|~Ee))+SA[7]+1126891415|0)<<10|Ie>>>22)+PA|0)^((Ee=((Ee+=(PA^(Ie|~zA))+SA[14]-1416354905|0)<<15|Ee>>>17)+Ie|0)|~PA))+SA[5]-57434055|0)<<21|zA>>>11)+Ee|0,zA=((zA+=((Ie=((Ie+=(zA^((PA=((PA+=(Ee^(zA|~Ie))+SA[12]+1700485571|0)<<6|PA>>>26)+zA|0)|~Ee))+SA[3]-1894986606|0)<<10|Ie>>>22)+PA|0)^((Ee=((Ee+=(PA^(Ie|~zA))+SA[10]-1051523|0)<<15|Ee>>>17)+Ie|0)|~PA))+SA[1]-2054922799|0)<<21|zA>>>11)+Ee|0,zA=((zA+=((Ie=((Ie+=(zA^((PA=((PA+=(Ee^(zA|~Ie))+SA[8]+1873313359|0)<<6|PA>>>26)+zA|0)|~Ee))+SA[15]-30611744|0)<<10|Ie>>>22)+PA|0)^((Ee=((Ee+=(PA^(Ie|~zA))+SA[6]-1560198380|0)<<15|Ee>>>17)+Ie|0)|~PA))+SA[13]+1309151649|0)<<21|zA>>>11)+Ee|0,zA=((zA+=((Ie=((Ie+=(zA^((PA=((PA+=(Ee^(zA|~Ie))+SA[4]-145523070|0)<<6|PA>>>26)+zA|0)|~Ee))+SA[11]-1120210379|0)<<10|Ie>>>22)+PA|0)^((Ee=((Ee+=(PA^(Ie|~zA))+SA[2]+718787259|0)<<15|Ee>>>17)+Ie|0)|~PA))+SA[9]-343485551|0)<<21|zA>>>11)+Ee|0,LA[0]=PA+LA[0]|0,LA[1]=zA+LA[1]|0,LA[2]=Ee+LA[2]|0,LA[3]=Ie+LA[3]|0}function E(LA){var SA,PA=[];for(SA=0;SA<64;SA+=4)PA[SA>>2]=LA.charCodeAt(SA)+(LA.charCodeAt(SA+1)<<8)+(LA.charCodeAt(SA+2)<<16)+(LA.charCodeAt(SA+3)<<24);return PA}function f(LA){var SA,PA=[];for(SA=0;SA<64;SA+=4)PA[SA>>2]=LA[SA]+(LA[SA+1]<<8)+(LA[SA+2]<<16)+(LA[SA+3]<<24);return PA}function D(LA){var SA,PA,zA,Ee,Ie,Li,Ui=LA.length,Yt=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ui;SA+=64)u(Yt,E(LA.substring(SA-64,SA)));for(PA=(LA=LA.substring(SA-64)).length,zA=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],SA=0;SA>2]|=LA.charCodeAt(SA)<<(SA%4<<3);if(zA[SA>>2]|=128<<(SA%4<<3),SA>55)for(u(Yt,zA),SA=0;SA<16;SA+=1)zA[SA]=0;return Ee=(Ee=8*Ui).toString(16).match(/(.*?)(.{0,8})$/),Ie=parseInt(Ee[2],16),Li=parseInt(Ee[1],16)||0,zA[14]=Ie,zA[15]=Li,u(Yt,zA),Yt}function v(LA){var SA,PA,zA,Ee,Ie,Li,Ui=LA.length,Yt=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ui;SA+=64)u(Yt,f(LA.subarray(SA-64,SA)));for(PA=(LA=SA-64>2]|=LA[SA]<<(SA%4<<3);if(zA[SA>>2]|=128<<(SA%4<<3),SA>55)for(u(Yt,zA),SA=0;SA<16;SA+=1)zA[SA]=0;return Ee=(Ee=8*Ui).toString(16).match(/(.*?)(.{0,8})$/),Ie=parseInt(Ee[2],16),Li=parseInt(Ee[1],16)||0,zA[14]=Ie,zA[15]=Li,u(Yt,zA),Yt}function N(LA){var SA,PA="";for(SA=0;SA<4;SA+=1)PA+=g[LA>>8*SA+4&15]+g[LA>>8*SA&15];return PA}function P(LA){var SA;for(SA=0;SA"u"||ArrayBuffer.prototype.slice||function(){function LA(SA,PA){return(SA=0|SA||0)<0?Math.max(SA+PA,0):Math.min(SA,PA)}ArrayBuffer.prototype.slice=function(SA,PA){var zA,Ee,Ie,Li,Ui=this.byteLength,Yt=LA(SA,Ui),Oi=Ui;return PA!==r&&(Oi=LA(PA,Ui)),Yt>Oi?new ArrayBuffer(0):(zA=Oi-Yt,Ee=new ArrayBuffer(zA),Ie=new Uint8Array(Ee),Li=new Uint8Array(this,Yt,zA),Ie.set(Li),Ee)}}(),VA.prototype.append=function(LA){return this.appendBinary(W(LA)),this},VA.prototype.appendBinary=function(LA){this._buff+=LA,this._length+=LA.length;var SA,PA=this._buff.length;for(SA=64;SA<=PA;SA+=64)u(this._hash,E(this._buff.substring(SA-64,SA)));return this._buff=this._buff.substring(SA-64),this},VA.prototype.end=function(LA){var SA,PA,zA=this._buff,Ee=zA.length,Ie=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(SA=0;SA>2]|=zA.charCodeAt(SA)<<(SA%4<<3);return this._finish(Ie,Ee),PA=P(this._hash),LA&&(PA=kA(PA)),this.reset(),PA},VA.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},VA.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},VA.prototype.setState=function(LA){return this._buff=LA.buff,this._length=LA.length,this._hash=LA.hash,this},VA.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},VA.prototype._finish=function(LA,SA){var PA,zA,Ee,Ie=SA;if(LA[Ie>>2]|=128<<(Ie%4<<3),Ie>55)for(u(this._hash,LA),Ie=0;Ie<16;Ie+=1)LA[Ie]=0;PA=(PA=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),zA=parseInt(PA[2],16),Ee=parseInt(PA[1],16)||0,LA[14]=zA,LA[15]=Ee,u(this._hash,LA)},VA.hash=function(LA,SA){return VA.hashBinary(W(LA),SA)},VA.hashBinary=function(LA,SA){var PA=P(D(LA));return SA?kA(PA):PA},VA.ArrayBuffer=function(){this.reset()},VA.ArrayBuffer.prototype.append=function(LA){var SA,PA=wA(this._buff.buffer,LA),zA=PA.length;for(this._length+=LA.byteLength,SA=64;SA<=zA;SA+=64)u(this._hash,f(PA.subarray(SA-64,SA)));return this._buff=SA-64>2]|=zA[SA]<<(SA%4<<3);return this._finish(Ie,Ee),PA=P(this._hash),LA&&(PA=kA(PA)),this.reset(),PA},VA.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},VA.ArrayBuffer.prototype.getState=function(){var LA=VA.prototype.getState.call(this);return LA.buff=EA(LA.buff),LA},VA.ArrayBuffer.prototype.setState=function(LA){return LA.buff=nA(LA.buff,!0),VA.prototype.setState.call(this,LA)},VA.ArrayBuffer.prototype.destroy=VA.prototype.destroy,VA.ArrayBuffer.prototype._finish=VA.prototype._finish,VA.ArrayBuffer.hash=function(LA,SA){var PA=P(v(new Uint8Array(LA)));return SA?kA(PA):PA},VA}()}(Ku)),Ku.exports),SC=uI(ju),K=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(s){var r;this._core=s;const{IN_MINI_APP:g}=s.utils;this.httpRequest=g?RI:Ju,(r=this.httpRequest)===null||r===void 0||r.init(s)}uploadToCOS(s){return mA(this,void 0,void 0,function*(){const r=`${ya} uploadToCOS`,{ssoLog:g,utils:{safeStringify:u}}=this._core,{file:E}=s;this.uploadFileType=s.uploadFileType,g.debug("uploadToCOS",`${r} options:${u(s)}`);try{const f=Date.now(),D=yield this._createCosOptions(s),v=D.fileExistsInCOS?{data:{location:D.downloadUrl}}:yield this._uploadFile(D);this._handleUploadError(v,s);const N=this._createUploadResult(E,v),P=Date.now()-f,W=function(EA){return EA<1024?`${EA}B`:EA<1048576?`${Math.floor(EA/1024)}KB`:`${Math.floor(EA/1048576)}MB`}(E.size),nA=`size:${W} time:${P}ms speed:${Nr(1e3*E.size/P)}`;return g.debug("uploadToCOS",`${r} ok. name:${E.name} ${nA}`),{uploadOptions:D,response:N}}catch(f){throw g.warn("uploadToCOS",`${r} failed, error:${u(f)}`),f}})}_handleUploadError(s,r){var g,u;const{ChatError:E}=(g=this._core)===null||g===void 0?void 0:g.helper;if(s.statusCode===403)throw r.url,!((u=s?.data)===null||u===void 0)&&u.uploadIP&&s.data.uploadIP,new E({message:"Upload failed with status 403"})}_createUploadResult(s,r){return{fileName:s.name,fileSize:s.size,fileType:s.type.slice(s.type.indexOf("/")+1).toLowerCase(),location:r.data.location||"",uploadTime:xr(Date.now(),!1),uploadSpeed:Nr(1e3*s.size/xr(Date.now(),!1))}}_createCosOptions(s){return mA(this,void 0,void 0,function*(){const{fileName:r,resources:g,uploadMethod:u}=yield this._prepareUploadParams(s),E=this._isC2CConversation(s.message.conversationID)?1:2;try{const f=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:r,uploadMethod:u,duration:this.duration,userID:s.message.from,conversationType:E}),{uploadUrl:D,downloadUrl:v,requestSnapshotUrl:N,thumbUrl:P,largeUrl:W,fileKey:nA,existFlag:EA}=f,wA=!Vt.isPrivateNetWork()&&f.uploadIP;return{url:this._getRawOrUploadProxyUrl(D),fileType:this.uploadFileType,fileName:r,resources:g,downloadUrl:v,requestSnapshotUrl:N,thumbUrl:P,largeUrl:W,fileKey:nA,uploadIP:wA||"",fileExistsInCOS:EA===1,onProgress:kA=>this._handleUploadProgress(kA,s)}}catch(f){throw console.error("Failed to create COS pre-signed URL options:",f),f}})}_prepareUploadParams(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g,isEmpty:u}}=this._core;r.debug("_prepareUploadParams",` prepareUploadParams:${g(s)}`);const{file:E}=s,{IN_MINI_APP:f,IN_RN_APP:D}=Vt.getPlatformFlags(),v=f||D,N=v&&s.message.type!==Ka,{name:P}=E,W=P.slice(P.lastIndexOf(".")),nA=`${Pr(999999)}${W}`,EA=N?E.name:nA,wA=yield this._generateHashFileName(E);return{fileName:u(wA)?dg(EA):`${wA}${W}`,resources:v?E.url:E,uploadMethod:v?1:0}})}_generateHashFileName(s){return mA(this,void 0,void 0,function*(){const{utils:{IN_MINI_APP:r,IN_BROWSER:g,IN_UNI_NATIVE_APP:u,isArray:E},ssoLog:f}=this._core,D=Date.now();let v="";return g&&(v=yield this._generateHashFileNameInWeb(s)),r&&(E(s.tempFiles)&&(s=s.tempFiles[0]),u||(v=yield this._generateFileNameInMiniProgram(s)),u&&(v=yield this._generateFileNameInUNINativeApp(s))),f.info("_generateHashFileName",`hashFileName:${v} costTime:${Date.now()-D}`),v})}_generateHashFileNameInWeb(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;let u="";try{u=yield new Promise((E,f)=>{const D=File.prototype.slice||File.prototype.mozSlice||File.prototype.webkitSlice;D||(r.warn("_generateHashFileNameInWeb","Browser does not support file slicing"),E(""));const v=10485760,N=Math.ceil(s.size/v);let P=0;const W=new SC.ArrayBuffer,nA=new FileReader,EA=setTimeout(()=>{nA.abort(),r.warn("_generateHashFileNameInWeb","File hash generation timeout"),E("")},2e3);function wA(){const kA=P*v,VA=kA+v>=s.size?s.size:kA+v;nA.readAsArrayBuffer(D.call(s,kA,VA))}nA.onload=kA=>{r.debug("_generateHashFileNameInWeb",`read chunk nr ${P+1} of ${N}`),W.append(kA.target.result),P++,P{clearTimeout(EA),f(kA)},wA()})}catch(E){r.warn("_generateHashFileNameInWeb",g(E))}return u})}_generateFileNameInMiniProgram(s){return mA(this,void 0,void 0,function*(){const{utils:{MINI_APP_NAMESPACE:r,safeStringify:g,isEmpty:u},ssoLog:E}=this._core;let f="";if(u(s.url))return E.warn("_generateFileNameInMiniProgram","file.url is empty"),f;if(typeof r?.getFileSystemManager!="function")return E.warn("_generateFileNameInUNINativeApp","getFileSystemManager is not a function"),f;try{f=yield new Promise((D,v)=>{r.getFileSystemManager().getFileInfo({filePath:s.url,success:N=>{D(N.digest)},fail:N=>{v(N)}})})}catch(D){E.warn("_generateFileNameInMiniProgram",g(D))}return f})}_generateFileNameInUNINativeApp(s){return mA(this,void 0,void 0,function*(){var r;const{utils:{safeStringify:g,isEmpty:u},ssoLog:E}=this._core;let f="";if(u(s.url))return E.warn("_generateFileNameInUNINativeApp","file.url is empty"),f;if(typeof((r=plus==null?void 0:plus.io)===null||r===void 0?void 0:r.getFileInfo)!="function")return E.warn("_generateFileNameInUNINativeApp","plus.io.getFileInfo is not a function"),f;try{f=yield new Promise((D,v)=>{plus.io.getFileInfo({filePath:s.url,success:N=>{D(N.digest)},fail:N=>{v(N)}})})}catch(D){E.warn("_generateFileNameInMiniProgram",g(D))}return f})}_handleUploadProgress(s,r){if(typeof r.onProgress=="function")try{r.onProgress(s.percent)}catch(g){throw console.warn("Upload progress callback error:",g),g}}_fetchCosSignatureUrl(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core,u=Vt.isSimpleCos(),E=this._prepareCosRequestData(s),f=u?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const D=yield function(N,P,W){return mA(this,void 0,void 0,function*(){try{const{helper:nA,channel:EA}=W,wA=nA.generateCosSpecifiedData({servcmd:N,data:P}),kA=`${wA.head.seq}${N}`;return yield EA.sendPacket(wA,{requestId:kA})}catch(nA){throw console.warn("getCosSig error:",nA),nA}})}(f,E,this._core);this.fetchCosTryCount=0;const v=this._processResponse(D);return r.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${u} data:${g(v)}`),v||{}}catch(D){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(s);throw this.fetchCosTryCount=0,D}})}_processResponse(s){var r;const g=Vt.isSimpleCos(),u=g?(r=s?.rpt_pre_sig)===null||r===void 0?void 0:r[0]:s;if(!u)return{};if(g){const{str_final_ip:W,rpt_pre_sig:nA,uint32_file_id:EA,uint32_exist_flag:wA,str_download_url:kA,str_upload_url:VA,str_snapshot_url:LA,str_file_key:SA}=u;return{uploadIP:W,preSig:nA,fileID:EA,existFlag:wA,downloadUrl:kA,uploadUrl:VA,requestSnapshotUrl:LA,fileKey:SA}}const{upload_url:E,download_url:f,snapshot_url:D,thumb_url:v,large_url:N,file_key:P}=u;return{uploadUrl:E,downloadUrl:f,requestSnapshotUrl:D,thumbUrl:v,largeUrl:N,fileKey:P}}_prepareCosRequestData(s){return Vt.isSimpleCos()?{uint32_upload_method:s.uploadMethod,uint32_platform:Vt.getPlatform(),uint32_sdkappid:Vt.getSDKAppID(),str_user_id:s.userID,uint32_scene:s.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:s.fileType,str_file_name:s.fileName}]}:{file_type:s.fileType,file_name:s.fileName,upload_method:s.uploadMethod,Duration:s.duration}}_uploadFile(s){return mA(this,void 0,void 0,function*(){return new Promise((r,g)=>{this.httpRequest.request(s,(u,E)=>{u&&this.uploadFileTryCount=3e4}_syncSystemClock(s){var r,g,u;const E=((r=s.headers)===null||r===void 0?void 0:r.date)||((g=s.headers)===null||g===void 0?void 0:g.Date)||((u=s.error)===null||u===void 0?void 0:u.ServerTime);if(E){const f=Date.now(),D=Date.parse(E);this.systemClockOffset=D-f}}_getRawOrUploadProxyUrl(s){const r=Vt.getFileUploadProxy();let g=s;return r&&(g=s.replace(/^https:\/\/[^/]+/,r)),g}_isC2CConversation(s){return s.slice(0,3)==="C2C"}};const U=2108,sA=2251,k=2252,x=2253,iA=["jpg","jpeg","gif","png","bmp","image","webp"],uA={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255},_A=1,ie=2;class ye{constructor(r,g){this.instanceID=Pr(9999999),this.sizeType=r.type||0,this.type=0,this.size=r.size||0,this.width=r.width||0,this.height=r.height||0,this.imageUrl=Vt.addAuthToUrl(r.imageUrl||r.url||""),this.url=Vt.addAuthToUrl(r.url||g)}setSizeType(r){this.sizeType=r}setType(r){this.type=r}setImageUrl(r){r&&(this.imageUrl=Vt.addAuthToUrl(r))}getImageUrl(){return this.imageUrl}}function p(s){const{originUrl:r,originWidth:g,originHeight:u,min:E=198}=s,f=parseInt(g)||0,D=parseInt(u)||0,v={url:void 0,width:0,height:0};if((f<=D?f:D)<=E)v.url=r,v.width=f,v.height=D;else{D<=f?(v.width=Math.ceil(f*E/D),v.height=E):(v.width=E,v.height=Math.ceil(D*E/f));const N=r&&r.indexOf("?")>-1?`${r}&`:`${r}?`;v.url=E===198?`${N}imageView2/3/w/198/h/198`:`${N}imageView2/3/w/720/h/720`}if(r===void 0){const{url:N}=v;return vo(v,["url"])}return v}class B{constructor(r){this._imageMemoryURL="",this._percent=0,this.type=gc;const{uuid:g,file:u,imageFormat:E,imageInfoArray:f=[],isCustomUpload:D=!1}=r;this._imageMemoryURL=this.createImageDataAsURL(u),this.content={imageFormat:E,uuid:g,imageInfoArray:[]},this[jr]=D,this.initImageInfoArray(f),this.autoFixUrl()}static parseServerPushElement(r){const{MsgContent:g}=r,{ImageFormat:u,ImageInfoArray:E,UUID:f}=g,D=function(v){return v.map(N=>({size:N.Size,type:N.Type,width:N.Width,height:N.Height,url:N.URL}))}(E);return new B({imageFormat:u,imageInfoArray:D,uuid:f})}createImageDataAsURL(r){let g="";const{IN_MINI_APP:u,IN_RN_APP:E,IN_BROWSER:f}=Vt.getPlatformFlags();return r&&((u||E)&&(g=r.url),f&&(g=window.URL.createObjectURL(r))),g}initImageInfoArray(r=[]){const g={type:0,size:0,width:0,height:0,url:""};for(let u=0;u<3;u++){const E=r[u]||Object.assign({},g),f=new ye(E,this._imageMemoryURL);f.setSizeType(u+1),f.setType(u),this.addImageInfo(f)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const r=["http","https"];this.content.imageInfoArray.forEach(g=>{if(!g.url||g.imageUrl==="")return;const[u,...E]=g.imageUrl.split("://"),f=E.join("://");r.includes(u)||g.setImageUrl(`https://${f}`)})}updatePercent(r){this._percent=Math.min(r,1)}updateImageFormat(r){this.content.imageFormat=uA[r.toUpperCase()]||uA.UNKNOWN}addImageInfo(r){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(r)}updateImageInfoArray(r){const g=this.content.imageInfoArray.length;let u;for(let E=0;E({InstanceId:g.instanceID,Type:g.sizeType,MsgType:g.type,Size:g.size,Width:g.width,Height:g.height,URL:Vt.removeAuthToUrl(g.imageUrl)}))}}const M=new class{init(s){this.core=s}},G={[ru]:"i",[Cl]:"a",[Da]:"v",[VE]:"f"};let O=null,z=null;function X(s){var r;const{store:g,utils:{isNumber:u,safeStringify:E},ssoLog:f}=M.core;try{const D=((r=g.get("cloudConfig"))===null||r===void 0?void 0:r.upload_size_limit)||"";D!==z&&(z=D,O=JSON.parse(D)||{});const v=O?.[G[s]];if(u(v))return 1024*v*1024}catch(D){f.debug("getCloudControlUploadSizeLimit",E(D))}return null}var gA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var r;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:f}=s;u.registerApi({apiName:"createImageMessage",context:this}),u.registerExperimentalAPI("createImageMessage",this,"createCustomUploadImageMessage"),(r=f?.messageFactory)===null||r===void 0||r.registerElementClass(gc,B),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createImageMessage(s){var r,g,u;try{const E=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,f=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:E})),D=this._processImage(s);s.payload.file=D;const v={imageFormat:uA.UNKNOWN,uuid:Vt.generateUUID(D),file:D,imageInfoArray:[]},N=new B(v);return f.setElement(N),this._messageOptionsMap.set(f.clientSequence,s),f}catch(E){throw E}}createCustomUploadImageMessage(s){var r,g,u,E;const{store:f,utils:{isEmpty:D}}=this._core,v=(r=f.get("login"))===null||r===void 0?void 0:r.userId,N=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:v})),{largeImageUuid:P,largeFileSize:W,largeImageWidth:nA,largeImageHeight:EA,largeImageUrl:wA,originImageUuid:kA,originFileSize:VA,originImageWidth:LA,originImageHeight:SA,originImageUrl:PA,thumbImageUuid:zA,thumbFileSize:Ee,thumbImageWidth:Ie,thumbImageHeight:Li,thumbImageUrl:Ui}=((E=s?.payload)===null||E===void 0?void 0:E.file)||{};if(D(PA)||D(kA))throw new Error("createImageMessageExperimental originImageUrl or originImageUuid is empty");const Yt=new B({imageFormat:uA.UNKNOWN,uuid:kA,imageInfoArray:[{instanceID:kA,size:VA,width:LA,height:SA,imageUrl:PA,url:PA},{instanceID:P,size:W,width:nA,height:EA,imageUrl:wA,url:wA},{instanceID:zA,size:Ee,width:Ie,height:Li,imageUrl:Ui,url:Ui}],isCustomUpload:!0});return N.setElement(Yt),this._messageOptionsMap.set(N.clientSequence,s),N._skipUpload=!0,N}upload(s){return mA(this,void 0,void 0,function*(){const r=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadImage(g);const u=yield this._performImageUpload(r,s,g),E=this._generateImageInfo(u);return r.updateImageFormat(u?.fileType),r.updateImageInfoArray(E),this._updateImageType(r.content.imageInfoArray),s})}_performImageUpload(s,r,g){return mA(this,void 0,void 0,function*(){const{to:u}=r,E={uploadFileType:ru,file:g,to:u,message:r,onProgress:v=>{var N,P;s.updatePercent(v),(P=(N=this._messageOptionsMap.get(r.clientSequence))===null||N===void 0?void 0:N.onProgress)===null||P===void 0||P.call(N,v)}},{uploadOptions:f,response:D}=yield K.uploadToCOS(E);return this._parseResponse(f,D)})}_generateImageInfo(s){const{location:r,fileSize:g,width:u,height:E,smallImageUrl:f,smallImageWidth:D,smallImageHeight:v,largeImageUrl:N,largeImageWidth:P,largeImageHeight:W,imageInfoArray:nA}=s,EA=Vt.addAuthToUrl(r),wA={size:g,url:EA,width:u,height:E};return nA?.length>0?this._processImageInfoArray(nA,g):f&&N?[Object.assign({},wA),{largeImageUrl:N,largeImageWidth:P,largeImageHeight:W},{smallImageUrl:f,smallImageWidth:D,smallImageHeight:v}]:[Object.assign({},wA),this._generateThumbInfo(EA,u,E,720),this._generateThumbInfo(EA,u,E,198)]}_generateThumbInfo(s,r,g,u){return p({originUrl:s,originWidth:r,originHeight:g,min:u})}_processImageInfoArray(s,r){let g,u,E;for(const f of s)f.type===1?(u=f,u.size=r):f.type===2?(E=f,E.size=r):(g=f,g.size=r);return[Object.assign({},g),Object.assign({},E),Object.assign({},u)]}_parseResponse(s,r){return mA(this,void 0,void 0,function*(){try{const{thumbUrl:g,largeUrl:u,downloadUrl:E}=s;if(g&&u&&(yield this._getImageInfoByUrl(g,r,"thumb"),yield this._getImageInfoByUrl(u,r,"large")),Vt.isSimpleCos()&&!Vt.isPrivateNetWork()&&(yield this._getImageInfoArray(E,r),r?.uploadIP)){const f=this._extractDomainFromUrl(E);f&&(yield this._getDownloadIP(f,r))}return r}catch(g){throw g}})}_extractDomainFromUrl(s){var r;try{const g=s.match(/:\/\/([^\/]+)/);return g?g[1]:null}catch(g){return(r=this._core)===null||r===void 0||r.ssoLog.warn("_extractDomainFromUrl",`Failed to extract domain from URL:${g.message}`),null}}_getImageInfoByUrl(s,r,g){return mA(this,void 0,void 0,function*(){var u;try{const E=Vt.addAuthToUrl(s),{width:f=0,height:D=0}=yield Vt.probeImageWidthHeight(E);r.width=f,r.height=D,g==="thumb"?(r.smallImageUrl=s,r.smallImageWidth=f,r.smallImageHeight=D):(r.largeImageUrl=s,r.largeImageWidth=f,r.largeImageHeight=D)}catch(E){(u=this._core)===null||u===void 0||u.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${g} image info:${E.message}`)}})}_validateBeforeUploadImage(s){var r;const{ChatError:g}=(r=this._core)===null||r===void 0?void 0:r.helper;if(!s)throw new g({code:sA});this._checkImageType(s),this._checkImageSize(s)}_processImage(s){var r;try{const{IN_MINI_APP:g}=(r=this._core)===null||r===void 0?void 0:r.utils;let{file:u}=s.payload;return u=g?this._processMiniAppImageFile(u):this._processWebImageFile(u),u}catch(g){throw g}}_processMiniAppImageFile(s){dl(s)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const r=s.tempFiles[0].path||s.tempFiles[0].tempFilePath;return{url:r,name:r.slice(r.lastIndexOf("/")+1),size:s.tempFiles&&s.tempFiles[0].size||1,type:r.slice(r.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(s){var r;const{ChatError:g}=(r=this._core)===null||r===void 0?void 0:r.helper,u=Vt.extractFileFromInput(s);if(!u)throw new g({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return u}_getDownloadIP(s,r){return mA(this,void 0,void 0,function*(){const g=`${ya} getDownloadIP domainName: ${s}`;try{const u=yield function(f,D){return mA(this,void 0,void 0,function*(){try{const{helper:v,channel:N}=D,P="im_cos_msg.get_final_ip",W={str_domain:f},nA=v.generateProtocolData({servcmd:P,data:W}),EA=`${nA.head.seq}${P}`;return yield N.sendPacket(nA,{requestId:EA})}catch(v){throw console.warn("getFinalIP error:",v),v}})}(s,this._core);if(!u||!u.str_final_ip)return;console.log(`${g} ok. downloadIP:${u}`);const E=r.location.split("/");E[0]=u.str_final_ip,r.location=E.join("/")}catch(u){console.warn(u)}})}_getImageInfoArray(s,r){return mA(this,void 0,void 0,function*(){try{const g=yield function(u,E){return mA(this,void 0,void 0,function*(){try{const{helper:f,channel:D}=E,v="im_cos_msg.get_imageinfo",N={str_image_url:u},P=f.generateProtocolData({servcmd:v,data:N}),W=`${P.head.seq}${v}`;return yield D.sendPacket(P,{requestId:W})}catch(f){throw console.warn("getImageInfo error:",f),f}})}(s,this._core);return r.imageInfoArray=this._processImageInfoResponse(g),r}catch(g){throw r.imageInfoArray=void 0,g}})}_processImageInfoResponse(s){if(!s)return[];const{rpt_msg_image_info:r}=s;return r.map(g=>({type:g.uint32_image_type,url:g.str_url,width:g.uint32_width,height:g.uint32_height,imageFormat:g.str_image_format}))}_checkImageType(s){const{utils:r,helper:g}=this._core;let u="";if(r.IN_MINI_APP&&(u=s.url.slice(s.url.lastIndexOf(".")+1)),r.IN_BROWSER&&(u=s.name.slice(s.name.lastIndexOf(".")+1)),iA.indexOf(u.toLowerCase())<0)throw new g.ChatError({code:k})}_checkImageSize(s){const{utils:r,helper:g,store:u}=this._core;let E=0;if(E=(r.IN_MINI_APP,s.size),E===0)throw new g.ChatError({code:U});if(E>=(X(ru)||20971520))throw new g.ChatError({code:x})}_updateImageType(s){s[1].type=ie,s[2].type=_A}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const DA=2108,GA=2401,KA=2402,re="2.5.0",Qe="1.18.0";function At(s,r){const g=s.split("."),u=r.split("."),E=Math.max(g.length,u.length);for(;g.lengthv)return 1;if(D0;return{isValid:r,error:r?null:{message:"content can not be empty"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{uuid:E,downloadFlag:f,fileUrl:D,fileName:v,fileSize:N}=u;return{MsgType:this.type,MsgContent:{Download_Flag:f,Url:Vt.removeAuthToUrl(D),FileName:v,FileSize:N,UUID:E}}}_getFileInfo(r){const{utils:{IN_UNI_NATIVE_APP:g}}=M.core;if(r.fileName&&r.fileSize)return{size:r.fileSize,name:r.fileName};const{file:u}=r;return u?(g&&this._processNativeAppFile(u),{size:u.size,name:u.name}):{size:0,name:""}}_processNativeAppFile(r){if(r.path&&r.path.includes(".")){const g=r.path.slice(r.path.lastIndexOf(".")+1).toLowerCase();r.type=g,r.name||(r.name=`${Pr(999999)}.${g}`)}r.name||(r.type="",r.name=r.path.slice(r.path.lastIndexOf("/")+1).toLowerCase()),r.suffix&&(r.type=r.suffix),r.url||(r.url=r.path)}}lt=jr;var xt=new class{constructor(){this._messageOptionsMap=new Map}init(s){var r;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:f}=s;u.registerApi({apiName:"createFileMessage",context:this}),u.registerExperimentalAPI("createFileMessage",this,"createCustomUploadFileMessage"),(r=f?.messageFactory)===null||r===void 0||r.registerElementClass(Ka,dt),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createFileMessage(s){var r,g,u;try{this._checkVersion();const E=this._processFile(s.payload.file);s.payload.file=E;const f=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:f})),v={uuid:Vt.generateUUID(E),file:E},N=new dt(v);return D.setElement(N),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadFileMessage(s){var r,g,u;try{const{store:E,message:f,utils:{isEmpty:D}}=this._core,v=(r=E.get("login"))===null||r===void 0?void 0:r.userId,{url:N,uuid:P,fileSize:W,fileName:nA=""}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{};if(D(N))throw new Error("url is required");const EA=(u=f.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:v})),wA=new dt({url:N,uuid:P,file:{size:W,name:nA},isCustomUpload:!0});return EA.setElement(wA),EA}catch(E){throw E}}upload(s){return mA(this,void 0,void 0,function*(){const{file:r}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadFile(r);const g=s.getElements()[0],u=yield this._performFileUpload(g,s,r),E=Vt.addAuthToUrl(u?.location);return g.updateFileUrl(E),s})}_validateBeforeUploadFile(s){const{helper:{ChatError:r}}=this._core;if(!s)throw new r({code:GA});const g=X(VE)||104857600;if(s.size>g)throw new r({code:KA});if(s.size===0)throw new r({code:DA})}_performFileUpload(s,r,g){return mA(this,void 0,void 0,function*(){const{to:u}=r,E={uploadFileType:VE,file:g,to:u,message:r,onProgress:D=>{var v,N;s.updatePercent(D),(N=(v=this._messageOptionsMap.get(r.clientSequence))===null||v===void 0?void 0:v.onProgress)===null||N===void 0||N.call(v,D)}},{response:f}=yield K.uploadToCOS(E);return f})}_processFile(s){var r,g;const{IN_BROWSER:u,IN_RN_APP:E,IN_WX_MINI_APP:f,IN_QQ_MINI_APP:D,IN_UNI_NATIVE_APP:v}=(r=this._core)===null||r===void 0?void 0:r.utils,{ChatError:N}=(g=this._core)===null||g===void 0?void 0:g.helper;if(u||v){const P=Vt.extractFileFromInput(s);if(!P)throw new N({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return P}if(f||D){const{tempFiles:P}=s;return Object.assign(Object.assign({},P[0]),{url:P[0].path})}return E?Object.assign(Object.assign({},s),{url:s.uri}):s}_checkVersion(){var s,r;const{MINI_APP_NAMESPACE:g,IN_MINI_APP:u,IN_WX_MINI_APP:E,IN_QQ_MINI_APP:f,IN_UNI_NATIVE_APP:D}=(s=this._core)===null||s===void 0?void 0:s.utils,{ChatError:v}=(r=this._core)===null||r===void 0?void 0:r.helper;if(u){if(!(E||f||D))throw new v({message:"Unsupported mini app environment"});const N=g.getSystemInfoSync().SDKVersion;if(E&&At(N,re)<0)throw new v({message:`WXChooseMessageFile requires SDK version ${re} or higher`});if(f&&At(N,Qe)<0)throw new v({message:`QQChooseMessageFile requires SDK version ${Qe} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const Wt=2108,Ki=2351,Eo=2352,so=["mp4","quicktime","mov","video"];var hi;class qo{constructor(r){this.type=Vl,this.uploadProgress=0,this[hi]=!1;const g=typeof r?.videoSecond=="number"?r?.videoSecond:0;this[jr]=r.isCustomUpload||!1,this.content={remoteVideoUrl:Vt.addAuthToUrl(r.remoteVideoUrl||r.videoUrl||""),videoFormat:r.videoFormat,videoSecond:parseInt(g?.toString(),10),videoSize:r.videoSize,videoUrl:Vt.addAuthToUrl(r.videoUrl),videoDownloadFlag:2,videoUUID:r.videoUUID,thumbUUID:r.thumbUUID,thumbFormat:r.thumbFormat,thumbWidth:r.thumbWidth,snapshotWidth:r.thumbWidth,thumbHeight:r.thumbHeight,snapshotHeight:r.thumbHeight,thumbSize:r.thumbSize,snapshotSize:r.thumbSize,thumbDownloadFlag:2,thumbUrl:Vt.addAuthToUrl(r.thumbUrl),snapshotUrl:Vt.addAuthToUrl(r.thumbUrl)}}static parseServerPushElement(r){const{MsgContent:g}=r,{VideoUrl:u,VideoFormat:E,VideoSecond:f,VideoSize:D,VideoDownloadFlag:v,VideoUUID:N,ThumbUUID:P,ThumbFormat:W,ThumbWidth:nA,SnapshotWidth:EA,ThumbHeight:wA,SnapshotHeight:kA,ThumbSize:VA,SnapshotSize:LA,ThumbDownloadFlag:SA,ThumbUrl:PA,SnapshotUrl:zA}=g;return new qo({videoUrl:u,videoFormat:E,videoSecond:f,videoSize:D,videoDownloadFlag:v,videoUUID:N,thumbUUID:P,thumbFormat:W,thumbWidth:nA,snapshotWidth:EA,thumbHeight:wA,snapshotHeight:kA,thumbSize:VA,snapshotSize:LA,thumbDownloadFlag:SA,thumbUrl:PA,snapshotUrl:zA})}updatePercent(r){this.uploadProgress=Math.min(r,1)}updateVideoUrl(r){r&&(this.content.remoteVideoUrl=r)}updateSnapshotInfo(r){const{snapshotUrl:g,snapshotWidth:u,snapshotHeight:E}=r;Vt.isEmpty(g)||(this.content.thumbUrl=this.content.snapshotUrl=g),Vt.isEmpty(u)||(this.content.thumbWidth=this.content.snapshotWidth=Number(u)),Vt.isEmpty(E)||(this.content.thumbHeight=this.content.snapshotHeight=Number(E))}validateBeforeSend(){if(this[jr])return{isValid:!0};const r=this.content.remoteVideoUrl!=="";return{isValid:r,error:r?null:{message:"content can not be empty"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{remoteVideoUrl:E,videoFormat:f,videoSecond:D,videoSize:v,videoDownloadFlag:N,videoUUID:P,thumbUUID:W,thumbFormat:nA,thumbWidth:EA,snapshotWidth:wA,thumbHeight:kA,snapshotHeight:VA,thumbSize:LA,snapshotSize:SA,thumbDownloadFlag:PA,thumbUrl:zA,snapshotUrl:Ee}=u;return{MsgType:this.type,MsgContent:{VideoUrl:Vt.removeAuthToUrl(E),VideoFormat:f,VideoSecond:D,VideoSize:v,VideoDownloadFlag:N,VideoUUID:P,ThumbUUID:W,ThumbFormat:nA,ThumbWidth:EA,SnapshotWidth:wA,ThumbHeight:kA,SnapshotHeight:VA,ThumbSize:LA,SnapshotSize:SA,ThumbDownloadFlag:PA,ThumbUrl:Vt.removeAuthToUrl(zA),SnapshotUrl:Vt.removeAuthToUrl(Ee)}}}}hi=jr;var cn,yi=new class{constructor(){this._messageOptionsMap=new Map}init(s){var r;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:f}=s;u.registerApi({apiName:"createVideoMessage",context:this}),u.registerExperimentalAPI("createVideoMessage",this,"createCustomUploadVideoMessage"),(r=f?.messageFactory)===null||r===void 0||r.registerElementClass(Vl,qo),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createVideoMessage(s){var r,g,u;try{const E=this._processVideo(s);s.payload.file=E;const f=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:f})),v={videoFormat:E.videoFile.type,videoSecond:hr(E.videoFile.second,0),videoSize:E.videoFile.size,remoteVideoUrl:"",videoUrl:E.videoFile.url,videoUUID:Vt.generateUUID(E.videoFile),thumbUUID:Vt.generateUUID(E.videoFile,"jpg"),thumbWidth:E.width||200,thumbHeight:E.height||200,thumbUrl:E.thumbUrl,thumbSize:E.thumbSize,thumbFormat:"jpg"},N=new qo(v);return D.setElement(N),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadVideoMessage(s){var r,g,u;try{const{store:E,message:f}=this._core;this._validateCustomUploadVideoMessage(s);const D=(r=E.get("login"))===null||r===void 0?void 0:r.userId,{videoUrl:v,videoUuid:N,duration:P,snapshotUrl:W,snapshotUuid:nA,videoFileSize:EA,videoType:wA,snapshotWidth:kA,snapshotHeight:VA,snapshotFileSize:LA,snapshotType:SA="jpg"}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},PA=(u=f.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:D})),zA=new qo({videoFormat:wA,videoSecond:P||0,videoSize:EA,remoteVideoUrl:v,videoUrl:v,videoUUID:N,thumbUUID:nA,thumbWidth:kA||200,thumbHeight:VA||200,thumbUrl:W,thumbSize:LA,thumbFormat:SA,isCustomUpload:!0});return PA.setElement(zA),this._messageOptionsMap.set(PA.clientSequence,s),PA}catch(E){throw E}}upload(s){return mA(this,void 0,void 0,function*(){const r=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadVideo(g);const u=yield this._performVideoUpload(r,s,g),{location:E,snapshotInfo:f}=u,D=Vt.addAuthToUrl(E);return r.updateVideoUrl(D),Vt.isEmpty(f)||r.updateSnapshotInfo(f),s})}_validateBeforeUploadVideo(s){const{helper:{ChatError:r}}=this._core,g=X(Da)||104857600;if(s.videoFile.size>g)throw new r({code:Ki});if(s.videoFile.size===0)throw new r({code:Wt});if(so.indexOf(s.videoFile.type)===-1)throw new r({code:Eo})}_validateCustomUploadVideoMessage(s){var r;const{utils:{isEmpty:g,isNumber:u}}=this._core,{videoUrl:E,videoUuid:f,duration:D,snapshotUrl:v,snapshotUuid:N}=((r=s?.payload)===null||r===void 0?void 0:r.file)||{};if(g(E)||g(f)||!u(D)||g(v)||g(N))throw new Error("Invalid video message options: missing required fields (videoUrl, videoUuid, duration, snapshotUrl, snapshotUuid)")}_performVideoUpload(s,r,g){return mA(this,void 0,void 0,function*(){const{to:u}=r,E={uploadFileType:Da,file:g,to:u,message:r,onProgress:v=>{var N,P;s.updatePercent(v),(P=(N=this._messageOptionsMap.get(r.clientSequence))===null||N===void 0?void 0:N.onProgress)===null||P===void 0||P.call(N,v)}},{response:f,uploadOptions:D}=yield K.uploadToCOS(E);return{snapshotInfo:yield this._getSnapshotInfoByUrl(D.requestSnapshotUrl),location:f.location}})}_processVideo(s){var r,g;try{const{ChatError:u}=(r=this._core)===null||r===void 0?void 0:r.helper,{IN_MINI_APP:E,IN_BROWSER:f}=(g=this._core)===null||g===void 0?void 0:g.utils;let{file:D}=s.payload,v={};if(E&&(v=this._processMiniVideoFile(D),D.name=v.name,D.url=v.url,D.type=v.type),f){const N=Vt.extractFileFromInput(D);if(!N)throw new u({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});D=N,v=this._processWebVideoFile(D)}return D.videoFile=v,D.thumbUrl="",D.thumbSize=0,D}catch(u){throw console.warn(`${ya} _processFile error:`,u),u}}_processMiniVideoFile(s){const{utils:{IN_UNI_NATIVE_APP:r},helper:{ChatError:g}}=this._core;if(dl(s))throw new g({message:"FileUnsupportedInMiniApp"});Array.isArray(s.tempFiles)&&(s=s.tempFiles[0]);let u=s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase();return r&&(u=s.fileType||u),{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.size||1,second:s.duration||0,type:u}}_processWebVideoFile(s){const{name:r,size:g=1,duration:u=0,type:E}=s,f=E.split("/")[1];return{url:window.URL.createObjectURL(s),name:r,size:g,second:u,type:f}}_getSnapshotInfoByUrl(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r}=this._core;try{r.debug("_getSnapshotInfoByUrl",`${ya} _getSnapshotInfoByUrl url:${s}`);const g={version:1,platform:Vt.getPlatform(),cover_name:dg(Pr(99999)),snapshot_url:s},u=yield function(N,P){return mA(this,void 0,void 0,function*(){try{const W="im_cos_msg.video_cover",{helper:nA,channel:EA}=P,wA=nA.generateCosSpecifiedData({servcmd:W,data:N}),kA=`${wA.head.seq}${W}`;return yield EA.sendPacket(wA,{requestId:kA})}catch(W){throw console.warn("getSnapshotInfo error:",W),W}})}(g,this._core),{download_url:E}=u||{};if(r.debug("_getSnapshotInfoByUrl",`${ya} _getSnapshotInfoByUrl OK snapshotUrl:${E}`),Vt.isEmpty(E))return{};const f=Vt.addAuthToUrl(E),{width:D=0,height:v=0}=yield Vt.probeImageWidthHeight(f);return{snapshotUrl:f,snapshotWidth:D,snapshotHeight:v}}catch(g){throw g}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};class to{constructor(r){this.uploadProgress=0,this.type=xg,this[cn]=!1,this[jr]=r.isCustomUpload||!1,this.content={downloadFlag:2,second:r.second,size:r.size,url:Vt.generateURL(r.url,{needAddAuthToUrl:!this[jr]}),remoteAudioUrl:Vt.addAuthToUrl(r.url||""),uuid:r.uuid}}static parseServerPushElement(r){const{MsgContent:g}=r,{Url:u,Download_Flag:E,Second:f,Size:D,UUID:v}=g;return new to({url:u,downloadFlag:E,second:f,size:D,uuid:v})}updatePercent(r){this.uploadProgress=Math.min(r,1)}updateAudioUrl(r){this.content.remoteAudioUrl=r}validateBeforeSend(){if(this[jr])return{isValid:!0};const r=this.content.remoteAudioUrl!=="";return{isValid:r,error:r?null:{message:"content can not be empty"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{uuid:E,downloadFlag:f,remoteAudioUrl:D,size:v,second:N}=u;return{MsgType:this.type,MsgContent:{Url:Vt.removeAuthToUrl(D),Download_Flag:f,Second:N,Size:v,UUID:E}}}}cn=jr;const rs=2108,be=2300,bt=2301;var OA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var r;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:f}=s;u.registerApi({apiName:"createAudioMessage",context:this}),u.registerExperimentalAPI("createAudioMessage",this,"createCustomUploadAudioMessage"),(r=f?.messageFactory)===null||r===void 0||r.registerElementClass(xg,to),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createAudioMessage(s){var r,g,u;try{let{file:E}=s.payload;E=this._processAudioFile(s.payload.file),s.payload.file=E;const f=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:f})),v={second:Math.max(1,Math.round((E.duration||E.second)/1e3)),size:E.fileSize||E.size||1,url:E.tempFilePath||E.uri||E.url,uuid:Vt.generateUUID(E)},N=new to(v);return D.setElement(N),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadAudioMessage(s){var r,g,u;try{this._validateCustomUploadOptions(s);const{store:E,message:f}=this._core,D=(r=E.get("login"))===null||r===void 0?void 0:r.userId,{url:v,uuid:N,duration:P,fileSize:W}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},nA=(u=f.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:D})),EA=new to({second:P,size:W||1,url:v,uuid:N,isCustomUpload:!0});return nA.setElement(EA),this._messageOptionsMap.set(nA.clientSequence,s),nA}catch(E){throw E}}upload(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;r.debug("upload",`${ya} uploadAudio message:${g(s)}`);const{file:u}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadAudio(u);const E=s.getElements()[0],f=yield this._performAudioUpload(E,s,u),D=Vt.addAuthToUrl(f?.location);return E.updateAudioUrl(D),s})}_validateBeforeUploadAudio(s){const{helper:{ChatError:r},store:g}=this._core;if(!s)throw new r({code:be});const u=X(Cl)||20971520;if(s.size>u)throw new r({code:bt});if(s.size===0)throw new r({code:rs})}_performAudioUpload(s,r,g){return mA(this,void 0,void 0,function*(){const{to:u}=r,E={uploadFileType:Cl,file:g,to:u,message:r,onProgress:D=>{var v,N;s.updatePercent(D),(N=(v=this._messageOptionsMap.get(r.clientSequence))===null||v===void 0?void 0:v.onProgress)===null||N===void 0||N.call(v,D)}},{response:f}=yield K.uploadToCOS(E);return f})}_processAudioFile(s){var r;const{IN_MINI_APP:g,IN_BROWSER:u}=(r=this._core)===null||r===void 0?void 0:r.utils;return g?this._processMiniFile(s):u?this._processWebFile(s):void 0}_processMiniFile(s){return{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.fileSize,second:s.duration,type:s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(s){if(s.tempFilePath||s.uri)return s;const r=URL.createObjectURL(s);return s.tempFilePath=r,s}_validateCustomUploadOptions(s){var r;const{utils:{isEmpty:g}}=this._core,{url:u,uuid:E,duration:f}=((r=s?.payload)===null||r===void 0?void 0:r.file)||{};if(g(u)||g(E)||g(f))throw new Error("Invalid audio message options")}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const oi={to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1},onProgress:{required:!1,rules:["function"],allowEmpty:!1}},ms={createImageMessage:oi,createAudioMessage:oi,createVideoMessage:oi,createFileMessage:oi},si={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},Dn={[gc]:gA,[Ka]:xt,[Vl]:yi,[xg]:OA};var Ni=new class{constructor(){this.name="RichMediaMessage"}install(s){this._core=s;const{constants:{OuterConstant:{MSG_AUDIO:r,MSG_FILE:g,MSG_IMAGE:u,MSG_VIDEO:E}}}=s;M.init(s),gA.init(s),xt.init(s),yi.init(s),OA.init(s),K.init(s),Vt.init(s),s.helper.registerApi({apiName:"sendMessage",context:this,matcher:f=>[r,g,u,E].includes(f[0].type)}),s.helper.registerValidateConfig({auth:si,params:ms})}sendMessage(s,r){return mA(this,void 0,void 0,function*(){var g,u,E;try{return this._isCustomUpload(s)||(yield this._upload(s)),yield(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(s,r)}catch(f){throw f}})}_upload(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;if(r.debug("_upload",` uploadFile message:${g(s)}`),s._relayFlag!==!0)try{const u=Dn[s.type];u&&(yield u.upload(s),r.info("_upload",` type:${s.type}`))}catch(u){throw s.status=au.FAIL,u instanceof Error&&(u.data={message:s}),this._core.message.messageDataHandler.storeConversationMessage(s),u}})}_isCustomUpload(s){var r,g;return((g=(r=s._elements)===null||r===void 0?void 0:r[0])===null||g===void 0?void 0:g[jr])===!0}};const yo=new class{init(s){this.core=s}};class yt{constructor(r){this.conversationID=r.conversationID||"",this.unreadCount=r.unreadCount||0,this.type=r.type||"",this.lastMessage=yo.core.common.buildLastMessage(r.lastMessage),this.peerReadTime=r.peerReadTime||0,this.groupAtInfoList=[],this.remark=r.remark||"",this.isPinned=r.isPinned||!1,this.messageRemindType=r.messageRemindType,this.markList=r.markList||[],this.customData=r.customData||"",this.conversationGroupList=r.conversationGroupList||[],this.draftText=r.draftText||"",this.userProfile=r.userProfile,this.groupProfile=r.groupProfile,this.subType=r.subType||"",this._isInfoCompleted=!1,this._init()}_init(){var r;const{core:{OuterConstant:g,utils:{isUndefined:u}}}=yo;u(this.userProfile)&&this.type===g.CONV_C2C?this.userProfile={userID:this.conversationID.replace(g.CONV_C2C,"")}:this.type===g.CONV_GROUP&&(!this.subType&&(!((r=this.groupProfile)===null||r===void 0)&&r.type)&&(this.subType=this.groupProfile.type),u(this.groupProfile)&&(this.groupProfile={groupID:this.conversationID.replace(g.CONV_GROUP,""),selfInfo:{},lastMessage:{},type:this.subType}))}updateUnreadCount(r){var g;const{core:{OuterConstant:u,utils:{isUndefined:E},store:f}}=yo,{nextUnreadCount:D,isFromGetConversations:v,isUnreadC2CMessage:N}=r;if(E(D))return;if(this.subType===u.GRP_AVCHATROOM)return void(this.unreadCount=0);if(v&&this.type===u.CONV_GROUP)return void(this.unreadCount=D);if(N&&this.type===u.CONV_C2C)return void(this.unreadCount=D);const P=((g=f.get("cloudConfig"))===null||g===void 0?void 0:g.support_unread_count_for_meeting)==="1";this.subType!==u.GRP_MEETING||P?this.unreadCount+=D:this.unreadCount=0}updateLastMessage(r){this.lastMessage=yo.core.common.buildLastMessage(r)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(r){const{core:{OuterConstant:g}}=yo,{sequence:u,time:E}=r;return this.type===g.CONV_C2C&&u===this.lastMessage.lastSequence&&E===this.lastMessage.lastTime||this.type===g.CONV_GROUP&&u===this.lastMessage.lastSequence}setLastMessageRevoked(r){this.lastMessage.isRevoked=r}setLastMessageRevoker(r){this.lastMessage.revoker=r}setDraftText(r){this.draftText=r}updateGroupAtInfoList(r){const{core:{common:{updateGroupAtInfo:g}}}=yo;g(r,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}const St=s=>{const{core:{OuterConstant:r,utils:{isString:g}}}=yo;return g(s)&&s.slice(0,3)===r.CONV_C2C},Cg=s=>{const{core:{OuterConstant:r,utils:{isString:g}}}=yo;return g(s)&&s.slice(0,5)===r.CONV_GROUP},qn=s=>{const{core:{OuterConstant:r,utils:{isString:g}}}=yo;return g(s)&&s===r.CONV_SYSTEM};function io(s){const{OuterConstant:r}=yo.core;let g="";return s===0?g=r.MSG_REMIND_ACPT_AND_NOTE:s===1?g=r.MSG_REMIND_DISCARD:s===2?g=r.MSG_REMIND_ACPT_NOT_NOTE:s===3&&(g=r.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}function Wr(s){const{OuterConstant:r}=yo.core;let g;return s.startsWith(r.CONV_C2C)&&(g=s.replace(r.CONV_C2C,"")),g==="@TLS#ERROR"||g==="@TLS#NOT_FOUND"}function cc(s,r){const{helper:g}=yo.core,u=new g.ChatError({functionName:s,code:r?.errorCode||r?.code,message:r?.errorInfo||r?.message});throw console.error(`${s} fail:`,u),u}var In,ua;(function(s){s[s.OFF=0]="OFF",s[s.ON=1]="ON"})(In||(In={})),function(s){s[s.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(ua||(ua={}));var Sa;(function(s){s[s.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",s[s.USER_OR_GRP_NOT_FOUND=2501]="USER_OR_GRP_NOT_FOUND",s[s.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE"})(Sa||(Sa={}));const oa=0,q=1;var QA=new class{constructor(){this._name="GetC2CMessageRemindType"}init(s){this._core=s}get(s){return mA(this,void 0,void 0,function*(){try{const{common:r}=this._core,g=yield function(E,f){return mA(this,void 0,void 0,function*(){const{toAccount:D,userIDList:v}=E,N={To_Account:D,Peer_Account:v};return f.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:N})})}({toAccount:r.getCurrentUserID(),userIDList:s},this._core),{MuteNotificationsList:u=[]}=g||{};u.forEach(E=>{const{Peer_Account:f,MuteNotifications:D}=E,v=`${this._core.OuterConstant.CONV_C2C}${f}`,N=io(D);NA.patchMessageRemindType([v],N)})}catch(r){console.error(`${this._name}.get fail:`,r)}})}},yA=new class{constructor(){this._name="GetGroupMessageRemindType"}init(s){this._core=s}get(s){return mA(this,void 0,void 0,function*(){if(s.length!==0)try{const r=yield function(u,E){return mA(this,void 0,void 0,function*(){const{groupIDList:f,responseFilter:D}=u,v={GroupIdList:f,ResponseFilter:D};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:v})})}({groupIDList:s,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:g=[]}=r||{};g.forEach(u=>{var E;const{GroupId:f,MemberList:D}=u,v=((E=D[0])===null||E===void 0?void 0:E.MsgFlag)||"",N=`${this._core.OuterConstant.CONV_GROUP}${f}`;NA.patchMessageRemindType([N],v)})}catch(r){console.error(`${this._name}.get fail:`,r)}})}},NA=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(s){this._core=s;const{helper:r,notificationCenter:g,appStore:{conversationStore:u},constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:f},InnerEvent:{SYNC_CONVERSATION_LIST:D,MESSAGE_PUSH:v,NEW_MESSAGE:N,MESSAGE_DELETED:P,MESSAGE_REVOKED:W,MESSAGE_MODIFIED:nA,CONVERSATION_UPDATED:EA,LOGOUT:wA,DESTROY:kA},InnerEventSubType:{C2C_MESSAGE_PEER_READ:VA}}=s;this._conversationStore=u,r.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,f.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),r.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,f.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),r.registerWorkflowStep(E.RECEIVE_C2C_NEW_MESSAGE,f.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),r.registerWorkflowStep(E.RECEIVE_C2C_NEW_MESSAGE,f.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),r.registerWorkflowStep(E.RECEIVE_GROUP_NEW_MESSAGE,f.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),r.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_RE_ONLINE,f.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),r.registerWorkflowStep(E.RECEIVE_GROUP_TIPS_NOTIFICATION,f.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this);const{InnerEventSubType:{GROUP_AT_TIPS:LA}}=g;g.subscribeInnerEvent(D,this._handleConversationSynced,this),g.subscribeInnerEvent(N,this._handleNewMessage,this),g.subscribeInnerEvent(v,LA,this._handleNewGroupAtTips,this),g.subscribeInnerEvent(P,this._handleMessageDeleted,this),g.subscribeInnerEvent(W,this._handleMessageRevoked,this),g.subscribeInnerEvent(nA,this._handleMessageModified,this),g.subscribeInnerEvent(EA,this._handleConversationUpdated,this),g.subscribeInnerEvent(v,VA,this._handleMessageRead,this),g.subscribeInnerEvent(wA,this._reset,this),g.subscribeInnerEvent(kA,this._dispose,this),s.ssoLog.debug(`${this._name}.init`)}_handleConversationSynced(s){this.updateLocalConversationList({conversationUpdateFieldList:s.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(s){const{constants:{WORKFLOW_STEP:r}}=this._core,{conversationUpdateFieldList:g=[],groupTipList:u=[],isUnreadC2CMessage:E}=s.result[r.UNREAD_MESSAGE_SYNC]||{};let f=!1;g.forEach(D=>{const{conversationID:v,unreadCount:N}=D,P=this.getLocalConversation(v);P&&P.unreadCount!==N&&(P.updateUnreadCount({nextUnreadCount:N,isUnreadC2CMessage:E}),f=!0)}),f&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(u)}_handleGroupAtTipsSynced(s){var r;for(let g=0;g0&&this._handleNewGroupAtTips({GroupTips:v._groupAtInfoList}),f=!0}f&&this.emitConversationListUpdate()}_handleNewMessage(s){const{conversationUpdateFieldList:r=[],isInstantMessage:g=!0,isUnreadC2CMessage:u=!1,updateUnreadCount:E=!0}=s.result||{};if(r.length===0)return;const{common:{isTopic:f}}=this._core;f(r[0].conversationID)||(this.updateLocalConversationList({conversationUpdateFieldList:r,isInstantMessage:g,isUnreadC2CMessage:u,isFromGetConversations:!1,updateUnreadCount:E}),r.filter(D=>this._isConversationNeedShow(D.conversationID)).length>0&&this.emitConversationListUpdate())}_handleNewGroupAtTips(s){const{GroupTips:r=[]}=s;r.forEach(g=>{const{GroupAtTips:u,MsgBody:E,MsgRandom:f,ClientSeq:D}=g;let v={};u?v=this._convertGroupAtTipsKey(u):E?v=Object.assign({},this._convertGroupAtTipsKey(E)):g.groupAtType&&(v=Object.assign({},g)),v.__random=f,v.__sequence=D,this._groupAtTipsList.push(v)}),console.log(`${this._name}._handleNewGroupAtTips groupAtTipsList: ${JSON.stringify(this._groupAtTipsList)}`),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(s){const{From_Account:r,GroupId:g,MsgSeq:u,GroupAtType:E}=s;return{from:r,groupID:g,sequence:u,groupAtType:E}}_updateGroupAtInfoList(){if(this._groupAtTipsList.length===0)return;const{common:s,OuterConstant:r}=this._core,g=s.getCurrentUserID();let u=!1;this._groupAtTipsList.forEach(E=>{const{groupID:f,from:D}=E;if(D!==g){const v=this.getLocalConversation(`${r.CONV_GROUP}${f}`);v&&(v.updateGroupAtInfoList(E),u=!0)}}),u&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(s){var r,g;console.log(`${this._name}._handleMessageDeleted, conversationID:`,s);const{message:{messageDataHandler:u},OuterConstant:E}=this._core,f=u?.getLocalMessageList(s)||[];let D={};for(let P=(f.length||0)-1;P>=0;P--)if(!f[P].isDeleted&&f[P]._isExcludedFromLastMessage!==!0){D=f[P];break}const v=this.getLocalConversation(s);if(!v)return;let N=!1;v.lastMessage.lastSequence===D.sequence&&v.lastMessage.lastTime===D.time||(!((g=(r=this._core)===null||r===void 0?void 0:r.helper)===null||g===void 0)&&g.isEmpty(D)&&(D=void 0),v.updateLastMessage(D),N=!0),s.startsWith(E.CONV_C2C)&&this.updateUnreadCount(s),N&&(this.emitConversationListUpdate(),console.log(`${this._name}._handleMessageDeleted. update conversationID:${s} with lastMessage:`,v.lastMessage))}_handleMessageRevoked(s){const{messageList:r=[],updateUnreadCount:g=!0}=s;if(console.log(`${this._name}._handleMessageRevoked messageList:${r.length}`),r.length===0)return;let u=null,E=!1;r.forEach(f=>{u=this.getLocalConversation(f.conversationID),u&&(g&&u.reduceUnreadCount()&&(E=!0),u.isLastMessageRevoked({sequence:f.sequence,time:f.time})&&(u.setLastMessageRevoked(!0),u.setLastMessageRevoker(f.revoker),E=!0))}),E&&this.emitConversationListUpdate()}_handleMessageModified(s){const{utils:{isEmpty:r},common:{getMessagePreviewText:g},ssoLog:u}=this._core;u.debug(`${this._name}._handleMessageModified`,JSON.stringify(s));const{conversationID:E,messageList:f}=s,D=this.getLocalConversation(E);if(r(D))return;const{lastMessage:v}=D;if(v){const N=f?.[0]||{};v.lastTime===N.time&&v.lastSequence===N.sequence&&v.version!==N.version&&(v.type=N.type,v.payload=N.payload,v.messageForShow=g(N.type,N.payload),v.cloudCustomData=N.cloudCustomData,v.version=N.version,this.emitConversationListUpdate(),console.log(`${this._name} conversationID:${E} lastMessage updated`))}}_handleConversationUpdated(s){this.emitConversationListUpdate(s?.needSort)}updateLocalConversationList(s){const{isFromGetConversations:r}=s,{newConversationList:g}=this._getTmpConversationListMapping(s);this._sortConversationList(),r||this._updateNewConversationProfile(g),this._core.ssoLog.debug("updateLocalConversationList",` newConversationList: ${g.length}`)}_getTmpConversationListMapping(s){const{OuterConstant:r}=this._core,{conversationUpdateFieldList:g,isFromGetConversations:u,isInstantMessage:E,isUnreadC2CMessage:f=!1,updateUnreadCount:D}=s,v=[],N=g?.length;for(let P=0;P{v[1].isPinned===!0?s(v[1].lastMessage.lastTime)?u.push(v):g.push(v):s(v[1].lastMessage.lastTime)?f.push(v):E.push(v)});const D=g.sort((v,N)=>N[1].lastMessage.lastTime-v[1].lastMessage.lastTime).concat(u).concat(E.sort((v,N)=>N[1].lastMessage.lastTime-v[1].lastMessage.lastTime)).concat(f);this._updateConversationMapFromList(D)}_updateNewConversationProfile(s){if(s.length===0)return;const r=[],g=[],{OuterConstant:{CONV_GROUP:u,CONV_C2C:E}}=this._core;s.forEach(f=>{const{conversationID:D,type:v}=f;if(v===E){const N=D.replace(E,"");r.push(N)}else if(v===u){const N=D.replace(u,"");g.push(N)}}),r.length>0&&this._updateC2CConversation(r),g.length>0&&this._updateGroupConversation(g)}_updateC2CConversation(s){var r;const{OuterConstant:{CONV_C2C:g},appStore:{userStore:u},user:E}=this._core;let f=!1;(r=E.userProfile)===null||r===void 0||r.getUserProfile({userIDList:s}).then(D=>{(D?.data||[]).forEach(v=>{var N;const{userID:P}=v,W=this.getLocalConversation(`${g}${P}`);if(W){const nA=((N=u.getFriend(P))===null||N===void 0?void 0:N.remark)||"";W.remark=nA,W.userProfile=v,f=!0}}),f&&this.emitConversationListUpdate()}).catch(D=>{}),QA.get(s)}_updateGroupConversation(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_GROUP:r},appStore:{groupStore:g},utils:{safeStringify:u},ssoLog:E,apiMap:{getGroupProfile:f}}=this._core;let D=!1;try{yield Promise.all(s.map(v=>mA(this,void 0,void 0,function*(){const N=g.getGroup(v),P=this.getLocalConversation(`${r}${v}`);N&&P&&(P.groupProfile=N,D=!0),P&&!P.getProfileCompleted()&&typeof f=="function"&&(yield f({groupID:v}))}))),yA.get(s),D&&this.emitConversationListUpdate()}catch(v){E.debug("_updateGroupConversation",u(v))}})}_handleMessageRead(s){const{OuterConstant:{CONV_C2C:r}}=this._core,{C2cNotifyMsgArray:g=[]}=s||{};g.forEach(u=>{const{To_Account:E,UinPairReadArray:f=[]}=u?.C2cReadedReceipt||{};f?.forEach(D=>{const{LastReadTime:v}=D,N=`${r}${E}`;this._updateConversationReadInfo({conversationID:N,peerReadTime:v}),this._updateMessageListPeerRead({conversationID:N,peerReadTime:v})})})}_updateConversationReadInfo(s){const{appStore:r,utils:{isEmpty:g},common:{getCurrentUserID:u}}=this._core,{conversationID:E,peerReadTime:f}=s,D=r.conversationStore.getConversationMap();if(D.has(E)){const v=D.get(E);v.peerReadTime=f;const N=v?.lastMessage;g(N)||N.fromAccount===u()&&N.lastTime<=f&&!N.isPeerRead&&(N.isPeerRead=!0,r.conversationStore.updateConversation(E,{lastMessage:N}))}}_updateMessageListPeerRead(s){const{notificationCenter:r,OuterEvent:g,message:u}=this._core,{conversationID:E,peerReadTime:f}=s,D=u.messageDataHandler.getLocalMessageList(E),v=u.messageDataHandler.getSparseMessageList(E),N=[];D.forEach(P=>{P.time<=f&&!P.isPeerRead&&P.flow==="out"&&(P.isPeerRead=!0,N.push(P))}),v.forEach(P=>{P.time<=f&&!P.isPeerRead&&P.flow==="out"&&(P.isPeerRead=!0,N.push(P))}),r.emitOuterEvent(g.MESSAGE_READ_BY_PEER,{name:g.MESSAGE_READ_BY_PEER,data:N})}_isConversationNeedShow(s){var r,g;const{OuterConstant:{CONV_GROUP:u,GRP_ROOM:E,GRP_LIVE:f},utils:{isUndefined:D}}=this._core,v=this.getLocalConversation(s);if(D(v))return!0;const N=v.type===u&&((r=v.groupProfile)===null||r===void 0?void 0:r.type)===E,P=v.type===u&&((g=v.groupProfile)===null||g===void 0?void 0:g.type)===f;return!(N||P)}updateUnreadCount(s,r=!0){var g,u;let E=!1;const f=this.getLocalConversation(s),D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageDataHandler)===null||u===void 0?void 0:u.getLocalMessageList(s);if(!f)return E;const v=f.unreadCount,N=D?.filter(P=>!P.isRead&&!P._onlineOnlyFlag&&!P.isDeleted).length;return console.log(`${this._name}._updateUnreadCount conversationID:${s} currentUnreadCount:${v} newUnreadCount:${N}`),v!==N&&(f.unreadCount=N,E=!0,r===!0&&this.emitConversationListUpdate()),E}emitConversationListUpdate(s=!1){var r,g;s&&this._sortConversationList();const{OuterEvent:{CONVERSATION_LIST_UPDATED:u},conversation:E}=this._core,f=this.getLocalConversationList();this._emitEvent({name:u,data:f,isSyncCompleted:(g=(r=E?.syncConversationHandler)===null||r===void 0?void 0:r.isSyncCompleted)===null||g===void 0?void 0:g.call(r)}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var s;const r=this.getTotalUnreadMessageCount();this._totalUnreadCount!==r&&(this._core.ssoLog.debug("_emitTotalUnreadCountUpdate",` from ${this._totalUnreadCount} to ${r}`),this._totalUnreadCount=r,this._emitEvent({name:(s=this._core)===null||s===void 0?void 0:s.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:r}))}_emitEvent(s){var r;(r=this._core)===null||r===void 0||r.notificationCenter.emitOuterEvent(s.name,s)}getTotalUnreadMessageCount(){const{OuterConstant:s,utils:{isEmpty:r}}=this._core,g=this.getLocalConversationList();let u=0;return g.forEach(E=>{E.type!==s.CONV_SYSTEM&&(r(E.messageRemindType)||E.messageRemindType===s.MSG_REMIND_ACPT_AND_NOTE)&&(u+=E.unreadCount)}),u}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter(s=>this._isConversationNeedShow(s.conversationID))}hasLocalConversation(s){return this._conversationStore.getConversationMap().has(s)}getLocalConversation(s){return this._conversationStore.getConversationMap().get(s)}setLocalConversation(s,r){return this._conversationStore.getConversationMap().set(s,r)}deleteLocalConversation(s){this._conversationStore.getConversationMap().delete(s)}_updateConversationMapFromList(s){this._clearConversationMap();for(const[r,g]of s)this.setLocalConversation(r,g)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(s,r){let g=!1;s.forEach(u=>{const E=this.getLocalConversation(u);E?.messageRemindType!==r&&(E.messageRemindType=r,g=!0)}),console.log(`${this._name}.patchMessageRemindType conversationIDList:${s} messageRemindType:${r} hasUpdated:${g}`),g&&this.emitConversationListUpdate()}markMessageAsRead(s){const{message:{messageDataHandler:r}}=this._core,{conversationID:g,lastReadTime:u=0,lastReadSequence:E=0}=s,f=r?.getLocalMessageList(g);if(f.length===0)return;const{length:D}=f;for(let v=D-1;v>=0;v--){const N=f[v],P=u&&N.time>u,W=E&&N.sequence>E;if(!P&&!W){if(N.flow==="in"&&N.isRead)break;N.setIsRead(!0)}}}appendToPinnedConversation(s){const r=[...this._conversationStore.getConversationMap().entries()],g=r.findIndex(u=>u[1].isPinned===!1);r.splice(g,0,[s.conversationID,s]),this._updateConversationMapFromList(r),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){const{notificationCenter:s,InnerEvent:{NEW_MESSAGE:r,MESSAGE_DELETED:g,MESSAGE_REVOKED:u,MESSAGE_MODIFIED:E,CONVERSATION_UPDATED:f,LOGOUT:D,DESTROY:v,SYNC_CONVERSATION_LIST:N}}=this._core,{InnerEventSubType:{GROUP_AT_TIPS:P}}=s;s.unSubscribeInnerEvent(r,this._handleNewMessage,this),s.unSubscribeInnerEvent(r,P,this._handleNewGroupAtTips,this),s.unSubscribeInnerEvent(g,this._handleMessageDeleted,this),s.unSubscribeInnerEvent(u,this._handleMessageRevoked,this),s.unSubscribeInnerEvent(E,this._handleMessageModified,this),s.unSubscribeInnerEvent(f,this._handleConversationUpdated,this),s.unSubscribeInnerEvent(N,this._handleConversationSynced,this),s.unSubscribeInnerEvent(D,this._reset,this),s.unSubscribeInnerEvent(v,this._dispose,this)}},ee=new class{constructor(){this._name="GetConversationList"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getConversationList",context:this})}getConversationList(s){return mA(this,void 0,void 0,function*(){return{code:0,data:{conversationList:this._getConversationList(s),isSyncCompleted:this._core.conversation.syncConversationHandler.isSyncCompleted()}}})}_getConversationList(s){const{utils:{isUndefined:r,isArray:g,isPlainObject:u}}=this._core;if(r(s))return NA.getLocalConversationList();if(g(s))return s.length===0?[]:NA.getLocalConversationList().filter(E=>s.includes(E.conversationID));if(u(s)){const{type:E,markType:f,groupName:D,hasUnreadCount:v,hasGroupAtInfo:N}=s;return NA.getLocalConversationList().filter(P=>this._filterType(P,E)&&this._filterMarkType(P,f)&&this._filterGroupName(P,D)&&this._filterUnreadCount(P,v)&&this._filterGroupAtInfo(P,N))}return[]}_filterType(s,r){const{OuterConstant:g}=this._core;return r!==g.CONV_C2C&&r!==g.CONV_GROUP||s.type===r}_filterGroupName(s,r){const{utils:{isString:g}}=this._core;return!g(r)||(r===""?s.conversationGroupList.length===0:s.conversationGroupList.includes(r))}_filterMarkType(s,r){const{utils:{isNumber:g}}=this._core;return!g(r)||(r===0?s.markList.length===0:s.markList.includes(r))}_filterUnreadCount(s,r){let g=!0;return r===!0?g=s.unreadCount>=1:r===!1&&(g=s.unreadCount===0),g}_filterGroupAtInfo(s,r){let g=!0;return r===!0?g=s.groupAtInfoList.length>=1:r===!1&&(g=s.groupAtInfoList.length===0),g}},Ne=new class{constructor(){this._name="GetConversationProfile"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_C2C:r,CONV_GROUP:g,GRP_AVCHATROOM:u},appStore:{groupStore:E},utils:{isEmpty:f}}=this._core,D={code:0,data:{}};let v=NA.getLocalConversation(s);if(qn(s))return D.data.conversation=v,D;let N=!1;const P=St(s)?r:g;if(f(v)&&(N=!0,v=new yt({conversationID:s,type:P})),console.log(`${this._name}.getConversationProfile conversationID:${s} isNewConversation:${N}`),D.data.conversation=v,v?.getProfileCompleted())return D;if(P===r){const W=s.replace(r,"");yield this._handleC2CConversation(v,W),N&&(yield QA.get([W]))}if(P===g){const W=s.replace(g,"");if(!E.getGroup(W))return D;yield this._handleGroupConversation(v,W),N&&v.groupProfile.type!==u&&(yield yA.get([W]))}return D})}_handleC2CConversation(s,r){return mA(this,void 0,void 0,function*(){var g,u;const{user:E,helper:f,utils:{isEmpty:D},appStore:{conversationStore:v,userStore:N}}=this._core,{conversationID:P}=s,W=yield(g=E.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:[r]});if(W?.data.length===0)throw new f.ChatError({code:Sa.USER_OR_GRP_NOT_FOUND});s.userProfile=W?.data[0];const nA=(u=N.getFriend(r))===null||u===void 0?void 0:u.remark;D(nA)||s.remark===nA||(s.remark=nA),s.setProfileCompleted();const EA=NA.hasLocalConversation(P);console.log(`${this._name}._handleC2CConversation conversationID:${P} hasLocalConversation: ${EA}`),EA?v.updateConversation(P,s):NA.appendToPinnedConversation(s)})}_handleGroupConversation(s,r){return mA(this,void 0,void 0,function*(){const{apiMap:{getGroupProfile:g},appStore:{conversationStore:u}}=this._core,{conversationID:E}=s,f=yield g({groupID:r});s.groupProfile=f?.data.group,s.setProfileCompleted();const D=NA.hasLocalConversation(E);console.log(`${this._name}._handleGroupConversation conversationID:${E} hasLocalConversation: ${D}`),D?u.updateConversation(E,s):NA.appendToPinnedConversation(s)})}},he=new class{init(s){const{helper:r}=s;r.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return NA.getTotalUnreadMessageCount()}},Ue=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(s){this._core=s;const{helper:r,common:{isTopic:g},notificationCenter:u,InnerEvent:{MESSAGE_PUSH:E},InnerEventSubType:{ALL_MESSAGE_READ:f}}=s;r.registerApi({apiName:"setMessageRead",context:this,matcher:D=>!g(D[0].conversationID)}),r.registerApi({apiName:"setAllMessageRead",context:this}),u.subscribeInnerEvent(E,f,this._handleAllMessageRead,this)}handleC2CMessageReadSync(s){const{helper:{isEmpty:r},OuterConstant:g}=this._core;s.forEach(u=>{const{ReadC2cMsgNotify:E}=u;if(!r(E)){const{UinPairReadArray:f=[]}=E;f.forEach(D=>{const{From_Account:v,LastReadTime:N}=D,P=`${g.CONV_C2C}${v}`;console.log(`${this._name}.handleC2CMessageReadSync conversationID:${P} lastReadTime:${N}`),NA.markMessageAsRead({conversationID:P,lastReadTime:N}),NA.updateUnreadCount(P)})}})}handleGroupMessageReadSync(s){const{OuterConstant:r,utils:{isUndefined:g}}=this._core;s.forEach(u=>{const{GroupReadInfoArray:E}=u.MsgBody;g(E)||E.forEach(f=>{const{GroupId:D,LastReadMsgSeq:v}=f,N=`${r.CONV_GROUP}${D}`;console.log(`${this._name}.handleGroupMessageReadSync conversationID:${N} lastReadSequence:${v}`),NA.markMessageAsRead({conversationID:N,lastReadSequence:v}),NA.updateUnreadCount(N),this._clearGroupAtInfoList(N)})})}setMessageRead(s){return mA(this,void 0,void 0,function*(){var r,g;const{OuterConstant:u}=this._core,{conversationID:E}=s,f={code:0,data:{}},D=NA.getLocalConversation(E);let v=`${this._name}.setMessageRead conversationID:${E} unreadCount:${D?.unreadCount||0}`;if(f.successLog={message:v},!D)return f;const N=!(!((g=(r=this._core)===null||r===void 0?void 0:r.helper)===null||g===void 0)&&g.isEmpty(D.groupAtInfoList));if(D.type===u.CONV_GROUP&&N&&this._deleteGroupAtTips(E),D.unreadCount===0)return f;const{helper:{ChatError:P}}=this._core;try{if(D.type===u.CONV_C2C){const W=this._getLocalMessageMaxTime(D);v+=`lastMessageTime:${W}`,yield this._setC2CMessageRead(E,W)}if(D.type===u.CONV_GROUP){const W=this._getLocalMessageMaxSequence(D);v+=`lastMessageSequence:${W}`,yield this._setGroupMessageRead(E,W)}}catch(W){const{errorCode:nA,errorInfo:EA}=W;throw new P({functionName:"setMessageRead",code:nA,message:EA,moreMessage:v})}return D.type===u.CONV_SYSTEM&&(D.unreadCount=0),NA.emitConversationListUpdate(),Object.assign(Object.assign({},f),{successLog:{message:v}})})}setAllMessageRead(){return mA(this,arguments,void 0,function*(s={}){const{OuterConstant:{READ_ALL_MSG:r},utils:{safeStringify:g}}=this._core;let u=`scope:${s.scope}`;s.scope||(s.scope=r);const{scope:E}=s,f=this._generateSetAllMessageReadRequestData(E);if(f.allC2CMessageReadStatus===oa&&f.groupMessageReadInfoList.length===0)return{code:0};try{const D=yield function(v){return mA(this,void 0,void 0,function*(){const{allC2CMessageReadStatus:N,groupMessageReadInfoList:P}=v,W={C2CReadAllMsg:N,GroupReadInfo:P};return yo.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:W})})}(f);if(D){const{GroupReadInfoArray:v,C2CReadAllMsg:N}=D,P=this._parseGroupReadInfo(v);this._updateAllConversationReadStatus({allC2CMessageReadStatus:N})>0&&NA.emitConversationListUpdate(),u+=`failureGroupInfoList:${g(P)}`}return{code:0,successLog:{message:u}}}catch(D){const{errorCode:v}=D;throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:v,moreMessage:u})}})}_handleAllMessageRead(s){const{GroupReadInfoArray:r,C2CReadAllMsg:g}=s;this._parseGroupReadInfo(r),this._updateAllConversationReadStatus({allC2CMessageReadStatus:g})>0&&NA.emitConversationListUpdate()}_updateAllConversationReadStatus(s){const{OuterConstant:{CONV_C2C:r,CONV_GROUP:g},appStore:u}=this._core,E=u.conversationStore.getConversationMap(),{allC2CMessageReadStatus:f}=s;let D=0;for(const[v,N]of E)if(N.unreadCount>=1){if(f===q&&N.type===r){const P=this._getLocalMessageMaxTime(N);NA.markMessageAsRead({conversationID:v,lastReadTime:P})}else if(N.type===g){const P=v.replace(g,"");if(this._serverGroupConversationLastReadSeqMap.has(P)){const W=this._serverGroupConversationLastReadSeqMap.get(P);NA.markMessageAsRead({conversationID:v,lastReadSequence:W})}}NA.updateUnreadCount(v,!1)&&(D+=1)}return D}_generateSetAllMessageReadRequestData(s){const{OuterConstant:{CONV_C2C:r,CONV_GROUP:g,READ_ALL_C2C_MSG:u},appStore:E}=this._core,f={allC2CMessageReadStatus:oa,groupMessageReadInfoList:[]},D=E.conversationStore.getConversationMap();for(const[,v]of D){const{type:N,unreadCount:P}=v;if(this._shouldSetAllMessageRead({scope:s,type:N,unreadCount:P})){if(N===r&&f.allC2CMessageReadStatus===oa){if(f.allC2CMessageReadStatus=q,s===u)break}else if(N===g){const W=this._getLocalMessageMaxSequence(v),{groupID:nA}=v.groupProfile;f.groupMessageReadInfoList.push({GroupId:nA,MsgSeq:W})}}}return f}_parseGroupReadInfo(s){const{utils:{isUndefined:r}}=this._core,g=[];return s?.forEach(u=>{const{GroupId:E,MsgSeq:f,RetCode:D,LastReadMsgSeq:v}=u;r(D)?this._serverGroupConversationLastReadSeqMap.set(E,v):(this._serverGroupConversationLastReadSeqMap.set(E,f),D!==0&&g.push(`${E}-${f}-${D}`))}),g}_deleteGroupAtTips(s){return mA(this,void 0,void 0,function*(){console.log(`${this._name}._deleteGroupAtTips conversationID:${s}`);const r=NA.getLocalConversation(s);if(!r)return;const g=r?.groupAtInfoList||[];if(g.length!==0)try{const{common:{getCurrentUserID:u,isCommunity:E},OuterConstant:{CONV_GROUP:f,CONV_AT_ALL:D}}=this._core;let v=[...g];if(E({groupID:s.replace(f,"")})&&(v=g.filter(P=>!P.atTypeArray.includes(D)),v.length===0))return void this._clearGroupAtInfoList(s,!1);const N=v.map(P=>({From_Account:P.from,To_Account:u(),MsgSeq:P.__sequence,MsgRandom:P.__random,GroupId:P.groupID}));yield function(P,W){return mA(this,void 0,void 0,function*(){const{messageListToDelete:nA}=P,EA={DelMsgList:nA};return W.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:EA})})}({messageListToDelete:N},this._core),console.log(`${this._name}._deleteGroupAtTips ok. count:${g.length}`),this._clearGroupAtInfoList(s)}catch(u){console.error(`${this._name}._deleteGroupAtTips fail:`,u)}})}_clearGroupAtInfoList(s,r=!0){const g=NA.getLocalConversation(s);g&&(g.groupAtInfoList.length>0&&(g.clearGroupAtInfoList(),console.log(`${this._name}._clearGroupAtInfoList conversationID:${s} needEmitConversationUpdate:${r}`)),r&&NA.emitConversationListUpdate())}_getLocalMessageMaxTime(s){var r;const{conversationID:g}=s,u=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...u.map(D=>D.time));let f=((r=s?.lastMessage)===null||r===void 0?void 0:r.lastTime)||0;return E>f&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${f} to ${E}`),f=E),f}_getLocalMessageMaxSequence(s){var r;const{conversationID:g}=s,u=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...u.map(D=>D.sequence));let f=((r=s?.lastMessage)===null||r===void 0?void 0:r.lastSequence)||0;return E>f&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${f} to ${E}`),f=E),f}_setC2CMessageRead(s,r){return mA(this,void 0,void 0,function*(){try{yield function(g,u){return mA(this,void 0,void 0,function*(){return u.common.buildAndSendPacket({servcmd:"openim.msgreaded",data:g})})}({C2CMsgReaded:{Cookie:"",C2CMsgReadedItem:[{To_Account:s.replace("C2C",""),LastedMsgTime:r,Receipt:1}]}},this._core),console.log(`${this._name}._setC2CMessageRead ok, lastReadTime:${r}`),NA.markMessageAsRead({conversationID:s,lastReadTime:r}),NA.updateUnreadCount(s)}catch(g){throw console.warn(`${this._name}._setC2CMessageRead fail:`,g),g}})}_setGroupMessageRead(s,r){return mA(this,void 0,void 0,function*(){try{yield function(g,u){return mA(this,void 0,void 0,function*(){const{groupID:E,lastMessageSequence:f}=g,D={GroupId:E,MsgReadedSeq:f};return u.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:D})})}({groupID:s.replace("GROUP",""),lastMessageSequence:r},this._core),console.log(`${this._name}._setGroupMessageRead ok, lastReadSequence:${r}`),NA.markMessageAsRead({conversationID:s,lastReadSequence:r}),NA.updateUnreadCount(s)}catch(g){throw console.warn(`${this._name}._setGroupMessageRead fail:`,g),g}})}_shouldSetAllMessageRead(s){const{OuterConstant:{CONV_C2C:r,CONV_GROUP:g,READ_ALL_MSG:u,READ_ALL_C2C_MSG:E,READ_ALL_GROUP_MSG:f}}=this._core,{type:D,scope:v,unreadCount:N}=s;return!(N<=0)&&(!(D!==r||![u,E].includes(v))||!(D!==g||![u,f].includes(v)))}},de=new class{constructor(){this._name="PinConversation"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(s,r){const{utils:{isArray:g}}=this._core;if(!g(s))return;const{OuterConstant:u}=this._core;let E=!1;s.forEach(f=>{const{Type:D,Peer_Account:v,GroupId:N}=f;let P;D===1?P=NA.getLocalConversation(`${u.CONV_C2C}${v}`):D===2&&(P=NA.getLocalConversation(`${u.CONV_GROUP}${N}`)),P&&(console.log(`${this._name}.handleConversationPinned conversationID:${P.conversationID} localPinned:${P.isPinned} remotePinned:${r}`),r&&!P.isPinned&&(P.isPinned=!0,E=!0),!r&&P.isPinned&&(P.isPinned=!1,E=!0))}),E&&NA.emitConversationListUpdate(!0)}pinConversation(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r,common:g,helper:{ChatError:u}}=this._core,{conversationID:E,isPinned:f}=s,D={code:0,data:{conversationID:E}},v=NA.getLocalConversation(E);if(v&&v.isPinned===f)return D;if(qn(E))return v&&(v.isPinned=f),NA.emitConversationListUpdate(!0),D;const N=`conversationID:${E} isPinned:${f}`;try{let P=null;if(St(E)?P={Type:1,To_Account:E.replace(r.CONV_C2C,"")}:Cg(E)&&(P={Type:2,GroupId:E.replace(r.CONV_GROUP,"")}),yield function(nA,EA){return mA(this,void 0,void 0,function*(){const{fromAccount:wA,operationType:kA,itemList:VA}=nA,LA={From_Account:wA,OperationType:kA,RecentContactItem:VA};return EA.common.buildAndSendPacket({servcmd:"recentcontact.top",data:LA})})}({fromAccount:g.getCurrentUserID(),operationType:f===!0?1:2,itemList:[P]},this._core)){if(v)v.isPinned!==f&&(v.isPinned=f);else{const nA=new yt({conversationID:E,type:St(E)?r.CONV_C2C:r.CONV_GROUP,isPinned:f});NA.setLocalConversation(E,nA)}NA.emitConversationListUpdate(!0)}return Object.assign(Object.assign({},D),{successLog:{message:N}})}catch(P){const{errorCode:W,errorInfo:nA}=P;throw new u({functionName:"pinConversation",code:W,message:nA,moreMessage:N})}})}},Ve=new class{constructor(){this._name="DeleteConversation"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(s){const{utils:{isArray:r}}=this._core;if(!r(s))return;const{OuterConstant:g}=this._core,u=[];s.forEach(E=>{const{Type:f,Peer_Account:D,GroupId:v}=E;f===1&&u.push(`${g.CONV_C2C}${D}`),f===2&&u.push(`${g.CONV_GROUP}${v}`)}),console.log(`${this._name}.handleConversationDeleted conversationIDList:${u}`),this._deleteLocalConversationList(u)}deleteConversation(s){return mA(this,void 0,void 0,function*(){const{utils:{isString:r}}=this._core;if(r(s))return this._deleteConversation({conversationIDList:[s],flag:ua.ONLY_CONVERSATIONID});const g=Object.assign({},s);return g.conversationIDList.length>100&&(g.conversationIDList=g.conversationIDList.slice(0,100)),this._deleteConversation(g)})}_deleteConversation(s){return mA(this,void 0,void 0,function*(){const{conversationIDList:r,clearHistoryMessage:g=!0,flag:u=0}=s,{helper:{ChatError:E}}=this._core,f=`conversationIDList:${r} clearHistoryMessage:${g}`;try{const D=yield Promise.all([this._deleteConversationFromLocal(r),this._deleteConversationFromServer(r,g)]),v=[...D[0],...D[1]];if(v.length===0)throw new this._core.helper.ChatError({code:Sa.CONV_NOT_FOUND});return{code:0,data:u===ua.ONLY_CONVERSATIONID?{conversationID:v[0]}:{conversationIDList:v},successLog:{message:f}}}catch(D){const{errorCode:v,errorInfo:N}=D;throw new E({code:v,message:N,moreMessage:f})}})}_deleteConversationFromLocal(s){const{OuterConstant:r}=this._core;return s.filter(g=>{var u;if(!NA.hasLocalConversation(g))return!1;const E=(u=NA.getLocalConversation(g))===null||u===void 0?void 0:u.type;return E!==r.CONV_GROUP||this._hasLocalGroup(g)?E===r.CONV_SYSTEM&&(this._deleteLocalConversation(g),!0):(this._deleteLocalConversation(g),!0)})}_deleteConversationFromServer(s,r){return mA(this,void 0,void 0,function*(){const{OuterConstant:g,common:u}=this._core,E={fromAccount:u.getCurrentUserID(),conversationList:[],clearHistoryMessage:r?1:0};if(s.forEach(D=>{var v;if(NA.hasLocalConversation(D)){const N=((v=NA.getLocalConversation(D))===null||v===void 0?void 0:v.type)||"",P=D.replace(N,"");N===g.CONV_C2C?E.conversationList.push({To_Account:P,Type:1}):N===g.CONV_GROUP&&this._hasLocalGroup(D)&&E.conversationList.push({ToGroupid:P,Type:2})}}),E.conversationList.length===0)return[];const f=yield function(D,v){return mA(this,void 0,void 0,function*(){const{fromAccount:N,conversationList:P,clearHistoryMessage:W}=D,nA={From_Account:N,ContactItem:P,ClearRamble:W};return v.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:nA})})}(E,this._core);if(f){const{ResultItem:D=[]}=f,v=[];return D.length>0&&D.forEach(N=>{if(N.ResultCode===0){const P=N.Type===1?`${g.CONV_C2C}${N.To_Account}`:`${g.CONV_GROUP}${N.ToGroupid}`;v.push(P)}}),this._deleteLocalConversationList(v),v}return[]})}_deleteLocalConversationList(s){let r=!1;s.forEach(g=>{NA.hasLocalConversation(g)&&(this._deleteLocalConversation(g,!1),r=!0)}),console.log(`${this._name}._deleteLocalConversationList isUpdate:${r}`),r&&NA.emitConversationListUpdate()}_deleteLocalConversation(s,r=!0){const g=NA.hasLocalConversation(s);console.log(`${this._name}._deleteLocalConversation conversationID:${s} has:${g}`),g&&(NA.deleteLocalConversation(s),this._deleteConversationLocalMessage(s),r&&NA.emitConversationListUpdate())}_hasLocalGroup(s){const{OuterConstant:{CONV_GROUP:r},appStore:{groupStore:g}}=this._core,u=s.replace(r,"");return!!g.getGroup(u)}_deleteConversationLocalMessage(s){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${s}`),this._core.message.messageDataHandler.deleteConversationMessageList(s),this._core.message.messageHistory.completedHistoryConversations.delete(s)}},_t=new class{constructor(){this._name="SetConversationDraft"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return mA(this,void 0,void 0,function*(){const{conversationID:r,draftText:g}=s;if(console.log(`${this._name} conversationID:${r} draftText:${g}`),!NA.hasLocalConversation(r))throw new this._core.helper.ChatError({code:Sa.CONV_NOT_FOUND});const u=NA.getLocalConversation(r);return u?.setDraftText(g),NA.emitConversationListUpdate(),{code:0,data:{conversation:u}}})}},ti=new class{constructor(){this._name="SetC2CMessageRemindType"}init(s){this._core=s}set(s,r){return mA(this,void 0,void 0,function*(){s.length>30&&(console.warn(`${this._name}.set userIDList length:${s.length} exceeds limit 30`),s.splice(30));const g=function(){const{MSG_REMIND_ACPT_AND_NOTE:P,MSG_REMIND_DISCARD:W,MSG_REMIND_ACPT_NOT_NOTE:nA}=yo.core.OuterConstant;return{[P]:0,[W]:1,[nA]:2}}()[r],u=yield function(P,W){return mA(this,void 0,void 0,function*(){const{userIDList:nA,receiveMessageOption:EA}=P,wA={Peer_Account:nA,Mute_Notifications:EA};return W.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:wA})})}({userIDList:s,receiveMessageOption:g},this._core),{ErrorList:E=[]}=u||{},f=[];E.forEach(P=>{const{Peer_Account:W,ErrorCode:nA}=P;f.push({userID:W,code:nA});const EA=s.indexOf(W);EA>-1&&s.splice(EA,1)});const D=[],v=[],{OuterConstant:N}=this._core;return s.forEach(P=>{v.push(`${N.CONV_C2C}${P}`),D.push({userID:P})}),NA.patchMessageRemindType(v,r),{code:0,data:{successUserIDList:D,failureUserIDList:f}}})}},ui=new class{constructor(){this._name="SetGroupMessageRemindType"}init(s){this._core=s}set(s,r){return mA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:g,isTopic:u},OuterConstant:E}=this._core;if(yield function(f,D){return mA(this,void 0,void 0,function*(){const{groupID:v,userID:N,receiveMessageOption:P}=f,W={GroupId:v,Member_Account:N,MsgFlag:P};return D.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:W})})}({groupID:s,userID:g(),receiveMessageOption:r},this._core),!u(s)){const f=`${E.CONV_GROUP}${s}`;NA.patchMessageRemindType([f],r)}return{code:0,data:{groupID:s,messageRemindType:r}}})}},Rt=new class{constructor(){this._name="SetMessageRemindType"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(s){const{helper:{isEmpty:r},OuterConstant:g,ssoLog:u}=this._core;s.forEach(E=>{const{MuteNotificationsSync:f}=E;if(!r(f)){const{To_Account:D,MuteNotifications:v}=f,N=D.map(W=>`${g.CONV_C2C}${W}`),P=io(v);u.debug(`${this._name}.handleC2CMessageRemindTypeSync conversationIDList:${N} messageRemindType:${P}`),NA.patchMessageRemindType(N,P)}})}setMessageRemindType(s){return mA(this,void 0,void 0,function*(){const r="setMessageRemindType",{groupID:g,userIDList:u,messageRemindType:E}=s,{helper:f,utils:{isUndefined:D},ssoLog:v}=this._core;try{if(!D(g))return v.debug(`${this._name}.${r} groupID:${g} messageRemindType:${E}`),yield ui.set(g,E);if(!D(u))return v.debug(`${this._name}.${r} userIDList:${u} messageRemindType:${E}`),yield ti.set(u,E);throw new f.ChatError({functionName:r,message:"userIDList or groupID is required"})}catch(N){throw new f.ChatError({functionName:r,code:N?.errorCode,message:N?.errorInfo,moreMessage:`groupID:${g} userIDList:${u} messageRemindType:${E}`})}})}},fi=new class{init(s){s.ssoLog.debug("ConversationAction.init"),this._core=s,ee.init(s),Ne.init(s),he.init(s),Ue.init(s),de.init(s),Ve.init(s),_t.init(s),Rt.init(s);const{notificationCenter:r,InnerEvent:{MESSAGE_PUSH:g,DESTROY:u}}=this._core,{InnerEventSubType:{CONV_MODIFIED:E,C2C_MESSAGE_READ_SYNC:f,GROUP_MESSAGE_READ_SYNC:D,C2C_REMIND_TYPE_SYNC:v}}=r;r.subscribeInnerEvent(g,E,this._onConversationModified,this),r.subscribeInnerEvent(g,f,this._onC2CMessageReadSync,this),r.subscribeInnerEvent(g,v,this._onC2CMessageRemindTypeSync,this),r.subscribeInnerEvent(g,D,this._onGroupMessageReadSync,this),r.subscribeInnerEvent(u,this._dispose,this)}_onConversationModified(s){const{constants:{ConvModifyPushType:r}}=this._core,{RecentContactMod:g=[]}=s;g.forEach(u=>{const{PushType:E}=u;if(E===r.CONV_DELETED){const{RecentContactList:f}=u.RecentContactDeleteItem;Ve.handleConversationDeleted(f)}if(E===r.CONV_PINED){const{RecentContactList:f}=u.RecentContactTopItem;de.handleConversationPinned(f,!0)}if(E===r.CONV_UNPINED){const{RecentContactList:f}=u.RecentContactTopItem;de.handleConversationPinned(f,!1)}})}_onC2CMessageReadSync(s){const{C2cNotifyMsgArray:r=[]}=s;Ue.handleC2CMessageReadSync(r)}_onC2CMessageRemindTypeSync(s){const{C2cNotifyMsgArray:r=[]}=s;Rt.handleC2CMessageRemindTypeSync(r)}_onGroupMessageReadSync(s){const{GroupTips:r=[]}=s;Ue.handleGroupMessageReadSync(r)}_dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:r,DESTROY:g}}=this._core,{InnerEventSubType:{CONV_MODIFIED:u,C2C_MESSAGE_READ_SYNC:E,GROUP_MESSAGE_READ_SYNC:f,C2C_REMIND_TYPE_SYNC:D}}=s;s.unSubscribeInnerEvent(r,u,this._onConversationModified,this),s.unSubscribeInnerEvent(r,E,this._onC2CMessageReadSync,this),s.unSubscribeInnerEvent(r,D,this._onC2CMessageRemindTypeSync,this),s.unSubscribeInnerEvent(r,f,this._onGroupMessageReadSync,this),s.unSubscribeInnerEvent(g,this._dispose,this)}},go=new class{init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(s){return mA(this,void 0,void 0,function*(){try{const{OuterConstant:{MSG_REMIND_ACPT_NOT_NOTE:r}}=this._core,{messageRemindType:g=r,isRepeated:u=!0}=s,{startTime:E=0,endTime:f=0}=this._calcStartAndEndTime(s),D=yield function(v){return mA(this,void 0,void 0,function*(){const{common:N}=yo.core,{startTime:P,endTime:W,isRepeated:nA,messageRemindType:EA}=v,wA={StartTime:P,EndTime:W,IsRepeated:nA,Level:EA};return N.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:wA})})}({messageRemindType:this._getType(g),startTime:E,endTime:f,isRepeated:u?In.ON:In.OFF});return{code:0,data:{errorCode:D.ErrorCode,errorInfo:D.ErrorInfo}}}catch(r){cc("setAllReceiveMessageOpt",r)}})}_calcStartAndEndTime(s){const{startHour:r=0,startMinute:g=0,startSecond:u=0,duration:E=0,isRepeated:f=!0}=s,D=new Date,v=new Date(D.getFullYear(),D.getMonth(),D.getDate(),r,g,u),N=Math.round(v.getTime()/1e3);let P=N+E;return f&&E>=86400&&(P=N+86400),{startTime:N,endTime:P}}_getType(s){const{OuterConstant:r}=this._core;return{[r.MSG_REMIND_ACPT_AND_NOTE]:0,[r.MSG_REMIND_DISCARD]:1,[r.MSG_REMIND_ACPT_NOT_NOTE]:2}[s]}},fn=new class{init(s){this._core=s;const{helper:r,notificationCenter:g,InnerEvent:u}=s;r.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),g.subscribeInnerEvent(u.MESSAGE_PUSH,g.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(s){const r=this._handleResult(s),{notificationCenter:g,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:u}}=this._core;g.emitOuterEvent(u,{name:u,data:r})}getAllReceiveMessageOpt(){return mA(this,void 0,void 0,function*(){try{const s=yield function(){return mA(this,void 0,void 0,function*(){const{common:r}=yo.core,g={To_Account:r.getCurrentUserID()};return r.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_get_do_not_disturb",data:g})})}();return{code:0,data:this._handleResult(s)}}catch(s){cc("getAllReceiveMessageOpt",s)}})}_handleResult(s){const{OuterConstant:r}=this._core,{MSG_REMIND_ACPT_AND_NOTE:g,MSG_REMIND_DISCARD:u,MSG_REMIND_ACPT_NOT_NOTE:E}=r,f={0:g,1:u,2:E},{Level:D,StartTime:v,EndTime:N,IsRepeated:P}=s;return{messageRemindType:f[D]||g,startTime:v,endTime:N,isRepeated:P===In.ON}}},xo=new class{init(s){s.ssoLog.debug("ReceiveMessageOptions.init"),this._core=s,ti.init(s),ui.init(s),QA.init(s),yA.init(s),go.init(s),fn.init(s)}};const ai=s=>!St(s)&&!Cg(s)&&!qn(s),Yr={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ai(s)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ai(s)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ai(s)||"conversationID is invalid."},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},deleteConversation:[{key:"options",required:!0,rules:["string","object"],allowEmpty:!1,customValidator:s=>{const{core:{utils:{isArray:r,isObject:g,isString:u}}}=yo;if(!u(s)&&!g(s))return"options is String or Object.";if(u(s)&&ai(s))return"conversationID is invalid.";if(g(s)){if(!r(s.conversationIDList))return"conversationIDList is not Array.";if(s.conversationIDList.length===0)return"conversationIDList is empty.";if(s.conversationIDList.some(E=>{if(ai(E))return!0}))return"conversationIDList includes invalid conversationID.";if(s.clearHistoryMessage&&typeof s.clearHistoryMessage!="boolean")return"clearHistoryMessage is not Boolean."}return!0}}],setConversationDraft:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!St(s)&&!Cg(s))||"conversationID is invalid."},draftText:{required:!0,rules:["string"],allowEmpty:!0}},setAllReceiveMessageOpt:{messageRemindType:{required:!1,rules:["string"],allowEmpty:!0},startHour:{required:!1,rules:["number"],allowEmpty:!0},startMinute:{required:!1,rules:["number"],allowEmpty:!0},startSecond:{required:!1,rules:["number"],allowEmpty:!0},duration:{required:!1,rules:["number"],allowEmpty:!0},isRepeated:{required:!1,rules:["boolean"],allowEmpty:!0}}},nn={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0};var er=new class{constructor(){this.name="Conversation"}install(s){yo.init(s),fi.init(s),xo.init(s),NA.init(s),s.helper.registerValidateConfig({auth:nn,params:Yr})}};const tr=new class{init(s){this.core=s}},na="AVChatRoom",zr="AV_HISTORY_MSG",lc="GRP_COUNTER",Wu="Set",Rm="Increase",Gi="Decrease",gi=0,_o=1,Es=2,un=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],hg=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Hl=["Role","JoinTime","MsgFlag","MsgSeq"],Dd=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Vc=0,_r=1,_I="notStart",cu="resolved",Yg="rejected",lu=10018,TI=11e3,Hc=2,zu=["Owner","Admin","Member"],wm=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],_m=0,Tm=1,Nm=2,QD=4,pD=1,KM=2,mD=3,fD=4,jM=5,_T=1,Sd=0,TT=4,yD=6,NT=400,DD=300,GT={from:!0,groupID:!0,groupName:!0,to:!0},WM={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},bT=2,zM=4,kT=5,LT=7,SD=8,vD=15,UQ=20,Gm=21,bm=2600,vd=2602,UT=2603,FT=2620,km=2621,MD=2623,Ch=2660,OT=2661,PT=2681,Lm=2683,ZM=2684,RD=2685,Um=2687,XM=3122,xT=10018,YT={0:"DisableInvite",1:"NeedPermission",2:"FreeAccess"},$M=s=>s===tr.core.OuterConstant.GRP_PUBLIC,Md=s=>s===tr.core.OuterConstant.GRP_AVCHATROOM,Fm=(s,r)=>{const{isArray:g}=tr.core.utils;if(!g(s)||!g(r))return!1;let u=!1;return r.forEach(({key:E,value:f})=>{const D=s.find(v=>v.key===E);D?D.value!==f&&(D.value=f,u=!0):(s.push({key:E,value:f}),u=!0)}),u},Rd=s=>{const r=[];if(!s)return r;for(let g=0,u=s.length;g{const r=[];for(let g=0,u=s.length;g0&&v.members.forEach(N=>{N.userID===this.selfInfo.userID&&D(this.selfInfo,N,["sequence"])})}updateSelfInfo(r){const{nameCard:g,joinTime:u,role:E,messageRemindType:f,readedSequence:D,excludedUnreadSequenceList:v}=r,{common:{deepMerge:N}}=tr.core;N(this.selfInfo,{nameCard:g,joinTime:u,role:E,messageRemindType:f,readedSequence:D,excludedUnreadSequenceList:v},[],["",null,void 0,0,NaN])}setSelfNameCard(r){this.selfInfo.nameCard=r}}var Wi=new class{constructor(){this._name="GroupDataHandler"}init(s){this._core=s;const{appStore:{groupStore:r}}=s;this._groupMap=r.getGroupMap()}hasLocalGroup(s){return this._groupMap.has(s)}getLocalGroup(s){return this._groupMap.get(s)}updateLocalGroup(s){const{common:{getCurrentUserID:r}}=this._core;let g;s.forEach(E=>{var f;g=E.groupID,this.hasLocalGroup(g)?(f=this.getLocalGroup(g))===null||f===void 0||f.updateGroup(E):(this._groupMap.set(g,new Zu(E)),this._clearGroupLocalMessage(g))});const u=r();for(const[,E]of this._groupMap)E.selfInfo.userID=u,E.selfInfo.role==="Owner"&&(E.ownerID=u)}deleteLocalGroup(s){this._groupMap.delete(s)}getLocalGroupList(){const{OuterConstant:{GRP_ROOM:s,GRP_LIVE:r}}=this._core;return[...this._groupMap.values()].filter(g=>{const{type:u}=g;return u!==s&&u!==r})}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){const s=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:r},notificationCenter:g}=this._core;g.emitOuterEvent(r,{name:r,data:s})}updateConversationGroupProfile(s){const{appStore:{conversationStore:r},OuterConstant:{CONV_GROUP:g}}=this._core,u=`${g}${s}`,E=r.getConversation(u);if(E){const f=this.getLocalGroup(s);E.setProfileCompleted(),r.updateConversation(u,{groupProfile:f})}}reset(){this.clearLocalGroup()}_clearGroupLocalMessage(s){const{message:{messageHistory:r,messageDataHandler:g},OuterConstant:{CONV_GROUP:u},ssoLog:E}=this._core;E.debug("_clearGroupLocalMessage",`groupID:${s}`);const f=`${u}${s}`;r.completedHistoryConversations.delete(f),g.deleteConversationMessageList(f)}};function Pm(s,r){return mA(this,void 0,void 0,function*(){const{type:g,limit:u,offset:E,supportTopic:f=0,memberAccount:D,responseFilter:v}=s,N={Type:g,Limit:u,Offset:E,Member_Account:D,ResponseFilter:v,SupportTopic:f,NeedAppDefineData:1};return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:N})})}const fs=function(s,r){return{code:0,data:s||{},successLog:r}};var AR=new class{constructor(){this._name="GetGroupList",this._pagingStatus=_I,this.PAGING_GRP_COUNT_LIMIT=200}init(s){this._core=s;const{helper:r,constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:u}}=s;r.registerApi({apiName:"getGroupList",context:this}),r.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_LOGIN,u.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return mA(this,arguments,void 0,function*(s=!1){if(s){const g=[];return yield this._pagingGetJoinedCommunityList({limit:this.PAGING_GRP_COUNT_LIMIT,offset:0,groupList:g}),Wi.updateLocalGroup(g),Wi.getLocalGroupList()}if(this._core.ssoLog.debug("getGroupList",`${this._name}.getGroupList pagingStatus:${this._pagingStatus}`),this._pagingStatus===Yg||this._pagingStatus===_I)return this._syncGroupList().then(()=>{const g=Wi.getLocalGroupList();return fs({groupList:g,isSyncCompleted:this._isSyncCompleted()})}).catch(g=>{throw g});const r=Wi.getLocalGroupList();return fs({groupList:r,isSyncCompleted:this._isSyncCompleted()},{message:`return group count:${r.length}`})})}_syncGroupList(){return mA(this,void 0,void 0,function*(){this._pagingStatus===_I&&Wi.clearLocalGroup();const s=this.PAGING_GRP_COUNT_LIMIT,r=[];try{yield this._pagingGetGroupList({limit:s,offset:0,groupList:r}),this._pagingStatus=cu,this._groupListTreeShaking(r),Wi.updateLocalGroup(r);const g=Wi.getLocalGroupList();return this._core.ssoLog.debug("_syncGroupList",`${this._name}._syncGroupList ok, count:${g.length}`),Wi.emitGroupListUpdate(),g}catch(g){throw this._pagingStatus=Yg,g}})}_pagingGetGroupList(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r}=this._core,{isCommunityRelay:g=!1,groupList:u}=s;let E,{limit:f,offset:D}=s;const v=[...un];g&&(E=this._core.OuterConstant.GRP_COMMUNITY,v.push("AtInfoList"));try{const N=yield Pm({type:E,limit:f,offset:D,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:v,SelfInfoFilter:[...Hl]}},this._core),{GroupIdList:P=[],TotalCount:W=0}=N||{},nA=this._convertGroupKey(P);u.push(...nA);const EA=D+f,wA=!(W>EA),kA=`offset:${D} limit:${f} total:${W} isCompleted:${wA} current:${u.length} isCommunityRelay:${g}`;return r.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. ${kA}`),g?wA?u:(D=EA,this._pagingGetGroupList({isCommunityRelay:!0,limit:f,offset:D,groupList:u})):wA?(r.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList start to get community list`),D=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:f,offset:D,groupList:u})):(D=EA,this._pagingGetGroupList({limit:f,offset:D,groupList:u}))}catch(N){if(N.ErrorCode===lu)return r.warn("_pagingGetGroupList",`${this._name}._pagingGetGroupList response size exceeds the limit, request count:${f}`),f=50,this._pagingGetGroupList({isCommunityRelay:g,limit:f,offset:D,groupList:u});if(g)return N.code===TI&&r.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. community unavailable`),u;throw N}})}_pagingGetJoinedCommunityList(s){return mA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:r},OuterConstant:g,ssoLog:u}=this._core,{groupList:E}=s;let{limit:f,offset:D}=s;try{const v=yield Pm({limit:f,offset:D,type:g.GRP_COMMUNITY,memberAccount:r(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...un],SelfInfoFilter:[...Hl]}},this._core),{GroupIdList:N=[],TotalCount:P=0}=v||{},W=this._convertGroupKey(N);E.push(...W);const nA=D+f,EA=!(P>nA),wA=`offset:${D} limit:${f} total:${P} isCompleted:${EA} current:${E.length}`;return u.debug("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList ok. ${wA}`),EA?E:(D=nA,this._pagingGetJoinedCommunityList({limit:f,offset:D,groupList:E}))}catch(v){if(v.code===xT)return u.warn("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList response size exceeds the limit, request count:${f}`),f=50,this._pagingGetJoinedCommunityList({limit:f,offset:D,groupList:E});throw v}})}_groupListTreeShaking(s){const r=new Map([...Wi.getLocalGroupList()]);for(let u=0,E=s.length;u{const{AtFlagList:E,AtMsgSeq:f,From_Account:D}=u;g.push({groupID:s,groupAtType:E,sequence:f,from:D})}),g}},Xu=new class{constructor(){this._name="CreateGroup"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"createGroup",context:this})}createGroup(s){return mA(this,void 0,void 0,function*(){var r;this._preCheckParams(s);const{helper:{ChatError:g}}=this._core;try{const{utils:{isEmpty:u},common:{getCurrentUserID:E},OuterConstant:{GRP_AVCHATROOM:f}}=this._core,D=yield function(nA,EA){return mA(this,void 0,void 0,function*(){const{name:wA,type:kA,groupID:VA,introduction:LA,notification:SA,avatar:PA,maxMemberNum:zA,joinOption:Ee,inviteOption:Ie,memberList:Li,groupCustomField:Ui,isSupportTopic:Yt}=nA;let Oi,Bn;Li&&(Oi=Li.map(Mt=>{const{userID:FA,memberCustomField:ci}=Mt;return{Member_Account:FA,AppMemberDefinedData:ci?JE(ci):void 0}})),Ui&&(Bn=JE(Ui));const Re={Name:wA,Type:kA,GroupId:VA,Introduction:LA,Notification:SA,FaceUrl:PA,MaxMemberCount:zA,ApplyJoinOption:Ee,InviteJoinOption:Ie,MemberList:Oi,AppDefinedData:Bn,SupportTopic:Yt,webPushFlag:1};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:Re})})}(Object.assign(Object.assign({},s),{ownerID:E()}),this._core),{GroupId:v,OverJoinedGroupLimit_Account:N=[]}=D||{},P=`${this._name}.createGroup ok, type:${s.type} groupID:${v} overLimitUserIDList:${N}`;if(u(s.memberList)||u(N)||(s.memberList=(r=s.memberList)===null||r===void 0?void 0:r.filter(nA=>N.includes(nA.userID))),s.type===f)return fs({group:new Zu(Object.assign(Object.assign({},s),{groupID:v}))},{message:P});Wi.updateLocalGroup([Object.assign(Object.assign({},s),{groupID:v})]);const W=Wi.getLocalGroup(v);return this._notNeedSendCustomMessage(s)||(this._sendCustomMessage(v,s.type),Wi.emitGroupListUpdate()),fs({group:W},{message:P})}catch(u){const{errorCode:E,errorInfo:f}=u;throw new g({functionName:"createGroup",code:E,message:f,moreMessage:` groupID:${s.groupID}`})}})}_preCheckParams(s){const{type:r,groupID:g}=s,{utils:{isEmpty:u,isUndefined:E},common:{isCommunity:f}}=this._core,D=!u(g);if(!(()=>{const{GRP_PUBLIC:v,GRP_WORK:N,GRP_MEETING:P,GRP_AVCHATROOM:W,GRP_COMMUNITY:nA}=tr.core.OuterConstant;return[v,N,P,W,nA]})().includes(r))throw new this._core.helper.ChatError({code:bm});if(!f({type:r})){if(D&&f({groupID:g}))throw new this._core.helper.ChatError({code:vd});E(s.isSupportTopic)||(s.isSupportTopic=void 0)}if(this._canIUseMemberList(r)||E(s.memberList)||(s.memberList=void 0),this._canIUseJoinOption(r)||E(s.joinOption)||(s.joinOption=void 0),f({type:r})){if(D&&!f({groupID:g}))throw new this._core.helper.ChatError({code:vd});s.isSupportTopic=this._canIUseTopic(s)?1:0}}_canIUseMemberList(s){return!Md(s)}_canIUseJoinOption(s){return $M(s)||this._core.common.isCommunity({type:s})}_canIUseTopic(s){const{isSupportTopic:r}=s;return r===!0}_notNeedSendCustomMessage(s){const{type:r,isSupportTopic:g}=s,{OuterConstant:{GRP_AVCHATROOM:u,GRP_COMMUNITY:E}}=this._core;return r===u||r===E&&g===1}_sendCustomMessage(s,r){var g,u,E,f,D,v;const{OuterConstant:N,common:{t:P}}=this._core;let W=P("CREATE_GROUP"),nA=Vc;r===N.GRP_COMMUNITY&&(W=P("CREATE_COMMUNITY"),nA=_r);const EA={to:s,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:W,cmd:nA,opUser:this._core.store.get("login").userId,version:4})}},wA=(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(EA);(v=(D=(f=this._core)===null||f===void 0?void 0:f.message)===null||D===void 0?void 0:D.messageSender)===null||v===void 0||v.sendMessage(wA,{})}},as=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(s){this._core=s;const{helper:r,constants:g}=s;r.registerWorkflowStep(g.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,g.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach(s=>{s.localMainSequence=0})}isGroupAttributesUpdated(s){const{elements:{newGroupProfile:r}}=s,{utils:{isEmpty:g,isUndefined:u}}=this._core;return!u(r)&&!g(r.groupAttributeOption)}handleGroupAttributesUpdated(s){const{groupID:r,groupAttributeOption:g}=s,{serverMainSequence:u,groupAttributeList:E=[],operation:f}=g;this._core.ssoLog.debug("handleGroupAttributesUpdated",`${this._name}.handleGroupAttributesUpdated groupID:${r} operation:${f}`);const{utils:{isUndefined:D}}=this._core;D(f)||(this.refreshGroupAttributesCache({groupID:r,serverMainSequence:u,groupAttributeList:E,operation:f}),this.emitGroupAttributesUpdated(r))}initGroupAttributesCache(s){const{groupID:r,avChatRoomKey:g}=s;this._groupAttributesCache.set(r,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:g,values:new Map}),this._core.ssoLog.debug("initGroupAttributesCache",`${this._name}.initGroupAttributesCache. groupID:${r} avChatRoomKey:${g}`)}hasGroupAttributesCache(s){return this._groupAttributesCache.has(s)}getGroupAttributesCache(s){return this.hasGroupAttributesCache(s)||this.initGroupAttributesCache({groupID:s}),this._groupAttributesCache.get(s)}deleteGroupAttributesCache(s){this.hasGroupAttributesCache(s)&&this._groupAttributesCache.delete(s)}refreshGroupAttributesCache(s){const{groupID:r,serverMainSequence:g,groupAttributeList:u,operation:E}=s;if(this.hasGroupAttributesCache(r)){const f=this.getGroupAttributesCache(r),{localMainSequence:D}=f;E!==jM&&g-D!==1||(f.serverMainSequence=g,f.localMainSequence=g,f.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:f,groupAttributeList:u,operation:E})),g-D>1&&(f.serverMainSequence=g),this._groupAttributesCache.set(r,f),this._core.ssoLog.debug("refreshGroupAttributesCache",`${this._name}.refreshGroupAttributesCache. operation:${E} localMainSequence:${D} serverMainSequence:${g}`)}}_updateGroupAttributesCacheValues(s){const{groupAttributes:r,groupAttributeList:g=[],operation:u}=s;u!==mD?u!==fD?(u===pD&&r.values.clear(),g.forEach(E=>{const{key:f,value:D,sequence:v}=E;r.values.set(f,{value:D,sequence:v})})):g.forEach(E=>{r.values.delete(E.key)}):r.values.clear()}getGroupAttributesCacheValues(s){var r;const{groupID:g,keyList:u=[]}=s,E={};if(this.hasGroupAttributesCache(g)){const{values:f}=this.getGroupAttributesCache(g);if(u.length===0){for(const D of f.keys())E[D]=((r=f.get(D))===null||r===void 0?void 0:r.value)||"";return E}return u.forEach(D=>{var v;f.has(D)&&(E[D]=((v=f.get(D))===null||v===void 0?void 0:v.value)||"")}),E}return E}saveGroupAttributesCacheValuesCopy(s){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:s})}emitGroupAttributesUpdated(s){var r,g;const{OuterConstant:{GRP_ROOM:u,GRP_LIVE:E}}=this._core,f=this.getGroupAttributesCacheValues({groupID:s}),D=this._core.appStore.groupStore.getGroup(s),{updatedKeyList:v,deletedKeyList:N}=this._computeValuesChangedData(f);v.length===0&&N.length===0||([u,E].includes(D.type)?(this._core.ssoLog.debug("RICH_STATUS_CHANGED",`${this._name}.emitRichStatusChanged update count:${v.length}, delete count:${N.length}`),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.OuterEvent.RICH_STATUS_CHANGED,data:{groupID:s,richStatus:f,updatedKeyList:v,deletedKeyList:N}})):(this._core.ssoLog.debug("emitGroupAttributesUpdated",`${this._name}.emitGroupAttributesUpdated update count:${v.length}, delete count:${N.length}`),this._emitEvent({name:(g=this._core)===null||g===void 0?void 0:g.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:s,groupAttributes:f,updatedKeyList:v,deletedKeyList:N}})))}_computeValuesChangedData(s){const{utils:{isUndefined:r}}=this._core,g=[],u=[];return Object.keys(s).forEach(E=>{s[E]!==this._groupAttributesCacheValuesCopy[E]&&g.push(E)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(E=>{r(s[E])&&u.push(E)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:g,deletedKeyList:u}}_emitEvent(s){var r;(r=this._core)===null||r===void 0||r.notificationCenter.emitOuterEvent(s.name,s)}convertKeyValueMapToList(s){const r=[];return Object.keys(s).forEach(g=>{r.push({key:g,value:s[g]})}),r}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}},Bh=new class{constructor(){this._name="DismissGroup"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(na)})}dismissGroup(s){return mA(this,void 0,void 0,function*(){const{helper:{ChatError:r}}=this._core;try{yield function(u,E){return mA(this,void 0,void 0,function*(){const f={GroupId:u};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:f})})}(s,this._core);const{type:g}=Wi.getLocalGroup(s);return Wi.deleteLocalGroup(s),Wi.emitGroupListUpdate(),as.deleteGroupAttributesCache(s),fs({groupID:s,type:g},{message:s})}catch(g){const{errorCode:u,errorInfo:E}=g;throw new r({functionName:"dismissGroup",code:u,message:E})}})}},Jl=new class{constructor(){this._name="GetGroupProfile"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(s){return mA(this,void 0,void 0,function*(){const{groupID:r,groupCustomFieldFilter:g}=s,u={groupIDList:[r],responseFilter:{GroupBaseInfoFilter:[...un],AppDefinedDataFilter_Group:g,MemberInfoFilter:[...Dd]}},{helper:{ChatError:E}}=this._core;try{const f=yield this.getGroupProfileAdvance(u),{successGroupList:D,failureGroupList:v}=f;if(v.length>0)throw v[0];let N;return!Wi.hasLocalGroup(r)&&Md(D[0].type)?N=new Zu(D[0]):(Wi.updateLocalGroup(D),N=Wi.getLocalGroup(r)),N.isSupportTopic||Wi.updateConversationGroupProfile(r),fs({group:N},{message:`groupID:${r}`})}catch(f){const{code:D,message:v}=f;throw new E({functionName:"getGroupProfile",code:D,message:v})}})}getGroupProfileAdvance(s){return mA(this,void 0,void 0,function*(){const{groupIDList:r}=s,{common:{isCommunity:g}}=this._core,u=r.filter(N=>!g({groupID:N})),E=r.filter(N=>g({groupID:N}));u.length>50&&(u.length=50),E.length>50&&(E.length=50);const f=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:u})),this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:E,isCommunityProfile:!0}))]),D=[],v=[];return f.forEach(N=>{D.push(...N.successGroupList),v.push(...N.failureGroupList)}),{successGroupList:D,failureGroupList:v}})}_getGroupProfileAdvance(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{isUndefined:g}}=this._core,{isCommunityProfile:u=!1}=s,E=vo(s,["isCommunityProfile"]);if(E.groupIDList.length===0)return{successGroupList:[],failureGroupList:[]};try{const f=yield function(W,nA){return mA(this,void 0,void 0,function*(){const{groupIDList:EA,responseFilter:wA}=W,kA={GroupIdList:EA,ResponseFilter:wA};return nA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:kA})})}(E,this._core),{GroupInfo:D=[]}=f||{},v=this._convertGroupProfileKey(D),N=v.filter(W=>g(W.errorCode)||W.errorCode===0),P=v.filter(W=>W.errorCode&&W.errorCode!==0).map(W=>({code:W.errorCode,message:W.errorInfo,data:{groupID:W.groupID}}));return r.debug("_getGroupProfileAdvance",`${this._name}._getGroupProfileAdvance ok, groupID:${E.groupIDList.join(",")}`),{successGroupList:N,failureGroupList:P}}catch(f){if(u)return{successGroupList:[],failureGroupList:[]};throw f}})}_convertGroupProfileKey(s){const r=[];for(let g=0,u=s.length;g0&&u{const{Key:N,Value:P=0}=v;E.set(N,P)}),this._groupCountersMap.set(r,{lastUpdateTime:Date.now(),groupCounterSeq:u,counters:E,avChatRoomKey:f})}}initGroupCountersCache(s){const{groupID:r,avChatRoomKey:g}=s;this._groupCountersMap.set(r,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:g})}getLocalCounters(s,r){const g={};if(!this._hasLocalGroupCounters(s))return g;const{counters:u}=this.getLocalGroupCounters(s);if(r.length>0)r.forEach(E=>{u.has(E)&&(g[E]=u.get(E))});else for(const E of u.keys())g[E]=u.get(E);return g}deleteLocalGroupCounters(s){const{groupID:r,counterList:g=[],groupCounterSeq:u}=s;if(this._hasLocalGroupCounters(r)){const{counters:E,avChatRoomKey:f}=this.getLocalGroupCounters(r);g.forEach(D=>{E.delete(D.key)}),this._groupCountersMap.set(r,{lastUpdateTime:Date.now(),groupCounterSeq:u,counters:E,avChatRoomKey:f})}}setGroupCounters(s,r){if(!this._hasLocalGroupCounters(s))return;const g=this.getLocalGroupCounters(s),{counters:u}=g;let E=!1;Object.entries(r).forEach(([f,D])=>{u.has(f)&&u.get(f)!==D&&(u.set(f,D),E=!0)}),E&&this._groupCountersMap.set(s,Object.assign(Object.assign({},g),{lastUpdateTime:Date.now(),counters:u}))}_hasLocalGroupCounters(s){return this._groupCountersMap.has(s)}reset(){this._groupCountersMap.clear()}},qE=new class{constructor(){this._name="JoinGroup"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"joinGroup",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(na)})}joinGroup(s){return mA(this,void 0,void 0,function*(){const{groupID:r}=s,{helper:{ChatError:g},OuterConstant:u,ssoLog:E}=this._core;try{if(Wi.hasLocalGroup(r))try{return yield Jl.getGroupProfile({groupID:r}),fs({status:u.JOIN_STATUS_ALREADY_IN_GROUP,group:Wi.getLocalGroup(r)},{message:`groupID:${r} joinedStatus:${u.JOIN_STATUS_ALREADY_IN_GROUP}`})}catch{return E.warn("joinGroup",`${this._name}.joinGroup ${r} was unjoined, start to join!`),Wi.deleteLocalGroup(r),yield this._applyJoinGroup(s)}return yield this._applyJoinGroup(s)}catch(f){const{errorCode:D,errorInfo:v}=f;throw new g({functionName:"joinGroup",code:D,message:v,moreMessage:`groupID:${r}`})}})}_applyJoinGroup(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r,helper:g,ssoLog:u}=this._core,{groupID:E}=s,f=Object.assign({},s),D=g.checkBusinessCapabilityBits(zr);D&&(f.historyMessageFlag=1);const v=yield function(SA,PA){return mA(this,void 0,void 0,function*(){const{groupID:zA,applyMessage:Ee,historyMessageFlag:Ie}=SA,Li={GroupId:zA,ApplyMsg:Ee,HugeGroupHistoryMsgFlag:Ie};return PA.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:Li})})}(f,this._core),{Type:N,JoinedStatus:P,LongPollingKey:W,StartSeq:nA,HugeGroupFlag:EA,AVChatRoomKey:wA,RspMsgList:kA=[]}=v||{},VA=`groupID:${E} joinedStatus:${P} longPollingKey:${W} startSeq:${nA} avChatRoomFlag:${EA} canGetAVChatRoomHistoryMsg:${D}, historyMessageCount:${kA.length}`;u.debug("_applyJoinGroup",`${this._name}._applyJoinGroup ok, ${VA}`);let LA=new Zu({groupID:E,type:N});if(P===r.JOIN_STATUS_WAIT_APPROVAL)return fs({status:r.JOIN_STATUS_WAIT_APPROVAL,group:LA});if(P===r.JOIN_STATUS_SUCCESS){try{LA=(yield Jl.getGroupProfile({groupID:E})).data.group}catch(SA){u.warn("_applyJoinGroup",`${this._name}._applyJoinGroup getGroupProfile failed, groupID: ${E}, errorCode:${SA?.code}`)}return this._handleJoinResult({group:LA,avChatRoomFlag:EA,longPollingKey:W,startSequence:nA,avChatRoomKey:wA,historyMessageList:kA})}throw new this._core.helper.ChatError({code:Ch})})}_handleJoinResult(s){const{group:r,avChatRoomFlag:g,avChatRoomKey:u}=s;return g===1?(as.initGroupAttributesCache({groupID:r.groupID,avChatRoomKey:u}),Ic.initGroupCountersCache({groupID:r.groupID,avChatRoomKey:u}),fs(s)):(Wi.updateLocalGroup([r]),Wi.emitGroupListUpdate(),fs({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:r},{message:`groupID:${r.groupID}`}))}},FQ=new class{constructor(){this._name="QuitGroup"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"quitGroup",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(na)})}quitGroup(s){return mA(this,void 0,void 0,function*(){if(!Wi.hasLocalGroup(s))throw new this._core.helper.ChatError({code:MD});const{helper:{ChatError:r}}=this._core;try{yield function(u,E){return mA(this,void 0,void 0,function*(){const f={GroupId:u};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:f})})}(s,this._core);const{type:g}=Wi.getLocalGroup(s);return Wi.deleteLocalGroup(s),Wi.emitGroupListUpdate(),as.deleteGroupAttributesCache(s),fs({groupID:s,type:g},{message:`groupID:${s}`})}catch(g){const{errorCode:u,errorInfo:E}=g;throw new r({functionName:"quitGroup",code:u,message:E,moreMessage:`groupID:${s}`})}})}},EB=new class{constructor(){this._name="SearchGroup"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(s){return mA(this,void 0,void 0,function*(){try{const r=yield function(PA,zA){return mA(this,void 0,void 0,function*(){const Ee={GroupIdList:[PA],GroupBasePublicInfoFilter:[...hg]};return zA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:Ee})})}(s,this._core),{GroupInfo:g=[]}=r||{},{AppDefinedData:u=[],ApplyJoinOption:E,CreateTime:f,FaceUrl:D,Introduction:v,InviteJoinOption:N,MaxMemberNum:P,MemberNum:W,Name:nA,Owner_Account:EA,Type:wA,ErrorCode:kA,ErrorInfo:VA}=g[0];if(kA!==0)throw new this._core.helper.ChatError({code:kA,message:VA});const LA=Rd(u),SA=new Zu({groupID:s,name:nA,avatar:D,introduction:v,joinOption:E,inviteOption:N,maxMemberCount:P,memberCount:W,type:wA,ownerID:EA,createTime:f,groupCustomField:LA});return fs({group:SA})}catch(r){const{errorCode:g,errorInfo:u}=r;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:g,message:u})}})}},VT=new class{constructor(){this._name="UpdateGroupProfile"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(s){return mA(this,void 0,void 0,function*(){const{groupID:r}=s,{utils:{isUndefined:g,safeStringify:u},ssoLog:E,helper:f}=this._core;let D=Wi.getLocalGroup(r);if(D){const{type:v}=D;this._canIUseJoinOption(v)||g(s.joinOption)||(E.warn("updateGroupProfile",`${this._name}.updateGroupProfile groupID:${r} joinOption is unavailable for Work/Meeting/AVChatRoom`),s.joinOption=void 0)}g(s.muteAllMembers)||(s.muteAllMembers=s.muteAllMembers===!0?"On":"Off");try{return yield function(v,N){return mA(this,void 0,void 0,function*(){const{groupID:P,name:W,avatar:nA,introduction:EA,notification:wA,muteAllMembers:kA,joinOption:VA,inviteOption:LA,groupCustomField:SA}=v,PA={GroupId:P,Name:W,FaceUrl:nA,Introduction:EA,Notification:wA,ShutUpAllMember:kA,ApplyJoinOption:VA,InviteJoinOption:LA,AppDefinedData:SA?JE(SA):void 0};return N.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:PA})})}(s,this._core),D?(D.updateGroup(s),Wi.emitGroupListUpdate()):D=new Zu(s),fs({group:D},{message:`groupID:${r}`})}catch(v){const{errorCode:N,errorInfo:P}=v;throw new f.ChatError({code:N,message:P,moreMessage:`options:${u(s)}`})}})}_canIUseJoinOption(s){return $M(s)||this._core.common.isCommunity({type:s})}},HT=new class{constructor(){this._name="ChangeGroupOwner"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(s){return mA(this,void 0,void 0,function*(){const r="changeGroupOwner",{groupID:g,newOwnerID:u}=s,E=Wi.getLocalGroup(g),{helper:f,OuterConstant:D,common:{getCurrentUserID:v}}=this._core;if(E?.type===D.GRP_AVCHATROOM)throw new f.ChatError({functionName:r,code:FT});if(u===v())throw new f.ChatError({functionName:r,code:km});try{return yield function(N,P){return mA(this,void 0,void 0,function*(){const{groupID:W,newOwnerID:nA}=N,EA={GroupId:W,NewOwner_Account:nA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:EA})})}(s,this._core),E.ownerID=u,Wi.emitGroupListUpdate(),fs({group:E})}catch(N){throw new f.ChatError({functionName:r,code:N?.errorCode,message:N?.errorInfo})}})}},OQ=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(na)})}getGroupOnlineMemberCount(s){return mA(this,void 0,void 0,function*(){const r="getGroupOnlineMemberCount";if(!Wi.hasLocalGroup(s))return fs({memberCount:0});const g=Date.now();if(this._onlineMemberCountMap.has(s)){const u=this._onlineMemberCountMap.get(s),{lastReqTime:E=0,memberCount:f=0}=u||{};if(g-E<=6e4)return fs({memberCount:f})}try{const u=yield function(D,v){return mA(this,void 0,void 0,function*(){const N={GroupId:D};return v.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:N})})}(s,this._core),{OnlineMemberNum:E=0}=u||{};this._onlineMemberCountMap.set(s,{lastReqTime:Date.now(),memberCount:E});const f=`${this._name}.${r} ok. groupID:${s} memberCount:${E}`;return fs({memberCount:E},{message:f})}catch(u){throw new this._core.helper.ChatError({functionName:r,code:u?.errorCode,message:u?.errorInfo})}})}},PQ=new class{init(s,r){s.ssoLog.debug("GroupAction.init"),AR.init(s),Xu.init(s),Bh.init(s,r),qE.init(s,r),FQ.init(s,r),EB.init(s),Jl.init(s),VT.init(s),HT.init(s),OQ.init(s,r)}dismissGroup(s){return Bh.dismissGroup(s)}joinGroup(s){return qE.joinGroup(s)}quitGroup(s){return FQ.quitGroup(s)}getGroupOnlineMemberCount(s){return OQ.getGroupOnlineMemberCount(s)}},eR=new class{constructor(){this._name="GetGroupApplicationList"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return mA(this,void 0,void 0,function*(){const s="getGroupApplicationList";try{const r=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]);this._core.ssoLog.debug("getGroupApplicationList",`${this._name}.${s} ok.`);const g=this._handleGroupApplicationResult([...r[0],...r[1]]);return fs({applicationList:g})}catch(r){throw new this._core.helper.ChatError({functionName:s,code:r?.errorCode,message:r?.errorInfo})}})}_getGroupApplicationList(s){return mA(this,void 0,void 0,function*(){const{type:r,startTime:g=0,limit:u=20}=s||{},{common:E}=this._core;let f;try{f=yield function(P,W){return mA(this,void 0,void 0,function*(){const{type:nA,startTime:EA,limit:wA,handleAccount:kA}=P,VA={Type:nA,StartTime:EA,Limit:wA,Handle_Account:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:VA})})}({type:r,startTime:g,limit:u,handleAccount:E.getCurrentUserID()},this._core)}catch(P){if(P?.errorCode!==11e3)throw P;f={}}const{NextStartTime:D=0,PendencyList:v=[]}=f||{};if(D===0)return v;const N=yield this._getGroupApplicationList(Object.assign(Object.assign({},s),{startTime:D}));return[...v,...N]})}_handleGroupApplicationResult(s){const r=[];return s.forEach(g=>{const u=this._convertApplicationData(g),{handled:E}=u,f=vo(u,["handled"]);E===0&&r.push(f)}),r}_convertApplicationData(s){const{Handled:r,AddTime:g,ApplyInviteMsg:u,Authentication:E,FromUserNickName:f,From_Account:D,GroupId:v,GroupName:N,PendencyType:P,To_Account:W}=s;return{handled:r,messageKey:g,applicant:D,applicantNick:f,groupID:v,groupName:N,authentication:E,applicationType:P,userID:W,note:u,addTime:g}}},tR=new class{constructor(){this._name="HandleGroupApplication"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(s){return mA(this,void 0,void 0,function*(){const{application:r}=s,g=this._handleParams(s);try{r?.applicationType===Hc?yield function(E,f){return mA(this,void 0,void 0,function*(){const{groupID:D,handleAction:v,handleMessage:N,applicant:P,authentication:W,invitee:nA}=E,EA={GroupId:D,HandleMsg:v,ApprovalMsg:N,Applicant_Account:P,Authentication:W,Invited_Account:nA};return f.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:EA})})}(g,this._core):yield function(E,f){return mA(this,void 0,void 0,function*(){const{groupID:D,handleAction:v,handleMessage:N,applicant:P,authentication:W,messageKey:nA}=E,EA={GroupId:D,HandleMsg:v,ApprovalMsg:N,Applicant_Account:P,Authentication:W,MsgKey:nA};return f.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:EA})})}(g,this._core);const u=Wi.getLocalGroup(g.groupID);return fs({group:u})}catch(u){throw new this._core.helper.ChatError({functionName:"handleGroupApplication",code:u?.errorCode,message:u?.errorInfo})}})}_handleParams(s){var r;const{handleAction:g,handleMessage:u,message:E,application:f}=s;let D,v,N,P,W;if(E){const{payload:nA}=E||{};D=nA.operatorID,v=(r=nA.groupProfile)===null||r===void 0?void 0:r.groupID,N=nA.authentication,P=nA.messageKey}else D=f?.applicant||"",v=f?.groupID||"",N=f?.authentication||"",P=f?.messageKey||0;return f?.applicationType===Hc&&(W=f.userID),{handleAction:g,handleMessage:u,applicant:D,invitee:W,groupID:v,authentication:N,messageKey:P}}},wD=new class{init(s){s.ssoLog.debug("GroupApplication.init"),eR.init(s),tR.init(s)}};let MC=class{constructor(s){this.userID="",this.avatar="",this.nick="",this.role="",this.joinTime="",this.nameCard="",this.muteUntil=0,this.memberCustomField=[],this.isOnline=!1,this.updateMember(s)}updateMember(s){const{core:{utils:{isUndefined:r},common:{deepMerge:g}}}=tr;r(s.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*s.muteTime)/1e3)),r(s.onlineStatus)||(this.isOnline=s.onlineStatus==="Online");const u=[null,void 0,"",0,NaN];s.memberCustomField&&Fm(this.memberCustomField,s.memberCustomField),g(this,s,["memberCustomField","marks","onlineStatus","muteTime"],u)}};function dB(s,r){return mA(this,void 0,void 0,function*(){const{groupID:g,userID:u,muteTime:E,role:f,nameCard:D,memberCustomField:v}=s;let N;v&&(N=JE(v));const P={GroupId:g,Member_Account:u,ShutUpTime:E,Role:f,NameCard:D,AppMemberDefinedData:N};return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:P})})}var _D=new class{constructor(){this._name="GetGroupMemberList"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(na)})}getGroupMemberList(s){return mA(this,void 0,void 0,function*(){const r="getGroupMemberList",{groupID:g,offset:u=0,count:E=100,role:f="",filter:D=""}=s,v=Wi.getLocalGroup(g),N=E>100?100:E,P={groupID:g,offset:u,limit:N,memberRoleFilter:zu.includes(f)?[f]:void 0,memberInfoFilter:wm};try{const W=yield function(Ie,Li){return mA(this,void 0,void 0,function*(){const{isCommunity:Ui}=Li.common,{groupID:Yt,offset:Oi,limit:Bn,memberRoleFilter:Re,memberInfoFilter:Mt}=Ie,FA={GroupId:Yt,Limit:Bn,MemberRoleFilter:Re,MemberInfoFilter:Mt};return Ui({groupID:Yt})?FA.Next=String(Oi):FA.Offset=Oi,Li.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:FA})})}(P,this._core),{MemberList:nA,MemberNum:EA,Next:wA}=W||{},kA=`${this._name}.${r} ok, totalMemberCount:${EA} next:${wA}`,{utils:{isArray:VA,isEmpty:LA},common:{isCommunity:SA}}=this._core;if(v&&(v.memberCount=EA),!VA(nA)||nA.length===0)return fs({memberList:[],offset:0},{message:kA});let PA=u+N;SA({groupID:g})&&(PA=LA(wA)?0:wA),nA.lengthD.userID),u=yield(r=this._core.user.userProfile)===null||r===void 0?void 0:r.getUserProfile({userIDList:g}),E=u?.data||[],f=new Map(E.map(D=>[D.userID,D]));return s.forEach(D=>{if(f.has(D.userID)){const{nick:v="",avatar:N=""}=f.get(D.userID);D.nick=v,D.avatar=N}}),s})}_generateGroupMember(s){const r=[];for(let g=0,u=s.length;g50&&(N.warn("getGroupMemberProfile",`${this._name}.${r} userIDList length:${u.length} exceeds limit 50`),u.splice(50));const P=`userIDList length:${u.length} groupID:${g}`;try{const W=yield function(kA,VA){return mA(this,void 0,void 0,function*(){const{groupID:LA,userIDList:SA,memberInfoFilter:PA,memberCustomFieldFilter:zA}=kA,Ee={GroupId:LA,Member_List_Account:SA,MemberInfoFilter:PA,AppDefinedDataFilter_GroupMember:zA};return VA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:Ee})})}({groupID:g,userIDList:u,memberCustomFieldFilter:E,memberInfoFilter:[...wm]},this._core),{MemberList:nA}=W||{};if(!v(nA)||nA.length===0)return fs({memberList:[]});let EA=this._convertMemberInfo(nA);EA=yield this._getMemberAvatarAndNick(EA);const wA=this._generateGroupMember(EA);return fs({memberList:wA},{message:P})}catch(W){throw new D.ChatError({functionName:r,code:W?.errorCode,message:W?.errorInfo,moreMessage:P})}})}_convertMemberInfo(s){const r=[];for(let g=0,u=s.length;gD.userID),u=yield(r=this._core.user.userProfile)===null||r===void 0?void 0:r.getUserProfile({userIDList:g}),E=u?.data||[],f=new Map(E.map(D=>[D.userID,D]));return s.forEach(D=>{if(f.has(D.userID)){const{nick:v="",avatar:N=""}=f.get(D.userID);D.nick=v,D.avatar=N}}),s})}_generateGroupMember(s){const r=[];for(let g=0,u=s.length;g({Member_Account:v}));try{const v=yield function(wA,kA){return mA(this,void 0,void 0,function*(){const{groupID:VA,userIDList:LA}=wA,SA={GroupId:VA,MemberList:LA};return kA.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:SA})})}({groupID:g,userIDList:D},this._core),{MemberList:N=[]}=v||{},{failureUserIDList:P,successUserIDList:W,existedUserIDList:nA,overLimitUserIDList:EA}=this._handleResult(N);return fs({failureUserIDList:P,successUserIDList:W,existedUserIDList:nA,overLimitUserIDList:EA,group:E},{message:` groupID:${g} successUserIDList:${W} failureUserIDList:${P} existedUserIDList:${nA} overLimitUserIDList:${EA}`})}catch(v){throw new f.ChatError({functionName:r,code:v?.errorCode,message:v?.errorInfo})}})}_handleResult(s){const r=[],g=[],u=[],E=[];return s.forEach(f=>{const{Result:D,Member_Account:v}=f;D===_m?r.push(v):D===Tm?g.push(v):D===Nm?u.push(v):D===QD&&E.push(v)}),{failureUserIDList:r,successUserIDList:g,existedUserIDList:u,overLimitUserIDList:E}}},_d=new class{constructor(){this._name="DeleteGroupMember"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(na)})}deleteGroupMember(s){return mA(this,void 0,void 0,function*(){const r="deleteGroupMember",{groupID:g,userIDList:u}=s,E=Wi.getLocalGroup(g),{helper:f,utils:{isUndefined:D},ssoLog:v}=this._core;if(D(E))throw new f.ChatError({functionName:r,code:UT});u.length>20&&(v.warn("deleteGroupMember",`${this._name}.${r} userIDList length:${u.length} exceeds limit 20`),u.splice(20));try{return yield function(N,P){return mA(this,void 0,void 0,function*(){const{groupID:W,userIDList:nA,reason:EA}=N,wA={GroupId:W,MemberToDel_Account:nA,Reason:EA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:wA})})}({groupID:g,userIDList:u},this._core),fs({group:E,userIDList:u},{message:`groupID:${g} userIDList length:${u.length}`})}catch(N){throw new f.ChatError({functionName:r,code:N?.errorCode,message:N?.errorInfo})}})}},iR=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(s){return mA(this,void 0,void 0,function*(){const{helper:r}=this._core,{groupID:g,userID:u,muteTime:E}=s,f=` groupID:${g} userID:${u} muteTime:${E}`;this._preCheckSettingMuteParams(s);try{yield dB(s,this._core);const D=Wi.getLocalGroup(g),v=new MC({userID:u,muteTime:E});return fs({group:D,member:v},{message:f})}catch(D){throw new r.ChatError({functionName:"setGroupMemberMuteTime",code:D?.errorCode,message:D?.errorInfo,moreMessage:f})}})}_preCheckSettingMuteParams(s){const{userID:r}=s,{store:g,helper:u}=this._core;if(r===g.get("login").userId)throw new u.ChatError({functionName:"setGroupMemberMuteTime",code:RD})}},YQ=new class{constructor(){this._name="SetGroupMemberRole"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(s){return mA(this,void 0,void 0,function*(){const r="setGroupMemberRole",{helper:g}=this._core,{groupID:u,userID:E,role:f}=s,D=`${this._name}.${r} ok, groupID:${u} userID:${E} role:${f}`;this._preCheckSettingRoleParams(s);try{yield dB(s,this._core);const v=Wi.getLocalGroup(u),N=new MC({userID:E,role:f});return fs({group:v,member:N},{message:D})}catch(v){throw new g.ChatError({functionName:r,code:v?.errorCode,message:v?.errorInfo,moreMessage:D})}})}_preCheckSettingRoleParams(s){var r;const{groupID:g,userID:u,role:E}=s,{store:f,helper:D,OuterConstant:v,common:{isCommunity:N}}=this._core,P=Wi.getLocalGroup(g);if(((r=P?.selfInfo)===null||r===void 0?void 0:r.role)!==v.GRP_MBR_ROLE_OWNER)throw new D.ChatError({functionName:"setGroupMemberRole",code:PT});if(u===f.get("login").userId)throw new D.ChatError({functionName:"setGroupMemberRole",code:ZM});const W=[...zu];if(N({groupID:g})&&W.push(v.GRP_MBR_ROLE_CUSTOM),!W.includes(E))throw new D.ChatError({functionName:"setGroupMemberRole",code:Lm})}},TD=new class{constructor(){this._name="SetGroupMemberNameCard"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(s){return mA(this,void 0,void 0,function*(){var r;const g="setGroupMemberNameCard",{helper:u,common:{getCurrentUserID:E}}=this._core,{groupID:f,userID:D=E(),nameCard:v}=s,N=`${this._name}.${g} ok, groupID:${f} userID:${D} nameCard:${v}`;this._preCheckSettingNameCardParams(s);try{yield dB({groupID:f,userID:D,nameCard:v},this._core);const W=Wi.getLocalGroup(f);D===((r=W?.selfInfo)===null||r===void 0?void 0:r.userID)&&(W.updateSelfInfo({nameCard:v}),Wi.emitGroupListUpdate(),Wi.updateConversationGroupProfile(f));const nA=new MC({userID:D,nameCard:v});return fs({group:W,member:nA},{message:N})}catch(P){throw new u.ChatError({functionName:g,code:P?.errorCode,message:P?.errorInfo,moreMessage:N})}})}_preCheckSettingNameCardParams(s){const{groupID:r}=s,{helper:g}=this._core,u=Wi.getLocalGroup(r);if(Md(u?.type))throw new g.ChatError({functionName:"setGroupMemberNameCard",code:Um})}},xm=new class{constructor(){this._name="SetGroupMemberCustomField"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(s){return mA(this,void 0,void 0,function*(){const r="setGroupMemberCustomField",{helper:g,common:{getCurrentUserID:u}}=this._core;this._preCheckSettingCustomFiledParams(s);const{groupID:E,userID:f=u(),memberCustomField:D}=s,v=`${this._name}.${r} ok, groupID:${E}userID:${f} memberCustomField:${JSON.stringify(D)}`;try{yield dB({groupID:E,userID:f,memberCustomField:D},this._core);const P=Wi.getLocalGroup(E),W=new MC({userID:f,memberCustomField:D});return fs({group:P,member:W},{message:v})}catch(N){throw new g.ChatError({functionName:r,code:N?.errorCode,message:N?.errorInfo,moreMessage:v})}})}_preCheckSettingCustomFiledParams(s){const{groupID:r}=s,{helper:g}=this._core,u=Wi.getLocalGroup(r);if(Md(u?.type))throw new g.ChatError({functionName:"setGroupMemberCustomField",code:Um})}},oR=new class{init(s,r){s.ssoLog.debug("GroupMember.init"),_D.init(s,r),xQ.init(s),wd.init(s),_d.init(s,r),iR.init(s),YQ.init(s),TD.init(s),xm.init(s)}getGroupMemberList(s){return _D.getGroupMemberList(s)}deleteGroupMember(s){return _d.deleteGroupMember(s)}},JT=new class{init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(s){return mA(this,void 0,void 0,function*(){const r="getGroupCounters";try{Om(r,lc);const{groupID:g,keyList:u=[]}=s,{avChatRoomKey:E,lastUpdateTime:f}=Ic.getLocalGroupCounters(g);if(!(Date.now()-f>=this._getExpireTime()))return{code:0,data:{counters:Ic.getLocalCounters(g,u)}};const D=yield function(P){return mA(this,void 0,void 0,function*(){const{groupID:W,GroupCounterKeys:nA,avChatRoomKey:EA}=P,{common:wA}=tr.core,kA={GroupId:W,keyList:nA,BytesKey:EA};return wA.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:kA})})}({groupID:g,keyList:u,avChatRoomKey:E}),{GroupCounter:v=[],GroupCounterSeq:N}=D;return Ic.updateLocalGroupCounters({groupID:g,counterList:v,groupCounterSeq:N}),{code:0,data:{counters:Ic.getLocalCounters(g,u)}}}catch(g){vC(r,g)}})}_getExpireTime(){const{store:s,utils:{isUndefined:r}}=this._core,g=s.get("cloudConfig")||{},{grp_counter_expire_time:u}=g;return r(u)?3e4:Number(u)}},Ym=new class{init(s){const{helper:r}=s;r.registerApi({apiName:"setGroupCounters",context:this}),r.registerApi({apiName:"increaseGroupCounter",context:this}),r.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(s){return mA(this,void 0,void 0,function*(){return this._handleCounterOperation(Wu,s)})}increaseGroupCounter(s){return mA(this,void 0,void 0,function*(){return this._handleCounterOperation(Rm,s)})}decreaseGroupCounter(s){return mA(this,void 0,void 0,function*(){return this._handleCounterOperation(Gi,s)})}_handleCounterOperation(s,r){return mA(this,void 0,void 0,function*(){const g=`${s}GroupCounter`;try{Om(g,lc);const{groupID:u,key:E,value:f=0}=r,{avChatRoomKey:D}=Ic.getLocalGroupCounters(u),v=s===Wu?this._convertObjectToList(r.counters):[{Key:E,Value:f}],N=yield this._updateGroupCounters({groupID:u,counterList:v,avChatRoomKey:D,mode:s});return Ic.setGroupCounters(u,N),{code:0,data:{counters:N}}}catch(u){vC(g,u)}})}_updateGroupCounters(s){return mA(this,void 0,void 0,function*(){const r=yield function(E){const{groupID:f,counterList:D,mode:v,avChatRoomKey:N}=E,{common:P}=tr.core,W={GroupId:f,GroupCounter:D,Mode:v,BytesKey:N};return P.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:W})}(s),{GroupCounter:g=[]}=r,u={};return g.forEach(E=>{const{Key:f,Value:D=0}=E;u[f]=D}),u})}_convertObjectToList(s){return Object.entries(s).map(([r,g])=>({Key:r,Value:g||0}))}},CB=new class{init(s){this._core=s,JT.init(s),Ym.init(s)}isGroupCounterUpdated(s){const{elements:{groupCounterInfo:r}}=s,{utils:{isEmpty:g}}=this._core;return!g(r)}handleGroupCounterUpdated(s){const{to:r,elements:{groupCounterInfo:g}}=s;g.forEach(u=>{const{type:E,groupCounterSeq:f,counterList:D=[]}=u;E!==gi&&E!==Es||this._processAndNotifyCounterUpdate(r,f,D),E===_o&&Ic.deleteLocalGroupCounters({groupID:r,groupCounterSeq:f,counterList:D})})}_processAndNotifyCounterUpdate(s,r,g){const{OuterEvent:u,notificationCenter:E}=this._core;Ic.updateLocalGroupCounters({groupID:s,groupCounterSeq:r,counterList:g}),g.forEach(({Key:f,Value:D=0})=>{E.emitOuterEvent(u.GROUP_COUNTER_UPDATED,{name:u.GROUP_COUNTER_UPDATED,data:{groupID:s,key:f,value:D}})})}reset(){Ic.reset()}},Vm=new class{constructor(){this._name="InitGroupAttributes"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(s){return mA(this,void 0,void 0,function*(){const{groupID:r,groupAttributes:g}=s,{serverMainSequence:u,avChatRoomKey:E}=as.getGroupAttributesCache(r),f=as.convertKeyValueMapToList(g);try{const D=yield function(W,nA){return mA(this,void 0,void 0,function*(){const{groupID:EA,mainSequence:wA,groupAttributeList:kA,avChatRoomKey:VA}=W,LA={GroupId:EA,AttrMainSeq:wA,GroupAttr:kA,BytesKey:VA,AttrControl:["RaceConflict"]};return nA.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:LA})})}({groupID:r,avChatRoomKey:E,groupAttributeList:f,mainSequence:u},this._core),{AttrMainSeq:v,GroupAttr:N}=D||{},P=N.map(W=>{const{Key:nA,seq:EA}=W;return{key:nA,value:g[nA],sequence:EA}});return as.saveGroupAttributesCacheValuesCopy(r),as.refreshGroupAttributesCache({groupID:r,serverMainSequence:v,groupAttributeList:P,operation:pD}),as.emitGroupAttributesUpdated(r),fs({groupAttributes:g},{message:` groupID:${r} serverMainSequence:${v}`})}catch(D){throw new this._core.helper.ChatError({functionName:"initGroupAttributes",code:D?.errorCode,message:D?.errorInfo})}})}},qT=new class{constructor(){this._name="SetGroupAttributes"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupAttributes",context:this}),r.registerExperimentalAPI("setRichStatus",this)}setGroupAttributes(s){return mA(this,void 0,void 0,function*(){const{groupID:r,groupAttributes:g,richStatusMode:u}=s,{serverMainSequence:E,avChatRoomKey:f,values:D}=as.getGroupAttributesCache(r),v=as.convertKeyValueMapToList(g).map(N=>{var P;const{key:W,value:nA}=N;return{key:W,value:nA,seq:((P=D.get(N.key))===null||P===void 0?void 0:P.sequence)||0}});try{const N=yield function(EA,wA){return mA(this,void 0,void 0,function*(){const{groupID:kA,mainSequence:VA,groupAttributeList:LA,avChatRoomKey:SA,richStatusMode:PA}=EA,zA={GroupId:kA,AttrMainSeq:VA,GroupAttr:LA,BytesKey:SA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:PA};return wA.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:zA})})}({groupID:r,avChatRoomKey:f,groupAttributeList:v,mainSequence:E,richStatusMode:u},this._core),{AttrMainSeq:P,GroupAttr:W}=N||{},nA=W.map(EA=>{const{Key:wA,seq:kA}=EA;return{key:wA,value:g[wA],sequence:kA}});return as.saveGroupAttributesCacheValuesCopy(r),as.refreshGroupAttributesCache({groupID:r,serverMainSequence:P,groupAttributeList:nA,operation:KM}),as.emitGroupAttributesUpdated(r),fs({groupAttributes:g},{message:` groupID:${r} serverMainSequence:${P}`})}catch(N){throw new this._core.helper.ChatError({functionName:"setGroupAttributes",code:N?.errorCode,message:N?.errorInfo})}})}setRichStatus(s){return mA(this,void 0,void 0,function*(){const{groupID:r,richStatus:g}=s;return this.setGroupAttributes({groupID:r,groupAttributes:g,richStatusMode:!0})})}},ND=new class{constructor(){this._name="DeleteGroupAttributes"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"deleteGroupAttributes",context:this}),r.registerExperimentalAPI("deleteRichStatus",this)}deleteGroupAttributes(s){return mA(this,void 0,void 0,function*(){const r="deleteGroupAttributes",{groupID:g,keyList:u=[],richStatusMode:E}=s;try{let f;f=u.length===0?yield this._clearGroupAttributes(g,{richStatusMode:E}):yield this._deleteGroupAttributes(g,{keyList:u,richStatusMode:E});const{resultList:D,serverMainSequence:v,operation:N,groupAttributeList:P}=f||{},W=`${this._name}.${r} ok. groupID:${g} operation: ${N}`;return as.saveGroupAttributesCacheValuesCopy(g),as.refreshGroupAttributesCache({groupID:g,serverMainSequence:v,groupAttributeList:P,operation:N}),as.emitGroupAttributesUpdated(g),fs({keyList:D},{message:W})}catch(f){throw new this._core.helper.ChatError({functionName:r,code:f?.errorCode,message:f?.errorInfo})}})}deleteRichStatus(s){return mA(this,void 0,void 0,function*(){return this.deleteGroupAttributes(Object.assign(Object.assign({},s),{richStatusMode:!0}))})}_deleteGroupAttributes(s,r){return mA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:u,values:E}=as.getGroupAttributesCache(s),{keyList:f,richStatusMode:D}=r,v=[],N=[];f.forEach(nA=>{if(E.has(nA)){const{sequence:EA=0}=E.get(nA)||{};N.push({key:nA,seq:EA}),v.push(nA)}});const P=yield function(nA,EA){return mA(this,void 0,void 0,function*(){const{groupID:wA,mainSequence:kA,groupAttributeList:VA,avChatRoomKey:LA,richStatusMode:SA}=nA,PA={GroupId:wA,AttrMainSeq:kA,GroupAttr:VA,BytesKey:LA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:SA};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:PA})})}({groupID:s,avChatRoomKey:u,groupAttributeList:N,mainSequence:g,richStatusMode:D},this._core),{AttrMainSeq:W}=P||{};return{resultList:v,serverMainSequence:W,groupAttributeList:N,operation:fD}})}_clearGroupAttributes(s,r){return mA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:u,values:E}=as.getGroupAttributesCache(s),{richStatusMode:f}=r||{},D=[...E.keys()],v=yield function(P,W){return mA(this,void 0,void 0,function*(){const{groupID:nA,mainSequence:EA,avChatRoomKey:wA,richStatusMode:kA}=P,VA={GroupId:nA,AttrMainSeq:EA,BytesKey:wA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:VA})})}({groupID:s,avChatRoomKey:u,mainSequence:g,richStatusMode:f},this._core),{AttrMainSeq:N}=v||{};return{resultList:D,serverMainSequence:N,operation:mD}})}},GD=new class{constructor(){this._name="GetGroupAttributes"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getGroupAttributes",context:this}),r.registerExperimentalAPI("getRichStatus",this,"getGroupAttributes")}getGroupAttributes(s){return mA(this,void 0,void 0,function*(){const{groupID:r}=s,{avChatRoomKey:g,lastUpdateTime:u,localMainSequence:E,serverMainSequence:f}=as.getGroupAttributesCache(r),{helper:{ChatError:D}}=this._core,v=`groupID:${r} localMainSequence:${E} serverMainSequence:${f} keyList:${s.keyList}`;if(Date.now()-u>=3e4||E{const{key:nA,value:EA,seq:wA}=W;return{key:nA,value:EA,sequence:wA}});return as.refreshGroupAttributesCache({groupID:u,serverMainSequence:v,groupAttributeList:P,operation:jM}),{serverGroupAttributeList:N}})}},VQ=new class{init(s){s.ssoLog.debug("GroupAttribute.init"),Vm.init(s),qT.init(s),ND.init(s),GD.init(s),as.init(s)}isGroupAttributesUpdated(s){return as.isGroupAttributesUpdated(s)}handleGroupAttributesUpdated(s){const{to:r,elements:{newGroupProfile:g}}=s,{groupAttributeOption:u}=g,{serverMainSequence:E,withChangedAttributeInfo:f}=u,{localMainSequence:D}=as.getGroupAttributesCache(r),v=E-D;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${r} withChangedAttributeInfo:${f} diffSequence:${v}`),v!==0)if(as.saveGroupAttributesCacheValuesCopy(r),f!==1||v!==1){if(as.hasGroupAttributesCache(r)){const{avChatRoomKey:N}=as.getGroupAttributesCache(r);GD.getGroupAttributesFromServer({groupID:r,avChatRoomKey:N}).then(()=>{as.emitGroupAttributesUpdated(r)}).catch(()=>{})}}else as.handleGroupAttributesUpdated({groupID:r,groupAttributeOption:u})}reset(){as.reset()}};function KE(s,r="tips"){const{ClientSeq:g,From_Account:u,MsgClientTime:E,MsgPriority:f,MsgRandom:D,MsgSeq:v,MsgTimeStamp:N,TinyId:P,ToGroupId:W,GroupInfo:nA,MsgBody:EA}=s,wA=function(kA){const{GroupCode:VA,GroupId:LA,GroupName:SA,GroupType:PA,MsgFrom_AccountExtraInfo:zA,From_Account:Ee,To_Account:Ie}=kA;return{groupCode:VA,groupID:LA,groupName:SA,type:PA,messageFromAccountExtraInformation:zA,from:Ee,to:Ie}}(nA);return{clientSequence:g,from:u,clientTime:E,priority:f,random:D,sequence:v,time:N,tinyID:P,to:W,groupProfile:wA,elements:r==="tips"?$u(EA):Qh(EA)}}function $u(s){const r={};return Object.keys(s).forEach(g=>{var u,E;switch(g){case"MemberNum":r.memberCount=s[g];break;case"OpType":r.operationType=s[g];break;case"Operator_Account":r.operatorID=s[g];break;case"List_Account":r.userIDList=s[g];break;case"MsgMemberExtraInfo":r.memberInfoList=(u=s[g])===null||u===void 0?void 0:u.map(f=>bD(f));break;case"MsgOperatorMemberExtraInfo":r.operatorInfo=bD(s[g]);break;case"MsgGroupNewInfo":r.newGroupProfile=function(f){const D={};return Object.keys(f).forEach(v=>{switch(v){case"GroupIntroduction":D.introduction=f[v];break;case"GroupName":D.groupName=f[v];break;case"GroupFaceUrl":D.avatar=f[v];break;case"GroupNotification":D.notification=f[v];break;case"ApplyJoinOption":D.joinOption=f[v];break;case"InviteJoinOption":D.inviteOption=f[v];break;case"ShutupAll":D.muteAllMembers=f[v];break;case"Owner_Account":D.ownerID=f[v];break;case"GroupAttrOption":D.groupAttributeOption=function(P){const{BytesChangedKeys:W,GroupAttrSeq:nA,OpType:EA,PushChangedAttrValFlag:wA,GroupAttrInfo:kA}=P,VA=kA.map(LA=>{const{Key:SA,Val:PA,SubKeySeq:zA}=LA;return{key:SA,value:PA,sequence:zA}});return{changedKeyList:W,groupAttributeList:VA,serverMainSequence:nA,operation:EA,withChangedAttributeInfo:wA}}(f[v]);break;case"MsgAppDefinedData":D.groupCustomField=(N=f[v])==null?void 0:N.map(P=>({key:P.Key,value:P.Value}));break;case"InviteOption":D.inviteOption=YT[f[v]]||f[v]}var N}),D}(s[g]);break;case"MsgMemberInfo":r.msgMemberInfo=(E=s[g])===null||E===void 0?void 0:E.map(f=>function(D){const{ShutupTime:v,User_Account:N}=D;return{muteTime:v,userID:N}}(f));break;case"OnlineMemberInfo":r.onlineMemberInfo=function(f){const{ExpireTime:D,OnlineMemberNum:v}=f;return{expireTime:D,onlineMemberNum:v}}(s[g]);break;case"GroupCounterInfo":r.groupCounterInfo=function(f){return f.map(D=>{const{GroupCounterSeq:v,GroupCounter:N,Type:P}=D;return{type:P,groupCounterSeq:v,counterList:N}})}(s[g])}}),r}function bD(s){const{ImageUrl:r,NickName:g,Role:u,UserId:E}=s;return{avatar:r,nick:g,role:u,userID:E}}function Qh(s){const r={};return Object.keys(s).forEach(g=>{switch(g){case"MsgKey":r.messageKey=s[g];break;case"Operator_Account":r.operatorID=s[g];break;case"ReportType":r.operationType=s[g];break;case"Authentication":r.authentication=s[g];break;case"MsgFlag":r.messageRemindType=s[g];break;case"UserDefinedField":r.userDefinedField=s[g];break;case"RemarkInfo":r.remarkInfo=s[g];break;case"BanDuration":r.duration=s[g];break;case"MuteTime":r.muteTime=s[g];break;case"MsgMemberExtraInfoList":r.inviteeInfoList=(u=s[g]||[])==null?void 0:u.map(E=>{const{UserId:f,ImageUrl:D,NickName:v}=E;return{userID:f,avatar:D,nick:v}});break;case"MemberList_Account":r.inviteeList=s[g]}var u}),r}class Hm{constructor(r){this.type=tr.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(r)}static parseServerPushElement(r){const g=$u(r);return new Hm(g)}_initContent(r){Object.keys(r).forEach(g=>{switch(g){case"groupProfile":this._initGroupProfile(r[g]);break;case"operatorInfo":this._initOperatorInfo(r[g]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(r[g]);break;case"newGroupProfile":this._initNewGroupProfile(r[g]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[g]=r[g]}}),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(r){this.content.groupProfile={};const g=Object.keys(r);for(let u=0;u{r.forEach(u=>{g.userID===u.userID&&Object.assign(g,u)})}):this.content.memberList=r}_initNewGroupProfile(r){this.content.newGroupProfile={};const g=Object.keys(r);for(let u=0;u0&&this._handleGroupTipMessage(g),{conversationUpdateFieldList:u,messageList:g}}_emitGroupTipsEvent(s){var r;const{constants:{WORKFLOW_STEP:g}}=this._core,{messageList:u=[]}=((r=s?.result)===null||r===void 0?void 0:r[g.HANDLE_GROUP_TIPS_NOTIFICATION])||{};if(u.length>0){const{notificationCenter:E,OuterEvent:f}=this._core;E.emitOuterEvent(f.MESSAGE_RECEIVED,{name:f.MESSAGE_RECEIVED,data:u})}}_handleGroupTips(s,r=!0){const{Event:g,GroupTips:u}=s,E=new Map,f=[],D=[];for(let v=0,N=u.length;v{const{operationType:u}=g.payload;switch(u){case r.JOINED:this._handleNewMemberJoined(g);break;case r.QUITTED:this._handleMemberQuitted(g);break;case r.KICKED:this._handleMemberKicked(g);break;case r.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(g);break;case r.ADMIN_SET:this._handleMemberGrantAdmin(g);break;case r.ADMIN_CANCELED:this._handleMemberRevokeAdmin(g)}})}_handleNewMemberJoined(s){this._handleGroupMemberCountUpdated(s)}_handleMemberQuitted(s){this._handleGroupMemberCountUpdated(s)}_handleMemberKicked(s){this._handleGroupMemberCountUpdated(s)}_handleGroupProfileUpdated(s){var r;const{newGroupProfile:g,groupProfile:u,operatorInfo:E}=s.payload,{groupID:f}=u,D=Wi.getLocalGroup(f);Object.keys(g).forEach(N=>{switch(N){case"ownerID":this._handleGroupOwnerChanged(f,g);break;case"groupName":D.name=g[N];break;case"groupCustomField":Array.isArray(D[N])&&Array.isArray(g[N])?Fm(D[N],g[N]):D[N]=g[N];break;default:D[N]=g[N]}});const{utils:{isUndefined:v}}=this._core;v(E)||((r=D?.selfInfo)===null||r===void 0?void 0:r.userID)!==E.userID||Object.keys(E).forEach(N=>{N==="nameCard"&&D.updateSelfInfo({nameCard:E[N]}),N==="role"&&this._updateSelfRole(D,E[N])}),Wi.emitGroupListUpdate(),Wi.updateConversationGroupProfile(f)}_handleGroupOwnerChanged(s,r){const{common:g,OuterConstant:u}=this._core,E=Wi.getLocalGroup(s),f=g.getCurrentUserID(),{ownerID:D}=r;f===D&&E.updateGroup({ownerID:D,selfInfo:{role:u.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(s,r){const{OuterConstant:g}=this._core;let u=g.GRP_MBR_ROLE_MEMBER;r===NT?u=g.GRP_MBR_ROLE_OWNER:r===DD&&(u=g.GRP_MBR_ROLE_ADMIN),s.updateSelfInfo({role:u})}_handleGroupMemberCountUpdated(s){const{memberCount:r,groupProfile:{groupID:g}}=s.payload,u=Wi.getLocalGroup(g),{utils:{isNumber:E}}=this._core;u&&E(r)&&u.memberCount!==r&&(u.memberCount=r,Wi.emitGroupListUpdate(),Wi.updateConversationGroupProfile(g))}_handleGroupTipsRecover(s){const{utils:{isArray:r}}=this._core,{groupTipList:g}=s?.result||{};r(g)&&g.forEach(u=>{const{messageList:E}=this._handleGroupTips({Event:u.Event,GroupTips:[u]},!1);this._handleGroupTipMessage(E)})}_handleMemberGrantAdmin(s){const{OuterConstant:r}=this._core,{groupProfile:g,userIDList:u}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:f}=g,D=Wi.getLocalGroup(f);D&&u.includes(E)&&(D.updateSelfInfo({role:r.GRP_MBR_ROLE_ADMIN}),Wi.emitGroupListUpdate(),Wi.updateConversationGroupProfile(f))}_handleMemberRevokeAdmin(s){const{OuterConstant:r}=this._core,{groupProfile:g,userIDList:u}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:f}=g,D=Wi.getLocalGroup(f);D&&u.includes(E)&&(D.updateSelfInfo({role:r.GRP_MBR_ROLE_MEMBER}),Wi.emitGroupListUpdate(),Wi.updateConversationGroupProfile(f))}};class HQ{constructor(r){this.type=tr.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(r)}static parseServerPushElement(r){const g=Qh(r);return new HQ(g)}_initContent(r){Object.keys(r).forEach(g=>{switch(g){case"remarkInfo":this.content.handleMessage=r[g];break;case"groupProfile":this._initGroupProfile(r[g]);break;case"memberInfoList":break;default:this.content[g]=r[g]}})}_initGroupProfile(r){this.content.groupProfile={};const g=Object.keys(r);for(let u=0;u0&&this._handleGroupSysTemMessage(g,E),g===!0&&E.length>0&&f.emitOuterEvent(D.MESSAGE_RECEIVED,{name:D.MESSAGE_RECEIVED,data:E})}_handleGroupSystemNotification(s,r){const g=[];let u={};for(let E=0;E0?[u]:[],messageList:g}}_assembleMessage(s){const{message:{messageFactory:r},OuterConstant:g,utils:{randomInt:u}}=this._core;s.flow="in",s.conversationType=g.CONV_SYSTEM,s.conversationSubType=s.groupProfile.type,s.conversationID=g.CONV_SYSTEM;const E=r.createMessage(s),f=new HQ(Object.assign(Object.assign({},s.elements),{groupProfile:Object.assign({},s.groupProfile)}));E.setElement(f),E.isSystemMessage=!0;const D=E.sequence===1&&E.random===1,v=E.sequence===2&&E.random===2;return(D||v)&&(E.sequence=u(),E.random=u(),E.generateMessageID()),E}_handleConversationOptions(s,r){const{OuterConstant:g}=this._core,u={conversationID:g.CONV_SYSTEM,unreadCount:0,type:g.CONV_SYSTEM,subType:s.conversationSubType,lastMessage:null};return r&&u.unreadCount++,u}_handleGroupSysTemMessage(s,r){s&&r.forEach(g=>{const{operationType:u}=g.payload;switch(u){case bT:this._handleGroupJoinResult(g);break;case zM:this._handleMemberKicked(g);break;case kT:this._handleGroupDismissed(g);break;case LT:this._handleGroupInvitedResult(g);break;case SD:this._handleGroupQuitResult(g);break;case UQ:this._handleMessageRemindTypeSynced(g);break;case Gm:this._handleAVChatRoomMemberBanned(g)}})}_handleGroupJoinResult(s){const{groupProfile:r}=s.payload,{groupID:g,type:u}=r,E=Wi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${g} type:${u} hasLocalGroup:${E}`),E||Md(u)||(Wi.updateLocalGroup([Object.assign({},r)]),Wi.emitGroupListUpdate())}_handleMemberKicked(s){const{groupProfile:{groupID:r,type:g}}=s.payload;Wi.hasLocalGroup(r)&&this._deleteLocalGroup(r,g),this._updateConversationProfile(r,{unreadCount:0})}_handleGroupDismissed(s){const{groupProfile:{groupID:r,type:g}}=s.payload;Wi.hasLocalGroup(r)&&this._deleteLocalGroup(r,g),this._updateConversationProfile(r,{unreadCount:0})}_handleGroupInvitedResult(s){const{groupProfile:r}=s.payload,{groupID:g}=r,u=Wi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${g} hasLocalGroup:${u}`),u||Jl.getGroupProfile({groupID:g}).then(E=>{const{data:{group:f}}=E;Wi.updateLocalGroup([Object.assign({},f)]),Wi.emitGroupListUpdate()})}_handleGroupQuitResult(s){const{groupProfile:{groupID:r,type:g}}=s.payload,u=Wi.hasLocalGroup(r);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${r} type:${g} hasLocalGroup:${u}`),u&&this._deleteLocalGroup(r,g),this._updateConversationProfile(r,{unreadCount:0})}_handleMessageRemindTypeSynced(s){const{groupProfile:{groupID:r},messageRemindType:g}=s.payload;this._updateConversationProfile(r,{messageRemindType:g})}_handleAVChatRoomMemberBanned(s){const{groupProfile:{groupID:r,type:g}}=s.payload;this._deleteLocalGroup(r,g)}_deleteLocalGroup(s,r){if(Md(r)){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:u}}=this._core;g.deleteConversation(`${u}${s}`)}Wi.deleteLocalGroup(s),Wi.emitGroupListUpdate()}_updateConversationProfile(s,r){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:u}}=this._core,E=`${u}${s}`;g.getConversation(E)&&g.updateConversation(E,r)}},kD=new class{init(s){this._core=s,s.ssoLog.debug("GroupNotificationHandler.init"),nR.init(s),sR.init(s);const{notificationCenter:r,InnerEvent:g}=s,{InnerEventSubType:u}=r;r.subscribeInnerEvent(g.MESSAGE_PUSH,u.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),r.subscribeInnerEvent(g.MESSAGE_PUSH,u.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),r.subscribeInnerEvent(g.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(s){const{common:{workflowManager:r},constants:{WORKFLOW_NAME:g}}=this._core;r.executeWorkflow(g.RECEIVE_GROUP_TIPS_NOTIFICATION,s)}_onNewGroupSystemNotification(s){sR.onNewGroupSystemNotification(s)}_dispose(){const{notificationCenter:s,InnerEvent:r}=this._core,{InnerEventSubType:g}=s;s.unSubscribeInnerEvent(r.MESSAGE_PUSH,g.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),s.unSubscribeInnerEvent(r.MESSAGE_PUSH,g.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this)}};const bs={required:!0,rules:["string"],allowEmpty:!1},JQ={required:!0,rules:["number"],allowEmpty:!1},Td={required:!0,rules:["array"],allowEmpty:!1},LD={required:!0,rules:["object"],allowEmpty:!1},KT={createGroup:{name:bs,type:bs},dismissGroup:[Object.assign({key:"groupID"},bs)],joinGroup:{groupID:bs,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},bs)],searchGroupByID:[Object.assign({key:"groupID"},bs)],getGroupProfile:{groupID:bs,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:bs,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:bs,newOwnerID:bs},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},bs)],handleGroupApplication:{handleAction:bs},getGroupMemberList:{groupID:bs},getGroupMemberProfile:{groupID:bs,userIDList:Td,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:bs,userIDList:Td},deleteGroupMember:{groupID:bs,userIDList:Td},setGroupMemberMuteTime:{groupID:bs,userID:bs,muteTime:Object.assign(Object.assign({},JQ),{customValidator:s=>!(s<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:bs,userID:bs,role:bs},setGroupMemberNameCard:{groupID:bs,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:bs},setGroupMemberCustomField:{groupID:bs,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:Td},markGroupMemberList:{groupID:bs,markType:Object.assign(Object.assign({},JQ),{customValidator:s=>!(s<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:Td},initGroupAttributes:{groupID:bs,groupAttributes:LD},setGroupAttributes:{groupID:bs,groupAttributes:LD},deleteGroupAttributes:{groupID:bs,keyList:Object.assign(Object.assign({},Td),{allowEmpty:!0})},getGroupAttributes:{groupID:bs,keyList:Object.assign(Object.assign({},Td),{allowEmpty:!0})},getGroupCounters:{groupID:bs,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:bs,counters:LD},increaseGroupCounter:{groupID:bs,key:bs,value:JQ},decreaseGroupCounter:{groupID:bs,key:bs,value:JQ}},jT={getGroupList:!0,createGroup:!0,dismissGroup:!0,joinGroup:!0,quitGroup:!0,searchGroupByID:!0,getGroupProfile:!0,updateGroupProfile:!0,changeGroupOwner:!0,getGroupOnlineMemberCount:!0,getGroupApplicationList:!0,handleGroupApplication:!0,getGroupMemberList:!0,getGroupMemberProfile:!0,addGroupMember:!0,deleteGroupMember:!0,setGroupMemberMuteTime:!0,setGroupMemberRole:!0,setGroupMemberNameCard:!0,setGroupMemberCustomField:!0,markGroupMemberList:!0,initGroupAttributes:!0,setGroupAttributes:!0,getGroupAttributes:!0,deleteGroupAttributes:!0,getGroupCounters:!0,setGroupCounters:!0,increaseGroupCounter:!0,decreaseGroupCounter:!0};var WT=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=Wi,this.groupAction=PQ,this.groupAttribute=VQ,this.groupMember=oR,this.groupCounter=CB,this.name="Group"}install(s,r=[]){this._core=s,tr.init(s),Wi.init(s),PQ.init(s,this),oR.init(s,this),wD.init(s),CB.init(s),VQ.init(s),kD.init(s),s.helper.registerValidateConfig({auth:jT,params:KT}),this._installSubPlugins(r);const{notificationCenter:g,InnerEvent:u}=s;g.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.subscribeInnerEvent(u.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(s){const{utils:{isArray:r}}=this._core;s&&r(s)&&s.forEach(g=>{var u;this._installedSubPlugins.includes(g.name)||((u=g.install)===null||u===void 0||u.call(g,this._core,this),this._installedSubPlugins.push(g.name))})}_reset(){Wi.reset(),VQ.reset(),CB.reset()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const hB=new class{init(s){this.core=s}},rR="AV_MBR_LIST",zT="AV_BAN_MBR",jE={NORMAL_MESSAGE:3,GROUP_TIPS_HAS_ROAMING:4,GROUP_SYSTEM_MESSAGE:5,GROUP_TIPS_HAS_NO_ROAMING:6,BROADCAST_MESSAGE:17,MESSAGE_REVOKED:20,MESSAGE_REACTION:21,LIVE_CUSTOM_DATA:100},ph={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},UD=60,FD=2603,ZT=2686,XT=2688,qQ=3122;class aR{constructor(r){const{core:g,manager:u,groupID:E,getRequestParams:f,onSuccess:D,onFail:v}=r;this._name="Polling",this._core=g,this._manager=u,this._timeoutID=-1,this._isRunning=!1,this._groupID=E,this._getRequestParams=f,this._onSuccess=D,this._onFail=v}start(){this._isRunning=!0,this._request(),console.log(`${this._name}.start pollingInterval:${this._manager.getCurrentPollingInterval(this._groupID)}`)}isRunning(){return this._isRunning}_request(){return mA(this,void 0,void 0,function*(){try{const r=this._getRequestParams(this._groupID),g=yield function(E,f){return mA(this,void 0,void 0,function*(){const{longPollingKey:D,startSequence:v,startBroadcastSeq:N,simplifiedMessage:P}=E,W={Key:D,StartSeq:v,StartBroadcastSeq:N,DownsizeFlag:P,USP:1,HoldTime:90};return f.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:W})})}(r,this._core);this._onSuccess(this._groupID,g);const u=this._manager.getCurrentPollingInterval(this._groupID);this._runNextPolling(u)}catch(r){this._onFail(this._groupID,r),this._runNextPolling(2e3)}})}_runNextPolling(r){this.isRunning()&&(this._timeoutID>-1&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),r))}stop(){console.log(`${this._name}.stop timerID:${this._timeoutID}`),this._timeoutID>-1&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class mh{constructor(r){this._maxLength=r,this._map=new Map}set(r){var g;if(this._map.size>=this._maxLength){const u=((g=this._map.entries().next().value)===null||g===void 0?void 0:g[0])||"";this._map.delete(u)}this._map.set(r,1)}has(r){return this._map.has(r)}delete(r){this.has(r)&&this._map.delete(r)}clear(){this._map.clear()}}const AE=s=>s===jE.GROUP_TIPS_HAS_NO_ROAMING||s===jE.GROUP_TIPS_HAS_ROAMING,KQ=s=>s===jE.GROUP_SYSTEM_MESSAGE;function Jm(s){const r=function(g){const{E:u,MCT:E,MR:f,MP:D,MTS:v,GId:N,MS:P,CCD:W,F_Account:nA,IsSys:EA,GInf:wA,MsgBody:kA}=g,VA=vo(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:u,MsgClientTime:E,MsgRandom:f,MsgPriority:D,MsgTimeStamp:v,ToGroupId:N,MsgSeq:P,CloudCustomData:W,From_Account:nA,IsSystemMsg:EA,GroupInfo:OD(wA),MsgBody:$T(kA)},VA)}(s);return function(g){const{Event:u}=g;(AE(u)||KQ(u))&&(g.From_Account=g.From_Account||"@TIM#SYSTEM"),E=u,(E===jE.BROADCAST_MESSAGE||(f=>f===jE.NORMAL_MESSAGE)(u))&&function(f){const{core:{OuterConstant:D}}=hB;f.CloudCustomData=f.CloudCustomData||"",f.MsgBody=f.MsgBody.map(v=>{if(v.MsgType===D.MSG_CUSTOM){const{content:N={}}=v;v.content=Object.assign({Data:"",Desc:"",Ext:""},N)}return v})}(g);var E;AE(u)&&function(f){const{GroupJoinType:D,MsgOperatorMemberExtraInfo:v={},MsgMemberExtraInfo:N,Operator_Account:P,List_Account:W,OpType:nA}=f.MsgBody||{};typeof D=="number"||nA!==1&&nA!==2||(f.MsgBody.GroupJoinType=nA===2?0:1),N||(f.MsgBody.MsgMemberExtraInfo=W?.map(EA=>({UserId:EA}))),nA!==1||N||(f.MsgBody.MsgMemberExtraInfo=[{UserId:v.UserId}]),f.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:P,ImageUrl:"",NickName:""},v)}(g),KQ(u)&&function(f){const{MsgOperatorMemberExtraInfo:D={},Operator_Account:v}=f.MsgBody||{};f.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:v,ImageUrl:"",NickName:""},D),f.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*f.MsgTimeStamp},f.MsgBody),f.MsgBody=Object.keys(f.MsgBody).filter(N=>N!=="MsgOperatorMemberExtraInfo").reduce((N,P)=>Object.assign(Object.assign({},N),{[P]:f.MsgBody[P]}),{})}(g)}(r),r}function OD(s){const r=s||{},{GN:g,GT:u,F_Hd:E,F_NN:f,F_Ll:D}=r,v=vo(r,["GN","GT","F_Hd","F_NN","F_Ll"]),N=Object.assign({GroupName:g,GroupType:u},v);return E&&(N.From_AccountHeadurl=E),f&&(N.From_AccountNick=f),D&&(N.From_AccountLevel=D),N}function $T(s){let r=s;Array.isArray(s)||(r=[s]);const g=r.map(u=>{const{O_Account:E,Opt:f,L_Account:D,RT:v,UDF:N,OpInf:P,OnlineInf:W,MsgMemberExtraInfo:nA}=u,EA=vo(u,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),wA=Object.assign({Operator_Account:E,OpType:f,List_Account:D,ReportType:v,UserDefinedField:N},EA);return P&&(wA.MsgOperatorMemberExtraInfo=function(kA){const{Img:VA,NN:LA}=kA,SA=vo(kA,["Img","NN"]);return Object.assign({ImageUrl:VA,NickName:LA},SA)}(P)),nA&&(wA.MsgMemberExtraInfo=function(kA){return kA?.map(VA=>{const{Img:LA,NN:SA}=VA,PA=vo(VA,["Img","NN"]);return Object.assign({ImageUrl:LA,NickName:SA},PA)})}(nA)),W&&(wA.OnlineMemberInfo=function(kA){const{ET:VA,Num:LA}=kA;return{ExpireTime:VA,OnlineMemberNum:LA}}(W)),wA});return Array.isArray(s)?g:g[0]}var fh=new class{constructor(){this._name="MessageParser",this._sequenceList=new mh(200),this._messageIDList=new mh(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(s,r){this._core=s,this._avChatRoomHandler=r}onMessageReceived(s,r,g=!1){this._sortServerMessageList({groupID:s,serverMessageList:r,isHistoryMessage:g});const u=this._handleMessageList(s,r);if(u.length===0)return;if(!g){const{appStore:{conversationStore:N},OuterConstant:{CONV_GROUP:P},common:{buildLastMessage:W}}=this._core,nA=W(u[u.length-1]);N.updateConversation(`${P}${s}`,{lastMessage:nA})}this._checkMessageStacked(u);const E=u.filter(N=>N.isModified===!0),f=u.filter(N=>N.isModified===!1),{OuterEvent:{MESSAGE_RECEIVED:D,MESSAGE_MODIFIED:v}}=this._core;E.length>0&&this._emitEvent({name:v,data:E}),f.length>0&&this._emitEvent({name:D,data:f})}_sortServerMessageList(s){const{groupID:r,serverMessageList:g,isHistoryMessage:u}=s;let E=[];this._avChatRoomHandler.isPollingSimplifiedMessage()&&!u?(g.sort((f,D)=>f.MS-D.MS),E=g.map(f=>f.MS)):(g.sort((f,D)=>f.MsgSeq-D.MsgSeq),E=g.map(f=>f.MsgSeq)),console.log(`${this._name}._sortServerMessageList groupID:${r} count:${E.length} sequenceList:${E}`),E.length=0}_handleMessageList(s,r){var g;const{message:{messageDataHandler:u,messageHelper:E}}=this._core,f=this._avChatRoomHandler.isPollingSimplifiedMessage(),D=[],v=r.length;for(let N=0;Ng===jE.MESSAGE_REVOKED)(r)?(this._handleMessageRevoked(s),null):(g=>g===jE.LIVE_CUSTOM_DATA)(r)?(this._onLiveCustomData(s),null):(g=>g===jE.MESSAGE_REACTION)(r)?null:s:(console.warn(`${this._name}.onMessageReceived unknown event:${r}`),null)}_createMessage(s){const{message:{messageFactory:r},OuterConstant:g}=this._core;let u=g.CONV_GROUP;s.elements.type===g.MSG_GRP_SYS_NOTICE&&(u=g.CONV_SYSTEM);const E=!!s.isSystemMessage,f=r.createMessage(Object.assign(Object.assign({},s),{conversationType:u,isSystemMessage:E,flow:"in"}));return f.setElement(s.elements),f}_filterDuplicateMessage(s){const{common:r}=this._core;if(!r.isUnlimitedAVChatRoom()){if(this._sequenceList.has(s.sequence))return null;this._sequenceList.set(s.sequence)}const g=this._messageIDList.has(s.ID);return g?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${s.ID} has:${g}`),null):(this._messageIDList.set(s.ID),s)}_handleMessageRevoked(s){const{OuterConstant:r,OuterEvent:{MESSAGE_REVOKED:g}}=this._core,{ToGroupId:u,MsgBody:{RevokeMsgList:E},RevokerInfo:{Revoker_Account:f,Reason:D=""}}=s,v=[];E.forEach(N=>{const{TinyId:P,MsgClientTime:W,Random:nA,MsgSeq:EA}=N,wA={conversationID:`${r.CONV_GROUP}${u}`,ID:`${P}-${W}-${nA}`,revoker:f,revokeReason:D,revokerInfo:{userID:f,nick:"",avatar:""},sequence:EA};v.push(wA)}),v.length!==0&&this._emitEvent({name:g,data:v})}_onLiveCustomData(s){const{OuterEvent:{ROOM_CUSTOM_DATA_RECEIVED:r}}=this._core,{ToGroupId:g,MsgSeq:u,MsgTimeStamp:E,MsgBody:f}=s,D=f?.Content||f?.MsgContent||"";this._emitEvent({name:r,data:D}),console.log(`${this._name}._onLiveCustomData groupID:${g} sequence:${u} time:${E} data:${D}`)}_onGroupDismissed(s){this._avChatRoomHandler.reset(s)}_checkMessageStacked(s){const{length:r}=s;if(r>=100&&this._reportMessageStackedCount<5){const g=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.info("MessageStacked",`count:${r} groupID:${g.join(",")}`),this._reportMessageStackedCount+=1}}_emitEvent(s){this._core.notificationCenter.emitOuterEvent(s.name,s)}onBroadcastMessageReceived(s){const{message:{messageHelper:r},OuterEvent:{MESSAGE_RECEIVED:g}}=this._core,u=this._avChatRoomHandler.isPollingSimplifiedMessage(),E=[],f=s.length;for(let D=0;D0&&this._emitEvent({name:g,data:E})}_updateLocalOnlineMemberCountFromTips(s){const{utils:{isEmpty:r}}=this._core,{ToGroupId:g,MsgBody:{OnlineMemberInfo:u}}=s;if(r(u))return;const{OnlineMemberNum:E=0,ExpireTime:f=UD}=u,D=Date.now();let v=this._avChatRoomHandler.getLocalOnlineMemberCount(g);r(v)?v={lastReqTime:0,lastSyncTime:0,latestUpdateTime:D,memberCount:E,expireTime:f}:(v.latestUpdateTime=D,v.memberCount=E),this._avChatRoomHandler.updateLocalOnlineMemberCount(g,v)}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};const BB=s=>{const{core:{store:r}}=hB;return(r.get("cloudConfig")||{})[s]},yh=s=>{const{core:{utils:{isUndefined:r}}}=hB;return!r(s)},jQ=()=>{const s=BB("polling_interval");return yh(s)?parseInt(s,10):300},QB=()=>{const s=BB("polling_simplified_msg");return yh(s)?parseInt(s,10):0};var gR=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}getGroupOnlineMemberCount(s){return mA(this,void 0,void 0,function*(){const{appStore:{groupStore:r},OuterConstant:g}=this._core,u=r.getGroup(s);return u?u.type===g.GRP_AVCHATROOM?this._getOnlineMemberCount(s):this._parentPlugin.groupAction.getGroupOnlineMemberCount(s):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(s){return mA(this,void 0,void 0,function*(){const r="_getOnlineMemberCount",{utils:{isEmpty:g}}=this._core,u=Vg.getLocalOnlineMemberCount(s);if(g(u)||this._isExpired(s)){const{memberCount:E=0}=yield this._getOnlineMemberCountFromServer(s);return console.log(`${this._name}.${r} ok, groupID:${s} memberCount:${E} from server.`),{code:0,data:{memberCount:E}}}return console.log(`${this._name}.${r} ok, groupID:${s} memberCount:${u.memberCount} from local.`),{code:0,data:{memberCount:u.memberCount}}})}_isExpired(s){const r=Vg.getLocalOnlineMemberCount(s),g=Date.now(),u=g-r.lastSyncTime>1e3*r.expireTime,E=g-r.latestUpdateTime>1e4,f=g-r.lastReqTime>3e3;return u&&E&&f}_getOnlineMemberCountFromServer(s){return mA(this,void 0,void 0,function*(){const r="_getOnlineMemberCountFromServer";try{const g=yield function(v,N){return mA(this,void 0,void 0,function*(){const P={GroupId:v};return N.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:P})})}(s,this._core),{OnlineMemberNum:u=0,ExpireTime:E=UD}=g||{},f=Date.now(),D={lastSyncTime:f,latestUpdateTime:f,lastReqTime:f,memberCount:u,expireTime:E};return Vg.updateLocalOnlineMemberCount(s,D),{memberCount:u}}catch(g){const u=new this._core.helper.ChatError({functionName:r,code:g?.errorCode,message:g?.errorInfo});throw console.error(`${this._name}.${r} fail:`,u),u}})}},Vg=new class{constructor(){this._name="AVChatRoomHandler",this._joinedGroupMap=new Map,this._pollingRequestInfoMap=new Map,this._pollingInstanceMap=new Map,this._onlineMemberCountMap=new Map,this._pollingIntervalMap=new Map,this._pollingNoMessageCountMap=new Map,this._membersReqInfoMap=new Map,this._startBroadcastSequence=1}init(s,r){this._core=s,this._parentPlugin=r,fh.init(s,this),s.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(s){const{OuterConstant:{GRP_AVCHATROOM:r}}=this._core,{GroupTips:g=[]}=s;for(let u=0;u0&&(r=[...this._joinedGroupMap.values()].filter(g=>g.type===s)),r}handleJoinGroupResult(s){return mA(this,void 0,void 0,function*(){const{utils:{isUndefined:r},OuterConstant:{CONV_GROUP:g},apiMap:{getConversationProfile:u},OuterConstant:E}=this._core,{longPollingKey:f,group:D,historyMessageList:v=[]}=s,{groupID:N}=D;return yield this._preCheck(D),this._joinedGroupMap.set(N,D),this._parentPlugin.groupDataHandler.updateLocalGroup([D]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),u(`${g}${N}`),gR.getGroupOnlineMemberCount(N),v.length>0&&fh.onMessageReceived(N,v,!0),r(f)?{code:0,data:{status:E.JOIN_STATUS_SUCCESS,group:D}}:{code:0,data:this.startMessageLongPolling(s)}})}isGroupCounterUpdated(s){return this._parentPlugin.groupCounter.isGroupCounterUpdated(s)}handleGroupCounterUpdated(s){this._parentPlugin.groupCounter.handleGroupCounterUpdated(s)}_preCheck(s){return mA(this,void 0,void 0,function*(){const{common:r,OuterConstant:g,helper:u,apiMap:{quitGroup:E},ssoLog:f}=this._core;if(r.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(()=>{const N=BB("polling_count_limit");return yh(N)&&N>0?parseInt(N,10):20})())throw new u.ChatError({code:XT,message:"the count of longPolling exceeds the max limit"});return}if(this._joinedAVChatRoomCount()===0||s.type===g.GRP_LIVE)return;const[D,v]=this._joinedGroupMap.entries().next().value;if(v.selfInfo.role===g.GRP_MBR_ROLE_OWNER)this._parentPlugin.groupDataHandler.deleteLocalGroup(D);else try{yield E(D)}catch(N){f.debug("quitGroup",`${this._name}._preCheck quitGroup failed, groupID:${D} info:`,N)}this.reset(D)})}startMessageLongPolling(s){const{OuterConstant:r}=this._core,{longPollingKey:g,startSequence:u=1,group:E}=s,{groupID:f}=E;return this._pollingRequestInfoMap.set(f,{longPollingKey:g,startSequence:u}),this._pollingIntervalMap.set(f,jQ()),this._startPolling(f),this._reportLongPollingCount(),{status:r.JOIN_STATUS_SUCCESS,group:E}}_startPolling(s){if(this._core.ssoLog.debug("_startPolling",`${this._name}._startPolling groupID:${s}`),this._pollingInstanceMap.has(s)){const g=this._pollingInstanceMap.get(s);return void(g?.isRunning()||g==null||g.start())}const r=new aR({core:this._core,manager:this,groupID:s,getRequestParams:this._handleRequestParams.bind(this),onSuccess:this._handleSuccess.bind(this),onFail:this._handleFailure.bind(this)});r.start(),this._pollingInstanceMap.set(s,r)}_handleRequestParams(s){const{longPollingKey:r,startSequence:g}=this._pollingRequestInfoMap.get(s)||{};return s===[...this._pollingInstanceMap.keys()][0]?{longPollingKey:r,startSequence:g,startBroadcastSeq:this._startBroadcastSequence,simplifiedMessage:QB()}:{longPollingKey:r,startSequence:g,simplifiedMessage:QB()}}_handleSuccess(s,r){const{ErrorCode:g}=r;if(g!==0){const{longPollingKey:u,startSequence:E}=this._pollingRequestInfoMap.get(s)||{};return void console.warn(`${this._name}._handleSuccess groupID:${s} key:${u} startSeq:${E} errorCode:${g}`)}this._hasJoinedAVChatRoom(s)&&this._handleResponseData(s,r)}_handleResponseData(s,r){const{Key:g,NextSeq:u,NextBroadcastSeq:E,RspMsgList:f=[],RspBroadcastMsgList:D=[]}=r;if(g&&u&&this._pollingRequestInfoMap.set(s,{longPollingKey:g,startSequence:u}),E&&E>this._startBroadcastSequence&&(this._startBroadcastSequence=E),f.length>0)this._getPollingNoMessageCount(s)!==0&&(this._updatePollingNoMessageCount(s,0),this._pollingIntervalMap.set(s,jQ())),fh.onMessageReceived(s,f);else{let v=this._getPollingNoMessageCount(s);if(v+=1,this._updatePollingNoMessageCount(s,v),v===(()=>{const N=BB("polling_no_msg_count");return yh(N)?parseInt(N,10):20})()){const N=jQ()+(()=>{const P=BB("polling_interval_plus");return yh(P)?parseInt(P,10):2e3})();this._pollingIntervalMap.set(s,N)}}D.length>0&&fh.onBroadcastMessageReceived(D)}_handleFailure(s,r){const{ssoLog:g,utils:{safeStringify:u}}=this._core;g.warn("polling",`${this._name}._handleFailure groupID:${s} error: ${u(r)}`)}_joinedAVChatRoomCount(){const{OuterConstant:s}=this._core;let r=[];return this._joinedGroupMap.size>0&&(r=this.getJoinedGroups().filter(g=>g.type===s.GRP_AVCHATROOM)),r.length}_hasJoinedAVChatRoom(s){return this._joinedGroupMap.has(s)}getJoinedGroups(){return[...this._joinedGroupMap.values()]}updateLocalLiveGroup(s,r){this._joinedGroupMap.set(s,r),this._parentPlugin.groupDataHandler.updateLocalGroup([r])}handleLiveHistoryMessages(s,r){fh.onMessageReceived(s,r,!0)}isOverFrequencyLimit(s){if(!this._membersReqInfoMap.has(s))return this._membersReqInfoMap.set(s,{startTime:Date.now(),requestCount:1}),!1;let{startTime:r,requestCount:g}=this._membersReqInfoMap.get(s);const{interval:u,count:E}=(()=>{const f=BB("av_members_freq_limit");if(yh(f)){const{interval:D,count:v}=JSON.parse(f);if(v>0&&D>0)return{interval:D,count:v}}return{interval:30,count:4}})();return Date.now()-r>1e3*u?(this._membersReqInfoMap.set(s,{startTime:Date.now(),requestCount:1}),!1):(g+=1,this._membersReqInfoMap.set(s,{startTime:r,requestCount:g}),g>E)}_stopPolling(s){if(this._core.ssoLog.debug("_stopPolling",`${this._name}._stopPolling groupID:${s}`),s){const{appStore:{conversationStore:r},OuterConstant:{CONV_GROUP:g}}=this._core;r.deleteConversation(`${g}${s}`);const u=this._pollingInstanceMap.get(s);return u?.stop(),this._parentPlugin.groupDataHandler.deleteLocalGroup(s),this._pollingInstanceMap.delete(s),this._pollingRequestInfoMap.delete(s),this._joinedGroupMap.delete(s),this._onlineMemberCountMap.delete(s),this._pollingIntervalMap.delete(s),this._pollingNoMessageCountMap.delete(s),void this._membersReqInfoMap.delete(s)}for(const r of this._pollingInstanceMap.values())r?.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear(),this._onlineMemberCountMap.clear(),this._pollingIntervalMap.clear(),this._pollingNoMessageCountMap.clear(),this._membersReqInfoMap.clear()}_updatePollingNoMessageCount(s,r){this._pollingNoMessageCountMap.set(s,r)}_getPollingNoMessageCount(s){return this._pollingNoMessageCountMap.get(s)||0}_reportLongPollingCount(){const s=this._joinedGroupMap.size;if(s>1){const{common:r,OuterConstant:g,ssoLog:u}=this._core,E=r.isUnlimitedAVChatRoom()?1:0,f=[],D=[];Array.from(this._joinedGroupMap.values()).forEach(({groupID:v,type:N})=>{N===g.GRP_LIVE?D.push(v):f.push(v)}),u.info("longPollingCount",String(s),{moreMessage:`av:${f.join(",")} live:${D.join(",")} code: ${E}`,eventType:29})}}reset(s){this._stopPolling(s),this._startBroadcastSequence=1,fh.reset()}},cR=new class{init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"joinGroup",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}joinGroup(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r}=this._core,g=yield this._parentPlugin.groupAction.joinGroup(s),{data:{status:u,group:{type:E}}}=g;return E===r.GRP_AVCHATROOM?u===r.JOIN_STATUS_ALREADY_IN_GROUP?g:Vg.handleJoinGroupResult(g.data):g})}},AN=new class{init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"quitGroup",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}quitGroup(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r}=this._core,g=yield this._parentPlugin.groupAction.quitGroup(s),{data:{type:u}}=g;return u===r.GRP_AVCHATROOM&&Vg.reset(s),g})}},lR=new class{init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"dismissGroup",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}dismissGroup(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r}=this._core,g=yield this._parentPlugin.groupAction.dismissGroup(s),{data:{type:u}}=g;return u===r.GRP_AVCHATROOM&&Vg.reset(s),g})}},qm=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}getGroupMemberList(s){return mA(this,void 0,void 0,function*(){const{appStore:{groupStore:r},helper:g,OuterConstant:u}=this._core,{groupID:E}=s,f=r.getGroup(E);if(f?.type===u.GRP_AVCHATROOM&&g.checkBusinessCapabilityBits(rR)){if(Vg.isOverFrequencyLimit(E))throw{code:2996,message:`Over frequency limit: get_members-${E}`};return this._getGroupMemberList(s)}return this._parentPlugin.groupMember.getGroupMemberList(s)})}_getGroupMemberList(s){return mA(this,void 0,void 0,function*(){const r="_getGroupMemberList",{helper:g}=this._core;try{const u=yield function(v,N){return mA(this,void 0,void 0,function*(){const{groupID:P,offset:W=0}=v,nA={GroupId:P,Timestamp:W};return N.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:nA})})}(s,this._core),{MemberList:E=[],NextTimestamp:f=0}=u||{},D=this._handleMemberList(E);return console.log(`${this._name}.${r} ok, groupID:${s.groupID} count:${D.length} nextOffset:${f}`),{code:0,data:{memberList:D,offset:f}}}catch(u){const E=new g.ChatError({functionName:r,code:u?.errorCode,message:u?.errorInfo});throw console.error(`${this._name}.${r} fail:`,E),E}})}_handleMemberList(s){return s.map(r=>{const{Member_Account:g,NickName:u="",Avatar:E="",Remark:f="",JoinTime:D=0,Marks:v=[]}=r;return{userID:g,nick:u,avatar:E,remark:f,joinTime:D,marks:v,isOnline:!0}})}},Km=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}deleteGroupMember(s){return mA(this,void 0,void 0,function*(){const r="deleteGroupMember",{appStore:{groupStore:g},utils:{isUndefined:u},helper:E,OuterConstant:f}=this._core,{groupID:D}=s,v=g.getGroup(D);if(u(v))throw new E.ChatError({functionName:r,code:FD});if(v.type===f.GRP_AVCHATROOM){if(E.checkBusinessCapabilityBits(zT))return this._deleteGroupMember(s);throw new E.ChatError({functionName:r,code:qQ})}return this._parentPlugin.groupMember.deleteGroupMember(s)})}_deleteGroupMember(s){return mA(this,void 0,void 0,function*(){const r="_deleteGroupMember",{appStore:{groupStore:g},helper:u,ssoLog:E}=this._core,{groupID:f,duration:D=0,userIDList:v}=s;if(D===0)throw new u.ChatError({functionName:r,code:ZT});try{return yield function(N,P){return mA(this,void 0,void 0,function*(){const{groupID:W,userIDList:nA,duration:EA,reason:wA}=N,kA={GroupId:W,Members_Account:nA,Duration:EA,Description:wA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:kA})})}(s,this._core),E.debug(r,`${this._name}.${r} ok, groupID:${f}`),{code:0,data:{group:g.getGroup(f),userIDList:v}}}catch(N){throw new u.ChatError({functionName:r,code:N?.errorCode,message:N?.errorInfo})}})}},Nd=new class{constructor(){this._name="MarkAVChatRoomMember"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(s){return mA(this,void 0,void 0,function*(){const r="markGroupMemberList",{groupID:g,markType:u,enableMark:E,userIDList:f=[]}=s,D=this._generateRequestData(s);try{const v=yield function(nA,EA){return mA(this,void 0,void 0,function*(){const{groupID:wA,operationType:kA,memberList:VA}=nA,LA={GroupId:wA,CommandType:kA,MemberList:VA};return EA.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:LA})})}(D,this._core),{MemberList:N=[]}=v||{},{successUserIDList:P,failureUserIDList:W}=this._handleResult(N,f);return{code:0,data:{successUserIDList:P,failureUserIDList:W},successLog:{message:`${this._name}.${r} ok, groupID:${g} markType:${u} enableMark:${E} success:${P.length} fail:${W.length}`}}}catch(v){throw new this._core.helper.ChatError({functionName:r,code:v?.errorCode,message:v?.errorInfo})}})}_generateRequestData(s){const{groupID:r,markType:g,enableMark:u,userIDList:E=[]}=s,f=u===!0?1:2,D=[...E];return D.length>500&&console.warn(`${this._name}._generateRequestData, the length of userIDList cannot exceed 500`),{groupID:r,operationType:f,memberList:D.map(v=>({Member_Account:v,Marks:[g]}))}}_handleResult(s,r){const g=[],u=[];return s.length===r.length?(g.push(...r),{successUserIDList:g,failureUserIDList:u}):(r.forEach(E=>{s.find(f=>f.Member_Account===E)?g.push(E):u.push(E)}),{successUserIDList:g,failureUserIDList:u})}},IR=new class{init(s,r){s.ssoLog.debug("AVChatRoomAction.init"),cR.init(s,r),AN.init(s,r),lR.init(s,r),qm.init(s,r),gR.init(s,r),Km.init(s,r),Nd.init(s)}},uR=new class{constructor(){this._name="LiveHandler"}init(s){this._core=s;const{helper:r,ssoLog:g}=s;r.registerExperimentalAPI("startMessageLongPolling",this),r.registerExperimentalAPI("stopMessageLongPolling",this),g.debug("LiveHandler.init")}startMessageLongPolling(s){const{common:r,utils:{isEmpty:g},OuterConstant:u,ssoLog:E}=this._core,{groupID:f,longPollingKey:D,longPollingSequence:v=1}=s;if(g(D))return E.warn("startMessageLongPolling",`${this._name}.startMessageLongPolling longPollingKey is empty.`),Promise.resolve({});Vg.hasPollingInstance(f)&&this.stopMessageLongPolling({groupID:f});const N=Vg.getJoinedLiveList(),P=r.isUnlimitedAVChatRoom();!P&&N.length>0&&this.stopMessageLongPolling({groupID:N[0].groupID}),E.debug("startMessageLongPolling",`${this._name}.startMessageLongPolling isUnlimited:${P} groupID:${f} longPollingKey:${D} longPollingSequence:${v}`);const W={groupID:f,type:u.GRP_LIVE};return Vg.updateLocalLiveGroup(f,W),this._getLiveHistoryMessages({groupID:f,longPollingKey:D,startSequence:v}),Vg.startMessageLongPolling({group:W,longPollingKey:D,startSequence:v})}stopMessageLongPolling(s){const{groupID:r}=s;return Vg.reset(r),this._core.ssoLog.debug("stopMessageLongPolling",`${this._name}.stopMessageLongPolling ok, groupID:${r}`),Promise.resolve({groupID:r})}_getLiveHistoryMessages(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r}=this._core,{groupID:g}=s;try{const u=yield function(f,D){return mA(this,void 0,void 0,function*(){const{groupID:v,longPollingKey:N,startSequence:P}=f,W={GroupId:v,LongPollingKey:N,PullPreSeq:P};return D.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_huge_group_msg",data:W})})}(s,this._core),{RspMsgList:E=[]}=u||{};r.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages ok, groupID:${g} count:${E.length}`),E.length>0&&Vg.handleLiveHistoryMessages(g,E)}catch(u){r.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages failed, groupID:${g} info:${u.message}`)}})}},jm=new class{constructor(){this.name="AVChatRoom"}install(s,r){this._core=s,hB.init(s),Vg.init(s,r),IR.init(s,r),uR.init(s);const{notificationCenter:g,InnerEvent:u}=s,{InnerEventSubType:E}=g;g.subscribeInnerEvent(u.MESSAGE_PUSH,E.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),g.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.subscribeInnerEvent(u.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(s){Vg.onAVChatRoomSystemNotification(s)}_reset(){Vg.reset()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core,{InnerEventSubType:g}=s;s.unSubscribeInnerEvent(r.MESSAGE_PUSH,g.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const og=new class{init(s){this.core=s}},Wm="message",pB="user",mB={OR:"or",AND:"and"},NI=20,eN=20,ER=20,Dh={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!s||!!(Array.isArray(s)&&s.length<=5)||"keywordList should be an array and length <= 5"},zm={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>!s||!![mB.OR,mB.AND].includes(s)||"keywordListMatchType should be OR or AND"},RC={required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s=="number"&&s>=1&&s<=100||"count must be a number between 1 and 100"},WQ={required:!1,rules:["string"],allowEmpty:!0},dR={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:r}=og.core;if(!Array.isArray(s))return"groupTypeList should be an array";const g=[r.GRP_PUBLIC,r.GRP_COMMUNITY,r.GRP_WORK,r.GRP_MEETING];let u=!1;for(let E=0;E{const{OuterConstant:r}=og.core,g=[r.MSG_TEXT,r.MSG_IMAGE,r.MSG_AUDIO,r.MSG_FILE,r.MSG_VIDEO,r.MSG_LOCATION,r.MSG_CUSTOM,r.MSG_MERGER];let u=!1;for(let E=0;E{const{OuterConstant:r}=og.core;return!(!s?.startsWith(r.CONV_C2C)&&!s?.startsWith(r.CONV_GROUP)&&s!==r.CONV_SYSTEM)||"conversationID is invalid"}},Zm=s=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:r=>typeof r=="number"&&r>=0||`${s} should be a number >= 0';`}),PD={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:r}=og.core;return!![r.GENDER_FEMALE,r.GENDER_MALE].includes(s)||"gender is invalid"}},Xm={searchCloudMessages:{keywordList:Dh,keywordListMatchType:zm,cursor:WQ,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!!(Array.isArray(s)&&s.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:CR,conversationID:hR,timePosition:Zm("timePosition"),timePeriod:Zm("timePeriod")},searchCloudUsers:{keywordList:Dh,keywordListMatchType:zm,cursor:WQ,count:RC,miniBirthday:Zm("miniBirthday"),maxBirthday:Zm("maxBirthday"),gender:PD},searchCloudGroupMembers:{keywordList:Dh,keywordListMatchType:zm,cursor:WQ,count:RC,groupTypeList:dR,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:Dh,keywordListMatchType:zm,cursor:WQ,count:RC,groupTypeList:dR}},xD={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var YD=new class{constructor(){this.name="CloudSearch"}install(s){this._core=s,og.init(s),s.helper.registerApi({apiName:"searchCloudMessages",context:this}),s.helper.registerApi({apiName:"searchCloudUsers",context:this}),s.helper.registerApi({apiName:"searchCloudGroupMembers",context:this}),s.helper.registerApi({apiName:"searchCloudGroups",context:this}),s.helper.registerValidateConfig({auth:xD,params:Xm})}searchCloudMessages(s){return mA(this,void 0,void 0,function*(){try{const{OuterConstant:r,helper:g}=this._core,{conversationID:u,timePeriod:E,timePosition:f}=s,D=vo(s,["conversationID","timePeriod","timePosition"]),v=Object.assign({count:100},D);u&&(u.startsWith(r.CONV_C2C)?v.account=u.replace(r.CONV_C2C,""):u.startsWith(r.CONV_GROUP)&&(v.groupID=u.replace(r.CONV_GROUP,""))),this._setTimeRangeParams(v,{timePeriod:E,timePosition:f});const N=yield function(LA){return mA(this,void 0,void 0,function*(){const{count:SA,keywordList:PA,keywordListMatchType:zA,senderUserIDList:Ee,messageTypeList:Ie,endTime:Li,startTime:Ui,cursor:Yt,account:Oi,groupID:Bn}=LA,Re={Count:SA,KeywordList:PA,MatchType:zA,SendUserIDList:Ee,MsgTypeList:Ie,EndTime:Li,StartTime:Ui,Cursor:Yt,PeerAccount:Oi,GroupID:Bn};return og.core.common.buildAndSendPacket({servcmd:"message_search.query",data:Re})})}(v);if(!N)return{code:0,data:{}};const{ErrorCode:P,ErrorInfo:W,TotalCount:nA,Cursor:EA="",ConversationMsgs:wA=[]}=N;if(P!==0)throw{errorCode:P,errorInfo:W};const kA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} res: totalCount:${nA}`;return{code:0,data:{searchResultList:wA.map(LA=>{const{MsgList:SA,Count:PA,GroupID:zA,UserID:Ee}=LA,Ie=zA?`${r.CONV_GROUP}${zA}`:`${r.CONV_C2C}${Ee}`;if(this._isSearchingAllConversations(s)&&PA>1)return{conversationID:Ie,messageCount:PA,messageList:[]};const Li=SA.map(Ui=>g.isEmpty(zA)?function(Yt,Oi){const Bn=Oi.OuterConstant.CONV_C2C,Re=Oi.message.messageHelper.parseServerPushMessage(Yt),Mt=Oi.message.messageFactory.createMessage(Object.assign(Object.assign({},Re),{conversationType:Bn,flow:"in"}));return Mt.setElement(Re.elements),Mt}(Ui,this._core):function(Yt,Oi){const Bn=Oi.OuterConstant.CONV_GROUP,Re=Oi.message.messageHelper.parseServerGroupMessage(Yt),Mt=Oi.message.messageFactory.createMessage(Object.assign(Object.assign({},Re),{conversationType:Bn,flow:"in"}));return Mt.setElement(Re.elements),Mt}(Ui,this._core));return{conversationID:Ie,messageCount:PA,messageList:Li}}),cursor:EA,totalCount:nA},successLog:{message:kA}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};this._handleError({errorCode:g,errorInfo:u,searchType:Wm,functionName:"searchCloudMessages"})}})}searchCloudUsers(s){return mA(this,void 0,void 0,function*(){var r;try{const{keywordListMatchType:g,count:u=eN}=s,E=vo(s,["keywordListMatchType","count"]),f=Object.assign({count:u,keywordListMatchType:g===mB.AND?1:0},E);this._setBirthdayRangeParams(f,s);const D=yield function(kA){return mA(this,void 0,void 0,function*(){const{count:VA,keywordList:LA,keywordListMatchType:SA,miniBirthday:PA,maxBirthday:zA,cursor:Ee,gender:Ie}=kA,Li={Count:VA,Keywords:LA,KeywordMatchType:SA,Cursor:Ee,UserBirthStart:PA,UserBirthEnd:zA,Gender:Ie};return og.core.common.buildAndSendPacket({servcmd:"user_search.query",data:Li})})}(f);if(!D)return{error:0,data:{}};const{ErrorCode:v,ErrorInfo:N,TotalCount:P,Cursor:W="",Users:nA=[]}=D;if(v!==0)throw{errorCode:v,errorInfo:N};const EA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${P}`,wA=[];for(let kA=0,VA=nA.length;kA({tag:Ee.Tag,value:Ee.StrValue})),zA=(r=this._core.user.userProfile)===null||r===void 0?void 0:r.createProfile(LA,PA);wA.push(zA)}return{code:0,data:{searchResultList:wA,cursor:W,totalCount:P},successLog:{message:EA}}}catch(g){const{errorCode:u,errorInfo:E}=g||{};this._handleError({errorCode:u,errorInfo:E,searchType:pB,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(s){return mA(this,void 0,void 0,function*(){try{const{count:r=ER,keywordListMatchType:g}=s,u=vo(s,["count","keywordListMatchType"]),E=Object.assign({count:r,keywordListMatchType:g===mB.AND?1:0},u),f=yield function(wA){return mA(this,void 0,void 0,function*(){const{count:kA,keywordList:VA,keywordListMatchType:LA,groupTypeList:SA,cursor:PA,groupIDList:zA}=wA,Ee={Count:kA,Keywords:VA,KeywordMatchType:LA,Cursor:PA,GroupType:SA,GroupIdList:zA};return og.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:Ee})})}(E);if(!f)return{code:0,data:{}};const{ErrorCode:D,ErrorInfo:v,GroupMembers:N=[],Cursor:P,TotalCount:W}=f;if(D!==0)throw{errorCode:D,errorInfo:v};const nA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${W}`,EA=new Map;return N.forEach(wA=>{const{GroupID:kA,GroupName:VA,GroupType:LA,GroupFaceUrl:SA,GroupMemberUserName:PA,GroupMemberUserID:zA,GroupMemberNameCard:Ee,GroupMemberAvatar:Ie=""}=wA,Li={groupID:kA,name:VA,type:LA,avatar:SA},Ui={userID:zA,nick:PA,nameCard:Ee,avatar:Ie};if(EA.has(kA)){const Yt=EA.get(kA);Yt.memberList.push(Ui),EA.set(kA,Yt)}else EA.set(kA,{groupInfo:Li,memberList:[Ui]})}),{code:0,data:{searchResultList:[...EA.values()],cursor:P,totalCount:W},successLog:{message:nA}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};this._handleError({errorCode:g,errorInfo:u,searchType:pB,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(s){return mA(this,void 0,void 0,function*(){try{const{count:r=NI,keywordListMatchType:g}=s,u=vo(s,["count","keywordListMatchType"]),E=Object.assign({count:r,keywordListMatchType:g===mB.AND?1:0},u),f=yield function(EA){return mA(this,void 0,void 0,function*(){const{count:wA,keywordList:kA,keywordListMatchType:VA,groupTypeList:LA,cursor:SA}=EA,PA={Count:wA,Keywords:kA,KeywordMatchType:VA,Cursor:SA,GroupType:LA};return og.core.common.buildAndSendPacket({servcmd:"group_search.query",data:PA})})}(E);if(!f)return{code:0,data:{}};const{ErrorCode:D,ErrorInfo:v,Groups:N,Cursor:P,TotalCount:W}=f;if(D!==0)throw{errorCode:D,errorInfo:v};const nA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${W}`;return{code:0,data:{searchResultList:N?.map(EA=>function(wA){const{GroupFaceUrl:kA,GroupID:VA,GroupIntroduction:LA,GroupMemberNum:SA,GroupName:PA,GroupOwnerTinyID:zA,GroupOwnerUserID:Ee,GroupOwnerUserName:Ie,GroupType:Li,GroupAddOption:Ui,GroupInviteOption:Yt}=wA;return{avatar:kA,groupID:VA,introduction:LA,memberCount:SA,name:PA,ownerTinyID:zA,ownerID:Ee,ownerNick:Ie,type:Li,joinOption:Ui,inviteOption:Yt}}(EA))||[],cursor:P,totalCount:W},successLog:{message:nA}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};this._handleError({errorCode:g,errorInfo:u,searchType:pB,functionName:"searchCloudGroups"})}})}_setTimeRangeParams(s,{timePeriod:r,timePosition:g}){r&&r>0&&(s.startTime=g&&g>0?g-r:this._core.helper.timeManager.getServerTimeSeconds()-r),s.startTime&&s.startTime<0&&(s.startTime=void 0),g&&g>0&&(s.endTime=g)}_handleError({errorCode:s,errorMessage:r,searchType:g}){const{helper:u}=this._core;let E=s;throw s===60020?E="SearchUnable":g!==Wm&&s===27003?E="SearchParamsError":g!==Wm&&s===60018&&(E="SearchOverLimit"),new u.ChatError({code:E,message:r})}_isSearchingAllConversations(s){return this._core.helper.isEmpty(s.conversationID)}_setBirthdayRangeParams(s,r){const{miniBirthday:g,maxBirthday:u}=r;g!==void 0&&(s.miniBirthday=g,u===void 0&&(s.maxBirthday=4294967295)),u!==void 0&&(s.maxBirthday=u)}};function Sh(s,r){return Math.round(Number(s)*Math.pow(10,r))/Math.pow(10,r)}const BR="qualityStat",VD="im-ssolog-quality-stat";var HD;(function(s){s[s.ONLINE=8]="ONLINE"})(HD||(HD={}));const $m="networkRTT",vh="messageE2EDelay",fB="sendMessageC2C",Mh="sendMessageGroup",Rh="sendMessageGroupAV",yB="sendMessageRichMedia",DB="cosUpload",wC="messageReceivedGroup",zQ="messageReceivedGroupAVPush",ZQ="messageReceivedGroupAVPull",tN={[$m]:2,[vh]:3,[fB]:4,[Mh]:5,[Rh]:6,[yB]:7,[wC]:8,[zQ]:9,[ZQ]:10,[DB]:11},QR=[fB,Mh,Rh,yB,DB],wh=[wC,zQ,ZQ],SB=[$m,vh,fB,Mh,Rh,yB,DB,wC,zQ,ZQ],JD={ERR_SVR_COMM_SENSITIVE_TEXT:80001,ERR_SVR_COMM_BODY_SIZE_LIMIT:80002,OPEN_SERVICE_OVERLOAD_ERROR:60022,ERR_SVR_MSG_PKG_PARSE_FAILED:20001,ERR_SVR_MSG_INTERNAL_AUTH_FAILED:20002,ERR_SVR_MSG_INVALID_ID:20003,ERR_SVR_MSG_PUSH_DENY:20006,ERR_SVR_MSG_IN_PEER_BLACKLIST:20007,ERR_SVR_MSG_BOTH_NOT_FRIEND:20009,ERR_SVR_MSG_NOT_PEER_FRIEND:20010,ERR_SVR_MSG_NOT_SELF_FRIEND:20011,ERR_SVR_MSG_SHUTUP_DENY:20012,ERR_SVR_GROUP_INVALID_PARAMETERS:10004,ERR_SVR_GROUP_PERMISSION_DENY:10007,ERR_SVR_GROUP_NOT_FOUND:10010,ERR_SVR_GROUP_INVALID_GROUPID:10015,ERR_SVR_GROUP_REJECT_FROM_THIRDPARTY:10016,ERR_SVR_GROUP_SHUTUP_DENY:10017,MSG_SEND_FAIL:2100,OVER_FREQUENCY_LIMIT:2996},Af="quality_stat";var XQ=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(JD))}init(s){this._core=s,Object.values(QR).forEach(r=>{this._messageStatsMap.set(r,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(s){const{name:r,message:g,error:u,startTs:E}=s,{SEND_MESSAGE_STAT:f}=this._core.constants;switch(r){case f.TOTAL_COUNT:this._handleTotalCount(g);break;case f.SUCCESS_COUNT:this._handleSuccessCount(g);break;case f.FAILED_COUNT:this._handleFailedCount(g,u);break;case f.SEND_COST:this._handleSendCost(g,E)}}getStatResult(s){const r=this._messageStatsMap.get(s);if(!r||r.totalCount===0)return null;const{totalCount:g,successCount:u,failedCountOfUserSide:E}=r,f=Sh(u/g*100,2),D=u+E,v=Sh(D/g*100,2),N=this._calcAverageValue(r,s);return this._resetStat(s),{total_count:g,success_count_business:u,percent_business:f,success_count_platform:D,percent_platform:v,average_value:N}}_handleTotalCount(s){const r=this._getSendMessageSpecifiedKey(s),g=r&&this._messageStatsMap.get(r);g&&g.totalCount++}_handleSuccessCount(s){const r=this._getSendMessageSpecifiedKey(s),g=r&&this._messageStatsMap.get(r);g&&g.successCount++}_handleFailedCount(s,r){var g;const u=(g=r?.code)!==null&&g!==void 0?g:r?.errorCode;if(this._isUserSideError(u)){const E=this._getSendMessageSpecifiedKey(s),f=E&&this._messageStatsMap.get(E);f&&f.failedCountOfUserSide++}}_handleSendCost(s,r){const g=this._getSendMessageSpecifiedKey(s),u=g&&this._messageStatsMap.get(g);u&&(u.costSum+=Date.now()-r,u.costCount++)}_isUserSideError(s){return this._userSideErrorCodes.has(s)||s>=120001&&s<=13e4||s>=10100&&s<=10200}_getSendMessageSpecifiedKey(s){const{MSG_IMAGE:r,MSG_AUDIO:g,MSG_VIDEO:u,MSG_FILE:E,CONV_C2C:f,CONV_GROUP:D,GRP_AVCHATROOM:v}=this._core.OuterConstant;if([r,g,u,E].includes(s.type))return yB;if(s.conversationType===f)return fB;if(s.conversationType===D){const{groupStore:N}=this._core.appStore,P=N.getGroup(s.to);if(!P)return;const{type:W}=P;return W===v?Rh:Mh}}_calcAverageValue(s,r){return s.costCount===0?0:Math.round(r===DB?1e3*s.fileSizeSum/s.costSum:s.costSum/s.costCount)}_resetStat(s){const r=this._messageStatsMap.get(s);r&&(r.totalCount=0,r.successCount=0,r.failedCountOfUserSide=0,r.costSum=0,r.costCount=0,r.fileSizeSum=0)}},$Q=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(s){this._core=s;const{OuterEvent:r,notificationCenter:g}=s;this._initStatsMap(),g.subscribeOuterEvent(r.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(s){const r=this._getReceivedMessageSpecifiedKey(s),{utils:{isUndefined:g},OuterConstant:{CONV_GROUP:u},ssoLog:E}=this._core;if(g(r)||!this._currentCycleStats.has(r))return void E.debug("addMessageSequence",`${BR}.addMessageSequence invalid key:${r}`);const{conversationID:f,sequence:D}=s,v=f.replace(u,""),N=this._lastCycleStats.get(r);if(N.size===0||!N.has(v))return void this._addToCurrentCycle(r,v,D);const P=N.get(v);D>P.minSeq&&D{const{sortedSequences:f,minSeq:D,maxSeq:v}=E;f.length>0&&(u+=f.length,g+=v-D+1)}),g===0?null:(this._transferCycleDataOptimized(s),{total_count:g,success_count_business:u,percent_business:Sh(u/g*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){const{notificationCenter:s,OuterEvent:{MESSAGE_RECEIVED:r}}=this._core;s.unSubscribeOuterEvent(r,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(wh).forEach(s=>{this._lastCycleStats.set(s,new Map),this._currentCycleStats.set(s,new Map)})}_onMessageReceived(s){const{data:r=[]}=s;r.forEach(g=>{this.addMessageSequence(g)})}_transferCycleDataOptimized(s){const r=this._currentCycleStats.get(s);if(!r)return;const g=new Map;r.forEach((u,E)=>{const f=u.dirty?[...u.sortedSequences].sort((D,v)=>D-v):u.sortedSequences;g.set(E,{sortedSequences:f,minSeq:u.minSeq,maxSeq:u.maxSeq,dirty:!1})}),this._lastCycleStats.set(s,g),this._currentCycleStats.set(s,new Map)}_getReceivedMessageSpecifiedKey(s){const{OuterConstant:{CONV_GROUP:r,GRP_AVCHATROOM:g}}=this._core;if(s.conversationType===r&&s?._onlineOnlyFlag!==!0){const{groupStore:u}=this._core.appStore,E=u.getGroup(s.to);if(!E)return null;const{type:f}=E;return f===g?ZQ:wC}}_insertToLastCycle(s,r){r.dirty&&(r.sortedSequences.sort((u,E)=>u-E),r.dirty=!1);const g=this._findInsertPos(r.sortedSequences,s);r.sortedSequences.splice(g,0,s),r.minSeq=Math.min(r.minSeq,s),r.maxSeq=Math.max(r.maxSeq,s)}_findInsertPos(s,r){let g=0,u=s.length-1;for(;g<=u;){const E=Math.floor((g+u)/2);if(s[E]===r)return E;s[E]0&&(this._totalDelay+=g,this._totalCount++,g<=1?this._countLessThan1s++:g<=3&&this._countLessThan3s++)}getStatResult(){if(this._totalCount===0)return null;const s={total_count:this._totalCount,success_count_business:this._countLessThan1s,success_count_platform:this._countLessThan3s,percent_business:this._calculatePercentage(this._countLessThan1s,this._totalCount),percent_platform:this._calculatePercentage(this._countLessThan3s,this._totalCount),average_value:this._calculateAverageDelay(this._totalCount)};return this.reset(),s}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){const{notificationCenter:s,OuterEvent:{MESSAGE_RECEIVED:r}}=this._core;s.unSubscribeOuterEvent(r,this._onMessageReceived,this),this.reset()}_onMessageReceived(s){const{data:r=[]}=s,{OuterConstant:{MSG_GRP_TIP:g,MSG_GRP_SYS_NOTICE:u}}=this._core,E=[g,u];r.forEach(f=>{!E.includes(f.type)&&f.clientTime>0&&this.addMessageDelay(f.clientTime)})}_calculateAverageDelay(s){return s===0?0:Sh(this._totalDelay/s,1)}_calculatePercentage(s,r){return Sh(s/r*100,2)}},pR=new class{init(s){this.core=s}},iN=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(s){this._core=s;const{helper:r,notificationCenter:g,InnerEvent:{QUALITY_STAT:u,LOGOUT:E,DESTROY:f},constants:{WORKFLOW_NAME:D,WORKFLOW_STEP:v}}=s;pR.init(s),XQ.init(s),$Q.init(s),Ap.init(s),r.registerWorkflowStep(D.SYNC_SERVER_INFO_AFTER_LOGIN,v.QUALITY_REPORT,this.handleLoginSuccess,this),g.subscribeInnerEvent(u,this._handleQualityStat,this),g.subscribeInnerEvent(E,this._reset,this),g.subscribeInnerEvent(f,this._dispose,this)}handleLoginSuccess(){const{store:s,helper:r,utils:{isUndefined:g}}=this._core,u=s.get("cloudConfig")||{},{q_rpt_interval:E}=u,f=g(E)?12e4:Number(E);r.taskScheduler.addTask({id:Af,intervalMs:f,callback:this.report,context:this})}report(){this._wholePeriod=!0;const s=[...SB.map(r=>{const g=this._buildQualityReportItem(r);return g?Object.assign(Object.assign({},g),{report_index:this._reportIndex,whole_period:this._wholePeriod}):null}).filter(Boolean),...this._pendingReports];this._pendingReports=[],this._needSkipReport()||this._uploadQualityReports(s)}_handleQualityStat(s){const{constants:{QUALITY_METRICS:r}}=this._core,{label:g,data:u}=s;g===r.MESSAGE_SEND_SUCCESS_RATE&&XQ.dispatchSendStats(u)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){const{store:s,utils:r}=this._core,g=s.get("cloudConfig")||{},u=s.get("instance")||{},{sdkAppId:E}=u,{q_rpt_sdkappid_bl:f=[]}=g;if(!r.isEmpty(f))return f.split(",").map(D=>Number(D)).includes(E)}_isTinyIDInWhitelist(){const{store:s,utils:r}=this._core,g=s.get("cloudConfig")||{},u=s.get("login")||{},E=Number(u.tinyID),{q_rpt_tinyid_wl:f=[]}=g;if(!r.isEmpty(f))return f.split(",").includes(E)}_buildQualityReportItem(s){const r=this._getStatResultByKey(s);if(r===null)return null;const g={quality_type:tN[s],timestamp:Date.now(),network_type:HD.ONLINE,extension:""};return Object.assign(Object.assign({},g),r)}_getStatResultByKey(s){switch(s){case vh:return Ap.getStatResult();case fB:case Mh:case Rh:case yB:case DB:return XQ.getStatResult(s);case wC:case zQ:case ZQ:return $Q.getStatResult(s);default:return null}}_uploadQualityReports(s){return mA(this,void 0,void 0,function*(){try{const r={header:this._core.common.getCommonHead(),quality:s};yield function(g){const{common:u,channel:E}=pR.core,f="imopenstat.tim_web_report_v2",D=u.generateSSOLogProtocolData({servcmd:f,data:g}),v=`${D.head.seq}${f}`;return E.sendPacket(D,{requestId:v})}(r),this._reportIndex++,this._wholePeriod=!1}catch(r){console.warn("doReport failed. error:",r),this._pendingReports=this._pendingReports.concat(s),this._cacheFailedLogs()}})}_cacheFailedLogs(){const s=this._pendingReports,r=`${BR}._cacheFailedLogs`;let g=[...this._failedLogsCache.get(VD)||[],...s];g.length>10&&(g=g.slice(g.length-10),console.log(`${r} logs overflow, keeping last 10 items`)),this._failedLogsCache.set(VD,g),console.log(`${r} count: ${g.length}`),this._pendingReports=[]}_reset(){const{helper:s}=this._core;s.taskScheduler.removeTask(Af)}_dispose(){const{notificationCenter:s,InnerEvent:{QUALITY_STAT:r,LOGOUT:g,DESTROY:u}}=this._core;s.unSubscribeInnerEvent(r,this._handleQualityStat,this),s.unSubscribeInnerEvent(g,this._reset,this),s.unSubscribeInnerEvent(u,this._dispose,this),this._reset(),Ap.dispose(),$Q.dispose()}};const hl=new class{init(s){this.core=s}};function mR(s){return mA(this,void 0,void 0,function*(){var r;const{message:g,user:u,appStore:E,constants:{OuterConstant:f}}=hl.core,D=E.conversationStore.getConversationMap();if(D.has(s)){const N=(r=D.get(s))===null||r===void 0?void 0:r.userProfile;if(N&&s.startsWith(f.CONV_C2C)){const{avatar:P,nick:W}=N;hl.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:P,latestNick:W,isSentByMe:!1})}}const{data:v}=(yield u.userProfile.getMyProfile())||{};if(v){const{avatar:N,nick:P}=v;g.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:N,latestNick:P,isSentByMe:!0})}})}function fR(s){return mA(this,void 0,void 0,function*(){const r=s.map(g=>g.revoker);try{const g=yield function(u){return mA(this,void 0,void 0,function*(){var E,f;const D=yield(E=hl.core.user.userProfile)===null||E===void 0?void 0:E.getUserProfile({userIDList:u});return D?.data?(f=D.data)===null||f===void 0?void 0:f.reduce((v,{userID:N,nick:P,avatar:W})=>(v[N]={nick:P||"",avatar:W||""},v),{}):null})}(r);g&&s.forEach(u=>{const{revoker:E}=u;g[E]&&(u.revokerInfo.nick=g[E].nick||"",u.revokerInfo.avatar=g[E].avatar||"",u.revokerInfo.userID=E)})}catch(g){console.debug(g)}})}const qD=1,yR=2,_h=20,ep=2500,DR=1,Th=300;function tp(s){return mA(this,void 0,void 0,function*(){var r,g;const{appStore:u,utils:{isEmpty:E},common:{getCurrentUserID:f},notificationCenter:D,OuterEvent:v,OuterConstant:{CONV_C2C:N}}=hl.core,{messageList:P,conversationID:W}=s,nA=u.conversationStore.getConversationMap();let EA=(r=nA.get(W))===null||r===void 0?void 0:r.peerReadTime;if(!EA){const kA=W.replace(N,""),VA=yield function(LA){return mA(this,void 0,void 0,function*(){const SA={To_Account:LA};return hl.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:SA})})}([kA]);if(VA){const{ReadTime:LA}=VA;EA=LA?.[0],nA.has(W)&&(nA.get(W).peerReadTime=EA)}}if(nA.has(W)){const kA=(g=nA.get(W))===null||g===void 0?void 0:g.lastMessage;E(kA)||kA.fromAccount===f()&&kA.lastTime<=EA&&!kA.isPeerRead&&(kA.isPeerRead=!0,u.conversationStore.updateConversation(W,{lastMessage:kA}))}const wA=[];P.forEach(kA=>{kA.time<=EA&&!kA.isPeerRead&&kA.flow==="out"&&(kA.isPeerRead=!0,wA.push(kA))}),wA.length>0&&D.emitOuterEvent(v.MESSAGE_READ_BY_PEER,{name:v.MESSAGE_READ_BY_PEER,data:wA})})}var SR=new class{init(s){this._core=s,s.helper.registerApi({apiName:"getMessageList",context:this}),s.helper.registerApi({apiName:"getMessageListHopping",context:this}),s.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(s){return mA(this,void 0,void 0,function*(){try{const{message:r,OuterConstant:{Direction:g,CONV_C2C:u,CONV_GROUP:E},InnerEvent:{HISTORY_MESSAGE_FETCHED:f},notificationCenter:D}=this._core,{conversationID:v,nextReqMessageID:N}=s,P=_h;if(v==="@TIM#SYSTEM")return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const W=this._getAvailableLocalMessagesCount({conversationID:v,nextReqMessageID:N});if(this._needFetchHistoryMessageList({conversationID:v,availableLocalMessagesCount:W,targetCount:P})){let nA=null;if(v.startsWith(E)?nA=yield r.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:v,sequence:Number(N),count:P,direction:g.FORWARD,shouldMarkCompleted:!0}):v.startsWith(u)&&(nA=yield r.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:v,messageID:N,count:P,direction:g.FORWARD,shouldMarkCompleted:!0})),nA){const{nextReqMessageIDFromServer:EA,hasNoMoreHistoryMessage:wA,messageList:kA}=nA,VA=r.messageDataHandler.prependLocalMessageList({messageList:kA,conversationID:v});(function(Ee){const{appStore:Ie,message:Li,OuterConstant:Ui}=hl.core,Yt=Ie.conversationStore.getConversation(Ee),Oi=Li.messageDataHandler.getLocalMessageList(Ee);if(!Yt||Oi.length===0||Ee===Ui.CONV_SYSTEM)return;const Bn=[];for(let Mt=0;MtFA.isRevoked).length;Re=Bn.length-Yt.unreadCount-Mt}else Re=Bn.length-Yt.unreadCount;for(let Mt=0;MtEe.isRevoked);yield fR(SA),D.emitInnerEvent(f,VA);const PA={nextReqMessageID:wA?"":String(EA),messageList:LA,isCompleted:wA},zA=LA.map(Ee=>Ee.sequence);return{code:0,data:PA,successLog:{message:`conversationID: ${v} nextReqMessageID: ${N} availableLocalMessagesCount: ${W} sequenceList: ${JSON.stringify(zA)}`}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:v,nextReqMessageID:N,count:P}),successLog:{message:`conversationID: ${v} nextReqMessageID: ${N} availableLocalMessagesCount: ${W}}`}}}catch(r){const{code:g,message:u}=r||{};throw new this._core.helper.ChatError({code:g,message:u,moreMessage:`options: ${this._core.utils.safeStringify(s)}`})}})}getMessageListHopping(s){return mA(this,void 0,void 0,function*(){var r,g;const{OuterConstant:{Direction:u,CONV_C2C:E,CONV_GROUP:f},utils:{safeStringify:D}}=this._core,{conversationID:v,sequence:N,time:P,direction:W=u.FORWARD}=s,{utils:{isEmpty:nA},message:EA,notificationCenter:wA,InnerEvent:{HISTORY_MESSAGE_FETCHED:kA}}=this._core;if(![u.BACKWARD,u.FORWARD].includes(W))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${D(s)}`});let{count:VA=_h}=s;VA=VA>_h?_h:VA;let LA=null;if(v.startsWith(f)){if(LA=yield EA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:v,sequence:N,count:VA,direction:W}),LA){const{nextReqMessageIDFromServer:SA,hasNoMoreHistoryMessage:PA,messageList:zA,invisibleSequenceList:Ee}=LA;if(this._core.message.messageDataHandler.storeSparseMessageList(zA),wA.emitInnerEvent(kA,zA),W===u.FORWARD){const Ie=PA&&SA<1;return{code:0,data:{messageList:zA,isCompleted:Ie,nextMessageSeq:Ie?"":SA}}}if(W===u.BACKWARD){if(nA(zA)&&nA(Ee))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const Ie=((r=zA?.[zA.length-1])===null||r===void 0?void 0:r.sequence)||0,Li=((g=Ee?.[Ee.length-1])===null||g===void 0?void 0:g.sequence)||0;return{code:0,data:{messageList:zA.filter(Ui=>Ui.sequence>=N),isCompleted:!PA,nextMessageSeq:PA?Math.max(Ie,Li)+1:""}}}return{code:0,data:LA}}}else if(v.startsWith(E)&&(LA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:v,count:VA+1,time:P,direction:W}),LA)){const{messageList:SA,lastMessageTime:PA,hasNoMoreHistoryMessage:zA}=LA;return wA.emitInnerEvent(kA,SA),zA||(W===u.FORWARD?SA.shift():SA.pop()),EA.messageDataHandler.storeSparseMessageList(SA),yield tp({messageList:SA,conversationID:v}),{code:0,data:{messageList:SA,isCompleted:zA,nextMessageTime:zA?"":PA}}}})}clearHistoryMessage(s){return mA(this,void 0,void 0,function*(){var r;const{appStore:g,common:{ChatError:u,getCurrentUserID:E},OuterConstant:{CONV_C2C:f,CONV_GROUP:D},apiMap:v,message:N}=this._core,P=g.conversationStore.getConversation(s);if(!P)throw new u({code:ep});const W={fromAccount:E()},{type:nA}=P;nA===f?(W.type=qD,W.toAccount=s.replace(f,"")):nA===D&&(W.type=yR,W.toGroupID=s.replace(D,""));try{return yield(r=v?.setMessageRead)===null||r===void 0?void 0:r.call(v,{conversationID:s}),(yield function(wA){return mA(this,void 0,void 0,function*(){const{fromAccount:kA,type:VA,toAccount:LA,toGroupID:SA}=wA,PA={From_Account:kA,Type:VA,To_Account:LA,ToGroupid:SA};return hl.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:PA})})}(W))&&(N.messageDataHandler.deleteConversationMessageList(s),N.messageHistory.completedHistoryConversations.delete(s),N.messageHistory.clearHistoryMessageListFetchAnchors(s),this._updateConversationLastMessage(s)),{code:0,data:{conversationID:s},successLog:{message:`convID:${s}`}}}catch(EA){const{errorCode:wA}=EA;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:wA,moreMessage:`convID:${s}`})}})}_updateConversationLastMessage(s){const{appStore:r}=this._core;r.conversationStore.updateConversation(s,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:s,nextReqMessageID:r}){const{OuterConstant:{CONV_C2C:g,CONV_GROUP:u}}=this._core,E=this._core.message.messageDataHandler.getLocalMessageList(s),{length:f}=E;if(!r)return f;let D=-1;return s?.startsWith(g)?D=E.findIndex(v=>v.ID===r):s?.startsWith(u)&&(D=E.findIndex(v=>r.includes("-")?v.ID===r:String(v.sequence)===r)),D===-1?0:D}_needFetchHistoryMessageList({conversationID:s,availableLocalMessagesCount:r,targetCount:g}){const{message:u}=this._core;return rr.startsWith(E)?EA.ID===g:String(EA.sequence)===g),W=nA>u?nA-u:0,N=nA):W=v>u?v-u:0,P.messageList=D.slice(W,nA),P.isCompleted=N<=u&&f.messageHistory.completedHistoryConversations.has(r),P.isCompleted?P.nextReqMessageID="":P.nextReqMessageID=this._generateNextReqMessageID({conversationID:r,targetIndex:W}),r.startsWith(E)&&(yield mR(r),yield tp({messageList:P.messageList,conversationID:r})),P})}_generateNextReqMessageID({conversationID:s,targetIndex:r}){const g=this._core.message.messageDataHandler.getLocalMessageList(s);return s.startsWith("C2C")?g[r].ID:String(g[r].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}},vB=new class{constructor(){this._lastMessageSequenceMapOnDisconnect=new Map,this._lastMessageTimeMapOnDisconnect=new Map}init(s){this._core=s;const{common:{workflowManager:r},constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:u,InnerEvent:E}}=s;r.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,u.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),r.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,u.C2C_HISTORY_MESSAGE_RECOVER,this._syncC2COfflineMessage,this),s.notificationCenter.subscribeInnerEvent(E.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncGroupOfflineMessage(s){const{conversationList:r}=s?.result||{},{OuterConstant:g,utils:{isArray:u}}=this._core;if(u(r)){const E=r.filter(f=>f.type===g.CONV_GROUP&&f.groupProfile.type!==g.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(E)}}_recoverGroupHistoryMessage(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r}=this._core,g=[],u=[];return yield Promise.all(s?.map(E=>mA(this,void 0,void 0,function*(){const{groupProfile:{groupID:f}={},lastMessage:{lastSequence:D}={}}=E,v=`${r.CONV_GROUP}${f}`;let N=this._getLocalLastMessageSequence(v);this._shouldRecoverHistory({localLastMessageSequence:N,serverLastMessageSequence:D})&&(yield this._recoverGroupHistoryForConversation({conversationID:v,localLastMessageSequence:N,serverLastMessageSequence:D,groupTipList:u})),g.push(v.replace(r.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:g,groupTipList:u}})}_recoverGroupHistoryForConversation(s){return mA(this,arguments,void 0,function*({conversationID:r,localLastMessageSequence:g,serverLastMessageSequence:u,groupTipList:E}){try{const{utils:{isArray:f,isObject:D,isEmpty:v},OuterEvent:N,OuterConstant:P,notificationCenter:W,message:nA,appStore:EA,common:{getMessagePreviewText:wA,buildLastMessage:kA}}=this._core,VA=u-g,LA=Math.min(20,VA),SA={},PA=yield nA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:r,sequence:g+LA,direction:P.Direction.FORWARD,count:LA}),{nextReqMessageIDFromServer:zA,hasNoMoreHistoryMessage:Ee,messageList:Ie,serverGroupTipList:Li}=PA;f(Li)&&E.push(...Li);const Ui=Ee&&zA<0,Yt=[];if(f(Ie)&&(Ie.forEach(Oi=>{nA.messageReceiver.groupMessageReceiver.updateMessageProfile(Oi),Oi.from===P.CONV_SYSTEM&&(Oi.isSystemMessage=!1),nA.messageDataHandler.storeConversationMessage(Oi)&&!v(Oi.payload)&&(Yt.push(Oi),Oi._isExcludedFromLastMessage||(SA.lastMessage=kA(Oi)))}),Yt.length>0&&W.emitOuterEvent(N.MESSAGE_RECEIVED,{name:N.MESSAGE_RECEIVED,data:Yt})),!Ui&&Ie.length>0){const Oi=Ie[Ie.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:r,localLastMessageSequence:Oi,serverLastMessageSequence:u,groupTipList:E})}D(SA.lastMessage)&&(SA.lastMessage.messageForShow=wA(SA.lastMessage.type,SA.lastMessage.payload),EA.conversationStore.updateConversation(r,SA))}catch(f){this._core.ssoLog.error("_recoverGroupHistoryForConversation",`Recovery failed for conversation:${r}`,{error:f})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:s}=this._core,r=s.messageDataHandler.getContinuousMessagesByConversation();for(const[g,u]of r){const E=Array.from(u.values());if(E?.length>0){const f=E[E.length-1];g.startsWith("C2C")?this._lastMessageTimeMapOnDisconnect.set(g,f.time):g.startsWith("GROUP")&&this._lastMessageSequenceMapOnDisconnect.set(g,f.sequence)}}}_getLocalLastMessageSequence(s){const{message:r}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(s))return this._lastMessageSequenceMapOnDisconnect.get(s);const g=r.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.sequence}_shouldRecoverHistory(s){const{localLastMessageSequence:r,serverLastMessageSequence:g}=s;if(typeof r!="number"||typeof g!="number")return!1;const u=g-r;return g!==0&&r>0&&u>=DR&&u{f.type===g.CONV_C2C&&E.push(f)}),this._recoverC2CHistoryMessage(E)}}_recoverC2CHistoryMessage(s){return mA(this,void 0,void 0,function*(){yield Promise.all(s?.map(r=>mA(this,void 0,void 0,function*(){const{conversationID:g,lastMessage:{lastTime:u}={}}=r,E=this._getLocalLastMessageTime(g);this._shouldRecoverC2CHistory({localLastMessageTime:E,serverLastMessageTime:u})&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:E,serverLastMessageTime:u}))})))})}_shouldRecoverC2CHistory(s){const{localLastMessageTime:r,serverLastMessageTime:g}=s,u=g-r;return r>0&&u>=1&&u<=600}_recoverHistoryForC2CConversation(s){return mA(this,void 0,void 0,function*(){var r;const{conversationID:g,localLastMessageTime:u,serverLastMessageTime:E}=s,{utils:{isArray:f,isObject:D,isEmpty:v,safeStringify:N},OuterEvent:P,OuterConstant:W,notificationCenter:nA,message:EA,appStore:wA,common:{getMessagePreviewText:kA,buildLastMessage:VA}}=this._core;try{const LA={},SA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:g,direction:W.Direction.BACKWARD,time:u,count:20});if(v(SA))return;const{hasNoMoreHistoryMessage:PA,messageList:zA}=SA,Ee=[];f(zA)&&(zA.forEach(Li=>{EA.messageDataHandler.storeConversationMessage(Li)&&!v(Li.payload)&&(Ee.push(Li),Li._isExcludedFromLastMessage||(LA.lastMessage=VA(Li)))}),Ee.length>0&&nA.emitOuterEvent(P.MESSAGE_RECEIVED,{name:P.MESSAGE_RECEIVED,data:Ee}));const Ie=(r=zA[zA.length-1])===null||r===void 0?void 0:r.time;!PA&&Ie>E&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:Ie,serverLastMessageTime:E})),D(LA.lastMessage)&&(LA.lastMessage.messageForShow=kA(LA.lastMessage.type,LA.lastMessage.payload),wA.conversationStore.updateConversation(g,LA))}catch(LA){this._core.ssoLog.error("_recoverHistoryForC2CConversation",`Recovery failed for conversation:${g} error: ${N(LA)}`)}})}_getLocalLastMessageTime(s){const{message:r}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(s))return this._lastMessageTimeMapOnDisconnect.get(s);const g=r.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},MB=new class{constructor(){this.name="HistoryMessage"}install(s){this._core=s,hl.init(s),SR.init(s),vB.init(s),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this.dispose,this),vB.dispose()}_reset(){vB.reset()}},KD=new class{init(s){this.core=s}},_C=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(s){const{helper:{registerExperimentalAPI:r}}=s;this._core=s,r("reportModalView",this),r("reportTUIFeatureUsage",this),r("reportRoomEngineEvent",this)}reportModalView(s){const{ssoLog:r,utils:{safeStringify:g,isString:u}}=this._core;try{if(!u(s))throw new Error("reportModalView data is not a string");r.createSSOLogData({method:"reportModalView",message:s,eventType:30}).end(!0)}catch(E){r.debug(`reportModalView Report failed: ${g(E)}`)}}reportTUIFeatureUsage(s){const{ssoLog:r,utils:{safeStringify:g,isEmpty:u}}=this._core,{atomicStoreID:E}=s;try{u(E)||this._reportedAtomicStoreIDs.has(E)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${s.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:E}),this._reportedAtomicStoreIDs.add(E))}catch(f){r.debug(`reportTUIFeatureUsage Report failed: ${g(f)}`)}}reportRoomEngineEvent(s){const{utils:{safeStringify:r},ssoLog:g}=this._core;try{g.debug(`reportRoomEngineEvent Report: ${r(s)}`);const{eventId:u,eventCode:E,eventResult:f,eventMessage:D,moreMessage:v,extensionMessage:N}=s;g.createSSOLogData({method:N,code:u,message:D,eventType:30,costTime:E,uiPlatform:f,moreMessage:v}).end(!0)}catch(u){g.debug(`reportRoomEngineEvent Report failed: ${r(u)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},ip=new class{constructor(){this.name="DataReport"}install(s){this._core=s;const{notificationCenter:r,InnerEvent:{LOGOUT:g,DESTROY:u}}=s;KD.init(s),_C.init(s),r.subscribeInnerEvent(g,this._reset,this),r.subscribeInnerEvent(u,this._dispose,this)}_reset(){_C.reset()}_dispose(){const{notificationCenter:s,InnerEvent:{LOGOUT:r,DESTROY:g}}=this._core;s.unSubscribeInnerEvent(r,this._reset,this),s.unSubscribeInnerEvent(g,this._dispose,this),_C.dispose()}};let ef=dr.STANDARD,RB=[];ef=dr.STANDARD,RB=[Ih,dC,CC,hC,kc,iN,MB,ip,YE,Ni,er,WT,jm,YD,tu];function wB(s,r){const{operationType:g,memberInfoList:u,operatorInfo:E}=s||{};let f={};if(tn(u)?tn(E)||(f=E):g!==bg.JOINED&&g!==bg.KICKED&&g!==bg.ADMIN_SET&&g!==bg.ADMIN_CANCELED||(f=Object.assign({},u[0])),!tn(f)){const{nick:D="",avatar:v=""}=f;r.nick=D,r.avatar=v}}const op=s=>({lastTime:s?.time||s?.lastTime||0,lastSequence:s?.sequence||s?.lastSequence||0,fromAccount:s?.from||s?.fromAccount||"",messageForShow:il(s?.type,s?.payload),payload:s?.payload||null,type:s?.type||"",isRevoked:s?.isRevoked||!1,cloudCustomData:s?.cloudCustomData||"",onlineOnlyFlag:s?._onlineOnlyFlag||!1,nick:s?.nick||"",nameCard:s?.nameCard||"",version:s?.version||0,isPeerRead:s?.isPeerRead||!1,revoker:s?.revoker||null});var np=Object.freeze({__proto__:null,ChatError:hn,WorkflowManager:Pn,buildAndSendPacket:Ig,buildLastMessage:op,get builtInPlugins(){return RB},checkBusinessCapabilityBits:us,deepMerge:Bd,getCurrentUserID:ar,getErrorMessage:dn,getMessagePreviewText:il,isC2CConv:s=>c(s)&&s.slice(0,3)===Pa.CONV_C2C,isCommunity:ea,isGroupConv:s=>c(s)&&s.slice(0,5)===Pa.CONV_GROUP,isInternational:bl,isTopic:tl,isUnlimitedAVChatRoom:function(){var s;return!!(!((s=Se.store.get("instance"))===null||s===void 0)&&s.unlimitedAVChatRoom)},liteChatInstanceMap:fa,registerInterceptor:Gc,registerValidateConfig:el,requireAuth:dd,get sdkEdition(){return ef},setGroupTipsUserInfo:wB,t:Uu,updateGroupAtInfo:(s,r)=>{const{CONV_AT_ME:g,CONV_AT_ALL:u,CONV_AT_ALL_AT_ME:E}=Po;if(function(v,N){const{CONV_AT_ME:P,CONV_AT_ALL:W,CONV_AT_ALL_AT_ME:nA}=Po,{groupID:EA,sequence:wA}=v;let kA=!1;return ea({groupID:EA})&&N.forEach(VA=>{VA.messageSequence===wA&&(VA.atTypeArray.includes(P)&&v.groupAtType.includes(W)&&(VA.atTypeArray=[nA]),VA.atTypeArray.includes(W)&&v.groupAtType.includes(P)&&(VA.atTypeArray=[nA],VA.__random=v.__random,VA.__sequence=v.__sequence),kA=!0)}),kA}(s,r))return;let f=[...s.groupAtType];f.includes(g)&&f.includes(u)&&(f=[E]);const D={from:s.from,groupID:s.groupID,topicID:s.topicID,messageSequence:s.sequence,atTypeArray:f,__random:s.__random,__sequence:s.__sequence};r.push(D)},validateAndExecute:wr,validateParameters:hI});class Iu{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return Iu._instance||(Iu._instance=new Iu),Iu._instance}static setInstance(r){Iu._instance=r}installBuiltInPlugin(r){r&&this._installPlugin(r,this._builtInPlugins)}installExternalPlugin(r){r&&this._installPlugin(r,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(r,g){let u=[];u=C(r)?r:[r];const E=u.findIndex(D=>D?.name==="AVChatRoom"),f=E>-1?u.splice(E,1):[];u.forEach(D=>{this._isPluginInstalled(D.name)||(D&&_g(D.install)?(g.add(D.name),_g(D.getInstalledSubPlugins)?(f?.forEach(v=>g.add(v?.name)),D.install(Sr.getInstance().exposeApiForPlugin(),f)):D.install(Sr.getInstance().exposeApiForPlugin()),_g(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):_g(D)?(g.add(D.name),D(Sr.getInstance().exposeApiForPlugin()),_g(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(r){return this._builtInPlugins.has(r)||this._externalPlugins.has(r)}_isLoggedIn(){var r;return((r=Se.store.get("login"))===null||r===void 0?void 0:r.isLoggedIn)===!0}}var _B=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(s){return this._conversationMap.get(s)}updateConversation(s,r,g){const{emit:u=!0,needSort:E=!1}=g||{},f=this._conversationMap.get(s);f&&!tn(r)&&(Object.keys(r).forEach(D=>{f[D]=r[D]}),u&&Se.notificationCenter.emitInnerEvent(lo.CONVERSATION_UPDATED,{needSort:E}))}deleteConversation(s){this._conversationMap.has(s)&&(this._conversationMap.delete(s),Se.notificationCenter.emitInnerEvent(lo.CONVERSATION_UPDATED))}},sp=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(s){return this._groupMap.get(s)}updateGroup(s,r){const g=this._groupMap.get(s);g&&!tn(r)&&Object.keys(r).forEach(u=>{g[u]=r[u]})}},rp=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,r,g){var u;const{operation:E,updateUnreadCount:f=!0}=g,D=vo(g,["operation","updateUnreadCount"]),v=[];for(const N of r){const P=(u=this._messagesByConversation.get(s))===null||u===void 0?void 0:u.get(N);if(!P)return!1;Object.keys(D).forEach(W=>{P[W]=D[W]}),v.push(P)}return this._emitMessageStoreOperationEvent(E,{conversationID:s,messageList:v,updateUnreadCount:f}),v}getMessagesByConversation(s){var r;return[...((r=this._messagesByConversation.get(s))===null||r===void 0?void 0:r.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(s,r){const{conversationID:g}=r;tl(g)?Se.notificationCenter.emitInnerEvent(Nu[s],r):Se.notificationCenter.emitInnerEvent(s,r)}},uc=new class{constructor(){this.userProfileMap=new Map,this.friendMap=new Map}getUserProfileMap(){return this.userProfileMap}getFriendMap(){return this.friendMap}getUserProfile(s){return this.userProfileMap.get(s)}getFriend(s){return this.friendMap.get(s)}},jD=Object.freeze({__proto__:null,conversationStore:_B,groupStore:sp,messageStore:rp,userStore:uc});class Sr{static getInstance(){return Sr._instance||(Sr._instance=new Sr),Sr._instance}static setInstance(r){Sr._instance=r}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:Se.notificationCenter.subscribeOuterEvent.bind(Se.notificationCenter),off:Se.notificationCenter.unSubscribeOuterEvent.bind(Se.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:Iu.getInstance().installExternalPlugin.bind(Iu.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(r){Se.ssoLog.debug("registerPlugin",r)}statKeyFeatureUsage(r){Se.ssoLog.debug("statTUIKeyFeatures",r)}setLogLevel(r){Se.ssoLog.debug("setLogLevel",r),Se.ssoLog.setLogLevel(r)}setApplicationID(r){Se.store.set("instance",{applicationID:r})}getApiMap(){return this._apiMap}setApiMap(r){this._apiMap=r}registerApi(r){const{common:{timeManager:g},utils:{safeStringify:u}}=Se,{apiName:E,context:f,methodName:D=E,matcher:v}=r;this._apiHandlersMap[E]||(this._apiHandlersMap[E]=[]),this._apiHandlersMap[E].push({context:f,methodName:D,matcher:v}),this._apiMap[E]&&this._apiHandlersMap[E].length!==1||(this._apiMap[E]=(...N)=>{const P=g.getServerTimeMs();let W=0;E==="login"&&(W=4),zI.includes(E)&&Se.ssoLog.debug(E,`${E} start params: ${u(N)}`),wr(D,N);const nA=this._apiHandlersMap[E];for(const EA of nA)if(!EA.matcher||EA.matcher(N))try{const wA=EA.context[EA.methodName].bind(EA.context)(...N);return this._isPromiseLike(wA)?this._handleAsyncResult(wA,E,W,P):(this._reportApiSuccessLog({result:wA,apiName:E,eventType:W,startTime:P}),wA)}catch(wA){throw Se.ssoLog.error(E,`${E} fail ${wA?.message||wA?.errorMessage})`,{error:wA,costTime:g.getServerTimeMs()-P,eventType:W,method:E}),wA}})}registerExperimentalAPI(r,g,u){const E=u||r;this._experimentalApiMap[r]=g[E].bind(g)}destroy(){return mA(this,void 0,void 0,function*(){var r,g;try{!((r=Se.store.get("login"))===null||r===void 0)&&r.isLogin&&(yield this._apiMap.logout()),Se.notificationCenter.emitInnerEvent(lo.DESTROY)}catch(u){console.debug("destroy error: ",u)}finally{Se.notificationCenter.emitOuterEvent(Rr.SDK_DESTROY,{SDKAppID:(g=Se.store.get("instance"))===null||g===void 0?void 0:g.sdkAppId}),fa.clear(),Iu.getInstance().clear(),Pn.getInstance().destroy(),Se.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:lo,InnerEventSubType:Se.notificationCenter.InnerEventSubType,OuterEvent:Rr,OuterConstant:Po,SignalingEvent:Xc,helper:Object.assign(Object.assign(Object.assign({},Se.utils),Se.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Gc,registerValidateConfig:el,checkBusinessCapabilityBits:us,registerWorkflowStep:Pn.getInstance().registerWorkflowStep.bind(Pn.getInstance()),ChatError:hn}),apiMap:this._apiMap},Se),{constants:Object.assign(Object.assign({},Ag),Se.constants),common:Object.assign(Object.assign(Object.assign({},np),Se.common),{workflowManager:Pn.getInstance()}),utils:Se.utils,appStore:jD})}callExperimentalAPI(r,g){return Se.ssoLog.debug(`callExperimentalAPI.${r} start params: ${Se.utils.safeStringify(g)}`),this._experimentalApiMap[r]?this._experimentalApiMap[r](g):(Se.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${r} not found, params: ${Se.utils.safeStringify(g)}`),Promise.reject(new hn({code:ma.INVALID_OPERATION})))}_isPromiseLike(r){return r!==null&&typeof r=="object"&&typeof r.then=="function"}_handleAsyncResult(r,g,u,E){return r.then(f=>(this._reportApiSuccessLog({result:f,apiName:g,eventType:u,startTime:E}),f)).catch(f=>{throw Se.ssoLog.error(g,`${g} fail ${f?.message||f?.errorMessage})`,{error:f,costTime:Se.common.timeManager.getServerTimeMs()-E,eventType:u,method:g,startTime:E}),f})}_reportApiSuccessLog(r){let{result:g,apiName:u,startTime:E,eventType:f}=r;const{timeManager:D}=Se.common,{successLog:{message:v,moreMessage:N}={message:"",moreMessage:""}}=g||{},P=D.getServerTimeMs();u==="login"&&(E+=D.getTimeOffsetWithServer()),zI.includes(u)&&Se.ssoLog.info(u,`${u} success ${v} ${N}`,{costTime:P-E,eventType:f,message:v,moreMessage:N,startTime:E}),g?.successLog&&delete g.successLog}}class vR{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:r,store:g}=Se;g.set("login",{isReady:!1}),Sr.getInstance().registerApi({apiName:"login",context:this}),Sr.getInstance().registerApi({apiName:"logout",context:this}),Sr.getInstance().registerApi({apiName:"getLoginUser",context:this}),Sr.getInstance().registerApi({apiName:"isReady",context:this}),Sr.getInstance().registerApi({apiName:"getServerTime",context:this}),Sr.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),r.subscribeInnerEvent(lo.RECONNECTED,this._reLogin,this),Se.notificationCenter.subscribeInnerEvent(lo.DESTROY,this._dispose,this)}login(r){return mA(this,void 0,void 0,function*(){var g;const{sdkEdition:u}=Se.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new hn({functionName:"login",code:ma.REPEAT_LOGIN});const E=yield this._performLogin(r);this._validateAfterLogin(E),this._handleLoginSuccess(E),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const f=(g=Se.channel.getSocketAdapter())===null||g===void 0?void 0:g.getId(),{appId:D,href:v}=Se.store.get("instance")||{},{instanceID:N,customStatus:P}=E||{};return{code:0,data:E,successLog:{message:u,moreMessage:`socketID:${f} instanceID:${N} customStatus:${P} href: ${v} appId: ${D}`}}}catch(E){const{errorCode:f}=E;f!==ma.REPEAT_LOGIN&&(this._latestLoginAt=0);const D=new hn({functionName:"login",code:f});throw console.error(D),D}})}_reLogin(){return mA(this,void 0,void 0,function*(){var r;try{if(!this._isLoginIn())return;const g=yield Lu(this._customLoginInfo);if(g){const{instanceID:u,customStatus:E}=g;Se.store.set("login",{statusInstanceId:u}),Pn.getInstance().executeWorkflow(jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:E,statusType:ME.USER_STATUS_ONLINE});const f=(r=Se.channel.getSocketAdapter())===null||r===void 0?void 0:r.getId();Se.ssoLog.info("reLogin",`socketId:${f} instanceId:${u}`)}}catch(g){console.warn(g)}})}logout(){return mA(this,arguments,void 0,function*(r=ca.USER_INITIATED){const{ssoLog:g}=Se;g.debug("logout",`logout start logoutReason: ${r}`);try{yield this._performLogout(r),g.info("logout","logout success"),Se.ssoLog.uploadSSOLogData()}catch(u){const{errorCode:E}=u;throw new hn({functionName:"logout",code:E})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?ar():""}isReady(){var r;return(r=Se.store.get("login"))===null||r===void 0?void 0:r.isReady}setCustomLoginInfo(r=""){this._customLoginInfo=r}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),Pn.getInstance().reset(),Se.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:r}=Se.common;return r.getServerTimeMs()}_updateAndEmitSDKReady(){Se.store.set("login",{isReady:!0}),setTimeout(()=>{Se.notificationCenter.emitOuterEvent(Rr.SDK_READY,{name:Rr.SDK_READY})},1)}_updateAndEmitSDKNotReady(){Se.store.set("login",{isReady:!1}),Se.notificationCenter.emitOuterEvent(Rr.SDK_NOT_READY,{name:Rr.SDK_NOT_READY})}_validateAfterLogin(r){const g="login";if(!r)throw new hn({functionName:g,message:"login response is empty"});const{tinyID:u,a2Key:E}=r||{};if(!u)throw new hn({functionName:g,code:ma.NO_TINYID});if(!E)throw new hn({functionName:g,code:ma.NO_A2KEY})}_createRepeatLoginResponse(){var r;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:dn({code:"RepeatLogin",replacement1:(r=Se.store.get("login"))===null||r===void 0?void 0:r.userId}),repeatLogin:!0}}}_performLogin(r){return mA(this,void 0,void 0,function*(){const{userID:g,userSig:u}=r;return Se.store.set("login",{userId:g,userSig:u}),this._latestLoginAt=Date.now(),Lu(this._customLoginInfo)})}_ensureAsyncComplete(){return mA(this,void 0,void 0,function*(){yield new Promise(r=>{setTimeout(()=>r(null),1)})})}_handleLoginSuccess(r){const{timeManager:g}=Se.common,{helloInterval:u,timeStamp:E,customStatus:f,purchaseBits:D}=r,v=1e3*E;g.calculateTimeOffsetWithServer(this._latestLoginAt,v),this._helloInterval=u||120,this._updateLoginStore(r),Se.user.userStatus.setCustomStatus(f),Pn.getInstance().executeWorkflow(jt.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:D}),Se.common.taskScheduler.addTask({id:Lg,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(r){return function(g){return mA(this,void 0,void 0,function*(){const{logoutReason:u}=g,E="im_open_status.wslogout",f=Se.common.generateProtocolData({servcmd:E,data:{wslogout_type:u,isWebUniapp:0}}),D=`${f.head.seq}${E}`;return yield Se.channel.sendPacket(f,{requestId:D})})}({logoutReason:r})}_updateLoginStore(r){const{a2Key:g,tinyID:u,instanceID:E,authKey:f}=r;Se.store.set("login",{a2Key:g,tinyID:u,statusInstanceId:E,authKey:f,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return mA(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const r="im_open_status.wshello",g=Se.common.generateProtocolData({servcmd:r,data:{isWebUniapp:0}}),u=`${g.head.seq}${r}`;return Se.channel.sendPacket(g,{requestId:u})}()}catch(r){Se.ssoLog.warn("_sendOnlinePresenceRequest",` error:${r.message}`)}})}_isLoginIn(){var r;return((r=Se.store.get("login"))===null||r===void 0?void 0:r.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){Se.common.taskScheduler.removeTask(Lg),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",Se.store.clear("login"),Se.store.set("login",{isReady:!1}),Se.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:r}=Se;r.unSubscribeInnerEvent(lo.RECONNECTED,this._reLogin,this),r.unSubscribeInnerEvent(lo.DESTROY,this._dispose,this)}}const MR={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},oN={logout:!0};class Nh{constructor(){this.loginAction=new vR,this.kickedOutHandler=new ku,this.loginAction.init(),this.kickedOutHandler.init(),el({auth:oN,params:MR})}}var Zr,eE,WE;(function(s){s.CONV_C2C="C2C",s.CONV_GROUP="GROUP",s.CONV_TOPIC="TOPIC",s.CONV_SYSTEM="@TIM#SYSTEM"})(Zr||(Zr={})),function(s){s.MSG_PRIORITY_HIGH="High",s.MSG_PRIORITY_NORMAL="Normal",s.MSG_PRIORITY_LOW="Low",s.MSG_PRIORITY_LOWEST="Lowest"}(eE||(eE={})),function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_IMAGE="TIMImageElem",s.MSG_AUDIO="TIMSoundElem",s.MSG_FILE="TIMFileElem",s.MSG_VIDEO="TIMVideoFileElem",s.MSG_GRP_TIP="TIMGroupTipElem",s.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",s.MSG_MERGER="TIMRelayElem"}(WE||(WE={}));const WD={1:eE.MSG_PRIORITY_HIGH,2:eE.MSG_PRIORITY_NORMAL,3:eE.MSG_PRIORITY_LOW,4:eE.MSG_PRIORITY_LOWEST},zD=0,RR=1;var tE;(function(s){s.IN="in",s.OUT="out"})(tE||(tE={}));const wR=2,ap={};function uu(s){if(!s)return 0;if(ap[s]===void 0){const r=new Date,g=`3${r.getHours()}`.slice(-2),u=`0${r.getMinutes()}`.slice(-2),E=`0${r.getSeconds()}`.slice(-2);ap[s]=parseInt([g,u,E,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${ap[s]}`)}else ap[s]+=1;return ap[s]}class zE{constructor(r){this.ID="",this.random=0,this.sequence=0,this.nameCard="",this.isRead=!1,this.isPeerRead=!1,this.isDeleted=!1,this.isResend=!1,this.hasRiskContent=!1,this._onlineOnlyFlag=!1,this.atUserList=[],this._groupAtInfoList=[],this.isBroadcastMessage=!1,this.priority=eE.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:g=Se.common.timeManager.getServerTimeSeconds()||0,senderTinyID:u,currentUser:E,needReadReceipt:f,isSupportExtension:D,customModerationConfigurationId:v,to:N,from:P,nick:W="",avatar:nA="",time:EA,messageControlInfo:wA,tinyID:kA,cloudCustomData:VA="",messageLifeTime:LA,messageVersion:SA=0,conversationType:PA,sequence:zA,checkResult:Ee=0,isPlaceMessage:Ie=0,messageFlagBits:Li,receiverList:Ui,isSystemMessage:Yt=!1,status:Oi=qr.SUCCESS,revokeReason:Bn="",conversationSubType:Re,clientSequence:Mt,protocol:FA="JSON",revokerInfo:ci={userID:"",nick:"",avatar:""},readReceiptInfo:xn={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:Pi,groupProfile:Vr,atUserList:ji,flow:Br,isRead:Ut=!1,priority:Ft=eE.MSG_PRIORITY_NORMAL,onlineOnlyFlag:oE=!1,nameCard:hs="",quoteInfo:Do}=r;var Bl;this.clientTime=g,this.senderTinyID=u||kA,this.needReadReceipt=f===!0||f===1,this.isSupportExtension=D===!0||D===1,this._cmConfigID=v,this.to=N,this.nick=W,this.avatar=nA,this.protocol=FA,this.random=Pi===void 0?(Bl=Bl||99999999,Math.round(Math.random()*Bl)):Pi,this.time=EA||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!wA?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!wA?.excludedFromUnreadCount,this.isModified=!!SA,this.cloudCustomData=VA,this.messageLifeTime=LA,this.from=P||null,this.sequence=zA||0,this.conversationType=PA||Zr.CONV_C2C,this.hasRiskContent=Ee>1,this.version=SA,this.isPlaceMessage=Ie,this.isRevoked=Ie===2||Li===8,this.isSystemMessage=Yt,this.readReceiptInfo=xn,this.revokeReason=Bn,this.revokerInfo=ci,this._receiverList=Ui,this.conversationSubType=Re,this.revoker=ci?.revoker||"",this.clientSequence=Mt||zA||0,this.status=Oi,this.atUserList=ji||[],this.flow=Br,this.isRead=Ut,this.priority=Ft,this._onlineOnlyFlag=oE,this.nameCard=hs,this.quoteInfo=Do,this.reInitialize(E),this._initC2CReadReceiptInfo(r),this._extractGroupInfo(Vr)}getElements(){return this._elements}isOnlineMessage(){return this.messageLifeTime===0}setElement(r){Array.isArray(r)?this._elements=r:this._elements=[r],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(r=>r.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(r){this._relayFlag=r}validateBeforeSend(){var r,g,u;return this._relayFlag?{isValid:!0}:((r=this._elements)===null||r===void 0?void 0:r.length)>0?(u=(g=this._elements[0])===null||g===void 0?void 0:g.validateBeforeSend)===null||u===void 0?void 0:u.call(g):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(r){const{readReceiptSentByPeer:g,timestamp:u=0}=r;this.conversationType===Zr.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=g===1,this.readReceiptInfo.timestamp=u)}_extractGroupInfo(r){if(!r)return;const{From_AccountNick:g,From_AccountHeadurl:u,MsgFrom_AccountExtraInfo:E,GroupType:f}=r,{NameCard:D}=E||{};typeof g=="string"&&(this.nick=g),typeof u=="string"&&(this.avatar=u),typeof D=="string"&&(this.nameCard=D),this.conversationSubType=f}reInitialize(r){r===this.from&&(this.isRead=!0),this._initSequence(r),this._concatConversationID(r),this.generateMessageID()}_concatConversationID(r){let g="";const u=this.conversationType;u!==Zr.CONV_SYSTEM?(g=u===Zr.CONV_C2C?r===this.from?this.to:this.from:this.to,this.conversationID=g?`${u}${g}`:null):this.conversationID=Zr.CONV_SYSTEM}_initSequence(r){this.clientSequence===0&&r&&(this.clientSequence=uu(r)),this.sequence===0&&this.conversationType===Zr.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Zr.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(r){this.isRead=r}}class Gd{static parseServerPushElement(r){const{MsgContent:g={}}=r,{Data:u,Ext:E,Desc:f}=g;return new Gd({data:u,description:f,extension:E})}constructor(r){this.type=WE.MSG_CUSTOM;const{data:g="",description:u="",extension:E=""}=r;this.content={data:g,description:u,extension:E}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{data:E,description:f,extension:D}=u;return{MsgType:this.type,MsgContent:{Data:E,Ext:D,Desc:f}}}validateBeforeSend(){const{isEmpty:r}=Se.utils,g=[this.content.data,this.content.description,this.content.extension].some(u=>!r(u));return{isValid:g,error:g?null:{message:"content can not be empty"}}}}class bd{static parseServerPushElement(r){const{MsgContent:g={Text:""}}=r,{Text:u}=g;return new bd({text:u})}constructor(r){this.type=Ng.MSG_TEXT,this.content={text:r.text||""}}validateBeforeSend(){var r,g;return((g=(r=this.content)===null||r===void 0?void 0:r.text)===null||g===void 0?void 0:g.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{text:E}=u;return{MsgType:this.type,MsgContent:{Text:E}}}}var tf=new class{constructor(){this._elementClassMap={[WE.MSG_CUSTOM]:Gd,[WE.MSG_TEXT]:bd}}init(){Sr.getInstance().registerApi({apiName:"createCustomMessage",context:this}),Sr.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(s,r){var g;(g=r).prototype!==void 0&&"constructor"in g.prototype&&(this._elementClassMap[s]=r)}getElementClass(s){return this._elementClassMap[s]}createMessage(s){const{from:r,flow:g=tE.OUT}=s,{userId:u}=Se.store.get("login")||{};this._isSendByCurrentInstance({from:r,flow:g,currentUser:u})?this._updateWithSenderInfo(s):this._isMultiEndpointSyncMessage({from:r,flow:g,currentUser:u})&&(s.flow=tE.OUT);const E=Object.assign(Object.assign({},s),{currentUser:u});return new zE(E)}createCustomMessage(s){const r=ar(),g=this.createMessage(Object.assign(Object.assign({},s),{from:r})),u=this._elementClassMap[WE.MSG_CUSTOM];if(!g)return null;if(u){const E=new u(s.payload);g.setElement(E)}return g}createTextMessage(s){var r;if(!s)return null;const g=typeof s.payload=="string"?s.payload:((r=s?.payload)===null||r===void 0?void 0:r.text)||"",u=new bd({text:g}),E=ar(),f=Se.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return f.setElement(u),f}_updateWithSenderInfo(s){var r,g;const{nick:u,avatar:E,conversationType:f,to:D}=s,{userId:v,tinyID:N}=Se.store.get("login")||{},P=uc.getUserProfile(v);return s.nick=u||P?.nick||"",s.avatar=E||P?.avatar||"",s.tinyID=s.tinyID||N||"",s.from=v,s.status=qr.UNSENT,s.flow=tE.OUT,f===Pa.CONV_GROUP&&(s.nameCard=(g=(r=sp.getGroup(D))===null||r===void 0?void 0:r.selfInfo)===null||g===void 0?void 0:g.nameCard),s}_isMultiEndpointSyncMessage(s){const{from:r,flow:g,currentUser:u}=s;return r===u&&g===tE.IN}_isSendByCurrentInstance(s){const{from:r,flow:g,currentUser:u}=s;return r===u&&g===tE.OUT}};const _R={PushFlag:0,Title:"",Desc:"",Ext:"",ApnsInfo:{Sound:"",BadgeMode:0,IsVoipPush:void 0,Image:"",InterruptionLevel:"active",ContentAvailable:0},AndroidInfo:{Sound:"",XiaoMiChannelID:"",OPPOChannelID:"",GoogleChannelID:"",VIVOClassification:1,VIVOCategory:"",HuaWeiCategory:"",OPPOCategory:"",HuaWeiImage:"",HonorImage:"",GoogleImage:"",HonorImportance:"",MeizuNotifyType:void 0}},kd={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},ZD={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function TR(s,r){return Object.keys(r).forEach(g=>{const{range:u,defaultValue:E}=r[g];s[g]=u.includes(s[g])?s[g]:E}),s}function gp(s){const r=s.lastIndexOf(".");return r===-1?s:s.slice(0,r)}function NR(s){const{androidInfo:r={},androidOPPOChannelID:g=""}=s,u=r.OPPOChannelID||g,E=TR(r,kd),{sound:f="",FCMChannelID:D=""}=E,v=vo(E,["sound","FCMChannelID"]);return Object.assign(Object.assign({},v),{Sound:gp(f),OPPOChannelID:u,GoogleChannelID:D})}function GR(s){const{apnsInfo:r={},ignoreIOSBadge:g=!1,disableVoipPush:u}=s,E=TR(r,ZD),{ignoreIOSBadge:f,disableVoipPush:D,enableIOSBackgroundNotification:v}=E,N=vo(E,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),P=f===!0||g===!0?1:0;let W;return n(u)||(W=u===!1?1:0),n(D)||(W=D===!1?1:0),Object.assign(Object.assign({},N),{BadgeMode:P,IsVoipPush:W,ContentAvailable:v?1:0})}function XD(s){return Se.utils.isPlainObject(s)?{PushFlag:s.disablePush===!0?1:0,Title:s.title||"",Desc:s.description||"",Ext:s.extension||"",ApnsInfo:GR(s),AndroidInfo:NR(s)}:_R}function of(s){const{From_AccountHeadurl:r,From_AccountNick:g,IsNeedReadReceipt:u,IsPeerRead:E,IsSyncMsg:f,MsgBody:D,MsgClientTime:v,MsgLifeTime:N,MsgRandom:P,MsgSeq:W,MsgTimeStamp:nA,SendMsgControl:EA,SupportMessageExtension:wA,TinyId:kA,MsgCheckResult:VA,CloudCustomData:LA,MsgVersion:SA,MsgFlagBits:PA,RevokerInfo:zA,InnerSdkCustomData:Ee}=s;let Ie,{From_Account:Li,To_Account:Ui}=s;if(f===1){const Yt=Ui;Ui=Li,Li=Yt}if(zA){const{Reason:Yt,Revoker_Account:Oi,Revoker_FromUin:Bn}=zA;Ie={reason:Yt,revoker:Oi,revokerFromUin:Bn,userID:Oi}}return{from:Li,avatar:r,nick:g,needReadReceipt:u===1,isSyncMessage:f,clientTime:v,messageLifeTime:N,random:P,sequence:W,time:nA,messageControlInfo:{excludedFromLastMessage:EA?.NoLastMsg===1,excludedFromUnreadCount:EA?.NoUnread===1},isSupportExtension:wA,to:Ui,tinyID:kA,checkResult:VA,cloudCustomData:LA,revokerInfo:Ie,messageVersion:SA,messageFlagBits:PA,readReceiptSentByPeer:E,elements:TC(D),onlineOnlyFlag:N===0,quoteInfo:cp(Ee)}}function nf(s){const{From_Account:r,MsgBody:g,MsgClientTime:u,MsgRandom:E,MsgSeq:f,MsgTimeStamp:D,To_Account:v,MsgVersion:N,CloudCustomData:P,MsgCheckResult:W}=s;return{from:r,clientTime:u,random:E,sequence:f,time:D,to:v,elements:TC(g),messageVersion:N,cloudCustomData:P,checkResult:W}}function $D(s){const{ClientSeq:r,From_Account:g,GroupInfo:u,MsgBody:E,MsgClientTime:f,MsgRandom:D,MsgSeq:v,MsgTimeStamp:N,SendMsgControl:P,SupportMessageExtension:W,TinyId:nA,CloudCustomData:EA,MsgVersion:wA,MsgCheckResult:kA,NeedReadReceipt:VA,IsPlaceMsg:LA,RevokerInfo:SA,GroupAtInfo:PA,OnlineOnlyFlag:zA,InnerSdkCustomData:Ee}=s;let Ie,Li=eE.MSG_PRIORITY_NORMAL;if(Object.keys(WD).includes(String(s.MsgPriority))&&(Li=WD[s.MsgPriority]),SA){const{Reason:Yt,Revoker_Account:Oi,Revoker_FromUin:Bn}=SA;Ie={reason:Yt,revoker:Oi,revokerFromUin:Bn,userID:Oi}}const Ui=function(Yt){const Oi=[];return Array.isArray(Yt)&&Yt.forEach(Bn=>{Bn.GroupAtAllFlag===zD?Oi.push(Bn.GroupAt_Account):Bn.GroupAtAllFlag===RR&&Oi.push(Po.MSG_AT_ALL)}),Oi}(PA);return{clientSequence:r,from:g,groupProfile:u,clientTime:f,priority:Li,random:D,sequence:v,time:N,messageControlInfo:{excludedFromLastMessage:P?.NoLastMsg===1,excludedFromUnreadCount:P?.NoUnread===1},isSupportExtension:W,tinyID:nA,cloudCustomData:EA,messageVersion:wA,checkResult:kA,needReadReceipt:VA,isPlaceMessage:LA,revokerInfo:Ie,atUserList:Ui,elements:TC(E),to:nN(s),onlineOnlyFlag:zA===1,quoteInfo:cp(Ee)}}function nN(s){const{utils:{isEmpty:r},constants:{IS_TOPIC_MESSAGE:g}}=Se,{ToGroupId:u,GroupInfo:{MillionGroupFlag:E=0,TopicId:f}={}}=s;return E!==g||r(f)?u:f}function TC(s){if(!s)return null;if(Array.isArray(s))return s.map(g=>{const u=Se.message.messageFactory.getElementClass(g.MsgType);return u?.parseServerPushElement(g)});const r=Se.message.messageFactory.getElementClass(s.MsgType);return r?.parseServerPushElement(s)}function AS(s){const{From_Account:r,MsgBody:g,MsgClientTime:u,MsgRandom:E,MsgSeq:f,MsgTimeStamp:D,GroupId:v,TopicId:N,MsgVersion:P,CloudCustomData:W,MsgCheckResult:nA}=s;return{from:r,clientTime:u,random:E,sequence:f,time:D,groupID:v,topicID:N,elements:TC(g),messageVersion:P,cloudCustomData:W,checkResult:nA}}function cp(s){const{utils:{isString:r,safeStringify:g},ssoLog:u}=Se;if(!r(s))return null;try{const{messageID:E,messageTime:f,messageSequence:D}=JSON.parse(s).businessQuote;return{msgID:E,messageTime:f,messageSequence:D}}catch(E){return u.debug("_parseServerQuoteInfo",g(E)),null}}function lp({conversationUpdateFields:s,message:r}){const{conversationID:g,conversationType:u,conversationSubType:E,flow:f,_isExcludedFromUnreadCount:D,_isExcludedFromLastMessage:v}=r,N=v?"":op(r),P=!D&&f===tE.IN;s.has(g)?(s.get(g).lastMessage=N,P&&s.get(g).unreadCount++):s.set(g,{conversationID:g,type:u,subType:E,unreadCount:P?1:0,lastMessage:N})}function TB(s){return s.filter(r=>{const g=!tn(r?._elements),u=r?.isPlaceMessage===1;return g||Se.ssoLog.error("emptyMessageBody",`from:${r.from} to:${r.to} sequence:${r.sequence}`),g&&!u})}function NB(s){const{messageDataHandler:r}=Se.message;return!r.isInMessageList(s)&&!r.isMessageSentByCurrentInstance(s)}var bR=Object.freeze({__proto__:null,autoIncrementIndex:uu,createAndroidPushInfo:NR,createApnsPushInfo:GR,createOfflinePushInfo:XD,filterValidMessages:TB,getAndroidSoundName:gp,parseServerGroupMessage:$D,parseServerPushC2CModifyMessage:nf,parseServerPushGroupModifyMessage:AS,parseServerPushMessage:of,parseServerPushMessageElement:TC,shouldStoreMessage:NB,updateConversationFields:lp});const{isPlainObject:kR}=Se.utils;function Ip(s,r={}){const{onlineUserOnly:g,messageControlInfo:u}=r;let{offlinePushInfo:E}=r;s.conversationType===Zr.CONV_C2C&&g===!0&&(E?E.disablePush=!0:E={disablePush:!0});let f="";typeof s.cloudCustomData=="string"&&s.cloudCustomData.length>0&&(f=s.cloudCustomData);const D=[];if(u&&kR(u)){const{excludedFromUnreadCount:v,excludedFromLastMessage:N,excludedFromContentModeration:P}=u;v===!0&&D.push("NoUnread"),N===!0&&D.push("NoLastMsg"),P===!0&&D.push("NoMsgCheck")}return{onlineUserOnly:g,cloudCustomData:f,messageControlInfo:D,offlinePushInfo:E}}function eS(s){const{webhookInfo:{disableCloudMessagePreHook:r=!1,disableCloudMessagePostHook:g=!1}={}}=s||{};if(!r&&!g)return;const u=[];return r&&u.push("ForbidBeforeSendMsgCallback"),g&&u.push("ForbidAfterSendMsgCallback"),u}function Gh(s,r){return mA(this,void 0,void 0,function*(){const g=s.conversationType===Zr.CONV_GROUP?function(E,f){var D;const v=Ip(E,f),{onlineUserOnly:N,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:nA}=v,EA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));let wA;return C(E._receiverList)&&E._receiverList.length>0&&(wA=E._receiverList,E._receiverList.length>50&&(wA=E._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:(D=Se.store.get("login"))===null||D===void 0?void 0:D.userId,GroupId:E.to,MsgBody:EA,CloudCustomData:P,Random:E.random,MsgPriority:E.priority,ClientSeq:E.clientSequence,GroupAtInfo:E._groupAtInfoList,OnlineOnlyFlag:N?1:0,MsgClientTime:E.clientTime,OfflinePushInfo:XD(nA),SendMsgControl:N?void 0:W,NeedReadReceipt:E.needReadReceipt===!0?1:0,To_Account:wA,SupportMessageExtension:E.isSupportExtension===!0?1:0,IsRelayMsg:E._relayFlag===!0?1:0,CustomModerationConfigID:E._cmConfigID,ForbidCallbackControl:eS(f),InnerSdkCustomData:bB(E)}}}(s,r):function(E,f){var D;const v=Ip(E,f),{onlineUserOnly:N,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:nA}=v,EA=N===!0?0:void 0,wA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:(D=Se.store.get("login"))===null||D===void 0?void 0:D.userId,To_Account:E.to,MsgBody:wA,CloudCustomData:P,MsgSeq:E.sequence,MsgRandom:E.random,MsgLifeTime:EA,From_AccountNick:E.nick,From_AccountHeadurl:E.avatar,SendMsgControl:EA!==0?W:void 0,MsgClientTime:E.clientTime,IsNeedReadReceipt:E.needReadReceipt===!0?1:0,SupportMessageExtension:E.isSupportExtension===!0?1:0,IsRelayMsg:E._relayFlag===!0?1:0,CustomModerationConfigID:E._cmConfigID,OfflinePushInfo:XD(nA),ForbidCallbackControl:eS(f),InnerSdkCustomData:bB(E)}}}(s,r),u=yield Ig(g);return u?{time:u.MsgTime,messageDropReason:u.MsgDropReason,sequence:u.MsgSeq}:null})}function bh(s){return mA(this,void 0,void 0,function*(){const{from:r,to:g,version:u=0,sequence:E,random:f,time:D,type:v,cloudCustomData:N}=s,P={From_Account:r,To_Account:g,MsgVersion:u,MsgSeq:E,MsgRandom:f,MsgTime:D,MsgType:v,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:N},W=yield Ig({servcmd:"openim.modify_c2c_msg",data:P});if(W){const{MsgBody:nA,MsgVersion:EA,CloudCustomData:wA}=W;return{elements:TC(nA),messageVersion:EA,cloudCustomData:wA}}})}function GB(s){return mA(this,void 0,void 0,function*(){const{to:r,version:g=0,sequence:u,cloudCustomData:E}=s,f={GroupId:r,MsgVersion:g,MsgSeq:u,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:E},D=yield Ig({servcmd:"openim.modify_group_msg",data:f});if(D){const{MsgBody:v,MsgVersion:N,CloudCustomData:P}=D;return{elements:TC(v),messageVersion:N,cloudCustomData:P}}})}function kh(s){return mA(this,void 0,void 0,function*(){const{groupID:r,count:g,messageSequence:u,messageSequenceList:E,getType:f}=s,D={GroupId:r,ReqMsgNumber:g,WithRecalledMsg:1,Version:1,GetType:f};return u&&(D.ReqMsgSeq=u),C(E)&&E.length>0&&(D.ReqMsgSeqList=E),yield Ig({servcmd:"group_open_http_svc.group_msg_get",data:D})})}function sf(s){return mA(this,void 0,void 0,function*(){const{peerAccount:r,count:g,lastMessageTime:u,messageKey:E,direction:f}=s;return Ig({servcmd:"openim.getroammsg",data:{Peer_Account:r,MaxCnt:g,WithRecalledMsg:1,LastMsgTime:u,MsgKey:E,GetDirection:f}})})}function bB(s){if(Se.utils.isObject(s.quoteInfo)){const{msgID:r,messageSequence:g,messageTime:u}=s.quoteInfo;return JSON.stringify({businessQuote:{messageID:r,messageSequence:g,messageTime:u}})}}var tS=Object.freeze({__proto__:null,createMessagePackOptions:Ip,generateForbidCallbackControl:eS,getC2CRoamingMessagesByAnchor:sf,getGroupRoamingMessagesByAnchor:kh,getRoamingMessages:function(s){return mA(this,void 0,void 0,function*(){const{peerAccount:r,count:g,lastMessageTime:u,messageKey:E}=s;return(yield Ig({servcmd:"openim.getroammsg",data:{Peer_Account:r,MaxCnt:g||15,LastMsgTime:u||0,MsgKey:E,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:bh,modifyGroupMessage:GB,sendMessage:Gh});const{isPlainObject:sN}=Se.utils,{MSG_AUDIO:iS,MSG_FILE:oS,MSG_IMAGE:LR,MSG_VIDEO:UR,MSG_MERGER:FR}=Po;class rf{constructor(){this._sendProtocolMap=new Map}init(){Sr.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:r=>![iS,oS,LR,UR,FR].includes(r[0].type)})}registerSendProtocol(r,g,u){this._sendProtocolMap.set(r,g.bind(u))}sendMessage(r,g){return mA(this,void 0,void 0,function*(){const{TOTAL_COUNT:u,SEND_COST:E,SUCCESS_COUNT:f,FAILED_COUNT:D}=Cr;if(!(r instanceof zE))throw new hn({code:ma.MSG_INSTANCE_REQUIRED});const v=r.validateBeforeSend();if(!v.isValid){const{code:W,message:nA=""}=v.error||{};throw new hn({code:W,message:nA})}this._reportMessageSendQuality({name:u,message:r});let N=!1;const{messageDataHandler:P}=Se.message||{};try{const{messageControlInfo:W}=g||{};let nA=null;P.addRandomOfSentMessage(r.random);const EA=Date.now(),wA=this._getSendProtocol(r);if(r.conversationType===Zr.CONV_C2C?(N=g?.onlineUserOnly===!0,nA=yield wA(r,g)):r.conversationType===Zr.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(r),nA=yield wA(r,g)),nA){const{messageDropReason:kA,sequence:VA,time:LA}=nA;if(this._updateNickAndAvatarOfSentMessageByMe(r),kA&&this._logRateLimitInfo(r,VA,kA),this._reportMessageSendQuality({name:f,message:r}),this._reportMessageSendQuality({name:E,message:r,startTs:EA}),r.isResend===!0){const SA=P.findMessage(r.ID);SA&&(Se.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${SA.ID}`),P.deleteConversationMessage(SA))}return r.status=qr.SUCCESS,r.time=LA,r.conversationType===Zr.CONV_GROUP&&(r.sequence=VA),N?r._onlineOnlyFlag=!0:(P.storeConversationMessage(r),this._applySentMessageControlInfo(r,W),this._emitOnlineMessageSent(r)),r.type===Ng.MSG_STREAM?{code:0,data:{message:r,streamMessageID:nA.streamMessageID}}:{code:0,data:{message:r}}}}catch(W){r.status=qr.FAIL,P.removeRandomOfSentMessage(r.random);let{errorCode:nA}=W||{},EA=W?.errorInfo||W?.message||"";throw this._hasRiskContent(nA)&&(r.hasRiskContent=!0),N||this._isRejectedByRestApi(nA)||P.storeConversationMessage(r),this._reportMessageSendQuality({name:D,message:r,error:W}),new hn({code:nA,message:EA,data:{message:r},moreMessage:`type:${r.type} from:${r.from} to:${r.to}`})}})}_hasRiskContent(r){return r===80001||r===80004}_isRejectedByRestApi(r){return r>=10100&&r<=10200||r>=120001&&r<=13e4}_emitOnlineMessageSent(r){const g=r._isExcludedFromLastMessage?"":r,{conversationID:u,conversationType:E}=r,f=tl(u)?lo.TOPIC_NEW_MESSAGE:lo.NEW_MESSAGE;Se.notificationCenter.emitInnerEvent(f,{result:{conversationUpdateFieldList:[{conversationID:u,type:E,message:r,lastMessage:g,unreadCount:0}]}})}_applySentMessageControlInfo(r,g){g&&sN(g)&&(g.excludedFromLastMessage===!0&&(r._isExcludedFromLastMessage=!0),g.excludedFromUnreadCount===!0&&(r._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(r,g,u){const E=`from:${r.from} to:${r.to} sequence:${g} messageDropReason:${u}`;Se.ssoLog.warn("messageDropReason",E)}_updateNickAndAvatarOfSentMessageByMe(r){const{messageDataHandler:g}=Se.message||{};let u=!1;const{conversationID:E}=r,f=g.getLatestMsgSentByMe(E);if(f){const{nick:D,avatar:v}=f;D===r.nick&&v===r.avatar||(u=!0),u&&g.updateNickAndAvatarOfSentMessage({conversationID:E,latestNick:r.nick,latestAvatar:r.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(r){return mA(this,void 0,void 0,function*(){var g,u,E;const{to:f,from:D}=r;let v=f,N=sp.getGroup(v);if(ea({groupID:v})&&N?.isSupportTopic)throw new hn({code:ma.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(tl(f)&&([v]=f.split(ga.TOPIC),N=sp.getGroup(v)),!N&&typeof((g=Sr.getInstance().getApiMap())===null||g===void 0?void 0:g.getGroupProfile)=="function"){const P=yield Sr.getInstance().getApiMap().getGroupProfile({groupID:v});if(((E=(u=P?.data)===null||u===void 0?void 0:u.group)===null||E===void 0?void 0:E.type)===Po.GRP_AVCHATROOM){const W=dn({code:ma.MSG_SEND_FAIL_NOT_IN_AV,replacement1:D,replacement2:v});throw new hn({code:ma.MSG_SEND_FAIL_NOT_IN_AV,message:W})}}return!0})}_reportMessageSendQuality(r){Se.notificationCenter.emitInnerEvent(lo.QUALITY_STAT,{label:dI.MESSAGE_SEND_SUCCESS_RATE,data:r})}_getSendProtocol(r){return this._sendProtocolMap.get(r.type)||Gh}}var rN=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){Se.notificationCenter.subscribeInnerEvent(lo.LOGOUT,this._reset,this),Se.notificationCenter.subscribeInnerEvent(lo.DESTROY,this._dispose,this)}get _messagesByConversation(){return rp.getMessages()}storeConversationMessage(s,r=!1){if(jn)return!0;const{conversationID:g}=s;if(!g||(this._messagesByConversation.has(g)||this._messagesByConversation.set(g,new Map),this._shouldSkipStoreMessage(s,r)))return!1;const u=this._getUniqueIdOfMessage(s);return this._messagesByConversation.get(g).set(u,s),this._updateLatestMessageMap(s),!0}_updateLatestMessageMap(s){const{conversationID:r}=s;s.flow==="out"?this._setLatestMsgSentByMe(r,s):r.startsWith("C2C")&&this._setLatestMsgSentByPeer(r,s)}_shouldSkipStoreMessage(s,r){const g=this._getUniqueIdOfMessage(s),u=this._messagesByConversation.get(s.conversationID);if(u?.has(g)){const E=u?.get(g);if(!r||E?.isModified===!0)return!0}return!1}deleteConversationMessage(s){var r;const{conversationID:g=""}=s,u=this._getUniqueIdOfMessage(s);this._messagesByConversation.has(g)&&((r=this._messagesByConversation.get(g))===null||r===void 0||r.delete(u))}modifyConversationMessage(s,r){var g;if(!this._messagesByConversation.has(s)&&!this._sparseMessagesByConversation.has(s))return{isUpdated:!1,message:null};const u=this._getUniqueIdOfMessage(r),E=this._getMessageFromLocalMessage(s,u);if(E){const{messageVersion:f,elements:D,cloudCustomData:v,checkResult:N=0}=r,P=N>1;if(Se.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${E.version} remoteVersion:${f}`),E.versionE.ID===s)||null,r)break;if(!r){const u=Array.from(this._sparseMessagesByConversation.values());for(const E of u)if(r=E.get(s)||null,r)break}return r}deleteConversationMessageList(s){this._messagesByConversation.has(s)&&(this._messagesByConversation.delete(s),this._latestMessageSentByMeMap.delete(s),this._latestMessageSentByPeerMap.delete(s)),this._sparseMessagesByConversation.has(s)&&this._sparseMessagesByConversation.delete(s)}revokeMessage({conversationID:s,sequence:r,random:g,revoker:u}){const E=this._messagesByConversation.get(s);let f=null;if(E){const D=Array.from(E.values());if(f=this._findMessageBySequenceAndRandom({messageList:D,random:g,sequence:r}),f){const v=this._getUniqueIdOfMessage(f);return rp.updateMessage(s,[v],{isRevoked:!0,revoker:u,operation:_c.revoke}),f}}if(this._sparseMessagesByConversation.has(s)){const D=Array.from(this._sparseMessagesByConversation.get(s).values());if(f=this._findMessageBySequenceAndRandom({messageList:D,random:g,sequence:r}),f)return f.isRevoked=!0,f.revoker=u,f}}_findMessageBySequenceAndRandom({messageList:s,sequence:r,random:g}){for(let u=0;u0){const D=new Map([...E,...f.entries()]);this._messagesByConversation.set(g,D),this._updateLatestMessageSentByMe(g),this._updateLatestMessageSentByPeer(g)}return u}storeSparseMessageList(s){if(s.length===0)return;const{conversationID:r}=s[0],g=s.length;this._sparseMessagesByConversation.has(r)||this._sparseMessagesByConversation.set(r,new Map);const u=this._sparseMessagesByConversation.get(r);for(let E=0;E=0;u--)if(g[u].flow==="out"){this._setLatestMsgSentByMe(s,g[u]);break}}}_updateLatestMessageSentByPeer(s){var r;const g=Array.from(((r=this._messagesByConversation.get(s))===null||r===void 0?void 0:r.values())||[]);if(g.length!==0&&s.startsWith("C2C")){for(let u=g.length-1;u>=0;u--)if(g[u].flow==="in"){this._setLatestMsgSentByPeer(s,g[u]);break}}}_getUniqueIdOfMessage(s){const{from:r,to:g,random:u,sequence:E,time:f}=s;return`${r}-${g}-${u}-${E}-${f}`}_setLatestMsgSentByPeer(s,r){this._latestMessageSentByPeerMap.set(s,r)}_setLatestMsgSentByMe(s,r){this._latestMessageSentByMeMap.set(s,r)}getLatestMsgSentByPeer(s){return this._latestMessageSentByPeerMap.get(s)}getLatestMsgSentByMe(s){return this._latestMessageSentByMeMap.get(s)}addRandomOfSentMessage(s){this._randomOfSentMessageList.add(s)}removeRandomOfSentMessage(s){this._randomOfSentMessageList.delete(s)}updateNickAndAvatarOfSentMessage(s){const{conversationID:r="",latestAvatar:g,latestNick:u,isSentByMe:E=!0}=s,f=this._messagesByConversation.get(r);if(!f)return;const D=Array.from(f.values()),v=E?"out":"in";D.forEach(N=>{const{nick:P,avatar:W,flow:nA}=N;nA===v&&(P!==u&&(N.nick=u),W!==g&&(N.avatar=g))})}isInMessageList(s){var r;const{conversationID:g}=s;if(!g||!this._messagesByConversation.has(g))return!1;const u=this._getUniqueIdOfMessage(s);return(r=this._messagesByConversation.get(g))===null||r===void 0?void 0:r.has(u)}isMessageSentByCurrentInstance(s){const{random:r}=s;return this._randomOfSentMessageList.has(r)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(s){const r=this._messagesByConversation.get(s);return r?[...r.values()]:[]}getSparseMessageList(s){const r=this._sparseMessagesByConversation.get(s);return r?[...r.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),Se.notificationCenter.unSubscribeInnerEvent(lo.LOGOUT,this._reset,this),Se.notificationCenter.unSubscribeInnerEvent(lo.DESTROY,this._dispose,this)}};function af(s,r){const g=_B.getConversation(s);if(g?.lastMessage){const{lastMessage:u}=g,{lastTime:E,lastSequence:f,version:D}=u,{time:v,sequence:N,messageVersion:P,elements:W,cloudCustomData:nA}=r;E===v&&f===N&&D!==P&&(u.type=W[0].type,u.payload=W[0].content,u.messageForShow=il(u.type,u.payload),u.cloudCustomData=nA,u.version=P,_B.updateConversation(s,{lastMessage:u}))}}class OR{init(){Sr.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,payload:u,sequence:E,conversationType:f,random:D,time:v,from:N,type:P}=r;if(this._canModifyMessageElement(P)){const W=r?._elements||[];W.length>=1&&(W[0].type=P,W[0].content=u)}try{let W=null,nA=null;if(f===Zr.CONV_C2C?W=yield bh(r):f===Zr.CONV_GROUP&&(W=yield GB(r)),W){let EA=`${f}${g}`;return g===ar()&&f===Zr.CONV_C2C&&(EA=`${f}${N}`),nA={conversationType:f,from:N,to:g,time:v,random:D,sequence:E,elements:W?.elements,cloudCustomData:W?.cloudCustomData,messageVersion:W?.messageVersion,conversationID:EA},this._handleModifyMessageSuccess(nA),{code:0,data:{message:r},successLog:{message:`to:${g}`}}}}catch(W){const{errorCode:nA}=W||{};throw new hn({functionName:"modifyMessage",code:nA,moreMessage:`to:${g}`})}})}_handleModifyMessageSuccess(r){const{conversationID:g}=r,{isUpdated:u,message:E}=Se.message.messageDataHandler.modifyConversationMessage(g,r);u===!0&&Se.notificationCenter.emitOuterEvent(Rr.MESSAGE_MODIFIED,{name:Rr.MESSAGE_MODIFIED,data:[E]}),Se.notificationCenter.emitInnerEvent(lo.MESSAGE_MODIFIED,{conversationID:g,message:E}),af(g,r)}_canModifyMessageElement(r){return[WE.MSG_TEXT,WE.MSG_CUSTOM,WE.MSG_LOCATION,WE.MSG_FACE].includes(r)}}class Lh{init(){const{notificationCenter:r}=Se,{InnerEventSubType:g}=r;Pn.getInstance().registerWorkflowStep(jt.RECEIVE_C2C_NEW_MESSAGE,Xt.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),Pn.getInstance().registerWorkflowStep(jt.RECEIVE_C2C_NEW_MESSAGE,Xt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),Pn.getInstance().registerWorkflowStep(jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Xt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),r.subscribeInnerEvent(lo.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),r.subscribeInnerEvent(lo.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),r.subscribeInnerEvent(lo.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(r){Pn.getInstance().executeWorkflow(jt.RECEIVE_C2C_NEW_MESSAGE,r)}_handleC2CMessagePush(r){const g=r.data||{},{messageDataHandler:u}=Se.message||{},E=[],f=new Map;return g.C2cMsgArray.forEach(D=>{const v=this._generateC2CMessage(D);this._updateMessageProfile(v);let N=v.isModified===1;u.isMessageSentByCurrentInstance(v)?v.isModified=N:N=!1,v._onlineOnlyFlag?u.isMessageSentByCurrentInstance(v)||E.push(v):NB(v)&&(u.storeConversationMessage(v)&&lp({conversationUpdateFields:f,message:v}),u.isMessageSentByCurrentInstance(v)&&!N||E.push(v))}),{conversationUpdateFieldList:[...f.values()],messages:E}}_emitMessageEventsAfterReceiveNewMessage(r){var g;const{messages:u=[]}=((g=r.result)===null||g===void 0?void 0:g[Xt.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(u)}_emitMessageEventsAfterSyncUnreadMessage(r){var g;const{messages:u=[]}=((g=r.result)===null||g===void 0?void 0:g[Xt.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(u)}_emitMessageEvents(r){const g=r?.filter(E=>E?.isModified===!0)||[];g.length>0&&Se.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:g});const u=r?.filter(E=>!E?.isModified);u.length>0&&Se.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:u})}_generateC2CMessage(r){const g=Zr.CONV_C2C,u=of(r),E=Se.message.messageFactory.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:tE.IN})),{elements:f}=u;return E.setElement(f),E}_updateMessageProfile(r){var g;const{messageDataHandler:u}=Se.message||{},E=(g=Se.store.get("login"))===null||g===void 0?void 0:g.userId,{from:f,nick:D,avatar:v,conversationID:N=""}=r;if(f!==E){const P=u.getLatestMsgSentByPeer(N);if(P){const{nick:W,avatar:nA}=P;n(D)||n(v)?(r.nick=c(W)?W:r.nick,r.avatar=c(nA)?nA:r.avatar):D===W&&v===nA||(u.updateNickAndAvatarOfSentMessage({conversationID:N,latestNick:D,latestAvatar:v,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:N,nick:D,avatar:v}))}}else{const P=u.getLatestMsgSentByMe(N);!P||D===P.nick&&v===P.avatar||u.updateNickAndAvatarOfSentMessage({conversationID:N,latestNick:D,latestAvatar:v,isSentByMe:!0})}}_updateConversationUserProfile(r){const{conversationID:g,nick:u,avatar:E}=r,f=_B.getConversation(g),{userProfile:D={}}=f||{};D.avatar===E&&D.nick===u||_B.updateConversation(g,{userProfile:Object.assign(Object.assign({},D),{nick:u,avatar:E})})}_updateMessageListDueToModify(r){const{conversationID:g}=r,{isUpdated:u,message:E}=Se.message.messageDataHandler.modifyConversationMessage(g,r);u===!0&&Se.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),Se.notificationCenter.emitInnerEvent("ModifyMessageSuccess",r),af(g,r)}_handleC2CMessageModify(r){r.C2cMsgModNotifys.forEach(g=>{var u;const E=Zr.CONV_C2C;let f=nf(g);const{to:D,from:v}=f;let N=`${E}${D}`;D===((u=Se.store.get("login"))===null||u===void 0?void 0:u.userId)&&(N=`${E}${v}`),f=Object.assign({conversationType:E,conversationID:N},f),this._updateMessageListDueToModify(f)})}_dispose(){const{notificationCenter:r}=Se,{InnerEventSubType:g}=r;Se.notificationCenter.unSubscribeInnerEvent(lo.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),Se.notificationCenter.unSubscribeInnerEvent(lo.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),Se.notificationCenter.unSubscribeInnerEvent(lo.DESTROY,this._dispose,this)}}class Uh{init(){const{notificationCenter:r}=Se,{InnerEventSubType:g}=r;Pn.getInstance().registerWorkflowStep(jt.RECEIVE_GROUP_NEW_MESSAGE,Xt.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),Pn.getInstance().registerWorkflowStep(jt.RECEIVE_GROUP_NEW_MESSAGE,Xt.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),r.subscribeInnerEvent(lo.MESSAGE_PUSH,g.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),r.subscribeInnerEvent(lo.MESSAGE_PUSH,g.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),r.subscribeInnerEvent(lo.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(r){this._canExecuteReceiverNewMessageWorkFlow(r)&&Pn.getInstance().executeWorkflow(jt.RECEIVE_GROUP_NEW_MESSAGE,r)}_handleGroupMessagePush(r){const g=r.data||{},{messageDataHandler:u}=Se.message,E=[],f=new Map,D=g?.GroupMsgArray;return D?.forEach(v=>{if(v.GroupInfo.NotVisible===1)return;const N=this._generateGroupMessage(v);this.updateMessageProfile(N);let P=N.isModified===1;u.isMessageSentByCurrentInstance(N)?N.isModified=P:P=!1,N._onlineOnlyFlag?u.isMessageSentByCurrentInstance(N)||E.push(N):NB(N)&&u.storeConversationMessage(N)&&(E.push(N),lp({conversationUpdateFields:f,message:N}))}),{conversationUpdateFieldList:[...f.values()],messages:E}}_emitMessageEvents(r){var g;const{messages:u}=((g=r.result)===null||g===void 0?void 0:g[Xt.HANDLE_GROUP_NEW_MESSAGE])||{},E=u?.filter(D=>D?.isModified===!0)||[];E.length>0&&Se.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:E});const f=u?.filter(D=>!D?.isModified)||[];f.length>0&&Se.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:f})}_generateGroupMessage(r){const g=Zr.CONV_GROUP,u=$D(r),E=Se.message.messageFactory.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:tE.IN})),{elements:f}=u;return E.setElement(f),E}updateMessageProfile(r){var g;const{messageDataHandler:u}=Se.message||{},E=(g=Se.store.get("login"))===null||g===void 0?void 0:g.userId,{from:f,nick:D,avatar:v,conversationID:N="",_elements:P}=r;if(f===E){const W=u.getLatestMsgSentByMe(N);!W||D===W.nick&&v===W.avatar||u.updateNickAndAvatarOfSentMessage({conversationID:N,latestNick:D,latestAvatar:v,isSentByMe:!0})}else if(f===Po.CONV_SYSTEM){const{operationType:W,memberInfoList:nA,operatorInfo:EA}=P;let wA={};if(tn(nA)?tn(EA)||(wA=EA):[bg.JOINED,bg.KICKED,bg.ADMIN_SET,bg.ADMIN_CANCELED].includes(W)&&(wA=Object.assign({},nA[0])),!tn(wA)){const{nick:kA="",avatar:VA=""}=wA;r.nick=kA,r.avatar=VA}}}_updateMessageListDueToModify(r){const{conversationID:g}=r,{isUpdated:u,message:E}=Se.message.messageDataHandler.modifyConversationMessage(g,r);u===!0&&Se.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),af(g,r)}_handleGroupMessageModify(r){r.GroupMsgModNotifys.forEach(g=>{const u=Zr.CONV_GROUP;let E=AS(g);const{topicID:f,groupID:D}=E,v=f||D,N=`${u}${v}`;E=Object.assign({conversationType:u,conversationID:N,to:v},E),this._updateMessageListDueToModify(E)})}_dispose(){const{notificationCenter:r}=Se,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:g,GROUP_MESSAGE_MODIFIED:u}}=r;r.unSubscribeInnerEvent(lo.MESSAGE_PUSH,g,this._handleGroupMessagePush,this),r.unSubscribeInnerEvent(lo.MESSAGE_PUSH,u,this._handleGroupMessageModify,this),r.unSubscribeInnerEvent(lo.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(r){var g,u;const{GroupId:E,GroupType:f}=((u=(g=r?.GroupMsgArray)===null||g===void 0?void 0:g[0])===null||u===void 0?void 0:u.GroupInfo)||{},D=f===xa.GRP_AVCHATROOM;return!(!sp.getGroup(E)&&D)}}var nS=new class{constructor(){this.c2cMessageReceiver=new Lh,this.groupMessageReceiver=new Uh}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const PR={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!s.startsWith("C2C")&&!s.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>function(r){var g;return typeof r?.text!="string"||typeof r.text=="string"&&((g=r?.text)===null||g===void 0?void 0:g.length)===0?"payload.text must be a string":!0}(s)}}},aN={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var gN=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(s){return mA(this,void 0,void 0,function*(){try{const{conversationID:r,count:g,direction:u,sequence:E,messageSequenceList:f,shouldMarkCompleted:D=!1,getType:v}=s,N=r.replace(Pa.CONV_GROUP,""),P=[];let W=E;if(u===$c.BACKWARD){if(typeof E!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};W=E+g-1}const nA=yield kh({groupID:N,count:g,messageSequence:W,messageSequenceList:f,getType:v});if(nA){const{RspMsgList:EA=[],NextReqMsgSeq:wA=0,IsFinished:kA,InvisibleMsgSeq:VA}=nA,LA=`groupID:${N} sequence:${E} reqSeq:${W} direction:${u} complete:${kA} nextSequence:${wA} remoteMsgCount:${EA.length} invisibleSequenceList:${VA}`,SA=[];for(let Ee=0;Ee=E),PA&&D&&this.completedHistoryConversations.add(r);const zA=TB(SA);return Se.ssoLog.info("getGroupRoamingMessagesByAnchor",LA),{messageList:zA,invisibleSequenceList:VA,nextReqMessageIDFromServer:wA,hasNoMoreHistoryMessage:PA,serverGroupTipList:P}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};throw new hn({code:g,message:u})}})}clearHistoryMessageListFetchAnchors(s){this._historyMessageListFetchAnchors.delete(s)}isHistoryMessageFetchCompleted(s){return this.completedHistoryConversations.has(s)}_parseMessage(s){var r;const g=Pa.CONV_GROUP;s.Event===4&&(s.MsgBody.MsgType=Po.MSG_GRP_TIP);const u=$D(s),E=tf.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:"in"}));return wB(((r=u.elements)===null||r===void 0?void 0:r.content)||{},E),E.setElement(u.elements),E}getC2CRoamingMessagesByAnchor(s){return mA(this,void 0,void 0,function*(){var r;try{const{conversationID:g,count:u,messageID:E,time:f,direction:D,shouldMarkCompleted:v=!1}=s;let N=f,P="";if(!f){const EA=E?Se.message.messageDataHandler.findMessage(E):null;if(N=EA?.time||0,E&&this._historyMessageListFetchAnchors.has(g)){const wA=this._historyMessageListFetchAnchors.get(g);N=wA.lastMessageTime,P=wA.messageKey}}const W=g.replace(Pa.CONV_C2C,""),nA=yield sf({count:u,lastMessageTime:N,messageKey:P,peerAccount:W,direction:D});if(nA){const{MsgList:EA=[],Complete:wA,MsgKey:kA,LastMsgTime:VA}=nA;this._historyMessageListFetchAnchors.set(g,{messageKey:kA,lastMessageTime:VA});const LA=[];for(let Ee=0;Ee{const{tag:E,value:f}=u;E&&E.indexOf(rS)>-1?g.profileCustomField.push({key:E,value:f}):Ld.has(E)&&(g[Ld.get(E)]=f)}),Object.assign(Object.assign({},gf),g)}parseProfileItem(s=[]){const r=[];return s.forEach(g=>{r.push({tag:g.Tag,value:g.Value})}),r}parseProfileList(s=[]){const r=[];return s.forEach(g=>{r.push({tag:g.Tag,value:g.ValueBytes})}),r}convertParamsToProfile(s){const r=[];return Object.keys(s).forEach(g=>{g!==aS&&r.push({tag:ql[g.toUpperCase()],value:s[g]})}),s.profileCustomField&&C(s.profileCustomField)&&s.profileCustomField.forEach(g=>{r.push({tag:g.key,value:g.value})}),r}normalizeProfileFields(s){const r={},g=[];return s.forEach(u=>{const{tag:E,value:f}=u;if(E&&E.indexOf(rS)>-1&&g.push({key:E,value:f}),Ld.has(E)&&f!==void 0){const D=Ld.get(E);r[D]=f}}),g.length>0&&(r.profileCustomField=g),r}};const{generateProtocolData:YR}=Se.common;function VR(s){return mA(this,void 0,void 0,function*(){const r="profile.portrait_get_all",g={From_Account:ar(),UserItem:[]};s.forEach(D=>{g.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:D})});const u=YR({servcmd:r,data:g}),E=`${u.head.seq}${r}`,f=yield Se.channel.sendPacket(u,{requestId:E});if(f)return function(D){const{ActionStatus:v,ErrorCode:N,ErrorDisplay:P,ErrorInfo:W,UserProfileItem:nA}=D,EA=[];return nA.map(wA=>{const{To_Account:kA,CustomSequence:VA,ResultCode:LA,ResultInfo:SA,StandardSequence:PA,ProfileItem:zA}=wA,Ee=iE.parseProfileItem(zA);EA.push({userId:kA,customSequence:VA,resultCode:LA,resultInfo:SA,standardSequence:PA,profileItem:Ee})}),{actionStatus:v,errorCode:N,errorDisplay:P,errorInfo:W,userProfile:EA}}(f)})}function ZE(s){return uc.getFriendMap().has(s)}const{isEmpty:gS}=Se.utils;class cf{constructor(){this._strangerProfileMap=new Map}init(){Sr.getInstance().registerApi({apiName:"getMyProfile",context:this}),Sr.getInstance().registerApi({apiName:"getUserProfile",context:this}),Sr.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=iE.createProfile.bind(iE);const{notificationCenter:r}=Se;Pn.getInstance().registerWorkflowStep(jt.SYNC_SERVER_INFO_AFTER_LOGIN,Xt.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),r.subscribeInnerEvent(lo.MESSAGE_PUSH,r.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),r.subscribeInnerEvent(lo.LOGOUT,this._reset,this),r.subscribeInnerEvent(lo.DESTROY,this._dispose,this)}getMyProfile(){return mA(this,void 0,void 0,function*(){try{const r=ar(),g=yield VR([r]);if(g){const u=this._handleProfileFormResponse(g)[0];return uc.getUserProfileMap().set(r,u),{code:0,data:u}}}catch(r){const{errorCode:g,errorInfo:u}=r;throw new hn({functionName:"getMyProfile",code:g,message:u})}})}getUserProfile(r){return mA(this,void 0,void 0,function*(){try{let{userIDList:g}=r;const{userIdListToRequest:u,profileFromCache:E}=this._filterRequestAndCacheUsers(g);if(u.length===0)return{code:0,data:E,successLog:{message:`userIDList.length:${g.length}`}};u.length>xR&&(Se.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),u.length=xR);const{data:f,error:D}=yield this._batchFetchUserProfiles(u),v=u.length,N=f.length,P=v-N;if(E.length===0&&v===P&&!gS(D))throw D;if(C(f))return f.forEach(nA=>{ZE(nA.userID)?uc.getUserProfileMap().set(nA.userID,nA):this._strangerProfileMap.set(nA.userID,nA)}),{code:0,data:f.concat(E),successLog:{message:`getUserProfile query:${v} success:${N} fail:${P} from cache:${E.length}`}}}catch(g){throw new hn(g)}})}getMyProfileCacheThenServer(){return mA(this,void 0,void 0,function*(){const r=ar(),g=uc.getUserProfileMap().has(r);return g?{code:0,data:g}:this.getMyProfile()})}updateMyProfile(r){return mA(this,void 0,void 0,function*(){const g=ar(),u={};for(const f in r)r[f]!==void 0&&(u[f]=r[f]);const E=iE.convertParamsToProfile(u);try{yield function(P){return mA(this,void 0,void 0,function*(){const W="profile.portrait_set",nA=YR({servcmd:W,data:P}),EA=`${nA.head.seq}${W}`,wA=yield Se.channel.sendPacket(nA,{requestId:EA});if(wA){const{ActionStatus:kA,ErrorCode:VA,ErrorDisplay:LA,ErrorInfo:SA}=wA;return{actionStatus:kA,errorCode:VA,errorDisplay:LA,errorInfo:SA}}})}({From_Account:g,ProfileItem:E});const D=uc.getUserProfile(g);let v;v=D?Object.assign(Object.assign({},D),u):iE.createProfile(g,E);const N=!cg(D,v,["lastUpdatedTime"]);return v.lastUpdatedTime=Date.now(),uc.getUserProfileMap().set(g,v),N&&this._emitProfileUpdated(v),{code:0,data:v,successLog:{message:`profileArray: ${Se.utils.safeStringify(E)}`}}}catch(f){const{errorCode:D,errorInfo:v}=f;throw new hn({functionName:"updateMyProfile",code:D,message:v,moreMessage:`params: ${Se.utils.safeStringify(r)}`})}})}updateMyNickAndAvatar(r){return mA(this,void 0,void 0,function*(){const g=ar(),u=Date.now(),E=uc.getUserProfile(g);let f={};f=E?Object.assign(E,r):iE.createProfile(g,r),f.lastUpdatedTime=u,uc.getUserProfileMap().set(g,f)})}_onProfileDataModify(r){const g=function(f){const{Profile_Account:D,PushType:v,ProfileList:N}=f;return{userId:D,pushType:v,profileList:iE.parseProfileList(N)}}(r.ProfileDataMod[0]);if(gS(g))return;const{isProfileUpdated:u,profile:E}=this._handleProfileModified(g);u&&this._emitProfileUpdated(E)}_emitProfileUpdated(r){Se.notificationCenter.emitInnerEvent(lo.PROFILE_UPDATE,{name:lo.PROFILE_UPDATE,data:[r]}),Se.notificationCenter.emitOuterEvent(Rr.PROFILE_UPDATED,{name:Rr.PROFILE_UPDATED,data:[r]}),_B.updateConversation(`C2C${r?.userID}`,{userProfile:r})}_dispose(){const{notificationCenter:r}=Se;r.unSubscribeInnerEvent(lo.LOGOUT,this._reset,this),r.unSubscribeInnerEvent(lo.MESSAGE_PUSH,r.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),r.unSubscribeInnerEvent(lo.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(r){const{userId:g,profileList:u}=r,E=uc.getUserProfile(g);if(!(ar()===g||ZE(g)&&E))return{isProfileUpdated:!1,profile:null};const f=iE.normalizeProfileFields(u),D=Object.keys(f).some(W=>W===aS?this._isCustomFieldChanged(E.profileCustomField,f.profileCustomField):E[W]!==f[W]);if(!D)return{isProfileUpdated:!1,profile:E};const v=Date.now(),N=Object.prototype.hasOwnProperty.call(f,aS)?this._mergeProfileCustomField(E.profileCustomField,f.profileCustomField):E.profileCustomField,P=Object.assign(Object.assign(Object.assign({},E),f),{profileCustomField:N,lastUpdatedTime:v});return uc.getUserProfileMap().set(g,P),{isProfileUpdated:D,profile:P}}_filterRequestAndCacheUsers(r){const g=[],u=[];return r.forEach(E=>{const f=uc.getUserProfileMap().has(E);ZE(E)&&f?u.push(uc.getUserProfile(E)):this._isStrangerAndProfileValid(E)?u.push(this._strangerProfileMap.get(E)):g.push(E)}),{userIdListToRequest:g,profileFromCache:u}}_handleProfileFormResponse(r){const{userProfile:g}=r;if(!Array.isArray(g))return[];const u=g.filter(f=>f.userId!=="@TLS#NOT_FOUND"&&f.userId!==""&&!gS(f.profileItem)),E=Date.now();return u.map(f=>{const D=iE.createProfile(f.userId,f.profileItem);return D.lastUpdatedTime=E,D})}_isStrangerAndProfileValid(r){var g;if(!ZE(r)){const{lastUpdatedTime:u=0}=this._strangerProfileMap.get(r)||{},E=((g=Se.store.get("cloudConfig"))===null||g===void 0?void 0:g.stranger_profile_expiration_time)||6e5;return Date.now()-u<=E}return!1}_chunkUserIDList(r,g){return Array.from({length:Math.ceil(r.length/g)},(u,E)=>r.slice(E*g,(E+1)*g))}_batchFetchUserProfiles(r){return mA(this,void 0,void 0,function*(){const g=[],u=[];let E={};return this._chunkUserIDList(r,100).forEach(f=>{g.push(VR(f))}),(yield Promise.allSettled(g)).forEach(f=>{if(f.status==="fulfilled"){const D=f.value,v=this._handleProfileFormResponse(D);C(v)&&u.push(...v)}else if(f.status==="rejected"){const{code:D,message:v}=f.reason||{};E={errorCode:D,message:v}}}),{data:u,error:E}})}_isCustomFieldChanged(r=[],g=[]){if(!C(g)||g.length===0)return!1;if(!C(r)||r.length===0)return!0;const u=new Map(r.map(E=>[E.key,E.value]));return g.some(E=>u.get(E.key)!==E.value)}_mergeProfileCustomField(r=[],g=[]){const u=C(r)?r.map(E=>Object.assign({},E)):[];return C(g)&&g.length!==0&&g.forEach(({key:E,value:f})=>{const D=u.find(v=>v.key===E);D?D.value=f:u.push({key:E,value:f})}),u}_reset(){uc.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const lf=new Map,cS=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let s=0,r=cS.length;s>(-2*f&6)):0)E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(E);try{return decodeURIComponent(escape(g))}catch(u){return console.warn(u),""}}const{isEmpty:lN}=Se.utils,{generateProtocolData:If}=Se.common;function HR(s){return mA(this,void 0,void 0,function*(){const r="im_open_status.ws_get_user_status",g=If({servcmd:r,data:{To_Account:s}}),u=`${g.head.seq}${r}`,E=yield Se.channel.sendPacket(g,{requestId:u});if(E)return function(f){const{ErrorCode:D,ErrorInfo:v,ErrorList:N=[],UserStatusList:P=[]}=f,W=P.map(EA=>{const{To_Account:wA,Status:kA,CustomStatus:VA,Detail:LA=[]}=EA;return{userID:wA,statusType:kA,customStatus:up(VA),onlineDevices:IN(LA)}}),nA=N.map(EA=>{const{To_Account:wA,Invalid_Account:kA,ErrorCode:VA,ErrorInfo:LA}=EA;return{userID:lN(kA)?wA:kA,code:VA,message:LA}});return{errorCode:D,errorInfo:v,successUserList:W,failureUserList:nA}}(E)})}function IN(s){const r=[];return s?.forEach(g=>{const{Platform:u,Status:E}=g;E==="Online"&&r.push(u)}),r}class uN{constructor(){this._customStatus=""}init(){const{notificationCenter:r}=Se;Sr.getInstance().registerApi({apiName:"getUserStatus",context:this}),Sr.getInstance().registerApi({apiName:"setSelfStatus",context:this}),Sr.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),Sr.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),Pn.getInstance().registerWorkflowStep(jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Xt.USER_STATUS_UPDATE,this._onReOnline,this),r.subscribeInnerEvent(lo.MESSAGE_PUSH,r.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),r.subscribeInnerEvent(lo.LOGOUT,this._reset,this),r.subscribeInnerEvent(lo.DESTROY,this._dispose,this)}setSelfStatus(r){return mA(this,void 0,void 0,function*(){const g=ar(),{customStatus:u}=r;try{return yield function(E){return mA(this,void 0,void 0,function*(){const f="im_open_status.ws_set_custom_status",D=If({servcmd:f,data:{CustomStatus:E}}),v=`${D.head.seq}${f}`,N=yield Se.channel.sendPacket(D,{requestId:v});if(N){const{ErrorCode:P,ErrorInfo:W}=N;return{errorCode:P,errorInfo:W}}})}(u),this._customStatus=u,{code:0,data:{userID:g,statusType:Fh,customStatus:u},successLog:{message:`customStatus: ${u}`}}}catch(E){const{errorCode:f,errorInfo:D}=E;throw new hn({functionName:"setSelfStatus",code:f,message:D})}})}getUserStatus(r){return mA(this,void 0,void 0,function*(){const{userIDList:g=[]}=r;if(this._isOnlyMeInArray(g))return this._getMyStatus();const u=yield this._getUserStatus(g);return Object.assign(Object.assign({},u),{successLog:{message:`userIDList length: ${g.length}`}})})}setCustomStatus(r){const g=up(r);this._customStatus=g}subscribeUserStatus(r){return mA(this,void 0,void 0,function*(){try{const{userIDList:g=[]}=r;this._checkBusinessCapabilityBits("subscribeUserStatus");const u=this._getMaxUserCount("subscribe"),E=this._sliceUserIDList(g,u),f=yield function(v){return mA(this,void 0,void 0,function*(){const{channel:N}=Se,P="im_open_status.ws_status_subscribe",W=If({servcmd:P,data:{To_Account:v}}),nA=`${W.head.seq}${P}`;return yield N.sendPacket(W,{requestId:nA})})}(E),D=this._parseResponse(f);return{code:0,data:{failureUserList:D},successLog:{message:`userID length:${g.length} failCount: ${D.length}`}}}catch(g){const{errorCode:u}=g;throw new hn({functionName:"subscribeUserStatus",code:u})}})}unsubscribeUserStatus(r){return mA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:g=[]}=r,u=this._getMaxUserCount("unsubscribe"),E=this._sliceUserIDList(g,u),f=yield function(v){return mA(this,void 0,void 0,function*(){const{channel:N}=Se,P="im_open_status.ws_status_unsubscribe";let W={};W=v.length===0?{UnsubscribeAll:1}:{To_Account:v};const nA=If({servcmd:P,data:W}),EA=`${nA.head.seq}${P}`;return yield N.sendPacket(nA,{requestId:EA})})}(E),D=this._parseResponse(f);return{code:0,data:{failureUserList:D},successLog:{message:`userID length:${g.length} failCount: ${D.length}`}}}catch(g){const{errorCode:u}=g;throw new hn({functionName:"unsubscribeUserStatus",code:u})}})}_onUserStatusUpdate(r){const{UserStatusList:g=[]}=r||{},u=g.map(E=>{const{To_Account:f,Status:D,CustomStatus:v,Platform:N}=E,P={userID:f,statusType:D,customStatus:up(v)};return N&&(P.onlineDevices=N),P});this._emitUserStatusUpdatedEvent(u)}_onReOnline(r){const g=up(r.data.customStatus);if(this._customStatus===g)return;this._customStatus=g;const u={userID:ar(),statusType:Fh,customStatus:g};this._emitUserStatusUpdatedEvent(u)}_emitUserStatusUpdatedEvent(r){Se.notificationCenter.emitOuterEvent(Rr.USER_STATUS_UPDATED,{name:Rr.USER_STATUS_UPDATED,data:r})}_sliceUserIDList(r,g){return r.slice(0,g)}_parseResponse(r){const{ErrorList:g=[]}=r;return g.map(u=>{const{To_Account:E,Invalid_Account:f,ErrorCode:D,ErrorInfo:v}=u;return{userID:Se.utils.isEmpty(f)?E:f,code:D,message:v}})}_checkBusinessCapabilityBits(r){if(!Se.store.get("commercialConfig").get(cN))throw new hn({functionName:r,code:ma.NO_USE,replacement1:r})}_getMaxUserCount(r){const g=Se.store.get("cloudConfig")||{},u={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}},{key:E,default:f}=u[r],D=g[E]||f;return parseInt(D,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:ar(),statusType:Fh,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(r){return mA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const g=this._getMaxUserCount("query"),u=this._sliceUserIDList(r,g),E=yield HR(u),{successUserList:f,failureUserList:D}=E||{};return{code:0,data:{successUserList:f,failureUserList:D}}}catch(g){const{errorCode:u}=g;throw new hn({functionName:"getUserStatus",code:u})}})}_isOnlyMeInArray(r){const g=ar();return r.length===1&&r.indexOf(g)>-1}_dispose(){const{notificationCenter:r}=Se;r.unSubscribeInnerEvent(lo.MESSAGE_PUSH,r.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),r.unSubscribeInnerEvent(lo.DESTROY,this._dispose,this),r.unSubscribeInnerEvent(lo.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const lS={getUserProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},updateMyProfile:{nick:{required:!1,rules:["string"],allowEmpty:!0},avatar:{required:!1,rules:["string"],allowEmpty:!0},gender:{required:!1,rules:["string"],allowEmpty:!0},selfSignature:{required:!1,rules:["string"],allowEmpty:!0},allowType:{required:!1,rules:["string"],allowEmpty:!0},birthday:{required:!1,rules:["number"],allowEmpty:!1},language:{required:!1,rules:["string"],allowEmpty:!0},messageSettings:{required:!1,rules:["string"],allowEmpty:!0},adminForbidType:{required:!1,rules:["string"],allowEmpty:!0},level:{required:!1,rules:["number"],allowEmpty:!1},role:{required:!1,rules:["number"],allowEmpty:!0},profileCustomField:{required:!1,rules:["array"],allowEmpty:!0,customValidator:function(s){for(const r of s){if(typeof r!="object")return"Each item in profileCustomField must be an object";if(typeof r?.key!="string")return"Each item.key in profileCustomField must be a string";if(!r?.key.startsWith(rS))return'Each item.key in profileCustomField must start with "Tag_Profile_Custom"'}return!0}}},setSelfStatus:{customStatus:{required:!0,rules:["string"],allowEmpty:!0}},getUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!1,rules:["array"],allowEmpty:!0}}},EN={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class dN{constructor(){this.userProfile=new cf,this.userStatus=new uN,this.userProfile.init(),this.userStatus.init(),el({auth:EN,params:lS})}}function IS(s){const r=[];if(!c(s))return r;const g=s.length;if(g===0)return r;for(let u=g-1;u>=0;u--)s[u]==="1"&&r.push(2**(g-u-1));return r}var Ud,NC,Fd;(function(s){s.NOT_START="notStart",s.PENDING="pending",s.RESOLVED="resolved",s.REJECTED="rejected"})(Ud||(Ud={})),function(s){s[s.C2C=1]="C2C",s[s.GROUP=2]="GROUP"}(NC||(NC={})),function(s){s[s.C2C=8]="C2C",s[s.GROUP=2]="GROUP"}(Fd||(Fd={}));class uS{constructor(){this._name="SyncConversationHandler",this._pagingStatus=Ud.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:r}=Se;Pn.getInstance().registerWorkflowStep(jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Xt.CONVERSATION_RECOVER,this._syncConversationList,this),Pn.getInstance().registerWorkflowStep(jt.SYNC_SERVER_INFO_AFTER_LOGIN,Xt.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),r.subscribeInnerEvent(lo.LOGOUT,this._reset,this),r.subscribeInnerEvent(lo.DESTROY,this._dispose,this),Se.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===Ud.RESOLVED}_syncConversationListAfterLogin(){return mA(this,void 0,void 0,function*(){return this._pagingStatus=Ud.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=Se;r.debug("_syncConversationList","start");try{const u=yield this._pagingGetConversationList(!0);this._pagingStatus=Ud.RESOLVED;const{conversationList:E=[]}=u||{};return r.info("_syncConversationList",`success count:${E.length}`),u}catch(u){const E=new hn(u);r.error("_syncConversationList",`fail ${g(u)}`,{error:E})}})}_pagingGetConversationList(r){return mA(this,void 0,void 0,function*(){try{const g=[];this._pagingStatus=Ud.PENDING;const u=yield function(nA){return mA(this,void 0,void 0,function*(){const{fromAccount:EA,pagingTimeStamp:wA,pagingStartIndex:kA,pagingPinnedTimeStamp:VA,pagingPinnedStartIndex:LA}=nA;return Ig({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:EA,StartIndex:kA,TimeStamp:wA,TopStartIndex:LA,TopTimeStamp:VA}})})}({fromAccount:ar(),pagingTimeStamp:r?this._pagingTimeStamp:0,pagingStartIndex:r?this._pagingStartIndex:0,pagingPinnedTimeStamp:r?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:r?this._pagingPinnedStartIndex:0}),{CompleteFlag:E,SessionItem:f=[],TimeStamp:D,StartIndex:v,TopTimeStamp:N,TopStartIndex:P}=u||{};let W=[];if(E===1&&(this._pagingStatus=Ud.RESOLVED),f.length>0&&(W=this._getConversationOptions(f),g.push(...W)),Se.notificationCenter.emitInnerEvent(lo.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:W}),this._pagingTimeStamp=D,this._pagingStartIndex=v,this._pagingPinnedTimeStamp=N,this._pagingPinnedStartIndex=P,E!==1){const{conversationList:nA}=yield this._pagingGetConversationList(r);g.push(...nA)}return{conversationList:g}}catch(g){throw g}})}_getConversationOptions(r){const{utils:{isUndefined:g}}=Se,u=this._convertConversationKey(r);return this._filterValidConversations(u).map(E=>(g(E.lastMsg)&&(E.lastMsg={elements:[]}),E.type===NC.C2C?this._assembleC2COption(E):this._assembleGroupOption(E)))}_filterValidConversations(r){return r.filter(({type:g,userID:u})=>g===NC.C2C&&!function(E){let f;return E.startsWith(Po.CONV_C2C)&&(f=E.replace(Po.CONV_C2C,"")),f==="@TLS#ERROR"||f==="@TLS#NOT_FOUND"}(u)||g===2)}_assembleC2COption(r){var g,u,E,f,D,v,N,P;const W=this._createUserprofile(r);return{conversationID:`${Po.CONV_C2C}${r.userID}`,type:Po.CONV_C2C,lastMessage:{lastTime:r.time,lastSequence:r.sequence,fromAccount:r.lastC2CMsgFromAccount,type:!((g=r.lastMsg)===null||g===void 0)&&g.elements[0]?(u=r.lastMsg)===null||u===void 0?void 0:u.elements[0].type:null,payload:!((E=r.lastMsg)===null||E===void 0)&&E.elements[0]?this._amendLayersOverLimitProp(r.lastMsg.elements[0].content):null,cloudCustomData:((v=(D=(f=r.lastMsg)===null||f===void 0?void 0:f.elements)===null||D===void 0?void 0:D[0])===null||v===void 0?void 0:v.cloudCustomData)||"",isRevoked:r.lastMessageFlag===Fd.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(r),revoker:((P=(N=r.lastMsg)===null||N===void 0?void 0:N.revokerInfo)===null||P===void 0?void 0:P.revoker)||null},unreadCount:0,userProfile:W,peerReadTime:r.peerReadTime,isPinned:r.isPinned===1,customData:r.customMark||"",markList:IS(r.standardMark),conversationGroupList:[],remark:r.friendRemark||"",messageRemindType:this._transMsgRemindType(r.messageRemindType)}}_createUserprofile(r){var g;const{userID:u,nick:E,peerAvatar:f}=r,D=[{tag:"Tag_Profile_IM_Nick",value:E},{tag:"Tag_Profile_IM_Image",value:f}];return(g=Se.user.userProfile)===null||g===void 0?void 0:g.createProfile(u,D)}_computeIsPeerRead(r){const g=ar(),{lastC2CMsgFromAccount:u,time:E,c2cPeerReadTime:f}=r;return u===g&&E<=f}_assembleGroupOption(r){var g,u,E,f,D;return{conversationID:`${Po.CONV_GROUP}${r.groupID}`,type:Po.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:r.time,lastSequence:r.sequence,fromAccount:r.msgGroupFromAccount},this._patchTypeAndPayload(r)),{cloudCustomData:((E=(u=(g=r.lastMsg)===null||g===void 0?void 0:g.elements)===null||u===void 0?void 0:u[0])===null||E===void 0?void 0:E.cloudCustomData)||"",isRevoked:r.lastMessageFlag===Fd.GROUP,onlineOnlyFlag:!1,nick:r.msgGroupFromNickName||"",nameCard:r.msgGroupFromCardName||"",revoker:((D=(f=r.lastMsg)===null||f===void 0?void 0:f.revokerInfo)===null||D===void 0?void 0:D.revoker)||null}),groupProfile:{groupID:r.groupID,name:r.groupNick,avatar:r.groupImage,type:r.groupType,nextMessageSeq:r.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(r),peerReadTime:0,isPinned:r.isPinned===1,version:0,customData:r.customMark||"",markList:IS(r.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(r.messageRemindType),subType:r.groupType}}_convertConversationKey(r){return r.map(g=>({type:g.Type,userID:g.To_Account,nick:g.C2cNick,peerAvatar:g.C2cImage,time:g.MsgTimeStamp,sequence:g.MsgSeq,lastC2CMsgFromAccount:g.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(g.LastMsg),lastMessageFlag:g.LastMsgFlags,c2cPeerReadTime:g.C2cPeerReadTime,peerReadTime:g.C2cPeerReadTime,friendRemark:g.C2cRemark,isPinned:g.TopFlags,standardMark:g.StandardMark,customMark:g.CustomMark,messageRemindType:g.MsgRecvOption,groupID:g.ToAccount,groupNick:g.GroupNick,groupImage:g.GroupImage,groupType:g.GroupType,nextMessageSeq:g.GroupNextMsgSeq,msgGroupFromAccount:g.MsgGroupFrom_Account,msgGroupFromNickName:g.MsgGroupFromNickName,msgGroupFromCardName:g.MsgGroupFromCardName,unreadCount:g.UnreadMsgCount,noUnreadCount:g.GroupIgnoredUnreadSeqCount}))}_convertLastMsgKey(r){var g,u,E;const{utils:{isEmpty:f}}=Se;if(f(r))return null;let D="",v=null;if(!f(r.GroupTips)){const{From_Account:N,GroupName:P}=((g=r.GroupTips)===null||g===void 0?void 0:g.GroupInfo)||{};D=Po.MSG_GRP_TIP,v=Object.assign(Object.assign({},this._parseContent(D,r.GroupTips.MsgBody)),{groupProfile:{from:N,groupName:P}})}return r.MsgBody&&(D=(u=r.MsgBody[0])===null||u===void 0?void 0:u.MsgType,v=this._parseContent(D,r.MsgBody[0])),{event:r.Event,elements:[{type:D,content:v,cloudCustomData:r.CloudCustomData}],revokerInfo:{revoker:(E=r.RevokerInfo)===null||E===void 0?void 0:E.Revoker_Account}}}_parseContent(r,g){var u;if(!g)return g;const E=Se.message.messageFactory.getElementClass(r);return E?(u=E.parseServerPushElement(g))===null||u===void 0?void 0:u.content:g}_amendLayersOverLimitProp(r){const{LayersOverLimit:g}=r;return vo(r,["LayersOverLimit"]).layersOverLimit=g===1,r}_transMsgRemindType(r){let g="";return r===0?g=Po.MSG_REMIND_ACPT_AND_NOTE:r===1?g=Po.MSG_REMIND_DISCARD:r===2?g=Po.MSG_REMIND_ACPT_NOT_NOTE:r===3&&(g=Po.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}_patchTypeAndPayload(r){var g;const{utils:{isUndefined:u}}=Se,{event:E,elements:f=[]}=r.lastMsg||{};return u(E)?{type:f[0]?f[0].type:null,payload:f[0]?this._amendLayersOverLimitProp(f[0].content):null}:{type:Po.MSG_GRP_TIP,payload:((g=f?.[0])===null||g===void 0?void 0:g.content)||{}}}_computeGroupUnreadCount(r){const{unreadCount:g=0,noUnreadCount:u=0}=r,E=g-u;return E>0?E:0}_reset(){this._pagingStatus=Ud.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:r}=Se;r.unSubscribeInnerEvent(lo.LOGOUT,this._reset,this),r.unSubscribeInnerEvent(lo.DESTROY,this._dispose,this)}}class ES{constructor(){this.syncConversationHandler=new uS,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Aa}`);var dS={create:function(s){var r,g;const{SDKAppID:u,testEnv:E=!1,devMode:f=!1,unlimitedAVChatRoom:D=!1,scene:v="",oversea:N=!1,instance:P,disableIndependentDomain:W=!1,proxyServer:nA=""}=s;let EA=u;if(!function(kA){if(typeof kA=="number")return!0;const VA=Number(kA);return!Number.isNaN(VA)}(EA))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(EA=Number(EA),fa.has(EA))return fa.get(EA);let wA=null;if(P)wA=P,wA._workflowManager&&Pn.setInstance(wA._workflowManager),wA._pluginManager&&wA._pluginManager.installBuiltInPlugin(RB),P.isReady()&&((g=(r=Pn.getInstance()).executeWorkflow)===null||g===void 0||g.call(r,jt.SYNC_SERVER_INFO_AFTER_LOGIN));else{const kA=function(){function Ee(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${Ee()+Ee()}${Ee()}${Ee()}${Ee()}${Ee()}${Ee()}${Ee()}`}();Se.init({sdkAppId:EA,instanceId:kA,testEnv:E,devMode:f,unlimitedAVChatRoom:D,disableIndependentDomain:W,scene:v,oversea:N,sdkEdition:ef,version:Aa,proxyServer:nA}),Pn.getInstance().init(),Se.message=new sS,Se.user=new dN,Se.login=new Nh,Se.conversation=new ES,Iu.getInstance().installBuiltInPlugin(RB),wA=Sr.getInstance().exposeApiForClient(),wA._workflowManager=Pn.getInstance(),wA._pluginManager=Iu.getInstance();const{utils:{IS_WORKER_AVAILABLE:VA,USER_AGENT:LA,getPlatformType:SA,isIOSWebView:PA}}=Se,zA=`instanceID:${kA} SDKAppID:${u} platform:${jA} host:${SA()} isIOSWebView:${PA} workerAvailable:${VA} UserAgent:${LA}`;Se.ssoLog.info("sdkConstruct",zA)}return fa.set(EA,wA),wA},TSignaling:Xc,EVENT:Rr,VERSION:Aa,TYPES:Po};return dS})}(hY)),hY.exports}var HnA=VnA();const rg=i4(HnA);var BY={exports:{}},JnA=BY.exports,H8;function qnA(){return H8||(H8=1,function(e,i){(function(n,c){e.exports=c()})(JnA,function(){function n(ae,Je){if(!(ae instanceof Je))throw new TypeError("Cannot call a class as a function")}function c(ae,Je){for(var pt=0;pt"u"&&typeof uni.requireNativePlugin=="function",qA=vA&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios",Ae=(vA&&uni.getDeviceInfo().platform.toLocaleLowerCase(),cA||eA||CA||IA||oA||vA),HA=b!==void 0&&(b.nativeModuleProxy!==void 0||b.ReactNative!==void 0),se=eA?qq:CA?tt:IA?swan:oA?my:cA?wx:vA?uni:{},WA=function(ae){if(T(ae)!=="object"||ae===null)return!1;var Je=Object.getPrototypeOf(ae);if(Je===null)return!0;for(var pt=Je;Object.getPrototypeOf(pt)!==null;)pt=Object.getPrototypeOf(pt);return Je===pt};function Ye(ae){if(ae==null)return!0;if(typeof ae=="boolean")return!1;if(typeof ae=="number")return ae===0;if(typeof ae=="string"||typeof ae=="function"||Array.isArray(ae))return ae.length===0;if(ae instanceof Error)return ae.message==="";if(WA(ae)){for(var Je in ae)if(Object.prototype.hasOwnProperty.call(ae,Je))return!1;return!0}return!1}var We=function(){return I(function ae(){n(this,ae),this._n="WebRequest"},[{key:"request",value:function(ae,Je){var pt=this,$t="".concat(this._n,".request"),Pt=ae.downloadUrl||"",ii=(ae.method||"PUT").toUpperCase(),ki=ae.url;if(console.log("%c tim-upload-plugin %c","background:#0abf5b; padding:1px; border-radius:3px; color: #fff","background:transparent","".concat($t," URL:").concat(ki)),ae.qs){var ao=function(Fi){var en=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"&",Ro=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"=";return Ye(Fi)?"":WA(Fi)?Object.keys(Fi).map(function(oo){var Ai=encodeURIComponent(oo)+Ro;return Array.isArray(Fi[oo])?Fi[oo].map(function(no){return Ai+encodeURIComponent(no)}).join(en):Ai+encodeURIComponent(Fi[oo])}).filter(Boolean).join(en):void 0}(ae.qs);ao&&(ki+="".concat(ki.indexOf("?")===-1?"?":"&").concat(ao))}var Ji=new XMLHttpRequest;Ji.open(ii,ki,!0),Ji.responseType=ae.dataType||"text";var Vi=ae.headers||{};if(ae.uploadByIP&&(Vi=R(R({},Vi),{},{host:ae.uploadIP})),!Ye(Vi))for(var wn in Vi)Vi.hasOwnProperty(wn)&&wn.toLowerCase()!=="content-length"&&wn.toLowerCase()!=="user-agent"&&wn.toLowerCase()!=="origin"&&wn.toLowerCase()!=="host"&&Ji.setRequestHeader(wn,Vi[wn]);return Ji.onload=function(){if(Ji.status===200)Je(null,pt._xhrRes(Ji,pt._xhrBody(Ji,Pt,ae.uploadByIP&&ae.uploadIP),Vi));else{if(ae.uploadIP&&ae.url.indexOf(ae.uploadIP)===-1)return ae.url=function(en,Ro){return en.replace(/^http(s)?:\/\/(.*?)\//,"https://".concat(Ro,"/"))}(ae.url,ae.uploadIP),ae.uploadByIP=!0,pt.request(ae,Je);var Fi={code:Ji.status,message:JSON.stringify(Ji.responseText)};Je(Fi,pt._xhrRes(Ji,pt._xhrBody(Ji,Pt,ae.uploadByIP&&ae.uploadIP),Vi))}},Ji.onerror=function(Fi){var en=pt._xhrBody(Ji,Pt,ae.uploadByIP&&ae.uploadIP),Ro={code:Ji.status,message:JSON.stringify(Ji.responseText)};en||Ji.statusText||Ji.status!==0||(Fi.message="CORS blocked or network error"),Je(Ro,pt._xhrRes(Ji,en)),Ro=null},ae.onProgress&&Ji.upload&&(Ji.upload.onprogress=function(Fi){var en=Fi.total,Ro=Fi.loaded,oo=Math.floor(100*Ro/en);ae.onProgress({total:en,loaded:Ro,percent:(oo>=100?100:oo)/100})}),Ji.send(ae.resources),Ji}},{key:"_xhrRes",value:function(ae,Je){var pt={};return ae.getAllResponseHeaders().trim().split(` +`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(g)),this._worker.postMessage({type:Er,url:r})}send(r){var g,u;try{(g=this._worker)===null||g===void 0||g.postMessage({type:On,data:r})}catch(E){(u=this._onSendFail)===null||u===void 0||u.call(this,E)}}bindSocketHandlers(r){const{onOpen:g,onMessage:u,onClose:E,onError:f,onSendFail:D}=r;if(this._worker){const v={[yn]:g,[ce]:u,[ot]:E,[Zt]:f,[Ho]:D};this._onSendFail=D,this._worker.onmessage=N=>{var P;const{type:W}=N?.data||{};typeof v[W]=="function"&&((P=v[W])===null||P===void 0||P.call(v,N?.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:Mg}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class WI{}var gn,ro=new class{constructor(){this._store=new Map}get(s){return this._store.get(s)}getStorage(s){return Fi?ii?my.getStorageSync({key:s}).data:no.getStorageSync(s):this._canUseLocalStorage()?localStorage.getItem(s):{}}set(s,r){const g=this._store.get(s)||{};r instanceof Map?this._store.set(s,r):this._store.set(s,Object.assign(Object.assign({},g),r))}setStorage(s,r){Fi?ii?my.setStorageSync({key:s,data:JSON.stringify(r)}):no.setStorageSync(s,JSON.stringify(r)):this._canUseLocalStorage()&&localStorage.setItem(s,JSON.stringify(r))}clear(s){typeof s=="string"?this._store.set(s,{}):this._store.clear()}clearLocalStorage(s){this._canUseLocalStorage()&&(typeof s=="string"?localStorage.setItem(s,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return typeof window<"u"&&navigator&&navigator.cookieEnabled&&localStorage}};class Mc{connectSocket(r){return this._socket=no.connectSocket({url:r,header:{"content-type":"application/json"},multiple:!0,complete:()=>{}}),this._socket}send(r){var g;(g=this._socket)===null||g===void 0||g.send({data:r,fail:this._onSendFail})}bindSocketHandlers(r){const{onOpen:g,onMessage:u,onClose:E,onError:f,onSendFail:D}=r;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(v=>u(v?.data)),this._socket.onError(()=>f),this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}(function(s){s[s.CONNECTED=0]="CONNECTED",s[s.CONNECTING=1]="CONNECTING",s[s.DISCONNECTED=2]="DISCONNECTED"})(gn||(gn={}));class cg{constructor(r){this._url="",this._readyState=gn.DISCONNECTED,this._url=r,this._id=b(),this._emitter=new Ls,ii?this._socket=new Mc:Xe||ao||pt||Je||ki||Pt?this._socket=new ts({onError:this._onError.bind(this)}):jn?this._socket=new WI:this._canUseWebWorker()?this._socket=new Ba:this._socket=new vc,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[gn.CONNECTED,gn.CONNECTING].includes(this._readyState)||(this._readyState=gn.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(r){this._readyState!==gn.CONNECTED?this.reconnect():this._socket.send(r)}reconnect(){[gn.CONNECTED,gn.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(r,g,u){this._emitter.on(r,g,u)}off(r,g,u){this._emitter.off(r,g,u)}isConnected(){return this._readyState===gn.CONNECTED}disconnect(){this._readyState=gn.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(r){this._readyState===gn.CONNECTING&&(this._readyState=gn.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:r}))}_onMessage(r){this._emitter.emit("message",r)}_onClose(r){this._readyState=gn.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:r})}_onError(r){this._readyState=gn.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:r})}_onSendFail(r){this._readyState=gn.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:r})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}_canUseWebWorker(){const r=ro.get("cloudConfig")||{};return(n(r.isWorkerEnabled)||r.isWorkerEnabled==="1")&&wo}}const Rg={[Ye.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[Ye.KOREA]:[[3e7,4e7],[173e7,174e7]],[Ye.GERMANY]:[[4e7,5e7],[174e7,175e7]],[Ye.IND]:[[5e7,6e7],[175e7,176e7]],[Ye.JPN]:[[6e7,7e7],[176e7,177e7]],[Ye.USA]:[[7e7,8e7],[177e7,178e7]],[Ye.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[Ye.KSA]:[[9e7,1e8],[179e7,18e8]]};function Qa(s){var r;if(!((r=ro.get("instance"))===null||r===void 0)&&r.oversea)return Ye.OVERSEA;for(const g of Object.keys(Rg))for(const[u,E]of Rg[g])if(s>=u&&s`${nA}=${W[nA]}`).join("&"));var W;return g?`${s}/binfo?${P}&compress=gzip`:`${s}/info?${P}`}function is(s){const r=ro.get("instance"),{sdkAppId:g,testEnv:u,proxyServer:E}=r,f=Qa(g);if(u)return Xs(We.TEST[f].DEFAULT,{isBinary:s});if(!tn(E))return Xs(E,{isBinary:s});const D=We.PRODUCTION[f],v=Ai&&D.ANYCAST,N=Ai,P=!!D.BACKUP_CN;return Xs({[Fo.INITIAL]:()=>(Uo=Fo.DEFAULT,D.DEFAULT),[Fo.DEFAULT]:()=>(Uo=Fo.IPV6,D.IPV6),[Fo.IPV6]:()=>(Uo=Fo.BACKUP,D.BACKUP),[Fo.BACKUP]:()=>N?(Uo=Fo.BACKUP_WEB_ONLY,function(W){const nA=Math.floor(10001*Math.random())+1e4;return W.replace("*",String(nA))}(D.BACKUP_WEB_ONLY)):P?(Uo=Fo.BACKUP_CN,D.BACKUP_CN):v?(Uo=Fo.ANYCAST,D.ANYCAST):D.DEFAULT,[Fo.BACKUP_WEB_ONLY]:()=>P?(Uo=Fo.BACKUP_CN,D.BACKUP_CN):v?(Uo=Fo.ANYCAST,D.ANYCAST):D.DEFAULT,[Fo.BACKUP_CN]:()=>(Uo=v?Fo.ANYCAST:Fo.DEFAULT,D[Uo]),[Fo.ANYCAST]:()=>(Uo=Fo.DEFAULT,D.ANYCAST="",D.DEFAULT)}[Uo](),{isBinary:s})}var wg=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(s,r){const g=Date.now(),u=g-s;this._timeOffsetWithServer=r+u-g}};const Rc=16;var ws=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(s){const{id:r}=s;this.removeTask(r),this._tasks.push(s),this._taskMap.set(r,s),this._sort(),this._scheduleNextTask()}_createTask(s){const{id:r,callback:g,context:u,isOnce:E=!1,intervalMs:f=Rc}=s,D=Math.max(f,Rc);return{id:r,nextExecuteTime:Date.now()+D,intervalMs:f,callback:g,context:u,isOnce:E}}addTask(s){const r=this._createTask(s);this._addTaskToScheduler(r)}addOnceTask(s){const r=this._createTask(Object.assign(Object.assign({},s),{isOnce:!0}));this._addTaskToScheduler(r)}removeTask(s){const r=this._tasks.findIndex(g=>g.id===s);r>-1&&(this._tasks.splice(r,1),this._taskMap.delete(s),this._scheduleNextTask())}updateTaskInterval(s,r){const g=this._taskMap.get(s);g&&(g.intervalMs=r,g.nextExecuteTime=Date.now()+r,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((s,r)=>s.nextExecuteTime-r.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const s=this._tasks[0];if(s){const r=Math.max(0,s.nextExecuteTime-Date.now());this._timer=setTimeout(()=>this._execute(),r)}}_execute(){const s=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=s;){const r=this._tasks[0];try{r.context?r.callback.call(r.context):r.callback(),r.isOnce?this.removeTask(r.id):(r.nextExecuteTime=s+r.intervalMs,this._sort())}catch(g){console.warn(`Task ${r.id} execution failed:`,g),r.isOnce&&this.removeTask(r.id)}}this._scheduleNextTask()}};function Fa(s){const r=[];for(let g=0;g=55296&&u<=56319){const E=s.charCodeAt(++g)-56320+(u-55296<<10)+65536;r.push(240|E>>18,128|E>>12&63,128|E>>6&63,128|63&E)}else u<=127?r.push(u):u<=2047?r.push(192|u>>6,128|63&u):r.push(224|u>>12,128|u>>6&63,128|63&u)}return new Uint8Array(r)}function Qs(s){const r=Array.isArray(s)?[]:Object.create(null);for(const g in s)Object.prototype.hasOwnProperty.call(s,g)&&_(g)&&s[g]!=null&&(s[g]===null||typeof s[g]!="object"?r[g]=s[g]:r[g]=Qs(s[g]));return r}function Tn(s,r){if(CA.includes(s))return 0;const g=Fa(JSON.stringify(r));let u=4294967295;const{length:E}=g;for(let f=0;f>>=1:u=u>>>1^3988292384}return(4294967295^u)>>>0}function pa(s){const{servcmd:r,data:g}=s,u=function(f){const D=ro.get("login")||{},v=ro.get("instance")||{};return{servcmd:f,ver:"v4",platform:jA,websdkappid:537048168,websdkversion:"1.7.3",a2:D.a2Key||void 0,tinyid:D.tinyID||void 0,status_instid:D.statusInstanceId||0,sdkappid:v.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:D.a2Key?void 0:D.userId,usersig:D.a2Key?void 0:D.userSig,sdkability:478343027,sdkability_ext:gA(""),cappid:v.applicationID||0,tjgID:"",seq:Ta(),cs:0}}(r),E=Qs(g);return u.cs=Tn(r,E),{head:u,body:E}}function _s(s){const{servcmd:r,data:g}=s,u=function(f){const D=ro.get("login")||{},v=ro.get("instance")||{};return{servcmd:f,ver:"v4",platform:jA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:v.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:D.statusInstanceId||0,sdkability:478343027,sdkability_ext:gA(""),cappid:v.applicationID||0,seq:Ta(),cs:0}}(r),E=Qs(g);return u.cs=Tn(r,E),{head:u,body:E}}let Oa=b();function Ta(){return Oa=Oa<2415919103?Oa+1:b(),Oa}function $(){var s;const r=ro.get("login")||{},g=ro.get("instance")||{};return{sdk_type:30,sdk_app_id:g.sdkAppId,sdk_version:"1.6.18",tiny_id:Number(r.tinyID),user_id:r.userId||((s=ro.get("webPush"))===null||s===void 0?void 0:s.userId),platform:jA,instance_id:g.instanceId,trace_id:new Date().getTime()}}var j,RA=Object.freeze({__proto__:null,calcBodyCRC:Tn,filterProtocolDataInvalidFields:Qs,generateCosSpecifiedData:function(s){const{servcmd:r,data:g}=s,u=function(f){const D=ro.get("login")||{},v=ro.get("instance")||{};return{servcmd:f,ver:"v4",platform:jA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:v.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:D.userId,usersig:D.userSig,status_instid:D.statusInstanceId||0,sdkability:478343027,sdkability_ext:gA(""),cappid:v.applicationID||0,seq:Ta(),cs:0}}(r),E=Qs(g);return u.cs=Tn(r,E),{head:u,body:E}},generateProtocolData:pa,generateSSOLogProtocolData:_s,generateSequence:Ta,getCommonHead:$,getHostSite:Qa,taskScheduler:ws,timeManager:wg});(function(s){s[s.info=4]="info",s[s.warning=5]="warning",s[s.error=6]="error"})(j||(j={}));const ZA={method:"extension",networkType:"network_type",eventType:"event_type",code:"error_code",message:"error_message",moreMessage:"more_message",duplicate:"duplicate",costTime:"cost_time",level:"level",uiPlatform:"ui_platform",timestamp:"timestamp"};class ne{constructor(r){this.level=j.info,this._canSendLog=!0,this._logCreatedAt=wg.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();const{method:g,eventType:u=0,message:E="",costTime:f=0,error:D,uiPlatform:v,moreMessage:N="",code:P=0,startTime:W=0}=r||{};this.eventType=u,this.method=g,this.message=E,this.costTime=f,this.moreMessage=`${N} startTime:${W}`,this.code=P,D&&this.setError(D),tn(v)||(this.uiPlatform=v)}setMoreMessage(r){this.moreMessage=`${this.moreMessage} ${r}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=wg.getTimeOffsetWithServer()}end(r=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=wg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),r&&this._ssoLogModule.uploadSSOLogData())}setError(r){var g;return r instanceof Error?this._canSendLog?(!((g=ro.get("netWorkMonitor"))===null||g===void 0)&&g.isNetworkOnline&&(r.errorCode&&(this.code=r.errorCode),r.errorMessage&&this.setMoreMessage(r.errorMessage)),this.level=j.error,this):this:(console.warn("SSOLogData.setError value not instanceof Error, please check!"),this)}setLogInfo(r){return Object.keys(r).forEach(g=>{Object.keys(ZA).includes(g)&&(this[g]=r[g])}),this}setSSOLogModule(r){this._ssoLogModule=r}_convertSSOLogDataKeyToServe(){const r={};return Object.keys(this).forEach(g=>{const u=g;ZA[u]&&(r[ZA[u]]=this[u])}),r}_getUiPlatform(){var r;const g=(r=ro.get("instance"))===null||r===void 0?void 0:r.scene;if(typeof g=="string"){const u=Number(g);return isNaN(u)?void 0:u}}_getSDKEdition(){var r;return(r=ro.get("instance"))===null||r===void 0?void 0:r.sdkEdition}}var De;(function(s){s.RECONNECTED="reconnected",s.CLOUD_CONFIG_UPDATE="cloud_config_update",s.SOCKET_DISCONNECTED="socket_disconnected"})(De||(De={}));var Ke=De;const qe=20,Et=6e4,ft=[4,5,6],Nt="report-logger";var Kt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=qe,this._maxThreshold=100,this._waitingTime=Et,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=IA.DEBUG,this._throttleConfig={global:{throttleTime:se,maxCount:WA},single:{throttleTime:Ae,maxCount:HA}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,es.subscribeInnerEvent(Ke.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),ws.addTask({id:Nt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(s){const{evt_rpt_threshold:r=qe,evt_rpt_waiting:g=Et,evt_rpt_level:u=ft,evt_rpt_sdkappid_bl:E="",evt_rpt_tinyid_wl:f="",evt_rpt_global_throttle_time:D=se,evt_rpt_global_throttle_count:v=WA,evt_rpt_single_throttle_time:N=Ae,evt_rpt_single_throttle_count:P=HA}=s||{};this._sdkAppIdBlackList=E.split(",").map(W=>Number(W)),this._waitingTime=Number(g),this._minThreshold=r,this._reportLevel=u,this._tinyIdWhiteList=f.split(","),this._throttleConfig={global:{throttleTime:D,maxCount:v},single:{throttleTime:N,maxCount:P}}}createSSOLogData(s){const r=new ne(s);return r.setSSOLogModule(this),this._ssoLogMap.set(s.method,r),r}getSSOLogData(s){return this._ssoLogMap.get(s)||{}}pushToLogQueue(s){s&&(this._logQueue.push(s),this._shouldUploadImmediately()&&this.uploadSSOLogData())}setLogLevel(s){[IA.DEBUG,IA.ERROR,IA.INFO,IA.NONE,IA.WARN].includes(s)&&(this._logLevel=s)}debug(s,r="",g){this._log(IA.DEBUG,s,r,g)}info(s,r="",g){this._log(IA.INFO,s,r,g)}warn(s,r="",g){this._log(IA.WARN,s,r,g)}error(s,r="",g){this._log(IA.ERROR,s,r,g)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this.uploadSSOLogData()}uploadSSOLogData(){return mA(this,void 0,void 0,function*(){if(this._logQueue.length===0)return;const s=this._logQueue.slice();this._logQueue=[];try{const r=this._filterLogs(s);if(r.length===0)return void(this._lastReportAt=Date.now());const g={Header:$(),Event:r};tn(g.Header.user_id)||(yield function(u){const E="imopenstat.tim_web_report_v2",f=_s({servcmd:E,data:u}),D=`${f.head.seq}${E}`;return ve.sendPacket(f,{requestId:D})}(g))}catch(r){this._requeueFailedLogs(s),this.debug("uploadSSOLogData",_n(r))}finally{this._lastReportAt=Date.now()}})}_requeueFailedLogs(s){this._logQueue=s.concat(this._logQueue);const r=this._logQueue.length-200;r>0&&(this._logQueue.splice(0,r),this.debug("uploadSSOLogData",`log queue overflow, dropped ${r} oldest logs`))}_savePlatFormInfo(){var s,r;if(Xe){const g=(r=(s=wx.getAccountInfoSync)===null||s===void 0?void 0:s.call(wx))===null||r===void 0?void 0:r.miniProgram;if(g){const{appId:u,envVersion:E}=g;ro.set("instance",{appId:u,envVersion:E})}}else Ai&&ro.set("instance",{href:window.location.href})}_filterLogs(s){const{tinyID:r}=ro.get("login")||{},{sdkAppId:g}=ro.get("instance")||{};return this._sdkAppIdBlackList.includes(g)&&!this._tinyIdWhiteList.includes(r)?[]:s.filter(u=>this._reportLevel.includes(u.level))}_checkThrottle(s){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(s)}_checkGlobalThrottle(){const s=Date.now();if(s-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=s;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(s){const r=Date.now(),g=this._singleThrottleMap.get(s);return g?r-g.startTime>=this._throttleConfig.single.throttleTime?(g.count=1,g.startTime=r,!1):g.count>=this._throttleConfig.single.maxCount||(g.count++,!1):(this._singleThrottleMap.set(s,{count:1,startTime:r}),!1)}_shouldLog(s){return s>=this._logLevel&&this._logLevel!==IA.NONE}_shouldReport(s){return this._reportLevel.includes(qA[s])}_formatLog(s,r,g,u){const E=new Date,f=`${E.getHours()}:${E.getMinutes()}:${E.getSeconds()}:${E.getMilliseconds()}`,D=`<${IA[s]}>`;return Gt||Fi?[`${oA} [${f}] ${D} [${r}] ${g}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",oA,"",`[${f}] ${D} [${r}] ${g} params: ${_n(u)}`]}_log(s,r,g,u){if(this._shouldLog(s)){const E=this._formatLog(s,r,g,u);vA[s].apply(console,E)}if(this._shouldReport(s)){const E=this._getThrottleKey(r,g,u);this._checkThrottle(E)||this.createSSOLogData(Object.assign(Object.assign({message:g},u),{method:r})).end()}}_getThrottleKey(s,r,g){const u=`${s}${r}${_n(Object.assign(Object.assign({},g),{costTime:""}))}`,E=Fa(JSON.stringify(u));let f=4294967295;const{length:D}=E;for(let v=0;v>>=1:f=f>>>1^3988292384}return`${(4294967295^f)>>>0}`}reset(){console.log("SSO_LOG_MODULE.reset"),ws.removeTask(Nt),es.unSubscribeInnerEvent(Ke.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=qe,this._maxThreshold=100,this._waitingTime=Et,this._logQueue=[],this._logLevel=IA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const di=15e3,Bt="Channel",Jt="channel_schedule_task",$i="channel_reconnect_task",eo="connected",os="connecting",Ti="disconnected",on=1e3,_g="network_status_change",dr="activity_status_change",Mr="send_fail",js="reconnect_failed",Nl="socket_error",ns="socket_close";function uI(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function ec(s){return ec=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(r){return typeof r}:function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},ec(s)}function wc(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Tu,Na={exports:{}},Gl=(Tu||(Tu=1,function(s){s.exports=function r(g,u,E){function f(N,P){if(!u[N]){if(!g[N]){if(!P&&wc)return wc(N);if(D)return D(N,!0);var W=new Error("Cannot find module '"+N+"'");throw W.code="MODULE_NOT_FOUND",W}var nA=u[N]={exports:{}};g[N][0].call(nA.exports,function(EA){return f(g[N][1][EA]||EA)},nA,nA.exports,r,g,u,E)}return u[N].exports}for(var D=wc,v=0;v>>6:(EA<65536?nA[VA++]=224|EA>>>12:(nA[VA++]=240|EA>>>18,nA[VA++]=128|EA>>>12&63),nA[VA++]=128|EA>>>6&63),nA[VA++]=128|63&EA);return nA},u.buf2binstring=function(W){return P(W,W.length)},u.binstring2buf=function(W){for(var nA=new E.Buf8(W.length),EA=0,wA=nA.length;EA>10&1023,SA[wA++]=56320|1023&kA)}return P(SA,wA)},u.utf8border=function(W,nA){var EA;for((nA=nA||W.length)>W.length&&(nA=W.length),EA=nA-1;0<=EA&&(192&W[EA])==128;)EA--;return EA<0||EA===0?nA:EA+v[W[EA]]>nA?EA:nA}},{"./common":1}],3:[function(r,g,u){g.exports=function(E,f,D,v){for(var N=65535&E,P=E>>>16&65535,W=0;D!==0;){for(D-=W=2e3>>1:f>>>1;D[v]=f}return D}();g.exports=function(f,D,v,N){var P=E,W=N+v;f^=-1;for(var nA=N;nA>>8^P[255&(f^D[nA])];return-1^f}},{}],6:[function(r,g,u){g.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(r,g,u){g.exports=function(E,f){var D,v,N,P,W,nA,EA,wA,kA,VA,LA,SA,PA,zA,Ee,Ie,Li,Ui,Yt,Oi,Bn,Re,Mt,FA,ci;D=E.state,v=E.next_in,FA=E.input,N=v+(E.avail_in-5),P=E.next_out,ci=E.output,W=P-(f-E.avail_out),nA=P+(E.avail_out-257),EA=D.dmax,wA=D.wsize,kA=D.whave,VA=D.wnext,LA=D.window,SA=D.hold,PA=D.bits,zA=D.lencode,Ee=D.distcode,Ie=(1<>>=Yt=Ui>>>24,PA-=Yt,(Yt=Ui>>>16&255)==0)ci[P++]=65535&Ui;else{if(!(16&Yt)){if(!(64&Yt)){Ui=zA[(65535&Ui)+(SA&(1<>>=Yt,PA-=Yt),PA<15&&(SA+=FA[v++]<>>=Yt=Ui>>>24,PA-=Yt,!(16&(Yt=Ui>>>16&255))){if(!(64&Yt)){Ui=Ee[(65535&Ui)+(SA&(1<>>=Yt,PA-=Yt,(Yt=P-W)>3,SA&=(1<<(PA-=Oi<<3))-1,E.next_in=v,E.next_out=P,E.avail_in=v>>24&255)+(Re>>>8&65280)+((65280&Re)<<8)+((255&Re)<<24)}function SA(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new E.Buf16(320),this.work=new E.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function PA(Re){var Mt;return Re&&Re.state?(Mt=Re.state,Re.total_in=Re.total_out=Mt.total=0,Re.msg="",Mt.wrap&&(Re.adler=1&Mt.wrap),Mt.mode=wA,Mt.last=0,Mt.havedict=0,Mt.dmax=32768,Mt.head=null,Mt.hold=0,Mt.bits=0,Mt.lencode=Mt.lendyn=new E.Buf32(kA),Mt.distcode=Mt.distdyn=new E.Buf32(VA),Mt.sane=1,Mt.back=-1,nA):EA}function zA(Re){var Mt;return Re&&Re.state?((Mt=Re.state).wsize=0,Mt.whave=0,Mt.wnext=0,PA(Re)):EA}function Ee(Re,Mt){var FA,ci;return Re&&Re.state?(ci=Re.state,Mt<0?(FA=0,Mt=-Mt):(FA=1+(Mt>>4),Mt<48&&(Mt&=15)),Mt&&(Mt<8||15=Pi.wsize?(E.arraySet(Pi.window,Mt,FA-Pi.wsize,Pi.wsize,0),Pi.wnext=0,Pi.whave=Pi.wsize):(ci<(xn=Pi.wsize-Pi.wnext)&&(xn=ci),E.arraySet(Pi.window,Mt,FA-ci,xn,Pi.wnext),(ci-=xn)?(E.arraySet(Pi.window,Mt,FA-ci,ci,0),Pi.wnext=ci,Pi.whave=Pi.wsize):(Pi.wnext+=xn,Pi.wnext===Pi.wsize&&(Pi.wnext=0),Pi.whave>>8&255,FA.check=D(FA.check,Qg,2,0),Ft=Ut=0,FA.mode=2;break}if(FA.flags=0,FA.head&&(FA.head.done=!1),!(1&FA.wrap)||(((255&Ut)<<8)+(Ut>>8))%31){Re.msg="incorrect header check",FA.mode=30;break}if((15&Ut)!=8){Re.msg="unknown compression method",FA.mode=30;break}if(Ft-=4,ja=8+(15&(Ut>>>=4)),FA.wbits===0)FA.wbits=ja;else if(ja>FA.wbits){Re.msg="invalid window size",FA.mode=30;break}FA.dmax=1<>8&1),512&FA.flags&&(Qg[0]=255&Ut,Qg[1]=Ut>>>8&255,FA.check=D(FA.check,Qg,2,0)),Ft=Ut=0,FA.mode=3;case 3:for(;Ft<32;){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>>8&255,Qg[2]=Ut>>>16&255,Qg[3]=Ut>>>24&255,FA.check=D(FA.check,Qg,4,0)),Ft=Ut=0,FA.mode=4;case 4:for(;Ft<16;){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>8),512&FA.flags&&(Qg[0]=255&Ut,Qg[1]=Ut>>>8&255,FA.check=D(FA.check,Qg,2,0)),Ft=Ut=0,FA.mode=5;case 5:if(1024&FA.flags){for(;Ft<16;){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>>8&255,FA.check=D(FA.check,Qg,2,0)),Ft=Ut=0}else FA.head&&(FA.head.extra=null);FA.mode=6;case 6:if(1024&FA.flags&&(ji<(Do=FA.length)&&(Do=ji),Do&&(FA.head&&(ja=FA.head.extra_len-FA.length,FA.head.extra||(FA.head.extra=new Array(FA.head.extra_len)),E.arraySet(FA.head.extra,ci,Pi,Do,ja)),512&FA.flags&&(FA.check=D(FA.check,ci,Do,Pi)),ji-=Do,Pi+=Do,FA.length-=Do),FA.length))break A;FA.length=0,FA.mode=7;case 7:if(2048&FA.flags){if(ji===0)break A;for(Do=0;ja=ci[Pi+Do++],FA.head&&ja&&FA.length<65536&&(FA.head.name+=String.fromCharCode(ja)),ja&&Do>9&1,FA.head.done=!0),Re.adler=FA.check=0,FA.mode=12;break;case 10:for(;Ft<32;){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>>=7&Ft,Ft-=7&Ft,FA.mode=27;break}for(;Ft<3;){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>>=1)){case 0:FA.mode=14;break;case 1:if(Oi(FA),FA.mode=20,Mt!==6)break;Ut>>>=2,Ft-=2;break A;case 2:FA.mode=17;break;case 3:Re.msg="invalid block type",FA.mode=30}Ut>>>=2,Ft-=2;break;case 14:for(Ut>>>=7&Ft,Ft-=7&Ft;Ft<32;){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>>16^65535)){Re.msg="invalid stored block lengths",FA.mode=30;break}if(FA.length=65535&Ut,Ft=Ut=0,FA.mode=15,Mt===6)break A;case 15:FA.mode=16;case 16:if(Do=FA.length){if(ji>>=5,Ft-=5,FA.ndist=1+(31&Ut),Ut>>>=5,Ft-=5,FA.ncode=4+(15&Ut),Ut>>>=4,Ft-=4,286>>=3,Ft-=3}for(;FA.have<19;)FA.lens[CS[FA.have++]]=0;if(FA.lencode=FA.lendyn,FA.lenbits=7,kI={bits:FA.lenbits},jl=N(0,FA.lens,0,19,FA.lencode,0,FA.work,kI),FA.lenbits=kI.bits,jl){Re.msg="invalid code lengths set",FA.mode=30;break}FA.have=0,FA.mode=19;case 19:for(;FA.have>>16&255,bI=65535&qg,!((Gr=qg>>>24)<=Ft);){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>>=Gr,Ft-=Gr,FA.lens[FA.have++]=bI;else{if(bI===16){for(nE=Gr+2;Ft>>=Gr,Ft-=Gr,FA.have===0){Re.msg="invalid bit length repeat",FA.mode=30;break}ja=FA.lens[FA.have-1],Do=3+(3&Ut),Ut>>>=2,Ft-=2}else if(bI===17){for(nE=Gr+3;Ft>>=Gr)),Ut>>>=3,Ft-=3}else{for(nE=Gr+7;Ft>>=Gr)),Ut>>>=7,Ft-=7}if(FA.have+Do>FA.nlen+FA.ndist){Re.msg="invalid bit length repeat",FA.mode=30;break}for(;Do--;)FA.lens[FA.have++]=ja}}if(FA.mode===30)break;if(FA.lens[256]===0){Re.msg="invalid code -- missing end-of-block",FA.mode=30;break}if(FA.lenbits=9,kI={bits:FA.lenbits},jl=N(P,FA.lens,0,FA.nlen,FA.lencode,0,FA.work,kI),FA.lenbits=kI.bits,jl){Re.msg="invalid literal/lengths set",FA.mode=30;break}if(FA.distbits=6,FA.distcode=FA.distdyn,kI={bits:FA.distbits},jl=N(W,FA.lens,FA.nlen,FA.ndist,FA.distcode,0,FA.work,kI),FA.distbits=kI.bits,jl){Re.msg="invalid distances set",FA.mode=30;break}if(FA.mode=20,Mt===6)break A;case 20:FA.mode=21;case 21:if(6<=ji&&258<=Qr){Re.next_out=Vr,Re.avail_out=Qr,Re.next_in=Pi,Re.avail_in=ji,FA.hold=Ut,FA.bits=Ft,v(Re,hs),Vr=Re.next_out,xn=Re.output,Qr=Re.avail_out,Pi=Re.next_in,ci=Re.input,ji=Re.avail_in,Ut=FA.hold,Ft=FA.bits,FA.mode===12&&(FA.back=-1);break}for(FA.back=0;Jg=(qg=FA.lencode[Ut&(1<>>16&255,bI=65535&qg,!((Gr=qg>>>24)<=Ft);){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>Ec)])>>>16&255,bI=65535&qg,!(Ec+(Gr=qg>>>24)<=Ft);){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>>=Ec,Ft-=Ec,FA.back+=Ec}if(Ut>>>=Gr,Ft-=Gr,FA.back+=Gr,FA.length=bI,Jg===0){FA.mode=26;break}if(32&Jg){FA.back=-1,FA.mode=12;break}if(64&Jg){Re.msg="invalid literal/length code",FA.mode=30;break}FA.extra=15&Jg,FA.mode=22;case 22:if(FA.extra){for(nE=FA.extra;Ft>>=FA.extra,Ft-=FA.extra,FA.back+=FA.extra}FA.was=FA.length,FA.mode=23;case 23:for(;Jg=(qg=FA.distcode[Ut&(1<>>16&255,bI=65535&qg,!((Gr=qg>>>24)<=Ft);){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>Ec)])>>>16&255,bI=65535&qg,!(Ec+(Gr=qg>>>24)<=Ft);){if(ji===0)break A;ji--,Ut+=ci[Pi++]<>>=Ec,Ft-=Ec,FA.back+=Ec}if(Ut>>>=Gr,Ft-=Gr,FA.back+=Gr,64&Jg){Re.msg="invalid distance code",FA.mode=30;break}FA.offset=bI,FA.extra=15&Jg,FA.mode=24;case 24:if(FA.extra){for(nE=FA.extra;Ft>>=FA.extra,Ft-=FA.extra,FA.back+=FA.extra}if(FA.offset>FA.dmax){Re.msg="invalid distance too far back",FA.mode=30;break}FA.mode=25;case 25:if(Qr===0)break A;if(Do=hs-Qr,FA.offset>Do){if((Do=FA.offset-Do)>FA.whave&&FA.sane){Re.msg="invalid distance too far back",FA.mode=30;break}Do>FA.wnext?(Do-=FA.wnext,Bl=FA.wsize-Do):Bl=FA.wnext-Do,Do>FA.length&&(Do=FA.length),GC=FA.window}else GC=xn,Bl=Vr-FA.offset,Do=FA.length;for(QrLi?(Yt=Bl[GC+VA[Mt]],Oi=Ft[oE+VA[Mt]]):(Yt=96,Oi=0),SA=1<>Vr)+(PA-=SA)]=Ui<<24|Yt<<16|Oi,PA!==0;);for(SA=1<>=1;if(SA!==0?(Ut&=SA-1,Ut+=SA):Ut=0,Mt++,--hs[Re]==0){if(Re===ci)break;Re=W[nA+VA[Mt]]}if(xn{const v=new Uint8Array(D).slice(4);let N;try{N=Gl.inflate(v,{to:"string"})}catch(P){console.error("inflate error",P)}return N})(s.data):function(D){const v=new Uint8Array(D);let N="",P=0;const{length:W}=v;for(;P0)for(let kA=0;kA{var u;const{uplinkData:E,canResend:f,resolve:D,reject:v,timeout:N}=r;if(f){this._pendingRequests.set(g,{resolve:D,reject:v,timestamp:Date.now(),uplinkData:E,timeout:N,canResend:f});const P=this._isBinarySupported?Fa(E).buffer:E;(u=this._socketAdapter)===null||u===void 0||u.send(P)}else this._pendingRequests.delete(g)})}_onConnect(s){const{socketId:r,event:g={}}=s||{};this._connectionId=r,this._connectionEstablishedTime=Date.now();const u=Date.now()-this._connectionStartTime,E=`${Bt}.onConnect cost:${u} ms. socketID:${r} res:${JSON.stringify(g)}`;if(this._ssoLog({method:"onConnect",message:E}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const f=`${Bt}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:f}),es.emitInnerEvent(Ke.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:eo,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(s){const r=pa({servcmd:"openim.ws_msg_push_ack",data:{SessionData:s}});this.sendPacket(r)}_executeScheduledTaskIfReady(){return mA(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var s;return((s=this._socketAdapter)===null||s===void 0?void 0:s.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return mA(this,void 0,void 0,function*(){var s;const r=pa({servcmd:"heartbeat.alive",data:{}});try{const g=`${r.head.seq}${r.head.servcmd}`;yield this.sendPacket(r,{requestId:g,timeout:3e3})}catch(g){const u=(s=ro.get("netWorkMonitor"))===null||s===void 0?void 0:s.isNetworkOnline,E=`${Bt}.sendHeartbeat failed. isNetWorkOnline:${u} error: ${_n(g)}`;this._ssoLog({method:"sendHeartbeatError",message:E}),this._handleConnectStateChange({state:Ti,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return mA(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=ao?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(s){const r=`${Bt}.networkStatusChange ${JSON.stringify(s)}`;this._ssoLog({method:"networkStatusChange",message:r});const{isNetworkOnline:g,networkType:u}=s;g&&u!=="none"?this._handleConnectStateChange({state:eo,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:_g}):this._handleConnectStateChange({state:Ti,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:_g})}isPrivateNetWork(){const s=ro.get("instance")||{};return s.proxyServer&&!s.fileDownloadProxy}_handleConnectStateChange(s){const{state:r,shouldAttemptReconnect:g,shouldEmitEvent:u,reason:E}=s,f=`${Bt}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${g} shouldEmitEvent: ${u} reason: ${E}`;this._currentConnectState!==r&&(this._ssoLog({method:"handleConnectStateChange",message:f}),u&&(Kt.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${r}`),es.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:r}}),this._currentConnectState=r,r===Ti&&es.emitInnerEvent(Ke.SOCKET_DISCONNECTED)),g&&(this._resetReconnectDelay(),ws.addTask({id:$i,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(s){var r,g;const u=(g=(r=this._socketAdapter)===null||r===void 0?void 0:r._ws)===null||g===void 0?void 0:g.readyState,E=`${Bt}.activityStatusChange ${JSON.stringify(s)} readyState: ${u}`;Kt.debug("activityStatusChange",E),u===3&&this._handleConnectStateChange({state:Ti,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:dr})}_resetReconnectDelay(){var s;Kt.debug(`${Bt}._resetReconnectDelay`),ws.removeTask($i);const r=(s=ro.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=r?on:1e3}_scheduleReconnectWithBackoff(){var s;const r=(s=ro.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=r?Math.min(5e3,Math.max(on,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const g=new Date().toTimeString().slice(0,8),u=`${Bt}.scheduleReconnectWithBackoff timeStr: ${g} intendedDelay: ${this._intendedDelay}`;Kt.debug(u),this.reconnect(),ws.updateTaskInterval($i,this._intendedDelay)}_ssoLog(s){const{method:r,message:g}=s;Kt.info(r,g)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(s){mA(this,void 0,void 0,function*(){const r=s.split("/")[2];if(!r.startsWith("ws"))return;const g=`https://${r}/v3/netcheck/getconninfo?${s.slice(s.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield qi({method:"GET",url:g,data:{}})}catch(u){Kt.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${u.message}`)}})}(this._url),function(s){mA(this,void 0,void 0,function*(){const r=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${s.slice(s.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield qi({method:"GET",url:r,data:{}})}catch(g){Kt.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${g.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[s,r]of this._pendingRequests.entries()){const{reject:g,timestamp:u,timeout:E}=r;Date.now()-u>=E&&(this._pendingRequests.delete(s),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),g({errorCode:Zs,errorInfo:"NETWORK_TIMEOUT",data:{requestId:s}}))}}_updateIsBinarySupported(){var s;if(!((s=ro.get("instance"))===null||s===void 0)&&s.devMode)return void(this._isBinarySupported=!1);const r=Vo();if((ii||Xe&&r==="windows"||wn)&&(this._isBinarySupported=!1),ao){const{uniRuntimeVersion:g=""}=no.getSystemInfoSync();(function(u){const E=u.split(".").map(Number),[f=0,D=0,v=0]=E;return f>2||!(f<2)&&(D>2||!(D<2)&&v>=6)})(g)||(this._isBinarySupported=!1)}}_isCompressedData(s){const r=new Uint8Array(s);return r[0]===67&&r[1]===79&&r[2]===77&&r[3]===80}};const Se={init:function(s){ro.set("instance",s),ve.init()},destroy:function(){ve.dispose(),ro.clear(),ws.dispose()},notificationCenter:es,channel:ve,store:ro,ssoLog:Kt,utils:$a,common:RA,constants:we},Tg=s=>typeof s=="function";function lg(s,r,g){const u=g||[];if(!s||!r)return!1;const E=Object.keys(s).filter(D=>!u.includes(D)),f=Object.keys(r).filter(D=>!u.includes(D));return E.length===f.length&&E.every(D=>!!r.hasOwnProperty(D)&&(typeof s[D]=="object"&&s[D]!==null?lg(s[D],r[D],g):s[D]===r[D]))}var Ng;(function(s){s.SDK_READY="sdkStateReady",s.SDK_NOT_READY="sdkStateNotReady",s.SDK_DESTROY="sdkDestroy",s.MESSAGE_RECEIVED="onMessageReceived",s.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",s.MESSAGE_MODIFIED="onMessageModified",s.MESSAGE_REVOKED="onMessageRevoked",s.MESSAGE_READ_BY_PEER="onMessageReadByPeer",s.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",s.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",s.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",s.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",s.CONVERSATION_LIST_UPDATED="onConversationListUpdated",s.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",s.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",s.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",s.GROUP_LIST_UPDATED="onGroupListUpdated",s.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",s.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",s.TOPIC_CREATED="onTopicCreated",s.TOPIC_DELETED="onTopicDeleted",s.TOPIC_UPDATED="onTopicUpdated",s.PROFILE_UPDATED="onProfileUpdated",s.USER_STATUS_UPDATED="onUserStatusUpdated",s.BLACKLIST_UPDATED="blacklistUpdated",s.FRIEND_LIST_UPDATED="onFriendListUpdated",s.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",s.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",s.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",s.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",s.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",s.KICKED_OUT="kickedOut",s.ERROR="error",s.NET_STATE_CHANGE="netStateChange",s.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",s.SERVER_CONFIG_UPDATED="onServerConfigUpdated",s.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated",s.WEB_PUSH_MESSAGE_RECEIVED="onWebPushMessageReceived",s.GROUP_ONLINE_MEMBER_COUNT_CHANGED="onGroupOnlineMemberCountChanged",s.RICH_STATUS_CHANGED="onRichStatusChanged"})(Ng||(Ng={}));var Ts,Rr=Ng;(function(s){s.LOGOUT="logout",s.DESTROY="destroy",s.CLOUD_CONFIG_UPDATE="cloud_config_update",s.PROFILE_UPDATE="profile_updated",s.ERROR="error",s.RECONNECTED="reconnected",s.FORCE_OFFLINE="im_open_status.stat_forceoffline",s.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",s.OVERLOAD_PUSH="OverLoadPush.notify2",s.NEW_MESSAGE="new_message",s.MESSAGE_PUSH="im_open_push.msg_push",s.MESSAGE_DELETED="message_deleted",s.MESSAGE_REVOKED="message_revoked",s.MESSAGE_MODIFIED="message_modified",s.SOCKET_DISCONNECTED="socket_disconnected",s.CONVERSATION_UPDATED="conversation_updated",s.TOPIC_MESSAGE_DELETED="topic_message_deleted",s.TOPIC_MESSAGE_REVOKED="topic_message_revoked",s.TOPIC_MESSAGE_MODIFIED="topic_message_modified",s.TOPIC_NEW_MESSAGE="topic_new_message",s.QUALITY_STAT="quality_stat",s.SYNC_CONVERSATION_LIST="sync_conversation_list",s.HISTORY_MESSAGE_FETCHED="history_message_fetched"})(Ts||(Ts={}));var Ci,lo=Ts;(function(s){s.NEW_INVITATION_RECEIVED="newInvitationReceived",s.INVITEE_ACCEPTED="ts_invitee_accepted",s.INVITEE_REJECTED="ts_invitee_rejected",s.INVITATION_CANCELLED="ts_invitation_cancelled",s.INVITATION_TIMEOUT="ts_invitation_timeout",s.INVITATION_MODIFIED="ts_invitation_modified"})(Ci||(Ci={}));var Xc=Ci;const tc=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),Gg={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem",MSG_STREAM:"TIMStreamElem"};var qr;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(qr||(qr={}));const _c={modify:lo.MESSAGE_MODIFIED,delete:lo.MESSAGE_DELETED,revoke:lo.MESSAGE_REVOKED};var $c;(function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"})($c||($c={}));const Ig=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Gg),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:qr,Direction:$c}),Nu={[_c.modify]:lo.TOPIC_MESSAGE_MODIFIED,[_c.delete]:lo.TOPIC_MESSAGE_DELETED,[_c.revoke]:lo.TOPIC_MESSAGE_REVOKED},ME={GENDER_UNKNOWN:"Gender_Type_Unknown",GENDER_FEMALE:"Gender_Type_Female",GENDER_MALE:"Gender_Type_Male",USER_STATUS_UNKNOWN:0,USER_STATUS_ONLINE:1,USER_STATUS_OFFLINE:2,USER_STATUS_UNLOGINED:3,USER_NOT_FOUND:"@TLS#NOT_FOUND"},bg=Object.assign({},ME),Pa={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},Tc=Object.assign(Object.assign(Object.assign(Object.assign({},Pa),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),RE=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),xa={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},ga={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},kg={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},EI=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},xa),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),{GROUP_ID_PREFIX:ga,GROUP_TIPS_OPERATION_TYPE:kg}),Sn={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},Po=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},tc),Ig),bg),Tc),RE),EI),Sn),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),ma={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},Cr={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},jt={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message",RECEIVE_GROUP_TIPS_NOTIFICATION:"receive-group-tips-notification"},Xt={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover",HANDLE_GROUP_TIPS_NOTIFICATION:"handle-group-tips-notification",C2C_HISTORY_MESSAGE_RECOVER:"c2c-history-message-recover",FRIEND_APPLICATION_LIST_RECOVER:"friend-application-list-recover",EMIT_GROUP_TIPS_EVENT:"emit-group-tips-event",STREAM_MESSAGE_RECOVER:"stream-message-recover"},Lg={[jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:Xt.USER_STATUS_UPDATE},{stepId:Xt.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:Xt.UNREAD_MESSAGE_SYNC,dependency:Xt.C2C_HISTORY_MESSAGE_RECOVER},{stepId:Xt.CONVERSATION_RECOVER},{stepId:Xt.HISTORY_MESSAGE_RECOVER,dependency:Xt.CONVERSATION_RECOVER},{stepId:Xt.BLACKLIST_RECOVER},{stepId:Xt.FRIEND_RECOVER},{stepId:Xt.FRIEND_APPLICATION_LIST_RECOVER},{stepId:Xt.GROUP_REVOKED_NOTICE_RECOVER,dependency:Xt.HISTORY_MESSAGE_RECOVER},{stepId:Xt.GROUP_TIPS_RECOVER,dependency:Xt.HISTORY_MESSAGE_RECOVER},{stepId:Xt.TOPIC_REQUEST_INFO_RESET},{stepId:Xt.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:Xt.UNREAD_MESSAGE_SYNC},{stepId:Xt.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:Xt.UNREAD_MESSAGE_SYNC},{stepId:Xt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Xt.UNREAD_MESSAGE_SYNC,Xt.CONVERSATION_RECOVER]},{stepId:Xt.EMIT_C2C_MESSAGE_EVENT,dependency:[Xt.UNREAD_MESSAGE_SYNC,Xt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:Xt.C2C_HISTORY_MESSAGE_RECOVER,dependency:Xt.CONVERSATION_RECOVER},{stepId:Xt.STREAM_MESSAGE_RECOVER}],[jt.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:Xt.COMMERCIAL_CONFIG_UPDATE},{stepId:Xt.CLOUD_CONFIG_SYNC},{stepId:Xt.USER_PROFILE_SYNC},{stepId:Xt.UNREAD_MESSAGE_SYNC},{stepId:Xt.FRIEND_AND_BLACKLIST_SYNC},{stepId:Xt.GROUP_LIST_SYNC},{stepId:Xt.CONVERSATION_LIST_SYNC},{stepId:Xt.SIGNALING_MESSAGE_RECOVER,dependency:Xt.UNREAD_MESSAGE_SYNC},{stepId:Xt.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[Xt.UNREAD_MESSAGE_SYNC]},{stepId:Xt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Xt.UNREAD_MESSAGE_SYNC,Xt.CONVERSATION_LIST_SYNC]},{stepId:Xt.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[Xt.GROUP_LIST_SYNC,Xt.CONVERSATION_LIST_SYNC]},{stepId:Xt.CONVERSATION_GROUP_LIST_SYNC},{stepId:Xt.CONVERSATION_GROUP_UPDATE,dependency:[Xt.CONVERSATION_LIST_SYNC,Xt.CONVERSATION_GROUP_LIST_SYNC]},{stepId:Xt.QUALITY_REPORT}],[jt.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:Xt.HANDLE_C2C_NEW_MESSAGE},{stepId:Xt.UNREAD_MESSAGE_SYNC},{stepId:Xt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Xt.HANDLE_C2C_NEW_MESSAGE},{stepId:Xt.EMIT_C2C_MESSAGE_EVENT,dependency:[Xt.HANDLE_C2C_NEW_MESSAGE,Xt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:Xt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Xt.UNREAD_MESSAGE_SYNC]}],[jt.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:Xt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Xt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Xt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Xt.UPDATE_GROUP_NEXT_SEQUENCE,dependency:Xt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Xt.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:Xt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Xt.EMIT_GROUP_MESSAGE_EVENT,dependency:[Xt.HANDLE_GROUP_NEW_MESSAGE,Xt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[jt.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:Xt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Xt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Xt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Xt.EMIT_GROUP_TIPS_EVENT,dependency:[Xt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,Xt.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},dI={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},hr={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},zI=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","sendMessageReadReceipt","getMessageReadReceiptList","getGroupMessageReadMemberList","createMergerMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var Ag=Object.freeze({__proto__:null,ERROR_CODE:ma,InnerEvent:lo,NEED_LOG_API:zI,OuterConstant:Po,OuterEvent:Rr,PUSH:Sn,QUALITY_METRICS:dI,SDK_EDITION:Cr,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:hr,SignalingEvent:Xc,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Lg,WORKFLOW_NAME:jt,WORKFLOW_STEP:Xt}),ca,ps,Ns;(function(s){s[s.USER_INITIATED=0]="USER_INITIATED",s[s.KICKED_OUT=1]="KICKED_OUT"})(ca||(ca={})),function(s){s[s.multipleAccount=1]="multipleAccount",s[s.multipleDevice=2]="multipleDevice",s[s.restApi=3]="restApi"}(ps||(ps={})),function(s){s[s.multipleDevice=3002]="multipleDevice",s[s.multipleAccount=3003]="multipleAccount",s[s.usersigExpired=70001]="usersigExpired",s[s.restApi=20002]="restApi"}(Ns||(Ns={}));const Gu={[ps.multipleAccount]:"multipleAccount",[ps.multipleDevice]:"multipleDevice",[ps.restApi]:"REST_API_Kick",[Ns.multipleAccount]:"multipleAccount",[Ns.multipleDevice]:"multipleDevice",[Ns.restApi]:"REST_API_Kick",[Ns.usersigExpired]:"userSigExpired"},Ug="login_online_presence_task",{ERROR:Ya,DESTROY:Al,FORCE_OFFLINE:ZI}=lo,{KICKED_OUT_MULT_ACCOUNT:wE,KICKED_OUT_MULT_DEVICE:CI,KICKED_OUT_REST_API:bu,ACCOUNT_A2KEY_EXPIRED:bl,MSG_A2KEY_EXPIRED:Nc}=ma;class ku{init(){const{notificationCenter:r}=Se;r.subscribeInnerEvent(ZI,this._handleForceOfflineFromServerPush,this),r.subscribeInnerEvent(Ya,Nc,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),r.subscribeInnerEvent(Ya,bl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),r.subscribeInnerEvent(Ya,wE,this._handleForceOfflineFromResponse,this),r.subscribeInnerEvent(Ya,CI,this._handleForceOfflineFromResponse,this),r.subscribeInnerEvent(Ya,bu,this._handleForceOfflineFromResponse,this),r.subscribeInnerEvent(Al,this._dispose,this)}_handleForceOfflineFromServerPush(r){var g;if(((g=Se.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)===!0){const{EventArray:u=[]}=r?.body||{};this._extractKickedOutMessages(u).forEach(E=>{const{KickoutMsgNotify:{KickType:f,NewInstInfo:D,Instid:v}}=E;this._isCurrentInstanceKickedOut(v)&&this._processKickedOutReasonInfo({kickedOutReasonCode:f,newInstanceInfo:D})})}}_extractKickedOutMessages(r){return r.reduce((g,u)=>[...g,...u.C2cNotifyMsgArray||[]],[]).filter(g=>{var u;return this._isKickedOut((u=g?.KickoutMsgNotify)===null||u===void 0?void 0:u.KickType)})}_handleForceOfflineFromResponse(r){const{errorCode:g}=r;this._processKickedOutReasonInfo({kickedOutReasonCode:g})}_processKickedOutReasonInfo(r){return mA(this,void 0,void 0,function*(){const{kickedOutReasonCode:g}=r,{ssoLog:u,utils:{safeStringify:E}}=Se;try{this._logKickedOutEvent(r),this._shouldLogoutAfterKickedOut(g)?yield Se.login.loginAction.logout(ca.KICKED_OUT):Se.login.loginAction.handleLogoutCompleted()}catch(f){u.debug("_processKickedOutReasonInfo",` fail ${E(f)}`)}finally{Se.notificationCenter.emitOuterEvent(Rr.KICKED_OUT,{data:{type:Gu[g]},name:Rr.KICKED_OUT})}})}_logKickedOutEvent(r){const{kickedOutReasonCode:g,newInstanceInfo:u={}}=r,E=`type:${Gu[g]} newInstanceInfo: ${JSON.stringify(u)}`;Se.ssoLog.warn("kickedOut",E)}_isKickedOut(r){return[ps.multipleAccount,ps.multipleDevice,ps.restApi].includes(r)}_isChatLoginEvent(r){const{requestHead:g}=r||{};return g?.idtype!==1}_shouldLogoutAfterKickedOut(r){return![Ns.usersigExpired,ps.restApi].includes(r)}_isCurrentInstanceKickedOut(r){const{isLoggedIn:g,statusInstanceId:u}=Se.store.get("login")||{};return g===!0&&r===u}_dispose(){const{notificationCenter:r}=Se;r.unSubscribeInnerEvent(ZI,this._handleForceOfflineFromServerPush,this),r.unSubscribeInnerEvent(Ya,bl,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Ya,Nc,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Ya,wE,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Ya,CI,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Ya,bu,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Al,this._dispose,this)}}function Lu(s){return mA(this,void 0,void 0,function*(){const r="im_open_status.wslogin",g=Se.common.generateProtocolData({servcmd:r,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:s}}),u=`${g.head.seq}${r}`,E=yield Se.channel.sendPacket(g,{timeout:9e4,requestId:u});if(E){const{HelloInterval:f,InstId:D,TinyId:v,TimeStamp:N,CustomStatus:P,PurchaseBits:W,A2Key:nA,RichMsgAuthKey:EA,ErrorCode:wA,ErrorInfo:kA,ActionStatus:VA}=E;return{helloInterval:f,instanceID:D,tinyID:v,timeStamp:N,customStatus:P,purchaseBits:W,a2Key:nA,authKey:EA,errorCode:wA,errorInfo:kA,actionStatus:VA}}})}function kl(){const{store:s}=Se;return Qa(s.get("instance").sdkAppId)!==Ye.CHINA}function dn(s){var r;try{const g=ro.getStorage("errorMessage");if(!s||!g)return"";const u=((r=JSON.parse(g))===null||r===void 0?void 0:r.errorMessage)||{},{code:E,replacement1:f="",replacement2:D=""}=s;if(!E)return"";const v=kl()?`${E}_en`:`${E}_cn`;let N=u[u[v]?v:E]||"";return N&&(f&&(N=N.replace("$replacement1",f)),D&&(N=N.replace("$replacement2",D))),N}catch(g){return console.warn("Error parsing stored error messages:",g),""}}class hn extends Error{constructor(r={}){r.code=r.code||r.errorCode;let{functionName:g="Unknown",code:u,message:E="",data:f="",moreMessage:D="",errorMessage:v=""}=r;v=(u?dn(r):"")||v||E;let N=u?`${g} failed. error: {"message": ${v}, "code": ${u}}`:`${g} failed. error: {"message": ${v}}`;N=`${N} ${D}`,super(),this.code=u,this.errorCode=u,this.errorMessage=v,this.message=N,this.data=f}}function dd(s,r){var g;if(s&&((g=Se.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)!==!0)throw new hn({code:ma.USER_NOT_LOGGED_IN,functionName:r})}function hI(s,r,g){if(Array.isArray(s))for(let u=0;u{return P===(W=u,Object.prototype.toString.call(W).match(/^\[object (.*)\]$/)[1].toLowerCase());var W})){for(let W=0;W{const{interceptor:E,context:f}=u;E.apply(f,[g])})}(s)}function Gc(s,r){_E.push({interceptor:s,context:r})}function el(s){const{params:r,auth:g}=s;r&&typeof r=="object"&&Object.assign(Ll,r),g&&typeof g=="object"&&Object.assign(Cd,g)}function us(s){return Se.store.get("commercialConfig").get(s)}class Pn{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(r,g)=>{const u=Date.now();g?(this._stepStartTimes.set(`${r}-${g}`,u),Se.ssoLog.debug("_executeWorkflowStep",`[Workflow ${r}] Step ${g} started at ${new Date(u).toISOString()}`)):(this._workflowStartTimes.set(r,u),Se.ssoLog.debug("_executeWorkflowStep",`[Workflow ${r}] started at ${new Date(u).toISOString()}`))},success:(r,g)=>{const u=Date.now();if(g){const E=this._stepStartTimes.get(`${r}-${g}`),f=E?u-E:0;this._stepStartTimes.delete(`${r}-${g}`),Se.ssoLog.debug("_executeWorkflowStep",`[Workflow ${r}] Step ${g} completed successfully at ${new Date(u).toISOString()} (${f}ms)`)}else{const E=this._workflowStartTimes.get(r),f=E?u-E:0;this._workflowStartTimes.delete(r),Se.ssoLog.debug("_executeWorkflowStep",`[Workflow ${r}] completed successfully at ${new Date(u).toISOString()} (${f}ms)`)}},error:(r,g,u)=>{const{ssoLog:E,utils:{safeStringify:f}}=Se,D=Date.now();if(g){const v=this._stepStartTimes.get(`${r}-${g}`),N=v?D-v:0;this._stepStartTimes.delete(`${r}-${g}`),E.error("_executeWorkflowStep",`[Workflow ${r}] Step ${g} failed at ${new Date(D).toISOString()} (${N}ms) ${f(u)}`,{error:u})}else{const v=this._workflowStartTimes.get(r),N=v?D-v:0;this._workflowStartTimes.delete(r),E.error("_executeWorkflowStep",`[Workflow ${r}] failed at ${new Date(D).toISOString()} (${N}ms) ${f(u)}`,{error:u})}}}}static getInstance(){return Pn._instance||(Pn._instance=new Pn),Pn._instance}static setInstance(r){Pn._instance=r}init(){this._initializeWorkflows()}registerWorkflowStep(r,g,u,E){if(!this._handlers.has(r))return void Se.ssoLog.debug("registerWorkflowStep",`Workflow '${r}' not defined in core`);if(!Lg[r].find(D=>D.stepId===g))return void Se.ssoLog.debug("registerWorkflowStep",`Step '${g}' not defined in workflow '${r}'`);const f=this._handlers.get(r);f.has(g)||f.set(g,E?u.bind(E):u)}executeWorkflow(r,g){return mA(this,void 0,void 0,function*(){if(!this._validateWorkflow(r))return;Se.ssoLog.debug("executeWorkflow",`[Workflow ${r}] Started execution at ${new Date().toISOString()}`);const u=Lg[r],E={},f={cancelled:!1};this._activeWorkflows.set(r,{cancelToken:f});try{const D=new Map;u.forEach(N=>{D.set(N.stepId,N)});const v={workflowName:r,pendingSteps:new Set(u.map(N=>N.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:D,stepResults:E,data:g,cancelToken:f};yield new Promise((N,P)=>{const W=()=>{if(f.cancelled)return void N();this._getExecutableSteps({pendingSteps:v.pendingSteps,completedSteps:v.completedSteps,stepMap:v.stepMap,workflowName:r}).filter(nA=>!v.runningSteps.has(nA)).forEach(nA=>{v.completedSteps.has(nA)||v.runningSteps.has(nA)||this._executeWorkflowStep(nA,v,{onComplete:()=>{if(v.pendingSteps.size===0)return void N();this._getExecutableSteps({pendingSteps:v.pendingSteps,completedSteps:v.completedSteps,stepMap:v.stepMap,workflowName:r}).filter(EA=>!v.runningSteps.has(EA)).length===0&&v.runningSteps.size===0&&(Se.ssoLog.debug("executeWorkflow",`Workflow ${r} completed with some steps skipped due to dependency failures`),N())},onError:P,onStepComplete:W})})};W()}),Se.ssoLog.debug("executeWorkflow",`[Workflow ${r}] Completed execution at ${new Date().toISOString()}`)}catch(D){Se.ssoLog.error("executeWorkflow",`[Workflow ${r}] Failed execution at ${new Date().toISOString()}`,{error:D})}finally{this._activeWorkflows.delete(r)}})}_executeWorkflowStep(r,g,u){return mA(this,void 0,void 0,function*(){const{workflowName:E,runningSteps:f,stepMap:D,stepResults:v,data:N}=g;f.add(r),this._logWorkflowExecution(E,r,"start");try{const P=D.get(r);let W=null;P?.dependency&&(c(P.dependency)?W=v[P.dependency]:Array.isArray(P.dependency)&&(W={},P.dependency.forEach(EA=>{W[EA]=v[EA]})));const nA=this._handlers.get(E).get(r);if(nA){const EA=yield Promise.resolve(nA({data:N,result:W}));v[r]=EA,this._logWorkflowExecution(E,r,"success")}g.completedSteps.add(r)}catch(P){const W=`[Workflow].${E}.${r}`,{errorCode:nA,errorInfo:EA=`${W} failed`}=P||{},wA=new hn({functionName:W,code:nA,message:EA});Se.ssoLog.error(W,EA,{error:wA}),this._logWorkflowExecution(E,r,"error",P),u.onError(P)}finally{f.delete(r),g.pendingSteps.delete(r),u.onStepComplete(),u.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Lg).forEach(r=>{this._handlers.has(r)||this._handlers.set(r,new Map)})}_cancelWorkFlow(r){const g=this._activeWorkflows.get(r);if(!g)return;const{cancelToken:u}=g;u.cancelled=!0,this._activeWorkflows.delete(r)}_cancelAllWorkflows(){Object.keys(Lg).forEach(r=>{this._cancelWorkFlow(r)})}_validateWorkflow(r){return Lg[r]?!!this._handlers.get(r):!1}_getExecutableSteps(r){const{pendingSteps:g,completedSteps:u,stepMap:E,workflowName:f}=r;return Array.from(g).filter(D=>{const v=E.get(D)||{},{dependency:N,skipIfDependencyMissing:P=!0}=v;if(!N)return!0;if(c(N))return this._isStepRegistered({workflowName:f,stepId:N})?u.has(N):!P;if(C(N)){if(N.filter(W=>!this._isStepRegistered({workflowName:f,stepId:W})).length>0&&P)return!1;for(const W of N)if(!u.has(W))return!1;return!0}return!1})}_isStepRegistered(r){var g;const{workflowName:u,stepId:E}=r;return(g=this._handlers.get(u))===null||g===void 0?void 0:g.has(E)}_logWorkflowExecution(r,g,u,E){this._logHandlers[u](r,g)}}const fa=new Map,ea=({type:s,groupID:r})=>s===Po.GRP_COMMUNITY||`${r}`.startsWith(ga.COMMUNITY)&&!`${r}`.includes(ga.TOPIC),tl=(s="")=>{const r=s.startsWith("GROUP")?s.replace("GROUP",""):s;return r.startsWith(ga.COMMUNITY)&&`${r}`.includes(ga.TOPIC)},hd="openim",ic="million_group_open_http_svc";function ug(s){return mA(this,void 0,void 0,function*(){const{servcmd:r,data:g}=function(f){const{data:D}=f;return TE(D)||oc(D)}(s)?function(f){let{servcmd:D,data:v}=f;return oc(v)?function(N){const{servcmd:P,data:W}=N;let{GroupId:nA=""}=W;const EA=nA;return[nA]=EA.split(ga.TOPIC),{servcmd:$s(P),data:Object.assign(Object.assign({},W),{GroupId:nA,TopicId:EA})}}(f):(TE(v)&&(D=$s(D)),{servcmd:D,data:v})}(s):s,u=Se.common.generateProtocolData({servcmd:r,data:g}),E=`${u.head.seq}${r}`;return Se.channel.sendPacket(u,{requestId:E,timeout:s.timeout})})}function TE(s){const{Type:r,GroupId:g,GroupIdList:u=[]}=s,E=g||u[0]||"";return ea({type:r,groupID:E})}function oc(s){const{GroupId:r=""}=s;return tl(r)}function $s(s){if(s.includes(hd))return s;const r=s.split(".")[1];return`${ic}.${r}`}function ar(){var s;return(s=Se.store.get("login"))===null||s===void 0?void 0:s.userId}const Va=s=>C(s)||m(s),Bd=(s,r,g,u)=>{if(!Va(s)||!Va(r))return 0;let E=0;const f=Object.keys(r);let D;for(let v=0,N=f.length;v{if(n(r))return"";if(s===Po.MSG_TEXT)return r.text||"";const g=XI[s];return g?Uu(g):""},ol=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],$I="im_sdk_config_mgr.fetch_config",QI="im_sdk_config_mgr.push_configv2",nl="cloud-config",sl=2996,Ga=new class{init(s){this.core=s}};function Fg(s){return mA(this,void 0,void 0,function*(){const{sdkAppId:r}=Ga.core.store.get("instance")||{},g=Ga.core.helper.generateProtocolData({servcmd:$I,data:{uint32_sdkappid:r,uint64_version:s}}),u=`${g.head.seq}${$I}`;return Ga.core.channel.sendPacket(g,{requestId:u})})}var Nn=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(s){this._core=s;const{notificationCenter:r,InnerEvent:g,helper:u,constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:f},channel:D}=s;r.subscribeInnerEvent(QI,this._handlePushedConfig,this),u.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,f.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),r.subscribeInnerEvent(g.LOGOUT,this._reset,this),r.subscribeInnerEvent(g.DESTROY,this._dispose,this),u.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(ol),D.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(s){return mA(this,void 0,void 0,function*(){var r;const g={code:0,data:""};return s&&(g.data=((r=this._core.store.get("cloudConfig"))===null||r===void 0?void 0:r[s])||""),g})}checkMethodCallOverLimit(s){if(!this._cmdFrequencyLimitMap.has(s))return;if(!this._methodCallFrequencyMap.has(s))return void this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});const{count:r,interval:g}=this._cmdFrequencyLimitMap.get(s);let{startTime:u,methodCallCounter:E}=this._methodCallFrequencyMap.get(s);if(Date.now()-u>1e3*g)this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});else if(E+=1,this._methodCallFrequencyMap.set(s,{startTime:u,methodCallCounter:E}),E>r)throw new this._core.helper.ChatError({code:sl,replacement1:s})}_handlePushedConfig(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;r.info("_handlePushedConfig",g(s)),yield this._updateCloudConfig(s)})}_handleLoginSuccess(){return mA(this,void 0,void 0,function*(){const{ssoLog:s,utils:{safeStringify:r}}=this._core;try{if(this._canFetch()){const g=yield Fg(this._version);s.info("_fetchCloudConfigIfLogin",r(g)),yield this._updateCloudConfig(g)}this._core.helper.taskScheduler.addTask({id:nl,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(g){s.debug("_fetchCloudConfigIfLogin",r(g))}})}_fetchCloudConfigIfReady(){return mA(this,void 0,void 0,function*(){const{ssoLog:s,utils:{safeStringify:r}}=this._core;if(this._canFetch())try{const g=yield Fg(this._version);s.info("_fetchCloudConfigIfReady",r(g)),yield this._updateCloudConfig(g)}catch(g){s.error("_fetchCloudConfigIfReady",r(g))}})}_updateCloudConfig(s){return mA(this,void 0,void 0,function*(){const r=this._parseCloudConfig(s);r&&(this._core.store.set("cloudConfig",r),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,r),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:r}}))})}_canFetch(){const{isLoggedIn:s}=this._core.store.get("login")||{};return s&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(s){const{int32_error_code:r,str_error_message:g,str_json_config:u,uint32_expired_time:E,uint32_sdkappid:f,uint64_version:D}=s;let v=null;if(r===0){if(this._version!==D)try{v=JSON.parse(u),this._version=D}catch{}this._expirationTime=Date.now()+1e3*E}else this._expirationTime=r===void 0?Date.now()+36e5:Date.now()+12e4;return v}_parseCmdFreqLimit(){return mA(this,void 0,void 0,function*(){var s;let r=(s=yield this.getServerConfig("cmd_frequency_limit"))===null||s===void 0?void 0:s.data;const{isEmpty:g}=this._core.utils;if(!g(r))try{r=JSON.parse(r),this._updateCmdFreqLimitMap(r)}catch(u){console.warn(u)}})}_updateCmdFreqLimitMap(s){s.forEach(r=>{this._cmdFrequencyLimitMap.set(r.cmd,{interval:r.interval,count:r.count})})}_reset(){this._core.helper.taskScheduler.removeTask(nl),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(ol),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(QI,this._handlePushedConfig,this),s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this),this._reset()}};class Ar{constructor(r=0,g=0){this.high=r,this.low=g}equal(r){return r!==null&&this.low===r.low&&this.high===r.high}toString(){const r=Number(this.high).toString(16);let g=Number(this.low).toString(16);if(g.length<8){let u=8-g.length;for(;u;)g=`0${g}`,u--}return r+g}}const bc={SEARCH_GRP_SNS:new Ar(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Ar(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Ar(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Ar(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Ar(0,Math.pow(2,6)).toString(),USER_STATUS:new Ar(0,Math.pow(2,7)).toString(),CONV_MARK:new Ar(0,Math.pow(2,9)).toString(),CONV_GROUP:new Ar(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Ar(0,Math.pow(2,11)).toString(),MSG_EXT:new Ar(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Ar(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Ar(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Ar(Math.pow(2,7)).toString(),PLUGIN_CS:new Ar(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Ar(Math.pow(2,9)).toString(),PLUGIN_BOT:new Ar(Math.pow(2,10)).toString(),MSG_REACTION:new Ar(Math.pow(2,16)).toString(),FOLLOW:new Ar(Math.pow(2,20)).toString()},Au="CommercialConfig",eu="commercial-config";var NE=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(s){this._core=s;const{helper:r,notificationCenter:g,constants:{WORKFLOW_NAME:u,WORKFLOW_STEP:E,InnerEvent:f}}=s;g.subscribeInnerEvent(f.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),g.subscribeInnerEvent(f.LOGOUT,this._handleLogout,this),g.subscribeInnerEvent(f.DESTROY,this._dispose,this),r.registerWorkflowStep(u.SYNC_SERVER_INFO_AFTER_LOGIN,E.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),s.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),s.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(s){return mA(this,void 0,void 0,function*(){const r=parseInt(s,10).toString(2),{length:g}=r;let u,E=!0;for(let f=g-1,D=0;f>=0;f--,D++)if(r.charAt(f)==="1"&&(u=D<32?new Ar(0,2**D).toString():new Ar(2**(D-32),0).toString(),!this._featureMap.get(u))){E=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${Au}.isFeatureEnabled decimalNumber:${s} key:${u} ret:${E}`),{code:0,data:{enabled:E}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return mA(this,void 0,void 0,function*(){var s;const{ssoLog:r,utils:{safeStringify:g},common:{buildAndSendPacket:u}}=this._core;try{this._isFetching=!0;const E=yield u({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:(s=this._core.store.get("instance"))===null||s===void 0?void 0:s.sdkAppId}});E&&(this._parseCommercialConfig(E),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(E){r.error("_fetchAndParseCommercialConfig",g(E))}finally{this._isFetching=!1}})}_syncCommercialConfig(s){return mA(this,void 0,void 0,function*(){const{purchaseBits:r}=s?.data||{};r&&(this._parsePurchaseBits(r),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:eu,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var s;const r=(s=this._core.store.get("login"))===null||s===void 0?void 0:s.isLoggedIn,g=Date.now()>=this._expirationTime;return r&&!this._isFetching&&g}_handlePushedConfig(s){s?.body&&(this._parseCommercialConfig(s.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return mA(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(s){const{ssoLog:r}=this._core;if(typeof s!="object")return;const{int32_error_code:g,str_error_message:u,str_purchase_bits:E,uint32_expired_time:f}=s;g===0?(this._parsePurchaseBits(E),this._expirationTime=Date.now()+1e3*f):g===void 0?(r.warn("_parseCommercialConfig",`${Au}._parseCommercialConfig failed. Invalid message format:`,s),this._expirationTime=Date.now()+36e5):(r.warn("_parseCommercialConfig",`${Au}._parseCommercialConfig errorCode:${g} errorMessage:${u}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(s){return s&&typeof s=="string"&&s.length>=1&&s.length<=64&&/[01]{1,64}/.test(s)}_parsePurchaseBits(s){const{ssoLog:r,utils:{safeStringify:g}}=this._core;if(this._isValidPurchaseBits(s)){this._purchaseBits=s,this._featureMap.clear(),this._methodKeyMap.clear();let u=null;for(let E=s.length-1,f=0;E>=0;E--,f++)if(u=f<32?new Ar(0,2**f).toString():new Ar(2**(f-32),0).toString(),s[E]==="1"){this._featureMap.set(u,!0);const D=this._getKeyByValue(bc,u);D&&this._methodKeyMap.set(D,!0)}else{this._featureMap.set(u,!1);const D=this._getKeyByValue(bc,u);D&&this._methodKeyMap.set(D,!1)}}else r.warn("_parsePurchaseBits",`${Au}.parsePurchaseBits invalid purchases:${g(s)}`)}_getKeyByValue(s,r){const g=Object.entries(s).find(([u,E])=>E===r);return g?g[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(eu),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},lh=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(s){this._core=s;const{notificationCenter:r,InnerEvent:g,channel:u}=this._core;r.subscribeInnerEvent(g.OVERLOAD_PUSH,this._handleOverLoadPush,this),r.subscribeInnerEvent(g.LOGOUT,this._reset,this),r.subscribeInnerEvent(g.DESTROY,this._dispose,this),u.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(s){if(!this._serverOverloadInfoMap.has(s))return;const{overloadStartTimestamp:r,delaySeconds:g}=this._serverOverloadInfoMap.get(s);if(Date.now()-r<=1e3*g)throw new this._core.helper.ChatError({functionName:s,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(s)}_handleOverLoadPush(s){const{OverLoadServCmd:r,DelaySecs:g}=s;this._serverOverloadInfoMap.set(r,{overloadStartTimestamp:Date.now(),delaySeconds:g})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.OVERLOAD_PUSH,this._handleOverLoadPush,this),s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}},dC=new class{constructor(){this.name="ConfigCenter"}install(s){Ga.init(s),Nn.install(s),NE.install(s),lh.install(s)}},Ih=new class{constructor(){this.name="ErrorMessage",this._core=null}install(s){return mA(this,void 0,void 0,function*(){if(this._core=s,this._canFetch()){const r=yield this._fetchErrorMessage();if(!r)return;const g=this._parseResponse(r);this._saveErrorMessage(g)}})}_canFetch(){const s=this._core.store.getStorage("errorMessage");return!s||this._isExpired(s)}_saveErrorMessage(s){this._core.store.setStorage("errorMessage",{errorMessage:s,errorMessageSavedTime:new Date().getTime()})}_fetchErrorMessage(){return mA(this,void 0,void 0,function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(s){console.error(s)}})}_isExpired(s){if(!s)return!0;const{errorMessageSavedTime:r}=s;return r&&new Date().getTime()-r>=6048e5}_parseResponse(s){if(typeof s=="string"){const r=s.split(`; +`),g={},u=new RegExp(/'/g);for(let E=0;E{var zA,Ee,Ie;const Li=function(Ui,Yt){const{From_Account:Oi,From_AccountHeadurl:Bn,From_AccountNick:Re,IsNeedReadReceipt:Mt,MsgBody:FA,MsgClientTime:ci,MsgRandom:xn,MsgSeq:Pi,MsgTimeStamp:Vr,SendMsgControl:ji,SupportMessageExtension:Qr,To_Account:Ut,TinyId:Ft,MsgCheckResult:oE,CloudCustomData:hs,IsPeerRead:Do,MsgFlagBits:Bl,MsgVersion:GC,EventArray:Gr}=Ui;return{from:Oi,avatar:Bn,nick:Re,needReadReceipt:Mt===1,readReceiptSentByPeer:Do,clientTime:ci,messageFlagBits:Bl,random:xn,sequence:Pi,time:Vr,messageControlInfo:ji,isSupportExtension:Qr,to:Ut,tinyID:Ft,checkResult:oE,cloudCustomData:hs,messageVersion:GC,eventArray:Gr,elements:Yt.message.messageHelper.parseServerPushMessageElement(FA)}}(PA,VA);if(!((Ie=(Ee=(zA=PA?.EventArray)===null||zA===void 0?void 0:zA[0])===null||Ee===void 0?void 0:Ee.hasOwnProperty)===null||Ie===void 0)&&Ie.call(Ee,"C2cNotifyMsgArray"))SA.push(...function(Ui){var Yt;const Oi=[];return(Yt=Ui.EventArray)===null||Yt===void 0||Yt.forEach(Bn=>{var Re,Mt;const{C2cNotifyMsgArray:FA}=Bn,ci=(Mt=(Re=FA?.[0])===null||Re===void 0?void 0:Re.WithdrawC2cMsgNotify)===null||Mt===void 0?void 0:Mt.C2cWithdrawInfoArray;Array.isArray(ci)&&Oi.push(...ci)}),Oi}(PA));else{const Ui=VA.message.messageFactory.createMessage(Object.assign(Object.assign({},Li),{conversationType:"C2C",flow:"in"})),{elements:Yt}=Li;Ui.setElement(Yt),LA.push(Ui)}}),{unreadMessageList:LA,revokedMessageList:SA}}(N.MsgList,r);return{syncFlag:N?.SyncFlag,unreadMessageList:EA,revokedMessageList:wA,unreadCountList:P,overflowUnreadCountList:W,cookie:N?.Cookie,groupTipList:nA}}catch(N){console.warn(N)}})}var Og,Io;(function(s){s[s.START_SYNC=0]="START_SYNC",s[s.SYNCING=1]="SYNCING",s[s.SYNC_COMPLETE=2]="SYNC_COMPLETE"})(Og||(Og={})),function(s){s[s.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",s[s.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(Io||(Io={}));var CC=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie="",this._localConversationIDListBeforeDisconnect=[]}install(s){this._core=s;const{constants:r}=s;s.helper.registerWorkflowStep(r.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),s.helper.registerWorkflowStep(r.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,r.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),s.helper.registerWorkflowStep(r.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,r.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.SOCKET_DISCONNECTED,this._handleDisconnect,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(s){return mA(this,void 0,void 0,function*(){const{isAfterReOnline:r=!1,isAfterNewMessageReceived:g=!1,isAfterLogin:u=!1}=s||{};let E=Og.START_SYNC;const f=[],D=[],v=[],N=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:E});){const P=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:E,syncTriggerEvent:g?Io.NEW_MESSAGE_RECEIVED:Io.LOGIN_SUCCESS});if(!P)break;const{unreadMessageList:W=[],revokedMessageList:nA=[],overflowUnreadCountList:EA,unreadCountList:wA,groupTipList:kA}=P;if(this._cookie=P?.cookie||"",E=P?.syncFlag,this._parseAndSaveUnreadMessageList(W),v.push(...nA),this._updateConversationUnreadOptions({unreadCountList:wA,overflowUnreadCountList:EA,conversationUpdateFieldList:f}),Array.isArray(kA)&&D.push(...kA),r){const{messages:VA}=this._handleNewMessageList(W);N.push(...VA)}}return r?{conversationUpdateFieldList:f,revokedMessageList:v,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D,messages:N,isUnreadC2CMessage:!0}:{conversationUpdateFieldList:f,isInstantMessage:!u,isUnreadC2CMessage:!0,revokedMessageList:v,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D}})}_syncUnreadDBMessageAfterLogin(){return mA(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(s){return mA(this,void 0,void 0,function*(){if(s.data.Flag===1)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(s){const{unreadCountList:r,overflowUnreadCountList:g,conversationUpdateFieldList:u}=s,{constants:{OuterConstant:{CONV_C2C:E,CONV_SYSTEM:f}}}=this._core;r?.forEach(D=>{const{From_Account:v,UnreadCount:N}=D;if(v!==f){const P=u.find(({conversationID:W})=>W===`${E}${v}`);P?P.unreadCount=N:u.push({conversationID:`${E}${v}`,unreadCount:N,type:E})}}),g?.forEach(D=>{const{From_Account:v,LastMsgTime:N}=D;v!==f&&(u.find(({conversationID:P})=>P===`${E}${v}`)||u.push({conversationID:`${E}${v}`,type:E,lastMsgTime:N}))})}_syncUnreadDBMessageAfterReOnline(){return mA(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(s){var r;const{messageDataHandler:g}=this._core.message||{},u=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,{from:E,nick:f,avatar:D,conversationID:v=""}=s;if(E!==u){const N=g.getLatestMsgSentByPeer(v);if(N){const{nick:P,avatar:W}=N;f&&D?f===P&&D===W||g.updateNickAndAvatarOfSentMessage({conversationID:v,latestNick:f,latestAvatar:D,isSentByMe:!1}):(s.nick=P,s.avatar=W)}}else{const N=g.getLatestMsgSentByMe(v);!N||f===N.nick&&D===N.avatar||g.updateNickAndAvatarOfSentMessage({conversationID:v,latestNick:f,latestAvatar:D,isSentByMe:!0})}}_handleNewMessageList(s){const{messageDataHandler:r}=this._core.message||{},g=new Map,u=[];return s.forEach(E=>{this._updateMessageProfile(E);let f=E.isModified===1;if(r.isMessageSentByCurrentInstance(E)?E.isModified=f:f=!1,E.isOnlineMessage())E._onlineOnlyFlag=!0,r.isMessageSentByCurrentInstance(E)||u.push(E);else if(this._shouldStoreUnreadMessage(E)){if(r.storeConversationMessage(E)){const{conversationID:D,conversationType:v,conversationSubType:N,flow:P,_isExcludedFromUnreadCount:W,_isExcludedFromLastMessage:nA}=E,EA=nA?"":E;g.has(D)?(g.get(D).lastMessage=EA,P==="in"&&(W||g.get(D).unreadCount++)):g.set(D,{conversationID:D,type:v,subType:N,unreadCount:W||P!=="in"?0:1,lastMessage:EA})}r.isMessageSentByCurrentInstance(E)&&!f||u.push(E)}}),{messages:u,conversationOptions:g}}_shouldStoreUnreadMessage(s){var r;const{conversationID:g}=s,{message:u,appStore:E,utils:{isEmpty:f}}=this._core||{},D=Array.from(((r=E.conversationStore.getConversationMap())===null||r===void 0?void 0:r.keys())||[]),v=this._getLocalLastMessageTime(g);return!u.messageDataHandler.isInMessageList(s)&&D.includes(g)&&this._localConversationIDListBeforeDisconnect.includes(g)&&!f(v)}_fetchUnreadDBMessage(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;try{r.debug("_fetchUnreadDBMessage",`unread-message-synchronizer._fetchUnreadDBMessage options:${g(s)}`);const E=yield rl(s,this._core);if(!E)return null;const{syncFlag:f,unreadMessageList:D,revokedMessageList:v,cookie:N,unreadCountList:P,overflowUnreadCountList:W,groupTipList:nA}=E;return this._parseAndSaveUnreadMessageList(D),{syncFlag:f,cookie:N,unreadMessageList:D,revokedMessageList:v,unreadCountList:P,overflowUnreadCountList:W,groupTipList:nA}}catch(u){console.log(u)}})}_canContinueSync({cookie:s,syncFlag:r}){var g;return r===Og.START_SYNC||r===Og.SYNCING&&!(!((g=this._core)===null||g===void 0)&&g.helper.isEmpty(s))}_parseAndSaveUnreadMessageList(s){s.forEach(r=>{const{ID:g}=r;this._unreadDBMessageMap.set(g,r)})}_handleDisconnect(){var s;const{appStore:r}=this._core;this._localConversationIDListBeforeDisconnect=Array.from(((s=r.conversationStore.getConversationMap())===null||s===void 0?void 0:s.keys())||[])}_getLocalLastMessageTime(s){const{message:r}=this._core,g=r.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.time}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var s,r;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},GE=new class{init(s){var r;this._core=s,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),document?.addEventListener("visibilitychange",this._visibilityChangeHandler),(r=this._core)===null||r===void 0||r.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var s,r;const g=document?.visibilityState==="visible";(s=this._core)===null||s===void 0||s.store.set("activityMonitor",{isActive:g}),(r=this._core)===null||r===void 0||r.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:g})}_reset(){var s;(s=this._core)===null||s===void 0||s.store.clear("activityMonitor")}_dispose(){document?.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this),this._reset()}},bE=new class{init(s){var r;this._core=s,this._bindAppActivityEvent(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),(r=this._core)===null||r===void 0||r.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var s,r,g,u,E;const{MINI_APP_NAMESPACE:f,IN_TT_MINI_GAME:D,IN_WX_MINI_GAME:v}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};D||v?((r=f?.onShow)===null||r===void 0||r.call(f,()=>{var N,P;(N=this._core)===null||N===void 0||N.store.set("activityMonitor",{isActive:!0}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(g=f?.onHide)===null||g===void 0||g.call(f,()=>{var N,P;(N=this._core)===null||N===void 0||N.store.set("activityMonitor",{isActive:!1}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):((u=f?.onAppShow)===null||u===void 0||u.call(f,()=>{var N,P;(N=this._core)===null||N===void 0||N.store.set("activityMonitor",{isActive:!0}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(E=f?.onAppHide)===null||E===void 0||E.call(f,()=>{var N,P;(N=this._core)===null||N===void 0||N.store.set("activityMonitor",{isActive:!1}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var s;(s=this._core)===null||s===void 0||s.store.clear("activityMonitor")}_dispose(){const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this),this._reset()}},Qd=new class{init(s){const{IN_MINI_APP:r,IN_WX_MINI_PLUGIN:g}=s.helper;g||(r?bE.init(s):GE.init(s))}};const kE="none",al="online";var pI=new class{init(s){this._core=s,this._activateNetworkMonitoring(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return mA(this,void 0,void 0,function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)})}_deactivateNetworkMonitoring(){this._onOnlineCallback!==null&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),this._onOfflineCallback!==null&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(s){var r,g;const{isConnected:u,networkType:E}=s;(r=this._core)===null||r===void 0||r.store.set("netWorkMonitor",{isNetworkOnline:u,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:u,networkType:E})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:al})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:kE})}_reset(){var s;this._deactivateNetworkMonitoring(),(s=this._core)===null||s===void 0||s.store.clear("netWorkMonitor")}_dispose(){var s,r;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent((r=this._core)===null||r===void 0?void 0:r.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Fu=new class{init(s){this._core=s,this._activateNetworkMonitoring(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return mA(this,void 0,void 0,function*(){try{const{utils:{MINI_APP_NAMESPACE:s}}=this._core;this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),s.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(s){console.error(s)}})}_deactivateNetworkMonitoring(){if(this._mpNetworkStatusCallback!==null){const{utils:{MINI_APP_NAMESPACE:s}}=this._core;s.offNetworkStatusChange&&s.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null}}_onNetworkStatusChange(s){var r,g;const{isConnected:u,networkType:E}=s;(r=this._core)===null||r===void 0||r.store.set("netWorkMonitor",{isNetworkOnline:u,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:u,networkType:E})}_reset(){var s;this._deactivateNetworkMonitoring(),(s=this._core)===null||s===void 0||s.store.clear("netWorkMonitor")}_dispose(){var s,r;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent((r=this._core)===null||r===void 0?void 0:r.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Ou=new class{init(s){const{IN_MINI_APP:r}=s.utils;r?Fu.init(s):pI.init(s)}},hC=new class{constructor(){this.name="SystemStateMonitor"}install(s){Qd.init(s),Ou.init(s)}};const Tr=new Set(["tui_room_svr.*","callkit_records_svr.*","room_engine_srv.*","room_engine_http_srv.*","room_engine_mic.*","live_engine_srv.*","live_engine_http_srv.*","live_engine_pk.*","trtc_ai_service.*","call_engine_srv.*"]),Eg="tui_room_svr.*";var kc=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=Tr}install(s){this._core=s;const{notificationCenter:r,InnerEvent:g,helper:u}=s;r.subscribeInnerEvent(g.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),r.subscribeInnerEvent(g.LOGOUT,this._reset,this),r.subscribeInnerEvent(g.DESTROY,this._dispose,this),r.subscribeInnerEvent("im_open_push.msg_push",r.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),u.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),u.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(s){return mA(this,void 0,void 0,function*(){const r="transferBusinessCommand";try{const{serviceCommand:g=Eg}=s||{};if(!this._isValidTransferredCommand(g))throw new this._core.helper.ChatError({code:2995,functionName:r});return{code:0,data:(yield function(E,f){return mA(this,void 0,void 0,function*(){const{helper:D,channel:v}=f,{serviceCommand:N=Eg,data:P}=E||{};let W={};try{W=typeof P=="string"?JSON.parse(P):P}catch(wA){console.warn(wA)}const nA=D.generateProtocolData({servcmd:N,data:W}),EA=`${nA.head.seq}${N}`;return v.sendPacket(nA,{requestId:EA,shouldRejectOnError:!1})})}(s,this._core))||{}}}catch(g){throw console.warn(g),new this._core.helper.ChatError({code:g?.errorCode,message:g?.errorInfo,data:{},functionName:r})}})}_onCloudConfigUpdate(s={}){try{if(typeof s.rtc_cmd!="string")return;const r=JSON.parse(s.rtc_cmd);Array.isArray(r)&&(this._transferredCommands=new Set([...this._transferredCommands,...r]))}catch(r){console.log(r)}}_isValidTransferredCommand(s=""){const r=`${s?.split(".")[0]}.*`;return this._transferredCommands.has(r)}_onServerPushBusinessCommand(s){const{OuterEvent:r,notificationCenter:g}=this._core,{MsgContent:u}=s||{},{ROOM_CUSTOM_DATA_RECEIVED:E}=r;g.emitOuterEvent(E,{name:E,data:u})}_reset(){this._transferredCommands=Tr}_dispose(){const{notificationCenter:s,InnerEvent:r}=this._core;this._reset(),s.unSubscribeInnerEvent(r.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this),s.unSubscribeInnerEvent("im_open_push.msg_push",s.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const Pu=1,Ul=2,pd=3,ta=4,mI=5,Us="TIMCustomElem",BC="C2C",gl="GROUP",md="invite",fI="accept",Ha="cancel",QC="reject",Ja="modifyInvitation",yr="signaling",fd=8010,xu="signaling-timeout";function Dr(s){return s.filter(r=>{if(r.type===Us){const{cloudCustomData:g="",payload:{data:u=""}={}}=r,E=g.match(/"type":"tsignaling"/),f=u.match(/inviteID/),D=u.match(/actionType/);return E||f&&D}return!1})}function Lc(s){const{data:r}=s.payload;try{return JSON.parse(r)}catch(g){return console.error(g),null}}function cl(s,r){return s.toString(16).padStart(r,"0")}function Pg(s){if(s<0||s>53)throw new Error("Number of digits must be between 0 and 53");if(s<=30)return Math.floor(Math.random()*(1<0;const v=this._core.common.getCurrentUserID();return D.includes(v)}return!0}updateSignaling(s){const r=`${yr}.updateSignaling`,{inviteID:g,inviter:u,inviteeList:E,groupID:f}=s;if(console.log(`${r} inviteID:${g} inviter:${u} groupID:${f}`),f&&this.hasSignaling(g)){const D=E[0],{inviteeList:v}=this._onlineSignalingMap.get(g);v.includes(D)&&(v.splice(v.indexOf(D),1),console.log(`${r} remove ${D}. localInviteeList.length:${v.length}`)),v.length===0&&this.removeSignaling(g)}else this.removeSignaling(g)}setSignalingListenStatus(s){this._isSignalingListening=s}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var s,r;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},nc=new class{init(s){this._core=s}createInviteSignaling(s){const r=this._generateInviteID(),g=this._createInviteSignalingData(Object.assign(Object.assign({},s),{inviteID:r})),{groupID:u,inviteeList:E}=g,f=u||E[0];return{signaling:this._createSignaling(g,f),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createAcceptSignaling(s){const r=this._createAcceptSignalingData(s),{groupID:g,inviter:u}=r,E=g||u;return{signaling:this._createSignaling(r,E),signalingData:r,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createCancelSignaling(s){const r=this._createCancelSignalingData(s),{groupID:g,inviteeList:u}=r,E=g||u[0];return{signaling:this._createSignaling(r,E),signalingData:r,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createRejectSignaling(s){const r=this._createRejectSignalingData(s),{groupID:g,inviter:u}=r,E=g||u;return{signaling:this._createSignaling(r,E),signalingData:r,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createTimeoutSignaling(s){const{isInviter:r=!1}=s,g=this._createTimeoutSignalingData(s),{groupID:u,inviteeList:E,inviter:f}=g,D=u||(r?E[0]:f);return{signaling:this._createSignaling(g,D),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(g)}}_createSignalingExtensionOptions(s){var r,g;const{data:u="",onlineUserOnly:E,inviteID:f="",offlinePushInfo:D,actionType:v}=s,N=((g=(r=Jo.getSignaling(f))===null||r===void 0?void 0:r.signaling)===null||g===void 0?void 0:g._onlineOnlyFlag)||!1;return{onlineUserOnly:E||N,offlinePushInfo:D,messageControlInfo:this._createMessageControlInfo(u,v)}}_createMessageControlInfo(s,r){const g=r===mI&&!!s.match(/excludeTimeoutSignalingFromHistoryMessage/),u=!!s.match(/excludeFromHistoryMessage/)||!!s.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:g||u,excludedFromLastMessage:g||u}}_createInviteSignalingData(s){const r=`${yr}._createInviteSignalingData`,{userID:g,timeout:u=0,groupID:E="",inviteeList:f=[]}=s,D=this._core.common.getCurrentUserID(),v=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Pu,inviter:D,inviteeList:E?f:[g],timeout:u});return console.log(`${r} signalingData:`,v),v}_createAcceptSignalingData(s){const r=`${yr}._createAcceptSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviter:E,groupID:f}=Jo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:pd,groupID:f,inviter:E,inviteeList:[u]});return console.log(`${r} signalingData:`,D),D}_createCancelSignalingData(s){const r=`${yr}._createCancelSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviteeList:E,groupID:f}=Jo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Ul,groupID:f,inviter:u,inviteeList:E});return console.log(`${r} signalingData:`,D),D}_createRejectSignalingData(s){const r=`${yr}._createRejectSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviter:E,groupID:f}=Jo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:ta,groupID:f,inviter:E,inviteeList:[u]});return console.log(`${r} signalingData:`,D),D}_createTimeoutSignalingData(s){const r=`${yr}._createTimeoutSignalingData`,{isInviter:g=!1,inviteID:u}=s,{inviteeList:E,inviter:f}=Jo.getSignaling(u),D=this._core.common.getCurrentUserID(),v=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:mI,inviter:f,inviteeList:g?E:[D]});return console.log(`${r} signalingData:`,v),v}_createSignaling(s,r){var g,u,E;const{groupID:f=""}=s,D={to:r,conversationType:f?gl:BC,priority:"High",payload:{data:JSON.stringify(s)}};return(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(D)}_generateInviteID(){return[cl(Pg(32),8),cl(Pg(16),4),cl(16384|Pg(12),4),cl(32768|Pg(14),4),cl(Pg(48),12)].join("-")}_generateBaseSignalData(s){const{data:r="",inviteID:g="",groupID:u=""}=s;return{businessID:1,timeout:0,data:r,inviteID:g,groupID:u}}},eg=new class{constructor(){this._isProcessingSignaling=!1}init(s){this._core=s,s.helper.registerApi({apiName:"invite",context:this}),s.helper.registerApi({apiName:"accept",context:this}),s.helper.registerApi({apiName:"cancel",context:this}),s.helper.registerApi({apiName:"reject",context:this}),s.helper.registerApi({apiName:"modifyInvitation",context:this}),s.helper.registerApi({apiName:"getSignalingInfo",context:this}),s.helper.registerApi({apiName:"addSignalingListener",context:this}),s.helper.registerApi({apiName:"removeSignalingListener",context:this}),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this)}invite(s){return mA(this,void 0,void 0,function*(){var r;try{this._validateBeforeInvite(s);const{signaling:g,signalingData:u,signalingExtensionOptions:E}=nc.createInviteSignaling(s),f=yield this._sendSignaling(g,E);if(f?.code===0){const{inviteID:D,timeout:v}=u;return Jo.saveSignaling(D,Object.assign(Object.assign({},u),{signaling:g})),v>0&&((r=this._core)===null||r===void 0||r.helper.taskScheduler.addOnceTask({id:`${xu}-${D}`,intervalMs:1e3*(v+5),callback:this.handleInvitationExpiryTimer.bind(this,D)})),Object.assign(Object.assign({},f),{inviteID:D})}return f}catch(g){throw g}})}accept(s){return mA(this,void 0,void 0,function*(){try{const{inviteID:r}=s;this._validateBeforeAccept(r),this._isProcessingSignaling=!0;const{signaling:g,signalingData:u,signalingExtensionOptions:E}=nc.createAcceptSignaling(s),f=yield this._sendSignaling(g,E);return f?.code===0?(Jo.updateSignaling(u),Object.assign(Object.assign({},f),{inviteID:r})):f}catch(r){throw r}finally{this._isProcessingSignaling=!1}})}cancel(s){return mA(this,void 0,void 0,function*(){try{const{inviteID:r}=s;this._validateBeforeCancel(r),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:u}=nc.createCancelSignaling(s),E=yield this._sendSignaling(g,u);return E?.code===0?(Jo.removeSignaling(r),Object.assign(Object.assign({},E),{inviteID:r})):E}catch(r){throw r}finally{this._isProcessingSignaling=!1}})}reject(s){return mA(this,void 0,void 0,function*(){try{const{inviteID:r}=s;this._validateBeforeReject(r),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:u}=nc.createRejectSignaling(s),E=yield this._sendSignaling(g,u);return E?.code===0?(Jo.removeSignaling(r),Object.assign(Object.assign({},E),{inviteID:r})):E}catch(r){throw r}finally{this._isProcessingSignaling=!1}})}modifyInvitation(s){return mA(this,void 0,void 0,function*(){var r,g;const{inviteID:u,data:E}=s;let f="";try{this._validateBeforeModifyInvitation(u);const D=Jo.getSignaling(u),{signaling:v}=D,N=vo(D,["signaling"]);f=v.payload.data,N.data=E,v.payload.data=JSON.stringify(N);const P=yield(g=(r=this._core)===null||r===void 0?void 0:r.message.messageAction)===null||g===void 0?void 0:g.modifyMessage(v);return Jo.hasSignaling(u)&&Jo.saveSignaling(u,Object.assign(Object.assign({},N),{signaling:v})),P}catch(D){if(f){const{signaling:v}=Jo.getSignaling(u);v.payload.data=f}throw D}})}getSignalingInfo(s){const{ssoLog:r,utils:{safeStringify:g}}=this._core;if(Dr([s]).length===0)return;const u=Lc(s),E={businessID:u.businessID||1,inviteID:u.inviteID,groupID:u.groupID||"",inviter:u.inviter||"",inviteeList:u.inviteeList||[],data:u.data||"",actionType:u.actionType||Pu,timeout:u.timeout||0};return r.debug(`${yr} getSignalingInfo ${g(E)}`),E}addSignalingListener(s,r,g){var u,E;s===((u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED)&&Jo.setSignalingListenStatus(!0),(E=this._core)===null||E===void 0||E.notificationCenter.subscribeOuterEvent(s,r,g)}removeSignalingListener(s,r,g){var u,E;s===((u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED)&&Jo.setSignalingListenStatus(!1),(E=this._core)===null||E===void 0||E.notificationCenter.unSubscribeOuterEvent(s,r,g)}handleInvitationExpiryTimer(s){const r=Jo.getOnlineSignalingMap(),g=this._core.common.getCurrentUserID();if(!r.has(s))return;const u=r.get(s).inviter===g;this._sendTimeoutNotice({inviteID:s,isInviter:u})}_sendSignaling(s,r){return mA(this,void 0,void 0,function*(){var g,u,E;return(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(s,r)})}_sendTimeoutNotice(s){return mA(this,void 0,void 0,function*(){var r,g,u;this._core.ssoLog.debug("_sendTimeoutNotice",`${yr}._sendTimeoutNotice params:${JSON.stringify(s)}`);const{isInviter:E,inviteID:f}=s,{signaling:D,signalingData:v,signalingExtensionOptions:N}=nc.createTimeoutSignaling(s),P=yield this._sendSignaling(D,N);if(P?.code===0){const{data:W,groupID:nA,inviteeList:EA,inviter:wA}=v;(r=this._core)===null||r===void 0||r.notificationCenter.emitOuterEvent((g=this._core)===null||g===void 0?void 0:g.SignalingEvent.INVITATION_TIMEOUT,{name:(u=this._core)===null||u===void 0?void 0:u.SignalingEvent.INVITATION_TIMEOUT,data:{data:W,groupID:nA,inviteID:f,inviteeList:EA,inviter:wA,isSelfTimeout:!0,message:D}}),E?Jo.removeSignaling(f):Jo.updateSignaling(v)}})}_validateInviteId(s,r){if(!Jo.hasSignaling(r))throw new this._core.helper.ChatError({functionName:s,code:fd})}_validateProcessStatus(s){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:s,message:"processing other signaling operations"})}_validateBeforeInvite(s){const r=md,{userID:g}=s,u=this._core.common.getCurrentUserID();if(g===u)throw new this._core.helper.ChatError({functionName:r,message:`cannot invite yourself, currentUserId:${u}, inviteeId:${g}`})}_validateBeforeAccept(s){const r=fI;this._validateInviteId(r,s),this._validateProcessStatus(r);const g=this._core.common.getCurrentUserID(),{inviteeList:u}=Jo.getSignaling(s);if(!u.includes(g)){const E=`userID:${g} not in inviteeList. inviteID:${s}`;throw new this._core.helper.ChatError({functionName:r,message:E})}}_validateBeforeCancel(s){const r=Ha;this._validateInviteId(r,s),this._validateProcessStatus(r);const g=this._core.common.getCurrentUserID(),{inviter:u}=Jo.getSignaling(s);if(u!==g){const E=`unmatched inviter:${u} and my userID:${g}`;throw new this._core.helper.ChatError({functionName:r,message:E})}}_validateBeforeReject(s){const r=QC;this._validateInviteId(r,s),this._validateProcessStatus(r);const g=this._core.common.getCurrentUserID(),{inviteeList:u}=Jo.getSignaling(s);if(!u.includes(g)){const E=`userID:${g} not in inviteeList. inviteID:${s}`;throw new this._core.helper.ChatError({functionName:r,message:E})}}_validateBeforeModifyInvitation(s){const r=Ja;this._validateInviteId(r,s)}_dispose(){var s,r;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},Fl=new class{constructor(){this._actionProcessor=new Map([[Pu,this._onNewInvitationReceived.bind(this)],[ta,this._onInviteeRejected.bind(this)],[pd,this._onInviteeAccepted.bind(this)],[Ul,this._onInvitationCancelled.bind(this)],[mI,this._onInvitationTimeout.bind(this)]])}init(s){this._core=s,s.notificationCenter.subscribeOuterEvent(s.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),s.notificationCenter.subscribeOuterEvent(s.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(s){s.forEach(r=>{const g=Lc(r);if(g){const u=this._actionProcessor.get(g.actionType);u?.(g,r)}})}_handleMessageReceived(s){if(!Jo.getSignalingListenStatus())return;const r=Dr(s.data);r.length!==0&&this.handleActionSignaling(r)}_handleMessageModified(s){if(!Jo.getSignalingListenStatus())return;const r=Dr(s.data);r.length>0&&r.forEach(g=>{const u=Lc(g);u&&this._onInvitationModified(u,g)})}_onNewInvitationReceived(s,r){var g,u;const E=`${yr}._onNewInvitationReceived`,{inviteID:f,inviteeList:D,groupID:v}=s,N=this._core.common.getCurrentUserID();if(this._core.ssoLog.debug("_onNewInvitationReceived",`${E} signalingData:${JSON.stringify(s)}}`),v&&!D.includes(N))return;let{timeout:P}=s;const W=Date.now()/1e3-r.time;P>0&&W>0&&P>W&&(P-=W);const nA=Jo.getSignaling(f);nA!==s&&(nA||Jo.saveSignaling(f,Object.assign(Object.assign({},s),{signaling:r})),P>0&&((g=this._core)===null||g===void 0||g.helper.taskScheduler.addOnceTask({id:`${xu}-${f}`,intervalMs:1e3*P,callback:eg.handleInvitationExpiryTimer.bind(eg,f)})),this._emitEvent({name:(u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:D})}))}_onInviteeRejected(s){var r;const g=`${yr}._onInviteeRejected`,{inviteID:u,inviter:E,groupID:f,inviteeList:D}=s,v=Jo.hasSignaling(u);this._core.ssoLog.debug("_onInviteeRejected",`${g} inviteID:${u} hasInviteID:${v} inviter:${E} groupID:${f}`),v&&(Jo.updateSignaling(s),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{invitee:D[0]})}))}_onInviteeAccepted(s){var r;const g=`${yr}._onInviteeAccepted`,{inviteID:u,inviter:E,groupID:f,inviteeList:D}=s,v=Jo.hasSignaling(u);this._core.ssoLog.debug("_onInviteeAccepted",`${g} inviteID:${u} hasInviteID:${v} inviter:${E} groupID:${f}`),v&&(Jo.updateSignaling(s),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{invitee:D[0]})}))}_onInvitationCancelled(s){var r;const g=`${yr}._onInvitationCancelled`,{inviteID:u,inviter:E,groupID:f}=s,D=Jo.hasSignaling(u);this._core.ssoLog.debug("_onInvitationCancelled",`${g} inviteID:${u} hasInviteID:${D} inviter:${E} groupID:${f}`),D&&(Jo.removeSignaling(u),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(s)}))}_onInvitationTimeout(s){var r;const g=`${yr}._onInvitationTimeout`,{inviteID:u,inviteeList:E}=s,f=Jo.hasSignaling(u);this._core.ssoLog.debug("_onInvitationTimeout",`${g} inviteID:${u} hasInviteID:${f} data:${s.data}`),f&&(Jo.updateSignaling(s),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:E,isSelfTimeout:!1})}))}_onInvitationModified(s,r){var g;const u=`${yr}._onInvitationModified`,{inviteID:E,data:f}=s,D=Jo.hasSignaling(E);this._core.ssoLog.debug("_onInvitationModified",`${u} inviteID:${E} data:${f}`),D&&(Jo.saveSignaling(E,Object.assign(Object.assign({},s),{signaling:r})),this._emitEvent({name:(g=this._core)===null||g===void 0?void 0:g.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:E,data:f}}))}_emitEvent(s){var r;(r=this._core)===null||r===void 0||r.notificationCenter.emitOuterEvent(s.name,s)}_generateBaseEmitData(s){const{inviteID:r,inviter:g,groupID:u,data:E}=s;return{inviteID:r,inviter:g,groupID:u,data:E||""}}_dispose(){var s,r,g;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),(g=this._core)===null||g===void 0||g.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},ia=new class{constructor(){this._offlineSignalingMap=new Map}init(s){this._core=s;const{notificationCenter:r,helper:g,constants:{InnerEvent:u,WORKFLOW_STEP:E,WORKFLOW_NAME:f}}=s;r.subscribeInnerEvent(u.DESTROY,this._dispose,this),r.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.registerWorkflowStep(f.SYNC_SERVER_INFO_AFTER_LOGIN,E.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(s){const{result:{unreadMessageMap:r}={}}=s||{};if(!(r?.size!==0&&Jo.getSignalingListenStatus()))return;const g=Dr([...r.values()]);if(g.length!==0&&(g.forEach(u=>{this._handleC2CActionType(u)}),this._offlineSignalingMap.size>0)){const u=this._sortOfflineSignalingByTime();Fl.handleActionSignaling(u)}}_handleC2CActionType(s){const r=Lc(s);if(!r)return;const{actionType:g}=r;g===Pu?this._saveValidOfflineInvite(r,s):this._removeOfflineInvite(r)}_saveValidOfflineInvite(s,r){const{inviteID:g,inviteeList:u=[],timeout:E=0}=s,f=this._core.common.getCurrentUserID();if(!u.includes(f))return;const D=Date.now()/1e3-r.time;E>0&&D>E&&E!==0||this._offlineSignalingMap.set(g,Object.assign(Object.assign({},s),{signalingList:[r]}))}_removeOfflineInvite(s){const{inviteID:r=""}=s;this._offlineSignalingMap.has(r)&&this._offlineSignalingMap.delete(r)}_sortOfflineSignalingByTime(){let s=[];return this._offlineSignalingMap.forEach(r=>{s=[...s,...r.signalingList]}),s.sort((r,g)=>r.time-g.time)}_dispose(){var s,r;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};const uh={invite:{userID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0},timeout:{required:!1,rules:["number"],allowEmpty:!1},onlineUserOnly:{required:!1,rules:["boolean"],allowEmpty:!1},offlinePushInfo:{required:!1,rules:["object"],allowEmpty:!1}},cancel:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},accept:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},reject:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},modifyInvitation:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}}},ss={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var tu=new class{constructor(){this.name="Signaling"}install(s){eg.init(s),Fl.init(s),nc.init(s),Jo.init(s),ia.init(s),s.helper.registerValidateConfig({auth:ss,params:uh})}};const Wn=new class{init(s){this.core=s}};function Uc(s){let r;const{message:g}=Wn.core,{conversationID:u,messageID:E}=s;return r=g.messageDataHandler.getLocalMessageList(u).find(f=>f.ID===E),!r&&(r=g.messageDataHandler.getSparseMessageList(u).find(f=>f.ID===E)),r}function sc(s){return s.map(r=>{const{from:g,to:u,cloudCustomData:E,avatar:f,nick:D,ID:v,clientSequence:N,clientTime:P,messageRandom:W,messageSequence:nA,time:EA}=r;return{ClientSeq:N,CloudCustomData:E,From_Account:g,From_AccountHeadurl:f,From_AccountNick:D,Id:v,MsgBody:JSON.parse(JSON.stringify(r.transformElementsToServerFormat())),MsgClientTime:P,MsgRandom:W,Random:W,MsgSeq:nA,MsgTimeStamp:EA,ReceiverId:u,SenderId:g,To_Account:u}})}function Sr(s){var r;const{From_Account:g,From_AccountHeadurl:u,From_AccountNick:E,GroupId:f,MsgClientTime:D,ClientSeq:v,To_Account:N,MsgTimeStamp:P,TinyId:W,MsgRandom:nA,MsgSeq:EA}=s;return{from:g,avatar:u,nick:E,clientTime:D,time:P,tinyID:W,random:nA,sequence:EA,to:N,groupID:f,clientSequence:v,_elements:(r=s.MsgBody)===null||r===void 0?void 0:r.map(wA=>{const{MsgType:kA}=wA;return Wn.core.message.messageFactory.getElementClass(kA).parseServerPushElement(wA)})}}var Kr,tg;(function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_STREAM="TIMStreamElem"})(Kr||(Kr={})),function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"}(tg||(tg={}));const LE="MSG_REACTION",pC="MSG_EXT",Eh=0,uo=1,Fc={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},Ol="16k_zh",mC="16k_en",fC="16k_yue",Pl="16k_ja",iu="16k_zh-PY",yI={[Fc.ZH_CN]:Ol,[Fc.EN_US]:mC,[Fc.YUE_HK]:fC,[Fc.JA_JP]:Pl,[Fc.ZH_PY]:iu},DI=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,UE={READ:0,UNREAD:1},xl=1,Yl=2,xg=3;var rc;(function(s){s.IN="in",s.OUT="out"})(rc||(rc={}));const yd=16,FE=17;var Oc;(function(s){s[s.DATA=0]="DATA",s[s.REVOKED=1]="REVOKED"})(Oc||(Oc={}));var ou;(function(s){s[s.NORMAL=0]="NORMAL",s[s.TIMEOUT=1]="TIMEOUT"})(ou||(ou={}));const ho="StreamMsg.PushStreamHttp";var OE=new class{constructor(){this._reactionsMap=new Map}init(s){this._core=s;const{helper:r,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:u},InnerEventSubType:{MESSAGE_REACTION_UPDATED:E,MESSAGE_REACTION_UPDATED_SYNC:f}}=s;r.registerApi({apiName:"addMessageReaction",context:this}),r.registerApi({apiName:"removeMessageReaction",context:this}),r.registerApi({apiName:"getMessageReactions",context:this}),r.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),g.subscribeInnerEvent(u,E,this._handleReactionUpdated,this),g.subscribeInnerEvent(u,f,this._handleReactionSync,this)}addMessageReaction(s,r){return mA(this,void 0,void 0,function*(){const{OuterConstant:g,ssoLog:u,helper:E}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:f,ID:D,conversationType:v,from:N,to:P,clientSequence:W,random:nA,time:EA,sequence:wA}=s,kA=`conversationID:${f} messageID:${D} reactionID:${r}`;try{return this._recordMessageReactedByMe(D,r),v===g.CONV_C2C?yield function(VA,LA){return mA(this,void 0,void 0,function*(){var SA;const{from:PA,to:zA,clientSequence:Ee,random:Ie,time:Li,reactionID:Ui}=VA,Yt={From_Account:PA,To_Account:zA,MsgKey:`${Ee}_${Ie}_${Li}`,Reaction:Ui,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Wn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:Yt})})}({from:N,to:P,clientSequence:W,random:nA,time:EA,reactionID:r},this._core):v===g.CONV_GROUP&&(yield function(VA,LA){return mA(this,void 0,void 0,function*(){var SA;const{to:PA,reactionID:zA,sequence:Ee}=VA,Ie={GroupId:PA,MsgSeq:Ee,Reaction:zA,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Wn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:Ie})})}({to:P,reactionID:r,sequence:wA},this._core)),{code:0,successLog:{message:kA}}}catch(VA){this._removeMyReactionRecord(D,r);const{errorCode:LA}=VA||{};throw new E.ChatError({functionName:"addMessageReaction",code:LA,moreMessage:kA})}})}removeMessageReaction(s,r){return mA(this,void 0,void 0,function*(){const{OuterConstant:g,helper:u}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:E,ID:f,conversationType:D,from:v,to:N,clientSequence:P,random:W,time:nA,sequence:EA}=s,wA=`conversationID:${E} messageID:${f} reactionID:${r}`;try{return this._removeMyReactionRecord(f,r),D===g.CONV_C2C?yield function(kA,VA){return mA(this,void 0,void 0,function*(){var LA;const{from:SA,to:PA,clientSequence:zA,random:Ee,time:Ie,reactionID:Li}=kA,Ui={From_Account:SA,To_Account:PA,MsgKey:`${zA}_${Ee}_${Ie}`,Reaction:Li,Del_Account:[(LA=VA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Wn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:Ui})})}({from:v,to:N,clientSequence:P,random:W,time:nA,reactionID:r},this._core):D===g.CONV_GROUP&&(yield function(kA,VA){return mA(this,void 0,void 0,function*(){var LA;const{to:SA,reactionID:PA,sequence:zA}=kA,Ee={GroupId:SA,MsgSeq:zA,Reaction:PA,Del_Account:[(LA=VA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Wn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:Ee},VA)})}({to:N,reactionID:r,sequence:EA},this._core)),{code:0,successLog:{message:wA}}}catch(kA){const{errorCode:VA}=kA||{};throw new u.ChatError({functionName:"removeMessageReaction",code:VA,moreMessage:wA})}})}getAllUserListOfMessageReaction(s){return mA(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();const{message:r,reactionID:g,nextSeq:u=0}=s,E=s.count>100?100:s.count,{conversationID:f}=r,{ssoLog:D,helper:v,constants:N}=this._core;try{let P=null;if(P=f.startsWith(N.OuterConstant.CONV_C2C)?yield function(W){return mA(this,void 0,void 0,function*(){const{message:nA,nextSeq:EA,reactionID:wA,count:kA}=W,{from:VA,to:LA,clientSequence:SA,random:PA,time:zA}=nA,Ee={Reaction:wA,NextSeq:EA,Count:kA,From_Account:VA,To_Account:LA,MsgKey:`${SA}_${PA}_${zA}`};return Wn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:Ee})})}({message:r,reactionID:g,nextSeq:u,count:E}):yield function(W){return mA(this,void 0,void 0,function*(){const{message:nA,nextSeq:EA,reactionID:wA,count:kA}=W,{sequence:VA,to:LA}=nA,SA={Reaction:wA,NextSeq:EA,GroupId:LA,Count:kA,MsgSeq:VA};return Wn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:SA})})}({message:r,reactionID:g,nextSeq:u,count:E}),P){const{Reaction_Account:W,NextSeq:nA}=P,EA=yield this._getUserProfileList(W);return{code:0,data:{nextSeq:nA,isCompleted:u===0,userList:EA}}}}catch(P){const{errorCode:W}=P||{};throw new v.ChatError({functionName:"getAllUserListOfMessageReaction",code:W})}})}getMessageReactions(s){return mA(this,void 0,void 0,function*(){const{constants:r}=this._core;this._validateMessageReactionBusinessCapability();const{messageList:g,maxUserCountPerReaction:u=10}=s,E=g[0];let f=null;const D=new Map,{from:v,to:N,conversationType:P}=E,W=this._generateMessageKeyList(g,D);P===r.OuterConstant.CONV_C2C?f=yield function(kA){return mA(this,void 0,void 0,function*(){const{from:VA,to:LA,messageKeyList:SA,maxUserCountPerReaction:PA}=kA,zA={From_Account:VA,To_Account:LA,MsgKeyList:SA,Count:PA};return Wn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:zA})})}({from:v,to:N,messageKeyList:W,maxUserCountPerReaction:u}):P===r.OuterConstant.CONV_GROUP&&(f=yield function(kA){return mA(this,void 0,void 0,function*(){const{groupId:VA,messageSequenceList:LA,maxUserCountPerReaction:SA}=kA,PA={GroupId:VA,MsgSeqList:LA,Count:SA};return Wn.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:PA})})}({groupId:N,messageSequenceList:W,maxUserCountPerReaction:u}));const{Results:nA=[]}=f||{},EA=this._extractUserIDsFromReactionResults(nA),wA=yield this._getUserProfileMap(EA);return{code:0,data:{resultList:nA.map(kA=>{const{ReactionList:VA,MsgSeq:LA,MsgKey:SA}=kA;return{messageID:this._generateMessageID({messageSequence:LA,messageKey:SA,messageIDMap:D}),reactionList:VA.map(PA=>{const{Reaction:zA,Count:Ee,Reaction_Account:Ie,ReactedByMe:Li}=PA;return{reactionID:zA,totalUserCount:Ee,partialUserList:this._generatePartialUserInfo({userIDList:Ie,userProfileMap:wA}),reactedByMyself:Li===1}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(s){const r=[];return s?.forEach(g=>{const{ReactionList:u=[]}=g;u.forEach(E=>{E.Reaction_Account&&r.push(...E.Reaction_Account)})}),r}_getUserProfileList(s){return mA(this,void 0,void 0,function*(){var r;try{const g=yield(r=this._core.user.userProfile)===null||r===void 0?void 0:r.getUserProfile({userIDList:s});return g?g.data:[]}catch{return[]}})}_getUserProfileMap(s){return mA(this,void 0,void 0,function*(){const r=new Map;return(yield this._getUserProfileList(s)).forEach(g=>{const{nick:u,avatar:E,userID:f}=g;r.set(f,{nick:u,avatar:E,userID:f})}),r})}_recordMessageReactedByMe(s,r){const g=`${s}-${r}`;this._reactionsMap.has(g)?this._reactionsMap.get(g).reactedByMe=!0:this._reactionsMap.set(g,{reactedByMe:!0})}_removeMyReactionRecord(s,r){const g=`${s}-${r}`;this._reactionsMap.has(g)&&(this._reactionsMap.get(g).reactedByMe=!1)}_recordMessageReactionInfo(s){const{messageID:r,reactionID:g,reactionInfo:u}=s,E=`${r}-${g}`,f=this._reactionsMap.get(E)||{};this._reactionsMap.set(E,Object.assign(Object.assign({},f),u))}_validateMessageReactionBusinessCapability(){const{helper:s,constants:r}=this._core;if(!s.checkBusinessCapabilityBits(LE))throw new s.ChatError({functionName:"addMessageReaction",code:r.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(s){const{MsgReactionNotifyList:r}=s,{notificationCenter:g,constants:u}=this._core;r.forEach(E=>mA(this,void 0,void 0,function*(){const{C2CMsgInfo:f,GroupMsgInfo:D,MsgReactionSummary:v}=E,{TinyId:N,MsgClientTime:P,MsgRandom:W}=Object.assign(Object.assign({},f),D),nA=`${N}-${P}-${W}`,EA=this._extractUserIDsFromReactionResults([{ReactionList:v}]),wA=yield this._getUserProfileMap(EA),kA=v.map(VA=>{var LA;const{Reaction:SA,Reaction_Account:PA}=VA,zA=this._generatePartialUserInfo({userIDList:PA,userProfileMap:wA}),Ee=PA?VA.Count:0,Ie=((LA=this._reactionsMap.get(`${nA}-${SA}`))===null||LA===void 0?void 0:LA.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:nA,reactionID:SA,reactionInfo:{reactionID:SA,totalUserCount:Ee,partialUserList:zA}}),{reactionID:SA,totalUserCount:Ee,partialUserList:zA,reactedByMyself:Ie}});g.emitOuterEvent(u.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:u.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:nA,reactionList:kA}})}))}_handleReactionSync(s){var r;const{notificationCenter:g,constants:u}=this._core,{C2CMsgInfo:E={},GroupMsgInfo:f={},Reaction:D,OperateType:v}=s.MsgReactionNotify,{TinyId:N="",MsgClientTime:P=0,MsgRandom:W=0}=Object.assign(Object.assign({},E),f),nA=`${N}-${P}-${W}`,EA=`${nA}-${D}`;if(v===1?this._recordMessageReactedByMe(nA,D):this._removeMyReactionRecord(nA,D),(r=this._reactionsMap.get(EA))===null||r===void 0?void 0:r.reactionID){const wA=this._reactionsMap.get(EA);wA.reactedByMyself=v===1,g.emitOuterEvent(u.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:u.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:nA,reactionList:[wA]}})}}_generatePartialUserInfo({userIDList:s,userProfileMap:r}){const g=[];return s?.forEach(u=>{r.has(u)&&g.push(r.get(u))}),g}_generateMessageID(s){const{messageSequence:r,messageKey:g,messageIDMap:u}=s;return g?u.get(g):u.get(r)}_generateMessageKeyList(s,r){const{constants:g}=this._core,u=s[0],{conversationType:E}=u;let f=[];return E===g.OuterConstant.CONV_C2C?f=s.map(D=>{const{clientSequence:v,random:N,time:P,ID:W}=D,nA=`${v}_${N}_${P}`;return r.set(nA,W),nA}):E===g.OuterConstant.CONV_GROUP&&(f=s.map(D=>{const{ID:v,sequence:N}=D;return r.set(N,v),N})),f}},ig=new class{init(s){this._core=s;const{helper:r,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:u,GROUP_MESSAGE_READ_RECEIPT:E},notificationCenter:f}=s;r.registerApi({apiName:"sendMessageReadReceipt",context:this}),r.registerApi({apiName:"getMessageReadReceiptList",context:this}),r.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),f.subscribeInnerEvent(g,u,this._handleC2CMessageReadReceipt,this),f.subscribeInnerEvent(g,E,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(s){return mA(this,void 0,void 0,function*(){var r;const{common:g,constants:u}=this._core,E=this._filterValidMessageSendByOther(s);if(E.length===0)throw new g.ChatError({code:u.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:f}=E[0];return f===u.OuterConstant.CONV_C2C?yield function(D){return mA(this,void 0,void 0,function*(){const{common:v,constants:N}=Wn.core,P=D[0].conversationID.replace(N.OuterConstant.CONV_C2C,""),W=D.map(EA=>{const{from:wA,to:kA,sequence:VA,random:LA,time:SA,clientTime:PA}=EA;return{From_Account:wA,To_Account:kA,MsgSeq:VA,MsgRandom:LA,MsgTime:SA,MsgClientTime:PA}}),nA={Peer_Account:P,C2CMsgInfo:W};return v.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:nA})})}(E):yield function(D){return mA(this,void 0,void 0,function*(){const{common:v,constants:N}=Wn.core,P={GroupId:D[0].conversationID.replace(N.OuterConstant.CONV_GROUP,""),MsgSeqList:D.map(W=>({MsgSeq:W.sequence}))};return v.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:P})})}(E),{code:0,data:{}}}catch(f){const{errorCode:D,errorInfo:v}=f;throw new g.ChatError({code:D,message:v,moreMessage:`peerAccount:${(r=E?.[0])===null||r===void 0?void 0:r.conversationID}`})}})}getMessageReadReceiptList(s){return mA(this,void 0,void 0,function*(){const{common:r,constants:g}=this._core;try{const{conversationType:u}=s[0];if(u===g.OuterConstant.CONV_GROUP){const E=this._filterValidMessageSendByMe(s);if(E?.length>0){const f=yield function(v){return mA(this,void 0,void 0,function*(){const{common:N,constants:P}=Wn.core,W={GroupId:v[0].conversationID.replace(P.OuterConstant.CONV_GROUP,""),MsgSeqList:v.map(nA=>({MsgSeq:nA.sequence}))};return N.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:W})})}(E),{GroupMsgReceiptList:D}=f||{};this._updateGroupMessagesReadReceiptInfo({messageList:s,readReceiptList:D})}}return{code:0,data:{messageList:s}}}catch(u){const{errorCode:E,errorInfo:f}=u;throw new r.ChatError({code:E,message:f})}})}getGroupMessageReadMemberList(s){return mA(this,void 0,void 0,function*(){const{constants:r,common:g}=this._core,{message:u,filter:E=UE.READ,cursor:f=""}=s,{conversationID:D,sequence:v,ID:N}=u,P=D.replace(r.OuterConstant.CONV_GROUP,""),W=s.count>=100?100:s.count;try{const nA=yield function(EA){return mA(this,void 0,void 0,function*(){const{sequence:wA,groupID:kA,filter:VA,cursor:LA,count:SA}=EA,PA={MsgSeq:wA,GroupId:kA,Filter:VA,Cursor:LA,Num:SA};return Wn.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:PA})})}({groupID:P,sequence:v,filter:E,cursor:f,count:W});if(nA){const{Cursor:EA,IsFinish:wA,UnreadList:kA,ReadList:VA}=nA,LA={cursor:EA,isCompleted:wA===1,messageID:N,unreadUserIDList:[],readUserIDList:[]};return E===UE.READ?LA.readUserIDList=VA.map(SA=>SA.Read_Account):E===UE.UNREAD&&(LA.unreadUserIDList=kA.map(SA=>SA.Unread_Account)),{code:0,data:LA}}}catch(nA){const{errorCode:EA,errorInfo:wA}=nA;throw new g.ChatError({code:EA,message:wA})}})}_handleC2CMessageReadReceipt(s){const r=[],{constants:g,helper:u}=this._core,{C2cMsgInfo:E,PeerReadTime:f,Peer_Account:D}=s;if(u.isEmpty(E))return;const v=`${g.OuterConstant.CONV_C2C}${D}`;E?.forEach(N=>{const{TinyId:P,MsgClientTime:W,MsgRandom:nA}=N,EA=`${P}-${W}-${nA}`,wA=Uc({conversationID:v,messageID:EA});wA&&!wA.readReceiptInfo.isPeerRead&&(wA.readReceiptInfo.isPeerRead=!0,wA.readReceiptInfo.timestamp=f,r.push({userID:D,messageID:EA,isPeerRead:!0,timestamp:f}))}),this._emitReadReceiptEventIfNeed(r)}_updateGroupMessagesReadReceiptInfo(s){const{messageList:r,readReceiptList:g}=s,u=new Map;r.forEach(E=>{u.set(E.sequence,E)}),g?.forEach(E=>{if(E.Code===0){const{MsgSeq:f,ReadNum:D,UnreadNum:v}=E,N=u.get(f);N&&(N.readReceiptInfo.readCount=D,N.readReceiptInfo.unreadCount=v)}})}_handleGroupMessageReadReceipt(s){const r=[],{constants:g}=this._core,{GroupTips:u}=s;u.forEach(E=>{const{MsgBody:{GroupMsgReceiptList:f},GroupInfo:{GroupId:D}}=E,v=`${g.OuterConstant.CONV_GROUP}${D}`;f?.forEach(N=>{const{TinyId:P,MsgClientTime:W,MsgRandom:nA,ReadNum:EA,UnreadNum:wA}=N,kA=`${P}-${W}-${nA}`,VA=Uc({conversationID:v,messageID:kA}),LA={groupID:D,messageID:kA,readCount:0,unreadCount:0};VA&&(typeof EA=="number"&&(VA.readReceiptInfo.readCount=EA,LA.readCount=EA),typeof wA=="number"&&(VA.readReceiptInfo.unreadCount=wA,LA.unreadCount=wA),r.push(LA))})}),this._emitReadReceiptEventIfNeed(r)}_emitReadReceiptEventIfNeed(s){const{notificationCenter:r,OuterEvent:g}=this._core;s.length>0&&r.emitOuterEvent(g.MESSAGE_READ_RECEIPT_RECEIVED,{name:g.MESSAGE_READ_RECEIPT_RECEIVED,data:s})}_filterValidMessageSendByOther(s){return this._filterNeedReadReceiptMessages(s).filter(r=>{const{from:g}=r;return g!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(s){const{OuterConstant:r}=this._core.constants;return this._filterNeedReadReceiptMessages(s).filter(g=>{const{from:u,status:E}=g;return u===this._core.common.getCurrentUserID()&&E===r.MessageStatus.SUCCESS})}_filterNeedReadReceiptMessages(s){return s.filter(r=>r.needReadReceipt===!0)}dispose(){const{InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:r,GROUP_MESSAGE_READ_RECEIPT:g},notificationCenter:u}=this._core;u.unSubscribeInnerEvent(s,r,this._handleC2CMessageReadReceipt,this),u.unSubscribeInnerEvent(s,g,this._handleGroupMessageReadReceipt,this)}};function nu(s,r,g){return mA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:u}}=Wn.core,{from:E,to:f,clientSequence:D,random:v,time:N}=s;return u({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:E,To_Account:f,MsgKey:`${D}_${v}_${N}`,OperateType:g,ExtensionList:r}})})}function Yu(s,r,g){return mA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:u}}=Wn.core,{to:E,sequence:f}=s;return u({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:E,MsgSeq:f,OperateType:g,ExtensionList:r}})})}var Pc=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(s){this._core=s;const{notificationCenter:r,helper:{registerApi:g},InnerEvent:{MESSAGE_PUSH:u,LOGOUT:E},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:f}}=s;g({apiName:"setMessageExtensions",context:this}),g({apiName:"getMessageExtensions",context:this}),g({apiName:"deleteMessageExtensions",context:this}),r.subscribeInnerEvent(u,f,this._handleMessageExtensionsNotify,this),r.subscribeInnerEvent(E,this.reset,this)}setMessageExtensions(s,r){return mA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");const{constants:{OuterConstant:g},ssoLog:u}=this._core,{ID:E,conversationID:f,sequence:D,time:v,conversationType:N}=s;let P=r;r.length>20&&(P=r.slice(0,20),u.warn("setMessageExtensions","the length of extensions cannot exceed 20"));const W=this._generateServerExtensions(s,P),nA=`convID:${f} messageID:${E} sequence:${D} time:${v} count:${P.length}`;try{let EA;if(N===g.CONV_C2C?EA=yield nu(s,W,xl):N===g.CONV_GROUP&&(EA=yield Yu(s,W,xl)),EA){const{resultList:wA,successCount:kA,failureCount:VA}=this._handleModifyMessageExtensions(s,EA);return{code:0,data:{extensions:wA},successLog:{message:`${nA} successCount:${kA} failCount:${VA}`}}}return{code:0,data:{extensions:[]}}}catch(EA){const{errorCode:wA}=EA;throw new this._core.helper.ChatError({functionName:"setMessageExtensions",code:wA,moreMessage:nA})}})}getMessageExtensions(s){return mA(this,void 0,void 0,function*(){const{utils:{isUndefined:r}}=this._core;this._validateMessageExtensionBusinessCapability("getMessageExtensions");const{conversationID:g,ID:u,sequence:E,time:f}=s,D=`convID:${g} messageID:${u} sequence:${E} time:${f}`;try{let v;this._completedFetchExtensions.has(u)&&(v=this._extensionsLatestSequenceMap.get(u));const N=yield this._fetchMessageExtensions(s,v);return r(v)&&N.length>1&&this._completedFetchExtensions.add(u),{code:0,data:{extensions:N},successLog:{message:D}}}catch(v){const{errorCode:N,errorInfo:P=""}=v||{};throw new this._core.common.ChatError({code:N,message:P,moreMessage:D})}})}deleteMessageExtensions(s,r){return mA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");const{utils:{isEmpty:g},constants:{OuterConstant:u}}=this._core,{conversationType:E,conversationID:f,sequence:D,ID:v,time:N}=s;let P=xg;const W=[];g(r)||(P=Yl,r?.forEach(wA=>{W.push({key:wA,value:"",seq:0})}));const nA=`convID:${f} messageID:${v} sequence:${D} time:${N} operateType:${P}`,EA=this._generateServerExtensions(s,W);try{let wA;if(E===u.CONV_C2C?wA=yield nu(s,EA,P):E===u.CONV_GROUP&&(wA=yield Yu(s,EA,P)),wA){const{resultList:kA,successCount:VA,failureCount:LA}=this._handleModifyMessageExtensions(s,wA);return{code:0,data:{extensions:kA},successLog:{message:`${nA}successCount:${VA} failCount:${LA}`}}}return{code:0,data:{extensions:[]}}}catch(wA){const{errorCode:kA}=wA;throw new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:kA,moreMessage:nA})}})}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:r,LOGOUT:g},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:u}}=this._core;s.unSubscribeInnerEvent(r,u,this._handleMessageExtensionsNotify,this),s.subscribeInnerEvent(g,this.reset,this)}_handleModifyMessageExtensions(s,r){const{ID:g}=s,{Seq:u}=r,E=r.ExtensionList||[],f=[];let D=0,v=0,N=[];return E.forEach(P=>{const{ErrorCode:W,Extension:nA}=P,{Key:EA,Value:wA,Seq:kA}=nA;f.push({code:W,key:EA,value:wA}),W===0?D++:v++,N.push({key:EA,value:wA,seq:kA})}),this._extensionsLatestSequenceMap.set(g,u),N.length>0&&this._updateLocalExtensions(s.ID,N),{resultList:f,successCount:D,failureCount:v}}_updateLocalExtensions(s,r){this._messageExtensionsMap.has(s)||this._messageExtensionsMap.set(s,new Map);const g=this._messageExtensionsMap.get(s);r?.forEach(u=>{const{key:E,seq:f,value:D=""}=u;g?.set(E,{value:D,seq:f})})}_fetchMessageExtensions(s,r){return mA(this,void 0,void 0,function*(){const{constants:{OuterConstant:g},utils:{isEmpty:u}}=this._core;try{let E;const{conversationType:f,ID:D}=s;if(f===g.CONV_C2C?E=yield function(v,N){const{common:{buildAndSendPacket:P}}=Wn.core,{from:W,to:nA,clientSequence:EA,random:wA,time:kA}=v;return P({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:W,To_Account:nA,MsgKey:`${EA}_${wA}_${kA}`,StartSeq:N}})}(s,r):f===g.CONV_GROUP&&(E=yield function(v,N){const{common:{buildAndSendPacket:P}}=Wn.core,{to:W,sequence:nA}=v;return P({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:W,MsgSeq:nA,StartSeq:N}})}(s,r)),E){const{LatestSeq:v,ClearSeq:N,CompleteFlag:P}=E,W=(E.ExtensionList||[]).map(EA=>({key:EA.Key,value:EA.Value,seq:EA.Seq}));if(this._updateLocalExtensions(D,W),this._clearLocationExtensions(D,N),this._extensionsLatestSequenceMap.set(D,v),P!==1){const EA=W[W.length-1].seq+1;return this._fetchMessageExtensions(s,EA)}const nA=[];if(this._messageExtensionsMap.has(D)){const EA=this._messageExtensionsMap.get(D);EA?.forEach((wA,kA)=>{const{value:VA}=wA;u(VA)||nA.push({key:kA,value:VA})})}return nA}}catch(E){throw E}})}_clearLocationExtensions(s,r){if(!(r<=0)&&this._messageExtensionsMap.has(s)){const g=this._messageExtensionsMap.get(s);g?.forEach((u,E)=>{u.seq<=r&&g.delete(E)})}}_generateServerExtensions(s,r){const{ID:g}=s;if(this._messageExtensionsMap.has(g)){const u=this._messageExtensionsMap.get(g);return r.map(E=>{var f;const{key:D,value:v}=E;let N=0;return u?.has(D)&&(N=(f=u.get(D))===null||f===void 0?void 0:f.seq),{Key:D,Value:v,Seq:N}})}return r.map(u=>({Key:u.key,Value:u.value,Seq:0}))}_validateMessageExtensionBusinessCapability(s){const{helper:r,constants:g}=this._core;if(!r.checkBusinessCapabilityBits(pC))throw new r.ChatError({functionName:s,code:g.ERROR_CODE.NO_USE,replacement1:s})}_handleMessageExtensionsNotify(s){const{SetKVInfo:r,DeleteKVInfo:g,ClearKVInfo:u,MsgOptType:E,TinyId:f,MsgLastSeq:D,ExtensionC2cMsgInfo:v,ExtensionGroupMsgInfo:N}=s?.MsgExtensionNotify||{},P=v||N||{},{MsgClientTime:W,MsgRandom:nA}=P,EA=`${f}-${W}-${nA}`;this._extensionsLatestSequenceMap.set(EA,D),E===xl?this._handleMessageExtensionsUpdated({messageID:EA,updateMessageExtensionsInfo:r}):E===Yl?this._handleMessageExtensionsDeleted({messageID:EA,deleteMessageExtensionsInfo:g}):E===xg&&this._handleMessageExtensionsCleared({messageID:EA,clearMessageExtensionsInfo:u})}_handleMessageExtensionsUpdated(s){const{notificationCenter:r,OuterEvent:g}=this._core,{messageID:u,updateMessageExtensionsInfo:E=[]}=s,f=[];E.forEach(D=>{const{MsgKeyValue:v=[]}=D,N=v.map(P=>(f.push({key:P.Key,value:P.Value}),{key:P.Key,value:P.Value,seq:P.Seq}));this._updateLocalExtensions(u,N)}),r.emitOuterEvent(g.MESSAGE_EXTENSIONS_UPDATED,{name:g.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:u,extensions:f}})}_handleMessageExtensionsDeleted(s){const{notificationCenter:r,OuterEvent:g}=this._core,{messageID:u,deleteMessageExtensionsInfo:E=[]}=s,f=[];E.forEach(D=>{const{MsgKeyValue:v=[]}=D,N=v.map(P=>(f.push(P.Key),{key:P.Key,seq:P.Seq}));this._updateLocalExtensions(u,N)}),r.emitOuterEvent(g.MESSAGE_EXTENSIONS_DELETED,{name:g.MESSAGE_EXTENSIONS_DELETED,data:{messageID:u,keyList:f}})}_handleMessageExtensionsCleared(s){const{notificationCenter:r,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:g},utils:{isEmpty:u}}=this._core,{messageID:E,clearMessageExtensionsInfo:f=[]}=s,D=[];f.forEach(v=>{const{ClearMsgSeq:N}=v;this._messageExtensionsMap.has(E)&&(this._messageExtensionsMap.get(E)||[]).forEach((P,W)=>{P.seq<=N&&!u(P.value)&&D.push(W)}),this._clearLocationExtensions(E,N)}),r.emitOuterEvent(g,{name:g,data:{messageID:E,keyList:D}})}};const SI={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{constants:{OuterConstant:r}}=Wn.core;return s.status!==r.MessageStatus.SUCCESS?"message is not success":s.isSupportExtension===!0||"message is not support extension"}},ll={setMessageExtensions:[SI,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[SI],deleteMessageExtensions:[SI]},Il=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const r=function(g){var u;return typeof g?.text!="string"||typeof g.text=="string"&&((u=g?.text)===null||u===void 0?void 0:u.length)===0?"payload.text is invalid.":!0}(s);return r!==!0?r:!(s?.atUserList&&!Array.isArray(s.atUserList))||"atUserList should be an array or undefind."}}},findMessage:[{required:!0,rules:["string"],allowEmpty:!1}],translateText:{sourceTextList:{required:!0,rules:["array"],allowEmpty:!1},sourceLanguage:{required:!0,rules:["string"],allowEmpty:!1},targetLanguage:{required:!0,rules:["string"],allowEmpty:!1}},createForwardMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!s.startsWith("C2C")&&!s.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1}},createLocationMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{utils:{isString:r,isNumber:g}}=Wn.core;return r(s?.description)?g(s?.longitude)?!!g(s?.latitude)||"payload.latitude must be a number.":"payload.longitude must be a number.":"payload.description must be a string."}}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s!="number"?"maxUserCountPerReaction is invalid.":!(s<0||s>10)||"maxUserCountPerReaction should between [0, 10]."}},getAllUserListOfMessageReaction:{message:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>s.status==="success"||"message is invalid."},reactionID:{required:!0,rules:["string"],allowEmpty:!1},nextSeq:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["object"],allowEmpty:!1},filter:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),ll),{pinGroupMessage:{groupID:{required:!0,rules:["string"],allowEmpty:!1},message:{required:!0,rules:["object"],allowEmpty:!1},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},getPinnedGroupMessageList:[{key:"groupID",required:!0,rules:["string"],allowEmpty:!1}]}),{createQuoteMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"quotedMessage",required:!0,rules:["object"],allowEmpty:!1}]}),qa=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0,createLocationMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0,getAllUserListOfMessageReaction:!0}),{sendMessageReadReceipt:!0,getMessageReadReceiptList:!0,getGroupMessageReadMemberList:!0}),{setMessageExtensions:!0,getMessageExtensions:!0,deleteMessageExtensions:!0}),{pinGroupMessage:!0,getPinnedGroupMessageList:!0}),{createQuoteMessage:!0});class PE{constructor(r){this._core=r}deleteMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:u}=r,E={From_Account:this._core.common.getCurrentUserID(),To_Account:g,MsgKeyList:u};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:E})})}revokeMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,from:u,sequence:E,time:f,random:D}=r,v={MsgInfo:{From_Account:u,To_Account:g,MsgSeq:E,MsgRandom:D,MsgTimeStamp:f}};return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:v})})}}class la{constructor(r){this._core=r}deleteMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:u}=r,E={GroupId:g,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:u};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:E})})}revokeMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,sequence:u}=r,E={GroupId:g,MsgSeqList:[{MsgSeq:u}]};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:E})})}}const Gs=2116;class Or{constructor(r){this._core=r}generateRevokeMessage(r){const{conversationID:g,sequence:u,random:E,tinyID:f,clientTime:D,revokeReason:v,revoker:N}=r;let P={};const{messageDataHandler:W}=this._core.message;return P=W.revokeMessage({conversationID:g,sequence:u,random:E,revoker:N}),P||(P={conversationID:g,sequence:u},f&&D&&E&&(P.ID=`${f}-${D}-${E}`)),P.revoker=N,P.revokeReason=v,P.revokerInfo={userID:N,nick:"",avatar:""},P}updateRevokerInfo(r){return mA(this,void 0,void 0,function*(){const g=r.map(u=>u.revoker);try{const u=yield this._fetchUserInfos(g);u&&r.forEach(E=>{const{revoker:f}=E;u[f]&&(E.revokerInfo.nick=u[f].nick||"",E.revokerInfo.avatar=u[f].avatar||"",E.revokerInfo.userID=f)})}catch(u){console.debug(u)}})}_fetchUserInfos(r){return mA(this,void 0,void 0,function*(){var g,u;const E=yield(g=this._core.user.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:r});return E?.data?(u=E.data)===null||u===void 0?void 0:u.reduce((f,{userID:D,nick:v,avatar:N})=>(f[D]={nick:v||"",avatar:N||""},f),{}):null})}}var ul=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(s){this._core=s,this._groupMessageAction=new la(s),this._c2cMessageAction=new PE(s),this._messageHelper=new Or(s);const{helper:r}=s;r.registerApi({apiName:"deleteMessage",context:this}),r.registerApi({apiName:"revokeMessage",context:this}),r.registerApi({apiName:"resendMessage",context:this}),r.registerApi({apiName:"findMessage",context:this}),r.registerApi({apiName:"createQuoteMessage",context:this})}deleteMessage(s){return mA(this,void 0,void 0,function*(){let r=[],g=[];const{conversationID:u,conversationType:E}=s[0],f=u.replace(E,"");if(E==="@TIM#SYSTEM")throw new this._core.helper.ChatError({code:Gs});if(s.forEach(D=>{const{conversationID:v,conversationType:N,status:P,_onlineOnlyFlag:W,sequence:nA,random:EA,time:wA}=D||{};if(P==="success"&&v===u&&N===E){if(!W){const kA=N==="C2C"?`${nA}_${EA}_${wA}`:String(nA);r.push(kA)}g.push(D)}}),r.length===0)return this._handleDeleteMessageSuccess(g),{code:0,data:{messageList:g}};r.length>30&&(r=r.slice(0,30),g=g.slice(0,30));try{return E==="C2C"?yield this._c2cMessageAction.deleteMessage({to:f,messageIdentifiers:r}):yield this._groupMessageAction.deleteMessage({to:f,messageIdentifiers:r}),this._handleDeleteMessageSuccess(g),{code:0,data:{messageList:g}}}catch(D){const{utils:{safeStringify:v}}=this._core,{errorCode:N,errorInfo:P}=D;throw new this._core.helper.ChatError({functionName:"deleteMessage",code:N,message:P,moreMessage:`messageIdentifiers: ${v(r)}`})}})}revokeMessage(s){return mA(this,void 0,void 0,function*(){var r;const{conversationType:g,isRevoked:u,ID:E,type:f,from:D,to:v}=s;let N=null;const P=`type:${f} from:${D} to:${v} ID:${E}`;if(g==="@TIM#SYSTEM")throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(u)throw new this._core.helper.ChatError({message:"message has been revoked",moreMessage:P});try{if(N=g==="C2C"?yield this._c2cMessageAction.revokeMessage(s):yield this._groupMessageAction.revokeMessage(s),N){const{RecallRetList:W}=N,nA=((r=W?.[0])===null||r===void 0?void 0:r.RetCode)||0;if(nA!==0)throw new this._core.helper.ChatError({code:nA,moreMessage:P});return s.isRevoked=!0,yield this._handleRevokeMessageSuccess(s),{code:0,data:{message:s},successLog:{message:P}}}}catch(W){const{errorCode:nA}=W;throw new this._core.helper.ChatError({functionName:"revokeMessage",code:nA,moreMessage:P})}})}resendMessage(s,r){return mA(this,void 0,void 0,function*(){var g,u;return s.isResend=!0,s.status="unSend",(u=(g=this._core)===null||g===void 0?void 0:g.apiMap)===null||u===void 0?void 0:u.sendMessage(s,r)})}findMessage(s){return this._core.message.messageDataHandler.findMessage(s)}createQuoteMessage(s,r){const{ID:g,time:u,sequence:E}=r;return s.quoteInfo={msgID:g,messageTime:u,messageSequence:E},s}_handleDeleteMessageSuccess(s){if(s.length===0)return;const{message:{messageDataHandler:r},common:{isTopic:g},notificationCenter:u,InnerEvent:E}=this._core;s.forEach(D=>{D.isDeleted=!0;const v=r.getLocalMessageList(D.conversationID);v?.forEach(N=>{N.ID===D.ID&&(N.isDeleted=!0)})});const{conversationID:f=""}=s[0];g(f)?u.emitInnerEvent(E.TOPIC_MESSAGE_DELETED,f):u.emitInnerEvent(E.MESSAGE_DELETED,f)}_handleRevokeMessageSuccess(s){return mA(this,void 0,void 0,function*(){var r;const g=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,{conversationID:u,sequence:E,random:f}=s;this._core.message.messageDataHandler.revokeMessage({conversationID:u,sequence:E,random:f,revoker:g}),yield this._messageHelper.updateRevokerInfo([s])})}};class Vl{static parseServerPushElement(r){const{MsgContent:g={}}=r,{Index:u,Data:E}=g;return new Vl({index:u,data:E})}constructor(r){this.type=Kr.MSG_FACE;const{index:g,data:u}=r;this.content={index:g,data:u}}validateBeforeSend(){var r,g;return typeof((r=this.content)===null||r===void 0?void 0:r.index)=="number"&&typeof((g=this.content)===null||g===void 0?void 0:g.data)=="string"?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{index:E,data:f}=u;return{MsgType:this.type,MsgContent:{Index:E,Data:f}}}}class xc{static parseServerPushElement(r){const{MsgContent:g={}}=r,{Desc:u,Longitude:E,Latitude:f}=g;return new xc({description:u,longitude:E,latitude:f})}constructor(r){this.type=Kr.MSG_LOCATION;const{description:g,longitude:u,latitude:E}=r;this.content={description:g,longitude:u,latitude:E}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{description:E,longitude:f,latitude:D}=u;return{MsgType:this.type,MsgContent:{Desc:E,Longitude:f,Latitude:D}}}}class xE{static parseServerPushElement(r){const{MsgContent:g={}}=r,{StreamMsgID:u,CompatibleText:E,Markdown:f,BinaryData:D,ErrorCode:v,ErrorMsg:N}=g;return new xE({streamMessageID:u,compatibleText:E,markdown:f,binaryData:D,errorCode:v,errorMessage:N})}constructor(r){this.type=Kr.MSG_STREAM,this.content={streamMessageID:"",compatibleText:"",errorCode:0,errorMessage:"",isStreamEnded:!1},this._chunks=[],this._latestIndex=0;const{streamMessageID:g,compatibleText:u,markdown:E,binaryData:f,errorCode:D=0,errorMessage:v="",isStreamEnded:N=!1,chunks:P=[],latestIndex:W=0}=r;this.content.streamMessageID=g,this.content.compatibleText=u,this.content.markdown=E,this.content.binaryData=f,this.content.errorCode=D,this.content.errorMessage=v,this.content.isStreamEnded=N,this.content.chunks=P,this.content.latestIndex=W}updateChunks(r){if(!r||r.length===0)return;const g=r.sort((f,D)=>f.index-D.index),u=this._getMaxRevokedChunkIndex(g);u>=0&&(this._chunks=[],this._latestIndex=u,this._updateContent());const E=this._getValidChunks(g);if(E.length!==0&&(this._mergeAndSortChunks(E),this._chunks.length>0)){const f=this._chunks[this._chunks.length-1];this._latestIndex=f.index,this._updateContent(),this.content.isStreamEnded=f.isLast}}getLatestIndex(){return this._latestIndex}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{streamMessageID:E,chunks:f}=u,D=f?.map(v=>({EventType:v.eventType||"data",Index:v.index,Markdown:v.markdown,IsLast:v.isLast}));return{MsgType:this.type,MsgContent:{StreamMsgID:E,Chunks:D}}}validateBeforeSend(){var r,g;return((g=(r=this.content)===null||r===void 0?void 0:r.chunks)===null||g===void 0?void 0:g.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}_filterContinuousChunks(r,g){if(r.length===0)return[];const u=[];let E=g;for(const f of r){if(f.index>E)break;f.index===E&&(u.push(f),E++)}return u}_mergeAndSortChunks(r){const g=new Map;this._chunks.forEach(u=>{g.set(u.index,u)}),r.forEach(u=>{g.set(u.index,u)}),this._chunks=Array.from(g.values()).sort((u,E)=>u.index-E.index)}_updateContent(){this.content.markdown=this._chunks.map(g=>g.markdown).join("");const r=this._chunks.map(g=>g.binaryData).filter(g=>g?.length>0);if(r.length===0)this.content.binaryData=new Uint8Array(0);else if(r.length===1)this.content.binaryData=r[0];else{const g=r.reduce((f,D)=>f+D.length,0),u=new Uint8Array(g);let E=0;for(const f of r)u.set(f,E),E+=f.length;this.content.binaryData=u}}_getMaxRevokedChunkIndex(r){let g=-1;for(let u=0;ug&&(g=E.index)}return g}_getValidChunks(r){const g=r.filter(u=>u.eventType===Oc.DATA&&u.index>this._latestIndex);return this._filterContinuousChunks(g,this._latestIndex+1)}}var Yc=new class{init(s){this._core=s,s.message.messageFactory.registerElementClass(Kr.MSG_FACE,Vl),s.message.messageFactory.registerElementClass(Kr.MSG_LOCATION,xc),s.message.messageFactory.registerElementClass(Kr.MSG_STREAM,xE),s.helper.registerApi({apiName:"createFaceMessage",context:this}),s.helper.registerApi({apiName:"createTextAtMessage",context:this}),s.helper.registerApi({apiName:"createForwardMessage",context:this}),s.helper.registerApi({apiName:"createLocationMessage",context:this})}createFaceMessage(s){if(!s)return null;const{index:r,data:g}=s?.payload||{},u=new Vl({index:r,data:g}),E=this._core.common.getCurrentUserID(),f=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return f.setElement(u),f}createTextAtMessage(s){const{atUserList:r}=s?.payload||{},g=this._core.apiMap.createTextMessage(s),{OuterConstant:u}=this._core;if(!g)return null;if(Array.isArray(r)){const E=[],f=[];r.forEach(D=>{D!==u.MSG_AT_ALL?(E.push({GroupAtAllFlag:Eh,GroupAt_Account:D}),f.push(D)):(E.push({GroupAtAllFlag:uo}),f.push(u.MSG_AT_ALL))}),g._groupAtInfoList=E,g.atUserList=f}return g}createForwardMessage(s){const{helper:r,OuterConstant:g}=this._core,{to:u,conversationType:E,priority:f,payload:D,needReadReceipt:v,receiverList:N,cloudCustomData:P="",isSupportExtension:W=!1}=s;if(!Array.isArray(D._elements))throw new r.ChatError({functionName:"createForwardMessage",code:2454});if(D.type===g.MSG_GRP_TIP)throw new r.ChatError({functionName:"createForwardMessage",code:2453});const nA=this._core.common.getCurrentUserID(),EA=this._core.message.messageFactory.createMessage({to:u,from:nA,conversationType:E,isPlaceMessage:0,priority:f,payload:D,needReadReceipt:v,isSupportExtension:W,cloudCustomData:P,receiverList:N});return EA.setRelayFlag(!0),EA.setElement(D._elements[0]),EA}createLocationMessage(s){if(!s)return null;const{description:r,longitude:g,latitude:u}=s?.payload||{},E=new xc({description:r,longitude:g,latitude:u}),f=this._core.common.getCurrentUserID(),D=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:f}));return D.setElement(E),D}};let Vu=class{init(s){this._messageHelper=new Or(s),this._core=s;const{notificationCenter:r,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_REVOKED_MESSAGE:u},helper:{registerWorkflowStep:E},constants:{WORKFLOW_NAME:f,WORKFLOW_STEP:D}}=s;r.subscribeInnerEvent(g,u,this._handleC2CNotifyMessage,this),E(f.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(s){const{C2cNotifyMsgArray:r}=s;r?.forEach(g=>{Object.keys(g).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(g)})}_handleC2CRevokeMessage(s){return mA(this,void 0,void 0,function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:r}}=s;yield this._parseAndEmitC2CRevokedMessages(r)}catch(r){console.debug(r)}})}_parseAndEmitC2CRevokedMessages(s){return mA(this,void 0,void 0,function*(){const r=[],{notificationCenter:g,OuterEvent:u,common:{getCurrentUserID:E}}=this._core;s.forEach(f=>{var D;const{MsgRand:v,MsgSeq:N,To_Account:P,From_Account:W,RevokerInfo:{Revoker_Account:nA,Revoke_Reason:EA}}=f,wA=E()===W?`C2C${P}`:`C2C${W}`,kA=((D=f?.RevokerInfo)===null||D===void 0?void 0:D.Reason)||EA,VA=this._messageHelper.generateRevokeMessage({conversationID:wA,sequence:N,random:v,revoker:nA,revokeReason:kA});r.push(VA)}),r.length>0&&(yield this._messageHelper.updateRevokerInfo(r),g.emitOuterEvent(u.MESSAGE_REVOKED,{name:u.MESSAGE_REVOKED,data:r}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(s){return mA(this,void 0,void 0,function*(){const{revokedMessageList:r}=s.result;yield this._parseAndEmitC2CRevokedMessages(r)})}dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:r},InnerEventSubType:{C2C_REVOKED_MESSAGE:g}}=this._core;s.unSubscribeInnerEvent(r,g,this._handleC2CNotifyMessage,this)}},yC=class{init(s){this._messageHelper=new Or(s),this._core=s;const{notificationCenter:r,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{GROUP_MESSAGE_REVOKED:u}}=s;r.subscribeInnerEvent(g,u,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(s){const{GroupTips:r}=s;r?.forEach(g=>{var u;Array.isArray((u=g?.MsgBody)===null||u===void 0?void 0:u.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(g)})}_handleGroupRevokeMessage(s){return mA(this,void 0,void 0,function*(){try{const{RevokerInfo:r,MsgBody:{GroupWithdrawInfoArray:g},GroupInfo:u}=s,E=[],f=[],{notificationCenter:D,OuterEvent:v,utils:{isEmpty:N},common:{isCommunity:P}}=this._core;let W=!1;u&&(W=P({groupID:u.GroupId})||!N(u.TopicId)),g.forEach(nA=>{const{Random:EA,MsgSeq:wA,GroupId:kA,MsgClientTime:VA,TinyId:LA,TopicId:SA,RevokerInfo:{Revoker_Account:PA=r?.Revoker_Account||"",Reason:zA=r?.Reason||""}}=nA,Ee=SA?`GROUP${SA}`:`GROUP${kA}`,Ie=this._messageHelper.generateRevokeMessage({conversationID:Ee,sequence:wA,random:EA,tinyID:LA,clientTime:VA,revoker:PA,revokeReason:zA});W?(Ie.revokerInfo.nick=u.From_AccountNick,Ie.revokerInfo.avatar=u.From_AccountHeadurl,E.push(Ie)):f.push(Ie)}),f.length>0&&(yield this._messageHelper.updateRevokerInfo(f),E.push(...f)),E.length!==0&&D.emitOuterEvent(v.MESSAGE_REVOKED,{name:v.MESSAGE_REVOKED,data:E})}catch(r){console.debug(r)}})}dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:r},InnerEventSubType:{GROUP_MESSAGE_REVOKED:g}}=this._core;s.unSubscribeInnerEvent(r,g,this._handleGroupNotifyMessage,this)}};var su=new class{constructor(){this._c2cMessageReceiver=new Vu,this._groupMessageReceiver=new yC}init(s){this._c2cMessageReceiver.init(s),this._groupMessageReceiver.init(s)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}},dh=new class{constructor(){this._core=null}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"translateText",context:this})}translateText(s){return mA(this,void 0,void 0,function*(){try{const{sourceLanguage:r,sourceTextList:g,targetLanguage:u}=s,E=yield function(f,D){return mA(this,void 0,void 0,function*(){var v,N;const{sourceTextList:P,sourceLanguage:W,targetLanguage:nA}=f,{store:EA,common:wA}=D,kA={SourceText:P,Source:W,Target:nA,FromAccount:(v=EA.get("login"))===null||v===void 0?void 0:v.tinyID,SDKAppID:(N=EA.get("instance"))===null||N===void 0?void 0:N.sdkAppId},VA=yield wA.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:kA});if(VA){const{CmdErrorCode:LA,TargetText:SA}=VA;return{cmdErrorCode:LA,translatedTextList:SA}}})}({sourceLanguage:r,sourceTextList:g,targetLanguage:u},this._core);if(E){const{cmdErrorCode:{ErrorCode:f,ErrorInfo:D},translatedTextList:v}=E;if(f===0)return{code:0,data:{translatedTextList:v}};throw{errorCode:f,errorInfo:D,message:D}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};throw new this._core.helper.ChatError({functionName:"translateText",code:g,message:u})}})}},Hu=new class{init(s){this._core=s,s.helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(s){return mA(this,void 0,void 0,function*(){var r;const{message:g,language:u=Fc.ZH_PY}=s;let{url:E}=g.payload||{};const f=this._core.common.getCurrentUserID();g.from===f&&g.flow==="out"&&(E=g.payload.remoteAudioUrl),this._validateVoiceFormat(E);const D=((r=DI.exec(E))===null||r===void 0?void 0:r[1])||"mp3",v=yI[u]||iu;try{const N=yield function(P){var W;const{store:nA,common:EA}=Wn.core,{url:wA,format:kA,serverLanguageType:VA}=P,LA={BytesUrl:wA,BytesEngServiceType:VA,BytesVoiceFormat:kA,Uint32Sdkappid:(W=nA.get("instance"))===null||W===void 0?void 0:W.sdkAppId,Uint64SourceType:0};return EA.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:LA})}({url:E,format:D,serverLanguageType:v});if(N){const{CmdErrorCode:P,BytesResult:W}=N;if(P.ErrorCode===0)return{code:0,data:{result:W}};throw{code:P.ErrorCode,message:P.ErrorInfo}}}catch(N){const{code:P,message:W}=N||{};throw new this._core.common.ChatError({functionName:"convertVoiceToText",code:P,message:W})}})}_validateVoiceFormat(s){if(!DI.test(s))throw new this._core.common.ChatError({code:2119})}};class vI{constructor(r){const{constants:g,common:u,utils:E}=Wn.core,{CONV_C2C:f,CONV_GROUP:D}=g.OuterConstant,{ID:v,tinyID:N,from:P,to:W,clientTime:nA=u.timeManager.getServerTimeSeconds()||0,random:EA,sequence:wA,cloudCustomData:kA="",nick:VA="",avatar:LA="",clientSequence:SA,conversationType:PA,groupID:zA,_elements:Ee,time:Ie}=r;this.ID=v||`${N}-${nA}-${EA}`,this.messageRandom=EA,this.from=P,this.messageSender=P,this.time=Ie,this.messageSequence=wA,this.clientSequence=SA||wA,this.clientTime=nA,this.cloudCustomData=kA,this.messageReceiver=W,this.avatar=LA,this.nick=VA;const Li=E.deepCopyWithMethods(Ee);Li.forEach(Ui=>{Ui.payload=Ui.content,delete Ui.content}),this.messageBody=Li,v?PA.startsWith(f)?this.receiverUserID=W:PA.startsWith(D)&&(this.receiverGroupID=W):zA?(this.receiverGroupID=zA,this.messageReceiver=zA):W&&(this.receiverUserID=W,this.messageReceiver=W)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(r=>r.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class El{static parseServerPushElement(r){const{MsgContent:g}=r,{MsgList:u=[],CompatibleText:E,AbstractList:f,Title:D,PbMsgKey:v,JsonMsgKey:N}=g||{},P=u.map(W=>Sr(W));return new El({messageList:P,title:D,abstractList:f,compatibleText:E,pbDownloadKey:v,downloadKey:N})}constructor(r){this.type=Wn.core.constants.OuterConstant.MSG_MERGER;const{messageList:g,title:u,abstractList:E,compatibleText:f,pbDownloadKey:D="",downloadKey:v="",version:N=0,layersOverLimit:P=!1}=r,W=[];g.forEach(nA=>{if(nA){const EA=new vI(nA);W.push(EA)}}),this.content={messageList:W,title:u,abstractList:E,compatibleText:f,version:N,downloadKey:v,pbDownloadKey:D,layersOverLimit:P}}validateBeforeSend(){const{isEmpty:r}=Wn.core.helper;return r(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{abstractList:E,compatibleText:f,downloadKey:D,layersOverLimit:v,pbDownloadKey:N,title:P,version:W,messageList:nA}=u;return{MsgType:this.type,MsgContent:{AbstractList:E,CompatibleText:f,JsonMsgKey:D,LayersOverLimit:v,PbMsgKey:N,Title:P,Version:W,MsgList:sc(nA)}}}}var DC=new class{init(s){this._core=s;const{message:r,helper:g,constants:{OuterConstant:u}}=s;r.messageFactory.registerElementClass(u.MSG_MERGER,El),g.registerApi({apiName:"createMergerMessage",context:this}),g.registerApi({apiName:"sendMessage",context:this,matcher:E=>E[0].type===u.MSG_MERGER}),g.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(s){const{common:r}=this._core;if(!s)return null;const g=new El(s.payload),u=r.getCurrentUserID(),E=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:u}));return E.setRelayFlag(!0),E.setElement(g),E}sendMessage(s,r){return mA(this,void 0,void 0,function*(){var g,u,E;try{const f=function(P){let W="utf-8";Wn.core.helper.IN_BROWSER&&document&&(W=document.charset.toLowerCase());let nA,EA=0,wA=0;if(wA=P.length,W==="utf-8"||W==="utf8")for(let kA=0;kA11264){D=this._core.utils.deepCopyWithMethods(s);try{const{JsonMsgKey:P,PbMsgKey:W}=yield function(EA){return mA(this,void 0,void 0,function*(){const{payload:{messageList:wA}}=EA,kA={MsgList:sc(wA)};return Wn.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:kA})})}(D),{payload:nA}=D;v=new El(Object.assign(Object.assign({},nA),{messageList:[],downloadKey:P,pbDownloadKey:W})),D.setElement(v)}catch(P){console.error(P)}}const{data:{message:N}}=yield(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(D,r);return v&&N.setElement(s._elements),{code:0,data:{message:N}}}catch(f){const{errorCode:D}=f;throw new this._core.helper.ChatError({code:D})}})}downloadMergerMessage(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r}=this._core,g=s.payload,{downloadKey:u,pbDownload:E,type:f,messageList:D}=g,v=vo(g,["downloadKey","pbDownload","type","messageList"]);try{const N=yield function(nA){return mA(this,void 0,void 0,function*(){return Wn.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:nA}})})}(u),{MsgList:P}=N||{},W=P?.map(nA=>{const EA=Sr(nA);return new vI(EA)});return typeof s.isOnlineMessage=="function"?s.setElement({type:s.type,content:Object.assign({messageList:W},v)}):(s.payload.messageList=W,s.payload.downloadKey="",s.payload.pbDownloadKey=""),r.info("downloadMergerMessage",` success downloadKey:${u}`),s}catch(N){const{errorCode:P}=N;throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:P,moreMessage:u})}})}},Ia=new class{init(s){this._core=s,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(s){return mA(this,void 0,void 0,function*(){const{appStore:r,message:g,common:{getCurrentUserID:u},utils:{isArray:E}}=this._core,{GroupId:f,To_Account:D}=s;s.From_Account=s.From_Account||u();let v=null;if(f){v=this._generateGroupMessage(Object.assign(Object.assign({},s),{ToGroupId:f}));const N=r.userStore.getUserProfile(u());v.level=N?.level||0,E(D)&&D.length>0&&(v._receiverList=D)}else D&&(v=this._generateC2CMessage(s));return g.messageSender.sendMessage(v,s)})}_generateC2CMessage(s){const{message:r,OuterConstant:{CONV_C2C:g}}=this._core,u=g,E=r.messageHelper.parseServerPushMessage(s),f=r.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:u,flow:rc.OUT})),{elements:D}=E;return f.setElement(D),f}_generateGroupMessage(s){const{message:r,OuterConstant:{CONV_GROUP:g}}=this._core,u=g,E=r.messageHelper.parseServerGroupMessage(s),f=r.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:u,flow:rc.OUT})),{elements:D}=E;return f.setElement(D),f}},ac=new class{init(s){this._core=s;const{helper:r,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:u},InnerEventSubType:{GROUP_MESSAGE_PINNED:E}}=s;g.subscribeInnerEvent(u,E,this._handleGroupMessagePinned,this),r.registerApi({apiName:"pinGroupMessage",context:this}),r.registerApi({apiName:"getPinnedGroupMessageList",context:this})}pinGroupMessage(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,common:{isTopic:g},OuterConstant:{GROUP_ID_PREFIX:u},helper:{ChatError:E}}=this._core;let{groupID:f,message:D,isPinned:v}=s;const{sequence:N}=D;try{return yield function(P){return mA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:W,getCurrentUserID:nA}}=Wn.core,{groupID:EA,sequence:wA,isPinned:kA}=P,VA=nA(),LA=kA?"group_open_http_svc.pin_message":"group_open_http_svc.unpin_message",SA={GroupId:EA,MsgSeq:wA};return kA?SA.Pinner_Account=VA:SA.UnPinner_Account=VA,W({servcmd:LA,data:SA})})}({groupID:f,sequence:N,isPinned:v}),{code:0,data:{}}}catch(P){const{errorCode:W,errorInfo:nA}=P||{};throw new E({code:W,message:nA})}})}getPinnedGroupMessageList(s){return mA(this,void 0,void 0,function*(){let r=[];try{const g=yield function(u){return mA(this,void 0,void 0,function*(){const{groupID:E}=u,{common:{buildAndSendPacket:f}}=Wn.core;return f({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:E}})})}({groupID:s});if(g){const{PinnedMsgList:u=[]}=g;r=yield this._updatePinnedMessageInfo({serverPinnedMessageList:u,groupID:s})}return{code:0,data:{messageList:r}}}catch(g){throw g}})}_handleGroupMessagePinned(s){const{message:{messageHelper:r,messageFactory:g},notificationCenter:u,OuterEvent:E,OuterConstant:f}=this._core;s.GroupTips.forEach(D=>{const{ToGroupId:v,MsgBody:{PinnedMsg:N,OpType:P,MsgOperatorMemberExtraInfo:W,SdkGroupMessageId:nA}}=D,{UserId:EA,NickName:wA="",ImageUrl:kA=""}=W;let VA=null,LA=!1;if(P===yd){LA=!0;const SA=r.parseServerGroupMessage(N);VA=g.createMessage(Object.assign(Object.assign({},SA),{conversationType:f.CONV_GROUP,flow:"in"})),VA.setElement(SA.elements),VA.pinnerInfo={userID:EA,nick:wA,avatar:kA}}else if(P===FE){const{ClientTime:SA,Random:PA,SenderTinyId:zA,ServerTime:Ee,MsgSeq:Ie}=nA;VA={ID:`${zA}-${SA}-${PA}`,sequence:Ie,random:PA,time:Ee,clientTime:SA}}VA&&u.emitOuterEvent(E.PINNED_GROUP_MESSAGE_UPDATED,{name:E.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:v,message:VA,isPinned:LA,operatorInfo:{userID:EA,nick:wA,avatar:kA}}})})}_findMessageBySequence(s,r){const{message:{messageDataHandler:g}}=this._core;return[...g.getLocalMessageList(s),...g.getSparseMessageList(s)].find(u=>u.sequence===r)}_updatePinnedMessageInfo(s){return mA(this,arguments,void 0,function*({serverPinnedMessageList:r,groupID:g}){const{OuterConstant:{CONV_GROUP:u},utils:{isEmpty:E}}=this._core,f=[],D=[],v=[],N=new Map,P=`${u}${g}`;for(let nA=0;nA{const{sequence:kA}=wA,VA=N.get(kA),LA=nA[VA]||{userID:VA,nick:"",avatar:""};wA.pinnerInfo=LA}),f.sort((wA,kA)=>wA.sequence-kA.sequence),f}return[]})}_fetchPinnedMessageInfo(s){return mA(this,void 0,void 0,function*(){var r,g;const{message:{messageHistory:u},user:{userProfile:E},utils:{isArray:f}}=this._core,{conversationID:D,messageSequenceList:v,pinnerIDList:N}=s,P=yield Promise.all([this._fetchMessageBySequence({conversationID:D,messageSequenceList:v}),E?.getUserProfile({userIDList:N})]);if(f(P)){const W={};return(((r=P[1])===null||r===void 0?void 0:r.data)||[]).forEach(nA=>{const{userID:EA,nick:wA="",avatar:kA=""}=nA;W[EA]={userID:EA,nick:wA,avatar:kA}}),{messageList:((g=P[0])===null||g===void 0?void 0:g.messageList)||[],pinnerInfoMap:W}}})}_fetchMessageBySequence(s){return mA(this,void 0,void 0,function*(){const{utils:{isEmpty:r},message:{messageHistory:g}}=this._core,{conversationID:u,messageSequenceList:E}=s;return r(E)?[]:g.getGroupRoamingMessagesByAnchor({conversationID:u,messageSequenceList:E,getType:3})})}};class dg{constructor(r){this.eventType=Oc.DATA,this.index=0,this.markdown="",this.isLast=!1,this.binaryData=null;const{EventType:g,Index:u,Markdown:E,IsLast:f,BinaryData:D}=r;this.eventType=g,this.index=u,this.markdown=E,this.isLast=f,this.binaryData=D}}var MI=new class{constructor(){this._messageMap=new Map,this._retryCountMap=new Map}init(s){this._core=s;const{notificationCenter:r,OuterEvent:{MESSAGE_RECEIVED:g},InnerEvent:{HISTORY_MESSAGE_FETCHED:u},common:{workflowManager:E},constants:{WORKFLOW_NAME:f,WORKFLOW_STEP:D}}=s;r.subscribeInnerEvent(ho,this._handleStreamMessageChunkPush,this),r.subscribeOuterEvent(g,this._handleMessageReceived,this),r.subscribeInnerEvent(u,this.processHistoryMessage,this),E.registerWorkflowStep(f.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.STREAM_MESSAGE_RECOVER,this._recoverStreamMessage,this)}processHistoryMessage(s){const{utils:{isEmpty:r,safeStringify:g},ssoLog:u}=this._core;try{s?.forEach(E=>{var f;if(this._isValidStreamMessage(E)){const D=(f=E?._elements)===null||f===void 0?void 0:f[0],{streamMessageID:v,markdown:N,binaryData:P}=D?.content||{};r(N)&&r(P)?(this._messageMap.set(v,E),this._fetchStreamMessageChunks(E)):D.content.isStreamEnded=!0}})}catch(E){u.error("processHistoryMessage.error",g(E))}}_handleMessageReceived(s){const r=s.data;r?.forEach(g=>{var u,E;if(this._isValidStreamMessage(g)){const{streamMessageID:f}=((E=(u=g?._elements)===null||u===void 0?void 0:u[0])===null||E===void 0?void 0:E.content)||{};f&&(this._messageMap.set(f,g),this._fetchStreamMessageChunks(g))}})}_isValidStreamMessage(s){var r,g;const{utils:{isEmpty:u}}=this._core,{streamMessageID:E}=((g=(r=s?._elements)===null||r===void 0?void 0:r[0])===null||g===void 0?void 0:g.content)||{};return s.type===Kr.MSG_STREAM&&!u(E)}_fetchStreamMessageChunks(s){return mA(this,void 0,void 0,function*(){var r,g;const{constants:{ERROR_CODE:u},ssoLog:E,utils:{safeStringify:f}}=this._core,D=(r=s._elements)===null||r===void 0?void 0:r[0],v=(g=D?.content)===null||g===void 0?void 0:g.streamMessageID;try{const{from:N,to:P}=s,W=D.getLatestIndex();if(D.content.isStreamEnded)return;const nA=yield function(EA){return mA(this,void 0,void 0,function*(){const{from:wA,to:kA,streamMessageID:VA,index:LA}=EA,SA={From_Account:wA,To_Account:kA,StreamMsgID:VA,AckIndex:LA};return Wn.core.common.buildAndSendPacket({servcmd:"StreamMsg.GetStreamHttp",data:SA,timeout:5e3})})}({from:N,to:P,streamMessageID:v,index:W});if(nA){const{ErrorCode:EA,ErrorInfo:wA}=nA;if(EA!==0)throw D.content.errorCode=EA,D.content.errorMessage=wA,{errorCode:EA,errorMessage:wA}}}catch(N){if(N.errorCode===u.NETWORK_TIMEOUT&&this._shouldRetryFetch(v)){const P=this._retryCountMap.get(v)||0;E.debug("_fetchStreamMessageChunks.timeout",`error: ${f(N)} retried: ${P}`),this._retryCountMap.set(v,P+1),this._fetchStreamMessageChunks(s)}else E.error("_fetchStreamMessageChunks.error",f(N))}})}_shouldRetryFetch(s){const{utils:{isNumber:r}}=this._core;if(!this._retryCountMap.has(s))return this._retryCountMap.set(s,1),!0;const g=this._retryCountMap.get(s);return!!(r(g)&&g<=3)}_onStreamEnded(s,r,g){const{ssoLog:u}=this._core;g.content.isStreamEnded=!0,g.stopReason=r,this._messageMap.delete(s),u.debug("_onStreamEnded",`streamMessage end, StopReason: ${r}`)}_handleStreamMessageChunkPush(s){var r;const{ssoLog:g}=this._core,{StopReason:u,Chunks:E,StreamID:f}=s?.body||{},D=this._messageMap.get(f);if(!D)return void g.warn(`_handleStreamMessageChunkPush, unfounded message: ${f}`);const v=(r=D._elements)===null||r===void 0?void 0:r[0];if(v&&this._validateExpectedChunk(v,E)){if(E.length>0){const N=E.map(P=>new dg(P));v.updateChunks(N)}this._emitMessageModify(D),function(N,P){mA(this,void 0,void 0,function*(){const{common:{generateProtocolData:W},utils:{safeStringify:nA},ssoLog:EA,channel:wA}=Wn.core,kA={StreamMsgID:N,AckIndex:P};try{const VA=W({servcmd:"StreamMsg.AckHttp",data:kA});wA.sendPacket(VA)}catch(VA){EA.debug("sendStreamChunkAck",nA(VA))}})}(f,v.getLatestIndex()),v.content.isStreamEnded&&this._onStreamEnded(f,u,v)}}_emitMessageModify(s){const{notificationCenter:r,OuterEvent:{MESSAGE_MODIFIED:g}}=this._core;r.emitOuterEvent(g,{name:g,data:[s]})}_validateExpectedChunk(s,r){const g=s.getLatestIndex()+1;let u=!1;for(let E=0;Ef.Index).join(", ")}]`),!1}return!0}_recoverStreamMessage(){this._retryCountMap.clear();const{ssoLog:s,utils:{safeStringify:r}}=this._core;try{const g=Array.from(this._messageMap.entries());for(let u=Math.max(0,g.length-300);u{const LA=this._getResponseBody(kA,E,nA&&EA),SA=this._buildResponse(kA,LA);if(kA.status===200)r(null,SA);else{if(EA&&!wA.includes(EA))return s.url=this._domainName2IP(wA,EA),s.uploadByIP=!0,this.request(s,r);r({code:kA.status,message:JSON.stringify(kA.responseText)},SA)}},kA.onerror=()=>{const LA=this._getResponseBody(kA,E,nA&&EA),SA=this._buildResponse(kA,LA),PA={code:kA.status,message:kA.status===0?"CORS blocked or network error":JSON.stringify(kA.responseText)};r(PA,SA)},s.onProgress&&kA.upload&&(kA.upload.onprogress=LA=>{const{total:SA,loaded:PA}=LA,zA=Math.min(Math.floor(100*PA/SA),100);s.onProgress({total:SA,loaded:PA,percent:zA/100})}),kA.send(P),kA})}_buildResponse(s,r){const g={};return s.getAllResponseHeaders().trim().split(` +`).forEach(u=>{if(u){const[E,f]=u.split(":").map(D=>D.trim());g[E.toLowerCase()]=f}}),{statusCode:s.status,statusMessage:s.statusText,headers:g,data:r}}_getResponseBody(s,r,g){return s.status===200&&r?{location:r,uploadIP:g}:{response:s.responseText,uploadIP:g}}_queryString(s,r="&",g="="){var u;const{isEmpty:E,isPlainObject:f}=(u=this._core)===null||u===void 0?void 0:u.utils;return E(s)?"":f(s)?Object.keys(s).map(D=>{const v=encodeURIComponent(D)+g;return Array.isArray(s[D])?s[D].map(N=>v+encodeURIComponent(N)).join(r):v+encodeURIComponent(s[D])}).filter(Boolean).join(r):void 0}_domainName2IP(s,r){return s.replace(/^http(s)?:\/\/(.*?)\//,`https://${r}/`)}};const qu=["unknown","image","video","audio","log"];var RI=new class{init(s){this._core=s}request(s,r){var g;const{MINI_APP_NAMESPACE:u,IN_ALIPAY_MINI_APP:E,isUniIOSApp:f}=(g=this._core)===null||g===void 0?void 0:g.utils,{resources:D="",headers:v={},url:N,downloadUrl:P=""}=s;let W=N,nA=null;const EA=P?P.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!EA)return void console.warn("message Invalid download URL format");const wA=decodeURIComponent(EA[3]),kA=wA.includes("?")?wA.split("?")[0]:wA||"",VA={key:s.fileKey||kA,success_action_status:200,"Content-Type":""},LA={};if(f()){const[PA,zA]=N.split("?sign=");zA&&(W=`${PA}?sign=${encodeURIComponent(zA)}`,LA.sign=decodeURIComponent(zA),LA.signature=decodeURIComponent(zA))}let SA={url:W,header:v,name:"file",filePath:D,formData:Object.assign(Object.assign({},VA),LA),timeout:s.timeout||3e5};if(E){const{name:PA}=SA,zA=vo(SA,["name"]);SA=Object.assign(Object.assign({},zA),{fileName:"file",fileType:s.fileType?qu[s.fileType]:"image"})}return nA=u.uploadFile(Object.assign(Object.assign({},SA),{success:PA=>{this._handleResponse({response:PA,downloadUrl:P,callback:r})},fail:PA=>{this._handleResponse({response:PA,downloadUrl:P,callback:r})}})),nA.onProgressUpdate&&nA.onProgressUpdate(PA=>{s.onProgress&&s.onProgress({total:PA.totalBytesExpectedToSend||0,loaded:PA.totalBytesSent||0,percent:PA.progress?Math.floor(PA.progress)/100:0})}),nA}_handleResponse(s){const{downloadUrl:r,response:g,callback:u}=s,E={};if(g.header)for(const D in g.header)g.header.hasOwnProperty(D)&&(E[D.toLowerCase()]=g.header[D]);const f=+g.statusCode;f===200?u(null,{statusCode:f,headers:E,data:Object.assign(Object.assign({},g.data),{location:r})}):u({code:f,message:JSON.stringify(g.data)},{statusCode:f,headers:E,data:void 0})}};function dl(s){return function(r){return Object.prototype.toString.call(r).match(/^\[object (.*)\]$/)[1].toLowerCase()}(s)==="file"}function Pr(s){const r=s||99999999;return Math.round(Math.random()*r)}function xr(s,r=!0,g=!0){const u=Date.now();return r?g?u-s+" ms":`${Math.round((u-s)/1e3)} s`:g?u-s:Math.round((u-s)/1e3)}function Cg(s){return`${Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")}-${s}`}function Br(s,r){return Math.round(Number(s)*10**r)/10**r}function Nr(s){return s<=1048576?`${Br(s/1024,1)}KB/s`:`${Br(s/1048576,1)}MB/s`}const gc="TIMImageElem",Yg="TIMSoundElem",Ka="TIMFileElem",Hl="TIMVideoFileElem",ya="RichMediaMessagePlugin",wI=["rich.my-imcloud.com","imrich.qcloud.com"],ru=1,Da=2,Cl=3,VE=255;var au;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(au||(au={}));const HE={wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/},jr=Symbol("isCustomUpload");var gu,Vt=new class{init(s){this._core=s}addAuthToUrl(s=""){if(this._isMiniProgramTempFile(s))return s;const r=function(g){return g?g.startsWith("https://")?g:g.startsWith("http://")?g.replace("http://","https://"):g:""}(s);return this.processResourceUrl(r)}removeAuthToUrl(s){return function(r,g){const[u,E]=r.split("?");if(!E)return u;const f=E.split("&").reduce((v,N)=>{const[P,W]=N.split("=");return P&&P!==g&&(v[P]=W||""),v},{}),D=Object.keys(f).map(v=>`${v}${f[v]?`=${f[v]}`:""}`).join("&");return D?`${u}?${D}`:u}(s,"authKey")}_isMiniProgramTempFile(s){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(HE).some(r=>r.test(s))}extractFileFromInput(s){const{utils:{isArray:r}}=this._core;return dl(s)?s:function(g){if(typeof g!="object"||g===null)return!1;const u=Object.getPrototypeOf(g);if(u===null)return!0;let E=u;for(;Object.getPrototypeOf(E)!==null;)E=Object.getPrototypeOf(E);return u===E}(s)&&typeof uni<"u"?r(s.tempFiles)&&s.tempFiles.length>0?s.tempFiles[0]:r(s.files)?s.files[0]:s.tempFile?s.tempFile:null:s instanceof HTMLInputElement&&s.files&&s.files.length>0?s.files[0]:null}probeImageWidthHeight(s){return mA(this,void 0,void 0,function*(){var r;const{IN_MINI_APP:g,IN_BROWSER:u}=((r=this._core)===null||r===void 0?void 0:r.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:u?this._probeImageDimensionsWeb(s):g?this._probeImageDimensionsMiniApp(s):void 0})}isSimpleCos(){var s;const r=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{simple_cos:g}=r;return g!=="0"}getFileDNList(){var s;let r=wI;const g=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{file_dn_list:u}=g;if(u===void 0)return r;try{JSON.parse(u).forEach(E=>{r.includes(E)||r.push(E)})}catch(E){console.warn(E),r=wI}return r}getPlatform(){var s;return(s=this._core)===null||s===void 0?void 0:s.utils.platform}generateUUID(s,r){var g;let u=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${(g=this._core)===null||g===void 0?void 0:g.utils.randomString()}`;if(r)return`${u}.${r}`;const E=s.name||s.value||s.url||s.tempFilePath,f=E&&E.slice(E.lastIndexOf(".")+1);return f&&(u=`${u}.${f}`),u}processResourceUrl(s){if(!s)return"";let r=s;const g=this.getFileDownloadProxy(),u=this.getAuthKey(),E=this.getFileDNList();return g&&(s.startsWith("http://")?r=s.replace(/^http:\/\/[^/]+/,g):s.startsWith("https://")&&(r=s.replace(/^https:\/\/[^/]+/,g))),u&&r.indexOf("authKey=")===-1&&function(D,v){let N=!1;if(D){const P=D.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),W=P&&P[2]||"";if(W.includes("rich-dev"))return!0;for(let nA=0;nA-1?`${r}&authKey=${u}`:`${r}?authKey=${u}`),r}getCurrentUserID(){var s,r;return(r=(s=this._core)===null||s===void 0?void 0:s.store.get("login"))===null||r===void 0?void 0:r.userId}getSDKAppID(){var s,r;return(r=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||r===void 0?void 0:r.sdkAppId}getFileDownloadProxy(){var s,r;return((r=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||r===void 0?void 0:r.fileDownloadProxy)||""}getFileUploadProxy(){var s,r;return((r=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||r===void 0?void 0:r.fileUploadProxy)||""}getAuthKey(){var s,r;return((r=(s=this._core)===null||s===void 0?void 0:s.store.get("login"))===null||r===void 0?void 0:r.authKey)||""}isPrivateNetWork(){var s,r;return(r=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||r===void 0?void 0:r.proxyServer}getPlatformFlags(){var s;const{IN_BROWSER:r,IN_MINI_APP:g,IN_RN_APP:u,IN_UNI_NATIVE_APP:E}=(s=this._core)===null||s===void 0?void 0:s.utils;return{IN_BROWSER:r,IN_MINI_APP:g,IN_RN_APP:u,IN_UNI_NATIVE_APP:E}}isEmpty(s){var r;const{isEmpty:g}=(r=this._core)===null||r===void 0?void 0:r.utils;return g(s)}generateURL(s,r){const{needAddAuthToUrl:g=!0}=r||{};return g?this.addAuthToUrl(s):s}_probeImageDimensionsMiniApp(s){var r;const{MINI_APP_NAMESPACE:g}=((r=this._core)===null||r===void 0?void 0:r.utils)||{};return new Promise(u=>{g.getImageInfo({src:s,success:E=>u({width:E.width,height:E.height}),fail:()=>u({width:0,height:0})})})}_shouldSkipProbing(){var s;const{IN_RN_APP:r,IS_IE:g,IE_VERSION:u,IN_WX_MINI_GAME:E}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};return r||g&&u===9||E}_probeImageDimensionsWeb(s){return new Promise(r=>{const g=new Image,u=()=>{g.onload=null,g.onerror=null,g.src=""};g.onload=()=>{r({width:g.width,height:g.height}),u()},g.onerror=()=>{r({width:0,height:0}),u()},g.src=s})}},Ku={exports:{}},ju=(gu||(gu=1,function(s){s.exports=function(r){var g=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function u(LA,SA){var PA=LA[0],zA=LA[1],Ee=LA[2],Ie=LA[3];zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA&Ee|~zA&Ie)+SA[0]-680876936|0)<<7|PA>>>25)+zA|0)&zA|~PA&Ee)+SA[1]-389564586|0)<<12|Ie>>>20)+PA|0)&PA|~Ie&zA)+SA[2]+606105819|0)<<17|Ee>>>15)+Ie|0)&Ie|~Ee&PA)+SA[3]-1044525330|0)<<22|zA>>>10)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA&Ee|~zA&Ie)+SA[4]-176418897|0)<<7|PA>>>25)+zA|0)&zA|~PA&Ee)+SA[5]+1200080426|0)<<12|Ie>>>20)+PA|0)&PA|~Ie&zA)+SA[6]-1473231341|0)<<17|Ee>>>15)+Ie|0)&Ie|~Ee&PA)+SA[7]-45705983|0)<<22|zA>>>10)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA&Ee|~zA&Ie)+SA[8]+1770035416|0)<<7|PA>>>25)+zA|0)&zA|~PA&Ee)+SA[9]-1958414417|0)<<12|Ie>>>20)+PA|0)&PA|~Ie&zA)+SA[10]-42063|0)<<17|Ee>>>15)+Ie|0)&Ie|~Ee&PA)+SA[11]-1990404162|0)<<22|zA>>>10)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA&Ee|~zA&Ie)+SA[12]+1804603682|0)<<7|PA>>>25)+zA|0)&zA|~PA&Ee)+SA[13]-40341101|0)<<12|Ie>>>20)+PA|0)&PA|~Ie&zA)+SA[14]-1502002290|0)<<17|Ee>>>15)+Ie|0)&Ie|~Ee&PA)+SA[15]+1236535329|0)<<22|zA>>>10)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA&Ie|Ee&~Ie)+SA[1]-165796510|0)<<5|PA>>>27)+zA|0)&Ee|zA&~Ee)+SA[6]-1069501632|0)<<9|Ie>>>23)+PA|0)&zA|PA&~zA)+SA[11]+643717713|0)<<14|Ee>>>18)+Ie|0)&PA|Ie&~PA)+SA[0]-373897302|0)<<20|zA>>>12)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA&Ie|Ee&~Ie)+SA[5]-701558691|0)<<5|PA>>>27)+zA|0)&Ee|zA&~Ee)+SA[10]+38016083|0)<<9|Ie>>>23)+PA|0)&zA|PA&~zA)+SA[15]-660478335|0)<<14|Ee>>>18)+Ie|0)&PA|Ie&~PA)+SA[4]-405537848|0)<<20|zA>>>12)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA&Ie|Ee&~Ie)+SA[9]+568446438|0)<<5|PA>>>27)+zA|0)&Ee|zA&~Ee)+SA[14]-1019803690|0)<<9|Ie>>>23)+PA|0)&zA|PA&~zA)+SA[3]-187363961|0)<<14|Ee>>>18)+Ie|0)&PA|Ie&~PA)+SA[8]+1163531501|0)<<20|zA>>>12)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA&Ie|Ee&~Ie)+SA[13]-1444681467|0)<<5|PA>>>27)+zA|0)&Ee|zA&~Ee)+SA[2]-51403784|0)<<9|Ie>>>23)+PA|0)&zA|PA&~zA)+SA[7]+1735328473|0)<<14|Ee>>>18)+Ie|0)&PA|Ie&~PA)+SA[12]-1926607734|0)<<20|zA>>>12)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA^Ee^Ie)+SA[5]-378558|0)<<4|PA>>>28)+zA|0)^zA^Ee)+SA[8]-2022574463|0)<<11|Ie>>>21)+PA|0)^PA^zA)+SA[11]+1839030562|0)<<16|Ee>>>16)+Ie|0)^Ie^PA)+SA[14]-35309556|0)<<23|zA>>>9)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA^Ee^Ie)+SA[1]-1530992060|0)<<4|PA>>>28)+zA|0)^zA^Ee)+SA[4]+1272893353|0)<<11|Ie>>>21)+PA|0)^PA^zA)+SA[7]-155497632|0)<<16|Ee>>>16)+Ie|0)^Ie^PA)+SA[10]-1094730640|0)<<23|zA>>>9)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA^Ee^Ie)+SA[13]+681279174|0)<<4|PA>>>28)+zA|0)^zA^Ee)+SA[0]-358537222|0)<<11|Ie>>>21)+PA|0)^PA^zA)+SA[3]-722521979|0)<<16|Ee>>>16)+Ie|0)^Ie^PA)+SA[6]+76029189|0)<<23|zA>>>9)+Ee|0,zA=((zA+=((Ee=((Ee+=((Ie=((Ie+=((PA=((PA+=(zA^Ee^Ie)+SA[9]-640364487|0)<<4|PA>>>28)+zA|0)^zA^Ee)+SA[12]-421815835|0)<<11|Ie>>>21)+PA|0)^PA^zA)+SA[15]+530742520|0)<<16|Ee>>>16)+Ie|0)^Ie^PA)+SA[2]-995338651|0)<<23|zA>>>9)+Ee|0,zA=((zA+=((Ie=((Ie+=(zA^((PA=((PA+=(Ee^(zA|~Ie))+SA[0]-198630844|0)<<6|PA>>>26)+zA|0)|~Ee))+SA[7]+1126891415|0)<<10|Ie>>>22)+PA|0)^((Ee=((Ee+=(PA^(Ie|~zA))+SA[14]-1416354905|0)<<15|Ee>>>17)+Ie|0)|~PA))+SA[5]-57434055|0)<<21|zA>>>11)+Ee|0,zA=((zA+=((Ie=((Ie+=(zA^((PA=((PA+=(Ee^(zA|~Ie))+SA[12]+1700485571|0)<<6|PA>>>26)+zA|0)|~Ee))+SA[3]-1894986606|0)<<10|Ie>>>22)+PA|0)^((Ee=((Ee+=(PA^(Ie|~zA))+SA[10]-1051523|0)<<15|Ee>>>17)+Ie|0)|~PA))+SA[1]-2054922799|0)<<21|zA>>>11)+Ee|0,zA=((zA+=((Ie=((Ie+=(zA^((PA=((PA+=(Ee^(zA|~Ie))+SA[8]+1873313359|0)<<6|PA>>>26)+zA|0)|~Ee))+SA[15]-30611744|0)<<10|Ie>>>22)+PA|0)^((Ee=((Ee+=(PA^(Ie|~zA))+SA[6]-1560198380|0)<<15|Ee>>>17)+Ie|0)|~PA))+SA[13]+1309151649|0)<<21|zA>>>11)+Ee|0,zA=((zA+=((Ie=((Ie+=(zA^((PA=((PA+=(Ee^(zA|~Ie))+SA[4]-145523070|0)<<6|PA>>>26)+zA|0)|~Ee))+SA[11]-1120210379|0)<<10|Ie>>>22)+PA|0)^((Ee=((Ee+=(PA^(Ie|~zA))+SA[2]+718787259|0)<<15|Ee>>>17)+Ie|0)|~PA))+SA[9]-343485551|0)<<21|zA>>>11)+Ee|0,LA[0]=PA+LA[0]|0,LA[1]=zA+LA[1]|0,LA[2]=Ee+LA[2]|0,LA[3]=Ie+LA[3]|0}function E(LA){var SA,PA=[];for(SA=0;SA<64;SA+=4)PA[SA>>2]=LA.charCodeAt(SA)+(LA.charCodeAt(SA+1)<<8)+(LA.charCodeAt(SA+2)<<16)+(LA.charCodeAt(SA+3)<<24);return PA}function f(LA){var SA,PA=[];for(SA=0;SA<64;SA+=4)PA[SA>>2]=LA[SA]+(LA[SA+1]<<8)+(LA[SA+2]<<16)+(LA[SA+3]<<24);return PA}function D(LA){var SA,PA,zA,Ee,Ie,Li,Ui=LA.length,Yt=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ui;SA+=64)u(Yt,E(LA.substring(SA-64,SA)));for(PA=(LA=LA.substring(SA-64)).length,zA=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],SA=0;SA>2]|=LA.charCodeAt(SA)<<(SA%4<<3);if(zA[SA>>2]|=128<<(SA%4<<3),SA>55)for(u(Yt,zA),SA=0;SA<16;SA+=1)zA[SA]=0;return Ee=(Ee=8*Ui).toString(16).match(/(.*?)(.{0,8})$/),Ie=parseInt(Ee[2],16),Li=parseInt(Ee[1],16)||0,zA[14]=Ie,zA[15]=Li,u(Yt,zA),Yt}function v(LA){var SA,PA,zA,Ee,Ie,Li,Ui=LA.length,Yt=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ui;SA+=64)u(Yt,f(LA.subarray(SA-64,SA)));for(PA=(LA=SA-64>2]|=LA[SA]<<(SA%4<<3);if(zA[SA>>2]|=128<<(SA%4<<3),SA>55)for(u(Yt,zA),SA=0;SA<16;SA+=1)zA[SA]=0;return Ee=(Ee=8*Ui).toString(16).match(/(.*?)(.{0,8})$/),Ie=parseInt(Ee[2],16),Li=parseInt(Ee[1],16)||0,zA[14]=Ie,zA[15]=Li,u(Yt,zA),Yt}function N(LA){var SA,PA="";for(SA=0;SA<4;SA+=1)PA+=g[LA>>8*SA+4&15]+g[LA>>8*SA&15];return PA}function P(LA){var SA;for(SA=0;SA"u"||ArrayBuffer.prototype.slice||function(){function LA(SA,PA){return(SA=0|SA||0)<0?Math.max(SA+PA,0):Math.min(SA,PA)}ArrayBuffer.prototype.slice=function(SA,PA){var zA,Ee,Ie,Li,Ui=this.byteLength,Yt=LA(SA,Ui),Oi=Ui;return PA!==r&&(Oi=LA(PA,Ui)),Yt>Oi?new ArrayBuffer(0):(zA=Oi-Yt,Ee=new ArrayBuffer(zA),Ie=new Uint8Array(Ee),Li=new Uint8Array(this,Yt,zA),Ie.set(Li),Ee)}}(),VA.prototype.append=function(LA){return this.appendBinary(W(LA)),this},VA.prototype.appendBinary=function(LA){this._buff+=LA,this._length+=LA.length;var SA,PA=this._buff.length;for(SA=64;SA<=PA;SA+=64)u(this._hash,E(this._buff.substring(SA-64,SA)));return this._buff=this._buff.substring(SA-64),this},VA.prototype.end=function(LA){var SA,PA,zA=this._buff,Ee=zA.length,Ie=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(SA=0;SA>2]|=zA.charCodeAt(SA)<<(SA%4<<3);return this._finish(Ie,Ee),PA=P(this._hash),LA&&(PA=kA(PA)),this.reset(),PA},VA.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},VA.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},VA.prototype.setState=function(LA){return this._buff=LA.buff,this._length=LA.length,this._hash=LA.hash,this},VA.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},VA.prototype._finish=function(LA,SA){var PA,zA,Ee,Ie=SA;if(LA[Ie>>2]|=128<<(Ie%4<<3),Ie>55)for(u(this._hash,LA),Ie=0;Ie<16;Ie+=1)LA[Ie]=0;PA=(PA=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),zA=parseInt(PA[2],16),Ee=parseInt(PA[1],16)||0,LA[14]=zA,LA[15]=Ee,u(this._hash,LA)},VA.hash=function(LA,SA){return VA.hashBinary(W(LA),SA)},VA.hashBinary=function(LA,SA){var PA=P(D(LA));return SA?kA(PA):PA},VA.ArrayBuffer=function(){this.reset()},VA.ArrayBuffer.prototype.append=function(LA){var SA,PA=wA(this._buff.buffer,LA),zA=PA.length;for(this._length+=LA.byteLength,SA=64;SA<=zA;SA+=64)u(this._hash,f(PA.subarray(SA-64,SA)));return this._buff=SA-64>2]|=zA[SA]<<(SA%4<<3);return this._finish(Ie,Ee),PA=P(this._hash),LA&&(PA=kA(PA)),this.reset(),PA},VA.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},VA.ArrayBuffer.prototype.getState=function(){var LA=VA.prototype.getState.call(this);return LA.buff=EA(LA.buff),LA},VA.ArrayBuffer.prototype.setState=function(LA){return LA.buff=nA(LA.buff,!0),VA.prototype.setState.call(this,LA)},VA.ArrayBuffer.prototype.destroy=VA.prototype.destroy,VA.ArrayBuffer.prototype._finish=VA.prototype._finish,VA.ArrayBuffer.hash=function(LA,SA){var PA=P(v(new Uint8Array(LA)));return SA?kA(PA):PA},VA}()}(Ku)),Ku.exports),SC=uI(ju),K=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(s){var r;this._core=s;const{IN_MINI_APP:g}=s.utils;this.httpRequest=g?RI:Ju,(r=this.httpRequest)===null||r===void 0||r.init(s)}uploadToCOS(s){return mA(this,void 0,void 0,function*(){const r=`${ya} uploadToCOS`,{ssoLog:g,utils:{safeStringify:u}}=this._core,{file:E}=s;this.uploadFileType=s.uploadFileType,g.debug("uploadToCOS",`${r} options:${u(s)}`);try{const f=Date.now(),D=yield this._createCosOptions(s),v=D.fileExistsInCOS?{data:{location:D.downloadUrl}}:yield this._uploadFile(D);this._handleUploadError(v,s);const N=this._createUploadResult(E,v),P=Date.now()-f,W=function(EA){return EA<1024?`${EA}B`:EA<1048576?`${Math.floor(EA/1024)}KB`:`${Math.floor(EA/1048576)}MB`}(E.size),nA=`size:${W} time:${P}ms speed:${Nr(1e3*E.size/P)}`;return g.debug("uploadToCOS",`${r} ok. name:${E.name} ${nA}`),{uploadOptions:D,response:N}}catch(f){throw g.warn("uploadToCOS",`${r} failed, error:${u(f)}`),f}})}_handleUploadError(s,r){var g,u;const{ChatError:E}=(g=this._core)===null||g===void 0?void 0:g.helper;if(s.statusCode===403)throw r.url,!((u=s?.data)===null||u===void 0)&&u.uploadIP&&s.data.uploadIP,new E({message:"Upload failed with status 403"})}_createUploadResult(s,r){return{fileName:s.name,fileSize:s.size,fileType:s.type.slice(s.type.indexOf("/")+1).toLowerCase(),location:r.data.location||"",uploadTime:xr(Date.now(),!1),uploadSpeed:Nr(1e3*s.size/xr(Date.now(),!1))}}_createCosOptions(s){return mA(this,void 0,void 0,function*(){const{fileName:r,resources:g,uploadMethod:u}=yield this._prepareUploadParams(s),E=this._isC2CConversation(s.message.conversationID)?1:2;try{const f=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:r,uploadMethod:u,duration:this.duration,userID:s.message.from,conversationType:E}),{uploadUrl:D,downloadUrl:v,requestSnapshotUrl:N,thumbUrl:P,largeUrl:W,fileKey:nA,existFlag:EA}=f,wA=!Vt.isPrivateNetWork()&&f.uploadIP;return{url:this._getRawOrUploadProxyUrl(D),fileType:this.uploadFileType,fileName:r,resources:g,downloadUrl:v,requestSnapshotUrl:N,thumbUrl:P,largeUrl:W,fileKey:nA,uploadIP:wA||"",fileExistsInCOS:EA===1,onProgress:kA=>this._handleUploadProgress(kA,s)}}catch(f){throw console.error("Failed to create COS pre-signed URL options:",f),f}})}_prepareUploadParams(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g,isEmpty:u}}=this._core;r.debug("_prepareUploadParams",` prepareUploadParams:${g(s)}`);const{file:E}=s,{IN_MINI_APP:f,IN_RN_APP:D}=Vt.getPlatformFlags(),v=f||D,N=v&&s.message.type!==Ka,{name:P}=E,W=P.slice(P.lastIndexOf(".")),nA=`${Pr(999999)}${W}`,EA=N?E.name:nA,wA=yield this._generateHashFileName(E);return{fileName:u(wA)?Cg(EA):`${wA}${W}`,resources:v?E.url:E,uploadMethod:v?1:0}})}_generateHashFileName(s){return mA(this,void 0,void 0,function*(){const{utils:{IN_MINI_APP:r,IN_BROWSER:g,IN_UNI_NATIVE_APP:u,isArray:E},ssoLog:f}=this._core,D=Date.now();let v="";return g&&(v=yield this._generateHashFileNameInWeb(s)),r&&(E(s.tempFiles)&&(s=s.tempFiles[0]),u||(v=yield this._generateFileNameInMiniProgram(s)),u&&(v=yield this._generateFileNameInUNINativeApp(s))),f.info("_generateHashFileName",`hashFileName:${v} costTime:${Date.now()-D}`),v})}_generateHashFileNameInWeb(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;let u="";try{u=yield new Promise((E,f)=>{const D=File.prototype.slice||File.prototype.mozSlice||File.prototype.webkitSlice;D||(r.warn("_generateHashFileNameInWeb","Browser does not support file slicing"),E(""));const v=10485760,N=Math.ceil(s.size/v);let P=0;const W=new SC.ArrayBuffer,nA=new FileReader,EA=setTimeout(()=>{nA.abort(),r.warn("_generateHashFileNameInWeb","File hash generation timeout"),E("")},2e3);function wA(){const kA=P*v,VA=kA+v>=s.size?s.size:kA+v;nA.readAsArrayBuffer(D.call(s,kA,VA))}nA.onload=kA=>{r.debug("_generateHashFileNameInWeb",`read chunk nr ${P+1} of ${N}`),W.append(kA.target.result),P++,P{clearTimeout(EA),f(kA)},wA()})}catch(E){r.warn("_generateHashFileNameInWeb",g(E))}return u})}_generateFileNameInMiniProgram(s){return mA(this,void 0,void 0,function*(){const{utils:{MINI_APP_NAMESPACE:r,safeStringify:g,isEmpty:u},ssoLog:E}=this._core;let f="";if(u(s.url))return E.warn("_generateFileNameInMiniProgram","file.url is empty"),f;if(typeof r?.getFileSystemManager!="function")return E.warn("_generateFileNameInUNINativeApp","getFileSystemManager is not a function"),f;try{f=yield new Promise((D,v)=>{r.getFileSystemManager().getFileInfo({filePath:s.url,success:N=>{D(N.digest)},fail:N=>{v(N)}})})}catch(D){E.warn("_generateFileNameInMiniProgram",g(D))}return f})}_generateFileNameInUNINativeApp(s){return mA(this,void 0,void 0,function*(){var r;const{utils:{safeStringify:g,isEmpty:u},ssoLog:E}=this._core;let f="";if(u(s.url))return E.warn("_generateFileNameInUNINativeApp","file.url is empty"),f;if(typeof((r=plus==null?void 0:plus.io)===null||r===void 0?void 0:r.getFileInfo)!="function")return E.warn("_generateFileNameInUNINativeApp","plus.io.getFileInfo is not a function"),f;try{f=yield new Promise((D,v)=>{plus.io.getFileInfo({filePath:s.url,success:N=>{D(N.digest)},fail:N=>{v(N)}})})}catch(D){E.warn("_generateFileNameInMiniProgram",g(D))}return f})}_handleUploadProgress(s,r){if(typeof r.onProgress=="function")try{r.onProgress(s.percent)}catch(g){throw console.warn("Upload progress callback error:",g),g}}_fetchCosSignatureUrl(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core,u=Vt.isSimpleCos(),E=this._prepareCosRequestData(s),f=u?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const D=yield function(N,P,W){return mA(this,void 0,void 0,function*(){try{const{helper:nA,channel:EA}=W,wA=nA.generateCosSpecifiedData({servcmd:N,data:P}),kA=`${wA.head.seq}${N}`;return yield EA.sendPacket(wA,{requestId:kA})}catch(nA){throw console.warn("getCosSig error:",nA),nA}})}(f,E,this._core);this.fetchCosTryCount=0;const v=this._processResponse(D);return r.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${u} data:${g(v)}`),v||{}}catch(D){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(s);throw this.fetchCosTryCount=0,D}})}_processResponse(s){var r;const g=Vt.isSimpleCos(),u=g?(r=s?.rpt_pre_sig)===null||r===void 0?void 0:r[0]:s;if(!u)return{};if(g){const{str_final_ip:W,rpt_pre_sig:nA,uint32_file_id:EA,uint32_exist_flag:wA,str_download_url:kA,str_upload_url:VA,str_snapshot_url:LA,str_file_key:SA}=u;return{uploadIP:W,preSig:nA,fileID:EA,existFlag:wA,downloadUrl:kA,uploadUrl:VA,requestSnapshotUrl:LA,fileKey:SA}}const{upload_url:E,download_url:f,snapshot_url:D,thumb_url:v,large_url:N,file_key:P}=u;return{uploadUrl:E,downloadUrl:f,requestSnapshotUrl:D,thumbUrl:v,largeUrl:N,fileKey:P}}_prepareCosRequestData(s){return Vt.isSimpleCos()?{uint32_upload_method:s.uploadMethod,uint32_platform:Vt.getPlatform(),uint32_sdkappid:Vt.getSDKAppID(),str_user_id:s.userID,uint32_scene:s.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:s.fileType,str_file_name:s.fileName}]}:{file_type:s.fileType,file_name:s.fileName,upload_method:s.uploadMethod,Duration:s.duration}}_uploadFile(s){return mA(this,void 0,void 0,function*(){return new Promise((r,g)=>{this.httpRequest.request(s,(u,E)=>{u&&this.uploadFileTryCount=3e4}_syncSystemClock(s){var r,g,u;const E=((r=s.headers)===null||r===void 0?void 0:r.date)||((g=s.headers)===null||g===void 0?void 0:g.Date)||((u=s.error)===null||u===void 0?void 0:u.ServerTime);if(E){const f=Date.now(),D=Date.parse(E);this.systemClockOffset=D-f}}_getRawOrUploadProxyUrl(s){const r=Vt.getFileUploadProxy();let g=s;return r&&(g=s.replace(/^https:\/\/[^/]+/,r)),g}_isC2CConversation(s){return s.slice(0,3)==="C2C"}};const U=2108,sA=2251,k=2252,x=2253,iA=["jpg","jpeg","gif","png","bmp","image","webp"],uA={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255},_A=1,ie=2;class ye{constructor(r,g){this.instanceID=Pr(9999999),this.sizeType=r.type||0,this.type=0,this.size=r.size||0,this.width=r.width||0,this.height=r.height||0,this.imageUrl=Vt.addAuthToUrl(r.imageUrl||r.url||""),this.url=Vt.addAuthToUrl(r.url||g)}setSizeType(r){this.sizeType=r}setType(r){this.type=r}setImageUrl(r){r&&(this.imageUrl=Vt.addAuthToUrl(r))}getImageUrl(){return this.imageUrl}}function p(s){const{originUrl:r,originWidth:g,originHeight:u,min:E=198}=s,f=parseInt(g)||0,D=parseInt(u)||0,v={url:void 0,width:0,height:0};if((f<=D?f:D)<=E)v.url=r,v.width=f,v.height=D;else{D<=f?(v.width=Math.ceil(f*E/D),v.height=E):(v.width=E,v.height=Math.ceil(D*E/f));const N=r&&r.indexOf("?")>-1?`${r}&`:`${r}?`;v.url=E===198?`${N}imageView2/3/w/198/h/198`:`${N}imageView2/3/w/720/h/720`}if(r===void 0){const{url:N}=v;return vo(v,["url"])}return v}class B{constructor(r){this._imageMemoryURL="",this._percent=0,this.type=gc;const{uuid:g,file:u,imageFormat:E,imageInfoArray:f=[],isCustomUpload:D=!1}=r;this._imageMemoryURL=this.createImageDataAsURL(u),this.content={imageFormat:E,uuid:g,imageInfoArray:[]},this[jr]=D,this.initImageInfoArray(f),this.autoFixUrl()}static parseServerPushElement(r){const{MsgContent:g}=r,{ImageFormat:u,ImageInfoArray:E,UUID:f}=g,D=function(v){return v.map(N=>({size:N.Size,type:N.Type,width:N.Width,height:N.Height,url:N.URL}))}(E);return new B({imageFormat:u,imageInfoArray:D,uuid:f})}createImageDataAsURL(r){let g="";const{IN_MINI_APP:u,IN_RN_APP:E,IN_BROWSER:f}=Vt.getPlatformFlags();return r&&((u||E)&&(g=r.url),f&&(g=window.URL.createObjectURL(r))),g}initImageInfoArray(r=[]){const g={type:0,size:0,width:0,height:0,url:""};for(let u=0;u<3;u++){const E=r[u]||Object.assign({},g),f=new ye(E,this._imageMemoryURL);f.setSizeType(u+1),f.setType(u),this.addImageInfo(f)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const r=["http","https"];this.content.imageInfoArray.forEach(g=>{if(!g.url||g.imageUrl==="")return;const[u,...E]=g.imageUrl.split("://"),f=E.join("://");r.includes(u)||g.setImageUrl(`https://${f}`)})}updatePercent(r){this._percent=Math.min(r,1)}updateImageFormat(r){this.content.imageFormat=uA[r.toUpperCase()]||uA.UNKNOWN}addImageInfo(r){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(r)}updateImageInfoArray(r){const g=this.content.imageInfoArray.length;let u;for(let E=0;E({InstanceId:g.instanceID,Type:g.sizeType,MsgType:g.type,Size:g.size,Width:g.width,Height:g.height,URL:Vt.removeAuthToUrl(g.imageUrl)}))}}const M=new class{init(s){this.core=s}},G={[ru]:"i",[Cl]:"a",[Da]:"v",[VE]:"f"};let O=null,z=null;function X(s){var r;const{store:g,utils:{isNumber:u,safeStringify:E},ssoLog:f}=M.core;try{const D=((r=g.get("cloudConfig"))===null||r===void 0?void 0:r.upload_size_limit)||"";D!==z&&(z=D,O=JSON.parse(D)||{});const v=O?.[G[s]];if(u(v))return 1024*v*1024}catch(D){f.debug("getCloudControlUploadSizeLimit",E(D))}return null}var cA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var r;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:f}=s;u.registerApi({apiName:"createImageMessage",context:this}),u.registerExperimentalAPI("createImageMessage",this,"createCustomUploadImageMessage"),(r=f?.messageFactory)===null||r===void 0||r.registerElementClass(gc,B),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createImageMessage(s){var r,g,u;try{const E=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,f=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:E})),D=this._processImage(s);s.payload.file=D;const v={imageFormat:uA.UNKNOWN,uuid:Vt.generateUUID(D),file:D,imageInfoArray:[]},N=new B(v);return f.setElement(N),this._messageOptionsMap.set(f.clientSequence,s),f}catch(E){throw E}}createCustomUploadImageMessage(s){var r,g,u,E;const{store:f,utils:{isEmpty:D}}=this._core,v=(r=f.get("login"))===null||r===void 0?void 0:r.userId,N=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:v})),{largeImageUuid:P,largeFileSize:W,largeImageWidth:nA,largeImageHeight:EA,largeImageUrl:wA,originImageUuid:kA,originFileSize:VA,originImageWidth:LA,originImageHeight:SA,originImageUrl:PA,thumbImageUuid:zA,thumbFileSize:Ee,thumbImageWidth:Ie,thumbImageHeight:Li,thumbImageUrl:Ui}=((E=s?.payload)===null||E===void 0?void 0:E.file)||{};if(D(PA)||D(kA))throw new Error("createImageMessageExperimental originImageUrl or originImageUuid is empty");const Yt=new B({imageFormat:uA.UNKNOWN,uuid:kA,imageInfoArray:[{instanceID:kA,size:VA,width:LA,height:SA,imageUrl:PA,url:PA},{instanceID:P,size:W,width:nA,height:EA,imageUrl:wA,url:wA},{instanceID:zA,size:Ee,width:Ie,height:Li,imageUrl:Ui,url:Ui}],isCustomUpload:!0});return N.setElement(Yt),this._messageOptionsMap.set(N.clientSequence,s),N._skipUpload=!0,N}upload(s){return mA(this,void 0,void 0,function*(){const r=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadImage(g);const u=yield this._performImageUpload(r,s,g),E=this._generateImageInfo(u);return r.updateImageFormat(u?.fileType),r.updateImageInfoArray(E),this._updateImageType(r.content.imageInfoArray),s})}_performImageUpload(s,r,g){return mA(this,void 0,void 0,function*(){const{to:u}=r,E={uploadFileType:ru,file:g,to:u,message:r,onProgress:v=>{var N,P;s.updatePercent(v),(P=(N=this._messageOptionsMap.get(r.clientSequence))===null||N===void 0?void 0:N.onProgress)===null||P===void 0||P.call(N,v)}},{uploadOptions:f,response:D}=yield K.uploadToCOS(E);return this._parseResponse(f,D)})}_generateImageInfo(s){const{location:r,fileSize:g,width:u,height:E,smallImageUrl:f,smallImageWidth:D,smallImageHeight:v,largeImageUrl:N,largeImageWidth:P,largeImageHeight:W,imageInfoArray:nA}=s,EA=Vt.addAuthToUrl(r),wA={size:g,url:EA,width:u,height:E};return nA?.length>0?this._processImageInfoArray(nA,g):f&&N?[Object.assign({},wA),{largeImageUrl:N,largeImageWidth:P,largeImageHeight:W},{smallImageUrl:f,smallImageWidth:D,smallImageHeight:v}]:[Object.assign({},wA),this._generateThumbInfo(EA,u,E,720),this._generateThumbInfo(EA,u,E,198)]}_generateThumbInfo(s,r,g,u){return p({originUrl:s,originWidth:r,originHeight:g,min:u})}_processImageInfoArray(s,r){let g,u,E;for(const f of s)f.type===1?(u=f,u.size=r):f.type===2?(E=f,E.size=r):(g=f,g.size=r);return[Object.assign({},g),Object.assign({},E),Object.assign({},u)]}_parseResponse(s,r){return mA(this,void 0,void 0,function*(){try{const{thumbUrl:g,largeUrl:u,downloadUrl:E}=s;if(g&&u&&(yield this._getImageInfoByUrl(g,r,"thumb"),yield this._getImageInfoByUrl(u,r,"large")),Vt.isSimpleCos()&&!Vt.isPrivateNetWork()&&(yield this._getImageInfoArray(E,r),r?.uploadIP)){const f=this._extractDomainFromUrl(E);f&&(yield this._getDownloadIP(f,r))}return r}catch(g){throw g}})}_extractDomainFromUrl(s){var r;try{const g=s.match(/:\/\/([^\/]+)/);return g?g[1]:null}catch(g){return(r=this._core)===null||r===void 0||r.ssoLog.warn("_extractDomainFromUrl",`Failed to extract domain from URL:${g.message}`),null}}_getImageInfoByUrl(s,r,g){return mA(this,void 0,void 0,function*(){var u;try{const E=Vt.addAuthToUrl(s),{width:f=0,height:D=0}=yield Vt.probeImageWidthHeight(E);r.width=f,r.height=D,g==="thumb"?(r.smallImageUrl=s,r.smallImageWidth=f,r.smallImageHeight=D):(r.largeImageUrl=s,r.largeImageWidth=f,r.largeImageHeight=D)}catch(E){(u=this._core)===null||u===void 0||u.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${g} image info:${E.message}`)}})}_validateBeforeUploadImage(s){var r;const{ChatError:g}=(r=this._core)===null||r===void 0?void 0:r.helper;if(!s)throw new g({code:sA});this._checkImageType(s),this._checkImageSize(s)}_processImage(s){var r;try{const{IN_MINI_APP:g}=(r=this._core)===null||r===void 0?void 0:r.utils;let{file:u}=s.payload;return u=g?this._processMiniAppImageFile(u):this._processWebImageFile(u),u}catch(g){throw g}}_processMiniAppImageFile(s){dl(s)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const r=s.tempFiles[0].path||s.tempFiles[0].tempFilePath;return{url:r,name:r.slice(r.lastIndexOf("/")+1),size:s.tempFiles&&s.tempFiles[0].size||1,type:r.slice(r.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(s){var r;const{ChatError:g}=(r=this._core)===null||r===void 0?void 0:r.helper,u=Vt.extractFileFromInput(s);if(!u)throw new g({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return u}_getDownloadIP(s,r){return mA(this,void 0,void 0,function*(){const g=`${ya} getDownloadIP domainName: ${s}`;try{const u=yield function(f,D){return mA(this,void 0,void 0,function*(){try{const{helper:v,channel:N}=D,P="im_cos_msg.get_final_ip",W={str_domain:f},nA=v.generateProtocolData({servcmd:P,data:W}),EA=`${nA.head.seq}${P}`;return yield N.sendPacket(nA,{requestId:EA})}catch(v){throw console.warn("getFinalIP error:",v),v}})}(s,this._core);if(!u||!u.str_final_ip)return;console.log(`${g} ok. downloadIP:${u}`);const E=r.location.split("/");E[0]=u.str_final_ip,r.location=E.join("/")}catch(u){console.warn(u)}})}_getImageInfoArray(s,r){return mA(this,void 0,void 0,function*(){try{const g=yield function(u,E){return mA(this,void 0,void 0,function*(){try{const{helper:f,channel:D}=E,v="im_cos_msg.get_imageinfo",N={str_image_url:u},P=f.generateProtocolData({servcmd:v,data:N}),W=`${P.head.seq}${v}`;return yield D.sendPacket(P,{requestId:W})}catch(f){throw console.warn("getImageInfo error:",f),f}})}(s,this._core);return r.imageInfoArray=this._processImageInfoResponse(g),r}catch(g){throw r.imageInfoArray=void 0,g}})}_processImageInfoResponse(s){if(!s)return[];const{rpt_msg_image_info:r}=s;return r.map(g=>({type:g.uint32_image_type,url:g.str_url,width:g.uint32_width,height:g.uint32_height,imageFormat:g.str_image_format}))}_checkImageType(s){const{utils:r,helper:g}=this._core;let u="";if(r.IN_MINI_APP&&(u=s.url.slice(s.url.lastIndexOf(".")+1)),r.IN_BROWSER&&(u=s.name.slice(s.name.lastIndexOf(".")+1)),iA.indexOf(u.toLowerCase())<0)throw new g.ChatError({code:k})}_checkImageSize(s){const{utils:r,helper:g,store:u}=this._core;let E=0;if(E=(r.IN_MINI_APP,s.size),E===0)throw new g.ChatError({code:U});if(E>=(X(ru)||20971520))throw new g.ChatError({code:x})}_updateImageType(s){s[1].type=ie,s[2].type=_A}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const DA=2108,GA=2401,KA=2402,re="2.5.0",Qe="1.18.0";function At(s,r){const g=s.split("."),u=r.split("."),E=Math.max(g.length,u.length);for(;g.lengthv)return 1;if(D0;return{isValid:r,error:r?null:{message:"content can not be empty"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{uuid:E,downloadFlag:f,fileUrl:D,fileName:v,fileSize:N}=u;return{MsgType:this.type,MsgContent:{Download_Flag:f,Url:Vt.removeAuthToUrl(D),FileName:v,FileSize:N,UUID:E}}}_getFileInfo(r){const{utils:{IN_UNI_NATIVE_APP:g}}=M.core;if(r.fileName&&r.fileSize)return{size:r.fileSize,name:r.fileName};const{file:u}=r;return u?(g&&this._processNativeAppFile(u),{size:u.size,name:u.name}):{size:0,name:""}}_processNativeAppFile(r){if(r.path&&r.path.includes(".")){const g=r.path.slice(r.path.lastIndexOf(".")+1).toLowerCase();r.type=g,r.name||(r.name=`${Pr(999999)}.${g}`)}r.name||(r.type="",r.name=r.path.slice(r.path.lastIndexOf("/")+1).toLowerCase()),r.suffix&&(r.type=r.suffix),r.url||(r.url=r.path)}}lt=jr;var xt=new class{constructor(){this._messageOptionsMap=new Map}init(s){var r;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:f}=s;u.registerApi({apiName:"createFileMessage",context:this}),u.registerExperimentalAPI("createFileMessage",this,"createCustomUploadFileMessage"),(r=f?.messageFactory)===null||r===void 0||r.registerElementClass(Ka,dt),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createFileMessage(s){var r,g,u;try{this._checkVersion();const E=this._processFile(s.payload.file);s.payload.file=E;const f=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:f})),v={uuid:Vt.generateUUID(E),file:E},N=new dt(v);return D.setElement(N),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadFileMessage(s){var r,g,u;try{const{store:E,message:f,utils:{isEmpty:D}}=this._core,v=(r=E.get("login"))===null||r===void 0?void 0:r.userId,{url:N,uuid:P,fileSize:W,fileName:nA=""}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{};if(D(N))throw new Error("url is required");const EA=(u=f.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:v})),wA=new dt({url:N,uuid:P,file:{size:W,name:nA},isCustomUpload:!0});return EA.setElement(wA),EA}catch(E){throw E}}upload(s){return mA(this,void 0,void 0,function*(){const{file:r}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadFile(r);const g=s.getElements()[0],u=yield this._performFileUpload(g,s,r),E=Vt.addAuthToUrl(u?.location);return g.updateFileUrl(E),s})}_validateBeforeUploadFile(s){const{helper:{ChatError:r}}=this._core;if(!s)throw new r({code:GA});const g=X(VE)||104857600;if(s.size>g)throw new r({code:KA});if(s.size===0)throw new r({code:DA})}_performFileUpload(s,r,g){return mA(this,void 0,void 0,function*(){const{to:u}=r,E={uploadFileType:VE,file:g,to:u,message:r,onProgress:D=>{var v,N;s.updatePercent(D),(N=(v=this._messageOptionsMap.get(r.clientSequence))===null||v===void 0?void 0:v.onProgress)===null||N===void 0||N.call(v,D)}},{response:f}=yield K.uploadToCOS(E);return f})}_processFile(s){var r,g;const{IN_BROWSER:u,IN_RN_APP:E,IN_WX_MINI_APP:f,IN_QQ_MINI_APP:D,IN_UNI_NATIVE_APP:v}=(r=this._core)===null||r===void 0?void 0:r.utils,{ChatError:N}=(g=this._core)===null||g===void 0?void 0:g.helper;if(u||v){const P=Vt.extractFileFromInput(s);if(!P)throw new N({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return P}if(f||D){const{tempFiles:P}=s;return Object.assign(Object.assign({},P[0]),{url:P[0].path})}return E?Object.assign(Object.assign({},s),{url:s.uri}):s}_checkVersion(){var s,r;const{MINI_APP_NAMESPACE:g,IN_MINI_APP:u,IN_WX_MINI_APP:E,IN_QQ_MINI_APP:f,IN_UNI_NATIVE_APP:D}=(s=this._core)===null||s===void 0?void 0:s.utils,{ChatError:v}=(r=this._core)===null||r===void 0?void 0:r.helper;if(u){if(!(E||f||D))throw new v({message:"Unsupported mini app environment"});const N=g.getSystemInfoSync().SDKVersion;if(E&&At(N,re)<0)throw new v({message:`WXChooseMessageFile requires SDK version ${re} or higher`});if(f&&At(N,Qe)<0)throw new v({message:`QQChooseMessageFile requires SDK version ${Qe} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const Wt=2108,Ki=2351,Eo=2352,so=["mp4","quicktime","mov","video"];var hi;class qo{constructor(r){this.type=Hl,this.uploadProgress=0,this[hi]=!1;const g=typeof r?.videoSecond=="number"?r?.videoSecond:0;this[jr]=r.isCustomUpload||!1,this.content={remoteVideoUrl:Vt.addAuthToUrl(r.remoteVideoUrl||r.videoUrl||""),videoFormat:r.videoFormat,videoSecond:parseInt(g?.toString(),10),videoSize:r.videoSize,videoUrl:Vt.addAuthToUrl(r.videoUrl),videoDownloadFlag:2,videoUUID:r.videoUUID,thumbUUID:r.thumbUUID,thumbFormat:r.thumbFormat,thumbWidth:r.thumbWidth,snapshotWidth:r.thumbWidth,thumbHeight:r.thumbHeight,snapshotHeight:r.thumbHeight,thumbSize:r.thumbSize,snapshotSize:r.thumbSize,thumbDownloadFlag:2,thumbUrl:Vt.addAuthToUrl(r.thumbUrl),snapshotUrl:Vt.addAuthToUrl(r.thumbUrl)}}static parseServerPushElement(r){const{MsgContent:g}=r,{VideoUrl:u,VideoFormat:E,VideoSecond:f,VideoSize:D,VideoDownloadFlag:v,VideoUUID:N,ThumbUUID:P,ThumbFormat:W,ThumbWidth:nA,SnapshotWidth:EA,ThumbHeight:wA,SnapshotHeight:kA,ThumbSize:VA,SnapshotSize:LA,ThumbDownloadFlag:SA,ThumbUrl:PA,SnapshotUrl:zA}=g;return new qo({videoUrl:u,videoFormat:E,videoSecond:f,videoSize:D,videoDownloadFlag:v,videoUUID:N,thumbUUID:P,thumbFormat:W,thumbWidth:nA,snapshotWidth:EA,thumbHeight:wA,snapshotHeight:kA,thumbSize:VA,snapshotSize:LA,thumbDownloadFlag:SA,thumbUrl:PA,snapshotUrl:zA})}updatePercent(r){this.uploadProgress=Math.min(r,1)}updateVideoUrl(r){r&&(this.content.remoteVideoUrl=r)}updateSnapshotInfo(r){const{snapshotUrl:g,snapshotWidth:u,snapshotHeight:E}=r;Vt.isEmpty(g)||(this.content.thumbUrl=this.content.snapshotUrl=g),Vt.isEmpty(u)||(this.content.thumbWidth=this.content.snapshotWidth=Number(u)),Vt.isEmpty(E)||(this.content.thumbHeight=this.content.snapshotHeight=Number(E))}validateBeforeSend(){if(this[jr])return{isValid:!0};const r=this.content.remoteVideoUrl!=="";return{isValid:r,error:r?null:{message:"content can not be empty"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{remoteVideoUrl:E,videoFormat:f,videoSecond:D,videoSize:v,videoDownloadFlag:N,videoUUID:P,thumbUUID:W,thumbFormat:nA,thumbWidth:EA,snapshotWidth:wA,thumbHeight:kA,snapshotHeight:VA,thumbSize:LA,snapshotSize:SA,thumbDownloadFlag:PA,thumbUrl:zA,snapshotUrl:Ee}=u;return{MsgType:this.type,MsgContent:{VideoUrl:Vt.removeAuthToUrl(E),VideoFormat:f,VideoSecond:D,VideoSize:v,VideoDownloadFlag:N,VideoUUID:P,ThumbUUID:W,ThumbFormat:nA,ThumbWidth:EA,SnapshotWidth:wA,ThumbHeight:kA,SnapshotHeight:VA,ThumbSize:LA,SnapshotSize:SA,ThumbDownloadFlag:PA,ThumbUrl:Vt.removeAuthToUrl(zA),SnapshotUrl:Vt.removeAuthToUrl(Ee)}}}}hi=jr;var cn,yi=new class{constructor(){this._messageOptionsMap=new Map}init(s){var r;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:f}=s;u.registerApi({apiName:"createVideoMessage",context:this}),u.registerExperimentalAPI("createVideoMessage",this,"createCustomUploadVideoMessage"),(r=f?.messageFactory)===null||r===void 0||r.registerElementClass(Hl,qo),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createVideoMessage(s){var r,g,u;try{const E=this._processVideo(s);s.payload.file=E;const f=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:f})),v={videoFormat:E.videoFile.type,videoSecond:Br(E.videoFile.second,0),videoSize:E.videoFile.size,remoteVideoUrl:"",videoUrl:E.videoFile.url,videoUUID:Vt.generateUUID(E.videoFile),thumbUUID:Vt.generateUUID(E.videoFile,"jpg"),thumbWidth:E.width||200,thumbHeight:E.height||200,thumbUrl:E.thumbUrl,thumbSize:E.thumbSize,thumbFormat:"jpg"},N=new qo(v);return D.setElement(N),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadVideoMessage(s){var r,g,u;try{const{store:E,message:f}=this._core;this._validateCustomUploadVideoMessage(s);const D=(r=E.get("login"))===null||r===void 0?void 0:r.userId,{videoUrl:v,videoUuid:N,duration:P,snapshotUrl:W,snapshotUuid:nA,videoFileSize:EA,videoType:wA,snapshotWidth:kA,snapshotHeight:VA,snapshotFileSize:LA,snapshotType:SA="jpg"}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},PA=(u=f.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:D})),zA=new qo({videoFormat:wA,videoSecond:P||0,videoSize:EA,remoteVideoUrl:v,videoUrl:v,videoUUID:N,thumbUUID:nA,thumbWidth:kA||200,thumbHeight:VA||200,thumbUrl:W,thumbSize:LA,thumbFormat:SA,isCustomUpload:!0});return PA.setElement(zA),this._messageOptionsMap.set(PA.clientSequence,s),PA}catch(E){throw E}}upload(s){return mA(this,void 0,void 0,function*(){const r=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadVideo(g);const u=yield this._performVideoUpload(r,s,g),{location:E,snapshotInfo:f}=u,D=Vt.addAuthToUrl(E);return r.updateVideoUrl(D),Vt.isEmpty(f)||r.updateSnapshotInfo(f),s})}_validateBeforeUploadVideo(s){const{helper:{ChatError:r}}=this._core,g=X(Da)||104857600;if(s.videoFile.size>g)throw new r({code:Ki});if(s.videoFile.size===0)throw new r({code:Wt});if(so.indexOf(s.videoFile.type)===-1)throw new r({code:Eo})}_validateCustomUploadVideoMessage(s){var r;const{utils:{isEmpty:g,isNumber:u}}=this._core,{videoUrl:E,videoUuid:f,duration:D,snapshotUrl:v,snapshotUuid:N}=((r=s?.payload)===null||r===void 0?void 0:r.file)||{};if(g(E)||g(f)||!u(D)||g(v)||g(N))throw new Error("Invalid video message options: missing required fields (videoUrl, videoUuid, duration, snapshotUrl, snapshotUuid)")}_performVideoUpload(s,r,g){return mA(this,void 0,void 0,function*(){const{to:u}=r,E={uploadFileType:Da,file:g,to:u,message:r,onProgress:v=>{var N,P;s.updatePercent(v),(P=(N=this._messageOptionsMap.get(r.clientSequence))===null||N===void 0?void 0:N.onProgress)===null||P===void 0||P.call(N,v)}},{response:f,uploadOptions:D}=yield K.uploadToCOS(E);return{snapshotInfo:yield this._getSnapshotInfoByUrl(D.requestSnapshotUrl),location:f.location}})}_processVideo(s){var r,g;try{const{ChatError:u}=(r=this._core)===null||r===void 0?void 0:r.helper,{IN_MINI_APP:E,IN_BROWSER:f}=(g=this._core)===null||g===void 0?void 0:g.utils;let{file:D}=s.payload,v={};if(E&&(v=this._processMiniVideoFile(D),D.name=v.name,D.url=v.url,D.type=v.type),f){const N=Vt.extractFileFromInput(D);if(!N)throw new u({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});D=N,v=this._processWebVideoFile(D)}return D.videoFile=v,D.thumbUrl="",D.thumbSize=0,D}catch(u){throw console.warn(`${ya} _processFile error:`,u),u}}_processMiniVideoFile(s){const{utils:{IN_UNI_NATIVE_APP:r},helper:{ChatError:g}}=this._core;if(dl(s))throw new g({message:"FileUnsupportedInMiniApp"});Array.isArray(s.tempFiles)&&(s=s.tempFiles[0]);let u=s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase();return r&&(u=s.fileType||u),{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.size||1,second:s.duration||0,type:u}}_processWebVideoFile(s){const{name:r,size:g=1,duration:u=0,type:E}=s,f=E.split("/")[1];return{url:window.URL.createObjectURL(s),name:r,size:g,second:u,type:f}}_getSnapshotInfoByUrl(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r}=this._core;try{r.debug("_getSnapshotInfoByUrl",`${ya} _getSnapshotInfoByUrl url:${s}`);const g={version:1,platform:Vt.getPlatform(),cover_name:Cg(Pr(99999)),snapshot_url:s},u=yield function(N,P){return mA(this,void 0,void 0,function*(){try{const W="im_cos_msg.video_cover",{helper:nA,channel:EA}=P,wA=nA.generateCosSpecifiedData({servcmd:W,data:N}),kA=`${wA.head.seq}${W}`;return yield EA.sendPacket(wA,{requestId:kA})}catch(W){throw console.warn("getSnapshotInfo error:",W),W}})}(g,this._core),{download_url:E}=u||{};if(r.debug("_getSnapshotInfoByUrl",`${ya} _getSnapshotInfoByUrl OK snapshotUrl:${E}`),Vt.isEmpty(E))return{};const f=Vt.addAuthToUrl(E),{width:D=0,height:v=0}=yield Vt.probeImageWidthHeight(f);return{snapshotUrl:f,snapshotWidth:D,snapshotHeight:v}}catch(g){throw g}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};class to{constructor(r){this.uploadProgress=0,this.type=Yg,this[cn]=!1,this[jr]=r.isCustomUpload||!1,this.content={downloadFlag:2,second:r.second,size:r.size,url:Vt.generateURL(r.url,{needAddAuthToUrl:!this[jr]}),remoteAudioUrl:Vt.addAuthToUrl(r.url||""),uuid:r.uuid}}static parseServerPushElement(r){const{MsgContent:g}=r,{Url:u,Download_Flag:E,Second:f,Size:D,UUID:v}=g;return new to({url:u,downloadFlag:E,second:f,size:D,uuid:v})}updatePercent(r){this.uploadProgress=Math.min(r,1)}updateAudioUrl(r){this.content.remoteAudioUrl=r}validateBeforeSend(){if(this[jr])return{isValid:!0};const r=this.content.remoteAudioUrl!=="";return{isValid:r,error:r?null:{message:"content can not be empty"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{uuid:E,downloadFlag:f,remoteAudioUrl:D,size:v,second:N}=u;return{MsgType:this.type,MsgContent:{Url:Vt.removeAuthToUrl(D),Download_Flag:f,Second:N,Size:v,UUID:E}}}}cn=jr;const rs=2108,be=2300,bt=2301;var OA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var r;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:f}=s;u.registerApi({apiName:"createAudioMessage",context:this}),u.registerExperimentalAPI("createAudioMessage",this,"createCustomUploadAudioMessage"),(r=f?.messageFactory)===null||r===void 0||r.registerElementClass(Yg,to),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createAudioMessage(s){var r,g,u;try{let{file:E}=s.payload;E=this._processAudioFile(s.payload.file),s.payload.file=E;const f=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:f})),v={second:Math.max(1,Math.round((E.duration||E.second)/1e3)),size:E.fileSize||E.size||1,url:E.tempFilePath||E.uri||E.url,uuid:Vt.generateUUID(E)},N=new to(v);return D.setElement(N),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadAudioMessage(s){var r,g,u;try{this._validateCustomUploadOptions(s);const{store:E,message:f}=this._core,D=(r=E.get("login"))===null||r===void 0?void 0:r.userId,{url:v,uuid:N,duration:P,fileSize:W}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},nA=(u=f.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:D})),EA=new to({second:P,size:W||1,url:v,uuid:N,isCustomUpload:!0});return nA.setElement(EA),this._messageOptionsMap.set(nA.clientSequence,s),nA}catch(E){throw E}}upload(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;r.debug("upload",`${ya} uploadAudio message:${g(s)}`);const{file:u}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadAudio(u);const E=s.getElements()[0],f=yield this._performAudioUpload(E,s,u),D=Vt.addAuthToUrl(f?.location);return E.updateAudioUrl(D),s})}_validateBeforeUploadAudio(s){const{helper:{ChatError:r},store:g}=this._core;if(!s)throw new r({code:be});const u=X(Cl)||20971520;if(s.size>u)throw new r({code:bt});if(s.size===0)throw new r({code:rs})}_performAudioUpload(s,r,g){return mA(this,void 0,void 0,function*(){const{to:u}=r,E={uploadFileType:Cl,file:g,to:u,message:r,onProgress:D=>{var v,N;s.updatePercent(D),(N=(v=this._messageOptionsMap.get(r.clientSequence))===null||v===void 0?void 0:v.onProgress)===null||N===void 0||N.call(v,D)}},{response:f}=yield K.uploadToCOS(E);return f})}_processAudioFile(s){var r;const{IN_MINI_APP:g,IN_BROWSER:u}=(r=this._core)===null||r===void 0?void 0:r.utils;return g?this._processMiniFile(s):u?this._processWebFile(s):void 0}_processMiniFile(s){return{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.fileSize,second:s.duration,type:s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(s){if(s.tempFilePath||s.uri)return s;const r=URL.createObjectURL(s);return s.tempFilePath=r,s}_validateCustomUploadOptions(s){var r;const{utils:{isEmpty:g}}=this._core,{url:u,uuid:E,duration:f}=((r=s?.payload)===null||r===void 0?void 0:r.file)||{};if(g(u)||g(E)||g(f))throw new Error("Invalid audio message options")}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const oi={to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1},onProgress:{required:!1,rules:["function"],allowEmpty:!1}},ms={createImageMessage:oi,createAudioMessage:oi,createVideoMessage:oi,createFileMessage:oi},si={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},Dn={[gc]:cA,[Ka]:xt,[Hl]:yi,[Yg]:OA};var Ni=new class{constructor(){this.name="RichMediaMessage"}install(s){this._core=s;const{constants:{OuterConstant:{MSG_AUDIO:r,MSG_FILE:g,MSG_IMAGE:u,MSG_VIDEO:E}}}=s;M.init(s),cA.init(s),xt.init(s),yi.init(s),OA.init(s),K.init(s),Vt.init(s),s.helper.registerApi({apiName:"sendMessage",context:this,matcher:f=>[r,g,u,E].includes(f[0].type)}),s.helper.registerValidateConfig({auth:si,params:ms})}sendMessage(s,r){return mA(this,void 0,void 0,function*(){var g,u,E;try{return this._isCustomUpload(s)||(yield this._upload(s)),yield(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(s,r)}catch(f){throw f}})}_upload(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;if(r.debug("_upload",` uploadFile message:${g(s)}`),s._relayFlag!==!0)try{const u=Dn[s.type];u&&(yield u.upload(s),r.info("_upload",` type:${s.type}`))}catch(u){throw s.status=au.FAIL,u instanceof Error&&(u.data={message:s}),this._core.message.messageDataHandler.storeConversationMessage(s),u}})}_isCustomUpload(s){var r,g;return((g=(r=s._elements)===null||r===void 0?void 0:r[0])===null||g===void 0?void 0:g[jr])===!0}};const yo=new class{init(s){this.core=s}};class yt{constructor(r){this.conversationID=r.conversationID||"",this.unreadCount=r.unreadCount||0,this.type=r.type||"",this.lastMessage=yo.core.common.buildLastMessage(r.lastMessage),this.peerReadTime=r.peerReadTime||0,this.groupAtInfoList=[],this.remark=r.remark||"",this.isPinned=r.isPinned||!1,this.messageRemindType=r.messageRemindType,this.markList=r.markList||[],this.customData=r.customData||"",this.conversationGroupList=r.conversationGroupList||[],this.draftText=r.draftText||"",this.userProfile=r.userProfile,this.groupProfile=r.groupProfile,this.subType=r.subType||"",this._isInfoCompleted=!1,this._init()}_init(){var r;const{core:{OuterConstant:g,utils:{isUndefined:u}}}=yo;u(this.userProfile)&&this.type===g.CONV_C2C?this.userProfile={userID:this.conversationID.replace(g.CONV_C2C,"")}:this.type===g.CONV_GROUP&&(!this.subType&&(!((r=this.groupProfile)===null||r===void 0)&&r.type)&&(this.subType=this.groupProfile.type),u(this.groupProfile)&&(this.groupProfile={groupID:this.conversationID.replace(g.CONV_GROUP,""),selfInfo:{},lastMessage:{},type:this.subType}))}updateUnreadCount(r){var g;const{core:{OuterConstant:u,utils:{isUndefined:E},store:f}}=yo,{nextUnreadCount:D,isFromGetConversations:v,isUnreadC2CMessage:N}=r;if(E(D))return;if(this.subType===u.GRP_AVCHATROOM)return void(this.unreadCount=0);if(v&&this.type===u.CONV_GROUP)return void(this.unreadCount=D);if(N&&this.type===u.CONV_C2C)return void(this.unreadCount=D);const P=((g=f.get("cloudConfig"))===null||g===void 0?void 0:g.support_unread_count_for_meeting)==="1";this.subType!==u.GRP_MEETING||P?this.unreadCount+=D:this.unreadCount=0}updateLastMessage(r){this.lastMessage=yo.core.common.buildLastMessage(r)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(r){const{core:{OuterConstant:g}}=yo,{sequence:u,time:E}=r;return this.type===g.CONV_C2C&&u===this.lastMessage.lastSequence&&E===this.lastMessage.lastTime||this.type===g.CONV_GROUP&&u===this.lastMessage.lastSequence}setLastMessageRevoked(r){this.lastMessage.isRevoked=r}setLastMessageRevoker(r){this.lastMessage.revoker=r}setDraftText(r){this.draftText=r}updateGroupAtInfoList(r){const{core:{common:{updateGroupAtInfo:g}}}=yo;g(r,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}const St=s=>{const{core:{OuterConstant:r,utils:{isString:g}}}=yo;return g(s)&&s.slice(0,3)===r.CONV_C2C},hg=s=>{const{core:{OuterConstant:r,utils:{isString:g}}}=yo;return g(s)&&s.slice(0,5)===r.CONV_GROUP},qn=s=>{const{core:{OuterConstant:r,utils:{isString:g}}}=yo;return g(s)&&s===r.CONV_SYSTEM};function io(s){const{OuterConstant:r}=yo.core;let g="";return s===0?g=r.MSG_REMIND_ACPT_AND_NOTE:s===1?g=r.MSG_REMIND_DISCARD:s===2?g=r.MSG_REMIND_ACPT_NOT_NOTE:s===3&&(g=r.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}function Wr(s){const{OuterConstant:r}=yo.core;let g;return s.startsWith(r.CONV_C2C)&&(g=s.replace(r.CONV_C2C,"")),g==="@TLS#ERROR"||g==="@TLS#NOT_FOUND"}function cc(s,r){const{helper:g}=yo.core,u=new g.ChatError({functionName:s,code:r?.errorCode||r?.code,message:r?.errorInfo||r?.message});throw console.error(`${s} fail:`,u),u}var In,ua;(function(s){s[s.OFF=0]="OFF",s[s.ON=1]="ON"})(In||(In={})),function(s){s[s.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(ua||(ua={}));var Sa;(function(s){s[s.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",s[s.USER_OR_GRP_NOT_FOUND=2501]="USER_OR_GRP_NOT_FOUND",s[s.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE"})(Sa||(Sa={}));const oa=0,q=1;var QA=new class{constructor(){this._name="GetC2CMessageRemindType"}init(s){this._core=s}get(s){return mA(this,void 0,void 0,function*(){try{const{common:r}=this._core,g=yield function(E,f){return mA(this,void 0,void 0,function*(){const{toAccount:D,userIDList:v}=E,N={To_Account:D,Peer_Account:v};return f.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:N})})}({toAccount:r.getCurrentUserID(),userIDList:s},this._core),{MuteNotificationsList:u=[]}=g||{};u.forEach(E=>{const{Peer_Account:f,MuteNotifications:D}=E,v=`${this._core.OuterConstant.CONV_C2C}${f}`,N=io(D);NA.patchMessageRemindType([v],N)})}catch(r){console.error(`${this._name}.get fail:`,r)}})}},yA=new class{constructor(){this._name="GetGroupMessageRemindType"}init(s){this._core=s}get(s){return mA(this,void 0,void 0,function*(){if(s.length!==0)try{const r=yield function(u,E){return mA(this,void 0,void 0,function*(){const{groupIDList:f,responseFilter:D}=u,v={GroupIdList:f,ResponseFilter:D};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:v})})}({groupIDList:s,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:g=[]}=r||{};g.forEach(u=>{var E;const{GroupId:f,MemberList:D}=u,v=((E=D[0])===null||E===void 0?void 0:E.MsgFlag)||"",N=`${this._core.OuterConstant.CONV_GROUP}${f}`;NA.patchMessageRemindType([N],v)})}catch(r){console.error(`${this._name}.get fail:`,r)}})}},NA=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(s){this._core=s;const{helper:r,notificationCenter:g,appStore:{conversationStore:u},constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:f},InnerEvent:{SYNC_CONVERSATION_LIST:D,MESSAGE_PUSH:v,NEW_MESSAGE:N,MESSAGE_DELETED:P,MESSAGE_REVOKED:W,MESSAGE_MODIFIED:nA,CONVERSATION_UPDATED:EA,LOGOUT:wA,DESTROY:kA},InnerEventSubType:{C2C_MESSAGE_PEER_READ:VA}}=s;this._conversationStore=u,r.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,f.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),r.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,f.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),r.registerWorkflowStep(E.RECEIVE_C2C_NEW_MESSAGE,f.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),r.registerWorkflowStep(E.RECEIVE_C2C_NEW_MESSAGE,f.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),r.registerWorkflowStep(E.RECEIVE_GROUP_NEW_MESSAGE,f.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),r.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_RE_ONLINE,f.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),r.registerWorkflowStep(E.RECEIVE_GROUP_TIPS_NOTIFICATION,f.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this);const{InnerEventSubType:{GROUP_AT_TIPS:LA}}=g;g.subscribeInnerEvent(D,this._handleConversationSynced,this),g.subscribeInnerEvent(N,this._handleNewMessage,this),g.subscribeInnerEvent(v,LA,this._handleNewGroupAtTips,this),g.subscribeInnerEvent(P,this._handleMessageDeleted,this),g.subscribeInnerEvent(W,this._handleMessageRevoked,this),g.subscribeInnerEvent(nA,this._handleMessageModified,this),g.subscribeInnerEvent(EA,this._handleConversationUpdated,this),g.subscribeInnerEvent(v,VA,this._handleMessageRead,this),g.subscribeInnerEvent(wA,this._reset,this),g.subscribeInnerEvent(kA,this._dispose,this),s.ssoLog.debug(`${this._name}.init`)}_handleConversationSynced(s){this.updateLocalConversationList({conversationUpdateFieldList:s.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(s){const{constants:{WORKFLOW_STEP:r}}=this._core,{conversationUpdateFieldList:g=[],groupTipList:u=[],isUnreadC2CMessage:E}=s.result[r.UNREAD_MESSAGE_SYNC]||{};let f=!1;g.forEach(D=>{const{conversationID:v,unreadCount:N}=D,P=this.getLocalConversation(v);P&&P.unreadCount!==N&&(P.updateUnreadCount({nextUnreadCount:N,isUnreadC2CMessage:E}),f=!0)}),f&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(u)}_handleGroupAtTipsSynced(s){var r;for(let g=0;g0&&this._handleNewGroupAtTips({GroupTips:v._groupAtInfoList}),f=!0}f&&this.emitConversationListUpdate()}_handleNewMessage(s){const{conversationUpdateFieldList:r=[],isInstantMessage:g=!0,isUnreadC2CMessage:u=!1,updateUnreadCount:E=!0}=s.result||{};if(r.length===0)return;const{common:{isTopic:f}}=this._core;f(r[0].conversationID)||(this.updateLocalConversationList({conversationUpdateFieldList:r,isInstantMessage:g,isUnreadC2CMessage:u,isFromGetConversations:!1,updateUnreadCount:E}),r.filter(D=>this._isConversationNeedShow(D.conversationID)).length>0&&this.emitConversationListUpdate())}_handleNewGroupAtTips(s){const{GroupTips:r=[]}=s;r.forEach(g=>{const{GroupAtTips:u,MsgBody:E,MsgRandom:f,ClientSeq:D}=g;let v={};u?v=this._convertGroupAtTipsKey(u):E?v=Object.assign({},this._convertGroupAtTipsKey(E)):g.groupAtType&&(v=Object.assign({},g)),v.__random=f,v.__sequence=D,this._groupAtTipsList.push(v)}),console.log(`${this._name}._handleNewGroupAtTips groupAtTipsList: ${JSON.stringify(this._groupAtTipsList)}`),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(s){const{From_Account:r,GroupId:g,MsgSeq:u,GroupAtType:E}=s;return{from:r,groupID:g,sequence:u,groupAtType:E}}_updateGroupAtInfoList(){if(this._groupAtTipsList.length===0)return;const{common:s,OuterConstant:r}=this._core,g=s.getCurrentUserID();let u=!1;this._groupAtTipsList.forEach(E=>{const{groupID:f,from:D}=E;if(D!==g){const v=this.getLocalConversation(`${r.CONV_GROUP}${f}`);v&&(v.updateGroupAtInfoList(E),u=!0)}}),u&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(s){var r,g;console.log(`${this._name}._handleMessageDeleted, conversationID:`,s);const{message:{messageDataHandler:u},OuterConstant:E}=this._core,f=u?.getLocalMessageList(s)||[];let D={};for(let P=(f.length||0)-1;P>=0;P--)if(!f[P].isDeleted&&f[P]._isExcludedFromLastMessage!==!0){D=f[P];break}const v=this.getLocalConversation(s);if(!v)return;let N=!1;v.lastMessage.lastSequence===D.sequence&&v.lastMessage.lastTime===D.time||(!((g=(r=this._core)===null||r===void 0?void 0:r.helper)===null||g===void 0)&&g.isEmpty(D)&&(D=void 0),v.updateLastMessage(D),N=!0),s.startsWith(E.CONV_C2C)&&this.updateUnreadCount(s),N&&(this.emitConversationListUpdate(),console.log(`${this._name}._handleMessageDeleted. update conversationID:${s} with lastMessage:`,v.lastMessage))}_handleMessageRevoked(s){const{messageList:r=[],updateUnreadCount:g=!0}=s;if(console.log(`${this._name}._handleMessageRevoked messageList:${r.length}`),r.length===0)return;let u=null,E=!1;r.forEach(f=>{u=this.getLocalConversation(f.conversationID),u&&(g&&u.reduceUnreadCount()&&(E=!0),u.isLastMessageRevoked({sequence:f.sequence,time:f.time})&&(u.setLastMessageRevoked(!0),u.setLastMessageRevoker(f.revoker),E=!0))}),E&&this.emitConversationListUpdate()}_handleMessageModified(s){const{utils:{isEmpty:r},common:{getMessagePreviewText:g},ssoLog:u}=this._core;u.debug(`${this._name}._handleMessageModified`,JSON.stringify(s));const{conversationID:E,messageList:f}=s,D=this.getLocalConversation(E);if(r(D))return;const{lastMessage:v}=D;if(v){const N=f?.[0]||{};v.lastTime===N.time&&v.lastSequence===N.sequence&&v.version!==N.version&&(v.type=N.type,v.payload=N.payload,v.messageForShow=g(N.type,N.payload),v.cloudCustomData=N.cloudCustomData,v.version=N.version,this.emitConversationListUpdate(),console.log(`${this._name} conversationID:${E} lastMessage updated`))}}_handleConversationUpdated(s){this.emitConversationListUpdate(s?.needSort)}updateLocalConversationList(s){const{isFromGetConversations:r}=s,{newConversationList:g}=this._getTmpConversationListMapping(s);this._sortConversationList(),r||this._updateNewConversationProfile(g),this._core.ssoLog.debug("updateLocalConversationList",` newConversationList: ${g.length}`)}_getTmpConversationListMapping(s){const{OuterConstant:r}=this._core,{conversationUpdateFieldList:g,isFromGetConversations:u,isInstantMessage:E,isUnreadC2CMessage:f=!1,updateUnreadCount:D}=s,v=[],N=g?.length;for(let P=0;P{v[1].isPinned===!0?s(v[1].lastMessage.lastTime)?u.push(v):g.push(v):s(v[1].lastMessage.lastTime)?f.push(v):E.push(v)});const D=g.sort((v,N)=>N[1].lastMessage.lastTime-v[1].lastMessage.lastTime).concat(u).concat(E.sort((v,N)=>N[1].lastMessage.lastTime-v[1].lastMessage.lastTime)).concat(f);this._updateConversationMapFromList(D)}_updateNewConversationProfile(s){if(s.length===0)return;const r=[],g=[],{OuterConstant:{CONV_GROUP:u,CONV_C2C:E}}=this._core;s.forEach(f=>{const{conversationID:D,type:v}=f;if(v===E){const N=D.replace(E,"");r.push(N)}else if(v===u){const N=D.replace(u,"");g.push(N)}}),r.length>0&&this._updateC2CConversation(r),g.length>0&&this._updateGroupConversation(g)}_updateC2CConversation(s){var r;const{OuterConstant:{CONV_C2C:g},appStore:{userStore:u},user:E}=this._core;let f=!1;(r=E.userProfile)===null||r===void 0||r.getUserProfile({userIDList:s}).then(D=>{(D?.data||[]).forEach(v=>{var N;const{userID:P}=v,W=this.getLocalConversation(`${g}${P}`);if(W){const nA=((N=u.getFriend(P))===null||N===void 0?void 0:N.remark)||"";W.remark=nA,W.userProfile=v,f=!0}}),f&&this.emitConversationListUpdate()}).catch(D=>{}),QA.get(s)}_updateGroupConversation(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_GROUP:r},appStore:{groupStore:g},utils:{safeStringify:u},ssoLog:E,apiMap:{getGroupProfile:f}}=this._core;let D=!1;try{yield Promise.all(s.map(v=>mA(this,void 0,void 0,function*(){const N=g.getGroup(v),P=this.getLocalConversation(`${r}${v}`);N&&P&&(P.groupProfile=N,D=!0),P&&!P.getProfileCompleted()&&typeof f=="function"&&(yield f({groupID:v}))}))),yA.get(s),D&&this.emitConversationListUpdate()}catch(v){E.debug("_updateGroupConversation",u(v))}})}_handleMessageRead(s){const{OuterConstant:{CONV_C2C:r}}=this._core,{C2cNotifyMsgArray:g=[]}=s||{};g.forEach(u=>{const{To_Account:E,UinPairReadArray:f=[]}=u?.C2cReadedReceipt||{};f?.forEach(D=>{const{LastReadTime:v}=D,N=`${r}${E}`;this._updateConversationReadInfo({conversationID:N,peerReadTime:v}),this._updateMessageListPeerRead({conversationID:N,peerReadTime:v})})})}_updateConversationReadInfo(s){const{appStore:r,utils:{isEmpty:g},common:{getCurrentUserID:u}}=this._core,{conversationID:E,peerReadTime:f}=s,D=r.conversationStore.getConversationMap();if(D.has(E)){const v=D.get(E);v.peerReadTime=f;const N=v?.lastMessage;g(N)||N.fromAccount===u()&&N.lastTime<=f&&!N.isPeerRead&&(N.isPeerRead=!0,r.conversationStore.updateConversation(E,{lastMessage:N}))}}_updateMessageListPeerRead(s){const{notificationCenter:r,OuterEvent:g,message:u}=this._core,{conversationID:E,peerReadTime:f}=s,D=u.messageDataHandler.getLocalMessageList(E),v=u.messageDataHandler.getSparseMessageList(E),N=[];D.forEach(P=>{P.time<=f&&!P.isPeerRead&&P.flow==="out"&&(P.isPeerRead=!0,N.push(P))}),v.forEach(P=>{P.time<=f&&!P.isPeerRead&&P.flow==="out"&&(P.isPeerRead=!0,N.push(P))}),r.emitOuterEvent(g.MESSAGE_READ_BY_PEER,{name:g.MESSAGE_READ_BY_PEER,data:N})}_isConversationNeedShow(s){var r,g;const{OuterConstant:{CONV_GROUP:u,GRP_ROOM:E,GRP_LIVE:f},utils:{isUndefined:D}}=this._core,v=this.getLocalConversation(s);if(D(v))return!0;const N=v.type===u&&((r=v.groupProfile)===null||r===void 0?void 0:r.type)===E,P=v.type===u&&((g=v.groupProfile)===null||g===void 0?void 0:g.type)===f;return!(N||P)}updateUnreadCount(s,r=!0){var g,u;let E=!1;const f=this.getLocalConversation(s),D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageDataHandler)===null||u===void 0?void 0:u.getLocalMessageList(s);if(!f)return E;const v=f.unreadCount,N=D?.filter(P=>!P.isRead&&!P._onlineOnlyFlag&&!P.isDeleted).length;return console.log(`${this._name}._updateUnreadCount conversationID:${s} currentUnreadCount:${v} newUnreadCount:${N}`),v!==N&&(f.unreadCount=N,E=!0,r===!0&&this.emitConversationListUpdate()),E}emitConversationListUpdate(s=!1){var r,g;s&&this._sortConversationList();const{OuterEvent:{CONVERSATION_LIST_UPDATED:u},conversation:E}=this._core,f=this.getLocalConversationList();this._emitEvent({name:u,data:f,isSyncCompleted:(g=(r=E?.syncConversationHandler)===null||r===void 0?void 0:r.isSyncCompleted)===null||g===void 0?void 0:g.call(r)}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var s;const r=this.getTotalUnreadMessageCount();this._totalUnreadCount!==r&&(this._core.ssoLog.debug("_emitTotalUnreadCountUpdate",` from ${this._totalUnreadCount} to ${r}`),this._totalUnreadCount=r,this._emitEvent({name:(s=this._core)===null||s===void 0?void 0:s.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:r}))}_emitEvent(s){var r;(r=this._core)===null||r===void 0||r.notificationCenter.emitOuterEvent(s.name,s)}getTotalUnreadMessageCount(){const{OuterConstant:s,utils:{isEmpty:r}}=this._core,g=this.getLocalConversationList();let u=0;return g.forEach(E=>{E.type!==s.CONV_SYSTEM&&(r(E.messageRemindType)||E.messageRemindType===s.MSG_REMIND_ACPT_AND_NOTE)&&(u+=E.unreadCount)}),u}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter(s=>this._isConversationNeedShow(s.conversationID))}hasLocalConversation(s){return this._conversationStore.getConversationMap().has(s)}getLocalConversation(s){return this._conversationStore.getConversationMap().get(s)}setLocalConversation(s,r){return this._conversationStore.getConversationMap().set(s,r)}deleteLocalConversation(s){this._conversationStore.getConversationMap().delete(s)}_updateConversationMapFromList(s){this._clearConversationMap();for(const[r,g]of s)this.setLocalConversation(r,g)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(s,r){let g=!1;s.forEach(u=>{const E=this.getLocalConversation(u);E?.messageRemindType!==r&&(E.messageRemindType=r,g=!0)}),console.log(`${this._name}.patchMessageRemindType conversationIDList:${s} messageRemindType:${r} hasUpdated:${g}`),g&&this.emitConversationListUpdate()}markMessageAsRead(s){const{message:{messageDataHandler:r}}=this._core,{conversationID:g,lastReadTime:u=0,lastReadSequence:E=0}=s,f=r?.getLocalMessageList(g);if(f.length===0)return;const{length:D}=f;for(let v=D-1;v>=0;v--){const N=f[v],P=u&&N.time>u,W=E&&N.sequence>E;if(!P&&!W){if(N.flow==="in"&&N.isRead)break;N.setIsRead(!0)}}}appendToPinnedConversation(s){const r=[...this._conversationStore.getConversationMap().entries()],g=r.findIndex(u=>u[1].isPinned===!1);r.splice(g,0,[s.conversationID,s]),this._updateConversationMapFromList(r),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){const{notificationCenter:s,InnerEvent:{NEW_MESSAGE:r,MESSAGE_DELETED:g,MESSAGE_REVOKED:u,MESSAGE_MODIFIED:E,CONVERSATION_UPDATED:f,LOGOUT:D,DESTROY:v,SYNC_CONVERSATION_LIST:N}}=this._core,{InnerEventSubType:{GROUP_AT_TIPS:P}}=s;s.unSubscribeInnerEvent(r,this._handleNewMessage,this),s.unSubscribeInnerEvent(r,P,this._handleNewGroupAtTips,this),s.unSubscribeInnerEvent(g,this._handleMessageDeleted,this),s.unSubscribeInnerEvent(u,this._handleMessageRevoked,this),s.unSubscribeInnerEvent(E,this._handleMessageModified,this),s.unSubscribeInnerEvent(f,this._handleConversationUpdated,this),s.unSubscribeInnerEvent(N,this._handleConversationSynced,this),s.unSubscribeInnerEvent(D,this._reset,this),s.unSubscribeInnerEvent(v,this._dispose,this)}},ee=new class{constructor(){this._name="GetConversationList"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getConversationList",context:this})}getConversationList(s){return mA(this,void 0,void 0,function*(){return{code:0,data:{conversationList:this._getConversationList(s),isSyncCompleted:this._core.conversation.syncConversationHandler.isSyncCompleted()}}})}_getConversationList(s){const{utils:{isUndefined:r,isArray:g,isPlainObject:u}}=this._core;if(r(s))return NA.getLocalConversationList();if(g(s))return s.length===0?[]:NA.getLocalConversationList().filter(E=>s.includes(E.conversationID));if(u(s)){const{type:E,markType:f,groupName:D,hasUnreadCount:v,hasGroupAtInfo:N}=s;return NA.getLocalConversationList().filter(P=>this._filterType(P,E)&&this._filterMarkType(P,f)&&this._filterGroupName(P,D)&&this._filterUnreadCount(P,v)&&this._filterGroupAtInfo(P,N))}return[]}_filterType(s,r){const{OuterConstant:g}=this._core;return r!==g.CONV_C2C&&r!==g.CONV_GROUP||s.type===r}_filterGroupName(s,r){const{utils:{isString:g}}=this._core;return!g(r)||(r===""?s.conversationGroupList.length===0:s.conversationGroupList.includes(r))}_filterMarkType(s,r){const{utils:{isNumber:g}}=this._core;return!g(r)||(r===0?s.markList.length===0:s.markList.includes(r))}_filterUnreadCount(s,r){let g=!0;return r===!0?g=s.unreadCount>=1:r===!1&&(g=s.unreadCount===0),g}_filterGroupAtInfo(s,r){let g=!0;return r===!0?g=s.groupAtInfoList.length>=1:r===!1&&(g=s.groupAtInfoList.length===0),g}},Ne=new class{constructor(){this._name="GetConversationProfile"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_C2C:r,CONV_GROUP:g,GRP_AVCHATROOM:u},appStore:{groupStore:E},utils:{isEmpty:f}}=this._core,D={code:0,data:{}};let v=NA.getLocalConversation(s);if(qn(s))return D.data.conversation=v,D;let N=!1;const P=St(s)?r:g;if(f(v)&&(N=!0,v=new yt({conversationID:s,type:P})),console.log(`${this._name}.getConversationProfile conversationID:${s} isNewConversation:${N}`),D.data.conversation=v,v?.getProfileCompleted())return D;if(P===r){const W=s.replace(r,"");yield this._handleC2CConversation(v,W),N&&(yield QA.get([W]))}if(P===g){const W=s.replace(g,"");if(!E.getGroup(W))return D;yield this._handleGroupConversation(v,W),N&&v.groupProfile.type!==u&&(yield yA.get([W]))}return D})}_handleC2CConversation(s,r){return mA(this,void 0,void 0,function*(){var g,u;const{user:E,helper:f,utils:{isEmpty:D},appStore:{conversationStore:v,userStore:N}}=this._core,{conversationID:P}=s,W=yield(g=E.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:[r]});if(W?.data.length===0)throw new f.ChatError({code:Sa.USER_OR_GRP_NOT_FOUND});s.userProfile=W?.data[0];const nA=(u=N.getFriend(r))===null||u===void 0?void 0:u.remark;D(nA)||s.remark===nA||(s.remark=nA),s.setProfileCompleted();const EA=NA.hasLocalConversation(P);console.log(`${this._name}._handleC2CConversation conversationID:${P} hasLocalConversation: ${EA}`),EA?v.updateConversation(P,s):NA.appendToPinnedConversation(s)})}_handleGroupConversation(s,r){return mA(this,void 0,void 0,function*(){const{apiMap:{getGroupProfile:g},appStore:{conversationStore:u}}=this._core,{conversationID:E}=s,f=yield g({groupID:r});s.groupProfile=f?.data.group,s.setProfileCompleted();const D=NA.hasLocalConversation(E);console.log(`${this._name}._handleGroupConversation conversationID:${E} hasLocalConversation: ${D}`),D?u.updateConversation(E,s):NA.appendToPinnedConversation(s)})}},he=new class{init(s){const{helper:r}=s;r.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return NA.getTotalUnreadMessageCount()}},Ue=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(s){this._core=s;const{helper:r,common:{isTopic:g},notificationCenter:u,InnerEvent:{MESSAGE_PUSH:E},InnerEventSubType:{ALL_MESSAGE_READ:f}}=s;r.registerApi({apiName:"setMessageRead",context:this,matcher:D=>!g(D[0].conversationID)}),r.registerApi({apiName:"setAllMessageRead",context:this}),u.subscribeInnerEvent(E,f,this._handleAllMessageRead,this)}handleC2CMessageReadSync(s){const{helper:{isEmpty:r},OuterConstant:g}=this._core;s.forEach(u=>{const{ReadC2cMsgNotify:E}=u;if(!r(E)){const{UinPairReadArray:f=[]}=E;f.forEach(D=>{const{From_Account:v,LastReadTime:N}=D,P=`${g.CONV_C2C}${v}`;console.log(`${this._name}.handleC2CMessageReadSync conversationID:${P} lastReadTime:${N}`),NA.markMessageAsRead({conversationID:P,lastReadTime:N}),NA.updateUnreadCount(P)})}})}handleGroupMessageReadSync(s){const{OuterConstant:r,utils:{isUndefined:g}}=this._core;s.forEach(u=>{const{GroupReadInfoArray:E}=u.MsgBody;g(E)||E.forEach(f=>{const{GroupId:D,LastReadMsgSeq:v}=f,N=`${r.CONV_GROUP}${D}`;console.log(`${this._name}.handleGroupMessageReadSync conversationID:${N} lastReadSequence:${v}`),NA.markMessageAsRead({conversationID:N,lastReadSequence:v}),NA.updateUnreadCount(N),this._clearGroupAtInfoList(N)})})}setMessageRead(s){return mA(this,void 0,void 0,function*(){var r,g;const{OuterConstant:u}=this._core,{conversationID:E}=s,f={code:0,data:{}},D=NA.getLocalConversation(E);let v=`${this._name}.setMessageRead conversationID:${E} unreadCount:${D?.unreadCount||0}`;if(f.successLog={message:v},!D)return f;const N=!(!((g=(r=this._core)===null||r===void 0?void 0:r.helper)===null||g===void 0)&&g.isEmpty(D.groupAtInfoList));if(D.type===u.CONV_GROUP&&N&&this._deleteGroupAtTips(E),D.unreadCount===0)return f;const{helper:{ChatError:P}}=this._core;try{if(D.type===u.CONV_C2C){const W=this._getLocalMessageMaxTime(D);v+=`lastMessageTime:${W}`,yield this._setC2CMessageRead(E,W)}if(D.type===u.CONV_GROUP){const W=this._getLocalMessageMaxSequence(D);v+=`lastMessageSequence:${W}`,yield this._setGroupMessageRead(E,W)}}catch(W){const{errorCode:nA,errorInfo:EA}=W;throw new P({functionName:"setMessageRead",code:nA,message:EA,moreMessage:v})}return D.type===u.CONV_SYSTEM&&(D.unreadCount=0),NA.emitConversationListUpdate(),Object.assign(Object.assign({},f),{successLog:{message:v}})})}setAllMessageRead(){return mA(this,arguments,void 0,function*(s={}){const{OuterConstant:{READ_ALL_MSG:r},utils:{safeStringify:g}}=this._core;let u=`scope:${s.scope}`;s.scope||(s.scope=r);const{scope:E}=s,f=this._generateSetAllMessageReadRequestData(E);if(f.allC2CMessageReadStatus===oa&&f.groupMessageReadInfoList.length===0)return{code:0};try{const D=yield function(v){return mA(this,void 0,void 0,function*(){const{allC2CMessageReadStatus:N,groupMessageReadInfoList:P}=v,W={C2CReadAllMsg:N,GroupReadInfo:P};return yo.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:W})})}(f);if(D){const{GroupReadInfoArray:v,C2CReadAllMsg:N}=D,P=this._parseGroupReadInfo(v);this._updateAllConversationReadStatus({allC2CMessageReadStatus:N})>0&&NA.emitConversationListUpdate(),u+=`failureGroupInfoList:${g(P)}`}return{code:0,successLog:{message:u}}}catch(D){const{errorCode:v}=D;throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:v,moreMessage:u})}})}_handleAllMessageRead(s){const{GroupReadInfoArray:r,C2CReadAllMsg:g}=s;this._parseGroupReadInfo(r),this._updateAllConversationReadStatus({allC2CMessageReadStatus:g})>0&&NA.emitConversationListUpdate()}_updateAllConversationReadStatus(s){const{OuterConstant:{CONV_C2C:r,CONV_GROUP:g},appStore:u}=this._core,E=u.conversationStore.getConversationMap(),{allC2CMessageReadStatus:f}=s;let D=0;for(const[v,N]of E)if(N.unreadCount>=1){if(f===q&&N.type===r){const P=this._getLocalMessageMaxTime(N);NA.markMessageAsRead({conversationID:v,lastReadTime:P})}else if(N.type===g){const P=v.replace(g,"");if(this._serverGroupConversationLastReadSeqMap.has(P)){const W=this._serverGroupConversationLastReadSeqMap.get(P);NA.markMessageAsRead({conversationID:v,lastReadSequence:W})}}NA.updateUnreadCount(v,!1)&&(D+=1)}return D}_generateSetAllMessageReadRequestData(s){const{OuterConstant:{CONV_C2C:r,CONV_GROUP:g,READ_ALL_C2C_MSG:u},appStore:E}=this._core,f={allC2CMessageReadStatus:oa,groupMessageReadInfoList:[]},D=E.conversationStore.getConversationMap();for(const[,v]of D){const{type:N,unreadCount:P}=v;if(this._shouldSetAllMessageRead({scope:s,type:N,unreadCount:P})){if(N===r&&f.allC2CMessageReadStatus===oa){if(f.allC2CMessageReadStatus=q,s===u)break}else if(N===g){const W=this._getLocalMessageMaxSequence(v),{groupID:nA}=v.groupProfile;f.groupMessageReadInfoList.push({GroupId:nA,MsgSeq:W})}}}return f}_parseGroupReadInfo(s){const{utils:{isUndefined:r}}=this._core,g=[];return s?.forEach(u=>{const{GroupId:E,MsgSeq:f,RetCode:D,LastReadMsgSeq:v}=u;r(D)?this._serverGroupConversationLastReadSeqMap.set(E,v):(this._serverGroupConversationLastReadSeqMap.set(E,f),D!==0&&g.push(`${E}-${f}-${D}`))}),g}_deleteGroupAtTips(s){return mA(this,void 0,void 0,function*(){console.log(`${this._name}._deleteGroupAtTips conversationID:${s}`);const r=NA.getLocalConversation(s);if(!r)return;const g=r?.groupAtInfoList||[];if(g.length!==0)try{const{common:{getCurrentUserID:u,isCommunity:E},OuterConstant:{CONV_GROUP:f,CONV_AT_ALL:D}}=this._core;let v=[...g];if(E({groupID:s.replace(f,"")})&&(v=g.filter(P=>!P.atTypeArray.includes(D)),v.length===0))return void this._clearGroupAtInfoList(s,!1);const N=v.map(P=>({From_Account:P.from,To_Account:u(),MsgSeq:P.__sequence,MsgRandom:P.__random,GroupId:P.groupID}));yield function(P,W){return mA(this,void 0,void 0,function*(){const{messageListToDelete:nA}=P,EA={DelMsgList:nA};return W.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:EA})})}({messageListToDelete:N},this._core),console.log(`${this._name}._deleteGroupAtTips ok. count:${g.length}`),this._clearGroupAtInfoList(s)}catch(u){console.error(`${this._name}._deleteGroupAtTips fail:`,u)}})}_clearGroupAtInfoList(s,r=!0){const g=NA.getLocalConversation(s);g&&(g.groupAtInfoList.length>0&&(g.clearGroupAtInfoList(),console.log(`${this._name}._clearGroupAtInfoList conversationID:${s} needEmitConversationUpdate:${r}`)),r&&NA.emitConversationListUpdate())}_getLocalMessageMaxTime(s){var r;const{conversationID:g}=s,u=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...u.map(D=>D.time));let f=((r=s?.lastMessage)===null||r===void 0?void 0:r.lastTime)||0;return E>f&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${f} to ${E}`),f=E),f}_getLocalMessageMaxSequence(s){var r;const{conversationID:g}=s,u=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...u.map(D=>D.sequence));let f=((r=s?.lastMessage)===null||r===void 0?void 0:r.lastSequence)||0;return E>f&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${f} to ${E}`),f=E),f}_setC2CMessageRead(s,r){return mA(this,void 0,void 0,function*(){try{yield function(g,u){return mA(this,void 0,void 0,function*(){return u.common.buildAndSendPacket({servcmd:"openim.msgreaded",data:g})})}({C2CMsgReaded:{Cookie:"",C2CMsgReadedItem:[{To_Account:s.replace("C2C",""),LastedMsgTime:r,Receipt:1}]}},this._core),console.log(`${this._name}._setC2CMessageRead ok, lastReadTime:${r}`),NA.markMessageAsRead({conversationID:s,lastReadTime:r}),NA.updateUnreadCount(s)}catch(g){throw console.warn(`${this._name}._setC2CMessageRead fail:`,g),g}})}_setGroupMessageRead(s,r){return mA(this,void 0,void 0,function*(){try{yield function(g,u){return mA(this,void 0,void 0,function*(){const{groupID:E,lastMessageSequence:f}=g,D={GroupId:E,MsgReadedSeq:f};return u.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:D})})}({groupID:s.replace("GROUP",""),lastMessageSequence:r},this._core),console.log(`${this._name}._setGroupMessageRead ok, lastReadSequence:${r}`),NA.markMessageAsRead({conversationID:s,lastReadSequence:r}),NA.updateUnreadCount(s)}catch(g){throw console.warn(`${this._name}._setGroupMessageRead fail:`,g),g}})}_shouldSetAllMessageRead(s){const{OuterConstant:{CONV_C2C:r,CONV_GROUP:g,READ_ALL_MSG:u,READ_ALL_C2C_MSG:E,READ_ALL_GROUP_MSG:f}}=this._core,{type:D,scope:v,unreadCount:N}=s;return!(N<=0)&&(!(D!==r||![u,E].includes(v))||!(D!==g||![u,f].includes(v)))}},de=new class{constructor(){this._name="PinConversation"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(s,r){const{utils:{isArray:g}}=this._core;if(!g(s))return;const{OuterConstant:u}=this._core;let E=!1;s.forEach(f=>{const{Type:D,Peer_Account:v,GroupId:N}=f;let P;D===1?P=NA.getLocalConversation(`${u.CONV_C2C}${v}`):D===2&&(P=NA.getLocalConversation(`${u.CONV_GROUP}${N}`)),P&&(console.log(`${this._name}.handleConversationPinned conversationID:${P.conversationID} localPinned:${P.isPinned} remotePinned:${r}`),r&&!P.isPinned&&(P.isPinned=!0,E=!0),!r&&P.isPinned&&(P.isPinned=!1,E=!0))}),E&&NA.emitConversationListUpdate(!0)}pinConversation(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r,common:g,helper:{ChatError:u}}=this._core,{conversationID:E,isPinned:f}=s,D={code:0,data:{conversationID:E}},v=NA.getLocalConversation(E);if(v&&v.isPinned===f)return D;if(qn(E))return v&&(v.isPinned=f),NA.emitConversationListUpdate(!0),D;const N=`conversationID:${E} isPinned:${f}`;try{let P=null;if(St(E)?P={Type:1,To_Account:E.replace(r.CONV_C2C,"")}:hg(E)&&(P={Type:2,GroupId:E.replace(r.CONV_GROUP,"")}),yield function(nA,EA){return mA(this,void 0,void 0,function*(){const{fromAccount:wA,operationType:kA,itemList:VA}=nA,LA={From_Account:wA,OperationType:kA,RecentContactItem:VA};return EA.common.buildAndSendPacket({servcmd:"recentcontact.top",data:LA})})}({fromAccount:g.getCurrentUserID(),operationType:f===!0?1:2,itemList:[P]},this._core)){if(v)v.isPinned!==f&&(v.isPinned=f);else{const nA=new yt({conversationID:E,type:St(E)?r.CONV_C2C:r.CONV_GROUP,isPinned:f});NA.setLocalConversation(E,nA)}NA.emitConversationListUpdate(!0)}return Object.assign(Object.assign({},D),{successLog:{message:N}})}catch(P){const{errorCode:W,errorInfo:nA}=P;throw new u({functionName:"pinConversation",code:W,message:nA,moreMessage:N})}})}},Ve=new class{constructor(){this._name="DeleteConversation"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(s){const{utils:{isArray:r}}=this._core;if(!r(s))return;const{OuterConstant:g}=this._core,u=[];s.forEach(E=>{const{Type:f,Peer_Account:D,GroupId:v}=E;f===1&&u.push(`${g.CONV_C2C}${D}`),f===2&&u.push(`${g.CONV_GROUP}${v}`)}),console.log(`${this._name}.handleConversationDeleted conversationIDList:${u}`),this._deleteLocalConversationList(u)}deleteConversation(s){return mA(this,void 0,void 0,function*(){const{utils:{isString:r}}=this._core;if(r(s))return this._deleteConversation({conversationIDList:[s],flag:ua.ONLY_CONVERSATIONID});const g=Object.assign({},s);return g.conversationIDList.length>100&&(g.conversationIDList=g.conversationIDList.slice(0,100)),this._deleteConversation(g)})}_deleteConversation(s){return mA(this,void 0,void 0,function*(){const{conversationIDList:r,clearHistoryMessage:g=!0,flag:u=0}=s,{helper:{ChatError:E}}=this._core,f=`conversationIDList:${r} clearHistoryMessage:${g}`;try{const D=yield Promise.all([this._deleteConversationFromLocal(r),this._deleteConversationFromServer(r,g)]),v=[...D[0],...D[1]];if(v.length===0)throw new this._core.helper.ChatError({code:Sa.CONV_NOT_FOUND});return{code:0,data:u===ua.ONLY_CONVERSATIONID?{conversationID:v[0]}:{conversationIDList:v},successLog:{message:f}}}catch(D){const{errorCode:v,errorInfo:N}=D;throw new E({code:v,message:N,moreMessage:f})}})}_deleteConversationFromLocal(s){const{OuterConstant:r}=this._core;return s.filter(g=>{var u;if(!NA.hasLocalConversation(g))return!1;const E=(u=NA.getLocalConversation(g))===null||u===void 0?void 0:u.type;return E!==r.CONV_GROUP||this._hasLocalGroup(g)?E===r.CONV_SYSTEM&&(this._deleteLocalConversation(g),!0):(this._deleteLocalConversation(g),!0)})}_deleteConversationFromServer(s,r){return mA(this,void 0,void 0,function*(){const{OuterConstant:g,common:u}=this._core,E={fromAccount:u.getCurrentUserID(),conversationList:[],clearHistoryMessage:r?1:0};if(s.forEach(D=>{var v;if(NA.hasLocalConversation(D)){const N=((v=NA.getLocalConversation(D))===null||v===void 0?void 0:v.type)||"",P=D.replace(N,"");N===g.CONV_C2C?E.conversationList.push({To_Account:P,Type:1}):N===g.CONV_GROUP&&this._hasLocalGroup(D)&&E.conversationList.push({ToGroupid:P,Type:2})}}),E.conversationList.length===0)return[];const f=yield function(D,v){return mA(this,void 0,void 0,function*(){const{fromAccount:N,conversationList:P,clearHistoryMessage:W}=D,nA={From_Account:N,ContactItem:P,ClearRamble:W};return v.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:nA})})}(E,this._core);if(f){const{ResultItem:D=[]}=f,v=[];return D.length>0&&D.forEach(N=>{if(N.ResultCode===0){const P=N.Type===1?`${g.CONV_C2C}${N.To_Account}`:`${g.CONV_GROUP}${N.ToGroupid}`;v.push(P)}}),this._deleteLocalConversationList(v),v}return[]})}_deleteLocalConversationList(s){let r=!1;s.forEach(g=>{NA.hasLocalConversation(g)&&(this._deleteLocalConversation(g,!1),r=!0)}),console.log(`${this._name}._deleteLocalConversationList isUpdate:${r}`),r&&NA.emitConversationListUpdate()}_deleteLocalConversation(s,r=!0){const g=NA.hasLocalConversation(s);console.log(`${this._name}._deleteLocalConversation conversationID:${s} has:${g}`),g&&(NA.deleteLocalConversation(s),this._deleteConversationLocalMessage(s),r&&NA.emitConversationListUpdate())}_hasLocalGroup(s){const{OuterConstant:{CONV_GROUP:r},appStore:{groupStore:g}}=this._core,u=s.replace(r,"");return!!g.getGroup(u)}_deleteConversationLocalMessage(s){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${s}`),this._core.message.messageDataHandler.deleteConversationMessageList(s),this._core.message.messageHistory.completedHistoryConversations.delete(s)}},_t=new class{constructor(){this._name="SetConversationDraft"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return mA(this,void 0,void 0,function*(){const{conversationID:r,draftText:g}=s;if(console.log(`${this._name} conversationID:${r} draftText:${g}`),!NA.hasLocalConversation(r))throw new this._core.helper.ChatError({code:Sa.CONV_NOT_FOUND});const u=NA.getLocalConversation(r);return u?.setDraftText(g),NA.emitConversationListUpdate(),{code:0,data:{conversation:u}}})}},ti=new class{constructor(){this._name="SetC2CMessageRemindType"}init(s){this._core=s}set(s,r){return mA(this,void 0,void 0,function*(){s.length>30&&(console.warn(`${this._name}.set userIDList length:${s.length} exceeds limit 30`),s.splice(30));const g=function(){const{MSG_REMIND_ACPT_AND_NOTE:P,MSG_REMIND_DISCARD:W,MSG_REMIND_ACPT_NOT_NOTE:nA}=yo.core.OuterConstant;return{[P]:0,[W]:1,[nA]:2}}()[r],u=yield function(P,W){return mA(this,void 0,void 0,function*(){const{userIDList:nA,receiveMessageOption:EA}=P,wA={Peer_Account:nA,Mute_Notifications:EA};return W.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:wA})})}({userIDList:s,receiveMessageOption:g},this._core),{ErrorList:E=[]}=u||{},f=[];E.forEach(P=>{const{Peer_Account:W,ErrorCode:nA}=P;f.push({userID:W,code:nA});const EA=s.indexOf(W);EA>-1&&s.splice(EA,1)});const D=[],v=[],{OuterConstant:N}=this._core;return s.forEach(P=>{v.push(`${N.CONV_C2C}${P}`),D.push({userID:P})}),NA.patchMessageRemindType(v,r),{code:0,data:{successUserIDList:D,failureUserIDList:f}}})}},ui=new class{constructor(){this._name="SetGroupMessageRemindType"}init(s){this._core=s}set(s,r){return mA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:g,isTopic:u},OuterConstant:E}=this._core;if(yield function(f,D){return mA(this,void 0,void 0,function*(){const{groupID:v,userID:N,receiveMessageOption:P}=f,W={GroupId:v,Member_Account:N,MsgFlag:P};return D.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:W})})}({groupID:s,userID:g(),receiveMessageOption:r},this._core),!u(s)){const f=`${E.CONV_GROUP}${s}`;NA.patchMessageRemindType([f],r)}return{code:0,data:{groupID:s,messageRemindType:r}}})}},Rt=new class{constructor(){this._name="SetMessageRemindType"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(s){const{helper:{isEmpty:r},OuterConstant:g,ssoLog:u}=this._core;s.forEach(E=>{const{MuteNotificationsSync:f}=E;if(!r(f)){const{To_Account:D,MuteNotifications:v}=f,N=D.map(W=>`${g.CONV_C2C}${W}`),P=io(v);u.debug(`${this._name}.handleC2CMessageRemindTypeSync conversationIDList:${N} messageRemindType:${P}`),NA.patchMessageRemindType(N,P)}})}setMessageRemindType(s){return mA(this,void 0,void 0,function*(){const r="setMessageRemindType",{groupID:g,userIDList:u,messageRemindType:E}=s,{helper:f,utils:{isUndefined:D},ssoLog:v}=this._core;try{if(!D(g))return v.debug(`${this._name}.${r} groupID:${g} messageRemindType:${E}`),yield ui.set(g,E);if(!D(u))return v.debug(`${this._name}.${r} userIDList:${u} messageRemindType:${E}`),yield ti.set(u,E);throw new f.ChatError({functionName:r,message:"userIDList or groupID is required"})}catch(N){throw new f.ChatError({functionName:r,code:N?.errorCode,message:N?.errorInfo,moreMessage:`groupID:${g} userIDList:${u} messageRemindType:${E}`})}})}},fi=new class{init(s){s.ssoLog.debug("ConversationAction.init"),this._core=s,ee.init(s),Ne.init(s),he.init(s),Ue.init(s),de.init(s),Ve.init(s),_t.init(s),Rt.init(s);const{notificationCenter:r,InnerEvent:{MESSAGE_PUSH:g,DESTROY:u}}=this._core,{InnerEventSubType:{CONV_MODIFIED:E,C2C_MESSAGE_READ_SYNC:f,GROUP_MESSAGE_READ_SYNC:D,C2C_REMIND_TYPE_SYNC:v}}=r;r.subscribeInnerEvent(g,E,this._onConversationModified,this),r.subscribeInnerEvent(g,f,this._onC2CMessageReadSync,this),r.subscribeInnerEvent(g,v,this._onC2CMessageRemindTypeSync,this),r.subscribeInnerEvent(g,D,this._onGroupMessageReadSync,this),r.subscribeInnerEvent(u,this._dispose,this)}_onConversationModified(s){const{constants:{ConvModifyPushType:r}}=this._core,{RecentContactMod:g=[]}=s;g.forEach(u=>{const{PushType:E}=u;if(E===r.CONV_DELETED){const{RecentContactList:f}=u.RecentContactDeleteItem;Ve.handleConversationDeleted(f)}if(E===r.CONV_PINED){const{RecentContactList:f}=u.RecentContactTopItem;de.handleConversationPinned(f,!0)}if(E===r.CONV_UNPINED){const{RecentContactList:f}=u.RecentContactTopItem;de.handleConversationPinned(f,!1)}})}_onC2CMessageReadSync(s){const{C2cNotifyMsgArray:r=[]}=s;Ue.handleC2CMessageReadSync(r)}_onC2CMessageRemindTypeSync(s){const{C2cNotifyMsgArray:r=[]}=s;Rt.handleC2CMessageRemindTypeSync(r)}_onGroupMessageReadSync(s){const{GroupTips:r=[]}=s;Ue.handleGroupMessageReadSync(r)}_dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:r,DESTROY:g}}=this._core,{InnerEventSubType:{CONV_MODIFIED:u,C2C_MESSAGE_READ_SYNC:E,GROUP_MESSAGE_READ_SYNC:f,C2C_REMIND_TYPE_SYNC:D}}=s;s.unSubscribeInnerEvent(r,u,this._onConversationModified,this),s.unSubscribeInnerEvent(r,E,this._onC2CMessageReadSync,this),s.unSubscribeInnerEvent(r,D,this._onC2CMessageRemindTypeSync,this),s.unSubscribeInnerEvent(r,f,this._onGroupMessageReadSync,this),s.unSubscribeInnerEvent(g,this._dispose,this)}},go=new class{init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(s){return mA(this,void 0,void 0,function*(){try{const{OuterConstant:{MSG_REMIND_ACPT_NOT_NOTE:r}}=this._core,{messageRemindType:g=r,isRepeated:u=!0}=s,{startTime:E=0,endTime:f=0}=this._calcStartAndEndTime(s),D=yield function(v){return mA(this,void 0,void 0,function*(){const{common:N}=yo.core,{startTime:P,endTime:W,isRepeated:nA,messageRemindType:EA}=v,wA={StartTime:P,EndTime:W,IsRepeated:nA,Level:EA};return N.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:wA})})}({messageRemindType:this._getType(g),startTime:E,endTime:f,isRepeated:u?In.ON:In.OFF});return{code:0,data:{errorCode:D.ErrorCode,errorInfo:D.ErrorInfo}}}catch(r){cc("setAllReceiveMessageOpt",r)}})}_calcStartAndEndTime(s){const{startHour:r=0,startMinute:g=0,startSecond:u=0,duration:E=0,isRepeated:f=!0}=s,D=new Date,v=new Date(D.getFullYear(),D.getMonth(),D.getDate(),r,g,u),N=Math.round(v.getTime()/1e3);let P=N+E;return f&&E>=86400&&(P=N+86400),{startTime:N,endTime:P}}_getType(s){const{OuterConstant:r}=this._core;return{[r.MSG_REMIND_ACPT_AND_NOTE]:0,[r.MSG_REMIND_DISCARD]:1,[r.MSG_REMIND_ACPT_NOT_NOTE]:2}[s]}},fn=new class{init(s){this._core=s;const{helper:r,notificationCenter:g,InnerEvent:u}=s;r.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),g.subscribeInnerEvent(u.MESSAGE_PUSH,g.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(s){const r=this._handleResult(s),{notificationCenter:g,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:u}}=this._core;g.emitOuterEvent(u,{name:u,data:r})}getAllReceiveMessageOpt(){return mA(this,void 0,void 0,function*(){try{const s=yield function(){return mA(this,void 0,void 0,function*(){const{common:r}=yo.core,g={To_Account:r.getCurrentUserID()};return r.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_get_do_not_disturb",data:g})})}();return{code:0,data:this._handleResult(s)}}catch(s){cc("getAllReceiveMessageOpt",s)}})}_handleResult(s){const{OuterConstant:r}=this._core,{MSG_REMIND_ACPT_AND_NOTE:g,MSG_REMIND_DISCARD:u,MSG_REMIND_ACPT_NOT_NOTE:E}=r,f={0:g,1:u,2:E},{Level:D,StartTime:v,EndTime:N,IsRepeated:P}=s;return{messageRemindType:f[D]||g,startTime:v,endTime:N,isRepeated:P===In.ON}}},xo=new class{init(s){s.ssoLog.debug("ReceiveMessageOptions.init"),this._core=s,ti.init(s),ui.init(s),QA.init(s),yA.init(s),go.init(s),fn.init(s)}};const ai=s=>!St(s)&&!hg(s)&&!qn(s),Yr={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ai(s)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ai(s)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ai(s)||"conversationID is invalid."},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},deleteConversation:[{key:"options",required:!0,rules:["string","object"],allowEmpty:!1,customValidator:s=>{const{core:{utils:{isArray:r,isObject:g,isString:u}}}=yo;if(!u(s)&&!g(s))return"options is String or Object.";if(u(s)&&ai(s))return"conversationID is invalid.";if(g(s)){if(!r(s.conversationIDList))return"conversationIDList is not Array.";if(s.conversationIDList.length===0)return"conversationIDList is empty.";if(s.conversationIDList.some(E=>{if(ai(E))return!0}))return"conversationIDList includes invalid conversationID.";if(s.clearHistoryMessage&&typeof s.clearHistoryMessage!="boolean")return"clearHistoryMessage is not Boolean."}return!0}}],setConversationDraft:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!St(s)&&!hg(s))||"conversationID is invalid."},draftText:{required:!0,rules:["string"],allowEmpty:!0}},setAllReceiveMessageOpt:{messageRemindType:{required:!1,rules:["string"],allowEmpty:!0},startHour:{required:!1,rules:["number"],allowEmpty:!0},startMinute:{required:!1,rules:["number"],allowEmpty:!0},startSecond:{required:!1,rules:["number"],allowEmpty:!0},duration:{required:!1,rules:["number"],allowEmpty:!0},isRepeated:{required:!1,rules:["boolean"],allowEmpty:!0}}},nn={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0};var er=new class{constructor(){this.name="Conversation"}install(s){yo.init(s),fi.init(s),xo.init(s),NA.init(s),s.helper.registerValidateConfig({auth:nn,params:Yr})}};const tr=new class{init(s){this.core=s}},na="AVChatRoom",zr="AV_HISTORY_MSG",lc="GRP_COUNTER",Wu="Set",Rm="Increase",Gi="Decrease",gi=0,_o=1,Es=2,un=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],Bg=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Jl=["Role","JoinTime","MsgFlag","MsgSeq"],Dd=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Vc=0,_r=1,_I="notStart",cu="resolved",Vg="rejected",lu=10018,TI=11e3,Hc=2,zu=["Owner","Admin","Member"],wm=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],_m=0,Tm=1,Nm=2,QD=4,pD=1,KM=2,mD=3,fD=4,jM=5,_T=1,Sd=0,TT=4,yD=6,NT=400,DD=300,GT={from:!0,groupID:!0,groupName:!0,to:!0},WM={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},bT=2,zM=4,kT=5,LT=7,SD=8,vD=15,UQ=20,Gm=21,bm=2600,vd=2602,UT=2603,FT=2620,km=2621,MD=2623,Ch=2660,OT=2661,PT=2681,Lm=2683,ZM=2684,RD=2685,Um=2687,XM=3122,xT=10018,YT={0:"DisableInvite",1:"NeedPermission",2:"FreeAccess"},$M=s=>s===tr.core.OuterConstant.GRP_PUBLIC,Md=s=>s===tr.core.OuterConstant.GRP_AVCHATROOM,Fm=(s,r)=>{const{isArray:g}=tr.core.utils;if(!g(s)||!g(r))return!1;let u=!1;return r.forEach(({key:E,value:f})=>{const D=s.find(v=>v.key===E);D?D.value!==f&&(D.value=f,u=!0):(s.push({key:E,value:f}),u=!0)}),u},Rd=s=>{const r=[];if(!s)return r;for(let g=0,u=s.length;g{const r=[];for(let g=0,u=s.length;g0&&v.members.forEach(N=>{N.userID===this.selfInfo.userID&&D(this.selfInfo,N,["sequence"])})}updateSelfInfo(r){const{nameCard:g,joinTime:u,role:E,messageRemindType:f,readedSequence:D,excludedUnreadSequenceList:v}=r,{common:{deepMerge:N}}=tr.core;N(this.selfInfo,{nameCard:g,joinTime:u,role:E,messageRemindType:f,readedSequence:D,excludedUnreadSequenceList:v},[],["",null,void 0,0,NaN])}setSelfNameCard(r){this.selfInfo.nameCard=r}}var Wi=new class{constructor(){this._name="GroupDataHandler"}init(s){this._core=s;const{appStore:{groupStore:r}}=s;this._groupMap=r.getGroupMap()}hasLocalGroup(s){return this._groupMap.has(s)}getLocalGroup(s){return this._groupMap.get(s)}updateLocalGroup(s){const{common:{getCurrentUserID:r}}=this._core;let g;s.forEach(E=>{var f;g=E.groupID,this.hasLocalGroup(g)?(f=this.getLocalGroup(g))===null||f===void 0||f.updateGroup(E):(this._groupMap.set(g,new Zu(E)),this._clearGroupLocalMessage(g))});const u=r();for(const[,E]of this._groupMap)E.selfInfo.userID=u,E.selfInfo.role==="Owner"&&(E.ownerID=u)}deleteLocalGroup(s){this._groupMap.delete(s)}getLocalGroupList(){const{OuterConstant:{GRP_ROOM:s,GRP_LIVE:r}}=this._core;return[...this._groupMap.values()].filter(g=>{const{type:u}=g;return u!==s&&u!==r})}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){const s=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:r},notificationCenter:g}=this._core;g.emitOuterEvent(r,{name:r,data:s})}updateConversationGroupProfile(s){const{appStore:{conversationStore:r},OuterConstant:{CONV_GROUP:g}}=this._core,u=`${g}${s}`,E=r.getConversation(u);if(E){const f=this.getLocalGroup(s);E.setProfileCompleted(),r.updateConversation(u,{groupProfile:f})}}reset(){this.clearLocalGroup()}_clearGroupLocalMessage(s){const{message:{messageHistory:r,messageDataHandler:g},OuterConstant:{CONV_GROUP:u},ssoLog:E}=this._core;E.debug("_clearGroupLocalMessage",`groupID:${s}`);const f=`${u}${s}`;r.completedHistoryConversations.delete(f),g.deleteConversationMessageList(f)}};function Pm(s,r){return mA(this,void 0,void 0,function*(){const{type:g,limit:u,offset:E,supportTopic:f=0,memberAccount:D,responseFilter:v}=s,N={Type:g,Limit:u,Offset:E,Member_Account:D,ResponseFilter:v,SupportTopic:f,NeedAppDefineData:1};return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:N})})}const fs=function(s,r){return{code:0,data:s||{},successLog:r}};var AR=new class{constructor(){this._name="GetGroupList",this._pagingStatus=_I,this.PAGING_GRP_COUNT_LIMIT=200}init(s){this._core=s;const{helper:r,constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:u}}=s;r.registerApi({apiName:"getGroupList",context:this}),r.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_LOGIN,u.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return mA(this,arguments,void 0,function*(s=!1){if(s){const g=[];return yield this._pagingGetJoinedCommunityList({limit:this.PAGING_GRP_COUNT_LIMIT,offset:0,groupList:g}),Wi.updateLocalGroup(g),Wi.getLocalGroupList()}if(this._core.ssoLog.debug("getGroupList",`${this._name}.getGroupList pagingStatus:${this._pagingStatus}`),this._pagingStatus===Vg||this._pagingStatus===_I)return this._syncGroupList().then(()=>{const g=Wi.getLocalGroupList();return fs({groupList:g,isSyncCompleted:this._isSyncCompleted()})}).catch(g=>{throw g});const r=Wi.getLocalGroupList();return fs({groupList:r,isSyncCompleted:this._isSyncCompleted()},{message:`return group count:${r.length}`})})}_syncGroupList(){return mA(this,void 0,void 0,function*(){this._pagingStatus===_I&&Wi.clearLocalGroup();const s=this.PAGING_GRP_COUNT_LIMIT,r=[];try{yield this._pagingGetGroupList({limit:s,offset:0,groupList:r}),this._pagingStatus=cu,this._groupListTreeShaking(r),Wi.updateLocalGroup(r);const g=Wi.getLocalGroupList();return this._core.ssoLog.debug("_syncGroupList",`${this._name}._syncGroupList ok, count:${g.length}`),Wi.emitGroupListUpdate(),g}catch(g){throw this._pagingStatus=Vg,g}})}_pagingGetGroupList(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r}=this._core,{isCommunityRelay:g=!1,groupList:u}=s;let E,{limit:f,offset:D}=s;const v=[...un];g&&(E=this._core.OuterConstant.GRP_COMMUNITY,v.push("AtInfoList"));try{const N=yield Pm({type:E,limit:f,offset:D,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:v,SelfInfoFilter:[...Jl]}},this._core),{GroupIdList:P=[],TotalCount:W=0}=N||{},nA=this._convertGroupKey(P);u.push(...nA);const EA=D+f,wA=!(W>EA),kA=`offset:${D} limit:${f} total:${W} isCompleted:${wA} current:${u.length} isCommunityRelay:${g}`;return r.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. ${kA}`),g?wA?u:(D=EA,this._pagingGetGroupList({isCommunityRelay:!0,limit:f,offset:D,groupList:u})):wA?(r.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList start to get community list`),D=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:f,offset:D,groupList:u})):(D=EA,this._pagingGetGroupList({limit:f,offset:D,groupList:u}))}catch(N){if(N.ErrorCode===lu)return r.warn("_pagingGetGroupList",`${this._name}._pagingGetGroupList response size exceeds the limit, request count:${f}`),f=50,this._pagingGetGroupList({isCommunityRelay:g,limit:f,offset:D,groupList:u});if(g)return N.code===TI&&r.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. community unavailable`),u;throw N}})}_pagingGetJoinedCommunityList(s){return mA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:r},OuterConstant:g,ssoLog:u}=this._core,{groupList:E}=s;let{limit:f,offset:D}=s;try{const v=yield Pm({limit:f,offset:D,type:g.GRP_COMMUNITY,memberAccount:r(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...un],SelfInfoFilter:[...Jl]}},this._core),{GroupIdList:N=[],TotalCount:P=0}=v||{},W=this._convertGroupKey(N);E.push(...W);const nA=D+f,EA=!(P>nA),wA=`offset:${D} limit:${f} total:${P} isCompleted:${EA} current:${E.length}`;return u.debug("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList ok. ${wA}`),EA?E:(D=nA,this._pagingGetJoinedCommunityList({limit:f,offset:D,groupList:E}))}catch(v){if(v.code===xT)return u.warn("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList response size exceeds the limit, request count:${f}`),f=50,this._pagingGetJoinedCommunityList({limit:f,offset:D,groupList:E});throw v}})}_groupListTreeShaking(s){const r=new Map([...Wi.getLocalGroupList()]);for(let u=0,E=s.length;u{const{AtFlagList:E,AtMsgSeq:f,From_Account:D}=u;g.push({groupID:s,groupAtType:E,sequence:f,from:D})}),g}},Xu=new class{constructor(){this._name="CreateGroup"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"createGroup",context:this})}createGroup(s){return mA(this,void 0,void 0,function*(){var r;this._preCheckParams(s);const{helper:{ChatError:g}}=this._core;try{const{utils:{isEmpty:u},common:{getCurrentUserID:E},OuterConstant:{GRP_AVCHATROOM:f}}=this._core,D=yield function(nA,EA){return mA(this,void 0,void 0,function*(){const{name:wA,type:kA,groupID:VA,introduction:LA,notification:SA,avatar:PA,maxMemberNum:zA,joinOption:Ee,inviteOption:Ie,memberList:Li,groupCustomField:Ui,isSupportTopic:Yt}=nA;let Oi,Bn;Li&&(Oi=Li.map(Mt=>{const{userID:FA,memberCustomField:ci}=Mt;return{Member_Account:FA,AppMemberDefinedData:ci?JE(ci):void 0}})),Ui&&(Bn=JE(Ui));const Re={Name:wA,Type:kA,GroupId:VA,Introduction:LA,Notification:SA,FaceUrl:PA,MaxMemberCount:zA,ApplyJoinOption:Ee,InviteJoinOption:Ie,MemberList:Oi,AppDefinedData:Bn,SupportTopic:Yt,webPushFlag:1};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:Re})})}(Object.assign(Object.assign({},s),{ownerID:E()}),this._core),{GroupId:v,OverJoinedGroupLimit_Account:N=[]}=D||{},P=`${this._name}.createGroup ok, type:${s.type} groupID:${v} overLimitUserIDList:${N}`;if(u(s.memberList)||u(N)||(s.memberList=(r=s.memberList)===null||r===void 0?void 0:r.filter(nA=>N.includes(nA.userID))),s.type===f)return fs({group:new Zu(Object.assign(Object.assign({},s),{groupID:v}))},{message:P});Wi.updateLocalGroup([Object.assign(Object.assign({},s),{groupID:v})]);const W=Wi.getLocalGroup(v);return this._notNeedSendCustomMessage(s)||(this._sendCustomMessage(v,s.type),Wi.emitGroupListUpdate()),fs({group:W},{message:P})}catch(u){const{errorCode:E,errorInfo:f}=u;throw new g({functionName:"createGroup",code:E,message:f,moreMessage:` groupID:${s.groupID}`})}})}_preCheckParams(s){const{type:r,groupID:g}=s,{utils:{isEmpty:u,isUndefined:E},common:{isCommunity:f}}=this._core,D=!u(g);if(!(()=>{const{GRP_PUBLIC:v,GRP_WORK:N,GRP_MEETING:P,GRP_AVCHATROOM:W,GRP_COMMUNITY:nA}=tr.core.OuterConstant;return[v,N,P,W,nA]})().includes(r))throw new this._core.helper.ChatError({code:bm});if(!f({type:r})){if(D&&f({groupID:g}))throw new this._core.helper.ChatError({code:vd});E(s.isSupportTopic)||(s.isSupportTopic=void 0)}if(this._canIUseMemberList(r)||E(s.memberList)||(s.memberList=void 0),this._canIUseJoinOption(r)||E(s.joinOption)||(s.joinOption=void 0),f({type:r})){if(D&&!f({groupID:g}))throw new this._core.helper.ChatError({code:vd});s.isSupportTopic=this._canIUseTopic(s)?1:0}}_canIUseMemberList(s){return!Md(s)}_canIUseJoinOption(s){return $M(s)||this._core.common.isCommunity({type:s})}_canIUseTopic(s){const{isSupportTopic:r}=s;return r===!0}_notNeedSendCustomMessage(s){const{type:r,isSupportTopic:g}=s,{OuterConstant:{GRP_AVCHATROOM:u,GRP_COMMUNITY:E}}=this._core;return r===u||r===E&&g===1}_sendCustomMessage(s,r){var g,u,E,f,D,v;const{OuterConstant:N,common:{t:P}}=this._core;let W=P("CREATE_GROUP"),nA=Vc;r===N.GRP_COMMUNITY&&(W=P("CREATE_COMMUNITY"),nA=_r);const EA={to:s,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:W,cmd:nA,opUser:this._core.store.get("login").userId,version:4})}},wA=(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(EA);(v=(D=(f=this._core)===null||f===void 0?void 0:f.message)===null||D===void 0?void 0:D.messageSender)===null||v===void 0||v.sendMessage(wA,{})}},as=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(s){this._core=s;const{helper:r,constants:g}=s;r.registerWorkflowStep(g.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,g.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach(s=>{s.localMainSequence=0})}isGroupAttributesUpdated(s){const{elements:{newGroupProfile:r}}=s,{utils:{isEmpty:g,isUndefined:u}}=this._core;return!u(r)&&!g(r.groupAttributeOption)}handleGroupAttributesUpdated(s){const{groupID:r,groupAttributeOption:g}=s,{serverMainSequence:u,groupAttributeList:E=[],operation:f}=g;this._core.ssoLog.debug("handleGroupAttributesUpdated",`${this._name}.handleGroupAttributesUpdated groupID:${r} operation:${f}`);const{utils:{isUndefined:D}}=this._core;D(f)||(this.refreshGroupAttributesCache({groupID:r,serverMainSequence:u,groupAttributeList:E,operation:f}),this.emitGroupAttributesUpdated(r))}initGroupAttributesCache(s){const{groupID:r,avChatRoomKey:g}=s;this._groupAttributesCache.set(r,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:g,values:new Map}),this._core.ssoLog.debug("initGroupAttributesCache",`${this._name}.initGroupAttributesCache. groupID:${r} avChatRoomKey:${g}`)}hasGroupAttributesCache(s){return this._groupAttributesCache.has(s)}getGroupAttributesCache(s){return this.hasGroupAttributesCache(s)||this.initGroupAttributesCache({groupID:s}),this._groupAttributesCache.get(s)}deleteGroupAttributesCache(s){this.hasGroupAttributesCache(s)&&this._groupAttributesCache.delete(s)}refreshGroupAttributesCache(s){const{groupID:r,serverMainSequence:g,groupAttributeList:u,operation:E}=s;if(this.hasGroupAttributesCache(r)){const f=this.getGroupAttributesCache(r),{localMainSequence:D}=f;E!==jM&&g-D!==1||(f.serverMainSequence=g,f.localMainSequence=g,f.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:f,groupAttributeList:u,operation:E})),g-D>1&&(f.serverMainSequence=g),this._groupAttributesCache.set(r,f),this._core.ssoLog.debug("refreshGroupAttributesCache",`${this._name}.refreshGroupAttributesCache. operation:${E} localMainSequence:${D} serverMainSequence:${g}`)}}_updateGroupAttributesCacheValues(s){const{groupAttributes:r,groupAttributeList:g=[],operation:u}=s;u!==mD?u!==fD?(u===pD&&r.values.clear(),g.forEach(E=>{const{key:f,value:D,sequence:v}=E;r.values.set(f,{value:D,sequence:v})})):g.forEach(E=>{r.values.delete(E.key)}):r.values.clear()}getGroupAttributesCacheValues(s){var r;const{groupID:g,keyList:u=[]}=s,E={};if(this.hasGroupAttributesCache(g)){const{values:f}=this.getGroupAttributesCache(g);if(u.length===0){for(const D of f.keys())E[D]=((r=f.get(D))===null||r===void 0?void 0:r.value)||"";return E}return u.forEach(D=>{var v;f.has(D)&&(E[D]=((v=f.get(D))===null||v===void 0?void 0:v.value)||"")}),E}return E}saveGroupAttributesCacheValuesCopy(s){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:s})}emitGroupAttributesUpdated(s){var r,g;const{OuterConstant:{GRP_ROOM:u,GRP_LIVE:E}}=this._core,f=this.getGroupAttributesCacheValues({groupID:s}),D=this._core.appStore.groupStore.getGroup(s),{updatedKeyList:v,deletedKeyList:N}=this._computeValuesChangedData(f);v.length===0&&N.length===0||([u,E].includes(D.type)?(this._core.ssoLog.debug("RICH_STATUS_CHANGED",`${this._name}.emitRichStatusChanged update count:${v.length}, delete count:${N.length}`),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.OuterEvent.RICH_STATUS_CHANGED,data:{groupID:s,richStatus:f,updatedKeyList:v,deletedKeyList:N}})):(this._core.ssoLog.debug("emitGroupAttributesUpdated",`${this._name}.emitGroupAttributesUpdated update count:${v.length}, delete count:${N.length}`),this._emitEvent({name:(g=this._core)===null||g===void 0?void 0:g.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:s,groupAttributes:f,updatedKeyList:v,deletedKeyList:N}})))}_computeValuesChangedData(s){const{utils:{isUndefined:r}}=this._core,g=[],u=[];return Object.keys(s).forEach(E=>{s[E]!==this._groupAttributesCacheValuesCopy[E]&&g.push(E)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(E=>{r(s[E])&&u.push(E)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:g,deletedKeyList:u}}_emitEvent(s){var r;(r=this._core)===null||r===void 0||r.notificationCenter.emitOuterEvent(s.name,s)}convertKeyValueMapToList(s){const r=[];return Object.keys(s).forEach(g=>{r.push({key:g,value:s[g]})}),r}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}},Bh=new class{constructor(){this._name="DismissGroup"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(na)})}dismissGroup(s){return mA(this,void 0,void 0,function*(){const{helper:{ChatError:r}}=this._core;try{yield function(u,E){return mA(this,void 0,void 0,function*(){const f={GroupId:u};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:f})})}(s,this._core);const{type:g}=Wi.getLocalGroup(s);return Wi.deleteLocalGroup(s),Wi.emitGroupListUpdate(),as.deleteGroupAttributesCache(s),fs({groupID:s,type:g},{message:s})}catch(g){const{errorCode:u,errorInfo:E}=g;throw new r({functionName:"dismissGroup",code:u,message:E})}})}},ql=new class{constructor(){this._name="GetGroupProfile"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(s){return mA(this,void 0,void 0,function*(){const{groupID:r,groupCustomFieldFilter:g}=s,u={groupIDList:[r],responseFilter:{GroupBaseInfoFilter:[...un],AppDefinedDataFilter_Group:g,MemberInfoFilter:[...Dd]}},{helper:{ChatError:E}}=this._core;try{const f=yield this.getGroupProfileAdvance(u),{successGroupList:D,failureGroupList:v}=f;if(v.length>0)throw v[0];let N;return!Wi.hasLocalGroup(r)&&Md(D[0].type)?N=new Zu(D[0]):(Wi.updateLocalGroup(D),N=Wi.getLocalGroup(r)),N.isSupportTopic||Wi.updateConversationGroupProfile(r),fs({group:N},{message:`groupID:${r}`})}catch(f){const{code:D,message:v}=f;throw new E({functionName:"getGroupProfile",code:D,message:v})}})}getGroupProfileAdvance(s){return mA(this,void 0,void 0,function*(){const{groupIDList:r}=s,{common:{isCommunity:g}}=this._core,u=r.filter(N=>!g({groupID:N})),E=r.filter(N=>g({groupID:N}));u.length>50&&(u.length=50),E.length>50&&(E.length=50);const f=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:u})),this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:E,isCommunityProfile:!0}))]),D=[],v=[];return f.forEach(N=>{D.push(...N.successGroupList),v.push(...N.failureGroupList)}),{successGroupList:D,failureGroupList:v}})}_getGroupProfileAdvance(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{isUndefined:g}}=this._core,{isCommunityProfile:u=!1}=s,E=vo(s,["isCommunityProfile"]);if(E.groupIDList.length===0)return{successGroupList:[],failureGroupList:[]};try{const f=yield function(W,nA){return mA(this,void 0,void 0,function*(){const{groupIDList:EA,responseFilter:wA}=W,kA={GroupIdList:EA,ResponseFilter:wA};return nA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:kA})})}(E,this._core),{GroupInfo:D=[]}=f||{},v=this._convertGroupProfileKey(D),N=v.filter(W=>g(W.errorCode)||W.errorCode===0),P=v.filter(W=>W.errorCode&&W.errorCode!==0).map(W=>({code:W.errorCode,message:W.errorInfo,data:{groupID:W.groupID}}));return r.debug("_getGroupProfileAdvance",`${this._name}._getGroupProfileAdvance ok, groupID:${E.groupIDList.join(",")}`),{successGroupList:N,failureGroupList:P}}catch(f){if(u)return{successGroupList:[],failureGroupList:[]};throw f}})}_convertGroupProfileKey(s){const r=[];for(let g=0,u=s.length;g0&&u{const{Key:N,Value:P=0}=v;E.set(N,P)}),this._groupCountersMap.set(r,{lastUpdateTime:Date.now(),groupCounterSeq:u,counters:E,avChatRoomKey:f})}}initGroupCountersCache(s){const{groupID:r,avChatRoomKey:g}=s;this._groupCountersMap.set(r,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:g})}getLocalCounters(s,r){const g={};if(!this._hasLocalGroupCounters(s))return g;const{counters:u}=this.getLocalGroupCounters(s);if(r.length>0)r.forEach(E=>{u.has(E)&&(g[E]=u.get(E))});else for(const E of u.keys())g[E]=u.get(E);return g}deleteLocalGroupCounters(s){const{groupID:r,counterList:g=[],groupCounterSeq:u}=s;if(this._hasLocalGroupCounters(r)){const{counters:E,avChatRoomKey:f}=this.getLocalGroupCounters(r);g.forEach(D=>{E.delete(D.key)}),this._groupCountersMap.set(r,{lastUpdateTime:Date.now(),groupCounterSeq:u,counters:E,avChatRoomKey:f})}}setGroupCounters(s,r){if(!this._hasLocalGroupCounters(s))return;const g=this.getLocalGroupCounters(s),{counters:u}=g;let E=!1;Object.entries(r).forEach(([f,D])=>{u.has(f)&&u.get(f)!==D&&(u.set(f,D),E=!0)}),E&&this._groupCountersMap.set(s,Object.assign(Object.assign({},g),{lastUpdateTime:Date.now(),counters:u}))}_hasLocalGroupCounters(s){return this._groupCountersMap.has(s)}reset(){this._groupCountersMap.clear()}},qE=new class{constructor(){this._name="JoinGroup"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"joinGroup",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(na)})}joinGroup(s){return mA(this,void 0,void 0,function*(){const{groupID:r}=s,{helper:{ChatError:g},OuterConstant:u,ssoLog:E}=this._core;try{if(Wi.hasLocalGroup(r))try{return yield ql.getGroupProfile({groupID:r}),fs({status:u.JOIN_STATUS_ALREADY_IN_GROUP,group:Wi.getLocalGroup(r)},{message:`groupID:${r} joinedStatus:${u.JOIN_STATUS_ALREADY_IN_GROUP}`})}catch{return E.warn("joinGroup",`${this._name}.joinGroup ${r} was unjoined, start to join!`),Wi.deleteLocalGroup(r),yield this._applyJoinGroup(s)}return yield this._applyJoinGroup(s)}catch(f){const{errorCode:D,errorInfo:v}=f;throw new g({functionName:"joinGroup",code:D,message:v,moreMessage:`groupID:${r}`})}})}_applyJoinGroup(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r,helper:g,ssoLog:u}=this._core,{groupID:E}=s,f=Object.assign({},s),D=g.checkBusinessCapabilityBits(zr);D&&(f.historyMessageFlag=1);const v=yield function(SA,PA){return mA(this,void 0,void 0,function*(){const{groupID:zA,applyMessage:Ee,historyMessageFlag:Ie}=SA,Li={GroupId:zA,ApplyMsg:Ee,HugeGroupHistoryMsgFlag:Ie};return PA.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:Li})})}(f,this._core),{Type:N,JoinedStatus:P,LongPollingKey:W,StartSeq:nA,HugeGroupFlag:EA,AVChatRoomKey:wA,RspMsgList:kA=[]}=v||{},VA=`groupID:${E} joinedStatus:${P} longPollingKey:${W} startSeq:${nA} avChatRoomFlag:${EA} canGetAVChatRoomHistoryMsg:${D}, historyMessageCount:${kA.length}`;u.debug("_applyJoinGroup",`${this._name}._applyJoinGroup ok, ${VA}`);let LA=new Zu({groupID:E,type:N});if(P===r.JOIN_STATUS_WAIT_APPROVAL)return fs({status:r.JOIN_STATUS_WAIT_APPROVAL,group:LA});if(P===r.JOIN_STATUS_SUCCESS){try{LA=(yield ql.getGroupProfile({groupID:E})).data.group}catch(SA){u.warn("_applyJoinGroup",`${this._name}._applyJoinGroup getGroupProfile failed, groupID: ${E}, errorCode:${SA?.code}`)}return this._handleJoinResult({group:LA,avChatRoomFlag:EA,longPollingKey:W,startSequence:nA,avChatRoomKey:wA,historyMessageList:kA})}throw new this._core.helper.ChatError({code:Ch})})}_handleJoinResult(s){const{group:r,avChatRoomFlag:g,avChatRoomKey:u}=s;return g===1?(as.initGroupAttributesCache({groupID:r.groupID,avChatRoomKey:u}),Ic.initGroupCountersCache({groupID:r.groupID,avChatRoomKey:u}),fs(s)):(Wi.updateLocalGroup([r]),Wi.emitGroupListUpdate(),fs({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:r},{message:`groupID:${r.groupID}`}))}},FQ=new class{constructor(){this._name="QuitGroup"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"quitGroup",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(na)})}quitGroup(s){return mA(this,void 0,void 0,function*(){if(!Wi.hasLocalGroup(s))throw new this._core.helper.ChatError({code:MD});const{helper:{ChatError:r}}=this._core;try{yield function(u,E){return mA(this,void 0,void 0,function*(){const f={GroupId:u};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:f})})}(s,this._core);const{type:g}=Wi.getLocalGroup(s);return Wi.deleteLocalGroup(s),Wi.emitGroupListUpdate(),as.deleteGroupAttributesCache(s),fs({groupID:s,type:g},{message:`groupID:${s}`})}catch(g){const{errorCode:u,errorInfo:E}=g;throw new r({functionName:"quitGroup",code:u,message:E,moreMessage:`groupID:${s}`})}})}},EB=new class{constructor(){this._name="SearchGroup"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(s){return mA(this,void 0,void 0,function*(){try{const r=yield function(PA,zA){return mA(this,void 0,void 0,function*(){const Ee={GroupIdList:[PA],GroupBasePublicInfoFilter:[...Bg]};return zA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:Ee})})}(s,this._core),{GroupInfo:g=[]}=r||{},{AppDefinedData:u=[],ApplyJoinOption:E,CreateTime:f,FaceUrl:D,Introduction:v,InviteJoinOption:N,MaxMemberNum:P,MemberNum:W,Name:nA,Owner_Account:EA,Type:wA,ErrorCode:kA,ErrorInfo:VA}=g[0];if(kA!==0)throw new this._core.helper.ChatError({code:kA,message:VA});const LA=Rd(u),SA=new Zu({groupID:s,name:nA,avatar:D,introduction:v,joinOption:E,inviteOption:N,maxMemberCount:P,memberCount:W,type:wA,ownerID:EA,createTime:f,groupCustomField:LA});return fs({group:SA})}catch(r){const{errorCode:g,errorInfo:u}=r;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:g,message:u})}})}},VT=new class{constructor(){this._name="UpdateGroupProfile"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(s){return mA(this,void 0,void 0,function*(){const{groupID:r}=s,{utils:{isUndefined:g,safeStringify:u},ssoLog:E,helper:f}=this._core;let D=Wi.getLocalGroup(r);if(D){const{type:v}=D;this._canIUseJoinOption(v)||g(s.joinOption)||(E.warn("updateGroupProfile",`${this._name}.updateGroupProfile groupID:${r} joinOption is unavailable for Work/Meeting/AVChatRoom`),s.joinOption=void 0)}g(s.muteAllMembers)||(s.muteAllMembers=s.muteAllMembers===!0?"On":"Off");try{return yield function(v,N){return mA(this,void 0,void 0,function*(){const{groupID:P,name:W,avatar:nA,introduction:EA,notification:wA,muteAllMembers:kA,joinOption:VA,inviteOption:LA,groupCustomField:SA}=v,PA={GroupId:P,Name:W,FaceUrl:nA,Introduction:EA,Notification:wA,ShutUpAllMember:kA,ApplyJoinOption:VA,InviteJoinOption:LA,AppDefinedData:SA?JE(SA):void 0};return N.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:PA})})}(s,this._core),D?(D.updateGroup(s),Wi.emitGroupListUpdate()):D=new Zu(s),fs({group:D},{message:`groupID:${r}`})}catch(v){const{errorCode:N,errorInfo:P}=v;throw new f.ChatError({code:N,message:P,moreMessage:`options:${u(s)}`})}})}_canIUseJoinOption(s){return $M(s)||this._core.common.isCommunity({type:s})}},HT=new class{constructor(){this._name="ChangeGroupOwner"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(s){return mA(this,void 0,void 0,function*(){const r="changeGroupOwner",{groupID:g,newOwnerID:u}=s,E=Wi.getLocalGroup(g),{helper:f,OuterConstant:D,common:{getCurrentUserID:v}}=this._core;if(E?.type===D.GRP_AVCHATROOM)throw new f.ChatError({functionName:r,code:FT});if(u===v())throw new f.ChatError({functionName:r,code:km});try{return yield function(N,P){return mA(this,void 0,void 0,function*(){const{groupID:W,newOwnerID:nA}=N,EA={GroupId:W,NewOwner_Account:nA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:EA})})}(s,this._core),E.ownerID=u,Wi.emitGroupListUpdate(),fs({group:E})}catch(N){throw new f.ChatError({functionName:r,code:N?.errorCode,message:N?.errorInfo})}})}},OQ=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(na)})}getGroupOnlineMemberCount(s){return mA(this,void 0,void 0,function*(){const r="getGroupOnlineMemberCount";if(!Wi.hasLocalGroup(s))return fs({memberCount:0});const g=Date.now();if(this._onlineMemberCountMap.has(s)){const u=this._onlineMemberCountMap.get(s),{lastReqTime:E=0,memberCount:f=0}=u||{};if(g-E<=6e4)return fs({memberCount:f})}try{const u=yield function(D,v){return mA(this,void 0,void 0,function*(){const N={GroupId:D};return v.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:N})})}(s,this._core),{OnlineMemberNum:E=0}=u||{};this._onlineMemberCountMap.set(s,{lastReqTime:Date.now(),memberCount:E});const f=`${this._name}.${r} ok. groupID:${s} memberCount:${E}`;return fs({memberCount:E},{message:f})}catch(u){throw new this._core.helper.ChatError({functionName:r,code:u?.errorCode,message:u?.errorInfo})}})}},PQ=new class{init(s,r){s.ssoLog.debug("GroupAction.init"),AR.init(s),Xu.init(s),Bh.init(s,r),qE.init(s,r),FQ.init(s,r),EB.init(s),ql.init(s),VT.init(s),HT.init(s),OQ.init(s,r)}dismissGroup(s){return Bh.dismissGroup(s)}joinGroup(s){return qE.joinGroup(s)}quitGroup(s){return FQ.quitGroup(s)}getGroupOnlineMemberCount(s){return OQ.getGroupOnlineMemberCount(s)}},eR=new class{constructor(){this._name="GetGroupApplicationList"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return mA(this,void 0,void 0,function*(){const s="getGroupApplicationList";try{const r=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]);this._core.ssoLog.debug("getGroupApplicationList",`${this._name}.${s} ok.`);const g=this._handleGroupApplicationResult([...r[0],...r[1]]);return fs({applicationList:g})}catch(r){throw new this._core.helper.ChatError({functionName:s,code:r?.errorCode,message:r?.errorInfo})}})}_getGroupApplicationList(s){return mA(this,void 0,void 0,function*(){const{type:r,startTime:g=0,limit:u=20}=s||{},{common:E}=this._core;let f;try{f=yield function(P,W){return mA(this,void 0,void 0,function*(){const{type:nA,startTime:EA,limit:wA,handleAccount:kA}=P,VA={Type:nA,StartTime:EA,Limit:wA,Handle_Account:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:VA})})}({type:r,startTime:g,limit:u,handleAccount:E.getCurrentUserID()},this._core)}catch(P){if(P?.errorCode!==11e3)throw P;f={}}const{NextStartTime:D=0,PendencyList:v=[]}=f||{};if(D===0)return v;const N=yield this._getGroupApplicationList(Object.assign(Object.assign({},s),{startTime:D}));return[...v,...N]})}_handleGroupApplicationResult(s){const r=[];return s.forEach(g=>{const u=this._convertApplicationData(g),{handled:E}=u,f=vo(u,["handled"]);E===0&&r.push(f)}),r}_convertApplicationData(s){const{Handled:r,AddTime:g,ApplyInviteMsg:u,Authentication:E,FromUserNickName:f,From_Account:D,GroupId:v,GroupName:N,PendencyType:P,To_Account:W}=s;return{handled:r,messageKey:g,applicant:D,applicantNick:f,groupID:v,groupName:N,authentication:E,applicationType:P,userID:W,note:u,addTime:g}}},tR=new class{constructor(){this._name="HandleGroupApplication"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(s){return mA(this,void 0,void 0,function*(){const{application:r}=s,g=this._handleParams(s);try{r?.applicationType===Hc?yield function(E,f){return mA(this,void 0,void 0,function*(){const{groupID:D,handleAction:v,handleMessage:N,applicant:P,authentication:W,invitee:nA}=E,EA={GroupId:D,HandleMsg:v,ApprovalMsg:N,Applicant_Account:P,Authentication:W,Invited_Account:nA};return f.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:EA})})}(g,this._core):yield function(E,f){return mA(this,void 0,void 0,function*(){const{groupID:D,handleAction:v,handleMessage:N,applicant:P,authentication:W,messageKey:nA}=E,EA={GroupId:D,HandleMsg:v,ApprovalMsg:N,Applicant_Account:P,Authentication:W,MsgKey:nA};return f.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:EA})})}(g,this._core);const u=Wi.getLocalGroup(g.groupID);return fs({group:u})}catch(u){throw new this._core.helper.ChatError({functionName:"handleGroupApplication",code:u?.errorCode,message:u?.errorInfo})}})}_handleParams(s){var r;const{handleAction:g,handleMessage:u,message:E,application:f}=s;let D,v,N,P,W;if(E){const{payload:nA}=E||{};D=nA.operatorID,v=(r=nA.groupProfile)===null||r===void 0?void 0:r.groupID,N=nA.authentication,P=nA.messageKey}else D=f?.applicant||"",v=f?.groupID||"",N=f?.authentication||"",P=f?.messageKey||0;return f?.applicationType===Hc&&(W=f.userID),{handleAction:g,handleMessage:u,applicant:D,invitee:W,groupID:v,authentication:N,messageKey:P}}},wD=new class{init(s){s.ssoLog.debug("GroupApplication.init"),eR.init(s),tR.init(s)}};let MC=class{constructor(s){this.userID="",this.avatar="",this.nick="",this.role="",this.joinTime="",this.nameCard="",this.muteUntil=0,this.memberCustomField=[],this.isOnline=!1,this.updateMember(s)}updateMember(s){const{core:{utils:{isUndefined:r},common:{deepMerge:g}}}=tr;r(s.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*s.muteTime)/1e3)),r(s.onlineStatus)||(this.isOnline=s.onlineStatus==="Online");const u=[null,void 0,"",0,NaN];s.memberCustomField&&Fm(this.memberCustomField,s.memberCustomField),g(this,s,["memberCustomField","marks","onlineStatus","muteTime"],u)}};function dB(s,r){return mA(this,void 0,void 0,function*(){const{groupID:g,userID:u,muteTime:E,role:f,nameCard:D,memberCustomField:v}=s;let N;v&&(N=JE(v));const P={GroupId:g,Member_Account:u,ShutUpTime:E,Role:f,NameCard:D,AppMemberDefinedData:N};return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:P})})}var _D=new class{constructor(){this._name="GetGroupMemberList"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(na)})}getGroupMemberList(s){return mA(this,void 0,void 0,function*(){const r="getGroupMemberList",{groupID:g,offset:u=0,count:E=100,role:f="",filter:D=""}=s,v=Wi.getLocalGroup(g),N=E>100?100:E,P={groupID:g,offset:u,limit:N,memberRoleFilter:zu.includes(f)?[f]:void 0,memberInfoFilter:wm};try{const W=yield function(Ie,Li){return mA(this,void 0,void 0,function*(){const{isCommunity:Ui}=Li.common,{groupID:Yt,offset:Oi,limit:Bn,memberRoleFilter:Re,memberInfoFilter:Mt}=Ie,FA={GroupId:Yt,Limit:Bn,MemberRoleFilter:Re,MemberInfoFilter:Mt};return Ui({groupID:Yt})?FA.Next=String(Oi):FA.Offset=Oi,Li.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:FA})})}(P,this._core),{MemberList:nA,MemberNum:EA,Next:wA}=W||{},kA=`${this._name}.${r} ok, totalMemberCount:${EA} next:${wA}`,{utils:{isArray:VA,isEmpty:LA},common:{isCommunity:SA}}=this._core;if(v&&(v.memberCount=EA),!VA(nA)||nA.length===0)return fs({memberList:[],offset:0},{message:kA});let PA=u+N;SA({groupID:g})&&(PA=LA(wA)?0:wA),nA.lengthD.userID),u=yield(r=this._core.user.userProfile)===null||r===void 0?void 0:r.getUserProfile({userIDList:g}),E=u?.data||[],f=new Map(E.map(D=>[D.userID,D]));return s.forEach(D=>{if(f.has(D.userID)){const{nick:v="",avatar:N=""}=f.get(D.userID);D.nick=v,D.avatar=N}}),s})}_generateGroupMember(s){const r=[];for(let g=0,u=s.length;g50&&(N.warn("getGroupMemberProfile",`${this._name}.${r} userIDList length:${u.length} exceeds limit 50`),u.splice(50));const P=`userIDList length:${u.length} groupID:${g}`;try{const W=yield function(kA,VA){return mA(this,void 0,void 0,function*(){const{groupID:LA,userIDList:SA,memberInfoFilter:PA,memberCustomFieldFilter:zA}=kA,Ee={GroupId:LA,Member_List_Account:SA,MemberInfoFilter:PA,AppDefinedDataFilter_GroupMember:zA};return VA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:Ee})})}({groupID:g,userIDList:u,memberCustomFieldFilter:E,memberInfoFilter:[...wm]},this._core),{MemberList:nA}=W||{};if(!v(nA)||nA.length===0)return fs({memberList:[]});let EA=this._convertMemberInfo(nA);EA=yield this._getMemberAvatarAndNick(EA);const wA=this._generateGroupMember(EA);return fs({memberList:wA},{message:P})}catch(W){throw new D.ChatError({functionName:r,code:W?.errorCode,message:W?.errorInfo,moreMessage:P})}})}_convertMemberInfo(s){const r=[];for(let g=0,u=s.length;gD.userID),u=yield(r=this._core.user.userProfile)===null||r===void 0?void 0:r.getUserProfile({userIDList:g}),E=u?.data||[],f=new Map(E.map(D=>[D.userID,D]));return s.forEach(D=>{if(f.has(D.userID)){const{nick:v="",avatar:N=""}=f.get(D.userID);D.nick=v,D.avatar=N}}),s})}_generateGroupMember(s){const r=[];for(let g=0,u=s.length;g({Member_Account:v}));try{const v=yield function(wA,kA){return mA(this,void 0,void 0,function*(){const{groupID:VA,userIDList:LA}=wA,SA={GroupId:VA,MemberList:LA};return kA.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:SA})})}({groupID:g,userIDList:D},this._core),{MemberList:N=[]}=v||{},{failureUserIDList:P,successUserIDList:W,existedUserIDList:nA,overLimitUserIDList:EA}=this._handleResult(N);return fs({failureUserIDList:P,successUserIDList:W,existedUserIDList:nA,overLimitUserIDList:EA,group:E},{message:` groupID:${g} successUserIDList:${W} failureUserIDList:${P} existedUserIDList:${nA} overLimitUserIDList:${EA}`})}catch(v){throw new f.ChatError({functionName:r,code:v?.errorCode,message:v?.errorInfo})}})}_handleResult(s){const r=[],g=[],u=[],E=[];return s.forEach(f=>{const{Result:D,Member_Account:v}=f;D===_m?r.push(v):D===Tm?g.push(v):D===Nm?u.push(v):D===QD&&E.push(v)}),{failureUserIDList:r,successUserIDList:g,existedUserIDList:u,overLimitUserIDList:E}}},_d=new class{constructor(){this._name="DeleteGroupMember"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(na)})}deleteGroupMember(s){return mA(this,void 0,void 0,function*(){const r="deleteGroupMember",{groupID:g,userIDList:u}=s,E=Wi.getLocalGroup(g),{helper:f,utils:{isUndefined:D},ssoLog:v}=this._core;if(D(E))throw new f.ChatError({functionName:r,code:UT});u.length>20&&(v.warn("deleteGroupMember",`${this._name}.${r} userIDList length:${u.length} exceeds limit 20`),u.splice(20));try{return yield function(N,P){return mA(this,void 0,void 0,function*(){const{groupID:W,userIDList:nA,reason:EA}=N,wA={GroupId:W,MemberToDel_Account:nA,Reason:EA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:wA})})}({groupID:g,userIDList:u},this._core),fs({group:E,userIDList:u},{message:`groupID:${g} userIDList length:${u.length}`})}catch(N){throw new f.ChatError({functionName:r,code:N?.errorCode,message:N?.errorInfo})}})}},iR=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(s){return mA(this,void 0,void 0,function*(){const{helper:r}=this._core,{groupID:g,userID:u,muteTime:E}=s,f=` groupID:${g} userID:${u} muteTime:${E}`;this._preCheckSettingMuteParams(s);try{yield dB(s,this._core);const D=Wi.getLocalGroup(g),v=new MC({userID:u,muteTime:E});return fs({group:D,member:v},{message:f})}catch(D){throw new r.ChatError({functionName:"setGroupMemberMuteTime",code:D?.errorCode,message:D?.errorInfo,moreMessage:f})}})}_preCheckSettingMuteParams(s){const{userID:r}=s,{store:g,helper:u}=this._core;if(r===g.get("login").userId)throw new u.ChatError({functionName:"setGroupMemberMuteTime",code:RD})}},YQ=new class{constructor(){this._name="SetGroupMemberRole"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(s){return mA(this,void 0,void 0,function*(){const r="setGroupMemberRole",{helper:g}=this._core,{groupID:u,userID:E,role:f}=s,D=`${this._name}.${r} ok, groupID:${u} userID:${E} role:${f}`;this._preCheckSettingRoleParams(s);try{yield dB(s,this._core);const v=Wi.getLocalGroup(u),N=new MC({userID:E,role:f});return fs({group:v,member:N},{message:D})}catch(v){throw new g.ChatError({functionName:r,code:v?.errorCode,message:v?.errorInfo,moreMessage:D})}})}_preCheckSettingRoleParams(s){var r;const{groupID:g,userID:u,role:E}=s,{store:f,helper:D,OuterConstant:v,common:{isCommunity:N}}=this._core,P=Wi.getLocalGroup(g);if(((r=P?.selfInfo)===null||r===void 0?void 0:r.role)!==v.GRP_MBR_ROLE_OWNER)throw new D.ChatError({functionName:"setGroupMemberRole",code:PT});if(u===f.get("login").userId)throw new D.ChatError({functionName:"setGroupMemberRole",code:ZM});const W=[...zu];if(N({groupID:g})&&W.push(v.GRP_MBR_ROLE_CUSTOM),!W.includes(E))throw new D.ChatError({functionName:"setGroupMemberRole",code:Lm})}},TD=new class{constructor(){this._name="SetGroupMemberNameCard"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(s){return mA(this,void 0,void 0,function*(){var r;const g="setGroupMemberNameCard",{helper:u,common:{getCurrentUserID:E}}=this._core,{groupID:f,userID:D=E(),nameCard:v}=s,N=`${this._name}.${g} ok, groupID:${f} userID:${D} nameCard:${v}`;this._preCheckSettingNameCardParams(s);try{yield dB({groupID:f,userID:D,nameCard:v},this._core);const W=Wi.getLocalGroup(f);D===((r=W?.selfInfo)===null||r===void 0?void 0:r.userID)&&(W.updateSelfInfo({nameCard:v}),Wi.emitGroupListUpdate(),Wi.updateConversationGroupProfile(f));const nA=new MC({userID:D,nameCard:v});return fs({group:W,member:nA},{message:N})}catch(P){throw new u.ChatError({functionName:g,code:P?.errorCode,message:P?.errorInfo,moreMessage:N})}})}_preCheckSettingNameCardParams(s){const{groupID:r}=s,{helper:g}=this._core,u=Wi.getLocalGroup(r);if(Md(u?.type))throw new g.ChatError({functionName:"setGroupMemberNameCard",code:Um})}},xm=new class{constructor(){this._name="SetGroupMemberCustomField"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(s){return mA(this,void 0,void 0,function*(){const r="setGroupMemberCustomField",{helper:g,common:{getCurrentUserID:u}}=this._core;this._preCheckSettingCustomFiledParams(s);const{groupID:E,userID:f=u(),memberCustomField:D}=s,v=`${this._name}.${r} ok, groupID:${E}userID:${f} memberCustomField:${JSON.stringify(D)}`;try{yield dB({groupID:E,userID:f,memberCustomField:D},this._core);const P=Wi.getLocalGroup(E),W=new MC({userID:f,memberCustomField:D});return fs({group:P,member:W},{message:v})}catch(N){throw new g.ChatError({functionName:r,code:N?.errorCode,message:N?.errorInfo,moreMessage:v})}})}_preCheckSettingCustomFiledParams(s){const{groupID:r}=s,{helper:g}=this._core,u=Wi.getLocalGroup(r);if(Md(u?.type))throw new g.ChatError({functionName:"setGroupMemberCustomField",code:Um})}},oR=new class{init(s,r){s.ssoLog.debug("GroupMember.init"),_D.init(s,r),xQ.init(s),wd.init(s),_d.init(s,r),iR.init(s),YQ.init(s),TD.init(s),xm.init(s)}getGroupMemberList(s){return _D.getGroupMemberList(s)}deleteGroupMember(s){return _d.deleteGroupMember(s)}},JT=new class{init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(s){return mA(this,void 0,void 0,function*(){const r="getGroupCounters";try{Om(r,lc);const{groupID:g,keyList:u=[]}=s,{avChatRoomKey:E,lastUpdateTime:f}=Ic.getLocalGroupCounters(g);if(!(Date.now()-f>=this._getExpireTime()))return{code:0,data:{counters:Ic.getLocalCounters(g,u)}};const D=yield function(P){return mA(this,void 0,void 0,function*(){const{groupID:W,GroupCounterKeys:nA,avChatRoomKey:EA}=P,{common:wA}=tr.core,kA={GroupId:W,keyList:nA,BytesKey:EA};return wA.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:kA})})}({groupID:g,keyList:u,avChatRoomKey:E}),{GroupCounter:v=[],GroupCounterSeq:N}=D;return Ic.updateLocalGroupCounters({groupID:g,counterList:v,groupCounterSeq:N}),{code:0,data:{counters:Ic.getLocalCounters(g,u)}}}catch(g){vC(r,g)}})}_getExpireTime(){const{store:s,utils:{isUndefined:r}}=this._core,g=s.get("cloudConfig")||{},{grp_counter_expire_time:u}=g;return r(u)?3e4:Number(u)}},Ym=new class{init(s){const{helper:r}=s;r.registerApi({apiName:"setGroupCounters",context:this}),r.registerApi({apiName:"increaseGroupCounter",context:this}),r.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(s){return mA(this,void 0,void 0,function*(){return this._handleCounterOperation(Wu,s)})}increaseGroupCounter(s){return mA(this,void 0,void 0,function*(){return this._handleCounterOperation(Rm,s)})}decreaseGroupCounter(s){return mA(this,void 0,void 0,function*(){return this._handleCounterOperation(Gi,s)})}_handleCounterOperation(s,r){return mA(this,void 0,void 0,function*(){const g=`${s}GroupCounter`;try{Om(g,lc);const{groupID:u,key:E,value:f=0}=r,{avChatRoomKey:D}=Ic.getLocalGroupCounters(u),v=s===Wu?this._convertObjectToList(r.counters):[{Key:E,Value:f}],N=yield this._updateGroupCounters({groupID:u,counterList:v,avChatRoomKey:D,mode:s});return Ic.setGroupCounters(u,N),{code:0,data:{counters:N}}}catch(u){vC(g,u)}})}_updateGroupCounters(s){return mA(this,void 0,void 0,function*(){const r=yield function(E){const{groupID:f,counterList:D,mode:v,avChatRoomKey:N}=E,{common:P}=tr.core,W={GroupId:f,GroupCounter:D,Mode:v,BytesKey:N};return P.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:W})}(s),{GroupCounter:g=[]}=r,u={};return g.forEach(E=>{const{Key:f,Value:D=0}=E;u[f]=D}),u})}_convertObjectToList(s){return Object.entries(s).map(([r,g])=>({Key:r,Value:g||0}))}},CB=new class{init(s){this._core=s,JT.init(s),Ym.init(s)}isGroupCounterUpdated(s){const{elements:{groupCounterInfo:r}}=s,{utils:{isEmpty:g}}=this._core;return!g(r)}handleGroupCounterUpdated(s){const{to:r,elements:{groupCounterInfo:g}}=s;g.forEach(u=>{const{type:E,groupCounterSeq:f,counterList:D=[]}=u;E!==gi&&E!==Es||this._processAndNotifyCounterUpdate(r,f,D),E===_o&&Ic.deleteLocalGroupCounters({groupID:r,groupCounterSeq:f,counterList:D})})}_processAndNotifyCounterUpdate(s,r,g){const{OuterEvent:u,notificationCenter:E}=this._core;Ic.updateLocalGroupCounters({groupID:s,groupCounterSeq:r,counterList:g}),g.forEach(({Key:f,Value:D=0})=>{E.emitOuterEvent(u.GROUP_COUNTER_UPDATED,{name:u.GROUP_COUNTER_UPDATED,data:{groupID:s,key:f,value:D}})})}reset(){Ic.reset()}},Vm=new class{constructor(){this._name="InitGroupAttributes"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(s){return mA(this,void 0,void 0,function*(){const{groupID:r,groupAttributes:g}=s,{serverMainSequence:u,avChatRoomKey:E}=as.getGroupAttributesCache(r),f=as.convertKeyValueMapToList(g);try{const D=yield function(W,nA){return mA(this,void 0,void 0,function*(){const{groupID:EA,mainSequence:wA,groupAttributeList:kA,avChatRoomKey:VA}=W,LA={GroupId:EA,AttrMainSeq:wA,GroupAttr:kA,BytesKey:VA,AttrControl:["RaceConflict"]};return nA.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:LA})})}({groupID:r,avChatRoomKey:E,groupAttributeList:f,mainSequence:u},this._core),{AttrMainSeq:v,GroupAttr:N}=D||{},P=N.map(W=>{const{Key:nA,seq:EA}=W;return{key:nA,value:g[nA],sequence:EA}});return as.saveGroupAttributesCacheValuesCopy(r),as.refreshGroupAttributesCache({groupID:r,serverMainSequence:v,groupAttributeList:P,operation:pD}),as.emitGroupAttributesUpdated(r),fs({groupAttributes:g},{message:` groupID:${r} serverMainSequence:${v}`})}catch(D){throw new this._core.helper.ChatError({functionName:"initGroupAttributes",code:D?.errorCode,message:D?.errorInfo})}})}},qT=new class{constructor(){this._name="SetGroupAttributes"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupAttributes",context:this}),r.registerExperimentalAPI("setRichStatus",this)}setGroupAttributes(s){return mA(this,void 0,void 0,function*(){const{groupID:r,groupAttributes:g,richStatusMode:u}=s,{serverMainSequence:E,avChatRoomKey:f,values:D}=as.getGroupAttributesCache(r),v=as.convertKeyValueMapToList(g).map(N=>{var P;const{key:W,value:nA}=N;return{key:W,value:nA,seq:((P=D.get(N.key))===null||P===void 0?void 0:P.sequence)||0}});try{const N=yield function(EA,wA){return mA(this,void 0,void 0,function*(){const{groupID:kA,mainSequence:VA,groupAttributeList:LA,avChatRoomKey:SA,richStatusMode:PA}=EA,zA={GroupId:kA,AttrMainSeq:VA,GroupAttr:LA,BytesKey:SA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:PA};return wA.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:zA})})}({groupID:r,avChatRoomKey:f,groupAttributeList:v,mainSequence:E,richStatusMode:u},this._core),{AttrMainSeq:P,GroupAttr:W}=N||{},nA=W.map(EA=>{const{Key:wA,seq:kA}=EA;return{key:wA,value:g[wA],sequence:kA}});return as.saveGroupAttributesCacheValuesCopy(r),as.refreshGroupAttributesCache({groupID:r,serverMainSequence:P,groupAttributeList:nA,operation:KM}),as.emitGroupAttributesUpdated(r),fs({groupAttributes:g},{message:` groupID:${r} serverMainSequence:${P}`})}catch(N){throw new this._core.helper.ChatError({functionName:"setGroupAttributes",code:N?.errorCode,message:N?.errorInfo})}})}setRichStatus(s){return mA(this,void 0,void 0,function*(){const{groupID:r,richStatus:g}=s;return this.setGroupAttributes({groupID:r,groupAttributes:g,richStatusMode:!0})})}},ND=new class{constructor(){this._name="DeleteGroupAttributes"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"deleteGroupAttributes",context:this}),r.registerExperimentalAPI("deleteRichStatus",this)}deleteGroupAttributes(s){return mA(this,void 0,void 0,function*(){const r="deleteGroupAttributes",{groupID:g,keyList:u=[],richStatusMode:E}=s;try{let f;f=u.length===0?yield this._clearGroupAttributes(g,{richStatusMode:E}):yield this._deleteGroupAttributes(g,{keyList:u,richStatusMode:E});const{resultList:D,serverMainSequence:v,operation:N,groupAttributeList:P}=f||{},W=`${this._name}.${r} ok. groupID:${g} operation: ${N}`;return as.saveGroupAttributesCacheValuesCopy(g),as.refreshGroupAttributesCache({groupID:g,serverMainSequence:v,groupAttributeList:P,operation:N}),as.emitGroupAttributesUpdated(g),fs({keyList:D},{message:W})}catch(f){throw new this._core.helper.ChatError({functionName:r,code:f?.errorCode,message:f?.errorInfo})}})}deleteRichStatus(s){return mA(this,void 0,void 0,function*(){return this.deleteGroupAttributes(Object.assign(Object.assign({},s),{richStatusMode:!0}))})}_deleteGroupAttributes(s,r){return mA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:u,values:E}=as.getGroupAttributesCache(s),{keyList:f,richStatusMode:D}=r,v=[],N=[];f.forEach(nA=>{if(E.has(nA)){const{sequence:EA=0}=E.get(nA)||{};N.push({key:nA,seq:EA}),v.push(nA)}});const P=yield function(nA,EA){return mA(this,void 0,void 0,function*(){const{groupID:wA,mainSequence:kA,groupAttributeList:VA,avChatRoomKey:LA,richStatusMode:SA}=nA,PA={GroupId:wA,AttrMainSeq:kA,GroupAttr:VA,BytesKey:LA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:SA};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:PA})})}({groupID:s,avChatRoomKey:u,groupAttributeList:N,mainSequence:g,richStatusMode:D},this._core),{AttrMainSeq:W}=P||{};return{resultList:v,serverMainSequence:W,groupAttributeList:N,operation:fD}})}_clearGroupAttributes(s,r){return mA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:u,values:E}=as.getGroupAttributesCache(s),{richStatusMode:f}=r||{},D=[...E.keys()],v=yield function(P,W){return mA(this,void 0,void 0,function*(){const{groupID:nA,mainSequence:EA,avChatRoomKey:wA,richStatusMode:kA}=P,VA={GroupId:nA,AttrMainSeq:EA,BytesKey:wA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:VA})})}({groupID:s,avChatRoomKey:u,mainSequence:g,richStatusMode:f},this._core),{AttrMainSeq:N}=v||{};return{resultList:D,serverMainSequence:N,operation:mD}})}},GD=new class{constructor(){this._name="GetGroupAttributes"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getGroupAttributes",context:this}),r.registerExperimentalAPI("getRichStatus",this,"getGroupAttributes")}getGroupAttributes(s){return mA(this,void 0,void 0,function*(){const{groupID:r}=s,{avChatRoomKey:g,lastUpdateTime:u,localMainSequence:E,serverMainSequence:f}=as.getGroupAttributesCache(r),{helper:{ChatError:D}}=this._core,v=`groupID:${r} localMainSequence:${E} serverMainSequence:${f} keyList:${s.keyList}`;if(Date.now()-u>=3e4||E{const{key:nA,value:EA,seq:wA}=W;return{key:nA,value:EA,sequence:wA}});return as.refreshGroupAttributesCache({groupID:u,serverMainSequence:v,groupAttributeList:P,operation:jM}),{serverGroupAttributeList:N}})}},VQ=new class{init(s){s.ssoLog.debug("GroupAttribute.init"),Vm.init(s),qT.init(s),ND.init(s),GD.init(s),as.init(s)}isGroupAttributesUpdated(s){return as.isGroupAttributesUpdated(s)}handleGroupAttributesUpdated(s){const{to:r,elements:{newGroupProfile:g}}=s,{groupAttributeOption:u}=g,{serverMainSequence:E,withChangedAttributeInfo:f}=u,{localMainSequence:D}=as.getGroupAttributesCache(r),v=E-D;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${r} withChangedAttributeInfo:${f} diffSequence:${v}`),v!==0)if(as.saveGroupAttributesCacheValuesCopy(r),f!==1||v!==1){if(as.hasGroupAttributesCache(r)){const{avChatRoomKey:N}=as.getGroupAttributesCache(r);GD.getGroupAttributesFromServer({groupID:r,avChatRoomKey:N}).then(()=>{as.emitGroupAttributesUpdated(r)}).catch(()=>{})}}else as.handleGroupAttributesUpdated({groupID:r,groupAttributeOption:u})}reset(){as.reset()}};function KE(s,r="tips"){const{ClientSeq:g,From_Account:u,MsgClientTime:E,MsgPriority:f,MsgRandom:D,MsgSeq:v,MsgTimeStamp:N,TinyId:P,ToGroupId:W,GroupInfo:nA,MsgBody:EA}=s,wA=function(kA){const{GroupCode:VA,GroupId:LA,GroupName:SA,GroupType:PA,MsgFrom_AccountExtraInfo:zA,From_Account:Ee,To_Account:Ie}=kA;return{groupCode:VA,groupID:LA,groupName:SA,type:PA,messageFromAccountExtraInformation:zA,from:Ee,to:Ie}}(nA);return{clientSequence:g,from:u,clientTime:E,priority:f,random:D,sequence:v,time:N,tinyID:P,to:W,groupProfile:wA,elements:r==="tips"?$u(EA):Qh(EA)}}function $u(s){const r={};return Object.keys(s).forEach(g=>{var u,E;switch(g){case"MemberNum":r.memberCount=s[g];break;case"OpType":r.operationType=s[g];break;case"Operator_Account":r.operatorID=s[g];break;case"List_Account":r.userIDList=s[g];break;case"MsgMemberExtraInfo":r.memberInfoList=(u=s[g])===null||u===void 0?void 0:u.map(f=>bD(f));break;case"MsgOperatorMemberExtraInfo":r.operatorInfo=bD(s[g]);break;case"MsgGroupNewInfo":r.newGroupProfile=function(f){const D={};return Object.keys(f).forEach(v=>{switch(v){case"GroupIntroduction":D.introduction=f[v];break;case"GroupName":D.groupName=f[v];break;case"GroupFaceUrl":D.avatar=f[v];break;case"GroupNotification":D.notification=f[v];break;case"ApplyJoinOption":D.joinOption=f[v];break;case"InviteJoinOption":D.inviteOption=f[v];break;case"ShutupAll":D.muteAllMembers=f[v];break;case"Owner_Account":D.ownerID=f[v];break;case"GroupAttrOption":D.groupAttributeOption=function(P){const{BytesChangedKeys:W,GroupAttrSeq:nA,OpType:EA,PushChangedAttrValFlag:wA,GroupAttrInfo:kA}=P,VA=kA.map(LA=>{const{Key:SA,Val:PA,SubKeySeq:zA}=LA;return{key:SA,value:PA,sequence:zA}});return{changedKeyList:W,groupAttributeList:VA,serverMainSequence:nA,operation:EA,withChangedAttributeInfo:wA}}(f[v]);break;case"MsgAppDefinedData":D.groupCustomField=(N=f[v])==null?void 0:N.map(P=>({key:P.Key,value:P.Value}));break;case"InviteOption":D.inviteOption=YT[f[v]]||f[v]}var N}),D}(s[g]);break;case"MsgMemberInfo":r.msgMemberInfo=(E=s[g])===null||E===void 0?void 0:E.map(f=>function(D){const{ShutupTime:v,User_Account:N}=D;return{muteTime:v,userID:N}}(f));break;case"OnlineMemberInfo":r.onlineMemberInfo=function(f){const{ExpireTime:D,OnlineMemberNum:v}=f;return{expireTime:D,onlineMemberNum:v}}(s[g]);break;case"GroupCounterInfo":r.groupCounterInfo=function(f){return f.map(D=>{const{GroupCounterSeq:v,GroupCounter:N,Type:P}=D;return{type:P,groupCounterSeq:v,counterList:N}})}(s[g])}}),r}function bD(s){const{ImageUrl:r,NickName:g,Role:u,UserId:E}=s;return{avatar:r,nick:g,role:u,userID:E}}function Qh(s){const r={};return Object.keys(s).forEach(g=>{switch(g){case"MsgKey":r.messageKey=s[g];break;case"Operator_Account":r.operatorID=s[g];break;case"ReportType":r.operationType=s[g];break;case"Authentication":r.authentication=s[g];break;case"MsgFlag":r.messageRemindType=s[g];break;case"UserDefinedField":r.userDefinedField=s[g];break;case"RemarkInfo":r.remarkInfo=s[g];break;case"BanDuration":r.duration=s[g];break;case"MuteTime":r.muteTime=s[g];break;case"MsgMemberExtraInfoList":r.inviteeInfoList=(u=s[g]||[])==null?void 0:u.map(E=>{const{UserId:f,ImageUrl:D,NickName:v}=E;return{userID:f,avatar:D,nick:v}});break;case"MemberList_Account":r.inviteeList=s[g]}var u}),r}class Hm{constructor(r){this.type=tr.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(r)}static parseServerPushElement(r){const g=$u(r);return new Hm(g)}_initContent(r){Object.keys(r).forEach(g=>{switch(g){case"groupProfile":this._initGroupProfile(r[g]);break;case"operatorInfo":this._initOperatorInfo(r[g]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(r[g]);break;case"newGroupProfile":this._initNewGroupProfile(r[g]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[g]=r[g]}}),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(r){this.content.groupProfile={};const g=Object.keys(r);for(let u=0;u{r.forEach(u=>{g.userID===u.userID&&Object.assign(g,u)})}):this.content.memberList=r}_initNewGroupProfile(r){this.content.newGroupProfile={};const g=Object.keys(r);for(let u=0;u0&&this._handleGroupTipMessage(g),{conversationUpdateFieldList:u,messageList:g}}_emitGroupTipsEvent(s){var r;const{constants:{WORKFLOW_STEP:g}}=this._core,{messageList:u=[]}=((r=s?.result)===null||r===void 0?void 0:r[g.HANDLE_GROUP_TIPS_NOTIFICATION])||{};if(u.length>0){const{notificationCenter:E,OuterEvent:f}=this._core;E.emitOuterEvent(f.MESSAGE_RECEIVED,{name:f.MESSAGE_RECEIVED,data:u})}}_handleGroupTips(s,r=!0){const{Event:g,GroupTips:u}=s,E=new Map,f=[],D=[];for(let v=0,N=u.length;v{const{operationType:u}=g.payload;switch(u){case r.JOINED:this._handleNewMemberJoined(g);break;case r.QUITTED:this._handleMemberQuitted(g);break;case r.KICKED:this._handleMemberKicked(g);break;case r.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(g);break;case r.ADMIN_SET:this._handleMemberGrantAdmin(g);break;case r.ADMIN_CANCELED:this._handleMemberRevokeAdmin(g)}})}_handleNewMemberJoined(s){this._handleGroupMemberCountUpdated(s)}_handleMemberQuitted(s){this._handleGroupMemberCountUpdated(s)}_handleMemberKicked(s){this._handleGroupMemberCountUpdated(s)}_handleGroupProfileUpdated(s){var r;const{newGroupProfile:g,groupProfile:u,operatorInfo:E}=s.payload,{groupID:f}=u,D=Wi.getLocalGroup(f);Object.keys(g).forEach(N=>{switch(N){case"ownerID":this._handleGroupOwnerChanged(f,g);break;case"groupName":D.name=g[N];break;case"groupCustomField":Array.isArray(D[N])&&Array.isArray(g[N])?Fm(D[N],g[N]):D[N]=g[N];break;default:D[N]=g[N]}});const{utils:{isUndefined:v}}=this._core;v(E)||((r=D?.selfInfo)===null||r===void 0?void 0:r.userID)!==E.userID||Object.keys(E).forEach(N=>{N==="nameCard"&&D.updateSelfInfo({nameCard:E[N]}),N==="role"&&this._updateSelfRole(D,E[N])}),Wi.emitGroupListUpdate(),Wi.updateConversationGroupProfile(f)}_handleGroupOwnerChanged(s,r){const{common:g,OuterConstant:u}=this._core,E=Wi.getLocalGroup(s),f=g.getCurrentUserID(),{ownerID:D}=r;f===D&&E.updateGroup({ownerID:D,selfInfo:{role:u.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(s,r){const{OuterConstant:g}=this._core;let u=g.GRP_MBR_ROLE_MEMBER;r===NT?u=g.GRP_MBR_ROLE_OWNER:r===DD&&(u=g.GRP_MBR_ROLE_ADMIN),s.updateSelfInfo({role:u})}_handleGroupMemberCountUpdated(s){const{memberCount:r,groupProfile:{groupID:g}}=s.payload,u=Wi.getLocalGroup(g),{utils:{isNumber:E}}=this._core;u&&E(r)&&u.memberCount!==r&&(u.memberCount=r,Wi.emitGroupListUpdate(),Wi.updateConversationGroupProfile(g))}_handleGroupTipsRecover(s){const{utils:{isArray:r}}=this._core,{groupTipList:g}=s?.result||{};r(g)&&g.forEach(u=>{const{messageList:E}=this._handleGroupTips({Event:u.Event,GroupTips:[u]},!1);this._handleGroupTipMessage(E)})}_handleMemberGrantAdmin(s){const{OuterConstant:r}=this._core,{groupProfile:g,userIDList:u}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:f}=g,D=Wi.getLocalGroup(f);D&&u.includes(E)&&(D.updateSelfInfo({role:r.GRP_MBR_ROLE_ADMIN}),Wi.emitGroupListUpdate(),Wi.updateConversationGroupProfile(f))}_handleMemberRevokeAdmin(s){const{OuterConstant:r}=this._core,{groupProfile:g,userIDList:u}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:f}=g,D=Wi.getLocalGroup(f);D&&u.includes(E)&&(D.updateSelfInfo({role:r.GRP_MBR_ROLE_MEMBER}),Wi.emitGroupListUpdate(),Wi.updateConversationGroupProfile(f))}};class HQ{constructor(r){this.type=tr.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(r)}static parseServerPushElement(r){const g=Qh(r);return new HQ(g)}_initContent(r){Object.keys(r).forEach(g=>{switch(g){case"remarkInfo":this.content.handleMessage=r[g];break;case"groupProfile":this._initGroupProfile(r[g]);break;case"memberInfoList":break;default:this.content[g]=r[g]}})}_initGroupProfile(r){this.content.groupProfile={};const g=Object.keys(r);for(let u=0;u0&&this._handleGroupSysTemMessage(g,E),g===!0&&E.length>0&&f.emitOuterEvent(D.MESSAGE_RECEIVED,{name:D.MESSAGE_RECEIVED,data:E})}_handleGroupSystemNotification(s,r){const g=[];let u={};for(let E=0;E0?[u]:[],messageList:g}}_assembleMessage(s){const{message:{messageFactory:r},OuterConstant:g,utils:{randomInt:u}}=this._core;s.flow="in",s.conversationType=g.CONV_SYSTEM,s.conversationSubType=s.groupProfile.type,s.conversationID=g.CONV_SYSTEM;const E=r.createMessage(s),f=new HQ(Object.assign(Object.assign({},s.elements),{groupProfile:Object.assign({},s.groupProfile)}));E.setElement(f),E.isSystemMessage=!0;const D=E.sequence===1&&E.random===1,v=E.sequence===2&&E.random===2;return(D||v)&&(E.sequence=u(),E.random=u(),E.generateMessageID()),E}_handleConversationOptions(s,r){const{OuterConstant:g}=this._core,u={conversationID:g.CONV_SYSTEM,unreadCount:0,type:g.CONV_SYSTEM,subType:s.conversationSubType,lastMessage:null};return r&&u.unreadCount++,u}_handleGroupSysTemMessage(s,r){s&&r.forEach(g=>{const{operationType:u}=g.payload;switch(u){case bT:this._handleGroupJoinResult(g);break;case zM:this._handleMemberKicked(g);break;case kT:this._handleGroupDismissed(g);break;case LT:this._handleGroupInvitedResult(g);break;case SD:this._handleGroupQuitResult(g);break;case UQ:this._handleMessageRemindTypeSynced(g);break;case Gm:this._handleAVChatRoomMemberBanned(g)}})}_handleGroupJoinResult(s){const{groupProfile:r}=s.payload,{groupID:g,type:u}=r,E=Wi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${g} type:${u} hasLocalGroup:${E}`),E||Md(u)||(Wi.updateLocalGroup([Object.assign({},r)]),Wi.emitGroupListUpdate())}_handleMemberKicked(s){const{groupProfile:{groupID:r,type:g}}=s.payload;Wi.hasLocalGroup(r)&&this._deleteLocalGroup(r,g),this._updateConversationProfile(r,{unreadCount:0})}_handleGroupDismissed(s){const{groupProfile:{groupID:r,type:g}}=s.payload;Wi.hasLocalGroup(r)&&this._deleteLocalGroup(r,g),this._updateConversationProfile(r,{unreadCount:0})}_handleGroupInvitedResult(s){const{groupProfile:r}=s.payload,{groupID:g}=r,u=Wi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${g} hasLocalGroup:${u}`),u||ql.getGroupProfile({groupID:g}).then(E=>{const{data:{group:f}}=E;Wi.updateLocalGroup([Object.assign({},f)]),Wi.emitGroupListUpdate()})}_handleGroupQuitResult(s){const{groupProfile:{groupID:r,type:g}}=s.payload,u=Wi.hasLocalGroup(r);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${r} type:${g} hasLocalGroup:${u}`),u&&this._deleteLocalGroup(r,g),this._updateConversationProfile(r,{unreadCount:0})}_handleMessageRemindTypeSynced(s){const{groupProfile:{groupID:r},messageRemindType:g}=s.payload;this._updateConversationProfile(r,{messageRemindType:g})}_handleAVChatRoomMemberBanned(s){const{groupProfile:{groupID:r,type:g}}=s.payload;this._deleteLocalGroup(r,g)}_deleteLocalGroup(s,r){if(Md(r)){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:u}}=this._core;g.deleteConversation(`${u}${s}`)}Wi.deleteLocalGroup(s),Wi.emitGroupListUpdate()}_updateConversationProfile(s,r){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:u}}=this._core,E=`${u}${s}`;g.getConversation(E)&&g.updateConversation(E,r)}},kD=new class{init(s){this._core=s,s.ssoLog.debug("GroupNotificationHandler.init"),nR.init(s),sR.init(s);const{notificationCenter:r,InnerEvent:g}=s,{InnerEventSubType:u}=r;r.subscribeInnerEvent(g.MESSAGE_PUSH,u.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),r.subscribeInnerEvent(g.MESSAGE_PUSH,u.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),r.subscribeInnerEvent(g.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(s){const{common:{workflowManager:r},constants:{WORKFLOW_NAME:g}}=this._core;r.executeWorkflow(g.RECEIVE_GROUP_TIPS_NOTIFICATION,s)}_onNewGroupSystemNotification(s){sR.onNewGroupSystemNotification(s)}_dispose(){const{notificationCenter:s,InnerEvent:r}=this._core,{InnerEventSubType:g}=s;s.unSubscribeInnerEvent(r.MESSAGE_PUSH,g.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),s.unSubscribeInnerEvent(r.MESSAGE_PUSH,g.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this)}};const bs={required:!0,rules:["string"],allowEmpty:!1},JQ={required:!0,rules:["number"],allowEmpty:!1},Td={required:!0,rules:["array"],allowEmpty:!1},LD={required:!0,rules:["object"],allowEmpty:!1},KT={createGroup:{name:bs,type:bs},dismissGroup:[Object.assign({key:"groupID"},bs)],joinGroup:{groupID:bs,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},bs)],searchGroupByID:[Object.assign({key:"groupID"},bs)],getGroupProfile:{groupID:bs,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:bs,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:bs,newOwnerID:bs},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},bs)],handleGroupApplication:{handleAction:bs},getGroupMemberList:{groupID:bs},getGroupMemberProfile:{groupID:bs,userIDList:Td,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:bs,userIDList:Td},deleteGroupMember:{groupID:bs,userIDList:Td},setGroupMemberMuteTime:{groupID:bs,userID:bs,muteTime:Object.assign(Object.assign({},JQ),{customValidator:s=>!(s<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:bs,userID:bs,role:bs},setGroupMemberNameCard:{groupID:bs,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:bs},setGroupMemberCustomField:{groupID:bs,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:Td},markGroupMemberList:{groupID:bs,markType:Object.assign(Object.assign({},JQ),{customValidator:s=>!(s<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:Td},initGroupAttributes:{groupID:bs,groupAttributes:LD},setGroupAttributes:{groupID:bs,groupAttributes:LD},deleteGroupAttributes:{groupID:bs,keyList:Object.assign(Object.assign({},Td),{allowEmpty:!0})},getGroupAttributes:{groupID:bs,keyList:Object.assign(Object.assign({},Td),{allowEmpty:!0})},getGroupCounters:{groupID:bs,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:bs,counters:LD},increaseGroupCounter:{groupID:bs,key:bs,value:JQ},decreaseGroupCounter:{groupID:bs,key:bs,value:JQ}},jT={getGroupList:!0,createGroup:!0,dismissGroup:!0,joinGroup:!0,quitGroup:!0,searchGroupByID:!0,getGroupProfile:!0,updateGroupProfile:!0,changeGroupOwner:!0,getGroupOnlineMemberCount:!0,getGroupApplicationList:!0,handleGroupApplication:!0,getGroupMemberList:!0,getGroupMemberProfile:!0,addGroupMember:!0,deleteGroupMember:!0,setGroupMemberMuteTime:!0,setGroupMemberRole:!0,setGroupMemberNameCard:!0,setGroupMemberCustomField:!0,markGroupMemberList:!0,initGroupAttributes:!0,setGroupAttributes:!0,getGroupAttributes:!0,deleteGroupAttributes:!0,getGroupCounters:!0,setGroupCounters:!0,increaseGroupCounter:!0,decreaseGroupCounter:!0};var WT=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=Wi,this.groupAction=PQ,this.groupAttribute=VQ,this.groupMember=oR,this.groupCounter=CB,this.name="Group"}install(s,r=[]){this._core=s,tr.init(s),Wi.init(s),PQ.init(s,this),oR.init(s,this),wD.init(s),CB.init(s),VQ.init(s),kD.init(s),s.helper.registerValidateConfig({auth:jT,params:KT}),this._installSubPlugins(r);const{notificationCenter:g,InnerEvent:u}=s;g.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.subscribeInnerEvent(u.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(s){const{utils:{isArray:r}}=this._core;s&&r(s)&&s.forEach(g=>{var u;this._installedSubPlugins.includes(g.name)||((u=g.install)===null||u===void 0||u.call(g,this._core,this),this._installedSubPlugins.push(g.name))})}_reset(){Wi.reset(),VQ.reset(),CB.reset()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const hB=new class{init(s){this.core=s}},rR="AV_MBR_LIST",zT="AV_BAN_MBR",jE={NORMAL_MESSAGE:3,GROUP_TIPS_HAS_ROAMING:4,GROUP_SYSTEM_MESSAGE:5,GROUP_TIPS_HAS_NO_ROAMING:6,BROADCAST_MESSAGE:17,MESSAGE_REVOKED:20,MESSAGE_REACTION:21,LIVE_CUSTOM_DATA:100},ph={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},UD=60,FD=2603,ZT=2686,XT=2688,qQ=3122;class aR{constructor(r){const{core:g,manager:u,groupID:E,getRequestParams:f,onSuccess:D,onFail:v}=r;this._name="Polling",this._core=g,this._manager=u,this._timeoutID=-1,this._isRunning=!1,this._groupID=E,this._getRequestParams=f,this._onSuccess=D,this._onFail=v}start(){this._isRunning=!0,this._request(),console.log(`${this._name}.start pollingInterval:${this._manager.getCurrentPollingInterval(this._groupID)}`)}isRunning(){return this._isRunning}_request(){return mA(this,void 0,void 0,function*(){try{const r=this._getRequestParams(this._groupID),g=yield function(E,f){return mA(this,void 0,void 0,function*(){const{longPollingKey:D,startSequence:v,startBroadcastSeq:N,simplifiedMessage:P}=E,W={Key:D,StartSeq:v,StartBroadcastSeq:N,DownsizeFlag:P,USP:1,HoldTime:90};return f.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:W})})}(r,this._core);this._onSuccess(this._groupID,g);const u=this._manager.getCurrentPollingInterval(this._groupID);this._runNextPolling(u)}catch(r){this._onFail(this._groupID,r),this._runNextPolling(2e3)}})}_runNextPolling(r){this.isRunning()&&(this._timeoutID>-1&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),r))}stop(){console.log(`${this._name}.stop timerID:${this._timeoutID}`),this._timeoutID>-1&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class mh{constructor(r){this._maxLength=r,this._map=new Map}set(r){var g;if(this._map.size>=this._maxLength){const u=((g=this._map.entries().next().value)===null||g===void 0?void 0:g[0])||"";this._map.delete(u)}this._map.set(r,1)}has(r){return this._map.has(r)}delete(r){this.has(r)&&this._map.delete(r)}clear(){this._map.clear()}}const AE=s=>s===jE.GROUP_TIPS_HAS_NO_ROAMING||s===jE.GROUP_TIPS_HAS_ROAMING,KQ=s=>s===jE.GROUP_SYSTEM_MESSAGE;function Jm(s){const r=function(g){const{E:u,MCT:E,MR:f,MP:D,MTS:v,GId:N,MS:P,CCD:W,F_Account:nA,IsSys:EA,GInf:wA,MsgBody:kA}=g,VA=vo(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:u,MsgClientTime:E,MsgRandom:f,MsgPriority:D,MsgTimeStamp:v,ToGroupId:N,MsgSeq:P,CloudCustomData:W,From_Account:nA,IsSystemMsg:EA,GroupInfo:OD(wA),MsgBody:$T(kA)},VA)}(s);return function(g){const{Event:u}=g;(AE(u)||KQ(u))&&(g.From_Account=g.From_Account||"@TIM#SYSTEM"),E=u,(E===jE.BROADCAST_MESSAGE||(f=>f===jE.NORMAL_MESSAGE)(u))&&function(f){const{core:{OuterConstant:D}}=hB;f.CloudCustomData=f.CloudCustomData||"",f.MsgBody=f.MsgBody.map(v=>{if(v.MsgType===D.MSG_CUSTOM){const{content:N={}}=v;v.content=Object.assign({Data:"",Desc:"",Ext:""},N)}return v})}(g);var E;AE(u)&&function(f){const{GroupJoinType:D,MsgOperatorMemberExtraInfo:v={},MsgMemberExtraInfo:N,Operator_Account:P,List_Account:W,OpType:nA}=f.MsgBody||{};typeof D=="number"||nA!==1&&nA!==2||(f.MsgBody.GroupJoinType=nA===2?0:1),N||(f.MsgBody.MsgMemberExtraInfo=W?.map(EA=>({UserId:EA}))),nA!==1||N||(f.MsgBody.MsgMemberExtraInfo=[{UserId:v.UserId}]),f.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:P,ImageUrl:"",NickName:""},v)}(g),KQ(u)&&function(f){const{MsgOperatorMemberExtraInfo:D={},Operator_Account:v}=f.MsgBody||{};f.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:v,ImageUrl:"",NickName:""},D),f.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*f.MsgTimeStamp},f.MsgBody),f.MsgBody=Object.keys(f.MsgBody).filter(N=>N!=="MsgOperatorMemberExtraInfo").reduce((N,P)=>Object.assign(Object.assign({},N),{[P]:f.MsgBody[P]}),{})}(g)}(r),r}function OD(s){const r=s||{},{GN:g,GT:u,F_Hd:E,F_NN:f,F_Ll:D}=r,v=vo(r,["GN","GT","F_Hd","F_NN","F_Ll"]),N=Object.assign({GroupName:g,GroupType:u},v);return E&&(N.From_AccountHeadurl=E),f&&(N.From_AccountNick=f),D&&(N.From_AccountLevel=D),N}function $T(s){let r=s;Array.isArray(s)||(r=[s]);const g=r.map(u=>{const{O_Account:E,Opt:f,L_Account:D,RT:v,UDF:N,OpInf:P,OnlineInf:W,MsgMemberExtraInfo:nA}=u,EA=vo(u,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),wA=Object.assign({Operator_Account:E,OpType:f,List_Account:D,ReportType:v,UserDefinedField:N},EA);return P&&(wA.MsgOperatorMemberExtraInfo=function(kA){const{Img:VA,NN:LA}=kA,SA=vo(kA,["Img","NN"]);return Object.assign({ImageUrl:VA,NickName:LA},SA)}(P)),nA&&(wA.MsgMemberExtraInfo=function(kA){return kA?.map(VA=>{const{Img:LA,NN:SA}=VA,PA=vo(VA,["Img","NN"]);return Object.assign({ImageUrl:LA,NickName:SA},PA)})}(nA)),W&&(wA.OnlineMemberInfo=function(kA){const{ET:VA,Num:LA}=kA;return{ExpireTime:VA,OnlineMemberNum:LA}}(W)),wA});return Array.isArray(s)?g:g[0]}var fh=new class{constructor(){this._name="MessageParser",this._sequenceList=new mh(200),this._messageIDList=new mh(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(s,r){this._core=s,this._avChatRoomHandler=r}onMessageReceived(s,r,g=!1){this._sortServerMessageList({groupID:s,serverMessageList:r,isHistoryMessage:g});const u=this._handleMessageList(s,r);if(u.length===0)return;if(!g){const{appStore:{conversationStore:N},OuterConstant:{CONV_GROUP:P},common:{buildLastMessage:W}}=this._core,nA=W(u[u.length-1]);N.updateConversation(`${P}${s}`,{lastMessage:nA})}this._checkMessageStacked(u);const E=u.filter(N=>N.isModified===!0),f=u.filter(N=>N.isModified===!1),{OuterEvent:{MESSAGE_RECEIVED:D,MESSAGE_MODIFIED:v}}=this._core;E.length>0&&this._emitEvent({name:v,data:E}),f.length>0&&this._emitEvent({name:D,data:f})}_sortServerMessageList(s){const{groupID:r,serverMessageList:g,isHistoryMessage:u}=s;let E=[];this._avChatRoomHandler.isPollingSimplifiedMessage()&&!u?(g.sort((f,D)=>f.MS-D.MS),E=g.map(f=>f.MS)):(g.sort((f,D)=>f.MsgSeq-D.MsgSeq),E=g.map(f=>f.MsgSeq)),console.log(`${this._name}._sortServerMessageList groupID:${r} count:${E.length} sequenceList:${E}`),E.length=0}_handleMessageList(s,r){var g;const{message:{messageDataHandler:u,messageHelper:E}}=this._core,f=this._avChatRoomHandler.isPollingSimplifiedMessage(),D=[],v=r.length;for(let N=0;Ng===jE.MESSAGE_REVOKED)(r)?(this._handleMessageRevoked(s),null):(g=>g===jE.LIVE_CUSTOM_DATA)(r)?(this._onLiveCustomData(s),null):(g=>g===jE.MESSAGE_REACTION)(r)?null:s:(console.warn(`${this._name}.onMessageReceived unknown event:${r}`),null)}_createMessage(s){const{message:{messageFactory:r},OuterConstant:g}=this._core;let u=g.CONV_GROUP;s.elements.type===g.MSG_GRP_SYS_NOTICE&&(u=g.CONV_SYSTEM);const E=!!s.isSystemMessage,f=r.createMessage(Object.assign(Object.assign({},s),{conversationType:u,isSystemMessage:E,flow:"in"}));return f.setElement(s.elements),f}_filterDuplicateMessage(s){const{common:r}=this._core;if(!r.isUnlimitedAVChatRoom()){if(this._sequenceList.has(s.sequence))return null;this._sequenceList.set(s.sequence)}const g=this._messageIDList.has(s.ID);return g?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${s.ID} has:${g}`),null):(this._messageIDList.set(s.ID),s)}_handleMessageRevoked(s){const{OuterConstant:r,OuterEvent:{MESSAGE_REVOKED:g}}=this._core,{ToGroupId:u,MsgBody:{RevokeMsgList:E},RevokerInfo:{Revoker_Account:f,Reason:D=""}}=s,v=[];E.forEach(N=>{const{TinyId:P,MsgClientTime:W,Random:nA,MsgSeq:EA}=N,wA={conversationID:`${r.CONV_GROUP}${u}`,ID:`${P}-${W}-${nA}`,revoker:f,revokeReason:D,revokerInfo:{userID:f,nick:"",avatar:""},sequence:EA};v.push(wA)}),v.length!==0&&this._emitEvent({name:g,data:v})}_onLiveCustomData(s){const{OuterEvent:{ROOM_CUSTOM_DATA_RECEIVED:r}}=this._core,{ToGroupId:g,MsgSeq:u,MsgTimeStamp:E,MsgBody:f}=s,D=f?.Content||f?.MsgContent||"";this._emitEvent({name:r,data:D}),console.log(`${this._name}._onLiveCustomData groupID:${g} sequence:${u} time:${E} data:${D}`)}_onGroupDismissed(s){this._avChatRoomHandler.reset(s)}_checkMessageStacked(s){const{length:r}=s;if(r>=100&&this._reportMessageStackedCount<5){const g=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.info("MessageStacked",`count:${r} groupID:${g.join(",")}`),this._reportMessageStackedCount+=1}}_emitEvent(s){this._core.notificationCenter.emitOuterEvent(s.name,s)}onBroadcastMessageReceived(s){const{message:{messageHelper:r},OuterEvent:{MESSAGE_RECEIVED:g}}=this._core,u=this._avChatRoomHandler.isPollingSimplifiedMessage(),E=[],f=s.length;for(let D=0;D0&&this._emitEvent({name:g,data:E})}_updateLocalOnlineMemberCountFromTips(s){const{utils:{isEmpty:r}}=this._core,{ToGroupId:g,MsgBody:{OnlineMemberInfo:u}}=s;if(r(u))return;const{OnlineMemberNum:E=0,ExpireTime:f=UD}=u,D=Date.now();let v=this._avChatRoomHandler.getLocalOnlineMemberCount(g);r(v)?v={lastReqTime:0,lastSyncTime:0,latestUpdateTime:D,memberCount:E,expireTime:f}:(v.latestUpdateTime=D,v.memberCount=E),this._avChatRoomHandler.updateLocalOnlineMemberCount(g,v)}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};const BB=s=>{const{core:{store:r}}=hB;return(r.get("cloudConfig")||{})[s]},yh=s=>{const{core:{utils:{isUndefined:r}}}=hB;return!r(s)},jQ=()=>{const s=BB("polling_interval");return yh(s)?parseInt(s,10):300},QB=()=>{const s=BB("polling_simplified_msg");return yh(s)?parseInt(s,10):0};var gR=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}getGroupOnlineMemberCount(s){return mA(this,void 0,void 0,function*(){const{appStore:{groupStore:r},OuterConstant:g}=this._core,u=r.getGroup(s);return u?u.type===g.GRP_AVCHATROOM?this._getOnlineMemberCount(s):this._parentPlugin.groupAction.getGroupOnlineMemberCount(s):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(s){return mA(this,void 0,void 0,function*(){const r="_getOnlineMemberCount",{utils:{isEmpty:g}}=this._core,u=Hg.getLocalOnlineMemberCount(s);if(g(u)||this._isExpired(s)){const{memberCount:E=0}=yield this._getOnlineMemberCountFromServer(s);return console.log(`${this._name}.${r} ok, groupID:${s} memberCount:${E} from server.`),{code:0,data:{memberCount:E}}}return console.log(`${this._name}.${r} ok, groupID:${s} memberCount:${u.memberCount} from local.`),{code:0,data:{memberCount:u.memberCount}}})}_isExpired(s){const r=Hg.getLocalOnlineMemberCount(s),g=Date.now(),u=g-r.lastSyncTime>1e3*r.expireTime,E=g-r.latestUpdateTime>1e4,f=g-r.lastReqTime>3e3;return u&&E&&f}_getOnlineMemberCountFromServer(s){return mA(this,void 0,void 0,function*(){const r="_getOnlineMemberCountFromServer";try{const g=yield function(v,N){return mA(this,void 0,void 0,function*(){const P={GroupId:v};return N.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:P})})}(s,this._core),{OnlineMemberNum:u=0,ExpireTime:E=UD}=g||{},f=Date.now(),D={lastSyncTime:f,latestUpdateTime:f,lastReqTime:f,memberCount:u,expireTime:E};return Hg.updateLocalOnlineMemberCount(s,D),{memberCount:u}}catch(g){const u=new this._core.helper.ChatError({functionName:r,code:g?.errorCode,message:g?.errorInfo});throw console.error(`${this._name}.${r} fail:`,u),u}})}},Hg=new class{constructor(){this._name="AVChatRoomHandler",this._joinedGroupMap=new Map,this._pollingRequestInfoMap=new Map,this._pollingInstanceMap=new Map,this._onlineMemberCountMap=new Map,this._pollingIntervalMap=new Map,this._pollingNoMessageCountMap=new Map,this._membersReqInfoMap=new Map,this._startBroadcastSequence=1}init(s,r){this._core=s,this._parentPlugin=r,fh.init(s,this),s.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(s){const{OuterConstant:{GRP_AVCHATROOM:r}}=this._core,{GroupTips:g=[]}=s;for(let u=0;u0&&(r=[...this._joinedGroupMap.values()].filter(g=>g.type===s)),r}handleJoinGroupResult(s){return mA(this,void 0,void 0,function*(){const{utils:{isUndefined:r},OuterConstant:{CONV_GROUP:g},apiMap:{getConversationProfile:u},OuterConstant:E}=this._core,{longPollingKey:f,group:D,historyMessageList:v=[]}=s,{groupID:N}=D;return yield this._preCheck(D),this._joinedGroupMap.set(N,D),this._parentPlugin.groupDataHandler.updateLocalGroup([D]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),u(`${g}${N}`),gR.getGroupOnlineMemberCount(N),v.length>0&&fh.onMessageReceived(N,v,!0),r(f)?{code:0,data:{status:E.JOIN_STATUS_SUCCESS,group:D}}:{code:0,data:this.startMessageLongPolling(s)}})}isGroupCounterUpdated(s){return this._parentPlugin.groupCounter.isGroupCounterUpdated(s)}handleGroupCounterUpdated(s){this._parentPlugin.groupCounter.handleGroupCounterUpdated(s)}_preCheck(s){return mA(this,void 0,void 0,function*(){const{common:r,OuterConstant:g,helper:u,apiMap:{quitGroup:E},ssoLog:f}=this._core;if(r.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(()=>{const N=BB("polling_count_limit");return yh(N)&&N>0?parseInt(N,10):20})())throw new u.ChatError({code:XT,message:"the count of longPolling exceeds the max limit"});return}if(this._joinedAVChatRoomCount()===0||s.type===g.GRP_LIVE)return;const[D,v]=this._joinedGroupMap.entries().next().value;if(v.selfInfo.role===g.GRP_MBR_ROLE_OWNER)this._parentPlugin.groupDataHandler.deleteLocalGroup(D);else try{yield E(D)}catch(N){f.debug("quitGroup",`${this._name}._preCheck quitGroup failed, groupID:${D} info:`,N)}this.reset(D)})}startMessageLongPolling(s){const{OuterConstant:r}=this._core,{longPollingKey:g,startSequence:u=1,group:E}=s,{groupID:f}=E;return this._pollingRequestInfoMap.set(f,{longPollingKey:g,startSequence:u}),this._pollingIntervalMap.set(f,jQ()),this._startPolling(f),this._reportLongPollingCount(),{status:r.JOIN_STATUS_SUCCESS,group:E}}_startPolling(s){if(this._core.ssoLog.debug("_startPolling",`${this._name}._startPolling groupID:${s}`),this._pollingInstanceMap.has(s)){const g=this._pollingInstanceMap.get(s);return void(g?.isRunning()||g==null||g.start())}const r=new aR({core:this._core,manager:this,groupID:s,getRequestParams:this._handleRequestParams.bind(this),onSuccess:this._handleSuccess.bind(this),onFail:this._handleFailure.bind(this)});r.start(),this._pollingInstanceMap.set(s,r)}_handleRequestParams(s){const{longPollingKey:r,startSequence:g}=this._pollingRequestInfoMap.get(s)||{};return s===[...this._pollingInstanceMap.keys()][0]?{longPollingKey:r,startSequence:g,startBroadcastSeq:this._startBroadcastSequence,simplifiedMessage:QB()}:{longPollingKey:r,startSequence:g,simplifiedMessage:QB()}}_handleSuccess(s,r){const{ErrorCode:g}=r;if(g!==0){const{longPollingKey:u,startSequence:E}=this._pollingRequestInfoMap.get(s)||{};return void console.warn(`${this._name}._handleSuccess groupID:${s} key:${u} startSeq:${E} errorCode:${g}`)}this._hasJoinedAVChatRoom(s)&&this._handleResponseData(s,r)}_handleResponseData(s,r){const{Key:g,NextSeq:u,NextBroadcastSeq:E,RspMsgList:f=[],RspBroadcastMsgList:D=[]}=r;if(g&&u&&this._pollingRequestInfoMap.set(s,{longPollingKey:g,startSequence:u}),E&&E>this._startBroadcastSequence&&(this._startBroadcastSequence=E),f.length>0)this._getPollingNoMessageCount(s)!==0&&(this._updatePollingNoMessageCount(s,0),this._pollingIntervalMap.set(s,jQ())),fh.onMessageReceived(s,f);else{let v=this._getPollingNoMessageCount(s);if(v+=1,this._updatePollingNoMessageCount(s,v),v===(()=>{const N=BB("polling_no_msg_count");return yh(N)?parseInt(N,10):20})()){const N=jQ()+(()=>{const P=BB("polling_interval_plus");return yh(P)?parseInt(P,10):2e3})();this._pollingIntervalMap.set(s,N)}}D.length>0&&fh.onBroadcastMessageReceived(D)}_handleFailure(s,r){const{ssoLog:g,utils:{safeStringify:u}}=this._core;g.warn("polling",`${this._name}._handleFailure groupID:${s} error: ${u(r)}`)}_joinedAVChatRoomCount(){const{OuterConstant:s}=this._core;let r=[];return this._joinedGroupMap.size>0&&(r=this.getJoinedGroups().filter(g=>g.type===s.GRP_AVCHATROOM)),r.length}_hasJoinedAVChatRoom(s){return this._joinedGroupMap.has(s)}getJoinedGroups(){return[...this._joinedGroupMap.values()]}updateLocalLiveGroup(s,r){this._joinedGroupMap.set(s,r),this._parentPlugin.groupDataHandler.updateLocalGroup([r])}handleLiveHistoryMessages(s,r){fh.onMessageReceived(s,r,!0)}isOverFrequencyLimit(s){if(!this._membersReqInfoMap.has(s))return this._membersReqInfoMap.set(s,{startTime:Date.now(),requestCount:1}),!1;let{startTime:r,requestCount:g}=this._membersReqInfoMap.get(s);const{interval:u,count:E}=(()=>{const f=BB("av_members_freq_limit");if(yh(f)){const{interval:D,count:v}=JSON.parse(f);if(v>0&&D>0)return{interval:D,count:v}}return{interval:30,count:4}})();return Date.now()-r>1e3*u?(this._membersReqInfoMap.set(s,{startTime:Date.now(),requestCount:1}),!1):(g+=1,this._membersReqInfoMap.set(s,{startTime:r,requestCount:g}),g>E)}_stopPolling(s){if(this._core.ssoLog.debug("_stopPolling",`${this._name}._stopPolling groupID:${s}`),s){const{appStore:{conversationStore:r},OuterConstant:{CONV_GROUP:g}}=this._core;r.deleteConversation(`${g}${s}`);const u=this._pollingInstanceMap.get(s);return u?.stop(),this._parentPlugin.groupDataHandler.deleteLocalGroup(s),this._pollingInstanceMap.delete(s),this._pollingRequestInfoMap.delete(s),this._joinedGroupMap.delete(s),this._onlineMemberCountMap.delete(s),this._pollingIntervalMap.delete(s),this._pollingNoMessageCountMap.delete(s),void this._membersReqInfoMap.delete(s)}for(const r of this._pollingInstanceMap.values())r?.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear(),this._onlineMemberCountMap.clear(),this._pollingIntervalMap.clear(),this._pollingNoMessageCountMap.clear(),this._membersReqInfoMap.clear()}_updatePollingNoMessageCount(s,r){this._pollingNoMessageCountMap.set(s,r)}_getPollingNoMessageCount(s){return this._pollingNoMessageCountMap.get(s)||0}_reportLongPollingCount(){const s=this._joinedGroupMap.size;if(s>1){const{common:r,OuterConstant:g,ssoLog:u}=this._core,E=r.isUnlimitedAVChatRoom()?1:0,f=[],D=[];Array.from(this._joinedGroupMap.values()).forEach(({groupID:v,type:N})=>{N===g.GRP_LIVE?D.push(v):f.push(v)}),u.info("longPollingCount",String(s),{moreMessage:`av:${f.join(",")} live:${D.join(",")} code: ${E}`,eventType:29})}}reset(s){this._stopPolling(s),this._startBroadcastSequence=1,fh.reset()}},cR=new class{init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"joinGroup",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}joinGroup(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r}=this._core,g=yield this._parentPlugin.groupAction.joinGroup(s),{data:{status:u,group:{type:E}}}=g;return E===r.GRP_AVCHATROOM?u===r.JOIN_STATUS_ALREADY_IN_GROUP?g:Hg.handleJoinGroupResult(g.data):g})}},AN=new class{init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"quitGroup",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}quitGroup(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r}=this._core,g=yield this._parentPlugin.groupAction.quitGroup(s),{data:{type:u}}=g;return u===r.GRP_AVCHATROOM&&Hg.reset(s),g})}},lR=new class{init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"dismissGroup",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}dismissGroup(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r}=this._core,g=yield this._parentPlugin.groupAction.dismissGroup(s),{data:{type:u}}=g;return u===r.GRP_AVCHATROOM&&Hg.reset(s),g})}},qm=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}getGroupMemberList(s){return mA(this,void 0,void 0,function*(){const{appStore:{groupStore:r},helper:g,OuterConstant:u}=this._core,{groupID:E}=s,f=r.getGroup(E);if(f?.type===u.GRP_AVCHATROOM&&g.checkBusinessCapabilityBits(rR)){if(Hg.isOverFrequencyLimit(E))throw{code:2996,message:`Over frequency limit: get_members-${E}`};return this._getGroupMemberList(s)}return this._parentPlugin.groupMember.getGroupMemberList(s)})}_getGroupMemberList(s){return mA(this,void 0,void 0,function*(){const r="_getGroupMemberList",{helper:g}=this._core;try{const u=yield function(v,N){return mA(this,void 0,void 0,function*(){const{groupID:P,offset:W=0}=v,nA={GroupId:P,Timestamp:W};return N.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:nA})})}(s,this._core),{MemberList:E=[],NextTimestamp:f=0}=u||{},D=this._handleMemberList(E);return console.log(`${this._name}.${r} ok, groupID:${s.groupID} count:${D.length} nextOffset:${f}`),{code:0,data:{memberList:D,offset:f}}}catch(u){const E=new g.ChatError({functionName:r,code:u?.errorCode,message:u?.errorInfo});throw console.error(`${this._name}.${r} fail:`,E),E}})}_handleMemberList(s){return s.map(r=>{const{Member_Account:g,NickName:u="",Avatar:E="",Remark:f="",JoinTime:D=0,Marks:v=[]}=r;return{userID:g,nick:u,avatar:E,remark:f,joinTime:D,marks:v,isOnline:!0}})}},Km=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}deleteGroupMember(s){return mA(this,void 0,void 0,function*(){const r="deleteGroupMember",{appStore:{groupStore:g},utils:{isUndefined:u},helper:E,OuterConstant:f}=this._core,{groupID:D}=s,v=g.getGroup(D);if(u(v))throw new E.ChatError({functionName:r,code:FD});if(v.type===f.GRP_AVCHATROOM){if(E.checkBusinessCapabilityBits(zT))return this._deleteGroupMember(s);throw new E.ChatError({functionName:r,code:qQ})}return this._parentPlugin.groupMember.deleteGroupMember(s)})}_deleteGroupMember(s){return mA(this,void 0,void 0,function*(){const r="_deleteGroupMember",{appStore:{groupStore:g},helper:u,ssoLog:E}=this._core,{groupID:f,duration:D=0,userIDList:v}=s;if(D===0)throw new u.ChatError({functionName:r,code:ZT});try{return yield function(N,P){return mA(this,void 0,void 0,function*(){const{groupID:W,userIDList:nA,duration:EA,reason:wA}=N,kA={GroupId:W,Members_Account:nA,Duration:EA,Description:wA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:kA})})}(s,this._core),E.debug(r,`${this._name}.${r} ok, groupID:${f}`),{code:0,data:{group:g.getGroup(f),userIDList:v}}}catch(N){throw new u.ChatError({functionName:r,code:N?.errorCode,message:N?.errorInfo})}})}},Nd=new class{constructor(){this._name="MarkAVChatRoomMember"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(s){return mA(this,void 0,void 0,function*(){const r="markGroupMemberList",{groupID:g,markType:u,enableMark:E,userIDList:f=[]}=s,D=this._generateRequestData(s);try{const v=yield function(nA,EA){return mA(this,void 0,void 0,function*(){const{groupID:wA,operationType:kA,memberList:VA}=nA,LA={GroupId:wA,CommandType:kA,MemberList:VA};return EA.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:LA})})}(D,this._core),{MemberList:N=[]}=v||{},{successUserIDList:P,failureUserIDList:W}=this._handleResult(N,f);return{code:0,data:{successUserIDList:P,failureUserIDList:W},successLog:{message:`${this._name}.${r} ok, groupID:${g} markType:${u} enableMark:${E} success:${P.length} fail:${W.length}`}}}catch(v){throw new this._core.helper.ChatError({functionName:r,code:v?.errorCode,message:v?.errorInfo})}})}_generateRequestData(s){const{groupID:r,markType:g,enableMark:u,userIDList:E=[]}=s,f=u===!0?1:2,D=[...E];return D.length>500&&console.warn(`${this._name}._generateRequestData, the length of userIDList cannot exceed 500`),{groupID:r,operationType:f,memberList:D.map(v=>({Member_Account:v,Marks:[g]}))}}_handleResult(s,r){const g=[],u=[];return s.length===r.length?(g.push(...r),{successUserIDList:g,failureUserIDList:u}):(r.forEach(E=>{s.find(f=>f.Member_Account===E)?g.push(E):u.push(E)}),{successUserIDList:g,failureUserIDList:u})}},IR=new class{init(s,r){s.ssoLog.debug("AVChatRoomAction.init"),cR.init(s,r),AN.init(s,r),lR.init(s,r),qm.init(s,r),gR.init(s,r),Km.init(s,r),Nd.init(s)}},uR=new class{constructor(){this._name="LiveHandler"}init(s){this._core=s;const{helper:r,ssoLog:g}=s;r.registerExperimentalAPI("startMessageLongPolling",this),r.registerExperimentalAPI("stopMessageLongPolling",this),g.debug("LiveHandler.init")}startMessageLongPolling(s){const{common:r,utils:{isEmpty:g},OuterConstant:u,ssoLog:E}=this._core,{groupID:f,longPollingKey:D,longPollingSequence:v=1}=s;if(g(D))return E.warn("startMessageLongPolling",`${this._name}.startMessageLongPolling longPollingKey is empty.`),Promise.resolve({});Hg.hasPollingInstance(f)&&this.stopMessageLongPolling({groupID:f});const N=Hg.getJoinedLiveList(),P=r.isUnlimitedAVChatRoom();!P&&N.length>0&&this.stopMessageLongPolling({groupID:N[0].groupID}),E.debug("startMessageLongPolling",`${this._name}.startMessageLongPolling isUnlimited:${P} groupID:${f} longPollingKey:${D} longPollingSequence:${v}`);const W={groupID:f,type:u.GRP_LIVE};return Hg.updateLocalLiveGroup(f,W),this._getLiveHistoryMessages({groupID:f,longPollingKey:D,startSequence:v}),Hg.startMessageLongPolling({group:W,longPollingKey:D,startSequence:v})}stopMessageLongPolling(s){const{groupID:r}=s;return Hg.reset(r),this._core.ssoLog.debug("stopMessageLongPolling",`${this._name}.stopMessageLongPolling ok, groupID:${r}`),Promise.resolve({groupID:r})}_getLiveHistoryMessages(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r}=this._core,{groupID:g}=s;try{const u=yield function(f,D){return mA(this,void 0,void 0,function*(){const{groupID:v,longPollingKey:N,startSequence:P}=f,W={GroupId:v,LongPollingKey:N,PullPreSeq:P};return D.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_huge_group_msg",data:W})})}(s,this._core),{RspMsgList:E=[]}=u||{};r.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages ok, groupID:${g} count:${E.length}`),E.length>0&&Hg.handleLiveHistoryMessages(g,E)}catch(u){r.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages failed, groupID:${g} info:${u.message}`)}})}},jm=new class{constructor(){this.name="AVChatRoom"}install(s,r){this._core=s,hB.init(s),Hg.init(s,r),IR.init(s,r),uR.init(s);const{notificationCenter:g,InnerEvent:u}=s,{InnerEventSubType:E}=g;g.subscribeInnerEvent(u.MESSAGE_PUSH,E.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),g.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.subscribeInnerEvent(u.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(s){Hg.onAVChatRoomSystemNotification(s)}_reset(){Hg.reset()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core,{InnerEventSubType:g}=s;s.unSubscribeInnerEvent(r.MESSAGE_PUSH,g.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const og=new class{init(s){this.core=s}},Wm="message",pB="user",mB={OR:"or",AND:"and"},NI=20,eN=20,ER=20,Dh={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!s||!!(Array.isArray(s)&&s.length<=5)||"keywordList should be an array and length <= 5"},zm={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>!s||!![mB.OR,mB.AND].includes(s)||"keywordListMatchType should be OR or AND"},RC={required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s=="number"&&s>=1&&s<=100||"count must be a number between 1 and 100"},WQ={required:!1,rules:["string"],allowEmpty:!0},dR={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:r}=og.core;if(!Array.isArray(s))return"groupTypeList should be an array";const g=[r.GRP_PUBLIC,r.GRP_COMMUNITY,r.GRP_WORK,r.GRP_MEETING];let u=!1;for(let E=0;E{const{OuterConstant:r}=og.core,g=[r.MSG_TEXT,r.MSG_IMAGE,r.MSG_AUDIO,r.MSG_FILE,r.MSG_VIDEO,r.MSG_LOCATION,r.MSG_CUSTOM,r.MSG_MERGER];let u=!1;for(let E=0;E{const{OuterConstant:r}=og.core;return!(!s?.startsWith(r.CONV_C2C)&&!s?.startsWith(r.CONV_GROUP)&&s!==r.CONV_SYSTEM)||"conversationID is invalid"}},Zm=s=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:r=>typeof r=="number"&&r>=0||`${s} should be a number >= 0';`}),PD={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:r}=og.core;return!![r.GENDER_FEMALE,r.GENDER_MALE].includes(s)||"gender is invalid"}},Xm={searchCloudMessages:{keywordList:Dh,keywordListMatchType:zm,cursor:WQ,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!!(Array.isArray(s)&&s.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:CR,conversationID:hR,timePosition:Zm("timePosition"),timePeriod:Zm("timePeriod")},searchCloudUsers:{keywordList:Dh,keywordListMatchType:zm,cursor:WQ,count:RC,miniBirthday:Zm("miniBirthday"),maxBirthday:Zm("maxBirthday"),gender:PD},searchCloudGroupMembers:{keywordList:Dh,keywordListMatchType:zm,cursor:WQ,count:RC,groupTypeList:dR,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:Dh,keywordListMatchType:zm,cursor:WQ,count:RC,groupTypeList:dR}},xD={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var YD=new class{constructor(){this.name="CloudSearch"}install(s){this._core=s,og.init(s),s.helper.registerApi({apiName:"searchCloudMessages",context:this}),s.helper.registerApi({apiName:"searchCloudUsers",context:this}),s.helper.registerApi({apiName:"searchCloudGroupMembers",context:this}),s.helper.registerApi({apiName:"searchCloudGroups",context:this}),s.helper.registerValidateConfig({auth:xD,params:Xm})}searchCloudMessages(s){return mA(this,void 0,void 0,function*(){try{const{OuterConstant:r,helper:g}=this._core,{conversationID:u,timePeriod:E,timePosition:f}=s,D=vo(s,["conversationID","timePeriod","timePosition"]),v=Object.assign({count:100},D);u&&(u.startsWith(r.CONV_C2C)?v.account=u.replace(r.CONV_C2C,""):u.startsWith(r.CONV_GROUP)&&(v.groupID=u.replace(r.CONV_GROUP,""))),this._setTimeRangeParams(v,{timePeriod:E,timePosition:f});const N=yield function(LA){return mA(this,void 0,void 0,function*(){const{count:SA,keywordList:PA,keywordListMatchType:zA,senderUserIDList:Ee,messageTypeList:Ie,endTime:Li,startTime:Ui,cursor:Yt,account:Oi,groupID:Bn}=LA,Re={Count:SA,KeywordList:PA,MatchType:zA,SendUserIDList:Ee,MsgTypeList:Ie,EndTime:Li,StartTime:Ui,Cursor:Yt,PeerAccount:Oi,GroupID:Bn};return og.core.common.buildAndSendPacket({servcmd:"message_search.query",data:Re})})}(v);if(!N)return{code:0,data:{}};const{ErrorCode:P,ErrorInfo:W,TotalCount:nA,Cursor:EA="",ConversationMsgs:wA=[]}=N;if(P!==0)throw{errorCode:P,errorInfo:W};const kA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} res: totalCount:${nA}`;return{code:0,data:{searchResultList:wA.map(LA=>{const{MsgList:SA,Count:PA,GroupID:zA,UserID:Ee}=LA,Ie=zA?`${r.CONV_GROUP}${zA}`:`${r.CONV_C2C}${Ee}`;if(this._isSearchingAllConversations(s)&&PA>1)return{conversationID:Ie,messageCount:PA,messageList:[]};const Li=SA.map(Ui=>g.isEmpty(zA)?function(Yt,Oi){const Bn=Oi.OuterConstant.CONV_C2C,Re=Oi.message.messageHelper.parseServerPushMessage(Yt),Mt=Oi.message.messageFactory.createMessage(Object.assign(Object.assign({},Re),{conversationType:Bn,flow:"in"}));return Mt.setElement(Re.elements),Mt}(Ui,this._core):function(Yt,Oi){const Bn=Oi.OuterConstant.CONV_GROUP,Re=Oi.message.messageHelper.parseServerGroupMessage(Yt),Mt=Oi.message.messageFactory.createMessage(Object.assign(Object.assign({},Re),{conversationType:Bn,flow:"in"}));return Mt.setElement(Re.elements),Mt}(Ui,this._core));return{conversationID:Ie,messageCount:PA,messageList:Li}}),cursor:EA,totalCount:nA},successLog:{message:kA}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};this._handleError({errorCode:g,errorInfo:u,searchType:Wm,functionName:"searchCloudMessages"})}})}searchCloudUsers(s){return mA(this,void 0,void 0,function*(){var r;try{const{keywordListMatchType:g,count:u=eN}=s,E=vo(s,["keywordListMatchType","count"]),f=Object.assign({count:u,keywordListMatchType:g===mB.AND?1:0},E);this._setBirthdayRangeParams(f,s);const D=yield function(kA){return mA(this,void 0,void 0,function*(){const{count:VA,keywordList:LA,keywordListMatchType:SA,miniBirthday:PA,maxBirthday:zA,cursor:Ee,gender:Ie}=kA,Li={Count:VA,Keywords:LA,KeywordMatchType:SA,Cursor:Ee,UserBirthStart:PA,UserBirthEnd:zA,Gender:Ie};return og.core.common.buildAndSendPacket({servcmd:"user_search.query",data:Li})})}(f);if(!D)return{error:0,data:{}};const{ErrorCode:v,ErrorInfo:N,TotalCount:P,Cursor:W="",Users:nA=[]}=D;if(v!==0)throw{errorCode:v,errorInfo:N};const EA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${P}`,wA=[];for(let kA=0,VA=nA.length;kA({tag:Ee.Tag,value:Ee.StrValue})),zA=(r=this._core.user.userProfile)===null||r===void 0?void 0:r.createProfile(LA,PA);wA.push(zA)}return{code:0,data:{searchResultList:wA,cursor:W,totalCount:P},successLog:{message:EA}}}catch(g){const{errorCode:u,errorInfo:E}=g||{};this._handleError({errorCode:u,errorInfo:E,searchType:pB,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(s){return mA(this,void 0,void 0,function*(){try{const{count:r=ER,keywordListMatchType:g}=s,u=vo(s,["count","keywordListMatchType"]),E=Object.assign({count:r,keywordListMatchType:g===mB.AND?1:0},u),f=yield function(wA){return mA(this,void 0,void 0,function*(){const{count:kA,keywordList:VA,keywordListMatchType:LA,groupTypeList:SA,cursor:PA,groupIDList:zA}=wA,Ee={Count:kA,Keywords:VA,KeywordMatchType:LA,Cursor:PA,GroupType:SA,GroupIdList:zA};return og.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:Ee})})}(E);if(!f)return{code:0,data:{}};const{ErrorCode:D,ErrorInfo:v,GroupMembers:N=[],Cursor:P,TotalCount:W}=f;if(D!==0)throw{errorCode:D,errorInfo:v};const nA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${W}`,EA=new Map;return N.forEach(wA=>{const{GroupID:kA,GroupName:VA,GroupType:LA,GroupFaceUrl:SA,GroupMemberUserName:PA,GroupMemberUserID:zA,GroupMemberNameCard:Ee,GroupMemberAvatar:Ie=""}=wA,Li={groupID:kA,name:VA,type:LA,avatar:SA},Ui={userID:zA,nick:PA,nameCard:Ee,avatar:Ie};if(EA.has(kA)){const Yt=EA.get(kA);Yt.memberList.push(Ui),EA.set(kA,Yt)}else EA.set(kA,{groupInfo:Li,memberList:[Ui]})}),{code:0,data:{searchResultList:[...EA.values()],cursor:P,totalCount:W},successLog:{message:nA}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};this._handleError({errorCode:g,errorInfo:u,searchType:pB,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(s){return mA(this,void 0,void 0,function*(){try{const{count:r=NI,keywordListMatchType:g}=s,u=vo(s,["count","keywordListMatchType"]),E=Object.assign({count:r,keywordListMatchType:g===mB.AND?1:0},u),f=yield function(EA){return mA(this,void 0,void 0,function*(){const{count:wA,keywordList:kA,keywordListMatchType:VA,groupTypeList:LA,cursor:SA}=EA,PA={Count:wA,Keywords:kA,KeywordMatchType:VA,Cursor:SA,GroupType:LA};return og.core.common.buildAndSendPacket({servcmd:"group_search.query",data:PA})})}(E);if(!f)return{code:0,data:{}};const{ErrorCode:D,ErrorInfo:v,Groups:N,Cursor:P,TotalCount:W}=f;if(D!==0)throw{errorCode:D,errorInfo:v};const nA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${W}`;return{code:0,data:{searchResultList:N?.map(EA=>function(wA){const{GroupFaceUrl:kA,GroupID:VA,GroupIntroduction:LA,GroupMemberNum:SA,GroupName:PA,GroupOwnerTinyID:zA,GroupOwnerUserID:Ee,GroupOwnerUserName:Ie,GroupType:Li,GroupAddOption:Ui,GroupInviteOption:Yt}=wA;return{avatar:kA,groupID:VA,introduction:LA,memberCount:SA,name:PA,ownerTinyID:zA,ownerID:Ee,ownerNick:Ie,type:Li,joinOption:Ui,inviteOption:Yt}}(EA))||[],cursor:P,totalCount:W},successLog:{message:nA}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};this._handleError({errorCode:g,errorInfo:u,searchType:pB,functionName:"searchCloudGroups"})}})}_setTimeRangeParams(s,{timePeriod:r,timePosition:g}){r&&r>0&&(s.startTime=g&&g>0?g-r:this._core.helper.timeManager.getServerTimeSeconds()-r),s.startTime&&s.startTime<0&&(s.startTime=void 0),g&&g>0&&(s.endTime=g)}_handleError({errorCode:s,errorMessage:r,searchType:g}){const{helper:u}=this._core;let E=s;throw s===60020?E="SearchUnable":g!==Wm&&s===27003?E="SearchParamsError":g!==Wm&&s===60018&&(E="SearchOverLimit"),new u.ChatError({code:E,message:r})}_isSearchingAllConversations(s){return this._core.helper.isEmpty(s.conversationID)}_setBirthdayRangeParams(s,r){const{miniBirthday:g,maxBirthday:u}=r;g!==void 0&&(s.miniBirthday=g,u===void 0&&(s.maxBirthday=4294967295)),u!==void 0&&(s.maxBirthday=u)}};function Sh(s,r){return Math.round(Number(s)*Math.pow(10,r))/Math.pow(10,r)}const BR="qualityStat",VD="im-ssolog-quality-stat";var HD;(function(s){s[s.ONLINE=8]="ONLINE"})(HD||(HD={}));const $m="networkRTT",vh="messageE2EDelay",fB="sendMessageC2C",Mh="sendMessageGroup",Rh="sendMessageGroupAV",yB="sendMessageRichMedia",DB="cosUpload",wC="messageReceivedGroup",zQ="messageReceivedGroupAVPush",ZQ="messageReceivedGroupAVPull",tN={[$m]:2,[vh]:3,[fB]:4,[Mh]:5,[Rh]:6,[yB]:7,[wC]:8,[zQ]:9,[ZQ]:10,[DB]:11},QR=[fB,Mh,Rh,yB,DB],wh=[wC,zQ,ZQ],SB=[$m,vh,fB,Mh,Rh,yB,DB,wC,zQ,ZQ],JD={ERR_SVR_COMM_SENSITIVE_TEXT:80001,ERR_SVR_COMM_BODY_SIZE_LIMIT:80002,OPEN_SERVICE_OVERLOAD_ERROR:60022,ERR_SVR_MSG_PKG_PARSE_FAILED:20001,ERR_SVR_MSG_INTERNAL_AUTH_FAILED:20002,ERR_SVR_MSG_INVALID_ID:20003,ERR_SVR_MSG_PUSH_DENY:20006,ERR_SVR_MSG_IN_PEER_BLACKLIST:20007,ERR_SVR_MSG_BOTH_NOT_FRIEND:20009,ERR_SVR_MSG_NOT_PEER_FRIEND:20010,ERR_SVR_MSG_NOT_SELF_FRIEND:20011,ERR_SVR_MSG_SHUTUP_DENY:20012,ERR_SVR_GROUP_INVALID_PARAMETERS:10004,ERR_SVR_GROUP_PERMISSION_DENY:10007,ERR_SVR_GROUP_NOT_FOUND:10010,ERR_SVR_GROUP_INVALID_GROUPID:10015,ERR_SVR_GROUP_REJECT_FROM_THIRDPARTY:10016,ERR_SVR_GROUP_SHUTUP_DENY:10017,MSG_SEND_FAIL:2100,OVER_FREQUENCY_LIMIT:2996},Af="quality_stat";var XQ=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(JD))}init(s){this._core=s,Object.values(QR).forEach(r=>{this._messageStatsMap.set(r,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(s){const{name:r,message:g,error:u,startTs:E}=s,{SEND_MESSAGE_STAT:f}=this._core.constants;switch(r){case f.TOTAL_COUNT:this._handleTotalCount(g);break;case f.SUCCESS_COUNT:this._handleSuccessCount(g);break;case f.FAILED_COUNT:this._handleFailedCount(g,u);break;case f.SEND_COST:this._handleSendCost(g,E)}}getStatResult(s){const r=this._messageStatsMap.get(s);if(!r||r.totalCount===0)return null;const{totalCount:g,successCount:u,failedCountOfUserSide:E}=r,f=Sh(u/g*100,2),D=u+E,v=Sh(D/g*100,2),N=this._calcAverageValue(r,s);return this._resetStat(s),{total_count:g,success_count_business:u,percent_business:f,success_count_platform:D,percent_platform:v,average_value:N}}_handleTotalCount(s){const r=this._getSendMessageSpecifiedKey(s),g=r&&this._messageStatsMap.get(r);g&&g.totalCount++}_handleSuccessCount(s){const r=this._getSendMessageSpecifiedKey(s),g=r&&this._messageStatsMap.get(r);g&&g.successCount++}_handleFailedCount(s,r){var g;const u=(g=r?.code)!==null&&g!==void 0?g:r?.errorCode;if(this._isUserSideError(u)){const E=this._getSendMessageSpecifiedKey(s),f=E&&this._messageStatsMap.get(E);f&&f.failedCountOfUserSide++}}_handleSendCost(s,r){const g=this._getSendMessageSpecifiedKey(s),u=g&&this._messageStatsMap.get(g);u&&(u.costSum+=Date.now()-r,u.costCount++)}_isUserSideError(s){return this._userSideErrorCodes.has(s)||s>=120001&&s<=13e4||s>=10100&&s<=10200}_getSendMessageSpecifiedKey(s){const{MSG_IMAGE:r,MSG_AUDIO:g,MSG_VIDEO:u,MSG_FILE:E,CONV_C2C:f,CONV_GROUP:D,GRP_AVCHATROOM:v}=this._core.OuterConstant;if([r,g,u,E].includes(s.type))return yB;if(s.conversationType===f)return fB;if(s.conversationType===D){const{groupStore:N}=this._core.appStore,P=N.getGroup(s.to);if(!P)return;const{type:W}=P;return W===v?Rh:Mh}}_calcAverageValue(s,r){return s.costCount===0?0:Math.round(r===DB?1e3*s.fileSizeSum/s.costSum:s.costSum/s.costCount)}_resetStat(s){const r=this._messageStatsMap.get(s);r&&(r.totalCount=0,r.successCount=0,r.failedCountOfUserSide=0,r.costSum=0,r.costCount=0,r.fileSizeSum=0)}},$Q=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(s){this._core=s;const{OuterEvent:r,notificationCenter:g}=s;this._initStatsMap(),g.subscribeOuterEvent(r.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(s){const r=this._getReceivedMessageSpecifiedKey(s),{utils:{isUndefined:g},OuterConstant:{CONV_GROUP:u},ssoLog:E}=this._core;if(g(r)||!this._currentCycleStats.has(r))return void E.debug("addMessageSequence",`${BR}.addMessageSequence invalid key:${r}`);const{conversationID:f,sequence:D}=s,v=f.replace(u,""),N=this._lastCycleStats.get(r);if(N.size===0||!N.has(v))return void this._addToCurrentCycle(r,v,D);const P=N.get(v);D>P.minSeq&&D{const{sortedSequences:f,minSeq:D,maxSeq:v}=E;f.length>0&&(u+=f.length,g+=v-D+1)}),g===0?null:(this._transferCycleDataOptimized(s),{total_count:g,success_count_business:u,percent_business:Sh(u/g*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){const{notificationCenter:s,OuterEvent:{MESSAGE_RECEIVED:r}}=this._core;s.unSubscribeOuterEvent(r,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(wh).forEach(s=>{this._lastCycleStats.set(s,new Map),this._currentCycleStats.set(s,new Map)})}_onMessageReceived(s){const{data:r=[]}=s;r.forEach(g=>{this.addMessageSequence(g)})}_transferCycleDataOptimized(s){const r=this._currentCycleStats.get(s);if(!r)return;const g=new Map;r.forEach((u,E)=>{const f=u.dirty?[...u.sortedSequences].sort((D,v)=>D-v):u.sortedSequences;g.set(E,{sortedSequences:f,minSeq:u.minSeq,maxSeq:u.maxSeq,dirty:!1})}),this._lastCycleStats.set(s,g),this._currentCycleStats.set(s,new Map)}_getReceivedMessageSpecifiedKey(s){const{OuterConstant:{CONV_GROUP:r,GRP_AVCHATROOM:g}}=this._core;if(s.conversationType===r&&s?._onlineOnlyFlag!==!0){const{groupStore:u}=this._core.appStore,E=u.getGroup(s.to);if(!E)return null;const{type:f}=E;return f===g?ZQ:wC}}_insertToLastCycle(s,r){r.dirty&&(r.sortedSequences.sort((u,E)=>u-E),r.dirty=!1);const g=this._findInsertPos(r.sortedSequences,s);r.sortedSequences.splice(g,0,s),r.minSeq=Math.min(r.minSeq,s),r.maxSeq=Math.max(r.maxSeq,s)}_findInsertPos(s,r){let g=0,u=s.length-1;for(;g<=u;){const E=Math.floor((g+u)/2);if(s[E]===r)return E;s[E]0&&(this._totalDelay+=g,this._totalCount++,g<=1?this._countLessThan1s++:g<=3&&this._countLessThan3s++)}getStatResult(){if(this._totalCount===0)return null;const s={total_count:this._totalCount,success_count_business:this._countLessThan1s,success_count_platform:this._countLessThan3s,percent_business:this._calculatePercentage(this._countLessThan1s,this._totalCount),percent_platform:this._calculatePercentage(this._countLessThan3s,this._totalCount),average_value:this._calculateAverageDelay(this._totalCount)};return this.reset(),s}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){const{notificationCenter:s,OuterEvent:{MESSAGE_RECEIVED:r}}=this._core;s.unSubscribeOuterEvent(r,this._onMessageReceived,this),this.reset()}_onMessageReceived(s){const{data:r=[]}=s,{OuterConstant:{MSG_GRP_TIP:g,MSG_GRP_SYS_NOTICE:u}}=this._core,E=[g,u];r.forEach(f=>{!E.includes(f.type)&&f.clientTime>0&&this.addMessageDelay(f.clientTime)})}_calculateAverageDelay(s){return s===0?0:Sh(this._totalDelay/s,1)}_calculatePercentage(s,r){return Sh(s/r*100,2)}},pR=new class{init(s){this.core=s}},iN=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(s){this._core=s;const{helper:r,notificationCenter:g,InnerEvent:{QUALITY_STAT:u,LOGOUT:E,DESTROY:f},constants:{WORKFLOW_NAME:D,WORKFLOW_STEP:v}}=s;pR.init(s),XQ.init(s),$Q.init(s),Ap.init(s),r.registerWorkflowStep(D.SYNC_SERVER_INFO_AFTER_LOGIN,v.QUALITY_REPORT,this.handleLoginSuccess,this),g.subscribeInnerEvent(u,this._handleQualityStat,this),g.subscribeInnerEvent(E,this._reset,this),g.subscribeInnerEvent(f,this._dispose,this)}handleLoginSuccess(){const{store:s,helper:r,utils:{isUndefined:g}}=this._core,u=s.get("cloudConfig")||{},{q_rpt_interval:E}=u,f=g(E)?12e4:Number(E);r.taskScheduler.addTask({id:Af,intervalMs:f,callback:this.report,context:this})}report(){this._wholePeriod=!0;const s=[...SB.map(r=>{const g=this._buildQualityReportItem(r);return g?Object.assign(Object.assign({},g),{report_index:this._reportIndex,whole_period:this._wholePeriod}):null}).filter(Boolean),...this._pendingReports];this._pendingReports=[],this._needSkipReport()||this._uploadQualityReports(s)}_handleQualityStat(s){const{constants:{QUALITY_METRICS:r}}=this._core,{label:g,data:u}=s;g===r.MESSAGE_SEND_SUCCESS_RATE&&XQ.dispatchSendStats(u)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){const{store:s,utils:r}=this._core,g=s.get("cloudConfig")||{},u=s.get("instance")||{},{sdkAppId:E}=u,{q_rpt_sdkappid_bl:f=[]}=g;if(!r.isEmpty(f))return f.split(",").map(D=>Number(D)).includes(E)}_isTinyIDInWhitelist(){const{store:s,utils:r}=this._core,g=s.get("cloudConfig")||{},u=s.get("login")||{},E=Number(u.tinyID),{q_rpt_tinyid_wl:f=[]}=g;if(!r.isEmpty(f))return f.split(",").includes(E)}_buildQualityReportItem(s){const r=this._getStatResultByKey(s);if(r===null)return null;const g={quality_type:tN[s],timestamp:Date.now(),network_type:HD.ONLINE,extension:""};return Object.assign(Object.assign({},g),r)}_getStatResultByKey(s){switch(s){case vh:return Ap.getStatResult();case fB:case Mh:case Rh:case yB:case DB:return XQ.getStatResult(s);case wC:case zQ:case ZQ:return $Q.getStatResult(s);default:return null}}_uploadQualityReports(s){return mA(this,void 0,void 0,function*(){try{const r={header:this._core.common.getCommonHead(),quality:s};yield function(g){const{common:u,channel:E}=pR.core,f="imopenstat.tim_web_report_v2",D=u.generateSSOLogProtocolData({servcmd:f,data:g}),v=`${D.head.seq}${f}`;return E.sendPacket(D,{requestId:v})}(r),this._reportIndex++,this._wholePeriod=!1}catch(r){console.warn("doReport failed. error:",r),this._pendingReports=this._pendingReports.concat(s),this._cacheFailedLogs()}})}_cacheFailedLogs(){const s=this._pendingReports,r=`${BR}._cacheFailedLogs`;let g=[...this._failedLogsCache.get(VD)||[],...s];g.length>10&&(g=g.slice(g.length-10),console.log(`${r} logs overflow, keeping last 10 items`)),this._failedLogsCache.set(VD,g),console.log(`${r} count: ${g.length}`),this._pendingReports=[]}_reset(){const{helper:s}=this._core;s.taskScheduler.removeTask(Af)}_dispose(){const{notificationCenter:s,InnerEvent:{QUALITY_STAT:r,LOGOUT:g,DESTROY:u}}=this._core;s.unSubscribeInnerEvent(r,this._handleQualityStat,this),s.unSubscribeInnerEvent(g,this._reset,this),s.unSubscribeInnerEvent(u,this._dispose,this),this._reset(),Ap.dispose(),$Q.dispose()}};const hl=new class{init(s){this.core=s}};function mR(s){return mA(this,void 0,void 0,function*(){var r;const{message:g,user:u,appStore:E,constants:{OuterConstant:f}}=hl.core,D=E.conversationStore.getConversationMap();if(D.has(s)){const N=(r=D.get(s))===null||r===void 0?void 0:r.userProfile;if(N&&s.startsWith(f.CONV_C2C)){const{avatar:P,nick:W}=N;hl.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:P,latestNick:W,isSentByMe:!1})}}const{data:v}=(yield u.userProfile.getMyProfile())||{};if(v){const{avatar:N,nick:P}=v;g.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:N,latestNick:P,isSentByMe:!0})}})}function fR(s){return mA(this,void 0,void 0,function*(){const r=s.map(g=>g.revoker);try{const g=yield function(u){return mA(this,void 0,void 0,function*(){var E,f;const D=yield(E=hl.core.user.userProfile)===null||E===void 0?void 0:E.getUserProfile({userIDList:u});return D?.data?(f=D.data)===null||f===void 0?void 0:f.reduce((v,{userID:N,nick:P,avatar:W})=>(v[N]={nick:P||"",avatar:W||""},v),{}):null})}(r);g&&s.forEach(u=>{const{revoker:E}=u;g[E]&&(u.revokerInfo.nick=g[E].nick||"",u.revokerInfo.avatar=g[E].avatar||"",u.revokerInfo.userID=E)})}catch(g){console.debug(g)}})}const qD=1,yR=2,_h=20,ep=2500,DR=1,Th=300;function tp(s){return mA(this,void 0,void 0,function*(){var r,g;const{appStore:u,utils:{isEmpty:E},common:{getCurrentUserID:f},notificationCenter:D,OuterEvent:v,OuterConstant:{CONV_C2C:N}}=hl.core,{messageList:P,conversationID:W}=s,nA=u.conversationStore.getConversationMap();let EA=(r=nA.get(W))===null||r===void 0?void 0:r.peerReadTime;if(!EA){const kA=W.replace(N,""),VA=yield function(LA){return mA(this,void 0,void 0,function*(){const SA={To_Account:LA};return hl.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:SA})})}([kA]);if(VA){const{ReadTime:LA}=VA;EA=LA?.[0],nA.has(W)&&(nA.get(W).peerReadTime=EA)}}if(nA.has(W)){const kA=(g=nA.get(W))===null||g===void 0?void 0:g.lastMessage;E(kA)||kA.fromAccount===f()&&kA.lastTime<=EA&&!kA.isPeerRead&&(kA.isPeerRead=!0,u.conversationStore.updateConversation(W,{lastMessage:kA}))}const wA=[];P.forEach(kA=>{kA.time<=EA&&!kA.isPeerRead&&kA.flow==="out"&&(kA.isPeerRead=!0,wA.push(kA))}),wA.length>0&&D.emitOuterEvent(v.MESSAGE_READ_BY_PEER,{name:v.MESSAGE_READ_BY_PEER,data:wA})})}var SR=new class{init(s){this._core=s,s.helper.registerApi({apiName:"getMessageList",context:this}),s.helper.registerApi({apiName:"getMessageListHopping",context:this}),s.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(s){return mA(this,void 0,void 0,function*(){try{const{message:r,OuterConstant:{Direction:g,CONV_C2C:u,CONV_GROUP:E},InnerEvent:{HISTORY_MESSAGE_FETCHED:f},notificationCenter:D}=this._core,{conversationID:v,nextReqMessageID:N}=s,P=_h;if(v==="@TIM#SYSTEM")return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const W=this._getAvailableLocalMessagesCount({conversationID:v,nextReqMessageID:N});if(this._needFetchHistoryMessageList({conversationID:v,availableLocalMessagesCount:W,targetCount:P})){let nA=null;if(v.startsWith(E)?nA=yield r.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:v,sequence:Number(N),count:P,direction:g.FORWARD,shouldMarkCompleted:!0}):v.startsWith(u)&&(nA=yield r.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:v,messageID:N,count:P,direction:g.FORWARD,shouldMarkCompleted:!0})),nA){const{nextReqMessageIDFromServer:EA,hasNoMoreHistoryMessage:wA,messageList:kA}=nA,VA=r.messageDataHandler.prependLocalMessageList({messageList:kA,conversationID:v});(function(Ee){const{appStore:Ie,message:Li,OuterConstant:Ui}=hl.core,Yt=Ie.conversationStore.getConversation(Ee),Oi=Li.messageDataHandler.getLocalMessageList(Ee);if(!Yt||Oi.length===0||Ee===Ui.CONV_SYSTEM)return;const Bn=[];for(let Mt=0;MtFA.isRevoked).length;Re=Bn.length-Yt.unreadCount-Mt}else Re=Bn.length-Yt.unreadCount;for(let Mt=0;MtEe.isRevoked);yield fR(SA),D.emitInnerEvent(f,VA);const PA={nextReqMessageID:wA?"":String(EA),messageList:LA,isCompleted:wA},zA=LA.map(Ee=>Ee.sequence);return{code:0,data:PA,successLog:{message:`conversationID: ${v} nextReqMessageID: ${N} availableLocalMessagesCount: ${W} sequenceList: ${JSON.stringify(zA)}`}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:v,nextReqMessageID:N,count:P}),successLog:{message:`conversationID: ${v} nextReqMessageID: ${N} availableLocalMessagesCount: ${W}}`}}}catch(r){const{code:g,message:u}=r||{};throw new this._core.helper.ChatError({code:g,message:u,moreMessage:`options: ${this._core.utils.safeStringify(s)}`})}})}getMessageListHopping(s){return mA(this,void 0,void 0,function*(){var r,g;const{OuterConstant:{Direction:u,CONV_C2C:E,CONV_GROUP:f},utils:{safeStringify:D}}=this._core,{conversationID:v,sequence:N,time:P,direction:W=u.FORWARD}=s,{utils:{isEmpty:nA},message:EA,notificationCenter:wA,InnerEvent:{HISTORY_MESSAGE_FETCHED:kA}}=this._core;if(![u.BACKWARD,u.FORWARD].includes(W))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${D(s)}`});let{count:VA=_h}=s;VA=VA>_h?_h:VA;let LA=null;if(v.startsWith(f)){if(LA=yield EA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:v,sequence:N,count:VA,direction:W}),LA){const{nextReqMessageIDFromServer:SA,hasNoMoreHistoryMessage:PA,messageList:zA,invisibleSequenceList:Ee}=LA;if(this._core.message.messageDataHandler.storeSparseMessageList(zA),wA.emitInnerEvent(kA,zA),W===u.FORWARD){const Ie=PA&&SA<1;return{code:0,data:{messageList:zA,isCompleted:Ie,nextMessageSeq:Ie?"":SA}}}if(W===u.BACKWARD){if(nA(zA)&&nA(Ee))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const Ie=((r=zA?.[zA.length-1])===null||r===void 0?void 0:r.sequence)||0,Li=((g=Ee?.[Ee.length-1])===null||g===void 0?void 0:g.sequence)||0;return{code:0,data:{messageList:zA.filter(Ui=>Ui.sequence>=N),isCompleted:!PA,nextMessageSeq:PA?Math.max(Ie,Li)+1:""}}}return{code:0,data:LA}}}else if(v.startsWith(E)&&(LA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:v,count:VA+1,time:P,direction:W}),LA)){const{messageList:SA,lastMessageTime:PA,hasNoMoreHistoryMessage:zA}=LA;return wA.emitInnerEvent(kA,SA),zA||(W===u.FORWARD?SA.shift():SA.pop()),EA.messageDataHandler.storeSparseMessageList(SA),yield tp({messageList:SA,conversationID:v}),{code:0,data:{messageList:SA,isCompleted:zA,nextMessageTime:zA?"":PA}}}})}clearHistoryMessage(s){return mA(this,void 0,void 0,function*(){var r;const{appStore:g,common:{ChatError:u,getCurrentUserID:E},OuterConstant:{CONV_C2C:f,CONV_GROUP:D},apiMap:v,message:N}=this._core,P=g.conversationStore.getConversation(s);if(!P)throw new u({code:ep});const W={fromAccount:E()},{type:nA}=P;nA===f?(W.type=qD,W.toAccount=s.replace(f,"")):nA===D&&(W.type=yR,W.toGroupID=s.replace(D,""));try{return yield(r=v?.setMessageRead)===null||r===void 0?void 0:r.call(v,{conversationID:s}),(yield function(wA){return mA(this,void 0,void 0,function*(){const{fromAccount:kA,type:VA,toAccount:LA,toGroupID:SA}=wA,PA={From_Account:kA,Type:VA,To_Account:LA,ToGroupid:SA};return hl.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:PA})})}(W))&&(N.messageDataHandler.deleteConversationMessageList(s),N.messageHistory.completedHistoryConversations.delete(s),N.messageHistory.clearHistoryMessageListFetchAnchors(s),this._updateConversationLastMessage(s)),{code:0,data:{conversationID:s},successLog:{message:`convID:${s}`}}}catch(EA){const{errorCode:wA}=EA;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:wA,moreMessage:`convID:${s}`})}})}_updateConversationLastMessage(s){const{appStore:r}=this._core;r.conversationStore.updateConversation(s,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:s,nextReqMessageID:r}){const{OuterConstant:{CONV_C2C:g,CONV_GROUP:u}}=this._core,E=this._core.message.messageDataHandler.getLocalMessageList(s),{length:f}=E;if(!r)return f;let D=-1;return s?.startsWith(g)?D=E.findIndex(v=>v.ID===r):s?.startsWith(u)&&(D=E.findIndex(v=>r.includes("-")?v.ID===r:String(v.sequence)===r)),D===-1?0:D}_needFetchHistoryMessageList({conversationID:s,availableLocalMessagesCount:r,targetCount:g}){const{message:u}=this._core;return rr.startsWith(E)?EA.ID===g:String(EA.sequence)===g),W=nA>u?nA-u:0,N=nA):W=v>u?v-u:0,P.messageList=D.slice(W,nA),P.isCompleted=N<=u&&f.messageHistory.completedHistoryConversations.has(r),P.isCompleted?P.nextReqMessageID="":P.nextReqMessageID=this._generateNextReqMessageID({conversationID:r,targetIndex:W}),r.startsWith(E)&&(yield mR(r),yield tp({messageList:P.messageList,conversationID:r})),P})}_generateNextReqMessageID({conversationID:s,targetIndex:r}){const g=this._core.message.messageDataHandler.getLocalMessageList(s);return s.startsWith("C2C")?g[r].ID:String(g[r].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}},vB=new class{constructor(){this._lastMessageSequenceMapOnDisconnect=new Map,this._lastMessageTimeMapOnDisconnect=new Map}init(s){this._core=s;const{common:{workflowManager:r},constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:u,InnerEvent:E}}=s;r.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,u.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),r.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,u.C2C_HISTORY_MESSAGE_RECOVER,this._syncC2COfflineMessage,this),s.notificationCenter.subscribeInnerEvent(E.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncGroupOfflineMessage(s){const{conversationList:r}=s?.result||{},{OuterConstant:g,utils:{isArray:u}}=this._core;if(u(r)){const E=r.filter(f=>f.type===g.CONV_GROUP&&f.groupProfile.type!==g.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(E)}}_recoverGroupHistoryMessage(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r}=this._core,g=[],u=[];return yield Promise.all(s?.map(E=>mA(this,void 0,void 0,function*(){const{groupProfile:{groupID:f}={},lastMessage:{lastSequence:D}={}}=E,v=`${r.CONV_GROUP}${f}`;let N=this._getLocalLastMessageSequence(v);this._shouldRecoverHistory({localLastMessageSequence:N,serverLastMessageSequence:D})&&(yield this._recoverGroupHistoryForConversation({conversationID:v,localLastMessageSequence:N,serverLastMessageSequence:D,groupTipList:u})),g.push(v.replace(r.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:g,groupTipList:u}})}_recoverGroupHistoryForConversation(s){return mA(this,arguments,void 0,function*({conversationID:r,localLastMessageSequence:g,serverLastMessageSequence:u,groupTipList:E}){try{const{utils:{isArray:f,isObject:D,isEmpty:v},OuterEvent:N,OuterConstant:P,notificationCenter:W,message:nA,appStore:EA,common:{getMessagePreviewText:wA,buildLastMessage:kA}}=this._core,VA=u-g,LA=Math.min(20,VA),SA={},PA=yield nA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:r,sequence:g+LA,direction:P.Direction.FORWARD,count:LA}),{nextReqMessageIDFromServer:zA,hasNoMoreHistoryMessage:Ee,messageList:Ie,serverGroupTipList:Li}=PA;f(Li)&&E.push(...Li);const Ui=Ee&&zA<0,Yt=[];if(f(Ie)&&(Ie.forEach(Oi=>{nA.messageReceiver.groupMessageReceiver.updateMessageProfile(Oi),Oi.from===P.CONV_SYSTEM&&(Oi.isSystemMessage=!1),nA.messageDataHandler.storeConversationMessage(Oi)&&!v(Oi.payload)&&(Yt.push(Oi),Oi._isExcludedFromLastMessage||(SA.lastMessage=kA(Oi)))}),Yt.length>0&&W.emitOuterEvent(N.MESSAGE_RECEIVED,{name:N.MESSAGE_RECEIVED,data:Yt})),!Ui&&Ie.length>0){const Oi=Ie[Ie.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:r,localLastMessageSequence:Oi,serverLastMessageSequence:u,groupTipList:E})}D(SA.lastMessage)&&(SA.lastMessage.messageForShow=wA(SA.lastMessage.type,SA.lastMessage.payload),EA.conversationStore.updateConversation(r,SA))}catch(f){this._core.ssoLog.error("_recoverGroupHistoryForConversation",`Recovery failed for conversation:${r}`,{error:f})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:s}=this._core,r=s.messageDataHandler.getContinuousMessagesByConversation();for(const[g,u]of r){const E=Array.from(u.values());if(E?.length>0){const f=E[E.length-1];g.startsWith("C2C")?this._lastMessageTimeMapOnDisconnect.set(g,f.time):g.startsWith("GROUP")&&this._lastMessageSequenceMapOnDisconnect.set(g,f.sequence)}}}_getLocalLastMessageSequence(s){const{message:r}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(s))return this._lastMessageSequenceMapOnDisconnect.get(s);const g=r.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.sequence}_shouldRecoverHistory(s){const{localLastMessageSequence:r,serverLastMessageSequence:g}=s;if(typeof r!="number"||typeof g!="number")return!1;const u=g-r;return g!==0&&r>0&&u>=DR&&u{f.type===g.CONV_C2C&&E.push(f)}),this._recoverC2CHistoryMessage(E)}}_recoverC2CHistoryMessage(s){return mA(this,void 0,void 0,function*(){yield Promise.all(s?.map(r=>mA(this,void 0,void 0,function*(){const{conversationID:g,lastMessage:{lastTime:u}={}}=r,E=this._getLocalLastMessageTime(g);this._shouldRecoverC2CHistory({localLastMessageTime:E,serverLastMessageTime:u})&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:E,serverLastMessageTime:u}))})))})}_shouldRecoverC2CHistory(s){const{localLastMessageTime:r,serverLastMessageTime:g}=s,u=g-r;return r>0&&u>=1&&u<=600}_recoverHistoryForC2CConversation(s){return mA(this,void 0,void 0,function*(){var r;const{conversationID:g,localLastMessageTime:u,serverLastMessageTime:E}=s,{utils:{isArray:f,isObject:D,isEmpty:v,safeStringify:N},OuterEvent:P,OuterConstant:W,notificationCenter:nA,message:EA,appStore:wA,common:{getMessagePreviewText:kA,buildLastMessage:VA}}=this._core;try{const LA={},SA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:g,direction:W.Direction.BACKWARD,time:u,count:20});if(v(SA))return;const{hasNoMoreHistoryMessage:PA,messageList:zA}=SA,Ee=[];f(zA)&&(zA.forEach(Li=>{EA.messageDataHandler.storeConversationMessage(Li)&&!v(Li.payload)&&(Ee.push(Li),Li._isExcludedFromLastMessage||(LA.lastMessage=VA(Li)))}),Ee.length>0&&nA.emitOuterEvent(P.MESSAGE_RECEIVED,{name:P.MESSAGE_RECEIVED,data:Ee}));const Ie=(r=zA[zA.length-1])===null||r===void 0?void 0:r.time;!PA&&Ie>E&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:Ie,serverLastMessageTime:E})),D(LA.lastMessage)&&(LA.lastMessage.messageForShow=kA(LA.lastMessage.type,LA.lastMessage.payload),wA.conversationStore.updateConversation(g,LA))}catch(LA){this._core.ssoLog.error("_recoverHistoryForC2CConversation",`Recovery failed for conversation:${g} error: ${N(LA)}`)}})}_getLocalLastMessageTime(s){const{message:r}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(s))return this._lastMessageTimeMapOnDisconnect.get(s);const g=r.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},MB=new class{constructor(){this.name="HistoryMessage"}install(s){this._core=s,hl.init(s),SR.init(s),vB.init(s),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this.dispose,this),vB.dispose()}_reset(){vB.reset()}},KD=new class{init(s){this.core=s}},_C=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(s){const{helper:{registerExperimentalAPI:r}}=s;this._core=s,r("reportModalView",this),r("reportTUIFeatureUsage",this),r("reportRoomEngineEvent",this)}reportModalView(s){const{ssoLog:r,utils:{safeStringify:g,isString:u}}=this._core;try{if(!u(s))throw new Error("reportModalView data is not a string");r.createSSOLogData({method:"reportModalView",message:s,eventType:30}).end(!0)}catch(E){r.debug(`reportModalView Report failed: ${g(E)}`)}}reportTUIFeatureUsage(s){const{ssoLog:r,utils:{safeStringify:g,isEmpty:u}}=this._core,{atomicStoreID:E}=s;try{u(E)||this._reportedAtomicStoreIDs.has(E)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${s.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:E}),this._reportedAtomicStoreIDs.add(E))}catch(f){r.debug(`reportTUIFeatureUsage Report failed: ${g(f)}`)}}reportRoomEngineEvent(s){const{utils:{safeStringify:r},ssoLog:g}=this._core;try{g.debug(`reportRoomEngineEvent Report: ${r(s)}`);const{eventId:u,eventCode:E,eventResult:f,eventMessage:D,moreMessage:v,extensionMessage:N}=s;g.createSSOLogData({method:N,code:u,message:D,eventType:30,costTime:E,uiPlatform:f,moreMessage:v}).end(!0)}catch(u){g.debug(`reportRoomEngineEvent Report failed: ${r(u)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},ip=new class{constructor(){this.name="DataReport"}install(s){this._core=s;const{notificationCenter:r,InnerEvent:{LOGOUT:g,DESTROY:u}}=s;KD.init(s),_C.init(s),r.subscribeInnerEvent(g,this._reset,this),r.subscribeInnerEvent(u,this._dispose,this)}_reset(){_C.reset()}_dispose(){const{notificationCenter:s,InnerEvent:{LOGOUT:r,DESTROY:g}}=this._core;s.unSubscribeInnerEvent(r,this._reset,this),s.unSubscribeInnerEvent(g,this._dispose,this),_C.dispose()}};let ef=Cr.STANDARD,RB=[];ef=Cr.STANDARD,RB=[Ih,dC,CC,hC,kc,iN,MB,ip,YE,Ni,er,WT,jm,YD,tu];function wB(s,r){const{operationType:g,memberInfoList:u,operatorInfo:E}=s||{};let f={};if(tn(u)?tn(E)||(f=E):g!==kg.JOINED&&g!==kg.KICKED&&g!==kg.ADMIN_SET&&g!==kg.ADMIN_CANCELED||(f=Object.assign({},u[0])),!tn(f)){const{nick:D="",avatar:v=""}=f;r.nick=D,r.avatar=v}}const op=s=>({lastTime:s?.time||s?.lastTime||0,lastSequence:s?.sequence||s?.lastSequence||0,fromAccount:s?.from||s?.fromAccount||"",messageForShow:il(s?.type,s?.payload),payload:s?.payload||null,type:s?.type||"",isRevoked:s?.isRevoked||!1,cloudCustomData:s?.cloudCustomData||"",onlineOnlyFlag:s?._onlineOnlyFlag||!1,nick:s?.nick||"",nameCard:s?.nameCard||"",version:s?.version||0,isPeerRead:s?.isPeerRead||!1,revoker:s?.revoker||null});var np=Object.freeze({__proto__:null,ChatError:hn,WorkflowManager:Pn,buildAndSendPacket:ug,buildLastMessage:op,get builtInPlugins(){return RB},checkBusinessCapabilityBits:us,deepMerge:Bd,getCurrentUserID:ar,getErrorMessage:dn,getMessagePreviewText:il,isC2CConv:s=>c(s)&&s.slice(0,3)===Pa.CONV_C2C,isCommunity:ea,isGroupConv:s=>c(s)&&s.slice(0,5)===Pa.CONV_GROUP,isInternational:kl,isTopic:tl,isUnlimitedAVChatRoom:function(){var s;return!!(!((s=Se.store.get("instance"))===null||s===void 0)&&s.unlimitedAVChatRoom)},liteChatInstanceMap:fa,registerInterceptor:Gc,registerValidateConfig:el,requireAuth:dd,get sdkEdition(){return ef},setGroupTipsUserInfo:wB,t:Uu,updateGroupAtInfo:(s,r)=>{const{CONV_AT_ME:g,CONV_AT_ALL:u,CONV_AT_ALL_AT_ME:E}=Po;if(function(v,N){const{CONV_AT_ME:P,CONV_AT_ALL:W,CONV_AT_ALL_AT_ME:nA}=Po,{groupID:EA,sequence:wA}=v;let kA=!1;return ea({groupID:EA})&&N.forEach(VA=>{VA.messageSequence===wA&&(VA.atTypeArray.includes(P)&&v.groupAtType.includes(W)&&(VA.atTypeArray=[nA]),VA.atTypeArray.includes(W)&&v.groupAtType.includes(P)&&(VA.atTypeArray=[nA],VA.__random=v.__random,VA.__sequence=v.__sequence),kA=!0)}),kA}(s,r))return;let f=[...s.groupAtType];f.includes(g)&&f.includes(u)&&(f=[E]);const D={from:s.from,groupID:s.groupID,topicID:s.topicID,messageSequence:s.sequence,atTypeArray:f,__random:s.__random,__sequence:s.__sequence};r.push(D)},validateAndExecute:wr,validateParameters:hI});class Iu{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return Iu._instance||(Iu._instance=new Iu),Iu._instance}static setInstance(r){Iu._instance=r}installBuiltInPlugin(r){r&&this._installPlugin(r,this._builtInPlugins)}installExternalPlugin(r){r&&this._installPlugin(r,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(r,g){let u=[];u=C(r)?r:[r];const E=u.findIndex(D=>D?.name==="AVChatRoom"),f=E>-1?u.splice(E,1):[];u.forEach(D=>{this._isPluginInstalled(D.name)||(D&&Tg(D.install)?(g.add(D.name),Tg(D.getInstalledSubPlugins)?(f?.forEach(v=>g.add(v?.name)),D.install(vr.getInstance().exposeApiForPlugin(),f)):D.install(vr.getInstance().exposeApiForPlugin()),Tg(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):Tg(D)?(g.add(D.name),D(vr.getInstance().exposeApiForPlugin()),Tg(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(r){return this._builtInPlugins.has(r)||this._externalPlugins.has(r)}_isLoggedIn(){var r;return((r=Se.store.get("login"))===null||r===void 0?void 0:r.isLoggedIn)===!0}}var _B=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(s){return this._conversationMap.get(s)}updateConversation(s,r,g){const{emit:u=!0,needSort:E=!1}=g||{},f=this._conversationMap.get(s);f&&!tn(r)&&(Object.keys(r).forEach(D=>{f[D]=r[D]}),u&&Se.notificationCenter.emitInnerEvent(lo.CONVERSATION_UPDATED,{needSort:E}))}deleteConversation(s){this._conversationMap.has(s)&&(this._conversationMap.delete(s),Se.notificationCenter.emitInnerEvent(lo.CONVERSATION_UPDATED))}},sp=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(s){return this._groupMap.get(s)}updateGroup(s,r){const g=this._groupMap.get(s);g&&!tn(r)&&Object.keys(r).forEach(u=>{g[u]=r[u]})}},rp=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,r,g){var u;const{operation:E,updateUnreadCount:f=!0}=g,D=vo(g,["operation","updateUnreadCount"]),v=[];for(const N of r){const P=(u=this._messagesByConversation.get(s))===null||u===void 0?void 0:u.get(N);if(!P)return!1;Object.keys(D).forEach(W=>{P[W]=D[W]}),v.push(P)}return this._emitMessageStoreOperationEvent(E,{conversationID:s,messageList:v,updateUnreadCount:f}),v}getMessagesByConversation(s){var r;return[...((r=this._messagesByConversation.get(s))===null||r===void 0?void 0:r.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(s,r){const{conversationID:g}=r;tl(g)?Se.notificationCenter.emitInnerEvent(Nu[s],r):Se.notificationCenter.emitInnerEvent(s,r)}},uc=new class{constructor(){this.userProfileMap=new Map,this.friendMap=new Map}getUserProfileMap(){return this.userProfileMap}getFriendMap(){return this.friendMap}getUserProfile(s){return this.userProfileMap.get(s)}getFriend(s){return this.friendMap.get(s)}},jD=Object.freeze({__proto__:null,conversationStore:_B,groupStore:sp,messageStore:rp,userStore:uc});class vr{static getInstance(){return vr._instance||(vr._instance=new vr),vr._instance}static setInstance(r){vr._instance=r}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:Se.notificationCenter.subscribeOuterEvent.bind(Se.notificationCenter),off:Se.notificationCenter.unSubscribeOuterEvent.bind(Se.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:Iu.getInstance().installExternalPlugin.bind(Iu.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(r){Se.ssoLog.debug("registerPlugin",r)}statKeyFeatureUsage(r){Se.ssoLog.debug("statTUIKeyFeatures",r)}setLogLevel(r){Se.ssoLog.debug("setLogLevel",r),Se.ssoLog.setLogLevel(r)}setApplicationID(r){Se.store.set("instance",{applicationID:r})}getApiMap(){return this._apiMap}setApiMap(r){this._apiMap=r}registerApi(r){const{common:{timeManager:g},utils:{safeStringify:u}}=Se,{apiName:E,context:f,methodName:D=E,matcher:v}=r;this._apiHandlersMap[E]||(this._apiHandlersMap[E]=[]),this._apiHandlersMap[E].push({context:f,methodName:D,matcher:v}),this._apiMap[E]&&this._apiHandlersMap[E].length!==1||(this._apiMap[E]=(...N)=>{const P=g.getServerTimeMs();let W=0;E==="login"&&(W=4),zI.includes(E)&&Se.ssoLog.debug(E,`${E} start params: ${u(N)}`),wr(D,N);const nA=this._apiHandlersMap[E];for(const EA of nA)if(!EA.matcher||EA.matcher(N))try{const wA=EA.context[EA.methodName].bind(EA.context)(...N);return this._isPromiseLike(wA)?this._handleAsyncResult(wA,E,W,P):(this._reportApiSuccessLog({result:wA,apiName:E,eventType:W,startTime:P}),wA)}catch(wA){throw Se.ssoLog.error(E,`${E} fail ${wA?.message||wA?.errorMessage})`,{error:wA,costTime:g.getServerTimeMs()-P,eventType:W,method:E}),wA}})}registerExperimentalAPI(r,g,u){const E=u||r;this._experimentalApiMap[r]=g[E].bind(g)}destroy(){return mA(this,void 0,void 0,function*(){var r,g;try{!((r=Se.store.get("login"))===null||r===void 0)&&r.isLogin&&(yield this._apiMap.logout()),Se.notificationCenter.emitInnerEvent(lo.DESTROY)}catch(u){console.debug("destroy error: ",u)}finally{Se.notificationCenter.emitOuterEvent(Rr.SDK_DESTROY,{SDKAppID:(g=Se.store.get("instance"))===null||g===void 0?void 0:g.sdkAppId}),fa.clear(),Iu.getInstance().clear(),Pn.getInstance().destroy(),Se.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:lo,InnerEventSubType:Se.notificationCenter.InnerEventSubType,OuterEvent:Rr,OuterConstant:Po,SignalingEvent:Xc,helper:Object.assign(Object.assign(Object.assign({},Se.utils),Se.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Gc,registerValidateConfig:el,checkBusinessCapabilityBits:us,registerWorkflowStep:Pn.getInstance().registerWorkflowStep.bind(Pn.getInstance()),ChatError:hn}),apiMap:this._apiMap},Se),{constants:Object.assign(Object.assign({},Ag),Se.constants),common:Object.assign(Object.assign(Object.assign({},np),Se.common),{workflowManager:Pn.getInstance()}),utils:Se.utils,appStore:jD})}callExperimentalAPI(r,g){return Se.ssoLog.debug(`callExperimentalAPI.${r} start params: ${Se.utils.safeStringify(g)}`),this._experimentalApiMap[r]?this._experimentalApiMap[r](g):(Se.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${r} not found, params: ${Se.utils.safeStringify(g)}`),Promise.reject(new hn({code:ma.INVALID_OPERATION})))}_isPromiseLike(r){return r!==null&&typeof r=="object"&&typeof r.then=="function"}_handleAsyncResult(r,g,u,E){return r.then(f=>(this._reportApiSuccessLog({result:f,apiName:g,eventType:u,startTime:E}),f)).catch(f=>{throw Se.ssoLog.error(g,`${g} fail ${f?.message||f?.errorMessage})`,{error:f,costTime:Se.common.timeManager.getServerTimeMs()-E,eventType:u,method:g,startTime:E}),f})}_reportApiSuccessLog(r){let{result:g,apiName:u,startTime:E,eventType:f}=r;const{timeManager:D}=Se.common,{successLog:{message:v,moreMessage:N}={message:"",moreMessage:""}}=g||{},P=D.getServerTimeMs();u==="login"&&(E+=D.getTimeOffsetWithServer()),zI.includes(u)&&Se.ssoLog.info(u,`${u} success ${v} ${N}`,{costTime:P-E,eventType:f,message:v,moreMessage:N,startTime:E}),g?.successLog&&delete g.successLog}}class vR{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:r,store:g}=Se;g.set("login",{isReady:!1}),vr.getInstance().registerApi({apiName:"login",context:this}),vr.getInstance().registerApi({apiName:"logout",context:this}),vr.getInstance().registerApi({apiName:"getLoginUser",context:this}),vr.getInstance().registerApi({apiName:"isReady",context:this}),vr.getInstance().registerApi({apiName:"getServerTime",context:this}),vr.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),r.subscribeInnerEvent(lo.RECONNECTED,this._reLogin,this),Se.notificationCenter.subscribeInnerEvent(lo.DESTROY,this._dispose,this)}login(r){return mA(this,void 0,void 0,function*(){var g;const{sdkEdition:u}=Se.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new hn({functionName:"login",code:ma.REPEAT_LOGIN});const E=yield this._performLogin(r);this._validateAfterLogin(E),this._handleLoginSuccess(E),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const f=(g=Se.channel.getSocketAdapter())===null||g===void 0?void 0:g.getId(),{appId:D,href:v}=Se.store.get("instance")||{},{instanceID:N,customStatus:P}=E||{};return{code:0,data:E,successLog:{message:u,moreMessage:`socketID:${f} instanceID:${N} customStatus:${P} href: ${v} appId: ${D}`}}}catch(E){const{errorCode:f}=E;f!==ma.REPEAT_LOGIN&&(this._latestLoginAt=0);const D=new hn({functionName:"login",code:f});throw console.error(D),D}})}_reLogin(){return mA(this,void 0,void 0,function*(){var r;try{if(!this._isLoginIn())return;const g=yield Lu(this._customLoginInfo);if(g){const{instanceID:u,customStatus:E}=g;Se.store.set("login",{statusInstanceId:u}),Pn.getInstance().executeWorkflow(jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:E,statusType:ME.USER_STATUS_ONLINE});const f=(r=Se.channel.getSocketAdapter())===null||r===void 0?void 0:r.getId();Se.ssoLog.info("reLogin",`socketId:${f} instanceId:${u}`)}}catch(g){console.warn(g)}})}logout(){return mA(this,arguments,void 0,function*(r=ca.USER_INITIATED){const{ssoLog:g}=Se;g.debug("logout",`logout start logoutReason: ${r}`);try{yield this._performLogout(r),g.info("logout","logout success"),Se.ssoLog.uploadSSOLogData()}catch(u){const{errorCode:E}=u;throw new hn({functionName:"logout",code:E})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?ar():""}isReady(){var r;return(r=Se.store.get("login"))===null||r===void 0?void 0:r.isReady}setCustomLoginInfo(r=""){this._customLoginInfo=r}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),Pn.getInstance().reset(),Se.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:r}=Se.common;return r.getServerTimeMs()}_updateAndEmitSDKReady(){Se.store.set("login",{isReady:!0}),setTimeout(()=>{Se.notificationCenter.emitOuterEvent(Rr.SDK_READY,{name:Rr.SDK_READY})},1)}_updateAndEmitSDKNotReady(){Se.store.set("login",{isReady:!1}),Se.notificationCenter.emitOuterEvent(Rr.SDK_NOT_READY,{name:Rr.SDK_NOT_READY})}_validateAfterLogin(r){const g="login";if(!r)throw new hn({functionName:g,message:"login response is empty"});const{tinyID:u,a2Key:E}=r||{};if(!u)throw new hn({functionName:g,code:ma.NO_TINYID});if(!E)throw new hn({functionName:g,code:ma.NO_A2KEY})}_createRepeatLoginResponse(){var r;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:dn({code:"RepeatLogin",replacement1:(r=Se.store.get("login"))===null||r===void 0?void 0:r.userId}),repeatLogin:!0}}}_performLogin(r){return mA(this,void 0,void 0,function*(){const{userID:g,userSig:u}=r;return Se.store.set("login",{userId:g,userSig:u}),this._latestLoginAt=Date.now(),Lu(this._customLoginInfo)})}_ensureAsyncComplete(){return mA(this,void 0,void 0,function*(){yield new Promise(r=>{setTimeout(()=>r(null),1)})})}_handleLoginSuccess(r){const{timeManager:g}=Se.common,{helloInterval:u,timeStamp:E,customStatus:f,purchaseBits:D}=r,v=1e3*E;g.calculateTimeOffsetWithServer(this._latestLoginAt,v),this._helloInterval=u||120,this._updateLoginStore(r),Se.user.userStatus.setCustomStatus(f),Pn.getInstance().executeWorkflow(jt.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:D}),Se.common.taskScheduler.addTask({id:Ug,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(r){return function(g){return mA(this,void 0,void 0,function*(){const{logoutReason:u}=g,E="im_open_status.wslogout",f=Se.common.generateProtocolData({servcmd:E,data:{wslogout_type:u,isWebUniapp:0}}),D=`${f.head.seq}${E}`;return yield Se.channel.sendPacket(f,{requestId:D})})}({logoutReason:r})}_updateLoginStore(r){const{a2Key:g,tinyID:u,instanceID:E,authKey:f}=r;Se.store.set("login",{a2Key:g,tinyID:u,statusInstanceId:E,authKey:f,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return mA(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const r="im_open_status.wshello",g=Se.common.generateProtocolData({servcmd:r,data:{isWebUniapp:0}}),u=`${g.head.seq}${r}`;return Se.channel.sendPacket(g,{requestId:u})}()}catch(r){Se.ssoLog.warn("_sendOnlinePresenceRequest",` error:${r.message}`)}})}_isLoginIn(){var r;return((r=Se.store.get("login"))===null||r===void 0?void 0:r.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){Se.common.taskScheduler.removeTask(Ug),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",Se.store.clear("login"),Se.store.set("login",{isReady:!1}),Se.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:r}=Se;r.unSubscribeInnerEvent(lo.RECONNECTED,this._reLogin,this),r.unSubscribeInnerEvent(lo.DESTROY,this._dispose,this)}}const MR={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},oN={logout:!0};class Nh{constructor(){this.loginAction=new vR,this.kickedOutHandler=new ku,this.loginAction.init(),this.kickedOutHandler.init(),el({auth:oN,params:MR})}}var Zr,eE,WE;(function(s){s.CONV_C2C="C2C",s.CONV_GROUP="GROUP",s.CONV_TOPIC="TOPIC",s.CONV_SYSTEM="@TIM#SYSTEM"})(Zr||(Zr={})),function(s){s.MSG_PRIORITY_HIGH="High",s.MSG_PRIORITY_NORMAL="Normal",s.MSG_PRIORITY_LOW="Low",s.MSG_PRIORITY_LOWEST="Lowest"}(eE||(eE={})),function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_IMAGE="TIMImageElem",s.MSG_AUDIO="TIMSoundElem",s.MSG_FILE="TIMFileElem",s.MSG_VIDEO="TIMVideoFileElem",s.MSG_GRP_TIP="TIMGroupTipElem",s.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",s.MSG_MERGER="TIMRelayElem"}(WE||(WE={}));const WD={1:eE.MSG_PRIORITY_HIGH,2:eE.MSG_PRIORITY_NORMAL,3:eE.MSG_PRIORITY_LOW,4:eE.MSG_PRIORITY_LOWEST},zD=0,RR=1;var tE;(function(s){s.IN="in",s.OUT="out"})(tE||(tE={}));const wR=2,ap={};function uu(s){if(!s)return 0;if(ap[s]===void 0){const r=new Date,g=`3${r.getHours()}`.slice(-2),u=`0${r.getMinutes()}`.slice(-2),E=`0${r.getSeconds()}`.slice(-2);ap[s]=parseInt([g,u,E,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${ap[s]}`)}else ap[s]+=1;return ap[s]}class zE{constructor(r){this.ID="",this.random=0,this.sequence=0,this.nameCard="",this.isRead=!1,this.isPeerRead=!1,this.isDeleted=!1,this.isResend=!1,this.hasRiskContent=!1,this._onlineOnlyFlag=!1,this.atUserList=[],this._groupAtInfoList=[],this.isBroadcastMessage=!1,this.priority=eE.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:g=Se.common.timeManager.getServerTimeSeconds()||0,senderTinyID:u,currentUser:E,needReadReceipt:f,isSupportExtension:D,customModerationConfigurationId:v,to:N,from:P,nick:W="",avatar:nA="",time:EA,messageControlInfo:wA,tinyID:kA,cloudCustomData:VA="",messageLifeTime:LA,messageVersion:SA=0,conversationType:PA,sequence:zA,checkResult:Ee=0,isPlaceMessage:Ie=0,messageFlagBits:Li,receiverList:Ui,isSystemMessage:Yt=!1,status:Oi=qr.SUCCESS,revokeReason:Bn="",conversationSubType:Re,clientSequence:Mt,protocol:FA="JSON",revokerInfo:ci={userID:"",nick:"",avatar:""},readReceiptInfo:xn={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:Pi,groupProfile:Vr,atUserList:ji,flow:Qr,isRead:Ut=!1,priority:Ft=eE.MSG_PRIORITY_NORMAL,onlineOnlyFlag:oE=!1,nameCard:hs="",quoteInfo:Do}=r;var Bl;this.clientTime=g,this.senderTinyID=u||kA,this.needReadReceipt=f===!0||f===1,this.isSupportExtension=D===!0||D===1,this._cmConfigID=v,this.to=N,this.nick=W,this.avatar=nA,this.protocol=FA,this.random=Pi===void 0?(Bl=Bl||99999999,Math.round(Math.random()*Bl)):Pi,this.time=EA||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!wA?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!wA?.excludedFromUnreadCount,this.isModified=!!SA,this.cloudCustomData=VA,this.messageLifeTime=LA,this.from=P||null,this.sequence=zA||0,this.conversationType=PA||Zr.CONV_C2C,this.hasRiskContent=Ee>1,this.version=SA,this.isPlaceMessage=Ie,this.isRevoked=Ie===2||Li===8,this.isSystemMessage=Yt,this.readReceiptInfo=xn,this.revokeReason=Bn,this.revokerInfo=ci,this._receiverList=Ui,this.conversationSubType=Re,this.revoker=ci?.revoker||"",this.clientSequence=Mt||zA||0,this.status=Oi,this.atUserList=ji||[],this.flow=Qr,this.isRead=Ut,this.priority=Ft,this._onlineOnlyFlag=oE,this.nameCard=hs,this.quoteInfo=Do,this.reInitialize(E),this._initC2CReadReceiptInfo(r),this._extractGroupInfo(Vr)}getElements(){return this._elements}isOnlineMessage(){return this.messageLifeTime===0}setElement(r){Array.isArray(r)?this._elements=r:this._elements=[r],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(r=>r.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(r){this._relayFlag=r}validateBeforeSend(){var r,g,u;return this._relayFlag?{isValid:!0}:((r=this._elements)===null||r===void 0?void 0:r.length)>0?(u=(g=this._elements[0])===null||g===void 0?void 0:g.validateBeforeSend)===null||u===void 0?void 0:u.call(g):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(r){const{readReceiptSentByPeer:g,timestamp:u=0}=r;this.conversationType===Zr.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=g===1,this.readReceiptInfo.timestamp=u)}_extractGroupInfo(r){if(!r)return;const{From_AccountNick:g,From_AccountHeadurl:u,MsgFrom_AccountExtraInfo:E,GroupType:f}=r,{NameCard:D}=E||{};typeof g=="string"&&(this.nick=g),typeof u=="string"&&(this.avatar=u),typeof D=="string"&&(this.nameCard=D),this.conversationSubType=f}reInitialize(r){r===this.from&&(this.isRead=!0),this._initSequence(r),this._concatConversationID(r),this.generateMessageID()}_concatConversationID(r){let g="";const u=this.conversationType;u!==Zr.CONV_SYSTEM?(g=u===Zr.CONV_C2C?r===this.from?this.to:this.from:this.to,this.conversationID=g?`${u}${g}`:null):this.conversationID=Zr.CONV_SYSTEM}_initSequence(r){this.clientSequence===0&&r&&(this.clientSequence=uu(r)),this.sequence===0&&this.conversationType===Zr.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Zr.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(r){this.isRead=r}}class Gd{static parseServerPushElement(r){const{MsgContent:g={}}=r,{Data:u,Ext:E,Desc:f}=g;return new Gd({data:u,description:f,extension:E})}constructor(r){this.type=WE.MSG_CUSTOM;const{data:g="",description:u="",extension:E=""}=r;this.content={data:g,description:u,extension:E}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{data:E,description:f,extension:D}=u;return{MsgType:this.type,MsgContent:{Data:E,Ext:D,Desc:f}}}validateBeforeSend(){const{isEmpty:r}=Se.utils,g=[this.content.data,this.content.description,this.content.extension].some(u=>!r(u));return{isValid:g,error:g?null:{message:"content can not be empty"}}}}class bd{static parseServerPushElement(r){const{MsgContent:g={Text:""}}=r,{Text:u}=g;return new bd({text:u})}constructor(r){this.type=Gg.MSG_TEXT,this.content={text:r.text||""}}validateBeforeSend(){var r,g;return((g=(r=this.content)===null||r===void 0?void 0:r.text)===null||g===void 0?void 0:g.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{text:E}=u;return{MsgType:this.type,MsgContent:{Text:E}}}}var tf=new class{constructor(){this._elementClassMap={[WE.MSG_CUSTOM]:Gd,[WE.MSG_TEXT]:bd}}init(){vr.getInstance().registerApi({apiName:"createCustomMessage",context:this}),vr.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(s,r){var g;(g=r).prototype!==void 0&&"constructor"in g.prototype&&(this._elementClassMap[s]=r)}getElementClass(s){return this._elementClassMap[s]}createMessage(s){const{from:r,flow:g=tE.OUT}=s,{userId:u}=Se.store.get("login")||{};this._isSendByCurrentInstance({from:r,flow:g,currentUser:u})?this._updateWithSenderInfo(s):this._isMultiEndpointSyncMessage({from:r,flow:g,currentUser:u})&&(s.flow=tE.OUT);const E=Object.assign(Object.assign({},s),{currentUser:u});return new zE(E)}createCustomMessage(s){const r=ar(),g=this.createMessage(Object.assign(Object.assign({},s),{from:r})),u=this._elementClassMap[WE.MSG_CUSTOM];if(!g)return null;if(u){const E=new u(s.payload);g.setElement(E)}return g}createTextMessage(s){var r;if(!s)return null;const g=typeof s.payload=="string"?s.payload:((r=s?.payload)===null||r===void 0?void 0:r.text)||"",u=new bd({text:g}),E=ar(),f=Se.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return f.setElement(u),f}_updateWithSenderInfo(s){var r,g;const{nick:u,avatar:E,conversationType:f,to:D}=s,{userId:v,tinyID:N}=Se.store.get("login")||{},P=uc.getUserProfile(v);return s.nick=u||P?.nick||"",s.avatar=E||P?.avatar||"",s.tinyID=s.tinyID||N||"",s.from=v,s.status=qr.UNSENT,s.flow=tE.OUT,f===Pa.CONV_GROUP&&(s.nameCard=(g=(r=sp.getGroup(D))===null||r===void 0?void 0:r.selfInfo)===null||g===void 0?void 0:g.nameCard),s}_isMultiEndpointSyncMessage(s){const{from:r,flow:g,currentUser:u}=s;return r===u&&g===tE.IN}_isSendByCurrentInstance(s){const{from:r,flow:g,currentUser:u}=s;return r===u&&g===tE.OUT}};const _R={PushFlag:0,Title:"",Desc:"",Ext:"",ApnsInfo:{Sound:"",BadgeMode:0,IsVoipPush:void 0,Image:"",InterruptionLevel:"active",ContentAvailable:0},AndroidInfo:{Sound:"",XiaoMiChannelID:"",OPPOChannelID:"",GoogleChannelID:"",VIVOClassification:1,VIVOCategory:"",HuaWeiCategory:"",OPPOCategory:"",HuaWeiImage:"",HonorImage:"",GoogleImage:"",HonorImportance:"",MeizuNotifyType:void 0}},kd={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},ZD={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function TR(s,r){return Object.keys(r).forEach(g=>{const{range:u,defaultValue:E}=r[g];s[g]=u.includes(s[g])?s[g]:E}),s}function gp(s){const r=s.lastIndexOf(".");return r===-1?s:s.slice(0,r)}function NR(s){const{androidInfo:r={},androidOPPOChannelID:g=""}=s,u=r.OPPOChannelID||g,E=TR(r,kd),{sound:f="",FCMChannelID:D=""}=E,v=vo(E,["sound","FCMChannelID"]);return Object.assign(Object.assign({},v),{Sound:gp(f),OPPOChannelID:u,GoogleChannelID:D})}function GR(s){const{apnsInfo:r={},ignoreIOSBadge:g=!1,disableVoipPush:u}=s,E=TR(r,ZD),{ignoreIOSBadge:f,disableVoipPush:D,enableIOSBackgroundNotification:v}=E,N=vo(E,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),P=f===!0||g===!0?1:0;let W;return n(u)||(W=u===!1?1:0),n(D)||(W=D===!1?1:0),Object.assign(Object.assign({},N),{BadgeMode:P,IsVoipPush:W,ContentAvailable:v?1:0})}function XD(s){return Se.utils.isPlainObject(s)?{PushFlag:s.disablePush===!0?1:0,Title:s.title||"",Desc:s.description||"",Ext:s.extension||"",ApnsInfo:GR(s),AndroidInfo:NR(s)}:_R}function of(s){const{From_AccountHeadurl:r,From_AccountNick:g,IsNeedReadReceipt:u,IsPeerRead:E,IsSyncMsg:f,MsgBody:D,MsgClientTime:v,MsgLifeTime:N,MsgRandom:P,MsgSeq:W,MsgTimeStamp:nA,SendMsgControl:EA,SupportMessageExtension:wA,TinyId:kA,MsgCheckResult:VA,CloudCustomData:LA,MsgVersion:SA,MsgFlagBits:PA,RevokerInfo:zA,InnerSdkCustomData:Ee}=s;let Ie,{From_Account:Li,To_Account:Ui}=s;if(f===1){const Yt=Ui;Ui=Li,Li=Yt}if(zA){const{Reason:Yt,Revoker_Account:Oi,Revoker_FromUin:Bn}=zA;Ie={reason:Yt,revoker:Oi,revokerFromUin:Bn,userID:Oi}}return{from:Li,avatar:r,nick:g,needReadReceipt:u===1,isSyncMessage:f,clientTime:v,messageLifeTime:N,random:P,sequence:W,time:nA,messageControlInfo:{excludedFromLastMessage:EA?.NoLastMsg===1,excludedFromUnreadCount:EA?.NoUnread===1},isSupportExtension:wA,to:Ui,tinyID:kA,checkResult:VA,cloudCustomData:LA,revokerInfo:Ie,messageVersion:SA,messageFlagBits:PA,readReceiptSentByPeer:E,elements:TC(D),onlineOnlyFlag:N===0,quoteInfo:cp(Ee)}}function nf(s){const{From_Account:r,MsgBody:g,MsgClientTime:u,MsgRandom:E,MsgSeq:f,MsgTimeStamp:D,To_Account:v,MsgVersion:N,CloudCustomData:P,MsgCheckResult:W}=s;return{from:r,clientTime:u,random:E,sequence:f,time:D,to:v,elements:TC(g),messageVersion:N,cloudCustomData:P,checkResult:W}}function $D(s){const{ClientSeq:r,From_Account:g,GroupInfo:u,MsgBody:E,MsgClientTime:f,MsgRandom:D,MsgSeq:v,MsgTimeStamp:N,SendMsgControl:P,SupportMessageExtension:W,TinyId:nA,CloudCustomData:EA,MsgVersion:wA,MsgCheckResult:kA,NeedReadReceipt:VA,IsPlaceMsg:LA,RevokerInfo:SA,GroupAtInfo:PA,OnlineOnlyFlag:zA,InnerSdkCustomData:Ee}=s;let Ie,Li=eE.MSG_PRIORITY_NORMAL;if(Object.keys(WD).includes(String(s.MsgPriority))&&(Li=WD[s.MsgPriority]),SA){const{Reason:Yt,Revoker_Account:Oi,Revoker_FromUin:Bn}=SA;Ie={reason:Yt,revoker:Oi,revokerFromUin:Bn,userID:Oi}}const Ui=function(Yt){const Oi=[];return Array.isArray(Yt)&&Yt.forEach(Bn=>{Bn.GroupAtAllFlag===zD?Oi.push(Bn.GroupAt_Account):Bn.GroupAtAllFlag===RR&&Oi.push(Po.MSG_AT_ALL)}),Oi}(PA);return{clientSequence:r,from:g,groupProfile:u,clientTime:f,priority:Li,random:D,sequence:v,time:N,messageControlInfo:{excludedFromLastMessage:P?.NoLastMsg===1,excludedFromUnreadCount:P?.NoUnread===1},isSupportExtension:W,tinyID:nA,cloudCustomData:EA,messageVersion:wA,checkResult:kA,needReadReceipt:VA,isPlaceMessage:LA,revokerInfo:Ie,atUserList:Ui,elements:TC(E),to:nN(s),onlineOnlyFlag:zA===1,quoteInfo:cp(Ee)}}function nN(s){const{utils:{isEmpty:r},constants:{IS_TOPIC_MESSAGE:g}}=Se,{ToGroupId:u,GroupInfo:{MillionGroupFlag:E=0,TopicId:f}={}}=s;return E!==g||r(f)?u:f}function TC(s){if(!s)return null;if(Array.isArray(s))return s.map(g=>{const u=Se.message.messageFactory.getElementClass(g.MsgType);return u?.parseServerPushElement(g)});const r=Se.message.messageFactory.getElementClass(s.MsgType);return r?.parseServerPushElement(s)}function AS(s){const{From_Account:r,MsgBody:g,MsgClientTime:u,MsgRandom:E,MsgSeq:f,MsgTimeStamp:D,GroupId:v,TopicId:N,MsgVersion:P,CloudCustomData:W,MsgCheckResult:nA}=s;return{from:r,clientTime:u,random:E,sequence:f,time:D,groupID:v,topicID:N,elements:TC(g),messageVersion:P,cloudCustomData:W,checkResult:nA}}function cp(s){const{utils:{isString:r,safeStringify:g},ssoLog:u}=Se;if(!r(s))return null;try{const{messageID:E,messageTime:f,messageSequence:D}=JSON.parse(s).businessQuote;return{msgID:E,messageTime:f,messageSequence:D}}catch(E){return u.debug("_parseServerQuoteInfo",g(E)),null}}function lp({conversationUpdateFields:s,message:r}){const{conversationID:g,conversationType:u,conversationSubType:E,flow:f,_isExcludedFromUnreadCount:D,_isExcludedFromLastMessage:v}=r,N=v?"":op(r),P=!D&&f===tE.IN;s.has(g)?(s.get(g).lastMessage=N,P&&s.get(g).unreadCount++):s.set(g,{conversationID:g,type:u,subType:E,unreadCount:P?1:0,lastMessage:N})}function TB(s){return s.filter(r=>{const g=!tn(r?._elements),u=r?.isPlaceMessage===1;return g||Se.ssoLog.error("emptyMessageBody",`from:${r.from} to:${r.to} sequence:${r.sequence}`),g&&!u})}function NB(s){const{messageDataHandler:r}=Se.message;return!r.isInMessageList(s)&&!r.isMessageSentByCurrentInstance(s)}var bR=Object.freeze({__proto__:null,autoIncrementIndex:uu,createAndroidPushInfo:NR,createApnsPushInfo:GR,createOfflinePushInfo:XD,filterValidMessages:TB,getAndroidSoundName:gp,parseServerGroupMessage:$D,parseServerPushC2CModifyMessage:nf,parseServerPushGroupModifyMessage:AS,parseServerPushMessage:of,parseServerPushMessageElement:TC,shouldStoreMessage:NB,updateConversationFields:lp});const{isPlainObject:kR}=Se.utils;function Ip(s,r={}){const{onlineUserOnly:g,messageControlInfo:u}=r;let{offlinePushInfo:E}=r;s.conversationType===Zr.CONV_C2C&&g===!0&&(E?E.disablePush=!0:E={disablePush:!0});let f="";typeof s.cloudCustomData=="string"&&s.cloudCustomData.length>0&&(f=s.cloudCustomData);const D=[];if(u&&kR(u)){const{excludedFromUnreadCount:v,excludedFromLastMessage:N,excludedFromContentModeration:P}=u;v===!0&&D.push("NoUnread"),N===!0&&D.push("NoLastMsg"),P===!0&&D.push("NoMsgCheck")}return{onlineUserOnly:g,cloudCustomData:f,messageControlInfo:D,offlinePushInfo:E}}function eS(s){const{webhookInfo:{disableCloudMessagePreHook:r=!1,disableCloudMessagePostHook:g=!1}={}}=s||{};if(!r&&!g)return;const u=[];return r&&u.push("ForbidBeforeSendMsgCallback"),g&&u.push("ForbidAfterSendMsgCallback"),u}function Gh(s,r){return mA(this,void 0,void 0,function*(){const g=s.conversationType===Zr.CONV_GROUP?function(E,f){var D;const v=Ip(E,f),{onlineUserOnly:N,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:nA}=v,EA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));let wA;return C(E._receiverList)&&E._receiverList.length>0&&(wA=E._receiverList,E._receiverList.length>50&&(wA=E._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:(D=Se.store.get("login"))===null||D===void 0?void 0:D.userId,GroupId:E.to,MsgBody:EA,CloudCustomData:P,Random:E.random,MsgPriority:E.priority,ClientSeq:E.clientSequence,GroupAtInfo:E._groupAtInfoList,OnlineOnlyFlag:N?1:0,MsgClientTime:E.clientTime,OfflinePushInfo:XD(nA),SendMsgControl:N?void 0:W,NeedReadReceipt:E.needReadReceipt===!0?1:0,To_Account:wA,SupportMessageExtension:E.isSupportExtension===!0?1:0,IsRelayMsg:E._relayFlag===!0?1:0,CustomModerationConfigID:E._cmConfigID,ForbidCallbackControl:eS(f),InnerSdkCustomData:bB(E)}}}(s,r):function(E,f){var D;const v=Ip(E,f),{onlineUserOnly:N,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:nA}=v,EA=N===!0?0:void 0,wA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:(D=Se.store.get("login"))===null||D===void 0?void 0:D.userId,To_Account:E.to,MsgBody:wA,CloudCustomData:P,MsgSeq:E.sequence,MsgRandom:E.random,MsgLifeTime:EA,From_AccountNick:E.nick,From_AccountHeadurl:E.avatar,SendMsgControl:EA!==0?W:void 0,MsgClientTime:E.clientTime,IsNeedReadReceipt:E.needReadReceipt===!0?1:0,SupportMessageExtension:E.isSupportExtension===!0?1:0,IsRelayMsg:E._relayFlag===!0?1:0,CustomModerationConfigID:E._cmConfigID,OfflinePushInfo:XD(nA),ForbidCallbackControl:eS(f),InnerSdkCustomData:bB(E)}}}(s,r),u=yield ug(g);return u?{time:u.MsgTime,messageDropReason:u.MsgDropReason,sequence:u.MsgSeq}:null})}function bh(s){return mA(this,void 0,void 0,function*(){const{from:r,to:g,version:u=0,sequence:E,random:f,time:D,type:v,cloudCustomData:N}=s,P={From_Account:r,To_Account:g,MsgVersion:u,MsgSeq:E,MsgRandom:f,MsgTime:D,MsgType:v,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:N},W=yield ug({servcmd:"openim.modify_c2c_msg",data:P});if(W){const{MsgBody:nA,MsgVersion:EA,CloudCustomData:wA}=W;return{elements:TC(nA),messageVersion:EA,cloudCustomData:wA}}})}function GB(s){return mA(this,void 0,void 0,function*(){const{to:r,version:g=0,sequence:u,cloudCustomData:E}=s,f={GroupId:r,MsgVersion:g,MsgSeq:u,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:E},D=yield ug({servcmd:"openim.modify_group_msg",data:f});if(D){const{MsgBody:v,MsgVersion:N,CloudCustomData:P}=D;return{elements:TC(v),messageVersion:N,cloudCustomData:P}}})}function kh(s){return mA(this,void 0,void 0,function*(){const{groupID:r,count:g,messageSequence:u,messageSequenceList:E,getType:f}=s,D={GroupId:r,ReqMsgNumber:g,WithRecalledMsg:1,Version:1,GetType:f};return u&&(D.ReqMsgSeq=u),C(E)&&E.length>0&&(D.ReqMsgSeqList=E),yield ug({servcmd:"group_open_http_svc.group_msg_get",data:D})})}function sf(s){return mA(this,void 0,void 0,function*(){const{peerAccount:r,count:g,lastMessageTime:u,messageKey:E,direction:f}=s;return ug({servcmd:"openim.getroammsg",data:{Peer_Account:r,MaxCnt:g,WithRecalledMsg:1,LastMsgTime:u,MsgKey:E,GetDirection:f}})})}function bB(s){if(Se.utils.isObject(s.quoteInfo)){const{msgID:r,messageSequence:g,messageTime:u}=s.quoteInfo;return JSON.stringify({businessQuote:{messageID:r,messageSequence:g,messageTime:u}})}}var tS=Object.freeze({__proto__:null,createMessagePackOptions:Ip,generateForbidCallbackControl:eS,getC2CRoamingMessagesByAnchor:sf,getGroupRoamingMessagesByAnchor:kh,getRoamingMessages:function(s){return mA(this,void 0,void 0,function*(){const{peerAccount:r,count:g,lastMessageTime:u,messageKey:E}=s;return(yield ug({servcmd:"openim.getroammsg",data:{Peer_Account:r,MaxCnt:g||15,LastMsgTime:u||0,MsgKey:E,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:bh,modifyGroupMessage:GB,sendMessage:Gh});const{isPlainObject:sN}=Se.utils,{MSG_AUDIO:iS,MSG_FILE:oS,MSG_IMAGE:LR,MSG_VIDEO:UR,MSG_MERGER:FR}=Po;class rf{constructor(){this._sendProtocolMap=new Map}init(){vr.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:r=>![iS,oS,LR,UR,FR].includes(r[0].type)})}registerSendProtocol(r,g,u){this._sendProtocolMap.set(r,g.bind(u))}sendMessage(r,g){return mA(this,void 0,void 0,function*(){const{TOTAL_COUNT:u,SEND_COST:E,SUCCESS_COUNT:f,FAILED_COUNT:D}=hr;if(!(r instanceof zE))throw new hn({code:ma.MSG_INSTANCE_REQUIRED});const v=r.validateBeforeSend();if(!v.isValid){const{code:W,message:nA=""}=v.error||{};throw new hn({code:W,message:nA})}this._reportMessageSendQuality({name:u,message:r});let N=!1;const{messageDataHandler:P}=Se.message||{};try{const{messageControlInfo:W}=g||{};let nA=null;P.addRandomOfSentMessage(r.random);const EA=Date.now(),wA=this._getSendProtocol(r);if(r.conversationType===Zr.CONV_C2C?(N=g?.onlineUserOnly===!0,nA=yield wA(r,g)):r.conversationType===Zr.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(r),nA=yield wA(r,g)),nA){const{messageDropReason:kA,sequence:VA,time:LA}=nA;if(this._updateNickAndAvatarOfSentMessageByMe(r),kA&&this._logRateLimitInfo(r,VA,kA),this._reportMessageSendQuality({name:f,message:r}),this._reportMessageSendQuality({name:E,message:r,startTs:EA}),r.isResend===!0){const SA=P.findMessage(r.ID);SA&&(Se.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${SA.ID}`),P.deleteConversationMessage(SA))}return r.status=qr.SUCCESS,r.time=LA,r.conversationType===Zr.CONV_GROUP&&(r.sequence=VA),N?r._onlineOnlyFlag=!0:(P.storeConversationMessage(r),this._applySentMessageControlInfo(r,W),this._emitOnlineMessageSent(r)),r.type===Gg.MSG_STREAM?{code:0,data:{message:r,streamMessageID:nA.streamMessageID}}:{code:0,data:{message:r}}}}catch(W){r.status=qr.FAIL,P.removeRandomOfSentMessage(r.random);let{errorCode:nA}=W||{},EA=W?.errorInfo||W?.message||"";throw this._hasRiskContent(nA)&&(r.hasRiskContent=!0),N||this._isRejectedByRestApi(nA)||P.storeConversationMessage(r),this._reportMessageSendQuality({name:D,message:r,error:W}),new hn({code:nA,message:EA,data:{message:r},moreMessage:`type:${r.type} from:${r.from} to:${r.to}`})}})}_hasRiskContent(r){return r===80001||r===80004}_isRejectedByRestApi(r){return r>=10100&&r<=10200||r>=120001&&r<=13e4}_emitOnlineMessageSent(r){const g=r._isExcludedFromLastMessage?"":r,{conversationID:u,conversationType:E}=r,f=tl(u)?lo.TOPIC_NEW_MESSAGE:lo.NEW_MESSAGE;Se.notificationCenter.emitInnerEvent(f,{result:{conversationUpdateFieldList:[{conversationID:u,type:E,message:r,lastMessage:g,unreadCount:0}]}})}_applySentMessageControlInfo(r,g){g&&sN(g)&&(g.excludedFromLastMessage===!0&&(r._isExcludedFromLastMessage=!0),g.excludedFromUnreadCount===!0&&(r._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(r,g,u){const E=`from:${r.from} to:${r.to} sequence:${g} messageDropReason:${u}`;Se.ssoLog.warn("messageDropReason",E)}_updateNickAndAvatarOfSentMessageByMe(r){const{messageDataHandler:g}=Se.message||{};let u=!1;const{conversationID:E}=r,f=g.getLatestMsgSentByMe(E);if(f){const{nick:D,avatar:v}=f;D===r.nick&&v===r.avatar||(u=!0),u&&g.updateNickAndAvatarOfSentMessage({conversationID:E,latestNick:r.nick,latestAvatar:r.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(r){return mA(this,void 0,void 0,function*(){var g,u,E;const{to:f,from:D}=r;let v=f,N=sp.getGroup(v);if(ea({groupID:v})&&N?.isSupportTopic)throw new hn({code:ma.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(tl(f)&&([v]=f.split(ga.TOPIC),N=sp.getGroup(v)),!N&&typeof((g=vr.getInstance().getApiMap())===null||g===void 0?void 0:g.getGroupProfile)=="function"){const P=yield vr.getInstance().getApiMap().getGroupProfile({groupID:v});if(((E=(u=P?.data)===null||u===void 0?void 0:u.group)===null||E===void 0?void 0:E.type)===Po.GRP_AVCHATROOM){const W=dn({code:ma.MSG_SEND_FAIL_NOT_IN_AV,replacement1:D,replacement2:v});throw new hn({code:ma.MSG_SEND_FAIL_NOT_IN_AV,message:W})}}return!0})}_reportMessageSendQuality(r){Se.notificationCenter.emitInnerEvent(lo.QUALITY_STAT,{label:dI.MESSAGE_SEND_SUCCESS_RATE,data:r})}_getSendProtocol(r){return this._sendProtocolMap.get(r.type)||Gh}}var rN=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){Se.notificationCenter.subscribeInnerEvent(lo.LOGOUT,this._reset,this),Se.notificationCenter.subscribeInnerEvent(lo.DESTROY,this._dispose,this)}get _messagesByConversation(){return rp.getMessages()}storeConversationMessage(s,r=!1){if(jn)return!0;const{conversationID:g}=s;if(!g||(this._messagesByConversation.has(g)||this._messagesByConversation.set(g,new Map),this._shouldSkipStoreMessage(s,r)))return!1;const u=this._getUniqueIdOfMessage(s);return this._messagesByConversation.get(g).set(u,s),this._updateLatestMessageMap(s),!0}_updateLatestMessageMap(s){const{conversationID:r}=s;s.flow==="out"?this._setLatestMsgSentByMe(r,s):r.startsWith("C2C")&&this._setLatestMsgSentByPeer(r,s)}_shouldSkipStoreMessage(s,r){const g=this._getUniqueIdOfMessage(s),u=this._messagesByConversation.get(s.conversationID);if(u?.has(g)){const E=u?.get(g);if(!r||E?.isModified===!0)return!0}return!1}deleteConversationMessage(s){var r;const{conversationID:g=""}=s,u=this._getUniqueIdOfMessage(s);this._messagesByConversation.has(g)&&((r=this._messagesByConversation.get(g))===null||r===void 0||r.delete(u))}modifyConversationMessage(s,r){var g;if(!this._messagesByConversation.has(s)&&!this._sparseMessagesByConversation.has(s))return{isUpdated:!1,message:null};const u=this._getUniqueIdOfMessage(r),E=this._getMessageFromLocalMessage(s,u);if(E){const{messageVersion:f,elements:D,cloudCustomData:v,checkResult:N=0}=r,P=N>1;if(Se.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${E.version} remoteVersion:${f}`),E.versionE.ID===s)||null,r)break;if(!r){const u=Array.from(this._sparseMessagesByConversation.values());for(const E of u)if(r=E.get(s)||null,r)break}return r}deleteConversationMessageList(s){this._messagesByConversation.has(s)&&(this._messagesByConversation.delete(s),this._latestMessageSentByMeMap.delete(s),this._latestMessageSentByPeerMap.delete(s)),this._sparseMessagesByConversation.has(s)&&this._sparseMessagesByConversation.delete(s)}revokeMessage({conversationID:s,sequence:r,random:g,revoker:u}){const E=this._messagesByConversation.get(s);let f=null;if(E){const D=Array.from(E.values());if(f=this._findMessageBySequenceAndRandom({messageList:D,random:g,sequence:r}),f){const v=this._getUniqueIdOfMessage(f);return rp.updateMessage(s,[v],{isRevoked:!0,revoker:u,operation:_c.revoke}),f}}if(this._sparseMessagesByConversation.has(s)){const D=Array.from(this._sparseMessagesByConversation.get(s).values());if(f=this._findMessageBySequenceAndRandom({messageList:D,random:g,sequence:r}),f)return f.isRevoked=!0,f.revoker=u,f}}_findMessageBySequenceAndRandom({messageList:s,sequence:r,random:g}){for(let u=0;u0){const D=new Map([...E,...f.entries()]);this._messagesByConversation.set(g,D),this._updateLatestMessageSentByMe(g),this._updateLatestMessageSentByPeer(g)}return u}storeSparseMessageList(s){if(s.length===0)return;const{conversationID:r}=s[0],g=s.length;this._sparseMessagesByConversation.has(r)||this._sparseMessagesByConversation.set(r,new Map);const u=this._sparseMessagesByConversation.get(r);for(let E=0;E=0;u--)if(g[u].flow==="out"){this._setLatestMsgSentByMe(s,g[u]);break}}}_updateLatestMessageSentByPeer(s){var r;const g=Array.from(((r=this._messagesByConversation.get(s))===null||r===void 0?void 0:r.values())||[]);if(g.length!==0&&s.startsWith("C2C")){for(let u=g.length-1;u>=0;u--)if(g[u].flow==="in"){this._setLatestMsgSentByPeer(s,g[u]);break}}}_getUniqueIdOfMessage(s){const{from:r,to:g,random:u,sequence:E,time:f}=s;return`${r}-${g}-${u}-${E}-${f}`}_setLatestMsgSentByPeer(s,r){this._latestMessageSentByPeerMap.set(s,r)}_setLatestMsgSentByMe(s,r){this._latestMessageSentByMeMap.set(s,r)}getLatestMsgSentByPeer(s){return this._latestMessageSentByPeerMap.get(s)}getLatestMsgSentByMe(s){return this._latestMessageSentByMeMap.get(s)}addRandomOfSentMessage(s){this._randomOfSentMessageList.add(s)}removeRandomOfSentMessage(s){this._randomOfSentMessageList.delete(s)}updateNickAndAvatarOfSentMessage(s){const{conversationID:r="",latestAvatar:g,latestNick:u,isSentByMe:E=!0}=s,f=this._messagesByConversation.get(r);if(!f)return;const D=Array.from(f.values()),v=E?"out":"in";D.forEach(N=>{const{nick:P,avatar:W,flow:nA}=N;nA===v&&(P!==u&&(N.nick=u),W!==g&&(N.avatar=g))})}isInMessageList(s){var r;const{conversationID:g}=s;if(!g||!this._messagesByConversation.has(g))return!1;const u=this._getUniqueIdOfMessage(s);return(r=this._messagesByConversation.get(g))===null||r===void 0?void 0:r.has(u)}isMessageSentByCurrentInstance(s){const{random:r}=s;return this._randomOfSentMessageList.has(r)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(s){const r=this._messagesByConversation.get(s);return r?[...r.values()]:[]}getSparseMessageList(s){const r=this._sparseMessagesByConversation.get(s);return r?[...r.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),Se.notificationCenter.unSubscribeInnerEvent(lo.LOGOUT,this._reset,this),Se.notificationCenter.unSubscribeInnerEvent(lo.DESTROY,this._dispose,this)}};function af(s,r){const g=_B.getConversation(s);if(g?.lastMessage){const{lastMessage:u}=g,{lastTime:E,lastSequence:f,version:D}=u,{time:v,sequence:N,messageVersion:P,elements:W,cloudCustomData:nA}=r;E===v&&f===N&&D!==P&&(u.type=W[0].type,u.payload=W[0].content,u.messageForShow=il(u.type,u.payload),u.cloudCustomData=nA,u.version=P,_B.updateConversation(s,{lastMessage:u}))}}class OR{init(){vr.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,payload:u,sequence:E,conversationType:f,random:D,time:v,from:N,type:P}=r;if(this._canModifyMessageElement(P)){const W=r?._elements||[];W.length>=1&&(W[0].type=P,W[0].content=u)}try{let W=null,nA=null;if(f===Zr.CONV_C2C?W=yield bh(r):f===Zr.CONV_GROUP&&(W=yield GB(r)),W){let EA=`${f}${g}`;return g===ar()&&f===Zr.CONV_C2C&&(EA=`${f}${N}`),nA={conversationType:f,from:N,to:g,time:v,random:D,sequence:E,elements:W?.elements,cloudCustomData:W?.cloudCustomData,messageVersion:W?.messageVersion,conversationID:EA},this._handleModifyMessageSuccess(nA),{code:0,data:{message:r},successLog:{message:`to:${g}`}}}}catch(W){const{errorCode:nA}=W||{};throw new hn({functionName:"modifyMessage",code:nA,moreMessage:`to:${g}`})}})}_handleModifyMessageSuccess(r){const{conversationID:g}=r,{isUpdated:u,message:E}=Se.message.messageDataHandler.modifyConversationMessage(g,r);u===!0&&Se.notificationCenter.emitOuterEvent(Rr.MESSAGE_MODIFIED,{name:Rr.MESSAGE_MODIFIED,data:[E]}),Se.notificationCenter.emitInnerEvent(lo.MESSAGE_MODIFIED,{conversationID:g,message:E}),af(g,r)}_canModifyMessageElement(r){return[WE.MSG_TEXT,WE.MSG_CUSTOM,WE.MSG_LOCATION,WE.MSG_FACE].includes(r)}}class Lh{init(){const{notificationCenter:r}=Se,{InnerEventSubType:g}=r;Pn.getInstance().registerWorkflowStep(jt.RECEIVE_C2C_NEW_MESSAGE,Xt.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),Pn.getInstance().registerWorkflowStep(jt.RECEIVE_C2C_NEW_MESSAGE,Xt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),Pn.getInstance().registerWorkflowStep(jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Xt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),r.subscribeInnerEvent(lo.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),r.subscribeInnerEvent(lo.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),r.subscribeInnerEvent(lo.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(r){Pn.getInstance().executeWorkflow(jt.RECEIVE_C2C_NEW_MESSAGE,r)}_handleC2CMessagePush(r){const g=r.data||{},{messageDataHandler:u}=Se.message||{},E=[],f=new Map;return g.C2cMsgArray.forEach(D=>{const v=this._generateC2CMessage(D);this._updateMessageProfile(v);let N=v.isModified===1;u.isMessageSentByCurrentInstance(v)?v.isModified=N:N=!1,v._onlineOnlyFlag?u.isMessageSentByCurrentInstance(v)||E.push(v):NB(v)&&(u.storeConversationMessage(v)&&lp({conversationUpdateFields:f,message:v}),u.isMessageSentByCurrentInstance(v)&&!N||E.push(v))}),{conversationUpdateFieldList:[...f.values()],messages:E}}_emitMessageEventsAfterReceiveNewMessage(r){var g;const{messages:u=[]}=((g=r.result)===null||g===void 0?void 0:g[Xt.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(u)}_emitMessageEventsAfterSyncUnreadMessage(r){var g;const{messages:u=[]}=((g=r.result)===null||g===void 0?void 0:g[Xt.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(u)}_emitMessageEvents(r){const g=r?.filter(E=>E?.isModified===!0)||[];g.length>0&&Se.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:g});const u=r?.filter(E=>!E?.isModified);u.length>0&&Se.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:u})}_generateC2CMessage(r){const g=Zr.CONV_C2C,u=of(r),E=Se.message.messageFactory.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:tE.IN})),{elements:f}=u;return E.setElement(f),E}_updateMessageProfile(r){var g;const{messageDataHandler:u}=Se.message||{},E=(g=Se.store.get("login"))===null||g===void 0?void 0:g.userId,{from:f,nick:D,avatar:v,conversationID:N=""}=r;if(f!==E){const P=u.getLatestMsgSentByPeer(N);if(P){const{nick:W,avatar:nA}=P;n(D)||n(v)?(r.nick=c(W)?W:r.nick,r.avatar=c(nA)?nA:r.avatar):D===W&&v===nA||(u.updateNickAndAvatarOfSentMessage({conversationID:N,latestNick:D,latestAvatar:v,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:N,nick:D,avatar:v}))}}else{const P=u.getLatestMsgSentByMe(N);!P||D===P.nick&&v===P.avatar||u.updateNickAndAvatarOfSentMessage({conversationID:N,latestNick:D,latestAvatar:v,isSentByMe:!0})}}_updateConversationUserProfile(r){const{conversationID:g,nick:u,avatar:E}=r,f=_B.getConversation(g),{userProfile:D={}}=f||{};D.avatar===E&&D.nick===u||_B.updateConversation(g,{userProfile:Object.assign(Object.assign({},D),{nick:u,avatar:E})})}_updateMessageListDueToModify(r){const{conversationID:g}=r,{isUpdated:u,message:E}=Se.message.messageDataHandler.modifyConversationMessage(g,r);u===!0&&Se.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),Se.notificationCenter.emitInnerEvent("ModifyMessageSuccess",r),af(g,r)}_handleC2CMessageModify(r){r.C2cMsgModNotifys.forEach(g=>{var u;const E=Zr.CONV_C2C;let f=nf(g);const{to:D,from:v}=f;let N=`${E}${D}`;D===((u=Se.store.get("login"))===null||u===void 0?void 0:u.userId)&&(N=`${E}${v}`),f=Object.assign({conversationType:E,conversationID:N},f),this._updateMessageListDueToModify(f)})}_dispose(){const{notificationCenter:r}=Se,{InnerEventSubType:g}=r;Se.notificationCenter.unSubscribeInnerEvent(lo.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),Se.notificationCenter.unSubscribeInnerEvent(lo.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),Se.notificationCenter.unSubscribeInnerEvent(lo.DESTROY,this._dispose,this)}}class Uh{init(){const{notificationCenter:r}=Se,{InnerEventSubType:g}=r;Pn.getInstance().registerWorkflowStep(jt.RECEIVE_GROUP_NEW_MESSAGE,Xt.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),Pn.getInstance().registerWorkflowStep(jt.RECEIVE_GROUP_NEW_MESSAGE,Xt.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),r.subscribeInnerEvent(lo.MESSAGE_PUSH,g.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),r.subscribeInnerEvent(lo.MESSAGE_PUSH,g.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),r.subscribeInnerEvent(lo.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(r){this._canExecuteReceiverNewMessageWorkFlow(r)&&Pn.getInstance().executeWorkflow(jt.RECEIVE_GROUP_NEW_MESSAGE,r)}_handleGroupMessagePush(r){const g=r.data||{},{messageDataHandler:u}=Se.message,E=[],f=new Map,D=g?.GroupMsgArray;return D?.forEach(v=>{if(v.GroupInfo.NotVisible===1)return;const N=this._generateGroupMessage(v);this.updateMessageProfile(N);let P=N.isModified===1;u.isMessageSentByCurrentInstance(N)?N.isModified=P:P=!1,N._onlineOnlyFlag?u.isMessageSentByCurrentInstance(N)||E.push(N):NB(N)&&u.storeConversationMessage(N)&&(E.push(N),lp({conversationUpdateFields:f,message:N}))}),{conversationUpdateFieldList:[...f.values()],messages:E}}_emitMessageEvents(r){var g;const{messages:u}=((g=r.result)===null||g===void 0?void 0:g[Xt.HANDLE_GROUP_NEW_MESSAGE])||{},E=u?.filter(D=>D?.isModified===!0)||[];E.length>0&&Se.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:E});const f=u?.filter(D=>!D?.isModified)||[];f.length>0&&Se.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:f})}_generateGroupMessage(r){const g=Zr.CONV_GROUP,u=$D(r),E=Se.message.messageFactory.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:tE.IN})),{elements:f}=u;return E.setElement(f),E}updateMessageProfile(r){var g;const{messageDataHandler:u}=Se.message||{},E=(g=Se.store.get("login"))===null||g===void 0?void 0:g.userId,{from:f,nick:D,avatar:v,conversationID:N="",_elements:P}=r;if(f===E){const W=u.getLatestMsgSentByMe(N);!W||D===W.nick&&v===W.avatar||u.updateNickAndAvatarOfSentMessage({conversationID:N,latestNick:D,latestAvatar:v,isSentByMe:!0})}else if(f===Po.CONV_SYSTEM){const{operationType:W,memberInfoList:nA,operatorInfo:EA}=P;let wA={};if(tn(nA)?tn(EA)||(wA=EA):[kg.JOINED,kg.KICKED,kg.ADMIN_SET,kg.ADMIN_CANCELED].includes(W)&&(wA=Object.assign({},nA[0])),!tn(wA)){const{nick:kA="",avatar:VA=""}=wA;r.nick=kA,r.avatar=VA}}}_updateMessageListDueToModify(r){const{conversationID:g}=r,{isUpdated:u,message:E}=Se.message.messageDataHandler.modifyConversationMessage(g,r);u===!0&&Se.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),af(g,r)}_handleGroupMessageModify(r){r.GroupMsgModNotifys.forEach(g=>{const u=Zr.CONV_GROUP;let E=AS(g);const{topicID:f,groupID:D}=E,v=f||D,N=`${u}${v}`;E=Object.assign({conversationType:u,conversationID:N,to:v},E),this._updateMessageListDueToModify(E)})}_dispose(){const{notificationCenter:r}=Se,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:g,GROUP_MESSAGE_MODIFIED:u}}=r;r.unSubscribeInnerEvent(lo.MESSAGE_PUSH,g,this._handleGroupMessagePush,this),r.unSubscribeInnerEvent(lo.MESSAGE_PUSH,u,this._handleGroupMessageModify,this),r.unSubscribeInnerEvent(lo.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(r){var g,u;const{GroupId:E,GroupType:f}=((u=(g=r?.GroupMsgArray)===null||g===void 0?void 0:g[0])===null||u===void 0?void 0:u.GroupInfo)||{},D=f===xa.GRP_AVCHATROOM;return!(!sp.getGroup(E)&&D)}}var nS=new class{constructor(){this.c2cMessageReceiver=new Lh,this.groupMessageReceiver=new Uh}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const PR={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!s.startsWith("C2C")&&!s.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>function(r){var g;return typeof r?.text!="string"||typeof r.text=="string"&&((g=r?.text)===null||g===void 0?void 0:g.length)===0?"payload.text must be a string":!0}(s)}}},aN={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var gN=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(s){return mA(this,void 0,void 0,function*(){try{const{conversationID:r,count:g,direction:u,sequence:E,messageSequenceList:f,shouldMarkCompleted:D=!1,getType:v}=s,N=r.replace(Pa.CONV_GROUP,""),P=[];let W=E;if(u===$c.BACKWARD){if(typeof E!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};W=E+g-1}const nA=yield kh({groupID:N,count:g,messageSequence:W,messageSequenceList:f,getType:v});if(nA){const{RspMsgList:EA=[],NextReqMsgSeq:wA=0,IsFinished:kA,InvisibleMsgSeq:VA}=nA,LA=`groupID:${N} sequence:${E} reqSeq:${W} direction:${u} complete:${kA} nextSequence:${wA} remoteMsgCount:${EA.length} invisibleSequenceList:${VA}`,SA=[];for(let Ee=0;Ee=E),PA&&D&&this.completedHistoryConversations.add(r);const zA=TB(SA);return Se.ssoLog.info("getGroupRoamingMessagesByAnchor",LA),{messageList:zA,invisibleSequenceList:VA,nextReqMessageIDFromServer:wA,hasNoMoreHistoryMessage:PA,serverGroupTipList:P}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};throw new hn({code:g,message:u})}})}clearHistoryMessageListFetchAnchors(s){this._historyMessageListFetchAnchors.delete(s)}isHistoryMessageFetchCompleted(s){return this.completedHistoryConversations.has(s)}_parseMessage(s){var r;const g=Pa.CONV_GROUP;s.Event===4&&(s.MsgBody.MsgType=Po.MSG_GRP_TIP);const u=$D(s),E=tf.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:"in"}));return wB(((r=u.elements)===null||r===void 0?void 0:r.content)||{},E),E.setElement(u.elements),E}getC2CRoamingMessagesByAnchor(s){return mA(this,void 0,void 0,function*(){var r;try{const{conversationID:g,count:u,messageID:E,time:f,direction:D,shouldMarkCompleted:v=!1}=s;let N=f,P="";if(!f){const EA=E?Se.message.messageDataHandler.findMessage(E):null;if(N=EA?.time||0,E&&this._historyMessageListFetchAnchors.has(g)){const wA=this._historyMessageListFetchAnchors.get(g);N=wA.lastMessageTime,P=wA.messageKey}}const W=g.replace(Pa.CONV_C2C,""),nA=yield sf({count:u,lastMessageTime:N,messageKey:P,peerAccount:W,direction:D});if(nA){const{MsgList:EA=[],Complete:wA,MsgKey:kA,LastMsgTime:VA}=nA;this._historyMessageListFetchAnchors.set(g,{messageKey:kA,lastMessageTime:VA});const LA=[];for(let Ee=0;Ee{const{tag:E,value:f}=u;E&&E.indexOf(rS)>-1?g.profileCustomField.push({key:E,value:f}):Ld.has(E)&&(g[Ld.get(E)]=f)}),Object.assign(Object.assign({},gf),g)}parseProfileItem(s=[]){const r=[];return s.forEach(g=>{r.push({tag:g.Tag,value:g.Value})}),r}parseProfileList(s=[]){const r=[];return s.forEach(g=>{r.push({tag:g.Tag,value:g.ValueBytes})}),r}convertParamsToProfile(s){const r=[];return Object.keys(s).forEach(g=>{g!==aS&&r.push({tag:Kl[g.toUpperCase()],value:s[g]})}),s.profileCustomField&&C(s.profileCustomField)&&s.profileCustomField.forEach(g=>{r.push({tag:g.key,value:g.value})}),r}normalizeProfileFields(s){const r={},g=[];return s.forEach(u=>{const{tag:E,value:f}=u;if(E&&E.indexOf(rS)>-1&&g.push({key:E,value:f}),Ld.has(E)&&f!==void 0){const D=Ld.get(E);r[D]=f}}),g.length>0&&(r.profileCustomField=g),r}};const{generateProtocolData:YR}=Se.common;function VR(s){return mA(this,void 0,void 0,function*(){const r="profile.portrait_get_all",g={From_Account:ar(),UserItem:[]};s.forEach(D=>{g.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:D})});const u=YR({servcmd:r,data:g}),E=`${u.head.seq}${r}`,f=yield Se.channel.sendPacket(u,{requestId:E});if(f)return function(D){const{ActionStatus:v,ErrorCode:N,ErrorDisplay:P,ErrorInfo:W,UserProfileItem:nA}=D,EA=[];return nA.map(wA=>{const{To_Account:kA,CustomSequence:VA,ResultCode:LA,ResultInfo:SA,StandardSequence:PA,ProfileItem:zA}=wA,Ee=iE.parseProfileItem(zA);EA.push({userId:kA,customSequence:VA,resultCode:LA,resultInfo:SA,standardSequence:PA,profileItem:Ee})}),{actionStatus:v,errorCode:N,errorDisplay:P,errorInfo:W,userProfile:EA}}(f)})}function ZE(s){return uc.getFriendMap().has(s)}const{isEmpty:gS}=Se.utils;class cf{constructor(){this._strangerProfileMap=new Map}init(){vr.getInstance().registerApi({apiName:"getMyProfile",context:this}),vr.getInstance().registerApi({apiName:"getUserProfile",context:this}),vr.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=iE.createProfile.bind(iE);const{notificationCenter:r}=Se;Pn.getInstance().registerWorkflowStep(jt.SYNC_SERVER_INFO_AFTER_LOGIN,Xt.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),r.subscribeInnerEvent(lo.MESSAGE_PUSH,r.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),r.subscribeInnerEvent(lo.LOGOUT,this._reset,this),r.subscribeInnerEvent(lo.DESTROY,this._dispose,this)}getMyProfile(){return mA(this,void 0,void 0,function*(){try{const r=ar(),g=yield VR([r]);if(g){const u=this._handleProfileFormResponse(g)[0];return uc.getUserProfileMap().set(r,u),{code:0,data:u}}}catch(r){const{errorCode:g,errorInfo:u}=r;throw new hn({functionName:"getMyProfile",code:g,message:u})}})}getUserProfile(r){return mA(this,void 0,void 0,function*(){try{let{userIDList:g}=r;const{userIdListToRequest:u,profileFromCache:E}=this._filterRequestAndCacheUsers(g);if(u.length===0)return{code:0,data:E,successLog:{message:`userIDList.length:${g.length}`}};u.length>xR&&(Se.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),u.length=xR);const{data:f,error:D}=yield this._batchFetchUserProfiles(u),v=u.length,N=f.length,P=v-N;if(E.length===0&&v===P&&!gS(D))throw D;if(C(f))return f.forEach(nA=>{ZE(nA.userID)?uc.getUserProfileMap().set(nA.userID,nA):this._strangerProfileMap.set(nA.userID,nA)}),{code:0,data:f.concat(E),successLog:{message:`getUserProfile query:${v} success:${N} fail:${P} from cache:${E.length}`}}}catch(g){throw new hn(g)}})}getMyProfileCacheThenServer(){return mA(this,void 0,void 0,function*(){const r=ar(),g=uc.getUserProfileMap().has(r);return g?{code:0,data:g}:this.getMyProfile()})}updateMyProfile(r){return mA(this,void 0,void 0,function*(){const g=ar(),u={};for(const f in r)r[f]!==void 0&&(u[f]=r[f]);const E=iE.convertParamsToProfile(u);try{yield function(P){return mA(this,void 0,void 0,function*(){const W="profile.portrait_set",nA=YR({servcmd:W,data:P}),EA=`${nA.head.seq}${W}`,wA=yield Se.channel.sendPacket(nA,{requestId:EA});if(wA){const{ActionStatus:kA,ErrorCode:VA,ErrorDisplay:LA,ErrorInfo:SA}=wA;return{actionStatus:kA,errorCode:VA,errorDisplay:LA,errorInfo:SA}}})}({From_Account:g,ProfileItem:E});const D=uc.getUserProfile(g);let v;v=D?Object.assign(Object.assign({},D),u):iE.createProfile(g,E);const N=!lg(D,v,["lastUpdatedTime"]);return v.lastUpdatedTime=Date.now(),uc.getUserProfileMap().set(g,v),N&&this._emitProfileUpdated(v),{code:0,data:v,successLog:{message:`profileArray: ${Se.utils.safeStringify(E)}`}}}catch(f){const{errorCode:D,errorInfo:v}=f;throw new hn({functionName:"updateMyProfile",code:D,message:v,moreMessage:`params: ${Se.utils.safeStringify(r)}`})}})}updateMyNickAndAvatar(r){return mA(this,void 0,void 0,function*(){const g=ar(),u=Date.now(),E=uc.getUserProfile(g);let f={};f=E?Object.assign(E,r):iE.createProfile(g,r),f.lastUpdatedTime=u,uc.getUserProfileMap().set(g,f)})}_onProfileDataModify(r){const g=function(f){const{Profile_Account:D,PushType:v,ProfileList:N}=f;return{userId:D,pushType:v,profileList:iE.parseProfileList(N)}}(r.ProfileDataMod[0]);if(gS(g))return;const{isProfileUpdated:u,profile:E}=this._handleProfileModified(g);u&&this._emitProfileUpdated(E)}_emitProfileUpdated(r){Se.notificationCenter.emitInnerEvent(lo.PROFILE_UPDATE,{name:lo.PROFILE_UPDATE,data:[r]}),Se.notificationCenter.emitOuterEvent(Rr.PROFILE_UPDATED,{name:Rr.PROFILE_UPDATED,data:[r]}),_B.updateConversation(`C2C${r?.userID}`,{userProfile:r})}_dispose(){const{notificationCenter:r}=Se;r.unSubscribeInnerEvent(lo.LOGOUT,this._reset,this),r.unSubscribeInnerEvent(lo.MESSAGE_PUSH,r.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),r.unSubscribeInnerEvent(lo.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(r){const{userId:g,profileList:u}=r,E=uc.getUserProfile(g);if(!(ar()===g||ZE(g)&&E))return{isProfileUpdated:!1,profile:null};const f=iE.normalizeProfileFields(u),D=Object.keys(f).some(W=>W===aS?this._isCustomFieldChanged(E.profileCustomField,f.profileCustomField):E[W]!==f[W]);if(!D)return{isProfileUpdated:!1,profile:E};const v=Date.now(),N=Object.prototype.hasOwnProperty.call(f,aS)?this._mergeProfileCustomField(E.profileCustomField,f.profileCustomField):E.profileCustomField,P=Object.assign(Object.assign(Object.assign({},E),f),{profileCustomField:N,lastUpdatedTime:v});return uc.getUserProfileMap().set(g,P),{isProfileUpdated:D,profile:P}}_filterRequestAndCacheUsers(r){const g=[],u=[];return r.forEach(E=>{const f=uc.getUserProfileMap().has(E);ZE(E)&&f?u.push(uc.getUserProfile(E)):this._isStrangerAndProfileValid(E)?u.push(this._strangerProfileMap.get(E)):g.push(E)}),{userIdListToRequest:g,profileFromCache:u}}_handleProfileFormResponse(r){const{userProfile:g}=r;if(!Array.isArray(g))return[];const u=g.filter(f=>f.userId!=="@TLS#NOT_FOUND"&&f.userId!==""&&!gS(f.profileItem)),E=Date.now();return u.map(f=>{const D=iE.createProfile(f.userId,f.profileItem);return D.lastUpdatedTime=E,D})}_isStrangerAndProfileValid(r){var g;if(!ZE(r)){const{lastUpdatedTime:u=0}=this._strangerProfileMap.get(r)||{},E=((g=Se.store.get("cloudConfig"))===null||g===void 0?void 0:g.stranger_profile_expiration_time)||6e5;return Date.now()-u<=E}return!1}_chunkUserIDList(r,g){return Array.from({length:Math.ceil(r.length/g)},(u,E)=>r.slice(E*g,(E+1)*g))}_batchFetchUserProfiles(r){return mA(this,void 0,void 0,function*(){const g=[],u=[];let E={};return this._chunkUserIDList(r,100).forEach(f=>{g.push(VR(f))}),(yield Promise.allSettled(g)).forEach(f=>{if(f.status==="fulfilled"){const D=f.value,v=this._handleProfileFormResponse(D);C(v)&&u.push(...v)}else if(f.status==="rejected"){const{code:D,message:v}=f.reason||{};E={errorCode:D,message:v}}}),{data:u,error:E}})}_isCustomFieldChanged(r=[],g=[]){if(!C(g)||g.length===0)return!1;if(!C(r)||r.length===0)return!0;const u=new Map(r.map(E=>[E.key,E.value]));return g.some(E=>u.get(E.key)!==E.value)}_mergeProfileCustomField(r=[],g=[]){const u=C(r)?r.map(E=>Object.assign({},E)):[];return C(g)&&g.length!==0&&g.forEach(({key:E,value:f})=>{const D=u.find(v=>v.key===E);D?D.value=f:u.push({key:E,value:f})}),u}_reset(){uc.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const lf=new Map,cS=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let s=0,r=cS.length;s>(-2*f&6)):0)E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(E);try{return decodeURIComponent(escape(g))}catch(u){return console.warn(u),""}}const{isEmpty:lN}=Se.utils,{generateProtocolData:If}=Se.common;function HR(s){return mA(this,void 0,void 0,function*(){const r="im_open_status.ws_get_user_status",g=If({servcmd:r,data:{To_Account:s}}),u=`${g.head.seq}${r}`,E=yield Se.channel.sendPacket(g,{requestId:u});if(E)return function(f){const{ErrorCode:D,ErrorInfo:v,ErrorList:N=[],UserStatusList:P=[]}=f,W=P.map(EA=>{const{To_Account:wA,Status:kA,CustomStatus:VA,Detail:LA=[]}=EA;return{userID:wA,statusType:kA,customStatus:up(VA),onlineDevices:IN(LA)}}),nA=N.map(EA=>{const{To_Account:wA,Invalid_Account:kA,ErrorCode:VA,ErrorInfo:LA}=EA;return{userID:lN(kA)?wA:kA,code:VA,message:LA}});return{errorCode:D,errorInfo:v,successUserList:W,failureUserList:nA}}(E)})}function IN(s){const r=[];return s?.forEach(g=>{const{Platform:u,Status:E}=g;E==="Online"&&r.push(u)}),r}class uN{constructor(){this._customStatus=""}init(){const{notificationCenter:r}=Se;vr.getInstance().registerApi({apiName:"getUserStatus",context:this}),vr.getInstance().registerApi({apiName:"setSelfStatus",context:this}),vr.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),vr.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),Pn.getInstance().registerWorkflowStep(jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Xt.USER_STATUS_UPDATE,this._onReOnline,this),r.subscribeInnerEvent(lo.MESSAGE_PUSH,r.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),r.subscribeInnerEvent(lo.LOGOUT,this._reset,this),r.subscribeInnerEvent(lo.DESTROY,this._dispose,this)}setSelfStatus(r){return mA(this,void 0,void 0,function*(){const g=ar(),{customStatus:u}=r;try{return yield function(E){return mA(this,void 0,void 0,function*(){const f="im_open_status.ws_set_custom_status",D=If({servcmd:f,data:{CustomStatus:E}}),v=`${D.head.seq}${f}`,N=yield Se.channel.sendPacket(D,{requestId:v});if(N){const{ErrorCode:P,ErrorInfo:W}=N;return{errorCode:P,errorInfo:W}}})}(u),this._customStatus=u,{code:0,data:{userID:g,statusType:Fh,customStatus:u},successLog:{message:`customStatus: ${u}`}}}catch(E){const{errorCode:f,errorInfo:D}=E;throw new hn({functionName:"setSelfStatus",code:f,message:D})}})}getUserStatus(r){return mA(this,void 0,void 0,function*(){const{userIDList:g=[]}=r;if(this._isOnlyMeInArray(g))return this._getMyStatus();const u=yield this._getUserStatus(g);return Object.assign(Object.assign({},u),{successLog:{message:`userIDList length: ${g.length}`}})})}setCustomStatus(r){const g=up(r);this._customStatus=g}subscribeUserStatus(r){return mA(this,void 0,void 0,function*(){try{const{userIDList:g=[]}=r;this._checkBusinessCapabilityBits("subscribeUserStatus");const u=this._getMaxUserCount("subscribe"),E=this._sliceUserIDList(g,u),f=yield function(v){return mA(this,void 0,void 0,function*(){const{channel:N}=Se,P="im_open_status.ws_status_subscribe",W=If({servcmd:P,data:{To_Account:v}}),nA=`${W.head.seq}${P}`;return yield N.sendPacket(W,{requestId:nA})})}(E),D=this._parseResponse(f);return{code:0,data:{failureUserList:D},successLog:{message:`userID length:${g.length} failCount: ${D.length}`}}}catch(g){const{errorCode:u}=g;throw new hn({functionName:"subscribeUserStatus",code:u})}})}unsubscribeUserStatus(r){return mA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:g=[]}=r,u=this._getMaxUserCount("unsubscribe"),E=this._sliceUserIDList(g,u),f=yield function(v){return mA(this,void 0,void 0,function*(){const{channel:N}=Se,P="im_open_status.ws_status_unsubscribe";let W={};W=v.length===0?{UnsubscribeAll:1}:{To_Account:v};const nA=If({servcmd:P,data:W}),EA=`${nA.head.seq}${P}`;return yield N.sendPacket(nA,{requestId:EA})})}(E),D=this._parseResponse(f);return{code:0,data:{failureUserList:D},successLog:{message:`userID length:${g.length} failCount: ${D.length}`}}}catch(g){const{errorCode:u}=g;throw new hn({functionName:"unsubscribeUserStatus",code:u})}})}_onUserStatusUpdate(r){const{UserStatusList:g=[]}=r||{},u=g.map(E=>{const{To_Account:f,Status:D,CustomStatus:v,Platform:N}=E,P={userID:f,statusType:D,customStatus:up(v)};return N&&(P.onlineDevices=N),P});this._emitUserStatusUpdatedEvent(u)}_onReOnline(r){const g=up(r.data.customStatus);if(this._customStatus===g)return;this._customStatus=g;const u={userID:ar(),statusType:Fh,customStatus:g};this._emitUserStatusUpdatedEvent(u)}_emitUserStatusUpdatedEvent(r){Se.notificationCenter.emitOuterEvent(Rr.USER_STATUS_UPDATED,{name:Rr.USER_STATUS_UPDATED,data:r})}_sliceUserIDList(r,g){return r.slice(0,g)}_parseResponse(r){const{ErrorList:g=[]}=r;return g.map(u=>{const{To_Account:E,Invalid_Account:f,ErrorCode:D,ErrorInfo:v}=u;return{userID:Se.utils.isEmpty(f)?E:f,code:D,message:v}})}_checkBusinessCapabilityBits(r){if(!Se.store.get("commercialConfig").get(cN))throw new hn({functionName:r,code:ma.NO_USE,replacement1:r})}_getMaxUserCount(r){const g=Se.store.get("cloudConfig")||{},u={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}},{key:E,default:f}=u[r],D=g[E]||f;return parseInt(D,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:ar(),statusType:Fh,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(r){return mA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const g=this._getMaxUserCount("query"),u=this._sliceUserIDList(r,g),E=yield HR(u),{successUserList:f,failureUserList:D}=E||{};return{code:0,data:{successUserList:f,failureUserList:D}}}catch(g){const{errorCode:u}=g;throw new hn({functionName:"getUserStatus",code:u})}})}_isOnlyMeInArray(r){const g=ar();return r.length===1&&r.indexOf(g)>-1}_dispose(){const{notificationCenter:r}=Se;r.unSubscribeInnerEvent(lo.MESSAGE_PUSH,r.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),r.unSubscribeInnerEvent(lo.DESTROY,this._dispose,this),r.unSubscribeInnerEvent(lo.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const lS={getUserProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},updateMyProfile:{nick:{required:!1,rules:["string"],allowEmpty:!0},avatar:{required:!1,rules:["string"],allowEmpty:!0},gender:{required:!1,rules:["string"],allowEmpty:!0},selfSignature:{required:!1,rules:["string"],allowEmpty:!0},allowType:{required:!1,rules:["string"],allowEmpty:!0},birthday:{required:!1,rules:["number"],allowEmpty:!1},language:{required:!1,rules:["string"],allowEmpty:!0},messageSettings:{required:!1,rules:["string"],allowEmpty:!0},adminForbidType:{required:!1,rules:["string"],allowEmpty:!0},level:{required:!1,rules:["number"],allowEmpty:!1},role:{required:!1,rules:["number"],allowEmpty:!0},profileCustomField:{required:!1,rules:["array"],allowEmpty:!0,customValidator:function(s){for(const r of s){if(typeof r!="object")return"Each item in profileCustomField must be an object";if(typeof r?.key!="string")return"Each item.key in profileCustomField must be a string";if(!r?.key.startsWith(rS))return'Each item.key in profileCustomField must start with "Tag_Profile_Custom"'}return!0}}},setSelfStatus:{customStatus:{required:!0,rules:["string"],allowEmpty:!0}},getUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!1,rules:["array"],allowEmpty:!0}}},EN={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class dN{constructor(){this.userProfile=new cf,this.userStatus=new uN,this.userProfile.init(),this.userStatus.init(),el({auth:EN,params:lS})}}function IS(s){const r=[];if(!c(s))return r;const g=s.length;if(g===0)return r;for(let u=g-1;u>=0;u--)s[u]==="1"&&r.push(2**(g-u-1));return r}var Ud,NC,Fd;(function(s){s.NOT_START="notStart",s.PENDING="pending",s.RESOLVED="resolved",s.REJECTED="rejected"})(Ud||(Ud={})),function(s){s[s.C2C=1]="C2C",s[s.GROUP=2]="GROUP"}(NC||(NC={})),function(s){s[s.C2C=8]="C2C",s[s.GROUP=2]="GROUP"}(Fd||(Fd={}));class uS{constructor(){this._name="SyncConversationHandler",this._pagingStatus=Ud.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:r}=Se;Pn.getInstance().registerWorkflowStep(jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Xt.CONVERSATION_RECOVER,this._syncConversationList,this),Pn.getInstance().registerWorkflowStep(jt.SYNC_SERVER_INFO_AFTER_LOGIN,Xt.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),r.subscribeInnerEvent(lo.LOGOUT,this._reset,this),r.subscribeInnerEvent(lo.DESTROY,this._dispose,this),Se.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===Ud.RESOLVED}_syncConversationListAfterLogin(){return mA(this,void 0,void 0,function*(){return this._pagingStatus=Ud.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=Se;r.debug("_syncConversationList","start");try{const u=yield this._pagingGetConversationList(!0);this._pagingStatus=Ud.RESOLVED;const{conversationList:E=[]}=u||{};return r.info("_syncConversationList",`success count:${E.length}`),u}catch(u){const E=new hn(u);r.error("_syncConversationList",`fail ${g(u)}`,{error:E})}})}_pagingGetConversationList(r){return mA(this,void 0,void 0,function*(){try{const g=[];this._pagingStatus=Ud.PENDING;const u=yield function(nA){return mA(this,void 0,void 0,function*(){const{fromAccount:EA,pagingTimeStamp:wA,pagingStartIndex:kA,pagingPinnedTimeStamp:VA,pagingPinnedStartIndex:LA}=nA;return ug({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:EA,StartIndex:kA,TimeStamp:wA,TopStartIndex:LA,TopTimeStamp:VA}})})}({fromAccount:ar(),pagingTimeStamp:r?this._pagingTimeStamp:0,pagingStartIndex:r?this._pagingStartIndex:0,pagingPinnedTimeStamp:r?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:r?this._pagingPinnedStartIndex:0}),{CompleteFlag:E,SessionItem:f=[],TimeStamp:D,StartIndex:v,TopTimeStamp:N,TopStartIndex:P}=u||{};let W=[];if(E===1&&(this._pagingStatus=Ud.RESOLVED),f.length>0&&(W=this._getConversationOptions(f),g.push(...W)),Se.notificationCenter.emitInnerEvent(lo.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:W}),this._pagingTimeStamp=D,this._pagingStartIndex=v,this._pagingPinnedTimeStamp=N,this._pagingPinnedStartIndex=P,E!==1){const{conversationList:nA}=yield this._pagingGetConversationList(r);g.push(...nA)}return{conversationList:g}}catch(g){throw g}})}_getConversationOptions(r){const{utils:{isUndefined:g}}=Se,u=this._convertConversationKey(r);return this._filterValidConversations(u).map(E=>(g(E.lastMsg)&&(E.lastMsg={elements:[]}),E.type===NC.C2C?this._assembleC2COption(E):this._assembleGroupOption(E)))}_filterValidConversations(r){return r.filter(({type:g,userID:u})=>g===NC.C2C&&!function(E){let f;return E.startsWith(Po.CONV_C2C)&&(f=E.replace(Po.CONV_C2C,"")),f==="@TLS#ERROR"||f==="@TLS#NOT_FOUND"}(u)||g===2)}_assembleC2COption(r){var g,u,E,f,D,v,N,P;const W=this._createUserprofile(r);return{conversationID:`${Po.CONV_C2C}${r.userID}`,type:Po.CONV_C2C,lastMessage:{lastTime:r.time,lastSequence:r.sequence,fromAccount:r.lastC2CMsgFromAccount,type:!((g=r.lastMsg)===null||g===void 0)&&g.elements[0]?(u=r.lastMsg)===null||u===void 0?void 0:u.elements[0].type:null,payload:!((E=r.lastMsg)===null||E===void 0)&&E.elements[0]?this._amendLayersOverLimitProp(r.lastMsg.elements[0].content):null,cloudCustomData:((v=(D=(f=r.lastMsg)===null||f===void 0?void 0:f.elements)===null||D===void 0?void 0:D[0])===null||v===void 0?void 0:v.cloudCustomData)||"",isRevoked:r.lastMessageFlag===Fd.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(r),revoker:((P=(N=r.lastMsg)===null||N===void 0?void 0:N.revokerInfo)===null||P===void 0?void 0:P.revoker)||null},unreadCount:0,userProfile:W,peerReadTime:r.peerReadTime,isPinned:r.isPinned===1,customData:r.customMark||"",markList:IS(r.standardMark),conversationGroupList:[],remark:r.friendRemark||"",messageRemindType:this._transMsgRemindType(r.messageRemindType)}}_createUserprofile(r){var g;const{userID:u,nick:E,peerAvatar:f}=r,D=[{tag:"Tag_Profile_IM_Nick",value:E},{tag:"Tag_Profile_IM_Image",value:f}];return(g=Se.user.userProfile)===null||g===void 0?void 0:g.createProfile(u,D)}_computeIsPeerRead(r){const g=ar(),{lastC2CMsgFromAccount:u,time:E,c2cPeerReadTime:f}=r;return u===g&&E<=f}_assembleGroupOption(r){var g,u,E,f,D;return{conversationID:`${Po.CONV_GROUP}${r.groupID}`,type:Po.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:r.time,lastSequence:r.sequence,fromAccount:r.msgGroupFromAccount},this._patchTypeAndPayload(r)),{cloudCustomData:((E=(u=(g=r.lastMsg)===null||g===void 0?void 0:g.elements)===null||u===void 0?void 0:u[0])===null||E===void 0?void 0:E.cloudCustomData)||"",isRevoked:r.lastMessageFlag===Fd.GROUP,onlineOnlyFlag:!1,nick:r.msgGroupFromNickName||"",nameCard:r.msgGroupFromCardName||"",revoker:((D=(f=r.lastMsg)===null||f===void 0?void 0:f.revokerInfo)===null||D===void 0?void 0:D.revoker)||null}),groupProfile:{groupID:r.groupID,name:r.groupNick,avatar:r.groupImage,type:r.groupType,nextMessageSeq:r.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(r),peerReadTime:0,isPinned:r.isPinned===1,version:0,customData:r.customMark||"",markList:IS(r.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(r.messageRemindType),subType:r.groupType}}_convertConversationKey(r){return r.map(g=>({type:g.Type,userID:g.To_Account,nick:g.C2cNick,peerAvatar:g.C2cImage,time:g.MsgTimeStamp,sequence:g.MsgSeq,lastC2CMsgFromAccount:g.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(g.LastMsg),lastMessageFlag:g.LastMsgFlags,c2cPeerReadTime:g.C2cPeerReadTime,peerReadTime:g.C2cPeerReadTime,friendRemark:g.C2cRemark,isPinned:g.TopFlags,standardMark:g.StandardMark,customMark:g.CustomMark,messageRemindType:g.MsgRecvOption,groupID:g.ToAccount,groupNick:g.GroupNick,groupImage:g.GroupImage,groupType:g.GroupType,nextMessageSeq:g.GroupNextMsgSeq,msgGroupFromAccount:g.MsgGroupFrom_Account,msgGroupFromNickName:g.MsgGroupFromNickName,msgGroupFromCardName:g.MsgGroupFromCardName,unreadCount:g.UnreadMsgCount,noUnreadCount:g.GroupIgnoredUnreadSeqCount}))}_convertLastMsgKey(r){var g,u,E;const{utils:{isEmpty:f}}=Se;if(f(r))return null;let D="",v=null;if(!f(r.GroupTips)){const{From_Account:N,GroupName:P}=((g=r.GroupTips)===null||g===void 0?void 0:g.GroupInfo)||{};D=Po.MSG_GRP_TIP,v=Object.assign(Object.assign({},this._parseContent(D,r.GroupTips.MsgBody)),{groupProfile:{from:N,groupName:P}})}return r.MsgBody&&(D=(u=r.MsgBody[0])===null||u===void 0?void 0:u.MsgType,v=this._parseContent(D,r.MsgBody[0])),{event:r.Event,elements:[{type:D,content:v,cloudCustomData:r.CloudCustomData}],revokerInfo:{revoker:(E=r.RevokerInfo)===null||E===void 0?void 0:E.Revoker_Account}}}_parseContent(r,g){var u;if(!g)return g;const E=Se.message.messageFactory.getElementClass(r);return E?(u=E.parseServerPushElement(g))===null||u===void 0?void 0:u.content:g}_amendLayersOverLimitProp(r){const{LayersOverLimit:g}=r;return vo(r,["LayersOverLimit"]).layersOverLimit=g===1,r}_transMsgRemindType(r){let g="";return r===0?g=Po.MSG_REMIND_ACPT_AND_NOTE:r===1?g=Po.MSG_REMIND_DISCARD:r===2?g=Po.MSG_REMIND_ACPT_NOT_NOTE:r===3&&(g=Po.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}_patchTypeAndPayload(r){var g;const{utils:{isUndefined:u}}=Se,{event:E,elements:f=[]}=r.lastMsg||{};return u(E)?{type:f[0]?f[0].type:null,payload:f[0]?this._amendLayersOverLimitProp(f[0].content):null}:{type:Po.MSG_GRP_TIP,payload:((g=f?.[0])===null||g===void 0?void 0:g.content)||{}}}_computeGroupUnreadCount(r){const{unreadCount:g=0,noUnreadCount:u=0}=r,E=g-u;return E>0?E:0}_reset(){this._pagingStatus=Ud.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:r}=Se;r.unSubscribeInnerEvent(lo.LOGOUT,this._reset,this),r.unSubscribeInnerEvent(lo.DESTROY,this._dispose,this)}}class ES{constructor(){this.syncConversationHandler=new uS,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Aa}`);var dS={create:function(s){var r,g;const{SDKAppID:u,testEnv:E=!1,devMode:f=!1,unlimitedAVChatRoom:D=!1,scene:v="",oversea:N=!1,instance:P,disableIndependentDomain:W=!1,proxyServer:nA=""}=s;let EA=u;if(!function(kA){if(typeof kA=="number")return!0;const VA=Number(kA);return!Number.isNaN(VA)}(EA))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(EA=Number(EA),fa.has(EA))return fa.get(EA);let wA=null;if(P)wA=P,wA._workflowManager&&Pn.setInstance(wA._workflowManager),wA._pluginManager&&wA._pluginManager.installBuiltInPlugin(RB),P.isReady()&&((g=(r=Pn.getInstance()).executeWorkflow)===null||g===void 0||g.call(r,jt.SYNC_SERVER_INFO_AFTER_LOGIN));else{const kA=function(){function Ee(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${Ee()+Ee()}${Ee()}${Ee()}${Ee()}${Ee()}${Ee()}${Ee()}`}();Se.init({sdkAppId:EA,instanceId:kA,testEnv:E,devMode:f,unlimitedAVChatRoom:D,disableIndependentDomain:W,scene:v,oversea:N,sdkEdition:ef,version:Aa,proxyServer:nA}),Pn.getInstance().init(),Se.message=new sS,Se.user=new dN,Se.login=new Nh,Se.conversation=new ES,Iu.getInstance().installBuiltInPlugin(RB),wA=vr.getInstance().exposeApiForClient(),wA._workflowManager=Pn.getInstance(),wA._pluginManager=Iu.getInstance();const{utils:{IS_WORKER_AVAILABLE:VA,USER_AGENT:LA,getPlatformType:SA,isIOSWebView:PA}}=Se,zA=`instanceID:${kA} SDKAppID:${u} platform:${jA} host:${SA()} isIOSWebView:${PA} workerAvailable:${VA} UserAgent:${LA}`;Se.ssoLog.info("sdkConstruct",zA)}return fa.set(EA,wA),wA},TSignaling:Xc,EVENT:Rr,VERSION:Aa,TYPES:Po};return dS})}(hY)),hY.exports}var HnA=VnA();const rg=i4(HnA);var BY={exports:{}},JnA=BY.exports,H8;function qnA(){return H8||(H8=1,function(e,i){(function(n,c){e.exports=c()})(JnA,function(){function n(ae,Je){if(!(ae instanceof Je))throw new TypeError("Cannot call a class as a function")}function c(ae,Je){for(var pt=0;pt"u"&&typeof uni.requireNativePlugin=="function",qA=vA&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios",Ae=(vA&&uni.getDeviceInfo().platform.toLocaleLowerCase(),gA||eA||CA||IA||oA||vA),HA=b!==void 0&&(b.nativeModuleProxy!==void 0||b.ReactNative!==void 0),se=eA?qq:CA?tt:IA?swan:oA?my:gA?wx:vA?uni:{},WA=function(ae){if(T(ae)!=="object"||ae===null)return!1;var Je=Object.getPrototypeOf(ae);if(Je===null)return!0;for(var pt=Je;Object.getPrototypeOf(pt)!==null;)pt=Object.getPrototypeOf(pt);return Je===pt};function Ye(ae){if(ae==null)return!0;if(typeof ae=="boolean")return!1;if(typeof ae=="number")return ae===0;if(typeof ae=="string"||typeof ae=="function"||Array.isArray(ae))return ae.length===0;if(ae instanceof Error)return ae.message==="";if(WA(ae)){for(var Je in ae)if(Object.prototype.hasOwnProperty.call(ae,Je))return!1;return!0}return!1}var We=function(){return I(function ae(){n(this,ae),this._n="WebRequest"},[{key:"request",value:function(ae,Je){var pt=this,$t="".concat(this._n,".request"),Pt=ae.downloadUrl||"",ii=(ae.method||"PUT").toUpperCase(),ki=ae.url;if(console.log("%c tim-upload-plugin %c","background:#0abf5b; padding:1px; border-radius:3px; color: #fff","background:transparent","".concat($t," URL:").concat(ki)),ae.qs){var ao=function(Fi){var en=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"&",Ro=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"=";return Ye(Fi)?"":WA(Fi)?Object.keys(Fi).map(function(oo){var Ai=encodeURIComponent(oo)+Ro;return Array.isArray(Fi[oo])?Fi[oo].map(function(no){return Ai+encodeURIComponent(no)}).join(en):Ai+encodeURIComponent(Fi[oo])}).filter(Boolean).join(en):void 0}(ae.qs);ao&&(ki+="".concat(ki.indexOf("?")===-1?"?":"&").concat(ao))}var Ji=new XMLHttpRequest;Ji.open(ii,ki,!0),Ji.responseType=ae.dataType||"text";var Vi=ae.headers||{};if(ae.uploadByIP&&(Vi=R(R({},Vi),{},{host:ae.uploadIP})),!Ye(Vi))for(var wn in Vi)Vi.hasOwnProperty(wn)&&wn.toLowerCase()!=="content-length"&&wn.toLowerCase()!=="user-agent"&&wn.toLowerCase()!=="origin"&&wn.toLowerCase()!=="host"&&Ji.setRequestHeader(wn,Vi[wn]);return Ji.onload=function(){if(Ji.status===200)Je(null,pt._xhrRes(Ji,pt._xhrBody(Ji,Pt,ae.uploadByIP&&ae.uploadIP),Vi));else{if(ae.uploadIP&&ae.url.indexOf(ae.uploadIP)===-1)return ae.url=function(en,Ro){return en.replace(/^http(s)?:\/\/(.*?)\//,"https://".concat(Ro,"/"))}(ae.url,ae.uploadIP),ae.uploadByIP=!0,pt.request(ae,Je);var Fi={code:Ji.status,message:JSON.stringify(Ji.responseText)};Je(Fi,pt._xhrRes(Ji,pt._xhrBody(Ji,Pt,ae.uploadByIP&&ae.uploadIP),Vi))}},Ji.onerror=function(Fi){var en=pt._xhrBody(Ji,Pt,ae.uploadByIP&&ae.uploadIP),Ro={code:Ji.status,message:JSON.stringify(Ji.responseText)};en||Ji.statusText||Ji.status!==0||(Fi.message="CORS blocked or network error"),Je(Ro,pt._xhrRes(Ji,en)),Ro=null},ae.onProgress&&Ji.upload&&(Ji.upload.onprogress=function(Fi){var en=Fi.total,Ro=Fi.loaded,oo=Math.floor(100*Ro/en);ae.onProgress({total:en,loaded:Ro,percent:(oo>=100?100:oo)/100})}),Ji.send(ae.resources),Ji}},{key:"_xhrRes",value:function(ae,Je){var pt={};return ae.getAllResponseHeaders().trim().split(` `).forEach(function($t){if($t){var Pt=$t.indexOf(":"),ii=$t.substr(0,Pt).trim().toLowerCase(),ki=$t.substr(Pt+1).trim();pt[ii]=ki}}),{statusCode:ae.status,statusMessage:ae.statusText,headers:pt,data:Je}}},{key:"_xhrBody",value:function(ae,Je,pt){return ae.status===200&&Je?{location:Je,uploadIP:pt}:{response:ae.responseText,uploadIP:pt}}}])}(),Pe=["unknown","image","video","audio","log"],we=["name"],et=function(){return I(function ae(){n(this,ae)},[{key:"request",value:function(ae,Je){var pt=this,$t=ae.resources,Pt=$t===void 0?"":$t,ii=ae.headers,ki=ii===void 0?{}:ii,ao=ae.url,Ji=ae.downloadUrl,Vi=Ji===void 0?"":Ji,wn=ao,Fi=null,en=Vi.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/),Ro=decodeURIComponent(en[3]),oo=Ro.indexOf("?")>-1?Ro.split("?")[0]:Ro,Ai={key:ae.fileKey?ae.fileKey:oo,success_action_status:200,"Content-Type":""},no={};if(qA){var Ri=ao.split("?sign=");if(Ri.length>1){var pn=Ri[1];wn="".concat(Ri[0],"?sign=").concat(encodeURIComponent("".concat(pn))),no.sign=decodeURIComponent(pn),no.signature=decodeURIComponent(pn)}}var jA={url:wn,header:ki,name:"file",filePath:Pt,formData:R(R({},Ai),no),timeout:ae.timeout||3e5};if(oA){var ue=jA;ue.name,jA=R(R({},function(He,Lt){if(He==null)return{};var ct,Ct,ei=function(Le,it){if(Le==null)return{};var Tt={};for(var Gt in Le)if({}.hasOwnProperty.call(Le,Gt)){if(it.includes(Gt))continue;Tt[Gt]=Le[Gt]}return Tt}(He,Lt);if(Object.getOwnPropertySymbols){var Ht=Object.getOwnPropertySymbols(He);for(Ct=0;Ct=3e4&&(this.systemClockOffset=ao-ki,Je=!0)}else Math.floor(ae.statusCode/100)===5&&(Je=!0)}return Je}}],[{key:"getVersion",value:function(){return"1.4.3"}}])}()})}(BY)),BY.exports}var KnA=qnA();const jnA=i4(KnA);/** * @vue/shared v3.5.13 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT -**//*! #__NO_SIDE_EFFECTS__ */function o4(e){const i=Object.create(null);for(const n of e.split(","))i[n]=1;return n=>n in i}const _a={},eT=[],GQ=()=>{},WnA=()=>!1,SV=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),n4=e=>e.startsWith("onUpdate:"),cI=Object.assign,s4=(e,i)=>{const n=e.indexOf(i);n>-1&&e.splice(n,1)},znA=Object.prototype.hasOwnProperty,$r=(e,i)=>znA.call(e,i),Ln=Array.isArray,tT=e=>vV(e)==="[object Map]",o9=e=>vV(e)==="[object Set]",ls=e=>typeof e=="function",Sg=e=>typeof e=="string",ym=e=>typeof e=="symbol",Ua=e=>e!==null&&typeof e=="object",n9=e=>(Ua(e)||ls(e))&&ls(e.then)&&ls(e.catch),s9=Object.prototype.toString,vV=e=>s9.call(e),ZnA=e=>vV(e).slice(8,-1),r9=e=>vV(e)==="[object Object]",r4=e=>Sg(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,aU=o4(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),MV=e=>{const i=Object.create(null);return n=>i[n]||(i[n]=e(n))},XnA=/-(\w)/g,ch=MV(e=>e.replace(XnA,(i,n)=>n?n.toUpperCase():"")),$nA=/\B([A-Z])/g,CD=MV(e=>e.replace($nA,"-$1").toLowerCase()),RV=MV(e=>e.charAt(0).toUpperCase()+e.slice(1)),Zj=MV(e=>e?`on${RV(e)}`:""),tD=(e,i)=>!Object.is(e,i),QY=(e,...i)=>{for(let n=0;n{Object.defineProperty(e,i,{configurable:!0,enumerable:!1,writable:c,value:n})},z3=e=>{const i=parseFloat(e);return isNaN(i)?e:i},AsA=e=>{const i=Sg(e)?Number(e):NaN;return isNaN(i)?e:i};let J8;const wV=()=>J8||(J8=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function lr(e){if(Ln(e)){const i={};for(let n=0;n{if(n){const c=n.split(tsA);c.length>1&&(i[c[0].trim()]=c[1].trim())}}),i}function xi(e){let i="";if(Sg(e))i=e;else if(Ln(e))for(let n=0;n!!(e&&e.__v_isRef===!0),ut=e=>Sg(e)?e:e==null?"":Ln(e)||Ua(e)&&(e.toString===s9||!ls(e.toString))?c9(e)?ut(e.value):JSON.stringify(e,l9,2):String(e),l9=(e,i)=>c9(i)?l9(e,i.value):tT(i)?{[`Map(${i.size})`]:[...i.entries()].reduce((n,[c,I],C)=>(n[Xj(c,C)+" =>"]=I,n),{})}:o9(i)?{[`Set(${i.size})`]:[...i.values()].map(n=>Xj(n))}:ym(i)?Xj(i):Ua(i)&&!Ln(i)&&!r9(i)?String(i):i,Xj=(e,i="")=>{var n;return ym(e)?`Symbol(${(n=e.description)!=null?n:i})`:e};/** +**//*! #__NO_SIDE_EFFECTS__ */function o4(e){const i=Object.create(null);for(const n of e.split(","))i[n]=1;return n=>n in i}const _a={},eT=[],GQ=()=>{},WnA=()=>!1,SV=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),n4=e=>e.startsWith("onUpdate:"),cI=Object.assign,s4=(e,i)=>{const n=e.indexOf(i);n>-1&&e.splice(n,1)},znA=Object.prototype.hasOwnProperty,$r=(e,i)=>znA.call(e,i),Ln=Array.isArray,tT=e=>vV(e)==="[object Map]",o9=e=>vV(e)==="[object Set]",ls=e=>typeof e=="function",vg=e=>typeof e=="string",ym=e=>typeof e=="symbol",Ua=e=>e!==null&&typeof e=="object",n9=e=>(Ua(e)||ls(e))&&ls(e.then)&&ls(e.catch),s9=Object.prototype.toString,vV=e=>s9.call(e),ZnA=e=>vV(e).slice(8,-1),r9=e=>vV(e)==="[object Object]",r4=e=>vg(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,aU=o4(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),MV=e=>{const i=Object.create(null);return n=>i[n]||(i[n]=e(n))},XnA=/-(\w)/g,ch=MV(e=>e.replace(XnA,(i,n)=>n?n.toUpperCase():"")),$nA=/\B([A-Z])/g,CD=MV(e=>e.replace($nA,"-$1").toLowerCase()),RV=MV(e=>e.charAt(0).toUpperCase()+e.slice(1)),Zj=MV(e=>e?`on${RV(e)}`:""),tD=(e,i)=>!Object.is(e,i),QY=(e,...i)=>{for(let n=0;n{Object.defineProperty(e,i,{configurable:!0,enumerable:!1,writable:c,value:n})},z3=e=>{const i=parseFloat(e);return isNaN(i)?e:i},AsA=e=>{const i=vg(e)?Number(e):NaN;return isNaN(i)?e:i};let J8;const wV=()=>J8||(J8=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function lr(e){if(Ln(e)){const i={};for(let n=0;n{if(n){const c=n.split(tsA);c.length>1&&(i[c[0].trim()]=c[1].trim())}}),i}function xi(e){let i="";if(vg(e))i=e;else if(Ln(e))for(let n=0;n!!(e&&e.__v_isRef===!0),ut=e=>vg(e)?e:e==null?"":Ln(e)||Ua(e)&&(e.toString===s9||!ls(e.toString))?c9(e)?ut(e.value):JSON.stringify(e,l9,2):String(e),l9=(e,i)=>c9(i)?l9(e,i.value):tT(i)?{[`Map(${i.size})`]:[...i.entries()].reduce((n,[c,I],C)=>(n[Xj(c,C)+" =>"]=I,n),{})}:o9(i)?{[`Set(${i.size})`]:[...i.values()].map(n=>Xj(n))}:ym(i)?Xj(i):Ua(i)&&!Ln(i)&&!r9(i)?String(i):i,Xj=(e,i="")=>{var n;return ym(e)?`Symbol(${(n=e.description)!=null?n:i})`:e};/** * @vue/reactivity v3.5.13 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT -**/let nC;class asA{constructor(i=!1){this.detached=i,this._active=!0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=nC,!i&&nC&&(this.index=(nC.scopes||(nC.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let i,n;if(this.scopes)for(i=0,n=this.scopes.length;i0)return;if(cU){let i=cU;for(cU=void 0;i;){const n=i.next;i.next=void 0,i.flags&=-9,i=n}}let e;for(;gU;){let i=gU;for(gU=void 0;i;){const n=i.next;if(i.next=void 0,i.flags&=-9,i.flags&1)try{i.trigger()}catch(c){e||(e=c)}i=n}}if(e)throw e}function d9(e){for(let i=e.deps;i;i=i.nextDep)i.version=-1,i.prevActiveLink=i.dep.activeLink,i.dep.activeLink=i}function C9(e){let i,n=e.depsTail,c=n;for(;c;){const I=c.prevDep;c.version===-1?(c===n&&(n=I),c4(c),csA(c)):i=c,c.dep.activeLink=c.prevActiveLink,c.prevActiveLink=void 0,c=I}e.deps=i,e.depsTail=n}function Z3(e){for(let i=e.deps;i;i=i.nextDep)if(i.dep.version!==i.version||i.dep.computed&&(h9(i.dep.computed)||i.dep.version!==i.version))return!0;return!!e._dirty}function h9(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===_U))return;e.globalVersion=_U;const i=e.dep;if(e.flags|=2,i.version>0&&!e.isSSR&&e.deps&&!Z3(e)){e.flags&=-3;return}const n=La,c=gB;La=e,gB=!0;try{d9(e);const I=e.fn(e._value);(i.version===0||tD(I,e._value))&&(e._value=I,i.version++)}catch(I){throw i.version++,I}finally{La=n,gB=c,C9(e),e.flags&=-3}}function c4(e,i=!1){const{dep:n,prevSub:c,nextSub:I}=e;if(c&&(c.nextSub=I,e.prevSub=void 0),I&&(I.prevSub=c,e.nextSub=void 0),n.subs===e&&(n.subs=c,!c&&n.computed)){n.computed.flags&=-5;for(let C=n.computed.deps;C;C=C.nextDep)c4(C,!0)}!i&&!--n.sc&&n.map&&n.map.delete(n.key)}function csA(e){const{prevDep:i,nextDep:n}=e;i&&(i.nextDep=n,e.prevDep=void 0),n&&(n.prevDep=i,e.nextDep=void 0)}let gB=!0;const B9=[];function hD(){B9.push(gB),gB=!1}function BD(){const e=B9.pop();gB=e===void 0?!0:e}function q8(e){const{cleanup:i}=e;if(e.cleanup=void 0,i){const n=La;La=void 0;try{i()}finally{La=n}}}let _U=0;class lsA{constructor(i,n){this.sub=i,this.dep=n,this.version=n.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class l4{constructor(i){this.computed=i,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0}track(i){if(!La||!gB||La===this.computed)return;let n=this.activeLink;if(n===void 0||n.sub!==La)n=this.activeLink=new lsA(La,this),La.deps?(n.prevDep=La.depsTail,La.depsTail.nextDep=n,La.depsTail=n):La.deps=La.depsTail=n,Q9(n);else if(n.version===-1&&(n.version=this.version,n.nextDep)){const c=n.nextDep;c.prevDep=n.prevDep,n.prevDep&&(n.prevDep.nextDep=c),n.prevDep=La.depsTail,n.nextDep=void 0,La.depsTail.nextDep=n,La.depsTail=n,La.deps===n&&(La.deps=c)}return n}trigger(i){this.version++,_U++,this.notify(i)}notify(i){a4();try{for(let n=this.subs;n;n=n.prevSub)n.sub.notify()&&n.sub.dep.notify()}finally{g4()}}}function Q9(e){if(e.dep.sc++,e.sub.flags&4){const i=e.dep.computed;if(i&&!e.dep.subs){i.flags|=20;for(let c=i.deps;c;c=c.nextDep)Q9(c)}const n=e.dep.subs;n!==e&&(e.prevSub=n,n&&(n.nextSub=e)),e.dep.subs=e}}const UY=new WeakMap,RM=Symbol(""),X3=Symbol(""),TU=Symbol("");function Du(e,i,n){if(gB&&La){let c=UY.get(e);c||UY.set(e,c=new Map);let I=c.get(n);I||(c.set(n,I=new l4),I.map=c,I.key=n),I.track()}}function hm(e,i,n,c,I,C){const m=UY.get(e);if(!m){_U++;return}const R=_=>{_&&_.trigger()};if(a4(),i==="clear")m.forEach(R);else{const _=Ln(e),T=_&&r4(n);if(_&&n==="length"){const b=Number(c);m.forEach((J,cA)=>{(cA==="length"||cA===TU||!ym(cA)&&cA>=b)&&R(J)})}else switch((n!==void 0||m.has(void 0))&&R(m.get(n)),T&&R(m.get(TU)),i){case"add":_?T&&R(m.get("length")):(R(m.get(RM)),tT(e)&&R(m.get(X3)));break;case"delete":_||(R(m.get(RM)),tT(e)&&R(m.get(X3)));break;case"set":tT(e)&&R(m.get(RM));break}}g4()}function IsA(e,i){const n=UY.get(e);return n&&n.get(i)}function T_(e){const i=Lr(e);return i===e?i:(Du(i,"iterate",TU),sh(e)?i:i.map(Su))}function _V(e){return Du(e=Lr(e),"iterate",TU),e}const usA={__proto__:null,[Symbol.iterator](){return A3(this,Symbol.iterator,Su)},concat(...e){return T_(this).concat(...e.map(i=>Ln(i)?T_(i):i))},entries(){return A3(this,"entries",e=>(e[1]=Su(e[1]),e))},every(e,i){return gm(this,"every",e,i,void 0,arguments)},filter(e,i){return gm(this,"filter",e,i,n=>n.map(Su),arguments)},find(e,i){return gm(this,"find",e,i,Su,arguments)},findIndex(e,i){return gm(this,"findIndex",e,i,void 0,arguments)},findLast(e,i){return gm(this,"findLast",e,i,Su,arguments)},findLastIndex(e,i){return gm(this,"findLastIndex",e,i,void 0,arguments)},forEach(e,i){return gm(this,"forEach",e,i,void 0,arguments)},includes(...e){return e3(this,"includes",e)},indexOf(...e){return e3(this,"indexOf",e)},join(e){return T_(this).join(e)},lastIndexOf(...e){return e3(this,"lastIndexOf",e)},map(e,i){return gm(this,"map",e,i,void 0,arguments)},pop(){return TL(this,"pop")},push(...e){return TL(this,"push",e)},reduce(e,...i){return K8(this,"reduce",e,i)},reduceRight(e,...i){return K8(this,"reduceRight",e,i)},shift(){return TL(this,"shift")},some(e,i){return gm(this,"some",e,i,void 0,arguments)},splice(...e){return TL(this,"splice",e)},toReversed(){return T_(this).toReversed()},toSorted(e){return T_(this).toSorted(e)},toSpliced(...e){return T_(this).toSpliced(...e)},unshift(...e){return TL(this,"unshift",e)},values(){return A3(this,"values",Su)}};function A3(e,i,n){const c=_V(e),I=c[i]();return c!==e&&!sh(e)&&(I._next=I.next,I.next=()=>{const C=I._next();return C.value&&(C.value=n(C.value)),C}),I}const EsA=Array.prototype;function gm(e,i,n,c,I,C){const m=_V(e),R=m!==e&&!sh(e),_=m[i];if(_!==EsA[i]){const J=_.apply(e,C);return R?Su(J):J}let T=n;m!==e&&(R?T=function(J,cA){return n.call(this,Su(J),cA,e)}:n.length>2&&(T=function(J,cA){return n.call(this,J,cA,e)}));const b=_.call(m,T,c);return R&&I?I(b):b}function K8(e,i,n,c){const I=_V(e);let C=n;return I!==e&&(sh(e)?n.length>3&&(C=function(m,R,_){return n.call(this,m,R,_,e)}):C=function(m,R,_){return n.call(this,m,Su(R),_,e)}),I[i](C,...c)}function e3(e,i,n){const c=Lr(e);Du(c,"iterate",TU);const I=c[i](...n);return(I===-1||I===!1)&&E4(n[0])?(n[0]=Lr(n[0]),c[i](...n)):I}function TL(e,i,n=[]){hD(),a4();const c=Lr(e)[i].apply(e,n);return g4(),BD(),c}const dsA=o4("__proto__,__v_isRef,__isVue"),p9=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!=="arguments"&&e!=="caller").map(e=>Symbol[e]).filter(ym));function CsA(e){ym(e)||(e=String(e));const i=Lr(this);return Du(i,"has",e),i.hasOwnProperty(e)}class m9{constructor(i=!1,n=!1){this._isReadonly=i,this._isShallow=n}get(i,n,c){if(n==="__v_skip")return i.__v_skip;const I=this._isReadonly,C=this._isShallow;if(n==="__v_isReactive")return!I;if(n==="__v_isReadonly")return I;if(n==="__v_isShallow")return C;if(n==="__v_raw")return c===(I?C?vsA:S9:C?D9:y9).get(i)||Object.getPrototypeOf(i)===Object.getPrototypeOf(c)?i:void 0;const m=Ln(i);if(!I){let _;if(m&&(_=usA[n]))return _;if(n==="hasOwnProperty")return CsA}const R=Reflect.get(i,n,aI(i)?i:c);return(ym(n)?p9.has(n):dsA(n))||(I||Du(i,"get",n),C)?R:aI(R)?m&&r4(n)?R:R.value:Ua(R)?I?mc(R):DM(R):R}}class f9 extends m9{constructor(i=!1){super(!1,i)}set(i,n,c,I){let C=i[n];if(!this._isShallow){const _=PM(C);if(!sh(c)&&!PM(c)&&(C=Lr(C),c=Lr(c)),!Ln(i)&&aI(C)&&!aI(c))return _?!1:(C.value=c,!0)}const m=Ln(i)&&r4(n)?Number(n)e,j1=e=>Reflect.getPrototypeOf(e);function msA(e,i,n){return function(...c){const I=this.__v_raw,C=Lr(I),m=tT(C),R=e==="entries"||e===Symbol.iterator&&m,_=e==="keys"&&m,T=I[e](...c),b=n?$3:i?AW:Su;return!i&&Du(C,"iterate",_?X3:RM),{next(){const{value:J,done:cA}=T.next();return cA?{value:J,done:cA}:{value:R?[b(J[0]),b(J[1])]:b(J),done:cA}},[Symbol.iterator](){return this}}}}function W1(e){return function(...i){return e==="delete"?!1:e==="clear"?void 0:this}}function fsA(e,i){const n={get(I){const C=this.__v_raw,m=Lr(C),R=Lr(I);e||(tD(I,R)&&Du(m,"get",I),Du(m,"get",R));const{has:_}=j1(m),T=i?$3:e?AW:Su;if(_.call(m,I))return T(C.get(I));if(_.call(m,R))return T(C.get(R));C!==m&&C.get(I)},get size(){const I=this.__v_raw;return!e&&Du(Lr(I),"iterate",RM),Reflect.get(I,"size",I)},has(I){const C=this.__v_raw,m=Lr(C),R=Lr(I);return e||(tD(I,R)&&Du(m,"has",I),Du(m,"has",R)),I===R?C.has(I):C.has(I)||C.has(R)},forEach(I,C){const m=this,R=m.__v_raw,_=Lr(R),T=i?$3:e?AW:Su;return!e&&Du(_,"iterate",RM),R.forEach((b,J)=>I.call(C,T(b),T(J),m))}};return cI(n,e?{add:W1("add"),set:W1("set"),delete:W1("delete"),clear:W1("clear")}:{add(I){!i&&!sh(I)&&!PM(I)&&(I=Lr(I));const C=Lr(this);return j1(C).has.call(C,I)||(C.add(I),hm(C,"add",I,I)),this},set(I,C){!i&&!sh(C)&&!PM(C)&&(C=Lr(C));const m=Lr(this),{has:R,get:_}=j1(m);let T=R.call(m,I);T||(I=Lr(I),T=R.call(m,I));const b=_.call(m,I);return m.set(I,C),T?tD(C,b)&&hm(m,"set",I,C):hm(m,"add",I,C),this},delete(I){const C=Lr(this),{has:m,get:R}=j1(C);let _=m.call(C,I);_||(I=Lr(I),_=m.call(C,I)),R&&R.call(C,I);const T=C.delete(I);return _&&hm(C,"delete",I,void 0),T},clear(){const I=Lr(this),C=I.size!==0,m=I.clear();return C&&hm(I,"clear",void 0,void 0),m}}),["keys","values","entries",Symbol.iterator].forEach(I=>{n[I]=msA(I,e,i)}),n}function I4(e,i){const n=fsA(e,i);return(c,I,C)=>I==="__v_isReactive"?!e:I==="__v_isReadonly"?e:I==="__v_raw"?c:Reflect.get($r(n,I)&&I in c?n:c,I,C)}const ysA={get:I4(!1,!1)},DsA={get:I4(!1,!0)},SsA={get:I4(!0,!1)};const y9=new WeakMap,D9=new WeakMap,S9=new WeakMap,vsA=new WeakMap;function MsA(e){switch(e){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function RsA(e){return e.__v_skip||!Object.isExtensible(e)?0:MsA(ZnA(e))}function DM(e){return PM(e)?e:u4(e,!1,BsA,ysA,y9)}function wsA(e){return u4(e,!1,psA,DsA,D9)}function mc(e){return u4(e,!0,QsA,SsA,S9)}function u4(e,i,n,c,I){if(!Ua(e)||e.__v_raw&&!(i&&e.__v_isReactive))return e;const C=I.get(e);if(C)return C;const m=RsA(e);if(m===0)return e;const R=new Proxy(e,m===2?c:n);return I.set(e,R),R}function iT(e){return PM(e)?iT(e.__v_raw):!!(e&&e.__v_isReactive)}function PM(e){return!!(e&&e.__v_isReadonly)}function sh(e){return!!(e&&e.__v_isShallow)}function E4(e){return e?!!e.__v_raw:!1}function Lr(e){const i=e&&e.__v_raw;return i?Lr(i):e}function _sA(e){return!$r(e,"__v_skip")&&Object.isExtensible(e)&&a9(e,"__v_skip",!0),e}const Su=e=>Ua(e)?DM(e):e,AW=e=>Ua(e)?mc(e):e;function aI(e){return e?e.__v_isRef===!0:!1}function Ge(e){return TsA(e,!1)}function TsA(e,i){return aI(e)?e:new NsA(e,i)}class NsA{constructor(i,n){this.dep=new l4,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=n?i:Lr(i),this._value=n?i:Su(i),this.__v_isShallow=n}get value(){return this.dep.track(),this._value}set value(i){const n=this._rawValue,c=this.__v_isShallow||sh(i)||PM(i);i=c?i:Lr(i),tD(i,n)&&(this._rawValue=i,this._value=c?i:Su(i),this.dep.trigger())}}function aA(e){return aI(e)?e.value:e}const GsA={get:(e,i,n)=>i==="__v_raw"?e:aA(Reflect.get(e,i,n)),set:(e,i,n,c)=>{const I=e[i];return aI(I)&&!aI(n)?(I.value=n,!0):Reflect.set(e,i,n,c)}};function v9(e){return iT(e)?e:new Proxy(e,GsA)}function Hn(e){const i=Ln(e)?new Array(e.length):{};for(const n in e)i[n]=M9(e,n);return i}class bsA{constructor(i,n,c){this._object=i,this._key=n,this._defaultValue=c,this.__v_isRef=!0,this._value=void 0}get value(){const i=this._object[this._key];return this._value=i===void 0?this._defaultValue:i}set value(i){this._object[this._key]=i}get dep(){return IsA(Lr(this._object),this._key)}}class ksA{constructor(i){this._getter=i,this.__v_isRef=!0,this.__v_isReadonly=!0,this._value=void 0}get value(){return this._value=this._getter()}}function t3(e,i,n){return aI(e)?e:ls(e)?new ksA(e):Ua(e)&&arguments.length>1?M9(e,i,n):Ge(e)}function M9(e,i,n){const c=e[i];return aI(c)?c:new bsA(e,i,n)}class LsA{constructor(i,n,c){this.fn=i,this.setter=n,this._value=void 0,this.dep=new l4(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=_U-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!n,this.isSSR=c}notify(){if(this.flags|=16,!(this.flags&8)&&La!==this)return E9(this,!0),!0}get value(){const i=this.dep.track();return h9(this),i&&(i.version=this.dep.version),this._value}set value(i){this.setter&&this.setter(i)}}function UsA(e,i,n=!1){let c,I;return ls(e)?c=e:(c=e.get,I=e.set),new LsA(c,I,n)}const z1={},FY=new WeakMap;let hM;function FsA(e,i=!1,n=hM){if(n){let c=FY.get(n);c||FY.set(n,c=[]),c.push(e)}}function OsA(e,i,n=_a){const{immediate:c,deep:I,once:C,scheduler:m,augmentJob:R,call:_}=n,T=HA=>I?HA:sh(HA)||I===!1||I===0?Bm(HA,1):Bm(HA);let b,J,cA,eA,CA=!1,IA=!1;if(aI(e)?(J=()=>e.value,CA=sh(e)):iT(e)?(J=()=>T(e),CA=!0):Ln(e)?(IA=!0,CA=e.some(HA=>iT(HA)||sh(HA)),J=()=>e.map(HA=>{if(aI(HA))return HA.value;if(iT(HA))return T(HA);if(ls(HA))return _?_(HA,2):HA()})):ls(e)?i?J=_?()=>_(e,2):e:J=()=>{if(cA){hD();try{cA()}finally{BD()}}const HA=hM;hM=b;try{return _?_(e,3,[eA]):e(eA)}finally{hM=HA}}:J=GQ,i&&I){const HA=J,se=I===!0?1/0:I;J=()=>Bm(HA(),se)}const oA=gsA(),vA=()=>{b.stop(),oA&&oA.active&&s4(oA.effects,b)};if(C&&i){const HA=i;i=(...se)=>{HA(...se),vA()}}let qA=IA?new Array(e.length).fill(z1):z1;const Ae=HA=>{if(!(!(b.flags&1)||!b.dirty&&!HA))if(i){const se=b.run();if(I||CA||(IA?se.some((WA,Ye)=>tD(WA,qA[Ye])):tD(se,qA))){cA&&cA();const WA=hM;hM=b;try{const Ye=[se,qA===z1?void 0:IA&&qA[0]===z1?[]:qA,eA];_?_(i,3,Ye):i(...Ye),qA=se}finally{hM=WA}}}else b.run()};return R&&R(Ae),b=new I9(J),b.scheduler=m?()=>m(Ae,!1):Ae,eA=HA=>FsA(HA,!1,b),cA=b.onStop=()=>{const HA=FY.get(b);if(HA){if(_)_(HA,4);else for(const se of HA)se();FY.delete(b)}},i?c?Ae(!0):qA=b.run():m?m(Ae.bind(null,!0),!0):b.run(),vA.pause=b.pause.bind(b),vA.resume=b.resume.bind(b),vA.stop=vA,vA}function Bm(e,i=1/0,n){if(i<=0||!Ua(e)||e.__v_skip||(n=n||new Set,n.has(e)))return e;if(n.add(e),i--,aI(e))Bm(e.value,i,n);else if(Ln(e))for(let c=0;c{Bm(c,i,n)});else if(r9(e)){for(const c in e)Bm(e[c],i,n);for(const c of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,c)&&Bm(e[c],i,n)}return e}/** +**/let nC;class asA{constructor(i=!1){this.detached=i,this._active=!0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=nC,!i&&nC&&(this.index=(nC.scopes||(nC.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let i,n;if(this.scopes)for(i=0,n=this.scopes.length;i0)return;if(cU){let i=cU;for(cU=void 0;i;){const n=i.next;i.next=void 0,i.flags&=-9,i=n}}let e;for(;gU;){let i=gU;for(gU=void 0;i;){const n=i.next;if(i.next=void 0,i.flags&=-9,i.flags&1)try{i.trigger()}catch(c){e||(e=c)}i=n}}if(e)throw e}function d9(e){for(let i=e.deps;i;i=i.nextDep)i.version=-1,i.prevActiveLink=i.dep.activeLink,i.dep.activeLink=i}function C9(e){let i,n=e.depsTail,c=n;for(;c;){const I=c.prevDep;c.version===-1?(c===n&&(n=I),c4(c),csA(c)):i=c,c.dep.activeLink=c.prevActiveLink,c.prevActiveLink=void 0,c=I}e.deps=i,e.depsTail=n}function Z3(e){for(let i=e.deps;i;i=i.nextDep)if(i.dep.version!==i.version||i.dep.computed&&(h9(i.dep.computed)||i.dep.version!==i.version))return!0;return!!e._dirty}function h9(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===_U))return;e.globalVersion=_U;const i=e.dep;if(e.flags|=2,i.version>0&&!e.isSSR&&e.deps&&!Z3(e)){e.flags&=-3;return}const n=La,c=gB;La=e,gB=!0;try{d9(e);const I=e.fn(e._value);(i.version===0||tD(I,e._value))&&(e._value=I,i.version++)}catch(I){throw i.version++,I}finally{La=n,gB=c,C9(e),e.flags&=-3}}function c4(e,i=!1){const{dep:n,prevSub:c,nextSub:I}=e;if(c&&(c.nextSub=I,e.prevSub=void 0),I&&(I.prevSub=c,e.nextSub=void 0),n.subs===e&&(n.subs=c,!c&&n.computed)){n.computed.flags&=-5;for(let C=n.computed.deps;C;C=C.nextDep)c4(C,!0)}!i&&!--n.sc&&n.map&&n.map.delete(n.key)}function csA(e){const{prevDep:i,nextDep:n}=e;i&&(i.nextDep=n,e.prevDep=void 0),n&&(n.prevDep=i,e.nextDep=void 0)}let gB=!0;const B9=[];function hD(){B9.push(gB),gB=!1}function BD(){const e=B9.pop();gB=e===void 0?!0:e}function q8(e){const{cleanup:i}=e;if(e.cleanup=void 0,i){const n=La;La=void 0;try{i()}finally{La=n}}}let _U=0;class lsA{constructor(i,n){this.sub=i,this.dep=n,this.version=n.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class l4{constructor(i){this.computed=i,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0}track(i){if(!La||!gB||La===this.computed)return;let n=this.activeLink;if(n===void 0||n.sub!==La)n=this.activeLink=new lsA(La,this),La.deps?(n.prevDep=La.depsTail,La.depsTail.nextDep=n,La.depsTail=n):La.deps=La.depsTail=n,Q9(n);else if(n.version===-1&&(n.version=this.version,n.nextDep)){const c=n.nextDep;c.prevDep=n.prevDep,n.prevDep&&(n.prevDep.nextDep=c),n.prevDep=La.depsTail,n.nextDep=void 0,La.depsTail.nextDep=n,La.depsTail=n,La.deps===n&&(La.deps=c)}return n}trigger(i){this.version++,_U++,this.notify(i)}notify(i){a4();try{for(let n=this.subs;n;n=n.prevSub)n.sub.notify()&&n.sub.dep.notify()}finally{g4()}}}function Q9(e){if(e.dep.sc++,e.sub.flags&4){const i=e.dep.computed;if(i&&!e.dep.subs){i.flags|=20;for(let c=i.deps;c;c=c.nextDep)Q9(c)}const n=e.dep.subs;n!==e&&(e.prevSub=n,n&&(n.nextSub=e)),e.dep.subs=e}}const UY=new WeakMap,RM=Symbol(""),X3=Symbol(""),TU=Symbol("");function Du(e,i,n){if(gB&&La){let c=UY.get(e);c||UY.set(e,c=new Map);let I=c.get(n);I||(c.set(n,I=new l4),I.map=c,I.key=n),I.track()}}function hm(e,i,n,c,I,C){const m=UY.get(e);if(!m){_U++;return}const R=_=>{_&&_.trigger()};if(a4(),i==="clear")m.forEach(R);else{const _=Ln(e),T=_&&r4(n);if(_&&n==="length"){const b=Number(c);m.forEach((J,gA)=>{(gA==="length"||gA===TU||!ym(gA)&&gA>=b)&&R(J)})}else switch((n!==void 0||m.has(void 0))&&R(m.get(n)),T&&R(m.get(TU)),i){case"add":_?T&&R(m.get("length")):(R(m.get(RM)),tT(e)&&R(m.get(X3)));break;case"delete":_||(R(m.get(RM)),tT(e)&&R(m.get(X3)));break;case"set":tT(e)&&R(m.get(RM));break}}g4()}function IsA(e,i){const n=UY.get(e);return n&&n.get(i)}function T_(e){const i=Lr(e);return i===e?i:(Du(i,"iterate",TU),sh(e)?i:i.map(Su))}function _V(e){return Du(e=Lr(e),"iterate",TU),e}const usA={__proto__:null,[Symbol.iterator](){return A3(this,Symbol.iterator,Su)},concat(...e){return T_(this).concat(...e.map(i=>Ln(i)?T_(i):i))},entries(){return A3(this,"entries",e=>(e[1]=Su(e[1]),e))},every(e,i){return gm(this,"every",e,i,void 0,arguments)},filter(e,i){return gm(this,"filter",e,i,n=>n.map(Su),arguments)},find(e,i){return gm(this,"find",e,i,Su,arguments)},findIndex(e,i){return gm(this,"findIndex",e,i,void 0,arguments)},findLast(e,i){return gm(this,"findLast",e,i,Su,arguments)},findLastIndex(e,i){return gm(this,"findLastIndex",e,i,void 0,arguments)},forEach(e,i){return gm(this,"forEach",e,i,void 0,arguments)},includes(...e){return e3(this,"includes",e)},indexOf(...e){return e3(this,"indexOf",e)},join(e){return T_(this).join(e)},lastIndexOf(...e){return e3(this,"lastIndexOf",e)},map(e,i){return gm(this,"map",e,i,void 0,arguments)},pop(){return TL(this,"pop")},push(...e){return TL(this,"push",e)},reduce(e,...i){return K8(this,"reduce",e,i)},reduceRight(e,...i){return K8(this,"reduceRight",e,i)},shift(){return TL(this,"shift")},some(e,i){return gm(this,"some",e,i,void 0,arguments)},splice(...e){return TL(this,"splice",e)},toReversed(){return T_(this).toReversed()},toSorted(e){return T_(this).toSorted(e)},toSpliced(...e){return T_(this).toSpliced(...e)},unshift(...e){return TL(this,"unshift",e)},values(){return A3(this,"values",Su)}};function A3(e,i,n){const c=_V(e),I=c[i]();return c!==e&&!sh(e)&&(I._next=I.next,I.next=()=>{const C=I._next();return C.value&&(C.value=n(C.value)),C}),I}const EsA=Array.prototype;function gm(e,i,n,c,I,C){const m=_V(e),R=m!==e&&!sh(e),_=m[i];if(_!==EsA[i]){const J=_.apply(e,C);return R?Su(J):J}let T=n;m!==e&&(R?T=function(J,gA){return n.call(this,Su(J),gA,e)}:n.length>2&&(T=function(J,gA){return n.call(this,J,gA,e)}));const b=_.call(m,T,c);return R&&I?I(b):b}function K8(e,i,n,c){const I=_V(e);let C=n;return I!==e&&(sh(e)?n.length>3&&(C=function(m,R,_){return n.call(this,m,R,_,e)}):C=function(m,R,_){return n.call(this,m,Su(R),_,e)}),I[i](C,...c)}function e3(e,i,n){const c=Lr(e);Du(c,"iterate",TU);const I=c[i](...n);return(I===-1||I===!1)&&E4(n[0])?(n[0]=Lr(n[0]),c[i](...n)):I}function TL(e,i,n=[]){hD(),a4();const c=Lr(e)[i].apply(e,n);return g4(),BD(),c}const dsA=o4("__proto__,__v_isRef,__isVue"),p9=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!=="arguments"&&e!=="caller").map(e=>Symbol[e]).filter(ym));function CsA(e){ym(e)||(e=String(e));const i=Lr(this);return Du(i,"has",e),i.hasOwnProperty(e)}class m9{constructor(i=!1,n=!1){this._isReadonly=i,this._isShallow=n}get(i,n,c){if(n==="__v_skip")return i.__v_skip;const I=this._isReadonly,C=this._isShallow;if(n==="__v_isReactive")return!I;if(n==="__v_isReadonly")return I;if(n==="__v_isShallow")return C;if(n==="__v_raw")return c===(I?C?vsA:S9:C?D9:y9).get(i)||Object.getPrototypeOf(i)===Object.getPrototypeOf(c)?i:void 0;const m=Ln(i);if(!I){let _;if(m&&(_=usA[n]))return _;if(n==="hasOwnProperty")return CsA}const R=Reflect.get(i,n,aI(i)?i:c);return(ym(n)?p9.has(n):dsA(n))||(I||Du(i,"get",n),C)?R:aI(R)?m&&r4(n)?R:R.value:Ua(R)?I?mc(R):DM(R):R}}class f9 extends m9{constructor(i=!1){super(!1,i)}set(i,n,c,I){let C=i[n];if(!this._isShallow){const _=PM(C);if(!sh(c)&&!PM(c)&&(C=Lr(C),c=Lr(c)),!Ln(i)&&aI(C)&&!aI(c))return _?!1:(C.value=c,!0)}const m=Ln(i)&&r4(n)?Number(n)e,j1=e=>Reflect.getPrototypeOf(e);function msA(e,i,n){return function(...c){const I=this.__v_raw,C=Lr(I),m=tT(C),R=e==="entries"||e===Symbol.iterator&&m,_=e==="keys"&&m,T=I[e](...c),b=n?$3:i?AW:Su;return!i&&Du(C,"iterate",_?X3:RM),{next(){const{value:J,done:gA}=T.next();return gA?{value:J,done:gA}:{value:R?[b(J[0]),b(J[1])]:b(J),done:gA}},[Symbol.iterator](){return this}}}}function W1(e){return function(...i){return e==="delete"?!1:e==="clear"?void 0:this}}function fsA(e,i){const n={get(I){const C=this.__v_raw,m=Lr(C),R=Lr(I);e||(tD(I,R)&&Du(m,"get",I),Du(m,"get",R));const{has:_}=j1(m),T=i?$3:e?AW:Su;if(_.call(m,I))return T(C.get(I));if(_.call(m,R))return T(C.get(R));C!==m&&C.get(I)},get size(){const I=this.__v_raw;return!e&&Du(Lr(I),"iterate",RM),Reflect.get(I,"size",I)},has(I){const C=this.__v_raw,m=Lr(C),R=Lr(I);return e||(tD(I,R)&&Du(m,"has",I),Du(m,"has",R)),I===R?C.has(I):C.has(I)||C.has(R)},forEach(I,C){const m=this,R=m.__v_raw,_=Lr(R),T=i?$3:e?AW:Su;return!e&&Du(_,"iterate",RM),R.forEach((b,J)=>I.call(C,T(b),T(J),m))}};return cI(n,e?{add:W1("add"),set:W1("set"),delete:W1("delete"),clear:W1("clear")}:{add(I){!i&&!sh(I)&&!PM(I)&&(I=Lr(I));const C=Lr(this);return j1(C).has.call(C,I)||(C.add(I),hm(C,"add",I,I)),this},set(I,C){!i&&!sh(C)&&!PM(C)&&(C=Lr(C));const m=Lr(this),{has:R,get:_}=j1(m);let T=R.call(m,I);T||(I=Lr(I),T=R.call(m,I));const b=_.call(m,I);return m.set(I,C),T?tD(C,b)&&hm(m,"set",I,C):hm(m,"add",I,C),this},delete(I){const C=Lr(this),{has:m,get:R}=j1(C);let _=m.call(C,I);_||(I=Lr(I),_=m.call(C,I)),R&&R.call(C,I);const T=C.delete(I);return _&&hm(C,"delete",I,void 0),T},clear(){const I=Lr(this),C=I.size!==0,m=I.clear();return C&&hm(I,"clear",void 0,void 0),m}}),["keys","values","entries",Symbol.iterator].forEach(I=>{n[I]=msA(I,e,i)}),n}function I4(e,i){const n=fsA(e,i);return(c,I,C)=>I==="__v_isReactive"?!e:I==="__v_isReadonly"?e:I==="__v_raw"?c:Reflect.get($r(n,I)&&I in c?n:c,I,C)}const ysA={get:I4(!1,!1)},DsA={get:I4(!1,!0)},SsA={get:I4(!0,!1)};const y9=new WeakMap,D9=new WeakMap,S9=new WeakMap,vsA=new WeakMap;function MsA(e){switch(e){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function RsA(e){return e.__v_skip||!Object.isExtensible(e)?0:MsA(ZnA(e))}function DM(e){return PM(e)?e:u4(e,!1,BsA,ysA,y9)}function wsA(e){return u4(e,!1,psA,DsA,D9)}function mc(e){return u4(e,!0,QsA,SsA,S9)}function u4(e,i,n,c,I){if(!Ua(e)||e.__v_raw&&!(i&&e.__v_isReactive))return e;const C=I.get(e);if(C)return C;const m=RsA(e);if(m===0)return e;const R=new Proxy(e,m===2?c:n);return I.set(e,R),R}function iT(e){return PM(e)?iT(e.__v_raw):!!(e&&e.__v_isReactive)}function PM(e){return!!(e&&e.__v_isReadonly)}function sh(e){return!!(e&&e.__v_isShallow)}function E4(e){return e?!!e.__v_raw:!1}function Lr(e){const i=e&&e.__v_raw;return i?Lr(i):e}function _sA(e){return!$r(e,"__v_skip")&&Object.isExtensible(e)&&a9(e,"__v_skip",!0),e}const Su=e=>Ua(e)?DM(e):e,AW=e=>Ua(e)?mc(e):e;function aI(e){return e?e.__v_isRef===!0:!1}function Ge(e){return TsA(e,!1)}function TsA(e,i){return aI(e)?e:new NsA(e,i)}class NsA{constructor(i,n){this.dep=new l4,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=n?i:Lr(i),this._value=n?i:Su(i),this.__v_isShallow=n}get value(){return this.dep.track(),this._value}set value(i){const n=this._rawValue,c=this.__v_isShallow||sh(i)||PM(i);i=c?i:Lr(i),tD(i,n)&&(this._rawValue=i,this._value=c?i:Su(i),this.dep.trigger())}}function aA(e){return aI(e)?e.value:e}const GsA={get:(e,i,n)=>i==="__v_raw"?e:aA(Reflect.get(e,i,n)),set:(e,i,n,c)=>{const I=e[i];return aI(I)&&!aI(n)?(I.value=n,!0):Reflect.set(e,i,n,c)}};function v9(e){return iT(e)?e:new Proxy(e,GsA)}function Hn(e){const i=Ln(e)?new Array(e.length):{};for(const n in e)i[n]=M9(e,n);return i}class bsA{constructor(i,n,c){this._object=i,this._key=n,this._defaultValue=c,this.__v_isRef=!0,this._value=void 0}get value(){const i=this._object[this._key];return this._value=i===void 0?this._defaultValue:i}set value(i){this._object[this._key]=i}get dep(){return IsA(Lr(this._object),this._key)}}class ksA{constructor(i){this._getter=i,this.__v_isRef=!0,this.__v_isReadonly=!0,this._value=void 0}get value(){return this._value=this._getter()}}function t3(e,i,n){return aI(e)?e:ls(e)?new ksA(e):Ua(e)&&arguments.length>1?M9(e,i,n):Ge(e)}function M9(e,i,n){const c=e[i];return aI(c)?c:new bsA(e,i,n)}class LsA{constructor(i,n,c){this.fn=i,this.setter=n,this._value=void 0,this.dep=new l4(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=_U-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!n,this.isSSR=c}notify(){if(this.flags|=16,!(this.flags&8)&&La!==this)return E9(this,!0),!0}get value(){const i=this.dep.track();return h9(this),i&&(i.version=this.dep.version),this._value}set value(i){this.setter&&this.setter(i)}}function UsA(e,i,n=!1){let c,I;return ls(e)?c=e:(c=e.get,I=e.set),new LsA(c,I,n)}const z1={},FY=new WeakMap;let hM;function FsA(e,i=!1,n=hM){if(n){let c=FY.get(n);c||FY.set(n,c=[]),c.push(e)}}function OsA(e,i,n=_a){const{immediate:c,deep:I,once:C,scheduler:m,augmentJob:R,call:_}=n,T=HA=>I?HA:sh(HA)||I===!1||I===0?Bm(HA,1):Bm(HA);let b,J,gA,eA,CA=!1,IA=!1;if(aI(e)?(J=()=>e.value,CA=sh(e)):iT(e)?(J=()=>T(e),CA=!0):Ln(e)?(IA=!0,CA=e.some(HA=>iT(HA)||sh(HA)),J=()=>e.map(HA=>{if(aI(HA))return HA.value;if(iT(HA))return T(HA);if(ls(HA))return _?_(HA,2):HA()})):ls(e)?i?J=_?()=>_(e,2):e:J=()=>{if(gA){hD();try{gA()}finally{BD()}}const HA=hM;hM=b;try{return _?_(e,3,[eA]):e(eA)}finally{hM=HA}}:J=GQ,i&&I){const HA=J,se=I===!0?1/0:I;J=()=>Bm(HA(),se)}const oA=gsA(),vA=()=>{b.stop(),oA&&oA.active&&s4(oA.effects,b)};if(C&&i){const HA=i;i=(...se)=>{HA(...se),vA()}}let qA=IA?new Array(e.length).fill(z1):z1;const Ae=HA=>{if(!(!(b.flags&1)||!b.dirty&&!HA))if(i){const se=b.run();if(I||CA||(IA?se.some((WA,Ye)=>tD(WA,qA[Ye])):tD(se,qA))){gA&&gA();const WA=hM;hM=b;try{const Ye=[se,qA===z1?void 0:IA&&qA[0]===z1?[]:qA,eA];_?_(i,3,Ye):i(...Ye),qA=se}finally{hM=WA}}}else b.run()};return R&&R(Ae),b=new I9(J),b.scheduler=m?()=>m(Ae,!1):Ae,eA=HA=>FsA(HA,!1,b),gA=b.onStop=()=>{const HA=FY.get(b);if(HA){if(_)_(HA,4);else for(const se of HA)se();FY.delete(b)}},i?c?Ae(!0):qA=b.run():m?m(Ae.bind(null,!0),!0):b.run(),vA.pause=b.pause.bind(b),vA.resume=b.resume.bind(b),vA.stop=vA,vA}function Bm(e,i=1/0,n){if(i<=0||!Ua(e)||e.__v_skip||(n=n||new Set,n.has(e)))return e;if(n.add(e),i--,aI(e))Bm(e.value,i,n);else if(Ln(e))for(let c=0;c{Bm(c,i,n)});else if(r9(e)){for(const c in e)Bm(e[c],i,n);for(const c of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,c)&&Bm(e[c],i,n)}return e}/** * @vue/runtime-core v3.5.13 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT -**/function AF(e,i,n,c){try{return c?e(...c):e()}catch(I){TV(I,i,n)}}function lB(e,i,n,c){if(ls(e)){const I=AF(e,i,n,c);return I&&n9(I)&&I.catch(C=>{TV(C,i,n)}),I}if(Ln(e)){const I=[];for(let C=0;C>>1,I=fE[c],C=NU(I);C=NU(n)?fE.push(e):fE.splice(xsA(i),0,e),e.flags|=1,w9()}}function w9(){OY||(OY=R9.then(T9))}function YsA(e){Ln(e)?oT.push(...e):Hy&&e.id===-1?Hy.splice(L_+1,0,e):e.flags&1||(oT.push(e),e.flags|=1),w9()}function j8(e,i,n=yQ+1){for(;nNU(n)-NU(c));if(oT.length=0,Hy){Hy.push(...i);return}for(Hy=i,L_=0;L_e.id==null?e.flags&2?-1:1/0:e.id;function T9(e){try{for(yQ=0;yQ{c._d&&aZ(-1);const C=PY(i);let m;try{m=e(...I)}finally{PY(C),c._d&&aZ(1)}return m};return c._n=!0,c._c=!0,c._d=!0,c}function aa(e,i){if(rI===null)return e;const n=UV(rI),c=e.dirs||(e.dirs=[]);for(let I=0;Ie.__isTeleport,lU=e=>e&&(e.disabled||e.disabled===""),W8=e=>e&&(e.defer||e.defer===""),z8=e=>typeof SVGElement<"u"&&e instanceof SVGElement,Z8=e=>typeof MathMLElement=="function"&&e instanceof MathMLElement,eW=(e,i)=>{const n=e&&e.to;return Sg(n)?i?i(n):null:n},b9={name:"Teleport",__isTeleport:!0,process(e,i,n,c,I,C,m,R,_,T){const{mc:b,pc:J,pbc:cA,o:{insert:eA,querySelector:CA,createText:IA,createComment:oA}}=T,vA=lU(i.props);let{shapeFlag:qA,children:Ae,dynamicChildren:HA}=i;if(e==null){const se=i.el=IA(""),WA=i.anchor=IA("");eA(se,n,c),eA(WA,n,c);const Ye=(Pe,we)=>{qA&16&&(I&&I.isCE&&(I.ce._teleportTarget=Pe),b(Ae,Pe,we,I,C,m,R,_))},We=()=>{const Pe=i.target=eW(i.props,CA),we=k9(Pe,i,IA,eA);Pe&&(m!=="svg"&&z8(Pe)?m="svg":m!=="mathml"&&Z8(Pe)&&(m="mathml"),vA||(Ye(Pe,we),pY(i,!1)))};vA&&(Ye(n,WA),pY(i,!0)),W8(i.props)?pE(()=>{We(),i.el.__isMounted=!0},C):We()}else{if(W8(i.props)&&!e.el.__isMounted){pE(()=>{b9.process(e,i,n,c,I,C,m,R,_,T),delete e.el.__isMounted},C);return}i.el=e.el,i.targetStart=e.targetStart;const se=i.anchor=e.anchor,WA=i.target=e.target,Ye=i.targetAnchor=e.targetAnchor,We=lU(e.props),Pe=We?n:WA,we=We?se:Ye;if(m==="svg"||z8(WA)?m="svg":(m==="mathml"||Z8(WA))&&(m="mathml"),HA?(cA(e.dynamicChildren,HA,Pe,I,C,m,R),h4(e,i,!0)):_||J(e,i,Pe,we,I,C,m,R,!1),vA)We?i.props&&e.props&&i.props.to!==e.props.to&&(i.props.to=e.props.to):Z1(i,n,se,T,1);else if((i.props&&i.props.to)!==(e.props&&e.props.to)){const et=i.target=eW(i.props,CA);et&&Z1(i,et,null,T,0)}else We&&Z1(i,WA,Ye,T,1);pY(i,vA)}},remove(e,i,n,{um:c,o:{remove:I}},C){const{shapeFlag:m,children:R,anchor:_,targetStart:T,targetAnchor:b,target:J,props:cA}=e;if(J&&(I(T),I(b)),C&&I(_),m&16){const eA=C||!lU(cA);for(let CA=0;CA{e.isMounted=!0}),Zy(()=>{e.isUnmounting=!0}),e}const KC=[Function,Array],L9={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:KC,onEnter:KC,onAfterEnter:KC,onEnterCancelled:KC,onBeforeLeave:KC,onLeave:KC,onAfterLeave:KC,onLeaveCancelled:KC,onBeforeAppear:KC,onAppear:KC,onAfterAppear:KC,onAppearCancelled:KC},U9=e=>{const i=e.subTree;return i.component?U9(i.component):i},qsA={name:"BaseTransition",props:L9,setup(e,{slots:i}){const n=aX(),c=JsA();return()=>{const I=i.default&&P9(i.default(),!0);if(!I||!I.length)return;const C=F9(I),m=Lr(e),{mode:R}=m;if(c.isLeaving)return i3(C);const _=X8(C);if(!_)return i3(C);let T=tW(_,m,c,n,J=>T=J);_.type!==yE&&GU(_,T);let b=n.subTree&&X8(n.subTree);if(b&&b.type!==yE&&!QM(_,b)&&U9(n).type!==yE){let J=tW(b,m,c,n);if(GU(b,J),R==="out-in"&&_.type!==yE)return c.isLeaving=!0,J.afterLeave=()=>{c.isLeaving=!1,n.job.flags&8||n.update(),delete J.afterLeave,b=void 0},i3(C);R==="in-out"&&_.type!==yE?J.delayLeave=(cA,eA,CA)=>{const IA=O9(c,b);IA[String(b.key)]=b,cA[Jy]=()=>{eA(),cA[Jy]=void 0,delete T.delayedLeave,b=void 0},T.delayedLeave=()=>{CA(),delete T.delayedLeave,b=void 0}}:b=void 0}else b&&(b=void 0);return C}}};function F9(e){let i=e[0];if(e.length>1){for(const n of e)if(n.type!==yE){i=n;break}}return i}const KsA=qsA;function O9(e,i){const{leavingVNodes:n}=e;let c=n.get(i.type);return c||(c=Object.create(null),n.set(i.type,c)),c}function tW(e,i,n,c,I){const{appear:C,mode:m,persisted:R=!1,onBeforeEnter:_,onEnter:T,onAfterEnter:b,onEnterCancelled:J,onBeforeLeave:cA,onLeave:eA,onAfterLeave:CA,onLeaveCancelled:IA,onBeforeAppear:oA,onAppear:vA,onAfterAppear:qA,onAppearCancelled:Ae}=i,HA=String(e.key),se=O9(n,e),WA=(Pe,we)=>{Pe&&lB(Pe,c,9,we)},Ye=(Pe,we)=>{const et=we[1];WA(Pe,we),Ln(Pe)?Pe.every(Xe=>Xe.length<=1)&&et():Pe.length<=1&&et()},We={mode:m,persisted:R,beforeEnter(Pe){let we=_;if(!n.isMounted)if(C)we=oA||_;else return;Pe[Jy]&&Pe[Jy](!0);const et=se[HA];et&&QM(e,et)&&et.el[Jy]&&et.el[Jy](),WA(we,[Pe])},enter(Pe){let we=T,et=b,Xe=J;if(!n.isMounted)if(C)we=vA||T,et=qA||b,Xe=Ae||J;else return;let ae=!1;const Je=Pe[X1]=pt=>{ae||(ae=!0,pt?WA(Xe,[Pe]):WA(et,[Pe]),We.delayedLeave&&We.delayedLeave(),Pe[X1]=void 0)};we?Ye(we,[Pe,Je]):Je()},leave(Pe,we){const et=String(e.key);if(Pe[X1]&&Pe[X1](!0),n.isUnmounting)return we();WA(cA,[Pe]);let Xe=!1;const ae=Pe[Jy]=Je=>{Xe||(Xe=!0,we(),Je?WA(IA,[Pe]):WA(CA,[Pe]),Pe[Jy]=void 0,se[et]===e&&delete se[et])};se[et]=e,eA?Ye(eA,[Pe,ae]):ae()},clone(Pe){const we=tW(Pe,i,n,c,I);return I&&I(we),we}};return We}function i3(e){if(GV(e))return e=cD(e),e.children=null,e}function X8(e){if(!GV(e))return G9(e.type)&&e.children?F9(e.children):e;const{shapeFlag:i,children:n}=e;if(n){if(i&16)return n[0];if(i&32&&ls(n.default))return n.default()}}function GU(e,i){e.shapeFlag&6&&e.component?(e.transition=i,GU(e.component.subTree,i)):e.shapeFlag&128?(e.ssContent.transition=i.clone(e.ssContent),e.ssFallback.transition=i.clone(e.ssFallback)):e.transition=i}function P9(e,i=!1,n){let c=[],I=0;for(let C=0;C1)for(let C=0;CxY(CA,i&&(Ln(i)?i[IA]:i),n,c,I));return}if(nT(c)&&!I){c.shapeFlag&512&&c.type.__asyncResolved&&c.component.subTree.component&&xY(e,i,n,c.component.subTree);return}const C=c.shapeFlag&4?UV(c.component):c.el,m=I?null:C,{i:R,r:_}=e,T=i&&i.r,b=R.refs===_a?R.refs={}:R.refs,J=R.setupState,cA=Lr(J),eA=J===_a?()=>!1:CA=>$r(cA,CA);if(T!=null&&T!==_&&(Sg(T)?(b[T]=null,eA(T)&&(J[T]=null)):aI(T)&&(T.value=null)),ls(_))AF(_,R,12,[m,b]);else{const CA=Sg(_),IA=aI(_);if(CA||IA){const oA=()=>{if(e.f){const vA=CA?eA(_)?J[_]:b[_]:_.value;I?Ln(vA)&&s4(vA,C):Ln(vA)?vA.includes(C)||vA.push(C):CA?(b[_]=[C],eA(_)&&(J[_]=b[_])):(_.value=[C],e.k&&(b[e.k]=_.value))}else CA?(b[_]=m,eA(_)&&(J[_]=m)):IA&&(_.value=m,e.k&&(b[e.k]=m))};m?(oA.id=-1,pE(oA,n)):oA()}}}wV().requestIdleCallback;wV().cancelIdleCallback;const nT=e=>!!e.type.__asyncLoader,GV=e=>e.type.__isKeepAlive;function WsA(e,i){Y9(e,"a",i)}function zsA(e,i){Y9(e,"da",i)}function Y9(e,i,n=qI){const c=e.__wdc||(e.__wdc=()=>{let I=n;for(;I;){if(I.isDeactivated)return;I=I.parent}return e()});if(bV(i,c,n),n){let I=n.parent;for(;I&&I.parent;)GV(I.parent.vnode)&&ZsA(c,i,n,I),I=I.parent}}function ZsA(e,i,n,c){const I=bV(i,e,c,!0);$g(()=>{s4(c[i],I)},n)}function bV(e,i,n=qI,c=!1){if(n){const I=n[e]||(n[e]=[]),C=i.__weh||(i.__weh=(...m)=>{hD();const R=eF(n),_=lB(i,n,e,m);return R(),BD(),_});return c?I.unshift(C):I.push(C),C}}const Dm=e=>(i,n=qI)=>{(!LU||e==="sp")&&bV(e,(...c)=>i(...c),n)},XsA=Dm("bm"),Xg=Dm("m"),$sA=Dm("bu"),ArA=Dm("u"),Zy=Dm("bum"),$g=Dm("um"),erA=Dm("sp"),trA=Dm("rtg"),irA=Dm("rtc");function orA(e,i=qI){bV("ec",e,i)}const nrA="components";function srA(e,i){return arA(nrA,e,!0,i)||e}const rrA=Symbol.for("v-ndc");function arA(e,i,n=!0,c=!1){const I=rI||qI;if(I){const C=I.type;{const R=KrA(C,!1);if(R&&(R===i||R===ch(i)||R===RV(ch(i))))return C}const m=$8(I[e]||C[e],i)||$8(I.appContext[e],i);return!m&&c?C:m}}function $8(e,i){return e&&(e[i]||e[ch(i)]||e[RV(ch(i))])}function da(e,i,n,c){let I;const C=n,m=Ln(e);if(m||Sg(e)){const R=m&&iT(e);let _=!1;R&&(_=!sh(e),e=_V(e)),I=new Array(e.length);for(let T=0,b=e.length;Ti(R,_,void 0,C));else{const R=Object.keys(e);I=new Array(R.length);for(let _=0,T=R.length;_kU(i)?!(i.type===yE||i.type===kn&&!V9(i.children)):!0)?e:null}const iW=e=>e?gX(e)?UV(e):iW(e.parent):null,IU=cI(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>iW(e.parent),$root:e=>iW(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>J9(e),$forceUpdate:e=>e.f||(e.f=()=>{d4(e.update)}),$nextTick:e=>e.n||(e.n=JI.bind(e.proxy)),$watch:e=>wrA.bind(e)}),o3=(e,i)=>e!==_a&&!e.__isScriptSetup&&$r(e,i),grA={get({_:e},i){if(i==="__v_skip")return!0;const{ctx:n,setupState:c,data:I,props:C,accessCache:m,type:R,appContext:_}=e;let T;if(i[0]!=="$"){const eA=m[i];if(eA!==void 0)switch(eA){case 1:return c[i];case 2:return I[i];case 4:return n[i];case 3:return C[i]}else{if(o3(c,i))return m[i]=1,c[i];if(I!==_a&&$r(I,i))return m[i]=2,I[i];if((T=e.propsOptions[0])&&$r(T,i))return m[i]=3,C[i];if(n!==_a&&$r(n,i))return m[i]=4,n[i];oW&&(m[i]=0)}}const b=IU[i];let J,cA;if(b)return i==="$attrs"&&Du(e.attrs,"get",""),b(e);if((J=R.__cssModules)&&(J=J[i]))return J;if(n!==_a&&$r(n,i))return m[i]=4,n[i];if(cA=_.config.globalProperties,$r(cA,i))return cA[i]},set({_:e},i,n){const{data:c,setupState:I,ctx:C}=e;return o3(I,i)?(I[i]=n,!0):c!==_a&&$r(c,i)?(c[i]=n,!0):$r(e.props,i)||i[0]==="$"&&i.slice(1)in e?!1:(C[i]=n,!0)},has({_:{data:e,setupState:i,accessCache:n,ctx:c,appContext:I,propsOptions:C}},m){let R;return!!n[m]||e!==_a&&$r(e,m)||o3(i,m)||(R=C[0])&&$r(R,m)||$r(c,m)||$r(IU,m)||$r(I.config.globalProperties,m)},defineProperty(e,i,n){return n.get!=null?e._.accessCache[i]=0:$r(n,"value")&&this.set(e,i,n.value,null),Reflect.defineProperty(e,i,n)}};function AZ(e){return Ln(e)?e.reduce((i,n)=>(i[n]=null,i),{}):e}let oW=!0;function crA(e){const i=J9(e),n=e.proxy,c=e.ctx;oW=!1,i.beforeCreate&&eZ(i.beforeCreate,e,"bc");const{data:I,computed:C,methods:m,watch:R,provide:_,inject:T,created:b,beforeMount:J,mounted:cA,beforeUpdate:eA,updated:CA,activated:IA,deactivated:oA,beforeDestroy:vA,beforeUnmount:qA,destroyed:Ae,unmounted:HA,render:se,renderTracked:WA,renderTriggered:Ye,errorCaptured:We,serverPrefetch:Pe,expose:we,inheritAttrs:et,components:Xe,directives:ae,filters:Je}=i;if(T&&lrA(T,c,null),m)for(const Pt in m){const ii=m[Pt];ls(ii)&&(c[Pt]=ii.bind(n))}if(I){const Pt=I.call(n,n);Ua(Pt)&&(e.data=DM(Pt))}if(oW=!0,C)for(const Pt in C){const ii=C[Pt],ki=ls(ii)?ii.bind(n,n):ls(ii.get)?ii.get.bind(n,n):GQ,ao=!ls(ii)&&ls(ii.set)?ii.set.bind(n):GQ,Ji=gt({get:ki,set:ao});Object.defineProperty(c,Pt,{enumerable:!0,configurable:!0,get:()=>Ji.value,set:Vi=>Ji.value=Vi})}if(R)for(const Pt in R)H9(R[Pt],c,n,Pt);if(_){const Pt=ls(_)?_.call(n):_;Reflect.ownKeys(Pt).forEach(ii=>{Id(ii,Pt[ii])})}b&&eZ(b,e,"c");function $t(Pt,ii){Ln(ii)?ii.forEach(ki=>Pt(ki.bind(n))):ii&&Pt(ii.bind(n))}if($t(XsA,J),$t(Xg,cA),$t($sA,eA),$t(ArA,CA),$t(WsA,IA),$t(zsA,oA),$t(orA,We),$t(irA,WA),$t(trA,Ye),$t(Zy,qA),$t($g,HA),$t(erA,Pe),Ln(we))if(we.length){const Pt=e.exposed||(e.exposed={});we.forEach(ii=>{Object.defineProperty(Pt,ii,{get:()=>n[ii],set:ki=>n[ii]=ki})})}else e.exposed||(e.exposed={});se&&e.render===GQ&&(e.render=se),et!=null&&(e.inheritAttrs=et),Xe&&(e.components=Xe),ae&&(e.directives=ae),Pe&&x9(e)}function lrA(e,i,n=GQ){Ln(e)&&(e=nW(e));for(const c in e){const I=e[c];let C;Ua(I)?"default"in I?C=jI(I.from||c,I.default,!0):C=jI(I.from||c):C=jI(I),aI(C)?Object.defineProperty(i,c,{enumerable:!0,configurable:!0,get:()=>C.value,set:m=>C.value=m}):i[c]=C}}function eZ(e,i,n){lB(Ln(e)?e.map(c=>c.bind(i.proxy)):e.bind(i.proxy),i,n)}function H9(e,i,n,c){let I=c.includes(".")?iX(n,c):()=>n[c];if(Sg(e)){const C=i[e];ls(C)&&Kn(I,C)}else if(ls(e))Kn(I,e.bind(n));else if(Ua(e))if(Ln(e))e.forEach(C=>H9(C,i,n,c));else{const C=ls(e.handler)?e.handler.bind(n):i[e.handler];ls(C)&&Kn(I,C,e)}}function J9(e){const i=e.type,{mixins:n,extends:c}=i,{mixins:I,optionsCache:C,config:{optionMergeStrategies:m}}=e.appContext,R=C.get(i);let _;return R?_=R:!I.length&&!n&&!c?_=i:(_={},I.length&&I.forEach(T=>YY(_,T,m,!0)),YY(_,i,m)),Ua(i)&&C.set(i,_),_}function YY(e,i,n,c=!1){const{mixins:I,extends:C}=i;C&&YY(e,C,n,!0),I&&I.forEach(m=>YY(e,m,n,!0));for(const m in i)if(!(c&&m==="expose")){const R=IrA[m]||n&&n[m];e[m]=R?R(e[m],i[m]):i[m]}return e}const IrA={data:tZ,props:iZ,emits:iZ,methods:PL,computed:PL,beforeCreate:hE,created:hE,beforeMount:hE,mounted:hE,beforeUpdate:hE,updated:hE,beforeDestroy:hE,beforeUnmount:hE,destroyed:hE,unmounted:hE,activated:hE,deactivated:hE,errorCaptured:hE,serverPrefetch:hE,components:PL,directives:PL,watch:ErA,provide:tZ,inject:urA};function tZ(e,i){return i?e?function(){return cI(ls(e)?e.call(this,this):e,ls(i)?i.call(this,this):i)}:i:e}function urA(e,i){return PL(nW(e),nW(i))}function nW(e){if(Ln(e)){const i={};for(let n=0;n1)return n&&ls(i)?i.call(c&&c.proxy):i}}const K9={},j9=()=>Object.create(K9),W9=e=>Object.getPrototypeOf(e)===K9;function hrA(e,i,n,c=!1){const I={},C=j9();e.propsDefaults=Object.create(null),z9(e,i,I,C);for(const m in e.propsOptions[0])m in I||(I[m]=void 0);n?e.props=c?I:wsA(I):e.type.props?e.props=I:e.props=C,e.attrs=C}function BrA(e,i,n,c){const{props:I,attrs:C,vnode:{patchFlag:m}}=e,R=Lr(I),[_]=e.propsOptions;let T=!1;if((c||m>0)&&!(m&16)){if(m&8){const b=e.vnode.dynamicProps;for(let J=0;J{_=!0;const[cA,eA]=Z9(J,i,!0);cI(m,cA),eA&&R.push(...eA)};!n&&i.mixins.length&&i.mixins.forEach(b),e.extends&&b(e.extends),e.mixins&&e.mixins.forEach(b)}if(!C&&!_)return Ua(e)&&c.set(e,eT),eT;if(Ln(C))for(let b=0;be[0]==="_"||e==="$stable",C4=e=>Ln(e)?e.map(MQ):[MQ(e)],prA=(e,i,n)=>{if(i._n)return i;const c=Yi((...I)=>C4(i(...I)),n);return c._c=!1,c},$9=(e,i,n)=>{const c=e._ctx;for(const I in e){if(X9(I))continue;const C=e[I];if(ls(C))i[I]=prA(I,C,c);else if(C!=null){const m=C4(C);i[I]=()=>m}}},AX=(e,i)=>{const n=C4(i);e.slots.default=()=>n},eX=(e,i,n)=>{for(const c in i)(n||c!=="_")&&(e[c]=i[c])},mrA=(e,i,n)=>{const c=e.slots=j9();if(e.vnode.shapeFlag&32){const I=i._;I?(eX(c,i,n),n&&a9(c,"_",I,!0)):$9(i,c)}else i&&AX(e,i)},frA=(e,i,n)=>{const{vnode:c,slots:I}=e;let C=!0,m=_a;if(c.shapeFlag&32){const R=i._;R?n&&R===1?C=!1:eX(I,i,n):(C=!i.$stable,$9(i,I)),m=i}else i&&(AX(e,i),m={default:1});if(C)for(const R in I)!X9(R)&&m[R]==null&&delete I[R]},pE=LrA;function yrA(e){return DrA(e)}function DrA(e,i){const n=wV();n.__VUE__=!0;const{insert:c,remove:I,patchProp:C,createElement:m,createText:R,createComment:_,setText:T,setElementText:b,parentNode:J,nextSibling:cA,setScopeId:eA=GQ,insertStaticContent:CA}=e,IA=(jA,ue,He,Lt=null,ct=null,Ct=null,ei=void 0,Ht=null,Le=!!ue.dynamicChildren)=>{if(jA===ue)return;jA&&!QM(jA,ue)&&(Lt=oo(jA),Vi(jA,ct,Ct,!0),jA=null),ue.patchFlag===-2&&(Le=!1,ue.dynamicChildren=null);const{type:it,ref:Tt,shapeFlag:Gt}=ue;switch(it){case LV:oA(jA,ue,He,Lt);break;case yE:vA(jA,ue,He,Lt);break;case s3:jA==null&&qA(ue,He,Lt,ei);break;case kn:Xe(jA,ue,He,Lt,ct,Ct,ei,Ht,Le);break;default:Gt&1?se(jA,ue,He,Lt,ct,Ct,ei,Ht,Le):Gt&6?ae(jA,ue,He,Lt,ct,Ct,ei,Ht,Le):(Gt&64||Gt&128)&&it.process(jA,ue,He,Lt,ct,Ct,ei,Ht,Le,Ri)}Tt!=null&&ct&&xY(Tt,jA&&jA.ref,Ct,ue||jA,!ue)},oA=(jA,ue,He,Lt)=>{if(jA==null)c(ue.el=R(ue.children),He,Lt);else{const ct=ue.el=jA.el;ue.children!==jA.children&&T(ct,ue.children)}},vA=(jA,ue,He,Lt)=>{jA==null?c(ue.el=_(ue.children||""),He,Lt):ue.el=jA.el},qA=(jA,ue,He,Lt)=>{[jA.el,jA.anchor]=CA(jA.children,ue,He,Lt,jA.el,jA.anchor)},Ae=({el:jA,anchor:ue},He,Lt)=>{let ct;for(;jA&&jA!==ue;)ct=cA(jA),c(jA,He,Lt),jA=ct;c(ue,He,Lt)},HA=({el:jA,anchor:ue})=>{let He;for(;jA&&jA!==ue;)He=cA(jA),I(jA),jA=He;I(ue)},se=(jA,ue,He,Lt,ct,Ct,ei,Ht,Le)=>{ue.type==="svg"?ei="svg":ue.type==="math"&&(ei="mathml"),jA==null?WA(ue,He,Lt,ct,Ct,ei,Ht,Le):Pe(jA,ue,ct,Ct,ei,Ht,Le)},WA=(jA,ue,He,Lt,ct,Ct,ei,Ht)=>{let Le,it;const{props:Tt,shapeFlag:Gt,transition:Hi,dirs:po}=jA;if(Le=jA.el=m(jA.type,Ct,Tt&&Tt.is,Tt),Gt&8?b(Le,jA.children):Gt&16&&We(jA.children,Le,null,Lt,ct,n3(jA,Ct),ei,Ht),po&&cM(jA,null,Lt,"created"),Ye(Le,jA,jA.scopeId,ei,Lt),Tt){for(const Zi in Tt)Zi!=="value"&&!aU(Zi)&&C(Le,Zi,null,Tt[Zi],Ct,Lt);"value"in Tt&&C(Le,"value",null,Tt.value,Ct),(it=Tt.onVnodeBeforeMount)&&fQ(it,Lt,jA)}po&&cM(jA,null,Lt,"beforeMount");const To=SrA(ct,Hi);To&&Hi.beforeEnter(Le),c(Le,ue,He),((it=Tt&&Tt.onVnodeMounted)||To||po)&&pE(()=>{it&&fQ(it,Lt,jA),To&&Hi.enter(Le),po&&cM(jA,null,Lt,"mounted")},ct)},Ye=(jA,ue,He,Lt,ct)=>{if(He&&eA(jA,He),Lt)for(let Ct=0;Ct{for(let it=Le;it{const Ht=ue.el=jA.el;let{patchFlag:Le,dynamicChildren:it,dirs:Tt}=ue;Le|=jA.patchFlag&16;const Gt=jA.props||_a,Hi=ue.props||_a;let po;if(He&&lM(He,!1),(po=Hi.onVnodeBeforeUpdate)&&fQ(po,He,ue,jA),Tt&&cM(ue,jA,He,"beforeUpdate"),He&&lM(He,!0),(Gt.innerHTML&&Hi.innerHTML==null||Gt.textContent&&Hi.textContent==null)&&b(Ht,""),it?we(jA.dynamicChildren,it,Ht,He,Lt,n3(ue,ct),Ct):ei||ii(jA,ue,Ht,null,He,Lt,n3(ue,ct),Ct,!1),Le>0){if(Le&16)et(Ht,Gt,Hi,He,ct);else if(Le&2&&Gt.class!==Hi.class&&C(Ht,"class",null,Hi.class,ct),Le&4&&C(Ht,"style",Gt.style,Hi.style,ct),Le&8){const To=ue.dynamicProps;for(let Zi=0;Zi{po&&fQ(po,He,ue,jA),Tt&&cM(ue,jA,He,"updated")},Lt)},we=(jA,ue,He,Lt,ct,Ct,ei)=>{for(let Ht=0;Ht{if(ue!==He){if(ue!==_a)for(const Ct in ue)!aU(Ct)&&!(Ct in He)&&C(jA,Ct,ue[Ct],null,ct,Lt);for(const Ct in He){if(aU(Ct))continue;const ei=He[Ct],Ht=ue[Ct];ei!==Ht&&Ct!=="value"&&C(jA,Ct,Ht,ei,ct,Lt)}"value"in He&&C(jA,"value",ue.value,He.value,ct)}},Xe=(jA,ue,He,Lt,ct,Ct,ei,Ht,Le)=>{const it=ue.el=jA?jA.el:R(""),Tt=ue.anchor=jA?jA.anchor:R("");let{patchFlag:Gt,dynamicChildren:Hi,slotScopeIds:po}=ue;po&&(Ht=Ht?Ht.concat(po):po),jA==null?(c(it,He,Lt),c(Tt,He,Lt),We(ue.children||[],He,Tt,ct,Ct,ei,Ht,Le)):Gt>0&&Gt&64&&Hi&&jA.dynamicChildren?(we(jA.dynamicChildren,Hi,He,ct,Ct,ei,Ht),(ue.key!=null||ct&&ue===ct.subTree)&&h4(jA,ue,!0)):ii(jA,ue,He,Tt,ct,Ct,ei,Ht,Le)},ae=(jA,ue,He,Lt,ct,Ct,ei,Ht,Le)=>{ue.slotScopeIds=Ht,jA==null?ue.shapeFlag&512?ct.ctx.activate(ue,He,Lt,ei,Le):Je(ue,He,Lt,ct,Ct,ei,Le):pt(jA,ue,Le)},Je=(jA,ue,He,Lt,ct,Ct,ei)=>{const Ht=jA.component=YrA(jA,Lt,ct);if(GV(jA)&&(Ht.ctx.renderer=Ri),VrA(Ht,!1,ei),Ht.asyncDep){if(ct&&ct.registerDep(Ht,$t,ei),!jA.el){const Le=Ht.subTree=kt(yE);vA(null,Le,ue,He)}}else $t(Ht,jA,ue,He,ct,Ct,ei)},pt=(jA,ue,He)=>{const Lt=ue.component=jA.component;if(brA(jA,ue,He))if(Lt.asyncDep&&!Lt.asyncResolved){Pt(Lt,ue,He);return}else Lt.next=ue,Lt.update();else ue.el=jA.el,Lt.vnode=ue},$t=(jA,ue,He,Lt,ct,Ct,ei)=>{const Ht=()=>{if(jA.isMounted){let{next:Gt,bu:Hi,u:po,parent:To,vnode:Zi}=jA;{const jn=tX(jA);if(jn){Gt&&(Gt.el=Zi.el,Pt(jA,Gt,ei)),jn.asyncDep.then(()=>{jA.isUnmounted||Ht()});return}}let wo=Gt,Cn;lM(jA,!1),Gt?(Gt.el=Zi.el,Pt(jA,Gt,ei)):Gt=Zi,Hi&&QY(Hi),(Cn=Gt.props&&Gt.props.onVnodeBeforeUpdate)&&fQ(Cn,To,Gt,Zi),lM(jA,!0);const an=sZ(jA),Vo=jA.subTree;jA.subTree=an,IA(Vo,an,J(Vo.el),oo(Vo),jA,ct,Ct),Gt.el=an.el,wo===null&&krA(jA,an.el),po&&pE(po,ct),(Cn=Gt.props&&Gt.props.onVnodeUpdated)&&pE(()=>fQ(Cn,To,Gt,Zi),ct)}else{let Gt;const{el:Hi,props:po}=ue,{bm:To,m:Zi,parent:wo,root:Cn,type:an}=jA,Vo=nT(ue);lM(jA,!1),To&&QY(To),!Vo&&(Gt=po&&po.onVnodeBeforeMount)&&fQ(Gt,wo,ue),lM(jA,!0);{Cn.ce&&Cn.ce._injectChildStyle(an);const jn=jA.subTree=sZ(jA);IA(null,jn,He,Lt,jA,ct,Ct),ue.el=jn.el}if(Zi&&pE(Zi,ct),!Vo&&(Gt=po&&po.onVnodeMounted)){const jn=ue;pE(()=>fQ(Gt,wo,jn),ct)}(ue.shapeFlag&256||wo&&nT(wo.vnode)&&wo.vnode.shapeFlag&256)&&jA.a&&pE(jA.a,ct),jA.isMounted=!0,ue=He=Lt=null}};jA.scope.on();const Le=jA.effect=new I9(Ht);jA.scope.off();const it=jA.update=Le.run.bind(Le),Tt=jA.job=Le.runIfDirty.bind(Le);Tt.i=jA,Tt.id=jA.uid,Le.scheduler=()=>d4(Tt),lM(jA,!0),it()},Pt=(jA,ue,He)=>{ue.component=jA;const Lt=jA.vnode.props;jA.vnode=ue,jA.next=null,BrA(jA,ue.props,Lt,He),frA(jA,ue.children,He),hD(),j8(jA),BD()},ii=(jA,ue,He,Lt,ct,Ct,ei,Ht,Le=!1)=>{const it=jA&&jA.children,Tt=jA?jA.shapeFlag:0,Gt=ue.children,{patchFlag:Hi,shapeFlag:po}=ue;if(Hi>0){if(Hi&128){ao(it,Gt,He,Lt,ct,Ct,ei,Ht,Le);return}else if(Hi&256){ki(it,Gt,He,Lt,ct,Ct,ei,Ht,Le);return}}po&8?(Tt&16&&Ro(it,ct,Ct),Gt!==it&&b(He,Gt)):Tt&16?po&16?ao(it,Gt,He,Lt,ct,Ct,ei,Ht,Le):Ro(it,ct,Ct,!0):(Tt&8&&b(He,""),po&16&&We(Gt,He,Lt,ct,Ct,ei,Ht,Le))},ki=(jA,ue,He,Lt,ct,Ct,ei,Ht,Le)=>{jA=jA||eT,ue=ue||eT;const it=jA.length,Tt=ue.length,Gt=Math.min(it,Tt);let Hi;for(Hi=0;HiTt?Ro(jA,ct,Ct,!0,!1,Gt):We(ue,He,Lt,ct,Ct,ei,Ht,Le,Gt)},ao=(jA,ue,He,Lt,ct,Ct,ei,Ht,Le)=>{let it=0;const Tt=ue.length;let Gt=jA.length-1,Hi=Tt-1;for(;it<=Gt&&it<=Hi;){const po=jA[it],To=ue[it]=Le?qy(ue[it]):MQ(ue[it]);if(QM(po,To))IA(po,To,He,null,ct,Ct,ei,Ht,Le);else break;it++}for(;it<=Gt&&it<=Hi;){const po=jA[Gt],To=ue[Hi]=Le?qy(ue[Hi]):MQ(ue[Hi]);if(QM(po,To))IA(po,To,He,null,ct,Ct,ei,Ht,Le);else break;Gt--,Hi--}if(it>Gt){if(it<=Hi){const po=Hi+1,To=poHi)for(;it<=Gt;)Vi(jA[it],ct,Ct,!0),it++;else{const po=it,To=it,Zi=new Map;for(it=To;it<=Hi;it++){const xs=ue[it]=Le?qy(ue[it]):MQ(ue[it]);xs.key!=null&&Zi.set(xs.key,it)}let wo,Cn=0;const an=Hi-To+1;let Vo=!1,jn=0;const vo=new Array(an);for(it=0;it=an){Vi(xs,ct,Ct,!0);continue}let Zs;if(xs.key!=null)Zs=Zi.get(xs.key);else for(wo=To;wo<=Hi;wo++)if(vo[wo-To]===0&&QM(xs,ue[wo])){Zs=wo;break}Zs===void 0?Vi(xs,ct,Ct,!0):(vo[Zs-To]=it+1,Zs>=jn?jn=Zs:Vo=!0,IA(xs,ue[Zs],He,null,ct,Ct,ei,Ht,Le),Cn++)}const mA=Vo?vrA(vo):eT;for(wo=mA.length-1,it=an-1;it>=0;it--){const xs=To+it,Zs=ue[xs],mn=xs+1{const{el:Ct,type:ei,transition:Ht,children:Le,shapeFlag:it}=jA;if(it&6){Ji(jA.component.subTree,ue,He,Lt);return}if(it&128){jA.suspense.move(ue,He,Lt);return}if(it&64){ei.move(jA,ue,He,Ri);return}if(ei===kn){c(Ct,ue,He);for(let Gt=0;GtHt.enter(Ct),ct);else{const{leave:Gt,delayLeave:Hi,afterLeave:po}=Ht,To=()=>c(Ct,ue,He),Zi=()=>{Gt(Ct,()=>{To(),po&&po()})};Hi?Hi(Ct,To,Zi):Zi()}else c(Ct,ue,He)},Vi=(jA,ue,He,Lt=!1,ct=!1)=>{const{type:Ct,props:ei,ref:Ht,children:Le,dynamicChildren:it,shapeFlag:Tt,patchFlag:Gt,dirs:Hi,cacheIndex:po}=jA;if(Gt===-2&&(ct=!1),Ht!=null&&xY(Ht,null,He,jA,!0),po!=null&&(ue.renderCache[po]=void 0),Tt&256){ue.ctx.deactivate(jA);return}const To=Tt&1&&Hi,Zi=!nT(jA);let wo;if(Zi&&(wo=ei&&ei.onVnodeBeforeUnmount)&&fQ(wo,ue,jA),Tt&6)en(jA.component,He,Lt);else{if(Tt&128){jA.suspense.unmount(He,Lt);return}To&&cM(jA,null,ue,"beforeUnmount"),Tt&64?jA.type.remove(jA,ue,He,Ri,Lt):it&&!it.hasOnce&&(Ct!==kn||Gt>0&&Gt&64)?Ro(it,ue,He,!1,!0):(Ct===kn&&Gt&384||!ct&&Tt&16)&&Ro(Le,ue,He),Lt&&wn(jA)}(Zi&&(wo=ei&&ei.onVnodeUnmounted)||To)&&pE(()=>{wo&&fQ(wo,ue,jA),To&&cM(jA,null,ue,"unmounted")},He)},wn=jA=>{const{type:ue,el:He,anchor:Lt,transition:ct}=jA;if(ue===kn){Fi(He,Lt);return}if(ue===s3){HA(jA);return}const Ct=()=>{I(He),ct&&!ct.persisted&&ct.afterLeave&&ct.afterLeave()};if(jA.shapeFlag&1&&ct&&!ct.persisted){const{leave:ei,delayLeave:Ht}=ct,Le=()=>ei(He,Ct);Ht?Ht(jA.el,Ct,Le):Le()}else Ct()},Fi=(jA,ue)=>{let He;for(;jA!==ue;)He=cA(jA),I(jA),jA=He;I(ue)},en=(jA,ue,He)=>{const{bum:Lt,scope:ct,job:Ct,subTree:ei,um:Ht,m:Le,a:it}=jA;nZ(Le),nZ(it),Lt&&QY(Lt),ct.stop(),Ct&&(Ct.flags|=8,Vi(ei,jA,ue,He)),Ht&&pE(Ht,ue),pE(()=>{jA.isUnmounted=!0},ue),ue&&ue.pendingBranch&&!ue.isUnmounted&&jA.asyncDep&&!jA.asyncResolved&&jA.suspenseId===ue.pendingId&&(ue.deps--,ue.deps===0&&ue.resolve())},Ro=(jA,ue,He,Lt=!1,ct=!1,Ct=0)=>{for(let ei=Ct;ei{if(jA.shapeFlag&6)return oo(jA.component.subTree);if(jA.shapeFlag&128)return jA.suspense.next();const ue=cA(jA.anchor||jA.el),He=ue&&ue[N9];return He?cA(He):ue};let Ai=!1;const no=(jA,ue,He)=>{jA==null?ue._vnode&&Vi(ue._vnode,null,null,!0):IA(ue._vnode||null,jA,ue,null,null,null,He),ue._vnode=jA,Ai||(Ai=!0,j8(),_9(),Ai=!1)},Ri={p:IA,um:Vi,m:Ji,r:wn,mt:Je,mc:We,pc:ii,pbc:we,n:oo,o:e};return{render:no,hydrate:void 0,createApp:CrA(no)}}function n3({type:e,props:i},n){return n==="svg"&&e==="foreignObject"||n==="mathml"&&e==="annotation-xml"&&i&&i.encoding&&i.encoding.includes("html")?void 0:n}function lM({effect:e,job:i},n){n?(e.flags|=32,i.flags|=4):(e.flags&=-33,i.flags&=-5)}function SrA(e,i){return(!e||e&&!e.pendingBranch)&&i&&!i.persisted}function h4(e,i,n=!1){const c=e.children,I=i.children;if(Ln(c)&&Ln(I))for(let C=0;C>1,e[n[R]]0&&(i[c]=n[C-1]),n[C]=c)}}for(C=n.length,m=n[C-1];C-- >0;)n[C]=m,m=i[m];return n}function tX(e){const i=e.subTree.component;if(i)return i.asyncDep&&!i.asyncResolved?i:tX(i)}function nZ(e){if(e)for(let i=0;ijI(MrA);function vT(e,i){return B4(e,null,i)}function Kn(e,i,n){return B4(e,i,n)}function B4(e,i,n=_a){const{immediate:c,deep:I,flush:C,once:m}=n,R=cI({},n),_=i&&c||!i&&C!=="post";let T;if(LU){if(C==="sync"){const eA=RrA();T=eA.__watcherHandles||(eA.__watcherHandles=[])}else if(!_){const eA=()=>{};return eA.stop=GQ,eA.resume=GQ,eA.pause=GQ,eA}}const b=qI;R.call=(eA,CA,IA)=>lB(eA,b,CA,IA);let J=!1;C==="post"?R.scheduler=eA=>{pE(eA,b&&b.suspense)}:C!=="sync"&&(J=!0,R.scheduler=(eA,CA)=>{CA?eA():d4(eA)}),R.augmentJob=eA=>{i&&(eA.flags|=4),J&&(eA.flags|=2,b&&(eA.id=b.uid,eA.i=b))};const cA=OsA(e,i,R);return LU&&(T?T.push(cA):_&&cA()),cA}function wrA(e,i,n){const c=this.proxy,I=Sg(e)?e.includes(".")?iX(c,e):()=>c[e]:e.bind(c,c);let C;ls(i)?C=i:(C=i.handler,n=i);const m=eF(this),R=B4(I,C.bind(c),n);return m(),R}function iX(e,i){const n=i.split(".");return()=>{let c=e;for(let I=0;Ii==="modelValue"||i==="model-value"?e.modelModifiers:e[`${i}Modifiers`]||e[`${ch(i)}Modifiers`]||e[`${CD(i)}Modifiers`];function TrA(e,i,...n){if(e.isUnmounted)return;const c=e.vnode.props||_a;let I=n;const C=i.startsWith("update:"),m=C&&_rA(c,i.slice(7));m&&(m.trim&&(I=n.map(b=>Sg(b)?b.trim():b)),m.number&&(I=n.map(z3)));let R,_=c[R=Zj(i)]||c[R=Zj(ch(i))];!_&&C&&(_=c[R=Zj(CD(i))]),_&&lB(_,e,6,I);const T=c[R+"Once"];if(T){if(!e.emitted)e.emitted={};else if(e.emitted[R])return;e.emitted[R]=!0,lB(T,e,6,I)}}function oX(e,i,n=!1){const c=i.emitsCache,I=c.get(e);if(I!==void 0)return I;const C=e.emits;let m={},R=!1;if(!ls(e)){const _=T=>{const b=oX(T,i,!0);b&&(R=!0,cI(m,b))};!n&&i.mixins.length&&i.mixins.forEach(_),e.extends&&_(e.extends),e.mixins&&e.mixins.forEach(_)}return!C&&!R?(Ua(e)&&c.set(e,null),null):(Ln(C)?C.forEach(_=>m[_]=null):cI(m,C),Ua(e)&&c.set(e,m),m)}function kV(e,i){return!e||!SV(i)?!1:(i=i.slice(2).replace(/Once$/,""),$r(e,i[0].toLowerCase()+i.slice(1))||$r(e,CD(i))||$r(e,i))}function sZ(e){const{type:i,vnode:n,proxy:c,withProxy:I,propsOptions:[C],slots:m,attrs:R,emit:_,render:T,renderCache:b,props:J,data:cA,setupState:eA,ctx:CA,inheritAttrs:IA}=e,oA=PY(e);let vA,qA;try{if(n.shapeFlag&4){const HA=I||c,se=HA;vA=MQ(T.call(se,HA,b,J,eA,cA,CA)),qA=R}else{const HA=i;vA=MQ(HA.length>1?HA(J,{attrs:R,slots:m,emit:_}):HA(J,null)),qA=i.props?R:NrA(R)}}catch(HA){uU.length=0,TV(HA,e,1),vA=kt(yE)}let Ae=vA;if(qA&&IA!==!1){const HA=Object.keys(qA),{shapeFlag:se}=Ae;HA.length&&se&7&&(C&&HA.some(n4)&&(qA=GrA(qA,C)),Ae=cD(Ae,qA,!1,!0))}return n.dirs&&(Ae=cD(Ae,null,!1,!0),Ae.dirs=Ae.dirs?Ae.dirs.concat(n.dirs):n.dirs),n.transition&&GU(Ae,n.transition),vA=Ae,PY(oA),vA}const NrA=e=>{let i;for(const n in e)(n==="class"||n==="style"||SV(n))&&((i||(i={}))[n]=e[n]);return i},GrA=(e,i)=>{const n={};for(const c in e)(!n4(c)||!(c.slice(9)in i))&&(n[c]=e[c]);return n};function brA(e,i,n){const{props:c,children:I,component:C}=e,{props:m,children:R,patchFlag:_}=i,T=C.emitsOptions;if(i.dirs||i.transition)return!0;if(n&&_>=0){if(_&1024)return!0;if(_&16)return c?rZ(c,m,T):!!m;if(_&8){const b=i.dynamicProps;for(let J=0;Je.__isSuspense;function LrA(e,i){i&&i.pendingBranch?Ln(e)?i.effects.push(...e):i.effects.push(e):YsA(e)}const kn=Symbol.for("v-fgt"),LV=Symbol.for("v-txt"),yE=Symbol.for("v-cmt"),s3=Symbol.for("v-stc"),uU=[];let sC=null;function xA(e=!1){uU.push(sC=e?null:[])}function UrA(){uU.pop(),sC=uU[uU.length-1]||null}let bU=1;function aZ(e,i=!1){bU+=e,e<0&&sC&&i&&(sC.hasOnce=!0)}function sX(e){return e.dynamicChildren=bU>0?sC||eT:null,UrA(),bU>0&&sC&&sC.push(e),e}function Ce(e,i,n,c,I,C){return sX(UA(e,i,n,c,I,C,!0))}function mi(e,i,n,c,I){return sX(kt(e,i,n,c,I,!0))}function kU(e){return e?e.__v_isVNode===!0:!1}function QM(e,i){return e.type===i.type&&e.key===i.key}const rX=({key:e})=>e??null,mY=({ref:e,ref_key:i,ref_for:n})=>(typeof e=="number"&&(e=""+e),e!=null?Sg(e)||aI(e)||ls(e)?{i:rI,r:e,k:i,f:!!n}:e:null);function UA(e,i=null,n=null,c=0,I=null,C=e===kn?0:1,m=!1,R=!1){const _={__v_isVNode:!0,__v_skip:!0,type:e,props:i,key:i&&rX(i),ref:i&&mY(i),scopeId:NV,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:C,patchFlag:c,dynamicProps:I,dynamicChildren:null,appContext:null,ctx:rI};return R?(Q4(_,n),C&128&&e.normalize(_)):n&&(_.shapeFlag|=Sg(n)?8:16),bU>0&&!m&&sC&&(_.patchFlag>0||C&6)&&_.patchFlag!==32&&sC.push(_),_}const kt=FrA;function FrA(e,i=null,n=null,c=0,I=null,C=!1){if((!e||e===rrA)&&(e=yE),kU(e)){const R=cD(e,i,!0);return n&&Q4(R,n),bU>0&&!C&&sC&&(R.shapeFlag&6?sC[sC.indexOf(e)]=R:sC.push(R)),R.patchFlag=-2,R}if(jrA(e)&&(e=e.__vccOpts),i){i=OrA(i);let{class:R,style:_}=i;R&&!Sg(R)&&(i.class=xi(R)),Ua(_)&&(E4(_)&&!Ln(_)&&(_=cI({},_)),i.style=lr(_))}const m=Sg(e)?1:nX(e)?128:G9(e)?64:Ua(e)?4:ls(e)?2:0;return UA(e,i,n,c,I,m,C,!0)}function OrA(e){return e?E4(e)||W9(e)?cI({},e):e:null}function cD(e,i,n=!1,c=!1){const{props:I,ref:C,patchFlag:m,children:R,transition:_}=e,T=i?rW(I||{},i):I,b={__v_isVNode:!0,__v_skip:!0,type:e.type,props:T,key:T&&rX(T),ref:i&&i.ref?n&&C?Ln(C)?C.concat(mY(i)):[C,mY(i)]:mY(i):C,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:R,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:i&&e.type!==kn?m===-1?16:m|16:m,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:_,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&cD(e.ssContent),ssFallback:e.ssFallback&&cD(e.ssFallback),el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce};return _&&c&&GU(b,_.clone(b)),b}function Ur(e=" ",i=0){return kt(LV,null,e,i)}function ht(e="",i=!1){return i?(xA(),mi(yE,null,e)):kt(yE,null,e)}function MQ(e){return e==null||typeof e=="boolean"?kt(yE):Ln(e)?kt(kn,null,e.slice()):kU(e)?qy(e):kt(LV,null,String(e))}function qy(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:cD(e)}function Q4(e,i){let n=0;const{shapeFlag:c}=e;if(i==null)i=null;else if(Ln(i))n=16;else if(typeof i=="object")if(c&65){const I=i.default;I&&(I._c&&(I._d=!1),Q4(e,I()),I._c&&(I._d=!0));return}else{n=32;const I=i._;!I&&!W9(i)?i._ctx=rI:I===3&&rI&&(rI.slots._===1?i._=1:(i._=2,e.patchFlag|=1024))}else ls(i)?(i={default:i,_ctx:rI},n=32):(i=String(i),c&64?(n=16,i=[Ur(i)]):n=8);e.children=i,e.shapeFlag|=n}function rW(...e){const i={};for(let n=0;nqI||rI;let VY,aW;{const e=wV(),i=(n,c)=>{let I;return(I=e[n])||(I=e[n]=[]),I.push(c),C=>{I.length>1?I.forEach(m=>m(C)):I[0](C)}};VY=i("__VUE_INSTANCE_SETTERS__",n=>qI=n),aW=i("__VUE_SSR_SETTERS__",n=>LU=n)}const eF=e=>{const i=qI;return VY(e),e.scope.on(),()=>{e.scope.off(),VY(i)}},gZ=()=>{qI&&qI.scope.off(),VY(null)};function gX(e){return e.vnode.shapeFlag&4}let LU=!1;function VrA(e,i=!1,n=!1){i&&aW(i);const{props:c,children:I}=e.vnode,C=gX(e);hrA(e,c,C,i),mrA(e,I,n);const m=C?HrA(e,i):void 0;return i&&aW(!1),m}function HrA(e,i){const n=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,grA);const{setup:c}=n;if(c){hD();const I=e.setupContext=c.length>1?qrA(e):null,C=eF(e),m=AF(c,e,0,[e.props,I]),R=n9(m);if(BD(),C(),(R||e.sp)&&!nT(e)&&x9(e),R){if(m.then(gZ,gZ),i)return m.then(_=>{cZ(e,_)}).catch(_=>{TV(_,e,0)});e.asyncDep=m}else cZ(e,m)}else cX(e)}function cZ(e,i,n){ls(i)?e.type.__ssrInlineRender?e.ssrRender=i:e.render=i:Ua(i)&&(e.setupState=v9(i)),cX(e)}function cX(e,i,n){const c=e.type;e.render||(e.render=c.render||GQ);{const I=eF(e);hD();try{crA(e)}finally{BD(),I()}}}const JrA={get(e,i){return Du(e,"get",""),e[i]}};function qrA(e){const i=n=>{e.exposed=n||{}};return{attrs:new Proxy(e.attrs,JrA),slots:e.slots,emit:e.emit,expose:i}}function UV(e){return e.exposed?e.exposeProxy||(e.exposeProxy=new Proxy(v9(_sA(e.exposed)),{get(i,n){if(n in i)return i[n];if(n in IU)return IU[n](e)},has(i,n){return n in i||n in IU}})):e.proxy}function KrA(e,i=!0){return ls(e)?e.displayName||e.name:e.name||i&&e.__name}function jrA(e){return ls(e)&&"__vccOpts"in e}const gt=(e,i)=>UsA(e,i,LU);function WrA(e,i,n){const c=arguments.length;return c===2?Ua(i)&&!Ln(i)?kU(i)?kt(e,null,[i]):kt(e,i):kt(e,null,i):(c>3?n=Array.prototype.slice.call(arguments,2):c===3&&kU(n)&&(n=[n]),kt(e,i,n))}const gW="3.5.13";/** +**/function AF(e,i,n,c){try{return c?e(...c):e()}catch(I){TV(I,i,n)}}function lB(e,i,n,c){if(ls(e)){const I=AF(e,i,n,c);return I&&n9(I)&&I.catch(C=>{TV(C,i,n)}),I}if(Ln(e)){const I=[];for(let C=0;C>>1,I=fE[c],C=NU(I);C=NU(n)?fE.push(e):fE.splice(xsA(i),0,e),e.flags|=1,w9()}}function w9(){OY||(OY=R9.then(T9))}function YsA(e){Ln(e)?oT.push(...e):Hy&&e.id===-1?Hy.splice(L_+1,0,e):e.flags&1||(oT.push(e),e.flags|=1),w9()}function j8(e,i,n=yQ+1){for(;nNU(n)-NU(c));if(oT.length=0,Hy){Hy.push(...i);return}for(Hy=i,L_=0;L_e.id==null?e.flags&2?-1:1/0:e.id;function T9(e){try{for(yQ=0;yQ{c._d&&aZ(-1);const C=PY(i);let m;try{m=e(...I)}finally{PY(C),c._d&&aZ(1)}return m};return c._n=!0,c._c=!0,c._d=!0,c}function aa(e,i){if(rI===null)return e;const n=UV(rI),c=e.dirs||(e.dirs=[]);for(let I=0;Ie.__isTeleport,lU=e=>e&&(e.disabled||e.disabled===""),W8=e=>e&&(e.defer||e.defer===""),z8=e=>typeof SVGElement<"u"&&e instanceof SVGElement,Z8=e=>typeof MathMLElement=="function"&&e instanceof MathMLElement,eW=(e,i)=>{const n=e&&e.to;return vg(n)?i?i(n):null:n},b9={name:"Teleport",__isTeleport:!0,process(e,i,n,c,I,C,m,R,_,T){const{mc:b,pc:J,pbc:gA,o:{insert:eA,querySelector:CA,createText:IA,createComment:oA}}=T,vA=lU(i.props);let{shapeFlag:qA,children:Ae,dynamicChildren:HA}=i;if(e==null){const se=i.el=IA(""),WA=i.anchor=IA("");eA(se,n,c),eA(WA,n,c);const Ye=(Pe,we)=>{qA&16&&(I&&I.isCE&&(I.ce._teleportTarget=Pe),b(Ae,Pe,we,I,C,m,R,_))},We=()=>{const Pe=i.target=eW(i.props,CA),we=k9(Pe,i,IA,eA);Pe&&(m!=="svg"&&z8(Pe)?m="svg":m!=="mathml"&&Z8(Pe)&&(m="mathml"),vA||(Ye(Pe,we),pY(i,!1)))};vA&&(Ye(n,WA),pY(i,!0)),W8(i.props)?pE(()=>{We(),i.el.__isMounted=!0},C):We()}else{if(W8(i.props)&&!e.el.__isMounted){pE(()=>{b9.process(e,i,n,c,I,C,m,R,_,T),delete e.el.__isMounted},C);return}i.el=e.el,i.targetStart=e.targetStart;const se=i.anchor=e.anchor,WA=i.target=e.target,Ye=i.targetAnchor=e.targetAnchor,We=lU(e.props),Pe=We?n:WA,we=We?se:Ye;if(m==="svg"||z8(WA)?m="svg":(m==="mathml"||Z8(WA))&&(m="mathml"),HA?(gA(e.dynamicChildren,HA,Pe,I,C,m,R),h4(e,i,!0)):_||J(e,i,Pe,we,I,C,m,R,!1),vA)We?i.props&&e.props&&i.props.to!==e.props.to&&(i.props.to=e.props.to):Z1(i,n,se,T,1);else if((i.props&&i.props.to)!==(e.props&&e.props.to)){const et=i.target=eW(i.props,CA);et&&Z1(i,et,null,T,0)}else We&&Z1(i,WA,Ye,T,1);pY(i,vA)}},remove(e,i,n,{um:c,o:{remove:I}},C){const{shapeFlag:m,children:R,anchor:_,targetStart:T,targetAnchor:b,target:J,props:gA}=e;if(J&&(I(T),I(b)),C&&I(_),m&16){const eA=C||!lU(gA);for(let CA=0;CA{e.isMounted=!0}),Zy(()=>{e.isUnmounting=!0}),e}const KC=[Function,Array],L9={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:KC,onEnter:KC,onAfterEnter:KC,onEnterCancelled:KC,onBeforeLeave:KC,onLeave:KC,onAfterLeave:KC,onLeaveCancelled:KC,onBeforeAppear:KC,onAppear:KC,onAfterAppear:KC,onAppearCancelled:KC},U9=e=>{const i=e.subTree;return i.component?U9(i.component):i},qsA={name:"BaseTransition",props:L9,setup(e,{slots:i}){const n=aX(),c=JsA();return()=>{const I=i.default&&P9(i.default(),!0);if(!I||!I.length)return;const C=F9(I),m=Lr(e),{mode:R}=m;if(c.isLeaving)return i3(C);const _=X8(C);if(!_)return i3(C);let T=tW(_,m,c,n,J=>T=J);_.type!==yE&&GU(_,T);let b=n.subTree&&X8(n.subTree);if(b&&b.type!==yE&&!QM(_,b)&&U9(n).type!==yE){let J=tW(b,m,c,n);if(GU(b,J),R==="out-in"&&_.type!==yE)return c.isLeaving=!0,J.afterLeave=()=>{c.isLeaving=!1,n.job.flags&8||n.update(),delete J.afterLeave,b=void 0},i3(C);R==="in-out"&&_.type!==yE?J.delayLeave=(gA,eA,CA)=>{const IA=O9(c,b);IA[String(b.key)]=b,gA[Jy]=()=>{eA(),gA[Jy]=void 0,delete T.delayedLeave,b=void 0},T.delayedLeave=()=>{CA(),delete T.delayedLeave,b=void 0}}:b=void 0}else b&&(b=void 0);return C}}};function F9(e){let i=e[0];if(e.length>1){for(const n of e)if(n.type!==yE){i=n;break}}return i}const KsA=qsA;function O9(e,i){const{leavingVNodes:n}=e;let c=n.get(i.type);return c||(c=Object.create(null),n.set(i.type,c)),c}function tW(e,i,n,c,I){const{appear:C,mode:m,persisted:R=!1,onBeforeEnter:_,onEnter:T,onAfterEnter:b,onEnterCancelled:J,onBeforeLeave:gA,onLeave:eA,onAfterLeave:CA,onLeaveCancelled:IA,onBeforeAppear:oA,onAppear:vA,onAfterAppear:qA,onAppearCancelled:Ae}=i,HA=String(e.key),se=O9(n,e),WA=(Pe,we)=>{Pe&&lB(Pe,c,9,we)},Ye=(Pe,we)=>{const et=we[1];WA(Pe,we),Ln(Pe)?Pe.every(Xe=>Xe.length<=1)&&et():Pe.length<=1&&et()},We={mode:m,persisted:R,beforeEnter(Pe){let we=_;if(!n.isMounted)if(C)we=oA||_;else return;Pe[Jy]&&Pe[Jy](!0);const et=se[HA];et&&QM(e,et)&&et.el[Jy]&&et.el[Jy](),WA(we,[Pe])},enter(Pe){let we=T,et=b,Xe=J;if(!n.isMounted)if(C)we=vA||T,et=qA||b,Xe=Ae||J;else return;let ae=!1;const Je=Pe[X1]=pt=>{ae||(ae=!0,pt?WA(Xe,[Pe]):WA(et,[Pe]),We.delayedLeave&&We.delayedLeave(),Pe[X1]=void 0)};we?Ye(we,[Pe,Je]):Je()},leave(Pe,we){const et=String(e.key);if(Pe[X1]&&Pe[X1](!0),n.isUnmounting)return we();WA(gA,[Pe]);let Xe=!1;const ae=Pe[Jy]=Je=>{Xe||(Xe=!0,we(),Je?WA(IA,[Pe]):WA(CA,[Pe]),Pe[Jy]=void 0,se[et]===e&&delete se[et])};se[et]=e,eA?Ye(eA,[Pe,ae]):ae()},clone(Pe){const we=tW(Pe,i,n,c,I);return I&&I(we),we}};return We}function i3(e){if(GV(e))return e=cD(e),e.children=null,e}function X8(e){if(!GV(e))return G9(e.type)&&e.children?F9(e.children):e;const{shapeFlag:i,children:n}=e;if(n){if(i&16)return n[0];if(i&32&&ls(n.default))return n.default()}}function GU(e,i){e.shapeFlag&6&&e.component?(e.transition=i,GU(e.component.subTree,i)):e.shapeFlag&128?(e.ssContent.transition=i.clone(e.ssContent),e.ssFallback.transition=i.clone(e.ssFallback)):e.transition=i}function P9(e,i=!1,n){let c=[],I=0;for(let C=0;C1)for(let C=0;CxY(CA,i&&(Ln(i)?i[IA]:i),n,c,I));return}if(nT(c)&&!I){c.shapeFlag&512&&c.type.__asyncResolved&&c.component.subTree.component&&xY(e,i,n,c.component.subTree);return}const C=c.shapeFlag&4?UV(c.component):c.el,m=I?null:C,{i:R,r:_}=e,T=i&&i.r,b=R.refs===_a?R.refs={}:R.refs,J=R.setupState,gA=Lr(J),eA=J===_a?()=>!1:CA=>$r(gA,CA);if(T!=null&&T!==_&&(vg(T)?(b[T]=null,eA(T)&&(J[T]=null)):aI(T)&&(T.value=null)),ls(_))AF(_,R,12,[m,b]);else{const CA=vg(_),IA=aI(_);if(CA||IA){const oA=()=>{if(e.f){const vA=CA?eA(_)?J[_]:b[_]:_.value;I?Ln(vA)&&s4(vA,C):Ln(vA)?vA.includes(C)||vA.push(C):CA?(b[_]=[C],eA(_)&&(J[_]=b[_])):(_.value=[C],e.k&&(b[e.k]=_.value))}else CA?(b[_]=m,eA(_)&&(J[_]=m)):IA&&(_.value=m,e.k&&(b[e.k]=m))};m?(oA.id=-1,pE(oA,n)):oA()}}}wV().requestIdleCallback;wV().cancelIdleCallback;const nT=e=>!!e.type.__asyncLoader,GV=e=>e.type.__isKeepAlive;function WsA(e,i){Y9(e,"a",i)}function zsA(e,i){Y9(e,"da",i)}function Y9(e,i,n=qI){const c=e.__wdc||(e.__wdc=()=>{let I=n;for(;I;){if(I.isDeactivated)return;I=I.parent}return e()});if(bV(i,c,n),n){let I=n.parent;for(;I&&I.parent;)GV(I.parent.vnode)&&ZsA(c,i,n,I),I=I.parent}}function ZsA(e,i,n,c){const I=bV(i,e,c,!0);$g(()=>{s4(c[i],I)},n)}function bV(e,i,n=qI,c=!1){if(n){const I=n[e]||(n[e]=[]),C=i.__weh||(i.__weh=(...m)=>{hD();const R=eF(n),_=lB(i,n,e,m);return R(),BD(),_});return c?I.unshift(C):I.push(C),C}}const Dm=e=>(i,n=qI)=>{(!LU||e==="sp")&&bV(e,(...c)=>i(...c),n)},XsA=Dm("bm"),Xg=Dm("m"),$sA=Dm("bu"),ArA=Dm("u"),Zy=Dm("bum"),$g=Dm("um"),erA=Dm("sp"),trA=Dm("rtg"),irA=Dm("rtc");function orA(e,i=qI){bV("ec",e,i)}const nrA="components";function srA(e,i){return arA(nrA,e,!0,i)||e}const rrA=Symbol.for("v-ndc");function arA(e,i,n=!0,c=!1){const I=rI||qI;if(I){const C=I.type;{const R=KrA(C,!1);if(R&&(R===i||R===ch(i)||R===RV(ch(i))))return C}const m=$8(I[e]||C[e],i)||$8(I.appContext[e],i);return!m&&c?C:m}}function $8(e,i){return e&&(e[i]||e[ch(i)]||e[RV(ch(i))])}function da(e,i,n,c){let I;const C=n,m=Ln(e);if(m||vg(e)){const R=m&&iT(e);let _=!1;R&&(_=!sh(e),e=_V(e)),I=new Array(e.length);for(let T=0,b=e.length;Ti(R,_,void 0,C));else{const R=Object.keys(e);I=new Array(R.length);for(let _=0,T=R.length;_kU(i)?!(i.type===yE||i.type===kn&&!V9(i.children)):!0)?e:null}const iW=e=>e?gX(e)?UV(e):iW(e.parent):null,IU=cI(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>iW(e.parent),$root:e=>iW(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>J9(e),$forceUpdate:e=>e.f||(e.f=()=>{d4(e.update)}),$nextTick:e=>e.n||(e.n=JI.bind(e.proxy)),$watch:e=>wrA.bind(e)}),o3=(e,i)=>e!==_a&&!e.__isScriptSetup&&$r(e,i),grA={get({_:e},i){if(i==="__v_skip")return!0;const{ctx:n,setupState:c,data:I,props:C,accessCache:m,type:R,appContext:_}=e;let T;if(i[0]!=="$"){const eA=m[i];if(eA!==void 0)switch(eA){case 1:return c[i];case 2:return I[i];case 4:return n[i];case 3:return C[i]}else{if(o3(c,i))return m[i]=1,c[i];if(I!==_a&&$r(I,i))return m[i]=2,I[i];if((T=e.propsOptions[0])&&$r(T,i))return m[i]=3,C[i];if(n!==_a&&$r(n,i))return m[i]=4,n[i];oW&&(m[i]=0)}}const b=IU[i];let J,gA;if(b)return i==="$attrs"&&Du(e.attrs,"get",""),b(e);if((J=R.__cssModules)&&(J=J[i]))return J;if(n!==_a&&$r(n,i))return m[i]=4,n[i];if(gA=_.config.globalProperties,$r(gA,i))return gA[i]},set({_:e},i,n){const{data:c,setupState:I,ctx:C}=e;return o3(I,i)?(I[i]=n,!0):c!==_a&&$r(c,i)?(c[i]=n,!0):$r(e.props,i)||i[0]==="$"&&i.slice(1)in e?!1:(C[i]=n,!0)},has({_:{data:e,setupState:i,accessCache:n,ctx:c,appContext:I,propsOptions:C}},m){let R;return!!n[m]||e!==_a&&$r(e,m)||o3(i,m)||(R=C[0])&&$r(R,m)||$r(c,m)||$r(IU,m)||$r(I.config.globalProperties,m)},defineProperty(e,i,n){return n.get!=null?e._.accessCache[i]=0:$r(n,"value")&&this.set(e,i,n.value,null),Reflect.defineProperty(e,i,n)}};function AZ(e){return Ln(e)?e.reduce((i,n)=>(i[n]=null,i),{}):e}let oW=!0;function crA(e){const i=J9(e),n=e.proxy,c=e.ctx;oW=!1,i.beforeCreate&&eZ(i.beforeCreate,e,"bc");const{data:I,computed:C,methods:m,watch:R,provide:_,inject:T,created:b,beforeMount:J,mounted:gA,beforeUpdate:eA,updated:CA,activated:IA,deactivated:oA,beforeDestroy:vA,beforeUnmount:qA,destroyed:Ae,unmounted:HA,render:se,renderTracked:WA,renderTriggered:Ye,errorCaptured:We,serverPrefetch:Pe,expose:we,inheritAttrs:et,components:Xe,directives:ae,filters:Je}=i;if(T&&lrA(T,c,null),m)for(const Pt in m){const ii=m[Pt];ls(ii)&&(c[Pt]=ii.bind(n))}if(I){const Pt=I.call(n,n);Ua(Pt)&&(e.data=DM(Pt))}if(oW=!0,C)for(const Pt in C){const ii=C[Pt],ki=ls(ii)?ii.bind(n,n):ls(ii.get)?ii.get.bind(n,n):GQ,ao=!ls(ii)&&ls(ii.set)?ii.set.bind(n):GQ,Ji=gt({get:ki,set:ao});Object.defineProperty(c,Pt,{enumerable:!0,configurable:!0,get:()=>Ji.value,set:Vi=>Ji.value=Vi})}if(R)for(const Pt in R)H9(R[Pt],c,n,Pt);if(_){const Pt=ls(_)?_.call(n):_;Reflect.ownKeys(Pt).forEach(ii=>{Id(ii,Pt[ii])})}b&&eZ(b,e,"c");function $t(Pt,ii){Ln(ii)?ii.forEach(ki=>Pt(ki.bind(n))):ii&&Pt(ii.bind(n))}if($t(XsA,J),$t(Xg,gA),$t($sA,eA),$t(ArA,CA),$t(WsA,IA),$t(zsA,oA),$t(orA,We),$t(irA,WA),$t(trA,Ye),$t(Zy,qA),$t($g,HA),$t(erA,Pe),Ln(we))if(we.length){const Pt=e.exposed||(e.exposed={});we.forEach(ii=>{Object.defineProperty(Pt,ii,{get:()=>n[ii],set:ki=>n[ii]=ki})})}else e.exposed||(e.exposed={});se&&e.render===GQ&&(e.render=se),et!=null&&(e.inheritAttrs=et),Xe&&(e.components=Xe),ae&&(e.directives=ae),Pe&&x9(e)}function lrA(e,i,n=GQ){Ln(e)&&(e=nW(e));for(const c in e){const I=e[c];let C;Ua(I)?"default"in I?C=jI(I.from||c,I.default,!0):C=jI(I.from||c):C=jI(I),aI(C)?Object.defineProperty(i,c,{enumerable:!0,configurable:!0,get:()=>C.value,set:m=>C.value=m}):i[c]=C}}function eZ(e,i,n){lB(Ln(e)?e.map(c=>c.bind(i.proxy)):e.bind(i.proxy),i,n)}function H9(e,i,n,c){let I=c.includes(".")?iX(n,c):()=>n[c];if(vg(e)){const C=i[e];ls(C)&&Kn(I,C)}else if(ls(e))Kn(I,e.bind(n));else if(Ua(e))if(Ln(e))e.forEach(C=>H9(C,i,n,c));else{const C=ls(e.handler)?e.handler.bind(n):i[e.handler];ls(C)&&Kn(I,C,e)}}function J9(e){const i=e.type,{mixins:n,extends:c}=i,{mixins:I,optionsCache:C,config:{optionMergeStrategies:m}}=e.appContext,R=C.get(i);let _;return R?_=R:!I.length&&!n&&!c?_=i:(_={},I.length&&I.forEach(T=>YY(_,T,m,!0)),YY(_,i,m)),Ua(i)&&C.set(i,_),_}function YY(e,i,n,c=!1){const{mixins:I,extends:C}=i;C&&YY(e,C,n,!0),I&&I.forEach(m=>YY(e,m,n,!0));for(const m in i)if(!(c&&m==="expose")){const R=IrA[m]||n&&n[m];e[m]=R?R(e[m],i[m]):i[m]}return e}const IrA={data:tZ,props:iZ,emits:iZ,methods:PL,computed:PL,beforeCreate:hE,created:hE,beforeMount:hE,mounted:hE,beforeUpdate:hE,updated:hE,beforeDestroy:hE,beforeUnmount:hE,destroyed:hE,unmounted:hE,activated:hE,deactivated:hE,errorCaptured:hE,serverPrefetch:hE,components:PL,directives:PL,watch:ErA,provide:tZ,inject:urA};function tZ(e,i){return i?e?function(){return cI(ls(e)?e.call(this,this):e,ls(i)?i.call(this,this):i)}:i:e}function urA(e,i){return PL(nW(e),nW(i))}function nW(e){if(Ln(e)){const i={};for(let n=0;n1)return n&&ls(i)?i.call(c&&c.proxy):i}}const K9={},j9=()=>Object.create(K9),W9=e=>Object.getPrototypeOf(e)===K9;function hrA(e,i,n,c=!1){const I={},C=j9();e.propsDefaults=Object.create(null),z9(e,i,I,C);for(const m in e.propsOptions[0])m in I||(I[m]=void 0);n?e.props=c?I:wsA(I):e.type.props?e.props=I:e.props=C,e.attrs=C}function BrA(e,i,n,c){const{props:I,attrs:C,vnode:{patchFlag:m}}=e,R=Lr(I),[_]=e.propsOptions;let T=!1;if((c||m>0)&&!(m&16)){if(m&8){const b=e.vnode.dynamicProps;for(let J=0;J{_=!0;const[gA,eA]=Z9(J,i,!0);cI(m,gA),eA&&R.push(...eA)};!n&&i.mixins.length&&i.mixins.forEach(b),e.extends&&b(e.extends),e.mixins&&e.mixins.forEach(b)}if(!C&&!_)return Ua(e)&&c.set(e,eT),eT;if(Ln(C))for(let b=0;be[0]==="_"||e==="$stable",C4=e=>Ln(e)?e.map(MQ):[MQ(e)],prA=(e,i,n)=>{if(i._n)return i;const c=Yi((...I)=>C4(i(...I)),n);return c._c=!1,c},$9=(e,i,n)=>{const c=e._ctx;for(const I in e){if(X9(I))continue;const C=e[I];if(ls(C))i[I]=prA(I,C,c);else if(C!=null){const m=C4(C);i[I]=()=>m}}},AX=(e,i)=>{const n=C4(i);e.slots.default=()=>n},eX=(e,i,n)=>{for(const c in i)(n||c!=="_")&&(e[c]=i[c])},mrA=(e,i,n)=>{const c=e.slots=j9();if(e.vnode.shapeFlag&32){const I=i._;I?(eX(c,i,n),n&&a9(c,"_",I,!0)):$9(i,c)}else i&&AX(e,i)},frA=(e,i,n)=>{const{vnode:c,slots:I}=e;let C=!0,m=_a;if(c.shapeFlag&32){const R=i._;R?n&&R===1?C=!1:eX(I,i,n):(C=!i.$stable,$9(i,I)),m=i}else i&&(AX(e,i),m={default:1});if(C)for(const R in I)!X9(R)&&m[R]==null&&delete I[R]},pE=LrA;function yrA(e){return DrA(e)}function DrA(e,i){const n=wV();n.__VUE__=!0;const{insert:c,remove:I,patchProp:C,createElement:m,createText:R,createComment:_,setText:T,setElementText:b,parentNode:J,nextSibling:gA,setScopeId:eA=GQ,insertStaticContent:CA}=e,IA=(jA,ue,He,Lt=null,ct=null,Ct=null,ei=void 0,Ht=null,Le=!!ue.dynamicChildren)=>{if(jA===ue)return;jA&&!QM(jA,ue)&&(Lt=oo(jA),Vi(jA,ct,Ct,!0),jA=null),ue.patchFlag===-2&&(Le=!1,ue.dynamicChildren=null);const{type:it,ref:Tt,shapeFlag:Gt}=ue;switch(it){case LV:oA(jA,ue,He,Lt);break;case yE:vA(jA,ue,He,Lt);break;case s3:jA==null&&qA(ue,He,Lt,ei);break;case kn:Xe(jA,ue,He,Lt,ct,Ct,ei,Ht,Le);break;default:Gt&1?se(jA,ue,He,Lt,ct,Ct,ei,Ht,Le):Gt&6?ae(jA,ue,He,Lt,ct,Ct,ei,Ht,Le):(Gt&64||Gt&128)&&it.process(jA,ue,He,Lt,ct,Ct,ei,Ht,Le,Ri)}Tt!=null&&ct&&xY(Tt,jA&&jA.ref,Ct,ue||jA,!ue)},oA=(jA,ue,He,Lt)=>{if(jA==null)c(ue.el=R(ue.children),He,Lt);else{const ct=ue.el=jA.el;ue.children!==jA.children&&T(ct,ue.children)}},vA=(jA,ue,He,Lt)=>{jA==null?c(ue.el=_(ue.children||""),He,Lt):ue.el=jA.el},qA=(jA,ue,He,Lt)=>{[jA.el,jA.anchor]=CA(jA.children,ue,He,Lt,jA.el,jA.anchor)},Ae=({el:jA,anchor:ue},He,Lt)=>{let ct;for(;jA&&jA!==ue;)ct=gA(jA),c(jA,He,Lt),jA=ct;c(ue,He,Lt)},HA=({el:jA,anchor:ue})=>{let He;for(;jA&&jA!==ue;)He=gA(jA),I(jA),jA=He;I(ue)},se=(jA,ue,He,Lt,ct,Ct,ei,Ht,Le)=>{ue.type==="svg"?ei="svg":ue.type==="math"&&(ei="mathml"),jA==null?WA(ue,He,Lt,ct,Ct,ei,Ht,Le):Pe(jA,ue,ct,Ct,ei,Ht,Le)},WA=(jA,ue,He,Lt,ct,Ct,ei,Ht)=>{let Le,it;const{props:Tt,shapeFlag:Gt,transition:Hi,dirs:po}=jA;if(Le=jA.el=m(jA.type,Ct,Tt&&Tt.is,Tt),Gt&8?b(Le,jA.children):Gt&16&&We(jA.children,Le,null,Lt,ct,n3(jA,Ct),ei,Ht),po&&cM(jA,null,Lt,"created"),Ye(Le,jA,jA.scopeId,ei,Lt),Tt){for(const Zi in Tt)Zi!=="value"&&!aU(Zi)&&C(Le,Zi,null,Tt[Zi],Ct,Lt);"value"in Tt&&C(Le,"value",null,Tt.value,Ct),(it=Tt.onVnodeBeforeMount)&&fQ(it,Lt,jA)}po&&cM(jA,null,Lt,"beforeMount");const To=SrA(ct,Hi);To&&Hi.beforeEnter(Le),c(Le,ue,He),((it=Tt&&Tt.onVnodeMounted)||To||po)&&pE(()=>{it&&fQ(it,Lt,jA),To&&Hi.enter(Le),po&&cM(jA,null,Lt,"mounted")},ct)},Ye=(jA,ue,He,Lt,ct)=>{if(He&&eA(jA,He),Lt)for(let Ct=0;Ct{for(let it=Le;it{const Ht=ue.el=jA.el;let{patchFlag:Le,dynamicChildren:it,dirs:Tt}=ue;Le|=jA.patchFlag&16;const Gt=jA.props||_a,Hi=ue.props||_a;let po;if(He&&lM(He,!1),(po=Hi.onVnodeBeforeUpdate)&&fQ(po,He,ue,jA),Tt&&cM(ue,jA,He,"beforeUpdate"),He&&lM(He,!0),(Gt.innerHTML&&Hi.innerHTML==null||Gt.textContent&&Hi.textContent==null)&&b(Ht,""),it?we(jA.dynamicChildren,it,Ht,He,Lt,n3(ue,ct),Ct):ei||ii(jA,ue,Ht,null,He,Lt,n3(ue,ct),Ct,!1),Le>0){if(Le&16)et(Ht,Gt,Hi,He,ct);else if(Le&2&&Gt.class!==Hi.class&&C(Ht,"class",null,Hi.class,ct),Le&4&&C(Ht,"style",Gt.style,Hi.style,ct),Le&8){const To=ue.dynamicProps;for(let Zi=0;Zi{po&&fQ(po,He,ue,jA),Tt&&cM(ue,jA,He,"updated")},Lt)},we=(jA,ue,He,Lt,ct,Ct,ei)=>{for(let Ht=0;Ht{if(ue!==He){if(ue!==_a)for(const Ct in ue)!aU(Ct)&&!(Ct in He)&&C(jA,Ct,ue[Ct],null,ct,Lt);for(const Ct in He){if(aU(Ct))continue;const ei=He[Ct],Ht=ue[Ct];ei!==Ht&&Ct!=="value"&&C(jA,Ct,Ht,ei,ct,Lt)}"value"in He&&C(jA,"value",ue.value,He.value,ct)}},Xe=(jA,ue,He,Lt,ct,Ct,ei,Ht,Le)=>{const it=ue.el=jA?jA.el:R(""),Tt=ue.anchor=jA?jA.anchor:R("");let{patchFlag:Gt,dynamicChildren:Hi,slotScopeIds:po}=ue;po&&(Ht=Ht?Ht.concat(po):po),jA==null?(c(it,He,Lt),c(Tt,He,Lt),We(ue.children||[],He,Tt,ct,Ct,ei,Ht,Le)):Gt>0&&Gt&64&&Hi&&jA.dynamicChildren?(we(jA.dynamicChildren,Hi,He,ct,Ct,ei,Ht),(ue.key!=null||ct&&ue===ct.subTree)&&h4(jA,ue,!0)):ii(jA,ue,He,Tt,ct,Ct,ei,Ht,Le)},ae=(jA,ue,He,Lt,ct,Ct,ei,Ht,Le)=>{ue.slotScopeIds=Ht,jA==null?ue.shapeFlag&512?ct.ctx.activate(ue,He,Lt,ei,Le):Je(ue,He,Lt,ct,Ct,ei,Le):pt(jA,ue,Le)},Je=(jA,ue,He,Lt,ct,Ct,ei)=>{const Ht=jA.component=YrA(jA,Lt,ct);if(GV(jA)&&(Ht.ctx.renderer=Ri),VrA(Ht,!1,ei),Ht.asyncDep){if(ct&&ct.registerDep(Ht,$t,ei),!jA.el){const Le=Ht.subTree=kt(yE);vA(null,Le,ue,He)}}else $t(Ht,jA,ue,He,ct,Ct,ei)},pt=(jA,ue,He)=>{const Lt=ue.component=jA.component;if(brA(jA,ue,He))if(Lt.asyncDep&&!Lt.asyncResolved){Pt(Lt,ue,He);return}else Lt.next=ue,Lt.update();else ue.el=jA.el,Lt.vnode=ue},$t=(jA,ue,He,Lt,ct,Ct,ei)=>{const Ht=()=>{if(jA.isMounted){let{next:Gt,bu:Hi,u:po,parent:To,vnode:Zi}=jA;{const jn=tX(jA);if(jn){Gt&&(Gt.el=Zi.el,Pt(jA,Gt,ei)),jn.asyncDep.then(()=>{jA.isUnmounted||Ht()});return}}let wo=Gt,Cn;lM(jA,!1),Gt?(Gt.el=Zi.el,Pt(jA,Gt,ei)):Gt=Zi,Hi&&QY(Hi),(Cn=Gt.props&&Gt.props.onVnodeBeforeUpdate)&&fQ(Cn,To,Gt,Zi),lM(jA,!0);const an=sZ(jA),Vo=jA.subTree;jA.subTree=an,IA(Vo,an,J(Vo.el),oo(Vo),jA,ct,Ct),Gt.el=an.el,wo===null&&krA(jA,an.el),po&&pE(po,ct),(Cn=Gt.props&&Gt.props.onVnodeUpdated)&&pE(()=>fQ(Cn,To,Gt,Zi),ct)}else{let Gt;const{el:Hi,props:po}=ue,{bm:To,m:Zi,parent:wo,root:Cn,type:an}=jA,Vo=nT(ue);lM(jA,!1),To&&QY(To),!Vo&&(Gt=po&&po.onVnodeBeforeMount)&&fQ(Gt,wo,ue),lM(jA,!0);{Cn.ce&&Cn.ce._injectChildStyle(an);const jn=jA.subTree=sZ(jA);IA(null,jn,He,Lt,jA,ct,Ct),ue.el=jn.el}if(Zi&&pE(Zi,ct),!Vo&&(Gt=po&&po.onVnodeMounted)){const jn=ue;pE(()=>fQ(Gt,wo,jn),ct)}(ue.shapeFlag&256||wo&&nT(wo.vnode)&&wo.vnode.shapeFlag&256)&&jA.a&&pE(jA.a,ct),jA.isMounted=!0,ue=He=Lt=null}};jA.scope.on();const Le=jA.effect=new I9(Ht);jA.scope.off();const it=jA.update=Le.run.bind(Le),Tt=jA.job=Le.runIfDirty.bind(Le);Tt.i=jA,Tt.id=jA.uid,Le.scheduler=()=>d4(Tt),lM(jA,!0),it()},Pt=(jA,ue,He)=>{ue.component=jA;const Lt=jA.vnode.props;jA.vnode=ue,jA.next=null,BrA(jA,ue.props,Lt,He),frA(jA,ue.children,He),hD(),j8(jA),BD()},ii=(jA,ue,He,Lt,ct,Ct,ei,Ht,Le=!1)=>{const it=jA&&jA.children,Tt=jA?jA.shapeFlag:0,Gt=ue.children,{patchFlag:Hi,shapeFlag:po}=ue;if(Hi>0){if(Hi&128){ao(it,Gt,He,Lt,ct,Ct,ei,Ht,Le);return}else if(Hi&256){ki(it,Gt,He,Lt,ct,Ct,ei,Ht,Le);return}}po&8?(Tt&16&&Ro(it,ct,Ct),Gt!==it&&b(He,Gt)):Tt&16?po&16?ao(it,Gt,He,Lt,ct,Ct,ei,Ht,Le):Ro(it,ct,Ct,!0):(Tt&8&&b(He,""),po&16&&We(Gt,He,Lt,ct,Ct,ei,Ht,Le))},ki=(jA,ue,He,Lt,ct,Ct,ei,Ht,Le)=>{jA=jA||eT,ue=ue||eT;const it=jA.length,Tt=ue.length,Gt=Math.min(it,Tt);let Hi;for(Hi=0;HiTt?Ro(jA,ct,Ct,!0,!1,Gt):We(ue,He,Lt,ct,Ct,ei,Ht,Le,Gt)},ao=(jA,ue,He,Lt,ct,Ct,ei,Ht,Le)=>{let it=0;const Tt=ue.length;let Gt=jA.length-1,Hi=Tt-1;for(;it<=Gt&&it<=Hi;){const po=jA[it],To=ue[it]=Le?qy(ue[it]):MQ(ue[it]);if(QM(po,To))IA(po,To,He,null,ct,Ct,ei,Ht,Le);else break;it++}for(;it<=Gt&&it<=Hi;){const po=jA[Gt],To=ue[Hi]=Le?qy(ue[Hi]):MQ(ue[Hi]);if(QM(po,To))IA(po,To,He,null,ct,Ct,ei,Ht,Le);else break;Gt--,Hi--}if(it>Gt){if(it<=Hi){const po=Hi+1,To=poHi)for(;it<=Gt;)Vi(jA[it],ct,Ct,!0),it++;else{const po=it,To=it,Zi=new Map;for(it=To;it<=Hi;it++){const xs=ue[it]=Le?qy(ue[it]):MQ(ue[it]);xs.key!=null&&Zi.set(xs.key,it)}let wo,Cn=0;const an=Hi-To+1;let Vo=!1,jn=0;const vo=new Array(an);for(it=0;it=an){Vi(xs,ct,Ct,!0);continue}let Zs;if(xs.key!=null)Zs=Zi.get(xs.key);else for(wo=To;wo<=Hi;wo++)if(vo[wo-To]===0&&QM(xs,ue[wo])){Zs=wo;break}Zs===void 0?Vi(xs,ct,Ct,!0):(vo[Zs-To]=it+1,Zs>=jn?jn=Zs:Vo=!0,IA(xs,ue[Zs],He,null,ct,Ct,ei,Ht,Le),Cn++)}const mA=Vo?vrA(vo):eT;for(wo=mA.length-1,it=an-1;it>=0;it--){const xs=To+it,Zs=ue[xs],mn=xs+1{const{el:Ct,type:ei,transition:Ht,children:Le,shapeFlag:it}=jA;if(it&6){Ji(jA.component.subTree,ue,He,Lt);return}if(it&128){jA.suspense.move(ue,He,Lt);return}if(it&64){ei.move(jA,ue,He,Ri);return}if(ei===kn){c(Ct,ue,He);for(let Gt=0;GtHt.enter(Ct),ct);else{const{leave:Gt,delayLeave:Hi,afterLeave:po}=Ht,To=()=>c(Ct,ue,He),Zi=()=>{Gt(Ct,()=>{To(),po&&po()})};Hi?Hi(Ct,To,Zi):Zi()}else c(Ct,ue,He)},Vi=(jA,ue,He,Lt=!1,ct=!1)=>{const{type:Ct,props:ei,ref:Ht,children:Le,dynamicChildren:it,shapeFlag:Tt,patchFlag:Gt,dirs:Hi,cacheIndex:po}=jA;if(Gt===-2&&(ct=!1),Ht!=null&&xY(Ht,null,He,jA,!0),po!=null&&(ue.renderCache[po]=void 0),Tt&256){ue.ctx.deactivate(jA);return}const To=Tt&1&&Hi,Zi=!nT(jA);let wo;if(Zi&&(wo=ei&&ei.onVnodeBeforeUnmount)&&fQ(wo,ue,jA),Tt&6)en(jA.component,He,Lt);else{if(Tt&128){jA.suspense.unmount(He,Lt);return}To&&cM(jA,null,ue,"beforeUnmount"),Tt&64?jA.type.remove(jA,ue,He,Ri,Lt):it&&!it.hasOnce&&(Ct!==kn||Gt>0&&Gt&64)?Ro(it,ue,He,!1,!0):(Ct===kn&&Gt&384||!ct&&Tt&16)&&Ro(Le,ue,He),Lt&&wn(jA)}(Zi&&(wo=ei&&ei.onVnodeUnmounted)||To)&&pE(()=>{wo&&fQ(wo,ue,jA),To&&cM(jA,null,ue,"unmounted")},He)},wn=jA=>{const{type:ue,el:He,anchor:Lt,transition:ct}=jA;if(ue===kn){Fi(He,Lt);return}if(ue===s3){HA(jA);return}const Ct=()=>{I(He),ct&&!ct.persisted&&ct.afterLeave&&ct.afterLeave()};if(jA.shapeFlag&1&&ct&&!ct.persisted){const{leave:ei,delayLeave:Ht}=ct,Le=()=>ei(He,Ct);Ht?Ht(jA.el,Ct,Le):Le()}else Ct()},Fi=(jA,ue)=>{let He;for(;jA!==ue;)He=gA(jA),I(jA),jA=He;I(ue)},en=(jA,ue,He)=>{const{bum:Lt,scope:ct,job:Ct,subTree:ei,um:Ht,m:Le,a:it}=jA;nZ(Le),nZ(it),Lt&&QY(Lt),ct.stop(),Ct&&(Ct.flags|=8,Vi(ei,jA,ue,He)),Ht&&pE(Ht,ue),pE(()=>{jA.isUnmounted=!0},ue),ue&&ue.pendingBranch&&!ue.isUnmounted&&jA.asyncDep&&!jA.asyncResolved&&jA.suspenseId===ue.pendingId&&(ue.deps--,ue.deps===0&&ue.resolve())},Ro=(jA,ue,He,Lt=!1,ct=!1,Ct=0)=>{for(let ei=Ct;ei{if(jA.shapeFlag&6)return oo(jA.component.subTree);if(jA.shapeFlag&128)return jA.suspense.next();const ue=gA(jA.anchor||jA.el),He=ue&&ue[N9];return He?gA(He):ue};let Ai=!1;const no=(jA,ue,He)=>{jA==null?ue._vnode&&Vi(ue._vnode,null,null,!0):IA(ue._vnode||null,jA,ue,null,null,null,He),ue._vnode=jA,Ai||(Ai=!0,j8(),_9(),Ai=!1)},Ri={p:IA,um:Vi,m:Ji,r:wn,mt:Je,mc:We,pc:ii,pbc:we,n:oo,o:e};return{render:no,hydrate:void 0,createApp:CrA(no)}}function n3({type:e,props:i},n){return n==="svg"&&e==="foreignObject"||n==="mathml"&&e==="annotation-xml"&&i&&i.encoding&&i.encoding.includes("html")?void 0:n}function lM({effect:e,job:i},n){n?(e.flags|=32,i.flags|=4):(e.flags&=-33,i.flags&=-5)}function SrA(e,i){return(!e||e&&!e.pendingBranch)&&i&&!i.persisted}function h4(e,i,n=!1){const c=e.children,I=i.children;if(Ln(c)&&Ln(I))for(let C=0;C>1,e[n[R]]0&&(i[c]=n[C-1]),n[C]=c)}}for(C=n.length,m=n[C-1];C-- >0;)n[C]=m,m=i[m];return n}function tX(e){const i=e.subTree.component;if(i)return i.asyncDep&&!i.asyncResolved?i:tX(i)}function nZ(e){if(e)for(let i=0;ijI(MrA);function vT(e,i){return B4(e,null,i)}function Kn(e,i,n){return B4(e,i,n)}function B4(e,i,n=_a){const{immediate:c,deep:I,flush:C,once:m}=n,R=cI({},n),_=i&&c||!i&&C!=="post";let T;if(LU){if(C==="sync"){const eA=RrA();T=eA.__watcherHandles||(eA.__watcherHandles=[])}else if(!_){const eA=()=>{};return eA.stop=GQ,eA.resume=GQ,eA.pause=GQ,eA}}const b=qI;R.call=(eA,CA,IA)=>lB(eA,b,CA,IA);let J=!1;C==="post"?R.scheduler=eA=>{pE(eA,b&&b.suspense)}:C!=="sync"&&(J=!0,R.scheduler=(eA,CA)=>{CA?eA():d4(eA)}),R.augmentJob=eA=>{i&&(eA.flags|=4),J&&(eA.flags|=2,b&&(eA.id=b.uid,eA.i=b))};const gA=OsA(e,i,R);return LU&&(T?T.push(gA):_&&gA()),gA}function wrA(e,i,n){const c=this.proxy,I=vg(e)?e.includes(".")?iX(c,e):()=>c[e]:e.bind(c,c);let C;ls(i)?C=i:(C=i.handler,n=i);const m=eF(this),R=B4(I,C.bind(c),n);return m(),R}function iX(e,i){const n=i.split(".");return()=>{let c=e;for(let I=0;Ii==="modelValue"||i==="model-value"?e.modelModifiers:e[`${i}Modifiers`]||e[`${ch(i)}Modifiers`]||e[`${CD(i)}Modifiers`];function TrA(e,i,...n){if(e.isUnmounted)return;const c=e.vnode.props||_a;let I=n;const C=i.startsWith("update:"),m=C&&_rA(c,i.slice(7));m&&(m.trim&&(I=n.map(b=>vg(b)?b.trim():b)),m.number&&(I=n.map(z3)));let R,_=c[R=Zj(i)]||c[R=Zj(ch(i))];!_&&C&&(_=c[R=Zj(CD(i))]),_&&lB(_,e,6,I);const T=c[R+"Once"];if(T){if(!e.emitted)e.emitted={};else if(e.emitted[R])return;e.emitted[R]=!0,lB(T,e,6,I)}}function oX(e,i,n=!1){const c=i.emitsCache,I=c.get(e);if(I!==void 0)return I;const C=e.emits;let m={},R=!1;if(!ls(e)){const _=T=>{const b=oX(T,i,!0);b&&(R=!0,cI(m,b))};!n&&i.mixins.length&&i.mixins.forEach(_),e.extends&&_(e.extends),e.mixins&&e.mixins.forEach(_)}return!C&&!R?(Ua(e)&&c.set(e,null),null):(Ln(C)?C.forEach(_=>m[_]=null):cI(m,C),Ua(e)&&c.set(e,m),m)}function kV(e,i){return!e||!SV(i)?!1:(i=i.slice(2).replace(/Once$/,""),$r(e,i[0].toLowerCase()+i.slice(1))||$r(e,CD(i))||$r(e,i))}function sZ(e){const{type:i,vnode:n,proxy:c,withProxy:I,propsOptions:[C],slots:m,attrs:R,emit:_,render:T,renderCache:b,props:J,data:gA,setupState:eA,ctx:CA,inheritAttrs:IA}=e,oA=PY(e);let vA,qA;try{if(n.shapeFlag&4){const HA=I||c,se=HA;vA=MQ(T.call(se,HA,b,J,eA,gA,CA)),qA=R}else{const HA=i;vA=MQ(HA.length>1?HA(J,{attrs:R,slots:m,emit:_}):HA(J,null)),qA=i.props?R:NrA(R)}}catch(HA){uU.length=0,TV(HA,e,1),vA=kt(yE)}let Ae=vA;if(qA&&IA!==!1){const HA=Object.keys(qA),{shapeFlag:se}=Ae;HA.length&&se&7&&(C&&HA.some(n4)&&(qA=GrA(qA,C)),Ae=cD(Ae,qA,!1,!0))}return n.dirs&&(Ae=cD(Ae,null,!1,!0),Ae.dirs=Ae.dirs?Ae.dirs.concat(n.dirs):n.dirs),n.transition&&GU(Ae,n.transition),vA=Ae,PY(oA),vA}const NrA=e=>{let i;for(const n in e)(n==="class"||n==="style"||SV(n))&&((i||(i={}))[n]=e[n]);return i},GrA=(e,i)=>{const n={};for(const c in e)(!n4(c)||!(c.slice(9)in i))&&(n[c]=e[c]);return n};function brA(e,i,n){const{props:c,children:I,component:C}=e,{props:m,children:R,patchFlag:_}=i,T=C.emitsOptions;if(i.dirs||i.transition)return!0;if(n&&_>=0){if(_&1024)return!0;if(_&16)return c?rZ(c,m,T):!!m;if(_&8){const b=i.dynamicProps;for(let J=0;Je.__isSuspense;function LrA(e,i){i&&i.pendingBranch?Ln(e)?i.effects.push(...e):i.effects.push(e):YsA(e)}const kn=Symbol.for("v-fgt"),LV=Symbol.for("v-txt"),yE=Symbol.for("v-cmt"),s3=Symbol.for("v-stc"),uU=[];let sC=null;function xA(e=!1){uU.push(sC=e?null:[])}function UrA(){uU.pop(),sC=uU[uU.length-1]||null}let bU=1;function aZ(e,i=!1){bU+=e,e<0&&sC&&i&&(sC.hasOnce=!0)}function sX(e){return e.dynamicChildren=bU>0?sC||eT:null,UrA(),bU>0&&sC&&sC.push(e),e}function Ce(e,i,n,c,I,C){return sX(UA(e,i,n,c,I,C,!0))}function mi(e,i,n,c,I){return sX(kt(e,i,n,c,I,!0))}function kU(e){return e?e.__v_isVNode===!0:!1}function QM(e,i){return e.type===i.type&&e.key===i.key}const rX=({key:e})=>e??null,mY=({ref:e,ref_key:i,ref_for:n})=>(typeof e=="number"&&(e=""+e),e!=null?vg(e)||aI(e)||ls(e)?{i:rI,r:e,k:i,f:!!n}:e:null);function UA(e,i=null,n=null,c=0,I=null,C=e===kn?0:1,m=!1,R=!1){const _={__v_isVNode:!0,__v_skip:!0,type:e,props:i,key:i&&rX(i),ref:i&&mY(i),scopeId:NV,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:C,patchFlag:c,dynamicProps:I,dynamicChildren:null,appContext:null,ctx:rI};return R?(Q4(_,n),C&128&&e.normalize(_)):n&&(_.shapeFlag|=vg(n)?8:16),bU>0&&!m&&sC&&(_.patchFlag>0||C&6)&&_.patchFlag!==32&&sC.push(_),_}const kt=FrA;function FrA(e,i=null,n=null,c=0,I=null,C=!1){if((!e||e===rrA)&&(e=yE),kU(e)){const R=cD(e,i,!0);return n&&Q4(R,n),bU>0&&!C&&sC&&(R.shapeFlag&6?sC[sC.indexOf(e)]=R:sC.push(R)),R.patchFlag=-2,R}if(jrA(e)&&(e=e.__vccOpts),i){i=OrA(i);let{class:R,style:_}=i;R&&!vg(R)&&(i.class=xi(R)),Ua(_)&&(E4(_)&&!Ln(_)&&(_=cI({},_)),i.style=lr(_))}const m=vg(e)?1:nX(e)?128:G9(e)?64:Ua(e)?4:ls(e)?2:0;return UA(e,i,n,c,I,m,C,!0)}function OrA(e){return e?E4(e)||W9(e)?cI({},e):e:null}function cD(e,i,n=!1,c=!1){const{props:I,ref:C,patchFlag:m,children:R,transition:_}=e,T=i?rW(I||{},i):I,b={__v_isVNode:!0,__v_skip:!0,type:e.type,props:T,key:T&&rX(T),ref:i&&i.ref?n&&C?Ln(C)?C.concat(mY(i)):[C,mY(i)]:mY(i):C,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:R,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:i&&e.type!==kn?m===-1?16:m|16:m,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:_,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&cD(e.ssContent),ssFallback:e.ssFallback&&cD(e.ssFallback),el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce};return _&&c&&GU(b,_.clone(b)),b}function Ur(e=" ",i=0){return kt(LV,null,e,i)}function ht(e="",i=!1){return i?(xA(),mi(yE,null,e)):kt(yE,null,e)}function MQ(e){return e==null||typeof e=="boolean"?kt(yE):Ln(e)?kt(kn,null,e.slice()):kU(e)?qy(e):kt(LV,null,String(e))}function qy(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:cD(e)}function Q4(e,i){let n=0;const{shapeFlag:c}=e;if(i==null)i=null;else if(Ln(i))n=16;else if(typeof i=="object")if(c&65){const I=i.default;I&&(I._c&&(I._d=!1),Q4(e,I()),I._c&&(I._d=!0));return}else{n=32;const I=i._;!I&&!W9(i)?i._ctx=rI:I===3&&rI&&(rI.slots._===1?i._=1:(i._=2,e.patchFlag|=1024))}else ls(i)?(i={default:i,_ctx:rI},n=32):(i=String(i),c&64?(n=16,i=[Ur(i)]):n=8);e.children=i,e.shapeFlag|=n}function rW(...e){const i={};for(let n=0;nqI||rI;let VY,aW;{const e=wV(),i=(n,c)=>{let I;return(I=e[n])||(I=e[n]=[]),I.push(c),C=>{I.length>1?I.forEach(m=>m(C)):I[0](C)}};VY=i("__VUE_INSTANCE_SETTERS__",n=>qI=n),aW=i("__VUE_SSR_SETTERS__",n=>LU=n)}const eF=e=>{const i=qI;return VY(e),e.scope.on(),()=>{e.scope.off(),VY(i)}},gZ=()=>{qI&&qI.scope.off(),VY(null)};function gX(e){return e.vnode.shapeFlag&4}let LU=!1;function VrA(e,i=!1,n=!1){i&&aW(i);const{props:c,children:I}=e.vnode,C=gX(e);hrA(e,c,C,i),mrA(e,I,n);const m=C?HrA(e,i):void 0;return i&&aW(!1),m}function HrA(e,i){const n=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,grA);const{setup:c}=n;if(c){hD();const I=e.setupContext=c.length>1?qrA(e):null,C=eF(e),m=AF(c,e,0,[e.props,I]),R=n9(m);if(BD(),C(),(R||e.sp)&&!nT(e)&&x9(e),R){if(m.then(gZ,gZ),i)return m.then(_=>{cZ(e,_)}).catch(_=>{TV(_,e,0)});e.asyncDep=m}else cZ(e,m)}else cX(e)}function cZ(e,i,n){ls(i)?e.type.__ssrInlineRender?e.ssrRender=i:e.render=i:Ua(i)&&(e.setupState=v9(i)),cX(e)}function cX(e,i,n){const c=e.type;e.render||(e.render=c.render||GQ);{const I=eF(e);hD();try{crA(e)}finally{BD(),I()}}}const JrA={get(e,i){return Du(e,"get",""),e[i]}};function qrA(e){const i=n=>{e.exposed=n||{}};return{attrs:new Proxy(e.attrs,JrA),slots:e.slots,emit:e.emit,expose:i}}function UV(e){return e.exposed?e.exposeProxy||(e.exposeProxy=new Proxy(v9(_sA(e.exposed)),{get(i,n){if(n in i)return i[n];if(n in IU)return IU[n](e)},has(i,n){return n in i||n in IU}})):e.proxy}function KrA(e,i=!0){return ls(e)?e.displayName||e.name:e.name||i&&e.__name}function jrA(e){return ls(e)&&"__vccOpts"in e}const gt=(e,i)=>UsA(e,i,LU);function WrA(e,i,n){const c=arguments.length;return c===2?Ua(i)&&!Ln(i)?kU(i)?kt(e,null,[i]):kt(e,i):kt(e,null,i):(c>3?n=Array.prototype.slice.call(arguments,2):c===3&&kU(n)&&(n=[n]),kt(e,i,n))}const gW="3.5.13";/** * @vue/runtime-dom v3.5.13 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT -**/let cW;const lZ=typeof window<"u"&&window.trustedTypes;if(lZ)try{cW=lZ.createPolicy("vue",{createHTML:e=>e})}catch{}const lX=cW?e=>cW.createHTML(e):e=>e,zrA="http://www.w3.org/2000/svg",ZrA="http://www.w3.org/1998/Math/MathML",Em=typeof document<"u"?document:null,IZ=Em&&Em.createElement("template"),XrA={insert:(e,i,n)=>{i.insertBefore(e,n||null)},remove:e=>{const i=e.parentNode;i&&i.removeChild(e)},createElement:(e,i,n,c)=>{const I=i==="svg"?Em.createElementNS(zrA,e):i==="mathml"?Em.createElementNS(ZrA,e):n?Em.createElement(e,{is:n}):Em.createElement(e);return e==="select"&&c&&c.multiple!=null&&I.setAttribute("multiple",c.multiple),I},createText:e=>Em.createTextNode(e),createComment:e=>Em.createComment(e),setText:(e,i)=>{e.nodeValue=i},setElementText:(e,i)=>{e.textContent=i},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>Em.querySelector(e),setScopeId(e,i){e.setAttribute(i,"")},insertStaticContent(e,i,n,c,I,C){const m=n?n.previousSibling:i.lastChild;if(I&&(I===C||I.nextSibling))for(;i.insertBefore(I.cloneNode(!0),n),!(I===C||!(I=I.nextSibling)););else{IZ.innerHTML=lX(c==="svg"?`${e}`:c==="mathml"?`${e}`:e);const R=IZ.content;if(c==="svg"||c==="mathml"){const _=R.firstChild;for(;_.firstChild;)R.appendChild(_.firstChild);R.removeChild(_)}i.insertBefore(R,n)}return[m?m.nextSibling:i.firstChild,n?n.previousSibling:i.lastChild]}},Uy="transition",NL="animation",UU=Symbol("_vtc"),IX={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},$rA=cI({},L9,IX),AaA=e=>(e.displayName="Transition",e.props=$rA,e),eaA=AaA((e,{slots:i})=>WrA(KsA,taA(e),i)),IM=(e,i=[])=>{Ln(e)?e.forEach(n=>n(...i)):e&&e(...i)},uZ=e=>e?Ln(e)?e.some(i=>i.length>1):e.length>1:!1;function taA(e){const i={};for(const Xe in e)Xe in IX||(i[Xe]=e[Xe]);if(e.css===!1)return i;const{name:n="v",type:c,duration:I,enterFromClass:C=`${n}-enter-from`,enterActiveClass:m=`${n}-enter-active`,enterToClass:R=`${n}-enter-to`,appearFromClass:_=C,appearActiveClass:T=m,appearToClass:b=R,leaveFromClass:J=`${n}-leave-from`,leaveActiveClass:cA=`${n}-leave-active`,leaveToClass:eA=`${n}-leave-to`}=e,CA=iaA(I),IA=CA&&CA[0],oA=CA&&CA[1],{onBeforeEnter:vA,onEnter:qA,onEnterCancelled:Ae,onLeave:HA,onLeaveCancelled:se,onBeforeAppear:WA=vA,onAppear:Ye=qA,onAppearCancelled:We=Ae}=i,Pe=(Xe,ae,Je,pt)=>{Xe._enterCancelled=pt,uM(Xe,ae?b:R),uM(Xe,ae?T:m),Je&&Je()},we=(Xe,ae)=>{Xe._isLeaving=!1,uM(Xe,J),uM(Xe,eA),uM(Xe,cA),ae&&ae()},et=Xe=>(ae,Je)=>{const pt=Xe?Ye:qA,$t=()=>Pe(ae,Xe,Je);IM(pt,[ae,$t]),EZ(()=>{uM(ae,Xe?_:C),cm(ae,Xe?b:R),uZ(pt)||dZ(ae,c,IA,$t)})};return cI(i,{onBeforeEnter(Xe){IM(vA,[Xe]),cm(Xe,C),cm(Xe,m)},onBeforeAppear(Xe){IM(WA,[Xe]),cm(Xe,_),cm(Xe,T)},onEnter:et(!1),onAppear:et(!0),onLeave(Xe,ae){Xe._isLeaving=!0;const Je=()=>we(Xe,ae);cm(Xe,J),Xe._enterCancelled?(cm(Xe,cA),BZ()):(BZ(),cm(Xe,cA)),EZ(()=>{Xe._isLeaving&&(uM(Xe,J),cm(Xe,eA),uZ(HA)||dZ(Xe,c,oA,Je))}),IM(HA,[Xe,Je])},onEnterCancelled(Xe){Pe(Xe,!1,void 0,!0),IM(Ae,[Xe])},onAppearCancelled(Xe){Pe(Xe,!0,void 0,!0),IM(We,[Xe])},onLeaveCancelled(Xe){we(Xe),IM(se,[Xe])}})}function iaA(e){if(e==null)return null;if(Ua(e))return[r3(e.enter),r3(e.leave)];{const i=r3(e);return[i,i]}}function r3(e){return AsA(e)}function cm(e,i){i.split(/\s+/).forEach(n=>n&&e.classList.add(n)),(e[UU]||(e[UU]=new Set)).add(i)}function uM(e,i){i.split(/\s+/).forEach(c=>c&&e.classList.remove(c));const n=e[UU];n&&(n.delete(i),n.size||(e[UU]=void 0))}function EZ(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}let oaA=0;function dZ(e,i,n,c){const I=e._endId=++oaA,C=()=>{I===e._endId&&c()};if(n!=null)return setTimeout(C,n);const{type:m,timeout:R,propCount:_}=naA(e,i);if(!m)return c();const T=m+"end";let b=0;const J=()=>{e.removeEventListener(T,cA),C()},cA=eA=>{eA.target===e&&++b>=_&&J()};setTimeout(()=>{b<_&&J()},R+1),e.addEventListener(T,cA)}function naA(e,i){const n=window.getComputedStyle(e),c=CA=>(n[CA]||"").split(", "),I=c(`${Uy}Delay`),C=c(`${Uy}Duration`),m=CZ(I,C),R=c(`${NL}Delay`),_=c(`${NL}Duration`),T=CZ(R,_);let b=null,J=0,cA=0;i===Uy?m>0&&(b=Uy,J=m,cA=C.length):i===NL?T>0&&(b=NL,J=T,cA=_.length):(J=Math.max(m,T),b=J>0?m>T?Uy:NL:null,cA=b?b===Uy?C.length:_.length:0);const eA=b===Uy&&/\b(transform|all)(,|$)/.test(c(`${Uy}Property`).toString());return{type:b,timeout:J,propCount:cA,hasTransform:eA}}function CZ(e,i){for(;e.lengthhZ(n)+hZ(e[c])))}function hZ(e){return e==="auto"?0:Number(e.slice(0,-1).replace(",","."))*1e3}function BZ(){return document.body.offsetHeight}function saA(e,i,n){const c=e[UU];c&&(i=(i?[i,...c]:[...c]).join(" ")),i==null?e.removeAttribute("class"):n?e.setAttribute("class",i):e.className=i}const HY=Symbol("_vod"),uX=Symbol("_vsh"),ha={beforeMount(e,{value:i},{transition:n}){e[HY]=e.style.display==="none"?"":e.style.display,n&&i?n.beforeEnter(e):GL(e,i)},mounted(e,{value:i},{transition:n}){n&&i&&n.enter(e)},updated(e,{value:i,oldValue:n},{transition:c}){!i!=!n&&(c?i?(c.beforeEnter(e),GL(e,!0),c.enter(e)):c.leave(e,()=>{GL(e,!1)}):GL(e,i))},beforeUnmount(e,{value:i}){GL(e,i)}};function GL(e,i){e.style.display=i?e[HY]:"none",e[uX]=!i}const raA=Symbol(""),aaA=/(^|;)\s*display\s*:/;function gaA(e,i,n){const c=e.style,I=Sg(n);let C=!1;if(n&&!I){if(i)if(Sg(i))for(const m of i.split(";")){const R=m.slice(0,m.indexOf(":")).trim();n[R]==null&&fY(c,R,"")}else for(const m in i)n[m]==null&&fY(c,m,"");for(const m in n)m==="display"&&(C=!0),fY(c,m,n[m])}else if(I){if(i!==n){const m=c[raA];m&&(n+=";"+m),c.cssText=n,C=aaA.test(n)}}else i&&e.removeAttribute("style");HY in e&&(e[HY]=C?c.display:"",e[uX]&&(c.display="none"))}const QZ=/\s*!important$/;function fY(e,i,n){if(Ln(n))n.forEach(c=>fY(e,i,c));else if(n==null&&(n=""),i.startsWith("--"))e.setProperty(i,n);else{const c=caA(e,i);QZ.test(n)?e.setProperty(CD(c),n.replace(QZ,""),"important"):e[c]=n}}const pZ=["Webkit","Moz","ms"],a3={};function caA(e,i){const n=a3[i];if(n)return n;let c=ch(i);if(c!=="filter"&&c in e)return a3[i]=c;c=RV(c);for(let I=0;Ig3||(EaA.then(()=>g3=0),g3=Date.now());function CaA(e,i){const n=c=>{if(!c._vts)c._vts=Date.now();else if(c._vts<=n.attached)return;lB(haA(c,n.value),i,5,[c])};return n.value=e,n.attached=daA(),n}function haA(e,i){if(Ln(i)){const n=e.stopImmediatePropagation;return e.stopImmediatePropagation=()=>{n.call(e),e._stopped=!0},i.map(c=>I=>!I._stopped&&c&&c(I))}else return i}const vZ=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,BaA=(e,i,n,c,I,C)=>{const m=I==="svg";i==="class"?saA(e,c,m):i==="style"?gaA(e,n,c):SV(i)?n4(i)||IaA(e,i,n,c,C):(i[0]==="."?(i=i.slice(1),!0):i[0]==="^"?(i=i.slice(1),!1):QaA(e,i,c,m))?(yZ(e,i,c),!e.tagName.includes("-")&&(i==="value"||i==="checked"||i==="selected")&&fZ(e,i,c,m,C,i!=="value")):e._isVueCE&&(/[A-Z]/.test(i)||!Sg(c))?yZ(e,ch(i),c,C,i):(i==="true-value"?e._trueValue=c:i==="false-value"&&(e._falseValue=c),fZ(e,i,c,m))};function QaA(e,i,n,c){if(c)return!!(i==="innerHTML"||i==="textContent"||i in e&&vZ(i)&&ls(n));if(i==="spellcheck"||i==="draggable"||i==="translate"||i==="form"||i==="list"&&e.tagName==="INPUT"||i==="type"&&e.tagName==="TEXTAREA")return!1;if(i==="width"||i==="height"){const I=e.tagName;if(I==="IMG"||I==="VIDEO"||I==="CANVAS"||I==="SOURCE")return!1}return vZ(i)&&Sg(n)?!1:i in e}const MZ=e=>{const i=e.props["onUpdate:modelValue"]||!1;return Ln(i)?n=>QY(i,n):i};function paA(e){e.target.composing=!0}function RZ(e){const i=e.target;i.composing&&(i.composing=!1,i.dispatchEvent(new Event("input")))}const c3=Symbol("_assign"),maA={created(e,{modifiers:{lazy:i,trim:n,number:c}},I){e[c3]=MZ(I);const C=c||I.props&&I.props.type==="number";U_(e,i?"change":"input",m=>{if(m.target.composing)return;let R=e.value;n&&(R=R.trim()),C&&(R=z3(R)),e[c3](R)}),n&&U_(e,"change",()=>{e.value=e.value.trim()}),i||(U_(e,"compositionstart",paA),U_(e,"compositionend",RZ),U_(e,"change",RZ))},mounted(e,{value:i}){e.value=i??""},beforeUpdate(e,{value:i,oldValue:n,modifiers:{lazy:c,trim:I,number:C}},m){if(e[c3]=MZ(m),e.composing)return;const R=(C||e.type==="number")&&!/^0\d/.test(e.value)?z3(e.value):e.value,_=i??"";R!==_&&(document.activeElement===e&&e.type!=="range"&&(c&&i===n||I&&e.value.trim()===_)||(e.value=_))}},faA=["ctrl","shift","alt","meta"],yaA={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>"button"in e&&e.button!==0,middle:e=>"button"in e&&e.button!==1,right:e=>"button"in e&&e.button!==2,exact:(e,i)=>faA.some(n=>e[`${n}Key`]&&!i.includes(n))},SE=(e,i)=>{const n=e._withMods||(e._withMods={}),c=i.join(".");return n[c]||(n[c]=(I,...C)=>{for(let m=0;m{const n=e._withKeys||(e._withKeys={}),c=i.join(".");return n[c]||(n[c]=I=>{if(!("key"in I))return;const C=CD(I.key);if(i.some(m=>m===C||DaA[m]===C))return e(I)})},SaA=cI({patchProp:BaA},XrA);let wZ;function dX(){return wZ||(wZ=yrA(SaA))}const wM=(...e)=>{dX().render(...e)},vaA=(...e)=>{const i=dX().createApp(...e),{mount:n}=i;return i.mount=c=>{const I=RaA(c);if(!I)return;const C=i._component;!ls(C)&&!C.render&&!C.template&&(C.template=I.innerHTML),I.nodeType===1&&(I.textContent="");const m=n(I,!1,MaA(I));return I instanceof Element&&(I.removeAttribute("v-cloak"),I.setAttribute("data-v-app","")),m},i};function MaA(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function RaA(e){return Sg(e)?document.querySelector(e):e}function waA(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var xL={exports:{}},yY={exports:{}},_aA=yY.exports,_Z;function CX(){return _Z||(_Z=1,function(e,i){(function(n,c){e.exports=c()})(_aA,function(){const n=p=>p===void 0,c=p=>typeof p=="string",I=p=>{var B;return(B=Object.prototype.toString.call(p).match(/^\[object (.*)\]$/))===null||B===void 0?void 0:B[1].toLowerCase()},C=p=>typeof Array.isArray=="function"?Array.isArray(p):I(p)==="array",m=p=>p!==null&&typeof p=="object",R=p=>C(p)||m(p),_=p=>{if(typeof p!="string")return!1;const B=p[0];return!/[^a-zA-Z0-9]/.test(B)},T=p=>{if(typeof p!="object"||p===null)return!1;const B=Object.getPrototypeOf(p);if(B===null)return!0;let M=B;for(;Object.getPrototypeOf(M)!==null;)M=Object.getPrototypeOf(M);return B===M};function b(p=99999999){return Math.round(Math.random()*p)}const J=(p,B,M,G)=>{if(!R(p)||!R(B))return 0;let O=0;const z=Object.keys(B);let X;for(let gA=0,DA=z.length;gA"u"&&typeof uni.requireNativePlugin=="function",Ji=Xe&&typeof wx.miniapp=="object",Vi=typeof uni<"u",wn=pt&&typeof tt.enterChat=="function",Fi=Xe||Je||pt||Pt||ii||ao||ki,en=typeof window>"u"&&!Fi&&typeof Dg<"u"&&Dg.NativeScriptGlobals!==void 0,Ro=typeof Dg<"u"&&(Dg.nativeModuleProxy!==void 0||Dg.ReactNative!==void 0),oo=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,Ai=typeof uni<"u"?!Fi:typeof window<"u"&&!Fi&&!Ro,no=Je?qq:pt?tt:Pt?swan:ii?my:Xe?wx:ao?uni:ki?jd:{},Ri=Ai&&window&&window.navigator&&window.navigator.userAgent||"",pn=/(micromessenger|webbrowser)/i.test(Ri),jA=function(){let p="WEB";return pn?p="WEB":Je?p="QQ_MP":pt?p="TT_MP":Pt?p="BAIDU_MP":ii?p="ALI_MP":Xe?p=Ji?"DONUT_NATIVE_APP":"WX_MP":ao?p="UNI_NATIVE_APP":en?p="NS_NATIVE_APP":Ro&&(p="RN_NATIVE_APP"),eA[p]}(),ue=/iPad/i.test(Ri),He=/iPhone/i.test(Ri)&&!ue,Lt=/iPod/i.test(Ri),ct=He||ue||Lt,Ct=function(){const p=Ri.match(/OS (\d+)_/i);return p&&p[1]?p[1]:null}(),ei=/Android/i.test(Ri),Ht=function(){const p=Ri.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!p)return null;const B=p[1]&&parseFloat(p[1]),M=p[2]&&parseFloat(p[2]);return B&&M?parseFloat(`${p[1]}.${p[2]}`):B||null}(),Le=/Firefox/i.test(Ri),it=/Edge/i.test(Ri),Tt=!it&&/Chrome/i.test(Ri),Gt=/MSIE/.test(Ri)||Ri.indexOf("Trident")>-1&&Ri.indexOf("rv:11.0")>-1,Hi=function(){const p=/MSIE\s(\d+)\.\d/.exec(Ri);let B=p&&parseFloat(p[1]);return!B&&/Trident\/7.0/i.test(Ri)&&/rv:11.0/.test(Ri)&&(B=11),B}(),po=/Safari/i.test(Ri)&&!Tt&&!ei&&!it,To=/Windows/i.test(Ri),Zi=/MAC OS X/i.test(Ri),wo=Ai&&typeof Worker<"u"&&!Gt,Cn=ei||ct,an=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:p}=window.navigator;return!(!ct||p||po)}();function Vo(){let p="unknown";if(Zi&&(p="mac"),To&&(p="windows"),ct&&(p="ios"),ei&&(p="android"),Fi)try{const{platform:B}=no.getSystemInfoSync();B!==void 0&&(p=B)}catch(B){console.error(B)}return p}const jn=typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0&&typeof window>"u";function vo(p,B){var M={};for(var G in p)Object.prototype.hasOwnProperty.call(p,G)&&B.indexOf(G)<0&&(M[G]=p[G]);if(p!=null&&typeof Object.getOwnPropertySymbols=="function"){var O=0;for(G=Object.getOwnPropertySymbols(p);O{no.request({url:M,data:G,method:B,timeout:O,header:{"content-type":Fr},success:gA=>z(gA.data),fail:()=>X(new Error(`{"message":"Network error","code":${xs}}`))})}):jn?void 0:new Promise((z,X)=>{const gA=new XMLHttpRequest,DA=setTimeout(()=>{gA.abort(),X(new Error(`{"message":"Request timeout","code":${Zs}}`))},O);gA.onreadystatechange=function(){if(gA.readyState===4)if(clearTimeout(DA),gA.status===200||gA.status===304)try{z(gA.responseText?JSON.parse(gA.responseText):null)}catch{z(gA.responseText)}else X(new Error(`{"message":"Network error","code":${xs}}`))},gA.open(B,M,!0),gA.setRequestHeader("Content-type",Fr),gA.send(G||null)})})}function tn(p){if(p==null)return!0;if(typeof p=="boolean")return!1;if(typeof p=="number")return p===0;if(typeof p=="string"||typeof p=="function"||Array.isArray(p))return p.length===0;if(p instanceof Error)return p.message==="";if(T(p)){for(const B in p)if(Object.prototype.hasOwnProperty.call(p,B))return!1;return!0}return(Object.prototype.toString.call(p)==="[object Map]"||Object.prototype.toString.call(p)==="[object Set]"||Object.prototype.toString.call(p)==="[object File]")&&p.size===0}function Ks(p,B){if(p===null||typeof p!="object")return p;const M=B||new WeakMap;if(M.has(p))return M.get(p);if(p instanceof Date)return new Date(p.getTime());if(p instanceof RegExp)return new RegExp(p.source,p.flags);if(p instanceof Map){const z=new Map;return M.set(p,z),p.forEach((X,gA)=>{z.set(Ks(gA,M),Ks(X,M))}),z}if(p instanceof Set){const z=new Set;return M.set(p,z),p.forEach(X=>{z.add(Ks(X,M))}),z}if(Array.isArray(p)){const z=[];return M.set(p,z),p.forEach(X=>{z.push(Ks(X,M))}),z}const G=Object.getPrototypeOf(p),O=Object.create(G);return M.set(p,O),[...Object.getOwnPropertyNames(p),...Object.getOwnPropertySymbols(p)].forEach(z=>{if(z==="__ob__"||z==="__v_skip"||z==="__v_isRef"||z==="__v_isReadonly")return;const X=Object.getOwnPropertyDescriptor(p,z);X&&(X.get||X.set?Object.defineProperty(O,z,X):O[z]=Ks(p[z],M))}),O}function _n(p,B,M){const G=new WeakSet,O=(z,X)=>{if(B&&(X=B(z,X)),X===void 0)return"undefined";if(X===null)return null;if(Number.isNaN(X))return"NaN";if(X===1/0)return"Infinity";if(X===-1/0)return"-Infinity";if(typeof X=="function")return`[Function: ${X.name||"anonymous"}]`;if(typeof X=="symbol")return X.toString();if(typeof X=="bigint")return`${X.toString()}n`;if(typeof X=="object"&&X!==null){if(G.has(X))return"[Circular]";G.add(X)}return X instanceof Date?X.toISOString():X instanceof Error?{name:X.name,message:X.message}:X instanceof Map?{dataType:"Map",value:Array.from(X.entries())}:X instanceof Set?{dataType:"Set",value:Array.from(X.values())}:X};try{return JSON.stringify(p,O,M)}catch(z){return console.error("Failed to stringify:",z),""}}function Is(){let p,B;return{promise:new Promise((M,G)=>{p=M,B=G}),resolve:p,reject:B}}var qt,$a=Object.freeze({__proto__:null,ANDROID_VERSION:Ht,IE_VERSION:Hi,IN_ALIPAY_MINI_APP:ii,IN_BAIDU_MINI_APP:Pt,IN_BROWSER:Ai,IN_DONUT_NATIVE_APP:Ji,IN_FEISHU_MINI_APP:wn,IN_JD_MINI_APP:ki,IN_MINI_APP:Fi,IN_NODE:jn,IN_NS_NATIVE_APP:en,IN_QQ_MINI_APP:Je,IN_RN_APP:Ro,IN_TT_MINI_APP:pt,IN_TT_MINI_GAME:$t,IN_UNI_APP:Vi,IN_UNI_NATIVE_APP:ao,IN_WX_MINI_APP:Xe,IN_WX_MINI_APP_DESK:et,IN_WX_MINI_GAME:ae,IN_WX_MINI_PLUGIN:oo,IOS_VERSION:Ct,IS_ANDROID:ei,IS_CHROME:Tt,IS_EDGE:it,IS_FIREFOX:Le,IS_IE:Gt,IS_IOS:ct,IS_IPAD:ue,IS_IPHONE:He,IS_IPOD:Lt,IS_MAC:Zi,IS_SAFARI:po,IS_WECHAT:pn,IS_WIN:To,IS_WORKER_AVAILABLE:wo,MINI_APP_NAMESPACE:no,USER_AGENT:Ri,base16EncodeBinaryString:cA,deepCopyWithMethods:Ks,deepMerge:J,generatePromise:Is,getPlatformType:Vo,getType:I,httpRequest:qi,isArray:C,isArrayOrObject:R,isEmpty:tn,isH5:Cn,isIOSWebView:an,isNumber:p=>p!==null&&(typeof p=="number"&&!Number.isNaN(p-0)||typeof p=="object"&&p.constructor===Number),isObject:m,isPlainObject:T,isString:c,isUndefined:n,isUniIOSApp:function(){return ao&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:_,platform:jA,randomInt:b,randomString:function(){const p="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let B="";for(let M=32;M>0;--M)B+=p[Math.floor(62*Math.random())];return B},safeStringify:_n});class Ls{constructor(){this.listeners={}}on(B,M,G){this.listeners[B]||(this.listeners[B]=[]),this.listeners[B].push({fn:M,context:G})}off(B,M,G){var O;M&&(this.listeners[B]=(O=this.listeners[B])===null||O===void 0?void 0:O.filter(z=>{const X=z.fn===M,gA=!G||z.context===G;return!(X&&gA)}))}emit(B,...M){const G=this.listeners[B];G&&G.forEach(O=>{const{fn:z,context:X}=O;try{z.apply(X,M)}catch(gA){console.warn(`Error in event handler for ${B} error: ${_n(gA)}`)}})}once(B,M,G){const O=(...z)=>{M.apply(G,z),this.off(B,O)};this.on(B,O)}}(function(p){p.BUSINESS_COMMAND="business_command",p.C2C_REALTIME_MESSAGE="c2c_realtime_message",p.C2C_MESSAGE_MODIFIED="c2c_message_modified",p.C2C_REVOKED_MESSAGE="c2c_message_revoked",p.GROUP_REALTIME_MESSAGE="group_realtime_message",p.GROUP_MESSAGE_MODIFIED="group_message_modified",p.GROUP_MESSAGE_REVOKED="group_message_revoked",p.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",p.MESSAGE_REACTION_UPDATED="message_reaction_updated",p.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",p.GROUP_AT_TIPS="group_at_tips",p.USER_STATUS_UPDATE="user_status_update",p.FRIEND_LIST_MODIFIED="friend_list_modified",p.PROFILE_MODIFIED="profile_modified",p.CONV_MODIFIED="conversation_modified",p.GROUP_TIPS_NOTIFICATION="group_tips_notification",p.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",p.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",p.GROUP_SYSTEM_NOTIFICATION="group_system_notification",p.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",p.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",p.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",p.FOLLOW_LIST_UPDATED="follow_list_updated",p.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",p.ALL_MESSAGE_READ="all_message_read",p.CONVERSATION_MARK_UPDATED="conversation_mark_updated",p.CONVERSATION_GROUP_ADD="conversation_group_add",p.CONVERSATION_GROUP_DELETED="conversation_group_deleted",p.CONVERSATION_GROUP_UPDATED="conversation_group_updated",p.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",p.TOPIC_AT_TIPS="topic_at_tips",p.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",p.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",p.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",p.TOPIC_LATEST_MESSAGE="topic_latest_message",p.GROUP_MESSAGE_PINNED="group_message_pinned"})(qt||(qt={}));const Bs=[16,17];function Un(p){var B;const M=[];return(B=p?.GroupTips)===null||B===void 0||B.forEach(G=>{var O;G.GroupInfo.MillionGroupFlag===2?M.push(qt.TOPIC_TIPS_NOTIFICATION):Bs.includes((O=G?.MsgBody)===null||O===void 0?void 0:O.OpType)?M.push(qt.GROUP_MESSAGE_PINNED):M.push(qt.GROUP_TIPS_NOTIFICATION)}),M}const Ir=[{conditions:[{type:"event",value:100}],subType:qt.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:qt.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:qt.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:qt.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:qt.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:qt.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:qt.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:qt.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:qt.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:qt.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(p){var B;const M=[];return(B=p?.C2cNotifyMsgArray)===null||B===void 0||B.forEach(G=>{G.WithdrawC2cMsgNotify&&M.push(qt.C2C_REVOKED_MESSAGE),G.C2cReadedReceipt&&M.push(qt.C2C_MESSAGE_PEER_READ),G.ReadC2cMsgNotify&&M.push(qt.C2C_MESSAGE_READ_SYNC),G.MuteNotificationsSync&&M.push(qt.C2C_REMIND_TYPE_SYNC)}),M}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Un},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(p){var B;const M=[];return(B=p?.GroupTips)===null||B===void 0||B.forEach(G=>{Array.isArray(G.MsgBody.GroupWithdrawInfoArray)?M.push(qt.GROUP_MESSAGE_REVOKED):Array.isArray(G.MsgBody.GroupMsgReceiptList)?M.push(qt.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(G.MsgBody.GroupReadInfoArray)?G.MsgBody.GroupReadInfoArray[0].TopicId?M.push(qt.TOPIC_MESSAGE_READ_SYNC):M.push(qt.GROUP_MESSAGE_READ_SYNC):G.GroupInfo.MillionGroupFlag===2?M.push(qt.TOPIC_SYSTEM_NOTIFICATION):M.push(qt.GROUP_SYSTEM_NOTIFICATION)}),M}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:Un},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(p){var B;const M=[];return(B=p?.GroupTips)===null||B===void 0||B.forEach(G=>{const{GroupAtTips:{TopicId:O}}=G;O?M.push(qt.TOPIC_AT_TIPS):M.push(qt.GROUP_AT_TIPS)}),M}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(p){var B;const M=[];return(B=p?.RecentContactMod)===null||B===void 0||B.forEach(G=>{switch(G.PushType){case Pe.CONV_MARK_UPDATED:M.push(qt.CONVERSATION_MARK_UPDATED);break;case Pe.CONV_GROUP_ADDED:M.push(qt.CONVERSATION_GROUP_ADD);break;case Pe.CONV_GROUP_DELETED:M.push(qt.CONVERSATION_GROUP_DELETED);break;case Pe.CONV_GROUP_UPDATED:M.push(qt.CONVERSATION_GROUP_UPDATED);break;default:M.push(qt.CONV_MODIFIED)}}),M}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:qt.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:qt.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:qt.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:qt.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:qt.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:qt.ALL_MESSAGE_READ}];var Fn;function rr(p){var B;const M=Array.isArray((B=p?.body)===null||B===void 0?void 0:B.EventArray)?p.body.EventArray:[],G=[];return M.forEach(O=>{O.Flag=p.body.Flag;const z=Ir.find(gA=>gA.conditions.every(DA=>{switch(DA.type){case"event":return O.Event===DA.value;case"hasKey":return Object.prototype.hasOwnProperty.call(O,DA.value);default:return!1}}));if(!z)return null;let X=[];typeof z.subTypeParser=="function"?X=z.subTypeParser(O):z.subType&&(X=z.subType),Array.isArray(X)?X.forEach(gA=>{G.push({type:`${Fn.SERVER_PUSH_MESSAGE}:${gA}`,data:O})}):G.push({type:`${Fn.SERVER_PUSH_MESSAGE}:${X}`,data:O})}),G}(function(p){p.SERVER_PUSH_MESSAGE="im_open_push.msg_push",p.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",p.ERROR="error"})(Fn||(Fn={}));const fo={[Fn.SERVER_PUSH_MESSAGE]:rr,[Fn.SERVER_PUSH_MESSAGE_MULTIPLE]:rr,[Fn.ERROR]:function(p){const{errorCode:B}=p;return[{type:`error:${B}`,data:p}]}},es=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._filteredCallbackMap=new Map,this._outerEventEmitter=new Ls,this._innerEventEmitter=new Ls,this.InnerEventSubType=qt}subscribeInnerEvent(p,B,M,G,O){var z;let X,gA,DA,GA;["string","number"].includes(typeof B)?(DA=`${p}:${B}`,GA=M,gA=G,X=O):(DA=p,GA=B,gA=M,X=typeof G=="function"?G:void 0),X?this._subscribeWithFilter(DA,GA,gA,X):(z=this._innerEventEmitter)===null||z===void 0||z.on(DA,GA,gA)}emitInnerEvent(p,B){var M,G;if((M=this._innerEventEmitter)===null||M===void 0||M.emit(p,B),Object.keys(fo).includes(p)){const O=(G=fo[p])===null||G===void 0?void 0:G.call(fo,B);O?.forEach(z=>{var X;z&&((X=this._innerEventEmitter)===null||X===void 0||X.emit(z.type,z.data))})}}subscribeOuterEvent(p,B,M){var G;(G=this._outerEventEmitter)===null||G===void 0||G.on(p,B,M)}unSubscribeOuterEvent(p,B,M){var G;(G=this._outerEventEmitter)===null||G===void 0||G.off(p,B,M)}unSubscribeInnerEvent(p,B,M,G){if(["string","number"].includes(typeof B)){const O=M,z=`${p}:${B}`;this._unsubscribeEvent(z,O,G)}else{const O=B;this._unsubscribeEvent(p,O,M)}}emitOuterEvent(p,B){var M;(M=this._outerEventEmitter)===null||M===void 0||M.emit(p,B)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}_subscribeWithFilter(p,B,M,G){var O;const z=X=>{G.call(M,X)&&B.call(M,X)};this._filteredCallbackMap.has(p)||this._filteredCallbackMap.set(p,[]),this._filteredCallbackMap.get(p).push({originalCallback:B,filteredCallback:z,filter:G,context:M}),(O=this._innerEventEmitter)===null||O===void 0||O.on(p,z,M)}_unsubscribeEvent(p,B,M){var G,O;const z=this._filteredCallbackMap.get(p);if(z){const X=z.findIndex(gA=>gA.originalCallback===B&&gA.context===M);if(X!==-1){const{filteredCallback:gA}=z[X];return(G=this._innerEventEmitter)===null||G===void 0||G.off(p,gA,M),z.splice(X,1),void(z.length===0&&this._filteredCallbackMap.delete(p))}}(O=this._innerEventEmitter)===null||O===void 0||O.off(p,B,M)}};class vc{constructor(){this._socket=null}connectSocket(B){return this._socket=new WebSocket(B),this._socket}send(B){var M,G;try{(M=this._socket)===null||M===void 0||M.send(B)}catch(O){(G=this._onSendFail)===null||G===void 0||G.call(this,O)}}bindSocketHandlers(B){const{onOpen:M,onMessage:G,onClose:O,onError:z,onSendFail:X}=B;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=M,this._socket.onmessage=G,this._socket.onclose=O,this._socket.onerror=z,this._onSendFail=X)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class ts{constructor(B){this._onError=B.onError}connectSocket(B){const M=this;return this._socket=no.connectSocket({url:B,header:{"content-type":"application/json"},complete:()=>{},fail:G=>M._onError(G)}),this._socket}send(B){var M;(M=this._socket)===null||M===void 0||M.send({data:B,fail:this._onSendFail})}bindSocketHandlers(B){const{onOpen:M,onMessage:G,onClose:O,onError:z,onSendFail:X}=B;this._socket&&(this._socket.onClose(O),this._socket.onOpen(M),this._socket.onMessage(G),this._socket.onError(z),this._onSendFail=X)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const ur="CONNECT",On="SEND",vg="DISCONNECT",yn="OPEN",ce="MESSAGE",ot="CLOSE",Zt="ERROR",Ho="SEND_FAIL";class Ba{constructor(){this._worker=null,this._blobUrl=null}connectSocket(B){const M=new Blob([` +**/let cW;const lZ=typeof window<"u"&&window.trustedTypes;if(lZ)try{cW=lZ.createPolicy("vue",{createHTML:e=>e})}catch{}const lX=cW?e=>cW.createHTML(e):e=>e,zrA="http://www.w3.org/2000/svg",ZrA="http://www.w3.org/1998/Math/MathML",Em=typeof document<"u"?document:null,IZ=Em&&Em.createElement("template"),XrA={insert:(e,i,n)=>{i.insertBefore(e,n||null)},remove:e=>{const i=e.parentNode;i&&i.removeChild(e)},createElement:(e,i,n,c)=>{const I=i==="svg"?Em.createElementNS(zrA,e):i==="mathml"?Em.createElementNS(ZrA,e):n?Em.createElement(e,{is:n}):Em.createElement(e);return e==="select"&&c&&c.multiple!=null&&I.setAttribute("multiple",c.multiple),I},createText:e=>Em.createTextNode(e),createComment:e=>Em.createComment(e),setText:(e,i)=>{e.nodeValue=i},setElementText:(e,i)=>{e.textContent=i},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>Em.querySelector(e),setScopeId(e,i){e.setAttribute(i,"")},insertStaticContent(e,i,n,c,I,C){const m=n?n.previousSibling:i.lastChild;if(I&&(I===C||I.nextSibling))for(;i.insertBefore(I.cloneNode(!0),n),!(I===C||!(I=I.nextSibling)););else{IZ.innerHTML=lX(c==="svg"?`${e}`:c==="mathml"?`${e}`:e);const R=IZ.content;if(c==="svg"||c==="mathml"){const _=R.firstChild;for(;_.firstChild;)R.appendChild(_.firstChild);R.removeChild(_)}i.insertBefore(R,n)}return[m?m.nextSibling:i.firstChild,n?n.previousSibling:i.lastChild]}},Uy="transition",NL="animation",UU=Symbol("_vtc"),IX={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},$rA=cI({},L9,IX),AaA=e=>(e.displayName="Transition",e.props=$rA,e),eaA=AaA((e,{slots:i})=>WrA(KsA,taA(e),i)),IM=(e,i=[])=>{Ln(e)?e.forEach(n=>n(...i)):e&&e(...i)},uZ=e=>e?Ln(e)?e.some(i=>i.length>1):e.length>1:!1;function taA(e){const i={};for(const Xe in e)Xe in IX||(i[Xe]=e[Xe]);if(e.css===!1)return i;const{name:n="v",type:c,duration:I,enterFromClass:C=`${n}-enter-from`,enterActiveClass:m=`${n}-enter-active`,enterToClass:R=`${n}-enter-to`,appearFromClass:_=C,appearActiveClass:T=m,appearToClass:b=R,leaveFromClass:J=`${n}-leave-from`,leaveActiveClass:gA=`${n}-leave-active`,leaveToClass:eA=`${n}-leave-to`}=e,CA=iaA(I),IA=CA&&CA[0],oA=CA&&CA[1],{onBeforeEnter:vA,onEnter:qA,onEnterCancelled:Ae,onLeave:HA,onLeaveCancelled:se,onBeforeAppear:WA=vA,onAppear:Ye=qA,onAppearCancelled:We=Ae}=i,Pe=(Xe,ae,Je,pt)=>{Xe._enterCancelled=pt,uM(Xe,ae?b:R),uM(Xe,ae?T:m),Je&&Je()},we=(Xe,ae)=>{Xe._isLeaving=!1,uM(Xe,J),uM(Xe,eA),uM(Xe,gA),ae&&ae()},et=Xe=>(ae,Je)=>{const pt=Xe?Ye:qA,$t=()=>Pe(ae,Xe,Je);IM(pt,[ae,$t]),EZ(()=>{uM(ae,Xe?_:C),cm(ae,Xe?b:R),uZ(pt)||dZ(ae,c,IA,$t)})};return cI(i,{onBeforeEnter(Xe){IM(vA,[Xe]),cm(Xe,C),cm(Xe,m)},onBeforeAppear(Xe){IM(WA,[Xe]),cm(Xe,_),cm(Xe,T)},onEnter:et(!1),onAppear:et(!0),onLeave(Xe,ae){Xe._isLeaving=!0;const Je=()=>we(Xe,ae);cm(Xe,J),Xe._enterCancelled?(cm(Xe,gA),BZ()):(BZ(),cm(Xe,gA)),EZ(()=>{Xe._isLeaving&&(uM(Xe,J),cm(Xe,eA),uZ(HA)||dZ(Xe,c,oA,Je))}),IM(HA,[Xe,Je])},onEnterCancelled(Xe){Pe(Xe,!1,void 0,!0),IM(Ae,[Xe])},onAppearCancelled(Xe){Pe(Xe,!0,void 0,!0),IM(We,[Xe])},onLeaveCancelled(Xe){we(Xe),IM(se,[Xe])}})}function iaA(e){if(e==null)return null;if(Ua(e))return[r3(e.enter),r3(e.leave)];{const i=r3(e);return[i,i]}}function r3(e){return AsA(e)}function cm(e,i){i.split(/\s+/).forEach(n=>n&&e.classList.add(n)),(e[UU]||(e[UU]=new Set)).add(i)}function uM(e,i){i.split(/\s+/).forEach(c=>c&&e.classList.remove(c));const n=e[UU];n&&(n.delete(i),n.size||(e[UU]=void 0))}function EZ(e){requestAnimationFrame(()=>{requestAnimationFrame(e)})}let oaA=0;function dZ(e,i,n,c){const I=e._endId=++oaA,C=()=>{I===e._endId&&c()};if(n!=null)return setTimeout(C,n);const{type:m,timeout:R,propCount:_}=naA(e,i);if(!m)return c();const T=m+"end";let b=0;const J=()=>{e.removeEventListener(T,gA),C()},gA=eA=>{eA.target===e&&++b>=_&&J()};setTimeout(()=>{b<_&&J()},R+1),e.addEventListener(T,gA)}function naA(e,i){const n=window.getComputedStyle(e),c=CA=>(n[CA]||"").split(", "),I=c(`${Uy}Delay`),C=c(`${Uy}Duration`),m=CZ(I,C),R=c(`${NL}Delay`),_=c(`${NL}Duration`),T=CZ(R,_);let b=null,J=0,gA=0;i===Uy?m>0&&(b=Uy,J=m,gA=C.length):i===NL?T>0&&(b=NL,J=T,gA=_.length):(J=Math.max(m,T),b=J>0?m>T?Uy:NL:null,gA=b?b===Uy?C.length:_.length:0);const eA=b===Uy&&/\b(transform|all)(,|$)/.test(c(`${Uy}Property`).toString());return{type:b,timeout:J,propCount:gA,hasTransform:eA}}function CZ(e,i){for(;e.lengthhZ(n)+hZ(e[c])))}function hZ(e){return e==="auto"?0:Number(e.slice(0,-1).replace(",","."))*1e3}function BZ(){return document.body.offsetHeight}function saA(e,i,n){const c=e[UU];c&&(i=(i?[i,...c]:[...c]).join(" ")),i==null?e.removeAttribute("class"):n?e.setAttribute("class",i):e.className=i}const HY=Symbol("_vod"),uX=Symbol("_vsh"),ha={beforeMount(e,{value:i},{transition:n}){e[HY]=e.style.display==="none"?"":e.style.display,n&&i?n.beforeEnter(e):GL(e,i)},mounted(e,{value:i},{transition:n}){n&&i&&n.enter(e)},updated(e,{value:i,oldValue:n},{transition:c}){!i!=!n&&(c?i?(c.beforeEnter(e),GL(e,!0),c.enter(e)):c.leave(e,()=>{GL(e,!1)}):GL(e,i))},beforeUnmount(e,{value:i}){GL(e,i)}};function GL(e,i){e.style.display=i?e[HY]:"none",e[uX]=!i}const raA=Symbol(""),aaA=/(^|;)\s*display\s*:/;function gaA(e,i,n){const c=e.style,I=vg(n);let C=!1;if(n&&!I){if(i)if(vg(i))for(const m of i.split(";")){const R=m.slice(0,m.indexOf(":")).trim();n[R]==null&&fY(c,R,"")}else for(const m in i)n[m]==null&&fY(c,m,"");for(const m in n)m==="display"&&(C=!0),fY(c,m,n[m])}else if(I){if(i!==n){const m=c[raA];m&&(n+=";"+m),c.cssText=n,C=aaA.test(n)}}else i&&e.removeAttribute("style");HY in e&&(e[HY]=C?c.display:"",e[uX]&&(c.display="none"))}const QZ=/\s*!important$/;function fY(e,i,n){if(Ln(n))n.forEach(c=>fY(e,i,c));else if(n==null&&(n=""),i.startsWith("--"))e.setProperty(i,n);else{const c=caA(e,i);QZ.test(n)?e.setProperty(CD(c),n.replace(QZ,""),"important"):e[c]=n}}const pZ=["Webkit","Moz","ms"],a3={};function caA(e,i){const n=a3[i];if(n)return n;let c=ch(i);if(c!=="filter"&&c in e)return a3[i]=c;c=RV(c);for(let I=0;Ig3||(EaA.then(()=>g3=0),g3=Date.now());function CaA(e,i){const n=c=>{if(!c._vts)c._vts=Date.now();else if(c._vts<=n.attached)return;lB(haA(c,n.value),i,5,[c])};return n.value=e,n.attached=daA(),n}function haA(e,i){if(Ln(i)){const n=e.stopImmediatePropagation;return e.stopImmediatePropagation=()=>{n.call(e),e._stopped=!0},i.map(c=>I=>!I._stopped&&c&&c(I))}else return i}const vZ=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,BaA=(e,i,n,c,I,C)=>{const m=I==="svg";i==="class"?saA(e,c,m):i==="style"?gaA(e,n,c):SV(i)?n4(i)||IaA(e,i,n,c,C):(i[0]==="."?(i=i.slice(1),!0):i[0]==="^"?(i=i.slice(1),!1):QaA(e,i,c,m))?(yZ(e,i,c),!e.tagName.includes("-")&&(i==="value"||i==="checked"||i==="selected")&&fZ(e,i,c,m,C,i!=="value")):e._isVueCE&&(/[A-Z]/.test(i)||!vg(c))?yZ(e,ch(i),c,C,i):(i==="true-value"?e._trueValue=c:i==="false-value"&&(e._falseValue=c),fZ(e,i,c,m))};function QaA(e,i,n,c){if(c)return!!(i==="innerHTML"||i==="textContent"||i in e&&vZ(i)&&ls(n));if(i==="spellcheck"||i==="draggable"||i==="translate"||i==="form"||i==="list"&&e.tagName==="INPUT"||i==="type"&&e.tagName==="TEXTAREA")return!1;if(i==="width"||i==="height"){const I=e.tagName;if(I==="IMG"||I==="VIDEO"||I==="CANVAS"||I==="SOURCE")return!1}return vZ(i)&&vg(n)?!1:i in e}const MZ=e=>{const i=e.props["onUpdate:modelValue"]||!1;return Ln(i)?n=>QY(i,n):i};function paA(e){e.target.composing=!0}function RZ(e){const i=e.target;i.composing&&(i.composing=!1,i.dispatchEvent(new Event("input")))}const c3=Symbol("_assign"),maA={created(e,{modifiers:{lazy:i,trim:n,number:c}},I){e[c3]=MZ(I);const C=c||I.props&&I.props.type==="number";U_(e,i?"change":"input",m=>{if(m.target.composing)return;let R=e.value;n&&(R=R.trim()),C&&(R=z3(R)),e[c3](R)}),n&&U_(e,"change",()=>{e.value=e.value.trim()}),i||(U_(e,"compositionstart",paA),U_(e,"compositionend",RZ),U_(e,"change",RZ))},mounted(e,{value:i}){e.value=i??""},beforeUpdate(e,{value:i,oldValue:n,modifiers:{lazy:c,trim:I,number:C}},m){if(e[c3]=MZ(m),e.composing)return;const R=(C||e.type==="number")&&!/^0\d/.test(e.value)?z3(e.value):e.value,_=i??"";R!==_&&(document.activeElement===e&&e.type!=="range"&&(c&&i===n||I&&e.value.trim()===_)||(e.value=_))}},faA=["ctrl","shift","alt","meta"],yaA={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>"button"in e&&e.button!==0,middle:e=>"button"in e&&e.button!==1,right:e=>"button"in e&&e.button!==2,exact:(e,i)=>faA.some(n=>e[`${n}Key`]&&!i.includes(n))},SE=(e,i)=>{const n=e._withMods||(e._withMods={}),c=i.join(".");return n[c]||(n[c]=(I,...C)=>{for(let m=0;m{const n=e._withKeys||(e._withKeys={}),c=i.join(".");return n[c]||(n[c]=I=>{if(!("key"in I))return;const C=CD(I.key);if(i.some(m=>m===C||DaA[m]===C))return e(I)})},SaA=cI({patchProp:BaA},XrA);let wZ;function dX(){return wZ||(wZ=yrA(SaA))}const wM=(...e)=>{dX().render(...e)},vaA=(...e)=>{const i=dX().createApp(...e),{mount:n}=i;return i.mount=c=>{const I=RaA(c);if(!I)return;const C=i._component;!ls(C)&&!C.render&&!C.template&&(C.template=I.innerHTML),I.nodeType===1&&(I.textContent="");const m=n(I,!1,MaA(I));return I instanceof Element&&(I.removeAttribute("v-cloak"),I.setAttribute("data-v-app","")),m},i};function MaA(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function RaA(e){return vg(e)?document.querySelector(e):e}function waA(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var xL={exports:{}},yY={exports:{}},_aA=yY.exports,_Z;function CX(){return _Z||(_Z=1,function(e,i){(function(n,c){e.exports=c()})(_aA,function(){const n=p=>p===void 0,c=p=>typeof p=="string",I=p=>{var B;return(B=Object.prototype.toString.call(p).match(/^\[object (.*)\]$/))===null||B===void 0?void 0:B[1].toLowerCase()},C=p=>typeof Array.isArray=="function"?Array.isArray(p):I(p)==="array",m=p=>p!==null&&typeof p=="object",R=p=>C(p)||m(p),_=p=>{if(typeof p!="string")return!1;const B=p[0];return!/[^a-zA-Z0-9]/.test(B)},T=p=>{if(typeof p!="object"||p===null)return!1;const B=Object.getPrototypeOf(p);if(B===null)return!0;let M=B;for(;Object.getPrototypeOf(M)!==null;)M=Object.getPrototypeOf(M);return B===M};function b(p=99999999){return Math.round(Math.random()*p)}const J=(p,B,M,G)=>{if(!R(p)||!R(B))return 0;let O=0;const z=Object.keys(B);let X;for(let cA=0,DA=z.length;cA"u"&&typeof uni.requireNativePlugin=="function",Ji=Xe&&typeof wx.miniapp=="object",Vi=typeof uni<"u",wn=pt&&typeof tt.enterChat=="function",Fi=Xe||Je||pt||Pt||ii||ao||ki,en=typeof window>"u"&&!Fi&&typeof Sg<"u"&&Sg.NativeScriptGlobals!==void 0,Ro=typeof Sg<"u"&&(Sg.nativeModuleProxy!==void 0||Sg.ReactNative!==void 0),oo=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,Ai=typeof uni<"u"?!Fi:typeof window<"u"&&!Fi&&!Ro,no=Je?qq:pt?tt:Pt?swan:ii?my:Xe?wx:ao?uni:ki?jd:{},Ri=Ai&&window&&window.navigator&&window.navigator.userAgent||"",pn=/(micromessenger|webbrowser)/i.test(Ri),jA=function(){let p="WEB";return pn?p="WEB":Je?p="QQ_MP":pt?p="TT_MP":Pt?p="BAIDU_MP":ii?p="ALI_MP":Xe?p=Ji?"DONUT_NATIVE_APP":"WX_MP":ao?p="UNI_NATIVE_APP":en?p="NS_NATIVE_APP":Ro&&(p="RN_NATIVE_APP"),eA[p]}(),ue=/iPad/i.test(Ri),He=/iPhone/i.test(Ri)&&!ue,Lt=/iPod/i.test(Ri),ct=He||ue||Lt,Ct=function(){const p=Ri.match(/OS (\d+)_/i);return p&&p[1]?p[1]:null}(),ei=/Android/i.test(Ri),Ht=function(){const p=Ri.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!p)return null;const B=p[1]&&parseFloat(p[1]),M=p[2]&&parseFloat(p[2]);return B&&M?parseFloat(`${p[1]}.${p[2]}`):B||null}(),Le=/Firefox/i.test(Ri),it=/Edge/i.test(Ri),Tt=!it&&/Chrome/i.test(Ri),Gt=/MSIE/.test(Ri)||Ri.indexOf("Trident")>-1&&Ri.indexOf("rv:11.0")>-1,Hi=function(){const p=/MSIE\s(\d+)\.\d/.exec(Ri);let B=p&&parseFloat(p[1]);return!B&&/Trident\/7.0/i.test(Ri)&&/rv:11.0/.test(Ri)&&(B=11),B}(),po=/Safari/i.test(Ri)&&!Tt&&!ei&&!it,To=/Windows/i.test(Ri),Zi=/MAC OS X/i.test(Ri),wo=Ai&&typeof Worker<"u"&&!Gt,Cn=ei||ct,an=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:p}=window.navigator;return!(!ct||p||po)}();function Vo(){let p="unknown";if(Zi&&(p="mac"),To&&(p="windows"),ct&&(p="ios"),ei&&(p="android"),Fi)try{const{platform:B}=no.getSystemInfoSync();B!==void 0&&(p=B)}catch(B){console.error(B)}return p}const jn=typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0&&typeof window>"u";function vo(p,B){var M={};for(var G in p)Object.prototype.hasOwnProperty.call(p,G)&&B.indexOf(G)<0&&(M[G]=p[G]);if(p!=null&&typeof Object.getOwnPropertySymbols=="function"){var O=0;for(G=Object.getOwnPropertySymbols(p);O{no.request({url:M,data:G,method:B,timeout:O,header:{"content-type":Fr},success:cA=>z(cA.data),fail:()=>X(new Error(`{"message":"Network error","code":${xs}}`))})}):jn?void 0:new Promise((z,X)=>{const cA=new XMLHttpRequest,DA=setTimeout(()=>{cA.abort(),X(new Error(`{"message":"Request timeout","code":${Zs}}`))},O);cA.onreadystatechange=function(){if(cA.readyState===4)if(clearTimeout(DA),cA.status===200||cA.status===304)try{z(cA.responseText?JSON.parse(cA.responseText):null)}catch{z(cA.responseText)}else X(new Error(`{"message":"Network error","code":${xs}}`))},cA.open(B,M,!0),cA.setRequestHeader("Content-type",Fr),cA.send(G||null)})})}function tn(p){if(p==null)return!0;if(typeof p=="boolean")return!1;if(typeof p=="number")return p===0;if(typeof p=="string"||typeof p=="function"||Array.isArray(p))return p.length===0;if(p instanceof Error)return p.message==="";if(T(p)){for(const B in p)if(Object.prototype.hasOwnProperty.call(p,B))return!1;return!0}return(Object.prototype.toString.call(p)==="[object Map]"||Object.prototype.toString.call(p)==="[object Set]"||Object.prototype.toString.call(p)==="[object File]")&&p.size===0}function Ks(p,B){if(p===null||typeof p!="object")return p;const M=B||new WeakMap;if(M.has(p))return M.get(p);if(p instanceof Date)return new Date(p.getTime());if(p instanceof RegExp)return new RegExp(p.source,p.flags);if(p instanceof Map){const z=new Map;return M.set(p,z),p.forEach((X,cA)=>{z.set(Ks(cA,M),Ks(X,M))}),z}if(p instanceof Set){const z=new Set;return M.set(p,z),p.forEach(X=>{z.add(Ks(X,M))}),z}if(Array.isArray(p)){const z=[];return M.set(p,z),p.forEach(X=>{z.push(Ks(X,M))}),z}const G=Object.getPrototypeOf(p),O=Object.create(G);return M.set(p,O),[...Object.getOwnPropertyNames(p),...Object.getOwnPropertySymbols(p)].forEach(z=>{if(z==="__ob__"||z==="__v_skip"||z==="__v_isRef"||z==="__v_isReadonly")return;const X=Object.getOwnPropertyDescriptor(p,z);X&&(X.get||X.set?Object.defineProperty(O,z,X):O[z]=Ks(p[z],M))}),O}function _n(p,B,M){const G=new WeakSet,O=(z,X)=>{if(B&&(X=B(z,X)),X===void 0)return"undefined";if(X===null)return null;if(Number.isNaN(X))return"NaN";if(X===1/0)return"Infinity";if(X===-1/0)return"-Infinity";if(typeof X=="function")return`[Function: ${X.name||"anonymous"}]`;if(typeof X=="symbol")return X.toString();if(typeof X=="bigint")return`${X.toString()}n`;if(typeof X=="object"&&X!==null){if(G.has(X))return"[Circular]";G.add(X)}return X instanceof Date?X.toISOString():X instanceof Error?{name:X.name,message:X.message}:X instanceof Map?{dataType:"Map",value:Array.from(X.entries())}:X instanceof Set?{dataType:"Set",value:Array.from(X.values())}:X};try{return JSON.stringify(p,O,M)}catch(z){return console.error("Failed to stringify:",z),""}}function Is(){let p,B;return{promise:new Promise((M,G)=>{p=M,B=G}),resolve:p,reject:B}}var qt,$a=Object.freeze({__proto__:null,ANDROID_VERSION:Ht,IE_VERSION:Hi,IN_ALIPAY_MINI_APP:ii,IN_BAIDU_MINI_APP:Pt,IN_BROWSER:Ai,IN_DONUT_NATIVE_APP:Ji,IN_FEISHU_MINI_APP:wn,IN_JD_MINI_APP:ki,IN_MINI_APP:Fi,IN_NODE:jn,IN_NS_NATIVE_APP:en,IN_QQ_MINI_APP:Je,IN_RN_APP:Ro,IN_TT_MINI_APP:pt,IN_TT_MINI_GAME:$t,IN_UNI_APP:Vi,IN_UNI_NATIVE_APP:ao,IN_WX_MINI_APP:Xe,IN_WX_MINI_APP_DESK:et,IN_WX_MINI_GAME:ae,IN_WX_MINI_PLUGIN:oo,IOS_VERSION:Ct,IS_ANDROID:ei,IS_CHROME:Tt,IS_EDGE:it,IS_FIREFOX:Le,IS_IE:Gt,IS_IOS:ct,IS_IPAD:ue,IS_IPHONE:He,IS_IPOD:Lt,IS_MAC:Zi,IS_SAFARI:po,IS_WECHAT:pn,IS_WIN:To,IS_WORKER_AVAILABLE:wo,MINI_APP_NAMESPACE:no,USER_AGENT:Ri,base16EncodeBinaryString:gA,deepCopyWithMethods:Ks,deepMerge:J,generatePromise:Is,getPlatformType:Vo,getType:I,httpRequest:qi,isArray:C,isArrayOrObject:R,isEmpty:tn,isH5:Cn,isIOSWebView:an,isNumber:p=>p!==null&&(typeof p=="number"&&!Number.isNaN(p-0)||typeof p=="object"&&p.constructor===Number),isObject:m,isPlainObject:T,isString:c,isUndefined:n,isUniIOSApp:function(){return ao&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:_,platform:jA,randomInt:b,randomString:function(){const p="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let B="";for(let M=32;M>0;--M)B+=p[Math.floor(62*Math.random())];return B},safeStringify:_n});class Ls{constructor(){this.listeners={}}on(B,M,G){this.listeners[B]||(this.listeners[B]=[]),this.listeners[B].push({fn:M,context:G})}off(B,M,G){var O;M&&(this.listeners[B]=(O=this.listeners[B])===null||O===void 0?void 0:O.filter(z=>{const X=z.fn===M,cA=!G||z.context===G;return!(X&&cA)}))}emit(B,...M){const G=this.listeners[B];G&&G.forEach(O=>{const{fn:z,context:X}=O;try{z.apply(X,M)}catch(cA){console.warn(`Error in event handler for ${B} error: ${_n(cA)}`)}})}once(B,M,G){const O=(...z)=>{M.apply(G,z),this.off(B,O)};this.on(B,O)}}(function(p){p.BUSINESS_COMMAND="business_command",p.C2C_REALTIME_MESSAGE="c2c_realtime_message",p.C2C_MESSAGE_MODIFIED="c2c_message_modified",p.C2C_REVOKED_MESSAGE="c2c_message_revoked",p.GROUP_REALTIME_MESSAGE="group_realtime_message",p.GROUP_MESSAGE_MODIFIED="group_message_modified",p.GROUP_MESSAGE_REVOKED="group_message_revoked",p.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",p.MESSAGE_REACTION_UPDATED="message_reaction_updated",p.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",p.GROUP_AT_TIPS="group_at_tips",p.USER_STATUS_UPDATE="user_status_update",p.FRIEND_LIST_MODIFIED="friend_list_modified",p.PROFILE_MODIFIED="profile_modified",p.CONV_MODIFIED="conversation_modified",p.GROUP_TIPS_NOTIFICATION="group_tips_notification",p.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",p.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",p.GROUP_SYSTEM_NOTIFICATION="group_system_notification",p.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",p.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",p.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",p.FOLLOW_LIST_UPDATED="follow_list_updated",p.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",p.ALL_MESSAGE_READ="all_message_read",p.CONVERSATION_MARK_UPDATED="conversation_mark_updated",p.CONVERSATION_GROUP_ADD="conversation_group_add",p.CONVERSATION_GROUP_DELETED="conversation_group_deleted",p.CONVERSATION_GROUP_UPDATED="conversation_group_updated",p.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",p.TOPIC_AT_TIPS="topic_at_tips",p.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",p.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",p.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",p.TOPIC_LATEST_MESSAGE="topic_latest_message",p.GROUP_MESSAGE_PINNED="group_message_pinned"})(qt||(qt={}));const Bs=[16,17];function Un(p){var B;const M=[];return(B=p?.GroupTips)===null||B===void 0||B.forEach(G=>{var O;G.GroupInfo.MillionGroupFlag===2?M.push(qt.TOPIC_TIPS_NOTIFICATION):Bs.includes((O=G?.MsgBody)===null||O===void 0?void 0:O.OpType)?M.push(qt.GROUP_MESSAGE_PINNED):M.push(qt.GROUP_TIPS_NOTIFICATION)}),M}const ur=[{conditions:[{type:"event",value:100}],subType:qt.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:qt.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:qt.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:qt.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:qt.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:qt.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:qt.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:qt.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:qt.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:qt.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(p){var B;const M=[];return(B=p?.C2cNotifyMsgArray)===null||B===void 0||B.forEach(G=>{G.WithdrawC2cMsgNotify&&M.push(qt.C2C_REVOKED_MESSAGE),G.C2cReadedReceipt&&M.push(qt.C2C_MESSAGE_PEER_READ),G.ReadC2cMsgNotify&&M.push(qt.C2C_MESSAGE_READ_SYNC),G.MuteNotificationsSync&&M.push(qt.C2C_REMIND_TYPE_SYNC)}),M}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Un},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(p){var B;const M=[];return(B=p?.GroupTips)===null||B===void 0||B.forEach(G=>{Array.isArray(G.MsgBody.GroupWithdrawInfoArray)?M.push(qt.GROUP_MESSAGE_REVOKED):Array.isArray(G.MsgBody.GroupMsgReceiptList)?M.push(qt.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(G.MsgBody.GroupReadInfoArray)?G.MsgBody.GroupReadInfoArray[0].TopicId?M.push(qt.TOPIC_MESSAGE_READ_SYNC):M.push(qt.GROUP_MESSAGE_READ_SYNC):G.GroupInfo.MillionGroupFlag===2?M.push(qt.TOPIC_SYSTEM_NOTIFICATION):M.push(qt.GROUP_SYSTEM_NOTIFICATION)}),M}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:Un},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(p){var B;const M=[];return(B=p?.GroupTips)===null||B===void 0||B.forEach(G=>{const{GroupAtTips:{TopicId:O}}=G;O?M.push(qt.TOPIC_AT_TIPS):M.push(qt.GROUP_AT_TIPS)}),M}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(p){var B;const M=[];return(B=p?.RecentContactMod)===null||B===void 0||B.forEach(G=>{switch(G.PushType){case Pe.CONV_MARK_UPDATED:M.push(qt.CONVERSATION_MARK_UPDATED);break;case Pe.CONV_GROUP_ADDED:M.push(qt.CONVERSATION_GROUP_ADD);break;case Pe.CONV_GROUP_DELETED:M.push(qt.CONVERSATION_GROUP_DELETED);break;case Pe.CONV_GROUP_UPDATED:M.push(qt.CONVERSATION_GROUP_UPDATED);break;default:M.push(qt.CONV_MODIFIED)}}),M}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:qt.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:qt.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:qt.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:qt.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:qt.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:qt.ALL_MESSAGE_READ}];var Fn;function rr(p){var B;const M=Array.isArray((B=p?.body)===null||B===void 0?void 0:B.EventArray)?p.body.EventArray:[],G=[];return M.forEach(O=>{O.Flag=p.body.Flag;const z=ur.find(cA=>cA.conditions.every(DA=>{switch(DA.type){case"event":return O.Event===DA.value;case"hasKey":return Object.prototype.hasOwnProperty.call(O,DA.value);default:return!1}}));if(!z)return null;let X=[];typeof z.subTypeParser=="function"?X=z.subTypeParser(O):z.subType&&(X=z.subType),Array.isArray(X)?X.forEach(cA=>{G.push({type:`${Fn.SERVER_PUSH_MESSAGE}:${cA}`,data:O})}):G.push({type:`${Fn.SERVER_PUSH_MESSAGE}:${X}`,data:O})}),G}(function(p){p.SERVER_PUSH_MESSAGE="im_open_push.msg_push",p.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",p.ERROR="error"})(Fn||(Fn={}));const fo={[Fn.SERVER_PUSH_MESSAGE]:rr,[Fn.SERVER_PUSH_MESSAGE_MULTIPLE]:rr,[Fn.ERROR]:function(p){const{errorCode:B}=p;return[{type:`error:${B}`,data:p}]}},es=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._filteredCallbackMap=new Map,this._outerEventEmitter=new Ls,this._innerEventEmitter=new Ls,this.InnerEventSubType=qt}subscribeInnerEvent(p,B,M,G,O){var z;let X,cA,DA,GA;["string","number"].includes(typeof B)?(DA=`${p}:${B}`,GA=M,cA=G,X=O):(DA=p,GA=B,cA=M,X=typeof G=="function"?G:void 0),X?this._subscribeWithFilter(DA,GA,cA,X):(z=this._innerEventEmitter)===null||z===void 0||z.on(DA,GA,cA)}emitInnerEvent(p,B){var M,G;if((M=this._innerEventEmitter)===null||M===void 0||M.emit(p,B),Object.keys(fo).includes(p)){const O=(G=fo[p])===null||G===void 0?void 0:G.call(fo,B);O?.forEach(z=>{var X;z&&((X=this._innerEventEmitter)===null||X===void 0||X.emit(z.type,z.data))})}}subscribeOuterEvent(p,B,M){var G;(G=this._outerEventEmitter)===null||G===void 0||G.on(p,B,M)}unSubscribeOuterEvent(p,B,M){var G;(G=this._outerEventEmitter)===null||G===void 0||G.off(p,B,M)}unSubscribeInnerEvent(p,B,M,G){if(["string","number"].includes(typeof B)){const O=M,z=`${p}:${B}`;this._unsubscribeEvent(z,O,G)}else{const O=B;this._unsubscribeEvent(p,O,M)}}emitOuterEvent(p,B){var M;(M=this._outerEventEmitter)===null||M===void 0||M.emit(p,B)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}_subscribeWithFilter(p,B,M,G){var O;const z=X=>{G.call(M,X)&&B.call(M,X)};this._filteredCallbackMap.has(p)||this._filteredCallbackMap.set(p,[]),this._filteredCallbackMap.get(p).push({originalCallback:B,filteredCallback:z,filter:G,context:M}),(O=this._innerEventEmitter)===null||O===void 0||O.on(p,z,M)}_unsubscribeEvent(p,B,M){var G,O;const z=this._filteredCallbackMap.get(p);if(z){const X=z.findIndex(cA=>cA.originalCallback===B&&cA.context===M);if(X!==-1){const{filteredCallback:cA}=z[X];return(G=this._innerEventEmitter)===null||G===void 0||G.off(p,cA,M),z.splice(X,1),void(z.length===0&&this._filteredCallbackMap.delete(p))}}(O=this._innerEventEmitter)===null||O===void 0||O.off(p,B,M)}};class vc{constructor(){this._socket=null}connectSocket(B){return this._socket=new WebSocket(B),this._socket}send(B){var M,G;try{(M=this._socket)===null||M===void 0||M.send(B)}catch(O){(G=this._onSendFail)===null||G===void 0||G.call(this,O)}}bindSocketHandlers(B){const{onOpen:M,onMessage:G,onClose:O,onError:z,onSendFail:X}=B;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=M,this._socket.onmessage=G,this._socket.onclose=O,this._socket.onerror=z,this._onSendFail=X)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class ts{constructor(B){this._onError=B.onError}connectSocket(B){const M=this;return this._socket=no.connectSocket({url:B,header:{"content-type":"application/json"},complete:()=>{},fail:G=>M._onError(G)}),this._socket}send(B){var M;(M=this._socket)===null||M===void 0||M.send({data:B,fail:this._onSendFail})}bindSocketHandlers(B){const{onOpen:M,onMessage:G,onClose:O,onError:z,onSendFail:X}=B;this._socket&&(this._socket.onClose(O),this._socket.onOpen(M),this._socket.onMessage(G),this._socket.onError(z),this._onSendFail=X)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const Er="CONNECT",On="SEND",Mg="DISCONNECT",yn="OPEN",ce="MESSAGE",ot="CLOSE",Zt="ERROR",Ho="SEND_FAIL";class Ba{constructor(){this._worker=null,this._blobUrl=null}connectSocket(B){const M=new Blob([` let _socket = null; self.onmessage = (event) => { @@ -211,11 +211,11 @@ _socket = null; } } -`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(M)),this._worker.postMessage({type:ur,url:B})}send(B){var M,G;try{(M=this._worker)===null||M===void 0||M.postMessage({type:On,data:B})}catch(O){(G=this._onSendFail)===null||G===void 0||G.call(this,O)}}bindSocketHandlers(B){const{onOpen:M,onMessage:G,onClose:O,onError:z,onSendFail:X}=B;if(this._worker){const gA={[yn]:M,[ce]:G,[ot]:O,[Zt]:z,[Ho]:X};this._onSendFail=X,this._worker.onmessage=DA=>{var GA;const{type:KA}=DA?.data||{};typeof gA[KA]=="function"&&((GA=gA[KA])===null||GA===void 0||GA.call(gA,DA?.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:vg}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class WI{}var gn,ro=new class{constructor(){this._store=new Map}get(p){return this._store.get(p)}getStorage(p){return Fi?ii?my.getStorageSync({key:p}).data:no.getStorageSync(p):this._canUseLocalStorage()?localStorage.getItem(p):{}}set(p,B){const M=this._store.get(p)||{};B instanceof Map?this._store.set(p,B):this._store.set(p,Object.assign(Object.assign({},M),B))}setStorage(p,B){Fi?ii?my.setStorageSync({key:p,data:JSON.stringify(B)}):no.setStorageSync(p,JSON.stringify(B)):this._canUseLocalStorage()&&localStorage.setItem(p,JSON.stringify(B))}clear(p){typeof p=="string"?this._store.set(p,{}):this._store.clear()}clearLocalStorage(p){this._canUseLocalStorage()&&(typeof p=="string"?localStorage.setItem(p,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return typeof window<"u"&&navigator&&navigator.cookieEnabled&&localStorage}};class Mc{connectSocket(B){return this._socket=no.connectSocket({url:B,header:{"content-type":"application/json"},multiple:!0,complete:()=>{}}),this._socket}send(B){var M;(M=this._socket)===null||M===void 0||M.send({data:B,fail:this._onSendFail})}bindSocketHandlers(B){const{onOpen:M,onMessage:G,onClose:O,onError:z,onSendFail:X}=B;this._socket&&(this._socket.onClose(O),this._socket.onOpen(M),this._socket.onMessage(gA=>G(gA?.data)),this._socket.onError(()=>z),this._onSendFail=X)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}(function(p){p[p.CONNECTED=0]="CONNECTED",p[p.CONNECTING=1]="CONNECTING",p[p.DISCONNECTED=2]="DISCONNECTED"})(gn||(gn={}));class gg{constructor(B){this._url="",this._readyState=gn.DISCONNECTED,this._url=B,this._id=b(),this._emitter=new Ls,ii?this._socket=new Mc:Xe||ao||pt||Je||ki||Pt?this._socket=new ts({onError:this._onError.bind(this)}):jn?this._socket=new WI:this._canUseWebWorker()?this._socket=new Ba:this._socket=new vc,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[gn.CONNECTED,gn.CONNECTING].includes(this._readyState)||(this._readyState=gn.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(B){this._readyState!==gn.CONNECTED?this.reconnect():this._socket.send(B)}reconnect(){[gn.CONNECTED,gn.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(B,M,G){this._emitter.on(B,M,G)}off(B,M,G){this._emitter.off(B,M,G)}isConnected(){return this._readyState===gn.CONNECTED}disconnect(){this._readyState=gn.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(B){this._readyState===gn.CONNECTING&&(this._readyState=gn.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:B}))}_onMessage(B){this._emitter.emit("message",B)}_onClose(B){this._readyState=gn.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:B})}_onError(B){this._readyState=gn.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:B})}_onSendFail(B){this._readyState=gn.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:B})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}_canUseWebWorker(){const B=ro.get("cloudConfig")||{};return(n(B.isWorkerEnabled)||B.isWorkerEnabled==="1")&&wo}}const Mg={[Ye.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[Ye.KOREA]:[[3e7,4e7],[173e7,174e7]],[Ye.GERMANY]:[[4e7,5e7],[174e7,175e7]],[Ye.IND]:[[5e7,6e7],[175e7,176e7]],[Ye.JPN]:[[6e7,7e7],[176e7,177e7]],[Ye.USA]:[[7e7,8e7],[177e7,178e7]],[Ye.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[Ye.KSA]:[[9e7,1e8],[179e7,18e8]]};function Qa(p){var B;if(!((B=ro.get("instance"))===null||B===void 0)&&B.oversea)return Ye.OVERSEA;for(const M of Object.keys(Mg))for(const[G,O]of Mg[M])if(p>=G&&p`${re}=${KA[re]}`).join("&"));var KA;return M?`${p}/binfo?${GA}&compress=gzip`:`${p}/info?${GA}`}function is(p){const B=ro.get("instance"),{sdkAppId:M,testEnv:G,proxyServer:O}=B,z=Qa(M);if(G)return Xs(We.TEST[z].DEFAULT,{isBinary:p});if(!tn(O))return Xs(O,{isBinary:p});const X=We.PRODUCTION[z],gA=Ai&&X.ANYCAST,DA=Ai,GA=!!X.BACKUP_CN;return Xs({[Fo.INITIAL]:()=>(Uo=Fo.DEFAULT,X.DEFAULT),[Fo.DEFAULT]:()=>(Uo=Fo.IPV6,X.IPV6),[Fo.IPV6]:()=>(Uo=Fo.BACKUP,X.BACKUP),[Fo.BACKUP]:()=>DA?(Uo=Fo.BACKUP_WEB_ONLY,function(KA){const re=Math.floor(10001*Math.random())+1e4;return KA.replace("*",String(re))}(X.BACKUP_WEB_ONLY)):GA?(Uo=Fo.BACKUP_CN,X.BACKUP_CN):gA?(Uo=Fo.ANYCAST,X.ANYCAST):X.DEFAULT,[Fo.BACKUP_WEB_ONLY]:()=>GA?(Uo=Fo.BACKUP_CN,X.BACKUP_CN):gA?(Uo=Fo.ANYCAST,X.ANYCAST):X.DEFAULT,[Fo.BACKUP_CN]:()=>(Uo=gA?Fo.ANYCAST:Fo.DEFAULT,X[Uo]),[Fo.ANYCAST]:()=>(Uo=Fo.DEFAULT,X.ANYCAST="",X.DEFAULT)}[Uo](),{isBinary:p})}var Rg=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(p,B){const M=Date.now(),G=M-p;this._timeOffsetWithServer=B+G-M}};const Rc=16;var ws=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(p){const{id:B}=p;this.removeTask(B),this._tasks.push(p),this._taskMap.set(B,p),this._sort(),this._scheduleNextTask()}_createTask(p){const{id:B,callback:M,context:G,isOnce:O=!1,intervalMs:z=Rc}=p,X=Math.max(z,Rc);return{id:B,nextExecuteTime:Date.now()+X,intervalMs:z,callback:M,context:G,isOnce:O}}addTask(p){const B=this._createTask(p);this._addTaskToScheduler(B)}addOnceTask(p){const B=this._createTask(Object.assign(Object.assign({},p),{isOnce:!0}));this._addTaskToScheduler(B)}removeTask(p){const B=this._tasks.findIndex(M=>M.id===p);B>-1&&(this._tasks.splice(B,1),this._taskMap.delete(p),this._scheduleNextTask())}updateTaskInterval(p,B){const M=this._taskMap.get(p);M&&(M.intervalMs=B,M.nextExecuteTime=Date.now()+B,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((p,B)=>p.nextExecuteTime-B.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const p=this._tasks[0];if(p){const B=Math.max(0,p.nextExecuteTime-Date.now());this._timer=setTimeout(()=>this._execute(),B)}}_execute(){const p=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=p;){const B=this._tasks[0];try{B.context?B.callback.call(B.context):B.callback(),B.isOnce?this.removeTask(B.id):(B.nextExecuteTime=p+B.intervalMs,this._sort())}catch(M){console.warn(`Task ${B.id} execution failed:`,M),B.isOnce&&this.removeTask(B.id)}}this._scheduleNextTask()}};function Fa(p){const B=[];for(let M=0;M=55296&&G<=56319){const O=p.charCodeAt(++M)-56320+(G-55296<<10)+65536;B.push(240|O>>18,128|O>>12&63,128|O>>6&63,128|63&O)}else G<=127?B.push(G):G<=2047?B.push(192|G>>6,128|63&G):B.push(224|G>>12,128|G>>6&63,128|63&G)}return new Uint8Array(B)}function Qs(p){const B=Array.isArray(p)?[]:Object.create(null);for(const M in p)Object.prototype.hasOwnProperty.call(p,M)&&_(M)&&p[M]!=null&&(p[M]===null||typeof p[M]!="object"?B[M]=p[M]:B[M]=Qs(p[M]));return B}function Tn(p,B){if(CA.includes(p))return 0;const M=Fa(JSON.stringify(B));let G=4294967295;const{length:O}=M;for(let z=0;z>>=1:G=G>>>1^3988292384}return(4294967295^G)>>>0}function pa(p){const{servcmd:B,data:M}=p,G=function(z){const X=ro.get("login")||{},gA=ro.get("instance")||{};return{servcmd:z,ver:"v4",platform:jA,websdkappid:537048168,websdkversion:"1.7.3",a2:X.a2Key||void 0,tinyid:X.tinyID||void 0,status_instid:X.statusInstanceId||0,sdkappid:gA.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:X.a2Key?void 0:X.userId,usersig:X.a2Key?void 0:X.userSig,sdkability:478343027,sdkability_ext:cA(""),cappid:gA.applicationID||0,tjgID:"",seq:Ta(),cs:0}}(B),O=Qs(M);return G.cs=Tn(B,O),{head:G,body:O}}function _s(p){const{servcmd:B,data:M}=p,G=function(z){const X=ro.get("login")||{},gA=ro.get("instance")||{};return{servcmd:z,ver:"v4",platform:jA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:gA.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:X.statusInstanceId||0,sdkability:478343027,sdkability_ext:cA(""),cappid:gA.applicationID||0,seq:Ta(),cs:0}}(B),O=Qs(M);return G.cs=Tn(B,O),{head:G,body:O}}let Oa=b();function Ta(){return Oa=Oa<2415919103?Oa+1:b(),Oa}function $(){var p;const B=ro.get("login")||{},M=ro.get("instance")||{};return{sdk_type:30,sdk_app_id:M.sdkAppId,sdk_version:"1.6.18",tiny_id:Number(B.tinyID),user_id:B.userId||((p=ro.get("webPush"))===null||p===void 0?void 0:p.userId),platform:jA,instance_id:M.instanceId,trace_id:new Date().getTime()}}var j,RA=Object.freeze({__proto__:null,calcBodyCRC:Tn,filterProtocolDataInvalidFields:Qs,generateCosSpecifiedData:function(p){const{servcmd:B,data:M}=p,G=function(z){const X=ro.get("login")||{},gA=ro.get("instance")||{};return{servcmd:z,ver:"v4",platform:jA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:gA.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:X.userId,usersig:X.userSig,status_instid:X.statusInstanceId||0,sdkability:478343027,sdkability_ext:cA(""),cappid:gA.applicationID||0,seq:Ta(),cs:0}}(B),O=Qs(M);return G.cs=Tn(B,O),{head:G,body:O}},generateProtocolData:pa,generateSSOLogProtocolData:_s,generateSequence:Ta,getCommonHead:$,getHostSite:Qa,taskScheduler:ws,timeManager:Rg});(function(p){p[p.info=4]="info",p[p.warning=5]="warning",p[p.error=6]="error"})(j||(j={}));const ZA={method:"extension",networkType:"network_type",eventType:"event_type",code:"error_code",message:"error_message",moreMessage:"more_message",duplicate:"duplicate",costTime:"cost_time",level:"level",uiPlatform:"ui_platform",timestamp:"timestamp"};class ne{constructor(B){this.level=j.info,this._canSendLog=!0,this._logCreatedAt=Rg.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();const{method:M,eventType:G=0,message:O="",costTime:z=0,error:X,uiPlatform:gA,moreMessage:DA="",code:GA=0,startTime:KA=0}=B||{};this.eventType=G,this.method=M,this.message=O,this.costTime=z,this.moreMessage=`${DA} startTime:${KA}`,this.code=GA,X&&this.setError(X),tn(gA)||(this.uiPlatform=gA)}setMoreMessage(B){this.moreMessage=`${this.moreMessage} ${B}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Rg.getTimeOffsetWithServer()}end(B=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=Rg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),B&&this._ssoLogModule.uploadSSOLogData())}setError(B){var M;return B instanceof Error?this._canSendLog?(!((M=ro.get("netWorkMonitor"))===null||M===void 0)&&M.isNetworkOnline&&(B.errorCode&&(this.code=B.errorCode),B.errorMessage&&this.setMoreMessage(B.errorMessage)),this.level=j.error,this):this:(console.warn("SSOLogData.setError value not instanceof Error, please check!"),this)}setLogInfo(B){return Object.keys(B).forEach(M=>{Object.keys(ZA).includes(M)&&(this[M]=B[M])}),this}setSSOLogModule(B){this._ssoLogModule=B}_convertSSOLogDataKeyToServe(){const B={};return Object.keys(this).forEach(M=>{const G=M;ZA[G]&&(B[ZA[G]]=this[G])}),B}_getUiPlatform(){var B;const M=(B=ro.get("instance"))===null||B===void 0?void 0:B.scene;if(typeof M=="string"){const G=Number(M);return isNaN(G)?void 0:G}}_getSDKEdition(){var B;return(B=ro.get("instance"))===null||B===void 0?void 0:B.sdkEdition}}var De;(function(p){p.RECONNECTED="reconnected",p.CLOUD_CONFIG_UPDATE="cloud_config_update",p.SOCKET_DISCONNECTED="socket_disconnected"})(De||(De={}));var Ke=De;const qe=20,Et=6e4,ft=[4,5,6],Nt="report-logger";var Kt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=qe,this._maxThreshold=100,this._waitingTime=Et,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=IA.DEBUG,this._throttleConfig={global:{throttleTime:se,maxCount:WA},single:{throttleTime:Ae,maxCount:HA}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,es.subscribeInnerEvent(Ke.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),ws.addTask({id:Nt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(p){const{evt_rpt_threshold:B=qe,evt_rpt_waiting:M=Et,evt_rpt_level:G=ft,evt_rpt_sdkappid_bl:O="",evt_rpt_tinyid_wl:z="",evt_rpt_global_throttle_time:X=se,evt_rpt_global_throttle_count:gA=WA,evt_rpt_single_throttle_time:DA=Ae,evt_rpt_single_throttle_count:GA=HA}=p||{};this._sdkAppIdBlackList=O.split(",").map(KA=>Number(KA)),this._waitingTime=Number(M),this._minThreshold=B,this._reportLevel=G,this._tinyIdWhiteList=z.split(","),this._throttleConfig={global:{throttleTime:X,maxCount:gA},single:{throttleTime:DA,maxCount:GA}}}createSSOLogData(p){const B=new ne(p);return B.setSSOLogModule(this),this._ssoLogMap.set(p.method,B),B}getSSOLogData(p){return this._ssoLogMap.get(p)||{}}pushToLogQueue(p){p&&(this._logQueue.push(p),this._shouldUploadImmediately()&&this.uploadSSOLogData())}setLogLevel(p){[IA.DEBUG,IA.ERROR,IA.INFO,IA.NONE,IA.WARN].includes(p)&&(this._logLevel=p)}debug(p,B="",M){this._log(IA.DEBUG,p,B,M)}info(p,B="",M){this._log(IA.INFO,p,B,M)}warn(p,B="",M){this._log(IA.WARN,p,B,M)}error(p,B="",M){this._log(IA.ERROR,p,B,M)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this.uploadSSOLogData()}uploadSSOLogData(){return mA(this,void 0,void 0,function*(){if(this._logQueue.length===0)return;const p=this._logQueue.slice();this._logQueue=[];try{const B=this._filterLogs(p);if(B.length===0)return void(this._lastReportAt=Date.now());const M={Header:$(),Event:B};tn(M.Header.user_id)||(yield function(G){const O="imopenstat.tim_web_report_v2",z=_s({servcmd:O,data:G}),X=`${z.head.seq}${O}`;return Nl.sendPacket(z,{requestId:X})}(M))}catch(B){this._requeueFailedLogs(p),this.debug("uploadSSOLogData",_n(B))}finally{this._lastReportAt=Date.now()}})}_requeueFailedLogs(p){this._logQueue=p.concat(this._logQueue);const B=this._logQueue.length-200;B>0&&(this._logQueue.splice(0,B),this.debug("uploadSSOLogData",`log queue overflow, dropped ${B} oldest logs`))}_savePlatFormInfo(){var p,B;if(Xe){const M=(B=(p=wx.getAccountInfoSync)===null||p===void 0?void 0:p.call(wx))===null||B===void 0?void 0:B.miniProgram;if(M){const{appId:G,envVersion:O}=M;ro.set("instance",{appId:G,envVersion:O})}}else Ai&&ro.set("instance",{href:window.location.href})}_filterLogs(p){const{tinyID:B}=ro.get("login")||{},{sdkAppId:M}=ro.get("instance")||{};return this._sdkAppIdBlackList.includes(M)&&!this._tinyIdWhiteList.includes(B)?[]:p.filter(G=>this._reportLevel.includes(G.level))}_checkThrottle(p){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(p)}_checkGlobalThrottle(){const p=Date.now();if(p-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=p;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(p){const B=Date.now(),M=this._singleThrottleMap.get(p);return M?B-M.startTime>=this._throttleConfig.single.throttleTime?(M.count=1,M.startTime=B,!1):M.count>=this._throttleConfig.single.maxCount||(M.count++,!1):(this._singleThrottleMap.set(p,{count:1,startTime:B}),!1)}_shouldLog(p){return p>=this._logLevel&&this._logLevel!==IA.NONE}_shouldReport(p){return this._reportLevel.includes(qA[p])}_formatLog(p,B,M,G){const O=new Date,z=`${O.getHours()}:${O.getMinutes()}:${O.getSeconds()}:${O.getMilliseconds()}`,X=`<${IA[p]}>`;return Gt||Fi?[`${oA} [${z}] ${X} [${B}] ${M}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",oA,"",`[${z}] ${X} [${B}] ${M} params: ${_n(G)}`]}_log(p,B,M,G){if(this._shouldLog(p)){const O=this._formatLog(p,B,M,G);vA[p].apply(console,O)}if(this._shouldReport(p)){const O=this._getThrottleKey(B,M,G);this._checkThrottle(O)||this.createSSOLogData(Object.assign(Object.assign({message:M},G),{method:B})).end()}}_getThrottleKey(p,B,M){const G=`${p}${B}${_n(Object.assign(Object.assign({},M),{costTime:""}))}`,O=Fa(JSON.stringify(G));let z=4294967295;const{length:X}=O;for(let gA=0;gA>>=1:z=z>>>1^3988292384}return`${(4294967295^z)>>>0}`}reset(){console.log("SSO_LOG_MODULE.reset"),ws.removeTask(Nt),es.unSubscribeInnerEvent(Ke.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=qe,this._maxThreshold=100,this._waitingTime=Et,this._logQueue=[],this._logLevel=IA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const di=15e3,Bt="Channel",Jt="channel_schedule_task",$i="channel_reconnect_task",eo="connected",os="connecting",Ti="disconnected",on=1e3,wg="network_status_change",Er="activity_status_change",Mr="send_fail",js="reconnect_failed",Tl="socket_error",ns="socket_close";function uI(p){return uI=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(B){return typeof B}:function(B){return B&&typeof Symbol=="function"&&B.constructor===Symbol&&B!==Symbol.prototype?"symbol":typeof B},uI(p)}function ec(p){throw new Error('Could not dynamically require "'+p+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var wc,Tu={exports:{}},Na=(wc||(wc=1,function(p){p.exports=function B(M,G,O){function z(DA,GA){if(!G[DA]){if(!M[DA]){if(!GA&&ec)return ec(DA);if(X)return X(DA,!0);var KA=new Error("Cannot find module '"+DA+"'");throw KA.code="MODULE_NOT_FOUND",KA}var re=G[DA]={exports:{}};M[DA][0].call(re.exports,function(Qe){return z(M[DA][1][Qe]||Qe)},re,re.exports,B,M,G,O)}return G[DA].exports}for(var X=ec,gA=0;gA>>6:(Qe<65536?re[dt++]=224|Qe>>>12:(re[dt++]=240|Qe>>>18,re[dt++]=128|Qe>>>12&63),re[dt++]=128|Qe>>>6&63),re[dt++]=128|63&Qe);return re},G.buf2binstring=function(KA){return GA(KA,KA.length)},G.binstring2buf=function(KA){for(var re=new O.Buf8(KA.length),Qe=0,At=re.length;Qe>10&1023,Wt[At++]=56320|1023<)}return GA(Wt,At)},G.utf8border=function(KA,re){var Qe;for((re=re||KA.length)>KA.length&&(re=KA.length),Qe=re-1;0<=Qe&&(192&KA[Qe])==128;)Qe--;return Qe<0||Qe===0?re:Qe+gA[KA[Qe]]>re?Qe:re}},{"./common":1}],3:[function(B,M,G){M.exports=function(O,z,X,gA){for(var DA=65535&O,GA=O>>>16&65535,KA=0;X!==0;){for(X-=KA=2e3>>1:z>>>1;X[gA]=z}return X}();M.exports=function(z,X,gA,DA){var GA=O,KA=DA+gA;z^=-1;for(var re=DA;re>>8^GA[255&(z^X[re])];return-1^z}},{}],6:[function(B,M,G){M.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(B,M,G){M.exports=function(O,z){var X,gA,DA,GA,KA,re,Qe,At,lt,dt,xt,Wt,Ki,Eo,so,hi,qo,cn,yi,to,rs,be,bt,OA,oi;X=O.state,gA=O.next_in,OA=O.input,DA=gA+(O.avail_in-5),GA=O.next_out,oi=O.output,KA=GA-(z-O.avail_out),re=GA+(O.avail_out-257),Qe=X.dmax,At=X.wsize,lt=X.whave,dt=X.wnext,xt=X.window,Wt=X.hold,Ki=X.bits,Eo=X.lencode,so=X.distcode,hi=(1<>>=yi=cn>>>24,Ki-=yi,(yi=cn>>>16&255)==0)oi[GA++]=65535&cn;else{if(!(16&yi)){if(!(64&yi)){cn=Eo[(65535&cn)+(Wt&(1<>>=yi,Ki-=yi),Ki<15&&(Wt+=OA[gA++]<>>=yi=cn>>>24,Ki-=yi,!(16&(yi=cn>>>16&255))){if(!(64&yi)){cn=so[(65535&cn)+(Wt&(1<>>=yi,Ki-=yi,(yi=GA-KA)>3,Wt&=(1<<(Ki-=to<<3))-1,O.next_in=gA,O.next_out=GA,O.avail_in=gA>>24&255)+(be>>>8&65280)+((65280&be)<<8)+((255&be)<<24)}function Wt(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new O.Buf16(320),this.work=new O.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Ki(be){var bt;return be&&be.state?(bt=be.state,be.total_in=be.total_out=bt.total=0,be.msg="",bt.wrap&&(be.adler=1&bt.wrap),bt.mode=At,bt.last=0,bt.havedict=0,bt.dmax=32768,bt.head=null,bt.hold=0,bt.bits=0,bt.lencode=bt.lendyn=new O.Buf32(lt),bt.distcode=bt.distdyn=new O.Buf32(dt),bt.sane=1,bt.back=-1,re):Qe}function Eo(be){var bt;return be&&be.state?((bt=be.state).wsize=0,bt.whave=0,bt.wnext=0,Ki(be)):Qe}function so(be,bt){var OA,oi;return be&&be.state?(oi=be.state,bt<0?(OA=0,bt=-bt):(OA=1+(bt>>4),bt<48&&(bt&=15)),bt&&(bt<8||15=si.wsize?(O.arraySet(si.window,bt,OA-si.wsize,si.wsize,0),si.wnext=0,si.whave=si.wsize):(oi<(ms=si.wsize-si.wnext)&&(ms=oi),O.arraySet(si.window,bt,OA-oi,ms,si.wnext),(oi-=ms)?(O.arraySet(si.window,bt,OA-oi,oi,0),si.wnext=oi,si.whave=si.wsize):(si.wnext+=ms,si.wnext===si.wsize&&(si.wnext=0),si.whave>>8&255,OA.check=X(OA.check,Ue,2,0),St=yt=0,OA.mode=2;break}if(OA.flags=0,OA.head&&(OA.head.done=!1),!(1&OA.wrap)||(((255&yt)<<8)+(yt>>8))%31){be.msg="incorrect header check",OA.mode=30;break}if((15&yt)!=8){be.msg="unknown compression method",OA.mode=30;break}if(St-=4,yA=8+(15&(yt>>>=4)),OA.wbits===0)OA.wbits=yA;else if(yA>OA.wbits){be.msg="invalid window size",OA.mode=30;break}OA.dmax=1<>8&1),512&OA.flags&&(Ue[0]=255&yt,Ue[1]=yt>>>8&255,OA.check=X(OA.check,Ue,2,0)),St=yt=0,OA.mode=3;case 3:for(;St<32;){if(Ni===0)break A;Ni--,yt+=oi[si++]<>>8&255,Ue[2]=yt>>>16&255,Ue[3]=yt>>>24&255,OA.check=X(OA.check,Ue,4,0)),St=yt=0,OA.mode=4;case 4:for(;St<16;){if(Ni===0)break A;Ni--,yt+=oi[si++]<>8),512&OA.flags&&(Ue[0]=255&yt,Ue[1]=yt>>>8&255,OA.check=X(OA.check,Ue,2,0)),St=yt=0,OA.mode=5;case 5:if(1024&OA.flags){for(;St<16;){if(Ni===0)break A;Ni--,yt+=oi[si++]<>>8&255,OA.check=X(OA.check,Ue,2,0)),St=yt=0}else OA.head&&(OA.head.extra=null);OA.mode=6;case 6:if(1024&OA.flags&&(Ni<(io=OA.length)&&(io=Ni),io&&(OA.head&&(yA=OA.head.extra_len-OA.length,OA.head.extra||(OA.head.extra=new Array(OA.head.extra_len)),O.arraySet(OA.head.extra,oi,si,io,yA)),512&OA.flags&&(OA.check=X(OA.check,oi,io,si)),Ni-=io,si+=io,OA.length-=io),OA.length))break A;OA.length=0,OA.mode=7;case 7:if(2048&OA.flags){if(Ni===0)break A;for(io=0;yA=oi[si+io++],OA.head&&yA&&OA.length<65536&&(OA.head.name+=String.fromCharCode(yA)),yA&&io>9&1,OA.head.done=!0),be.adler=OA.check=0,OA.mode=12;break;case 10:for(;St<32;){if(Ni===0)break A;Ni--,yt+=oi[si++]<>>=7&St,St-=7&St,OA.mode=27;break}for(;St<3;){if(Ni===0)break A;Ni--,yt+=oi[si++]<>>=1)){case 0:OA.mode=14;break;case 1:if(to(OA),OA.mode=20,bt!==6)break;yt>>>=2,St-=2;break A;case 2:OA.mode=17;break;case 3:be.msg="invalid block type",OA.mode=30}yt>>>=2,St-=2;break;case 14:for(yt>>>=7&St,St-=7&St;St<32;){if(Ni===0)break A;Ni--,yt+=oi[si++]<>>16^65535)){be.msg="invalid stored block lengths",OA.mode=30;break}if(OA.length=65535&yt,St=yt=0,OA.mode=15,bt===6)break A;case 15:OA.mode=16;case 16:if(io=OA.length){if(Ni>>=5,St-=5,OA.ndist=1+(31&yt),yt>>>=5,St-=5,OA.ncode=4+(15&yt),yt>>>=4,St-=4,286>>=3,St-=3}for(;OA.have<19;)OA.lens[de[OA.have++]]=0;if(OA.lencode=OA.lendyn,OA.lenbits=7,ee={bits:OA.lenbits},NA=DA(0,OA.lens,0,19,OA.lencode,0,OA.work,ee),OA.lenbits=ee.bits,NA){be.msg="invalid code lengths set",OA.mode=30;break}OA.have=0,OA.mode=19;case 19:for(;OA.have>>16&255,Sa=65535&he,!((In=he>>>24)<=St);){if(Ni===0)break A;Ni--,yt+=oi[si++]<>>=In,St-=In,OA.lens[OA.have++]=Sa;else{if(Sa===16){for(Ne=In+2;St>>=In,St-=In,OA.have===0){be.msg="invalid bit length repeat",OA.mode=30;break}yA=OA.lens[OA.have-1],io=3+(3&yt),yt>>>=2,St-=2}else if(Sa===17){for(Ne=In+3;St>>=In)),yt>>>=3,St-=3}else{for(Ne=In+7;St>>=In)),yt>>>=7,St-=7}if(OA.have+io>OA.nlen+OA.ndist){be.msg="invalid bit length repeat",OA.mode=30;break}for(;io--;)OA.lens[OA.have++]=yA}}if(OA.mode===30)break;if(OA.lens[256]===0){be.msg="invalid code -- missing end-of-block",OA.mode=30;break}if(OA.lenbits=9,ee={bits:OA.lenbits},NA=DA(GA,OA.lens,0,OA.nlen,OA.lencode,0,OA.work,ee),OA.lenbits=ee.bits,NA){be.msg="invalid literal/lengths set",OA.mode=30;break}if(OA.distbits=6,OA.distcode=OA.distdyn,ee={bits:OA.distbits},NA=DA(KA,OA.lens,OA.nlen,OA.ndist,OA.distcode,0,OA.work,ee),OA.distbits=ee.bits,NA){be.msg="invalid distances set",OA.mode=30;break}if(OA.mode=20,bt===6)break A;case 20:OA.mode=21;case 21:if(6<=Ni&&258<=yo){be.next_out=Dn,be.avail_out=yo,be.next_in=si,be.avail_in=Ni,OA.hold=yt,OA.bits=St,gA(be,qn),Dn=be.next_out,ms=be.output,yo=be.avail_out,si=be.next_in,oi=be.input,Ni=be.avail_in,yt=OA.hold,St=OA.bits,OA.mode===12&&(OA.back=-1);break}for(OA.back=0;ua=(he=OA.lencode[yt&(1<>>16&255,Sa=65535&he,!((In=he>>>24)<=St);){if(Ni===0)break A;Ni--,yt+=oi[si++]<>oa)])>>>16&255,Sa=65535&he,!(oa+(In=he>>>24)<=St);){if(Ni===0)break A;Ni--,yt+=oi[si++]<>>=oa,St-=oa,OA.back+=oa}if(yt>>>=In,St-=In,OA.back+=In,OA.length=Sa,ua===0){OA.mode=26;break}if(32&ua){OA.back=-1,OA.mode=12;break}if(64&ua){be.msg="invalid literal/length code",OA.mode=30;break}OA.extra=15&ua,OA.mode=22;case 22:if(OA.extra){for(Ne=OA.extra;St>>=OA.extra,St-=OA.extra,OA.back+=OA.extra}OA.was=OA.length,OA.mode=23;case 23:for(;ua=(he=OA.distcode[yt&(1<>>16&255,Sa=65535&he,!((In=he>>>24)<=St);){if(Ni===0)break A;Ni--,yt+=oi[si++]<>oa)])>>>16&255,Sa=65535&he,!(oa+(In=he>>>24)<=St);){if(Ni===0)break A;Ni--,yt+=oi[si++]<>>=oa,St-=oa,OA.back+=oa}if(yt>>>=In,St-=In,OA.back+=In,64&ua){be.msg="invalid distance code",OA.mode=30;break}OA.offset=Sa,OA.extra=15&ua,OA.mode=24;case 24:if(OA.extra){for(Ne=OA.extra;St>>=OA.extra,St-=OA.extra,OA.back+=OA.extra}if(OA.offset>OA.dmax){be.msg="invalid distance too far back",OA.mode=30;break}OA.mode=25;case 25:if(yo===0)break A;if(io=qn-yo,OA.offset>io){if((io=OA.offset-io)>OA.whave&&OA.sane){be.msg="invalid distance too far back",OA.mode=30;break}io>OA.wnext?(io-=OA.wnext,Wr=OA.wsize-io):Wr=OA.wnext-io,io>OA.length&&(io=OA.length),cc=OA.window}else cc=ms,Wr=Dn-OA.offset,io=OA.length;for(yoqo?(yi=Wr[cc+dt[bt]],to=St[Cg+dt[bt]]):(yi=96,to=0),Wt=1<>Dn)+(Ki-=Wt)]=cn<<24|yi<<16|to,Ki!==0;);for(Wt=1<>=1;if(Wt!==0?(yt&=Wt-1,yt+=Wt):yt=0,bt++,--qn[be]==0){if(be===oi)break;be=KA[re+dt[bt]]}if(ms{const gA=new Uint8Array(X).slice(4);let DA;try{DA=Na.inflate(gA,{to:"string"})}catch(GA){console.error("inflate error",GA)}return DA})(p.data):function(X){const gA=new Uint8Array(X);let DA="",GA=0;const{length:KA}=gA;for(;GA0)for(let lt=0;lt{var G;const{uplinkData:O,canResend:z,resolve:X,reject:gA,timeout:DA}=B;if(z){this._pendingRequests.set(M,{resolve:X,reject:gA,timestamp:Date.now(),uplinkData:O,timeout:DA,canResend:z});const GA=this._isBinarySupported?Fa(O).buffer:O;(G=this._socketAdapter)===null||G===void 0||G.send(GA)}else this._pendingRequests.delete(M)})}_onConnect(p){const{socketId:B,event:M={}}=p||{};this._connectionId=B,this._connectionEstablishedTime=Date.now();const G=Date.now()-this._connectionStartTime,O=`${Bt}.onConnect cost:${G} ms. socketID:${B} res:${JSON.stringify(M)}`;if(this._ssoLog({method:"onConnect",message:O}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const z=`${Bt}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:z}),es.emitInnerEvent(Ke.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:eo,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(p){const B=pa({servcmd:"openim.ws_msg_push_ack",data:{SessionData:p}});this.sendPacket(B)}_executeScheduledTaskIfReady(){return mA(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var p;return((p=this._socketAdapter)===null||p===void 0?void 0:p.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return mA(this,void 0,void 0,function*(){var p;const B=pa({servcmd:"heartbeat.alive",data:{}});try{const M=`${B.head.seq}${B.head.servcmd}`;yield this.sendPacket(B,{requestId:M,timeout:3e3})}catch(M){const G=(p=ro.get("netWorkMonitor"))===null||p===void 0?void 0:p.isNetworkOnline,O=`${Bt}.sendHeartbeat failed. isNetWorkOnline:${G} error: ${_n(M)}`;this._ssoLog({method:"sendHeartbeatError",message:O}),this._handleConnectStateChange({state:Ti,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return mA(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=ao?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(p){const B=`${Bt}.networkStatusChange ${JSON.stringify(p)}`;this._ssoLog({method:"networkStatusChange",message:B});const{isNetworkOnline:M,networkType:G}=p;M&&G!=="none"?this._handleConnectStateChange({state:eo,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:wg}):this._handleConnectStateChange({state:Ti,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:wg})}isPrivateNetWork(){const p=ro.get("instance")||{};return p.proxyServer&&!p.fileDownloadProxy}_handleConnectStateChange(p){const{state:B,shouldAttemptReconnect:M,shouldEmitEvent:G,reason:O}=p,z=`${Bt}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${M} shouldEmitEvent: ${G} reason: ${O}`;this._currentConnectState!==B&&(this._ssoLog({method:"handleConnectStateChange",message:z}),G&&(Kt.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${B}`),es.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:B}}),this._currentConnectState=B,B===Ti&&es.emitInnerEvent(Ke.SOCKET_DISCONNECTED)),M&&(this._resetReconnectDelay(),ws.addTask({id:$i,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(p){var B,M;const G=(M=(B=this._socketAdapter)===null||B===void 0?void 0:B._ws)===null||M===void 0?void 0:M.readyState,O=`${Bt}.activityStatusChange ${JSON.stringify(p)} readyState: ${G}`;Kt.debug("activityStatusChange",O),G===3&&this._handleConnectStateChange({state:Ti,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Er})}_resetReconnectDelay(){var p;Kt.debug(`${Bt}._resetReconnectDelay`),ws.removeTask($i);const B=(p=ro.get("activityMonitor"))===null||p===void 0?void 0:p.isActive;this._intendedDelay=B?on:1e3}_scheduleReconnectWithBackoff(){var p;const B=(p=ro.get("activityMonitor"))===null||p===void 0?void 0:p.isActive;this._intendedDelay=B?Math.min(5e3,Math.max(on,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const M=new Date().toTimeString().slice(0,8),G=`${Bt}.scheduleReconnectWithBackoff timeStr: ${M} intendedDelay: ${this._intendedDelay}`;Kt.debug(G),this.reconnect(),ws.updateTaskInterval($i,this._intendedDelay)}_ssoLog(p){const{method:B,message:M}=p;Kt.info(B,M)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(p){mA(this,void 0,void 0,function*(){const B=p.split("/")[2];if(!B.startsWith("ws"))return;const M=`https://${B}/v3/netcheck/getconninfo?${p.slice(p.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield qi({method:"GET",url:M,data:{}})}catch(G){Kt.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${G.message}`)}})}(this._url),function(p){mA(this,void 0,void 0,function*(){const B=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${p.slice(p.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield qi({method:"GET",url:B,data:{}})}catch(M){Kt.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${M.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[p,B]of this._pendingRequests.entries()){const{reject:M,timestamp:G,timeout:O}=B;Date.now()-G>=O&&(this._pendingRequests.delete(p),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),M({errorCode:Zs,errorInfo:"NETWORK_TIMEOUT",data:{requestId:p}}))}}_updateIsBinarySupported(){var p;if(!((p=ro.get("instance"))===null||p===void 0)&&p.devMode)return void(this._isBinarySupported=!1);const B=Vo();if((ii||Xe&&B==="windows"||wn)&&(this._isBinarySupported=!1),ao){const{uniRuntimeVersion:M=""}=no.getSystemInfoSync();(function(G){const O=G.split(".").map(Number),[z=0,X=0,gA=0]=O;return z>2||!(z<2)&&(X>2||!(X<2)&&gA>=6)})(M)||(this._isBinarySupported=!1)}}_isCompressedData(p){const B=new Uint8Array(p);return B[0]===67&&B[1]===79&&B[2]===77&&B[3]===80}};const ve={init:function(p){ro.set("instance",p),Nl.init()},destroy:function(){Nl.dispose(),ro.clear(),ws.dispose()},notificationCenter:es,channel:Nl,store:ro,ssoLog:Kt,utils:$a,common:RA,constants:we},Se=p=>typeof p=="function";function _g(p,B,M){const G=M||[];if(!p||!B)return!1;const O=Object.keys(p).filter(X=>!G.includes(X)),z=Object.keys(B).filter(X=>!G.includes(X));return O.length===z.length&&O.every(X=>!!B.hasOwnProperty(X)&&(typeof p[X]=="object"&&p[X]!==null?_g(p[X],B[X],M):p[X]===B[X]))}var cg;(function(p){p.SDK_READY="sdkStateReady",p.SDK_NOT_READY="sdkStateNotReady",p.SDK_DESTROY="sdkDestroy",p.MESSAGE_RECEIVED="onMessageReceived",p.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",p.MESSAGE_MODIFIED="onMessageModified",p.MESSAGE_REVOKED="onMessageRevoked",p.MESSAGE_READ_BY_PEER="onMessageReadByPeer",p.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",p.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",p.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",p.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",p.CONVERSATION_LIST_UPDATED="onConversationListUpdated",p.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",p.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",p.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",p.GROUP_LIST_UPDATED="onGroupListUpdated",p.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",p.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",p.TOPIC_CREATED="onTopicCreated",p.TOPIC_DELETED="onTopicDeleted",p.TOPIC_UPDATED="onTopicUpdated",p.PROFILE_UPDATED="onProfileUpdated",p.USER_STATUS_UPDATED="onUserStatusUpdated",p.BLACKLIST_UPDATED="blacklistUpdated",p.FRIEND_LIST_UPDATED="onFriendListUpdated",p.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",p.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",p.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",p.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",p.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",p.KICKED_OUT="kickedOut",p.ERROR="error",p.NET_STATE_CHANGE="netStateChange",p.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",p.SERVER_CONFIG_UPDATED="onServerConfigUpdated",p.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated",p.WEB_PUSH_MESSAGE_RECEIVED="onWebPushMessageReceived",p.GROUP_ONLINE_MEMBER_COUNT_CHANGED="onGroupOnlineMemberCountChanged",p.RICH_STATUS_CHANGED="onRichStatusChanged"})(cg||(cg={}));var Tg,Ts=cg;(function(p){p.LOGOUT="logout",p.DESTROY="destroy",p.CLOUD_CONFIG_UPDATE="cloud_config_update",p.PROFILE_UPDATE="profile_updated",p.ERROR="error",p.RECONNECTED="reconnected",p.FORCE_OFFLINE="im_open_status.stat_forceoffline",p.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",p.OVERLOAD_PUSH="OverLoadPush.notify2",p.NEW_MESSAGE="new_message",p.MESSAGE_PUSH="im_open_push.msg_push",p.MESSAGE_DELETED="message_deleted",p.MESSAGE_REVOKED="message_revoked",p.MESSAGE_MODIFIED="message_modified",p.SOCKET_DISCONNECTED="socket_disconnected",p.CONVERSATION_UPDATED="conversation_updated",p.TOPIC_MESSAGE_DELETED="topic_message_deleted",p.TOPIC_MESSAGE_REVOKED="topic_message_revoked",p.TOPIC_MESSAGE_MODIFIED="topic_message_modified",p.TOPIC_NEW_MESSAGE="topic_new_message",p.QUALITY_STAT="quality_stat",p.SYNC_CONVERSATION_LIST="sync_conversation_list",p.HISTORY_MESSAGE_FETCHED="history_message_fetched"})(Tg||(Tg={}));var Rr,Ci=Tg;(function(p){p.NEW_INVITATION_RECEIVED="newInvitationReceived",p.INVITEE_ACCEPTED="ts_invitee_accepted",p.INVITEE_REJECTED="ts_invitee_rejected",p.INVITATION_CANCELLED="ts_invitation_cancelled",p.INVITATION_TIMEOUT="ts_invitation_timeout",p.INVITATION_MODIFIED="ts_invitation_modified"})(Rr||(Rr={}));var lo=Rr;const Xc=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),tc={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem",MSG_STREAM:"TIMStreamElem"};var Ng;(function(p){p.UNSENT="unSend",p.SUCCESS="success",p.FAIL="fail"})(Ng||(Ng={}));const qr={modify:Ci.MESSAGE_MODIFIED,delete:Ci.MESSAGE_DELETED,revoke:Ci.MESSAGE_REVOKED};var _c;(function(p){p[p.FORWARD=0]="FORWARD",p[p.BACKWARD=1]="BACKWARD"})(_c||(_c={}));const $c=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},tc),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:Ng,Direction:_c}),lg={[qr.modify]:Ci.TOPIC_MESSAGE_MODIFIED,[qr.delete]:Ci.TOPIC_MESSAGE_DELETED,[qr.revoke]:Ci.TOPIC_MESSAGE_REVOKED},Nu={GENDER_UNKNOWN:"Gender_Type_Unknown",GENDER_FEMALE:"Gender_Type_Female",GENDER_MALE:"Gender_Type_Male",USER_STATUS_UNKNOWN:0,USER_STATUS_ONLINE:1,USER_STATUS_OFFLINE:2,USER_STATUS_UNLOGINED:3,USER_NOT_FOUND:"@TLS#NOT_FOUND"},ME=Object.assign({},Nu),Gg={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},Pa=Object.assign(Object.assign(Object.assign(Object.assign({},Gg),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),Tc=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),RE={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},xa={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},ga={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},bg=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},RE),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),{GROUP_ID_PREFIX:xa,GROUP_TIPS_OPERATION_TYPE:ga}),EI={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},Sn=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Xc),$c),ME),Pa),Tc),bg),EI),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),Po={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},ma={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},dr={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message",RECEIVE_GROUP_TIPS_NOTIFICATION:"receive-group-tips-notification"},jt={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover",HANDLE_GROUP_TIPS_NOTIFICATION:"handle-group-tips-notification",C2C_HISTORY_MESSAGE_RECOVER:"c2c-history-message-recover",FRIEND_APPLICATION_LIST_RECOVER:"friend-application-list-recover",EMIT_GROUP_TIPS_EVENT:"emit-group-tips-event",STREAM_MESSAGE_RECOVER:"stream-message-recover"},Xt={[dr.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:jt.USER_STATUS_UPDATE},{stepId:jt.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:jt.UNREAD_MESSAGE_SYNC,dependency:jt.C2C_HISTORY_MESSAGE_RECOVER},{stepId:jt.CONVERSATION_RECOVER},{stepId:jt.HISTORY_MESSAGE_RECOVER,dependency:jt.CONVERSATION_RECOVER},{stepId:jt.BLACKLIST_RECOVER},{stepId:jt.FRIEND_RECOVER},{stepId:jt.FRIEND_APPLICATION_LIST_RECOVER},{stepId:jt.GROUP_REVOKED_NOTICE_RECOVER,dependency:jt.HISTORY_MESSAGE_RECOVER},{stepId:jt.GROUP_TIPS_RECOVER,dependency:jt.HISTORY_MESSAGE_RECOVER},{stepId:jt.TOPIC_REQUEST_INFO_RESET},{stepId:jt.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:jt.UNREAD_MESSAGE_SYNC},{stepId:jt.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:jt.UNREAD_MESSAGE_SYNC},{stepId:jt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[jt.UNREAD_MESSAGE_SYNC,jt.CONVERSATION_RECOVER]},{stepId:jt.EMIT_C2C_MESSAGE_EVENT,dependency:[jt.UNREAD_MESSAGE_SYNC,jt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:jt.C2C_HISTORY_MESSAGE_RECOVER,dependency:jt.CONVERSATION_RECOVER},{stepId:jt.STREAM_MESSAGE_RECOVER}],[dr.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:jt.COMMERCIAL_CONFIG_UPDATE},{stepId:jt.CLOUD_CONFIG_SYNC},{stepId:jt.USER_PROFILE_SYNC},{stepId:jt.UNREAD_MESSAGE_SYNC},{stepId:jt.FRIEND_AND_BLACKLIST_SYNC},{stepId:jt.GROUP_LIST_SYNC},{stepId:jt.CONVERSATION_LIST_SYNC},{stepId:jt.SIGNALING_MESSAGE_RECOVER,dependency:jt.UNREAD_MESSAGE_SYNC},{stepId:jt.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[jt.UNREAD_MESSAGE_SYNC]},{stepId:jt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[jt.UNREAD_MESSAGE_SYNC,jt.CONVERSATION_LIST_SYNC]},{stepId:jt.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[jt.GROUP_LIST_SYNC,jt.CONVERSATION_LIST_SYNC]},{stepId:jt.CONVERSATION_GROUP_LIST_SYNC},{stepId:jt.CONVERSATION_GROUP_UPDATE,dependency:[jt.CONVERSATION_LIST_SYNC,jt.CONVERSATION_GROUP_LIST_SYNC]},{stepId:jt.QUALITY_REPORT}],[dr.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:jt.HANDLE_C2C_NEW_MESSAGE},{stepId:jt.UNREAD_MESSAGE_SYNC},{stepId:jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:jt.HANDLE_C2C_NEW_MESSAGE},{stepId:jt.EMIT_C2C_MESSAGE_EVENT,dependency:[jt.HANDLE_C2C_NEW_MESSAGE,jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:jt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[jt.UNREAD_MESSAGE_SYNC]}],[dr.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:jt.HANDLE_GROUP_NEW_MESSAGE},{stepId:jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:jt.HANDLE_GROUP_NEW_MESSAGE},{stepId:jt.UPDATE_GROUP_NEXT_SEQUENCE,dependency:jt.HANDLE_GROUP_NEW_MESSAGE},{stepId:jt.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:jt.HANDLE_GROUP_NEW_MESSAGE},{stepId:jt.EMIT_GROUP_MESSAGE_EVENT,dependency:[jt.HANDLE_GROUP_NEW_MESSAGE,jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[dr.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:jt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:jt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:jt.EMIT_GROUP_TIPS_EVENT,dependency:[jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,jt.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},kg={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},dI={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},Cr=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","sendMessageReadReceipt","getMessageReadReceiptList","getGroupMessageReadMemberList","createMergerMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var zI=Object.freeze({__proto__:null,ERROR_CODE:Po,InnerEvent:Ci,NEED_LOG_API:Cr,OuterConstant:Sn,OuterEvent:Ts,PUSH:EI,QUALITY_METRICS:kg,SDK_EDITION:ma,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:dI,SignalingEvent:lo,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Xt,WORKFLOW_NAME:dr,WORKFLOW_STEP:jt}),Ag,ca,ps;(function(p){p[p.USER_INITIATED=0]="USER_INITIATED",p[p.KICKED_OUT=1]="KICKED_OUT"})(Ag||(Ag={})),function(p){p[p.multipleAccount=1]="multipleAccount",p[p.multipleDevice=2]="multipleDevice",p[p.restApi=3]="restApi"}(ca||(ca={})),function(p){p[p.multipleDevice=3002]="multipleDevice",p[p.multipleAccount=3003]="multipleAccount",p[p.usersigExpired=70001]="usersigExpired",p[p.restApi=20002]="restApi"}(ps||(ps={}));const Ns={[ca.multipleAccount]:"multipleAccount",[ca.multipleDevice]:"multipleDevice",[ca.restApi]:"REST_API_Kick",[ps.multipleAccount]:"multipleAccount",[ps.multipleDevice]:"multipleDevice",[ps.restApi]:"REST_API_Kick",[ps.usersigExpired]:"userSigExpired"},Gu="login_online_presence_task",{ERROR:Lg,DESTROY:Ya,FORCE_OFFLINE:Al}=Ci,{KICKED_OUT_MULT_ACCOUNT:ZI,KICKED_OUT_MULT_DEVICE:wE,KICKED_OUT_REST_API:CI,ACCOUNT_A2KEY_EXPIRED:bu,MSG_A2KEY_EXPIRED:Gl}=Po;class Nc{init(){const{notificationCenter:B}=ve;B.subscribeInnerEvent(Al,this._handleForceOfflineFromServerPush,this),B.subscribeInnerEvent(Lg,Gl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),B.subscribeInnerEvent(Lg,bu,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),B.subscribeInnerEvent(Lg,ZI,this._handleForceOfflineFromResponse,this),B.subscribeInnerEvent(Lg,wE,this._handleForceOfflineFromResponse,this),B.subscribeInnerEvent(Lg,CI,this._handleForceOfflineFromResponse,this),B.subscribeInnerEvent(Ya,this._dispose,this)}_handleForceOfflineFromServerPush(B){var M;if(((M=ve.store.get("login"))===null||M===void 0?void 0:M.isLoggedIn)===!0){const{EventArray:G=[]}=B?.body||{};this._extractKickedOutMessages(G).forEach(O=>{const{KickoutMsgNotify:{KickType:z,NewInstInfo:X,Instid:gA}}=O;this._isCurrentInstanceKickedOut(gA)&&this._processKickedOutReasonInfo({kickedOutReasonCode:z,newInstanceInfo:X})})}}_extractKickedOutMessages(B){return B.reduce((M,G)=>[...M,...G.C2cNotifyMsgArray||[]],[]).filter(M=>{var G;return this._isKickedOut((G=M?.KickoutMsgNotify)===null||G===void 0?void 0:G.KickType)})}_handleForceOfflineFromResponse(B){const{errorCode:M}=B;this._processKickedOutReasonInfo({kickedOutReasonCode:M})}_processKickedOutReasonInfo(B){return mA(this,void 0,void 0,function*(){const{kickedOutReasonCode:M}=B,{ssoLog:G,utils:{safeStringify:O}}=ve;try{this._logKickedOutEvent(B),this._shouldLogoutAfterKickedOut(M)?yield ve.login.loginAction.logout(Ag.KICKED_OUT):ve.login.loginAction.handleLogoutCompleted()}catch(z){G.debug("_processKickedOutReasonInfo",` fail ${O(z)}`)}finally{ve.notificationCenter.emitOuterEvent(Ts.KICKED_OUT,{data:{type:Ns[M]},name:Ts.KICKED_OUT})}})}_logKickedOutEvent(B){const{kickedOutReasonCode:M,newInstanceInfo:G={}}=B,O=`type:${Ns[M]} newInstanceInfo: ${JSON.stringify(G)}`;ve.ssoLog.warn("kickedOut",O)}_isKickedOut(B){return[ca.multipleAccount,ca.multipleDevice,ca.restApi].includes(B)}_isChatLoginEvent(B){const{requestHead:M}=B||{};return M?.idtype!==1}_shouldLogoutAfterKickedOut(B){return![ps.usersigExpired,ca.restApi].includes(B)}_isCurrentInstanceKickedOut(B){const{isLoggedIn:M,statusInstanceId:G}=ve.store.get("login")||{};return M===!0&&B===G}_dispose(){const{notificationCenter:B}=ve;B.unSubscribeInnerEvent(Al,this._handleForceOfflineFromServerPush,this),B.unSubscribeInnerEvent(Lg,bu,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Lg,Gl,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Lg,ZI,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Lg,wE,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Lg,CI,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Ya,this._dispose,this)}}function ku(p){return mA(this,void 0,void 0,function*(){const B="im_open_status.wslogin",M=ve.common.generateProtocolData({servcmd:B,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:p}}),G=`${M.head.seq}${B}`,O=yield ve.channel.sendPacket(M,{timeout:9e4,requestId:G});if(O){const{HelloInterval:z,InstId:X,TinyId:gA,TimeStamp:DA,CustomStatus:GA,PurchaseBits:KA,A2Key:re,RichMsgAuthKey:Qe,ErrorCode:At,ErrorInfo:lt,ActionStatus:dt}=O;return{helloInterval:z,instanceID:X,tinyID:gA,timeStamp:DA,customStatus:GA,purchaseBits:KA,a2Key:re,authKey:Qe,errorCode:At,errorInfo:lt,actionStatus:dt}}})}function Lu(){const{store:p}=ve;return Qa(p.get("instance").sdkAppId)!==Ye.CHINA}function bl(p){var B;try{const M=ro.getStorage("errorMessage");if(!p||!M)return"";const G=((B=JSON.parse(M))===null||B===void 0?void 0:B.errorMessage)||{},{code:O,replacement1:z="",replacement2:X=""}=p;if(!O)return"";const gA=Lu()?`${O}_en`:`${O}_cn`;let DA=G[G[gA]?gA:O]||"";return DA&&(z&&(DA=DA.replace("$replacement1",z)),X&&(DA=DA.replace("$replacement2",X))),DA}catch(M){return console.warn("Error parsing stored error messages:",M),""}}class dn extends Error{constructor(B={}){B.code=B.code||B.errorCode;let{functionName:M="Unknown",code:G,message:O="",data:z="",moreMessage:X="",errorMessage:gA=""}=B;gA=(G?bl(B):"")||gA||O;let DA=G?`${M} failed. error: {"message": ${gA}, "code": ${G}}`:`${M} failed. error: {"message": ${gA}}`;DA=`${DA} ${X}`,super(),this.code=G,this.errorCode=G,this.errorMessage=gA,this.message=DA,this.data=z}}function hn(p,B){var M;if(p&&((M=ve.store.get("login"))===null||M===void 0?void 0:M.isLoggedIn)!==!0)throw new dn({code:Po.USER_NOT_LOGGED_IN,functionName:B})}function dd(p,B,M){if(Array.isArray(p))for(let G=0;G{return GA===(KA=G,Object.prototype.toString.call(KA).match(/^\[object (.*)\]$/)[1].toLowerCase());var KA})){for(let KA=0;KA{const{interceptor:O,context:z}=G;O.apply(z,[M])})}(p)}function wr(p,B){BI.push({interceptor:p,context:B})}function Gc(p){const{params:B,auth:M}=p;B&&typeof B=="object"&&Object.assign(Cd,B),M&&typeof M=="object"&&Object.assign(_E,M)}function el(p){return ve.store.get("commercialConfig").get(p)}class us{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(B,M)=>{const G=Date.now();M?(this._stepStartTimes.set(`${B}-${M}`,G),ve.ssoLog.debug("_executeWorkflowStep",`[Workflow ${B}] Step ${M} started at ${new Date(G).toISOString()}`)):(this._workflowStartTimes.set(B,G),ve.ssoLog.debug("_executeWorkflowStep",`[Workflow ${B}] started at ${new Date(G).toISOString()}`))},success:(B,M)=>{const G=Date.now();if(M){const O=this._stepStartTimes.get(`${B}-${M}`),z=O?G-O:0;this._stepStartTimes.delete(`${B}-${M}`),ve.ssoLog.debug("_executeWorkflowStep",`[Workflow ${B}] Step ${M} completed successfully at ${new Date(G).toISOString()} (${z}ms)`)}else{const O=this._workflowStartTimes.get(B),z=O?G-O:0;this._workflowStartTimes.delete(B),ve.ssoLog.debug("_executeWorkflowStep",`[Workflow ${B}] completed successfully at ${new Date(G).toISOString()} (${z}ms)`)}},error:(B,M,G)=>{const{ssoLog:O,utils:{safeStringify:z}}=ve,X=Date.now();if(M){const gA=this._stepStartTimes.get(`${B}-${M}`),DA=gA?X-gA:0;this._stepStartTimes.delete(`${B}-${M}`),O.error("_executeWorkflowStep",`[Workflow ${B}] Step ${M} failed at ${new Date(X).toISOString()} (${DA}ms) ${z(G)}`,{error:G})}else{const gA=this._workflowStartTimes.get(B),DA=gA?X-gA:0;this._workflowStartTimes.delete(B),O.error("_executeWorkflowStep",`[Workflow ${B}] failed at ${new Date(X).toISOString()} (${DA}ms) ${z(G)}`,{error:G})}}}}static getInstance(){return us._instance||(us._instance=new us),us._instance}static setInstance(B){us._instance=B}init(){this._initializeWorkflows()}registerWorkflowStep(B,M,G,O){if(!this._handlers.has(B))return void ve.ssoLog.debug("registerWorkflowStep",`Workflow '${B}' not defined in core`);if(!Xt[B].find(X=>X.stepId===M))return void ve.ssoLog.debug("registerWorkflowStep",`Step '${M}' not defined in workflow '${B}'`);const z=this._handlers.get(B);z.has(M)||z.set(M,O?G.bind(O):G)}executeWorkflow(B,M){return mA(this,void 0,void 0,function*(){if(!this._validateWorkflow(B))return;ve.ssoLog.debug("executeWorkflow",`[Workflow ${B}] Started execution at ${new Date().toISOString()}`);const G=Xt[B],O={},z={cancelled:!1};this._activeWorkflows.set(B,{cancelToken:z});try{const X=new Map;G.forEach(DA=>{X.set(DA.stepId,DA)});const gA={workflowName:B,pendingSteps:new Set(G.map(DA=>DA.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:X,stepResults:O,data:M,cancelToken:z};yield new Promise((DA,GA)=>{const KA=()=>{if(z.cancelled)return void DA();this._getExecutableSteps({pendingSteps:gA.pendingSteps,completedSteps:gA.completedSteps,stepMap:gA.stepMap,workflowName:B}).filter(re=>!gA.runningSteps.has(re)).forEach(re=>{gA.completedSteps.has(re)||gA.runningSteps.has(re)||this._executeWorkflowStep(re,gA,{onComplete:()=>{if(gA.pendingSteps.size===0)return void DA();this._getExecutableSteps({pendingSteps:gA.pendingSteps,completedSteps:gA.completedSteps,stepMap:gA.stepMap,workflowName:B}).filter(Qe=>!gA.runningSteps.has(Qe)).length===0&&gA.runningSteps.size===0&&(ve.ssoLog.debug("executeWorkflow",`Workflow ${B} completed with some steps skipped due to dependency failures`),DA())},onError:GA,onStepComplete:KA})})};KA()}),ve.ssoLog.debug("executeWorkflow",`[Workflow ${B}] Completed execution at ${new Date().toISOString()}`)}catch(X){ve.ssoLog.error("executeWorkflow",`[Workflow ${B}] Failed execution at ${new Date().toISOString()}`,{error:X})}finally{this._activeWorkflows.delete(B)}})}_executeWorkflowStep(B,M,G){return mA(this,void 0,void 0,function*(){const{workflowName:O,runningSteps:z,stepMap:X,stepResults:gA,data:DA}=M;z.add(B),this._logWorkflowExecution(O,B,"start");try{const GA=X.get(B);let KA=null;GA?.dependency&&(c(GA.dependency)?KA=gA[GA.dependency]:Array.isArray(GA.dependency)&&(KA={},GA.dependency.forEach(Qe=>{KA[Qe]=gA[Qe]})));const re=this._handlers.get(O).get(B);if(re){const Qe=yield Promise.resolve(re({data:DA,result:KA}));gA[B]=Qe,this._logWorkflowExecution(O,B,"success")}M.completedSteps.add(B)}catch(GA){const KA=`[Workflow].${O}.${B}`,{errorCode:re,errorInfo:Qe=`${KA} failed`}=GA||{},At=new dn({functionName:KA,code:re,message:Qe});ve.ssoLog.error(KA,Qe,{error:At}),this._logWorkflowExecution(O,B,"error",GA),G.onError(GA)}finally{z.delete(B),M.pendingSteps.delete(B),G.onStepComplete(),G.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Xt).forEach(B=>{this._handlers.has(B)||this._handlers.set(B,new Map)})}_cancelWorkFlow(B){const M=this._activeWorkflows.get(B);if(!M)return;const{cancelToken:G}=M;G.cancelled=!0,this._activeWorkflows.delete(B)}_cancelAllWorkflows(){Object.keys(Xt).forEach(B=>{this._cancelWorkFlow(B)})}_validateWorkflow(B){return Xt[B]?!!this._handlers.get(B):!1}_getExecutableSteps(B){const{pendingSteps:M,completedSteps:G,stepMap:O,workflowName:z}=B;return Array.from(M).filter(X=>{const gA=O.get(X)||{},{dependency:DA,skipIfDependencyMissing:GA=!0}=gA;if(!DA)return!0;if(c(DA))return this._isStepRegistered({workflowName:z,stepId:DA})?G.has(DA):!GA;if(C(DA)){if(DA.filter(KA=>!this._isStepRegistered({workflowName:z,stepId:KA})).length>0&&GA)return!1;for(const KA of DA)if(!G.has(KA))return!1;return!0}return!1})}_isStepRegistered(B){var M;const{workflowName:G,stepId:O}=B;return(M=this._handlers.get(G))===null||M===void 0?void 0:M.has(O)}_logWorkflowExecution(B,M,G,O){this._logHandlers[G](B,M)}}const Pn=new Map,fa=({type:p,groupID:B})=>p===Sn.GRP_COMMUNITY||`${B}`.startsWith(xa.COMMUNITY)&&!`${B}`.includes(xa.TOPIC),ea=(p="")=>{const B=p.startsWith("GROUP")?p.replace("GROUP",""):p;return B.startsWith(xa.COMMUNITY)&&`${B}`.includes(xa.TOPIC)},tl="openim",hd="million_group_open_http_svc";function ic(p){return mA(this,void 0,void 0,function*(){const{servcmd:B,data:M}=function(z){const{data:X}=z;return Ig(X)||TE(X)}(p)?function(z){let{servcmd:X,data:gA}=z;return TE(gA)?function(DA){const{servcmd:GA,data:KA}=DA;let{GroupId:re=""}=KA;const Qe=re;return[re]=Qe.split(xa.TOPIC),{servcmd:oc(GA),data:Object.assign(Object.assign({},KA),{GroupId:re,TopicId:Qe})}}(z):(Ig(gA)&&(X=oc(X)),{servcmd:X,data:gA})}(p):p,G=ve.common.generateProtocolData({servcmd:B,data:M}),O=`${G.head.seq}${B}`;return ve.channel.sendPacket(G,{requestId:O,timeout:p.timeout})})}function Ig(p){const{Type:B,GroupId:M,GroupIdList:G=[]}=p,O=M||G[0]||"";return fa({type:B,groupID:O})}function TE(p){const{GroupId:B=""}=p;return ea(B)}function oc(p){if(p.includes(tl))return p;const B=p.split(".")[1];return`${hd}.${B}`}function $s(){var p;return(p=ve.store.get("login"))===null||p===void 0?void 0:p.userId}const ar=p=>C(p)||m(p),Va=(p,B,M,G)=>{if(!ar(p)||!ar(B))return 0;let O=0;const z=Object.keys(B);let X;for(let gA=0,DA=z.length;gA{if(n(B))return"";if(p===Sn.MSG_TEXT)return B.text||"";const M=Uu[p];return M?EC(M):""},il=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],ol="im_sdk_config_mgr.fetch_config",$I="im_sdk_config_mgr.push_configv2",QI="cloud-config",nl=2996,sl=new class{init(p){this.core=p}};function Ga(p){return mA(this,void 0,void 0,function*(){const{sdkAppId:B}=sl.core.store.get("instance")||{},M=sl.core.helper.generateProtocolData({servcmd:ol,data:{uint32_sdkappid:B,uint64_version:p}}),G=`${M.head.seq}${ol}`;return sl.core.channel.sendPacket(M,{requestId:G})})}var Ug=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(p){this._core=p;const{notificationCenter:B,InnerEvent:M,helper:G,constants:{WORKFLOW_NAME:O,WORKFLOW_STEP:z},channel:X}=p;B.subscribeInnerEvent($I,this._handlePushedConfig,this),G.registerWorkflowStep(O.SYNC_SERVER_INFO_AFTER_LOGIN,z.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),B.subscribeInnerEvent(M.LOGOUT,this._reset,this),B.subscribeInnerEvent(M.DESTROY,this._dispose,this),G.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(il),X.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(p){return mA(this,void 0,void 0,function*(){var B;const M={code:0,data:""};return p&&(M.data=((B=this._core.store.get("cloudConfig"))===null||B===void 0?void 0:B[p])||""),M})}checkMethodCallOverLimit(p){if(!this._cmdFrequencyLimitMap.has(p))return;if(!this._methodCallFrequencyMap.has(p))return void this._methodCallFrequencyMap.set(p,{startTime:Date.now(),methodCallCounter:1});const{count:B,interval:M}=this._cmdFrequencyLimitMap.get(p);let{startTime:G,methodCallCounter:O}=this._methodCallFrequencyMap.get(p);if(Date.now()-G>1e3*M)this._methodCallFrequencyMap.set(p,{startTime:Date.now(),methodCallCounter:1});else if(O+=1,this._methodCallFrequencyMap.set(p,{startTime:G,methodCallCounter:O}),O>B)throw new this._core.helper.ChatError({code:nl,replacement1:p})}_handlePushedConfig(p){return mA(this,void 0,void 0,function*(){const{ssoLog:B,utils:{safeStringify:M}}=this._core;B.info("_handlePushedConfig",M(p)),yield this._updateCloudConfig(p)})}_handleLoginSuccess(){return mA(this,void 0,void 0,function*(){const{ssoLog:p,utils:{safeStringify:B}}=this._core;try{if(this._canFetch()){const M=yield Ga(this._version);p.info("_fetchCloudConfigIfLogin",B(M)),yield this._updateCloudConfig(M)}this._core.helper.taskScheduler.addTask({id:QI,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(M){p.debug("_fetchCloudConfigIfLogin",B(M))}})}_fetchCloudConfigIfReady(){return mA(this,void 0,void 0,function*(){const{ssoLog:p,utils:{safeStringify:B}}=this._core;if(this._canFetch())try{const M=yield Ga(this._version);p.info("_fetchCloudConfigIfReady",B(M)),yield this._updateCloudConfig(M)}catch(M){p.error("_fetchCloudConfigIfReady",B(M))}})}_updateCloudConfig(p){return mA(this,void 0,void 0,function*(){const B=this._parseCloudConfig(p);B&&(this._core.store.set("cloudConfig",B),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,B),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:B}}))})}_canFetch(){const{isLoggedIn:p}=this._core.store.get("login")||{};return p&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(p){const{int32_error_code:B,str_error_message:M,str_json_config:G,uint32_expired_time:O,uint32_sdkappid:z,uint64_version:X}=p;let gA=null;if(B===0){if(this._version!==X)try{gA=JSON.parse(G),this._version=X}catch{}this._expirationTime=Date.now()+1e3*O}else this._expirationTime=B===void 0?Date.now()+36e5:Date.now()+12e4;return gA}_parseCmdFreqLimit(){return mA(this,void 0,void 0,function*(){var p;let B=(p=yield this.getServerConfig("cmd_frequency_limit"))===null||p===void 0?void 0:p.data;const{isEmpty:M}=this._core.utils;if(!M(B))try{B=JSON.parse(B),this._updateCmdFreqLimitMap(B)}catch(G){console.warn(G)}})}_updateCmdFreqLimitMap(p){p.forEach(B=>{this._cmdFrequencyLimitMap.set(B.cmd,{interval:B.interval,count:B.count})})}_reset(){this._core.helper.taskScheduler.removeTask(QI),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(il),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent($I,this._handlePushedConfig,this),p.unSubscribeInnerEvent(B.LOGOUT,this._reset,this),p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this),this._reset()}};class Nn{constructor(B=0,M=0){this.high=B,this.low=M}equal(B){return B!==null&&this.low===B.low&&this.high===B.high}toString(){const B=Number(this.high).toString(16);let M=Number(this.low).toString(16);if(M.length<8){let G=8-M.length;for(;G;)M=`0${M}`,G--}return B+M}}const Ar={SEARCH_GRP_SNS:new Nn(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Nn(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Nn(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Nn(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Nn(0,Math.pow(2,6)).toString(),USER_STATUS:new Nn(0,Math.pow(2,7)).toString(),CONV_MARK:new Nn(0,Math.pow(2,9)).toString(),CONV_GROUP:new Nn(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Nn(0,Math.pow(2,11)).toString(),MSG_EXT:new Nn(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Nn(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Nn(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Nn(Math.pow(2,7)).toString(),PLUGIN_CS:new Nn(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Nn(Math.pow(2,9)).toString(),PLUGIN_BOT:new Nn(Math.pow(2,10)).toString(),MSG_REACTION:new Nn(Math.pow(2,16)).toString(),FOLLOW:new Nn(Math.pow(2,20)).toString()},bc="CommercialConfig",Au="commercial-config";var eu=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(p){this._core=p;const{helper:B,notificationCenter:M,constants:{WORKFLOW_NAME:G,WORKFLOW_STEP:O,InnerEvent:z}}=p;M.subscribeInnerEvent(z.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),M.subscribeInnerEvent(z.LOGOUT,this._handleLogout,this),M.subscribeInnerEvent(z.DESTROY,this._dispose,this),B.registerWorkflowStep(G.SYNC_SERVER_INFO_AFTER_LOGIN,O.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),p.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),p.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(p){return mA(this,void 0,void 0,function*(){const B=parseInt(p,10).toString(2),{length:M}=B;let G,O=!0;for(let z=M-1,X=0;z>=0;z--,X++)if(B.charAt(z)==="1"&&(G=X<32?new Nn(0,2**X).toString():new Nn(2**(X-32),0).toString(),!this._featureMap.get(G))){O=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${bc}.isFeatureEnabled decimalNumber:${p} key:${G} ret:${O}`),{code:0,data:{enabled:O}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return mA(this,void 0,void 0,function*(){var p;const{ssoLog:B,utils:{safeStringify:M},common:{buildAndSendPacket:G}}=this._core;try{this._isFetching=!0;const O=yield G({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:(p=this._core.store.get("instance"))===null||p===void 0?void 0:p.sdkAppId}});O&&(this._parseCommercialConfig(O),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(O){B.error("_fetchAndParseCommercialConfig",M(O))}finally{this._isFetching=!1}})}_syncCommercialConfig(p){return mA(this,void 0,void 0,function*(){const{purchaseBits:B}=p?.data||{};B&&(this._parsePurchaseBits(B),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:Au,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var p;const B=(p=this._core.store.get("login"))===null||p===void 0?void 0:p.isLoggedIn,M=Date.now()>=this._expirationTime;return B&&!this._isFetching&&M}_handlePushedConfig(p){p?.body&&(this._parseCommercialConfig(p.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return mA(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(p){const{ssoLog:B}=this._core;if(typeof p!="object")return;const{int32_error_code:M,str_error_message:G,str_purchase_bits:O,uint32_expired_time:z}=p;M===0?(this._parsePurchaseBits(O),this._expirationTime=Date.now()+1e3*z):M===void 0?(B.warn("_parseCommercialConfig",`${bc}._parseCommercialConfig failed. Invalid message format:`,p),this._expirationTime=Date.now()+36e5):(B.warn("_parseCommercialConfig",`${bc}._parseCommercialConfig errorCode:${M} errorMessage:${G}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(p){return p&&typeof p=="string"&&p.length>=1&&p.length<=64&&/[01]{1,64}/.test(p)}_parsePurchaseBits(p){const{ssoLog:B,utils:{safeStringify:M}}=this._core;if(this._isValidPurchaseBits(p)){this._purchaseBits=p,this._featureMap.clear(),this._methodKeyMap.clear();let G=null;for(let O=p.length-1,z=0;O>=0;O--,z++)if(G=z<32?new Nn(0,2**z).toString():new Nn(2**(z-32),0).toString(),p[O]==="1"){this._featureMap.set(G,!0);const X=this._getKeyByValue(Ar,G);X&&this._methodKeyMap.set(X,!0)}else{this._featureMap.set(G,!1);const X=this._getKeyByValue(Ar,G);X&&this._methodKeyMap.set(X,!1)}}else B.warn("_parsePurchaseBits",`${bc}.parsePurchaseBits invalid purchases:${M(p)}`)}_getKeyByValue(p,B){const M=Object.entries(p).find(([G,O])=>O===B);return M?M[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(Au),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},NE=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(p){this._core=p;const{notificationCenter:B,InnerEvent:M,channel:G}=this._core;B.subscribeInnerEvent(M.OVERLOAD_PUSH,this._handleOverLoadPush,this),B.subscribeInnerEvent(M.LOGOUT,this._reset,this),B.subscribeInnerEvent(M.DESTROY,this._dispose,this),G.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(p){if(!this._serverOverloadInfoMap.has(p))return;const{overloadStartTimestamp:B,delaySeconds:M}=this._serverOverloadInfoMap.get(p);if(Date.now()-B<=1e3*M)throw new this._core.helper.ChatError({functionName:p,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(p)}_handleOverLoadPush(p){const{OverLoadServCmd:B,DelaySecs:M}=p;this._serverOverloadInfoMap.set(B,{overloadStartTimestamp:Date.now(),delaySeconds:M})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(B.OVERLOAD_PUSH,this._handleOverLoadPush,this),p.unSubscribeInnerEvent(B.LOGOUT,this._reset,this),p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this)}},lh=new class{constructor(){this.name="ConfigCenter"}install(p){sl.init(p),Ug.install(p),eu.install(p),NE.install(p)}},dC=new class{constructor(){this.name="ErrorMessage",this._core=null}install(p){return mA(this,void 0,void 0,function*(){if(this._core=p,this._canFetch()){const B=yield this._fetchErrorMessage();if(!B)return;const M=this._parseResponse(B);this._saveErrorMessage(M)}})}_canFetch(){const p=this._core.store.getStorage("errorMessage");return!p||this._isExpired(p)}_saveErrorMessage(p){this._core.store.setStorage("errorMessage",{errorMessage:p,errorMessageSavedTime:new Date().getTime()})}_fetchErrorMessage(){return mA(this,void 0,void 0,function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(p){console.error(p)}})}_isExpired(p){if(!p)return!0;const{errorMessageSavedTime:B}=p;return B&&new Date().getTime()-B>=6048e5}_parseResponse(p){if(typeof p=="string"){const B=p.split(`; -`),M={},G=new RegExp(/'/g);for(let O=0;O{var Eo,so,hi;const qo=function(cn,yi){const{From_Account:to,From_AccountHeadurl:rs,From_AccountNick:be,IsNeedReadReceipt:bt,MsgBody:OA,MsgClientTime:oi,MsgRandom:ms,MsgSeq:si,MsgTimeStamp:Dn,SendMsgControl:Ni,SupportMessageExtension:yo,To_Account:yt,TinyId:St,MsgCheckResult:Cg,CloudCustomData:qn,IsPeerRead:io,MsgFlagBits:Wr,MsgVersion:cc,EventArray:In}=cn;return{from:to,avatar:rs,nick:be,needReadReceipt:bt===1,readReceiptSentByPeer:io,clientTime:oi,messageFlagBits:Wr,random:ms,sequence:si,time:Dn,messageControlInfo:Ni,isSupportExtension:yo,to:yt,tinyID:St,checkResult:Cg,cloudCustomData:qn,messageVersion:cc,eventArray:In,elements:yi.message.messageHelper.parseServerPushMessageElement(OA)}}(Ki,dt);if(!((hi=(so=(Eo=Ki?.EventArray)===null||Eo===void 0?void 0:Eo[0])===null||so===void 0?void 0:so.hasOwnProperty)===null||hi===void 0)&&hi.call(so,"C2cNotifyMsgArray"))Wt.push(...function(cn){var yi;const to=[];return(yi=cn.EventArray)===null||yi===void 0||yi.forEach(rs=>{var be,bt;const{C2cNotifyMsgArray:OA}=rs,oi=(bt=(be=OA?.[0])===null||be===void 0?void 0:be.WithdrawC2cMsgNotify)===null||bt===void 0?void 0:bt.C2cWithdrawInfoArray;Array.isArray(oi)&&to.push(...oi)}),to}(Ki));else{const cn=dt.message.messageFactory.createMessage(Object.assign(Object.assign({},qo),{conversationType:"C2C",flow:"in"})),{elements:yi}=qo;cn.setElement(yi),xt.push(cn)}}),{unreadMessageList:xt,revokedMessageList:Wt}}(DA.MsgList,B);return{syncFlag:DA?.SyncFlag,unreadMessageList:Qe,revokedMessageList:At,unreadCountList:GA,overflowUnreadCountList:KA,cookie:DA?.Cookie,groupTipList:re}}catch(DA){console.warn(DA)}})}var rl,Fg;(function(p){p[p.START_SYNC=0]="START_SYNC",p[p.SYNCING=1]="SYNCING",p[p.SYNC_COMPLETE=2]="SYNC_COMPLETE"})(rl||(rl={})),function(p){p[p.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",p[p.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(Fg||(Fg={}));var Io=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie="",this._localConversationIDListBeforeDisconnect=[]}install(p){this._core=p;const{constants:B}=p;p.helper.registerWorkflowStep(B.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,B.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),p.helper.registerWorkflowStep(B.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,B.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),p.helper.registerWorkflowStep(B.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,B.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.SOCKET_DISCONNECTED,this._handleDisconnect,this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.LOGOUT,this._reset,this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(p){return mA(this,void 0,void 0,function*(){const{isAfterReOnline:B=!1,isAfterNewMessageReceived:M=!1,isAfterLogin:G=!1}=p||{};let O=rl.START_SYNC;const z=[],X=[],gA=[],DA=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:O});){const GA=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:O,syncTriggerEvent:M?Fg.NEW_MESSAGE_RECEIVED:Fg.LOGIN_SUCCESS});if(!GA)break;const{unreadMessageList:KA=[],revokedMessageList:re=[],overflowUnreadCountList:Qe,unreadCountList:At,groupTipList:lt}=GA;if(this._cookie=GA?.cookie||"",O=GA?.syncFlag,this._parseAndSaveUnreadMessageList(KA),gA.push(...re),this._updateConversationUnreadOptions({unreadCountList:At,overflowUnreadCountList:Qe,conversationUpdateFieldList:z}),Array.isArray(lt)&&X.push(...lt),B){const{messages:dt}=this._handleNewMessageList(KA);DA.push(...dt)}}return B?{conversationUpdateFieldList:z,revokedMessageList:gA,unreadMessageMap:this._unreadDBMessageMap,groupTipList:X,messages:DA,isUnreadC2CMessage:!0}:{conversationUpdateFieldList:z,isInstantMessage:!G,isUnreadC2CMessage:!0,revokedMessageList:gA,unreadMessageMap:this._unreadDBMessageMap,groupTipList:X}})}_syncUnreadDBMessageAfterLogin(){return mA(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(p){return mA(this,void 0,void 0,function*(){if(p.data.Flag===1)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(p){const{unreadCountList:B,overflowUnreadCountList:M,conversationUpdateFieldList:G}=p,{constants:{OuterConstant:{CONV_C2C:O,CONV_SYSTEM:z}}}=this._core;B?.forEach(X=>{const{From_Account:gA,UnreadCount:DA}=X;if(gA!==z){const GA=G.find(({conversationID:KA})=>KA===`${O}${gA}`);GA?GA.unreadCount=DA:G.push({conversationID:`${O}${gA}`,unreadCount:DA,type:O})}}),M?.forEach(X=>{const{From_Account:gA,LastMsgTime:DA}=X;gA!==z&&(G.find(({conversationID:GA})=>GA===`${O}${gA}`)||G.push({conversationID:`${O}${gA}`,type:O,lastMsgTime:DA}))})}_syncUnreadDBMessageAfterReOnline(){return mA(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(p){var B;const{messageDataHandler:M}=this._core.message||{},G=(B=this._core.store.get("login"))===null||B===void 0?void 0:B.userId,{from:O,nick:z,avatar:X,conversationID:gA=""}=p;if(O!==G){const DA=M.getLatestMsgSentByPeer(gA);if(DA){const{nick:GA,avatar:KA}=DA;z&&X?z===GA&&X===KA||M.updateNickAndAvatarOfSentMessage({conversationID:gA,latestNick:z,latestAvatar:X,isSentByMe:!1}):(p.nick=GA,p.avatar=KA)}}else{const DA=M.getLatestMsgSentByMe(gA);!DA||z===DA.nick&&X===DA.avatar||M.updateNickAndAvatarOfSentMessage({conversationID:gA,latestNick:z,latestAvatar:X,isSentByMe:!0})}}_handleNewMessageList(p){const{messageDataHandler:B}=this._core.message||{},M=new Map,G=[];return p.forEach(O=>{this._updateMessageProfile(O);let z=O.isModified===1;if(B.isMessageSentByCurrentInstance(O)?O.isModified=z:z=!1,O.isOnlineMessage())O._onlineOnlyFlag=!0,B.isMessageSentByCurrentInstance(O)||G.push(O);else if(this._shouldStoreUnreadMessage(O)){if(B.storeConversationMessage(O)){const{conversationID:X,conversationType:gA,conversationSubType:DA,flow:GA,_isExcludedFromUnreadCount:KA,_isExcludedFromLastMessage:re}=O,Qe=re?"":O;M.has(X)?(M.get(X).lastMessage=Qe,GA==="in"&&(KA||M.get(X).unreadCount++)):M.set(X,{conversationID:X,type:gA,subType:DA,unreadCount:KA||GA!=="in"?0:1,lastMessage:Qe})}B.isMessageSentByCurrentInstance(O)&&!z||G.push(O)}}),{messages:G,conversationOptions:M}}_shouldStoreUnreadMessage(p){var B;const{conversationID:M}=p,{message:G,appStore:O,utils:{isEmpty:z}}=this._core||{},X=Array.from(((B=O.conversationStore.getConversationMap())===null||B===void 0?void 0:B.keys())||[]),gA=this._getLocalLastMessageTime(M);return!G.messageDataHandler.isInMessageList(p)&&X.includes(M)&&this._localConversationIDListBeforeDisconnect.includes(M)&&!z(gA)}_fetchUnreadDBMessage(p){return mA(this,void 0,void 0,function*(){const{ssoLog:B,utils:{safeStringify:M}}=this._core;try{B.debug("_fetchUnreadDBMessage",`unread-message-synchronizer._fetchUnreadDBMessage options:${M(p)}`);const O=yield Ih(p,this._core);if(!O)return null;const{syncFlag:z,unreadMessageList:X,revokedMessageList:gA,cookie:DA,unreadCountList:GA,overflowUnreadCountList:KA,groupTipList:re}=O;return this._parseAndSaveUnreadMessageList(X),{syncFlag:z,cookie:DA,unreadMessageList:X,revokedMessageList:gA,unreadCountList:GA,overflowUnreadCountList:KA,groupTipList:re}}catch(G){console.log(G)}})}_canContinueSync({cookie:p,syncFlag:B}){var M;return B===rl.START_SYNC||B===rl.SYNCING&&!(!((M=this._core)===null||M===void 0)&&M.helper.isEmpty(p))}_parseAndSaveUnreadMessageList(p){p.forEach(B=>{const{ID:M}=B;this._unreadDBMessageMap.set(M,B)})}_handleDisconnect(){var p;const{appStore:B}=this._core;this._localConversationIDListBeforeDisconnect=Array.from(((p=B.conversationStore.getConversationMap())===null||p===void 0?void 0:p.keys())||[])}_getLocalLastMessageTime(p){const{message:B}=this._core,M=B.messageDataHandler.getLocalMessageList(p),G=M[M.length-1];return G?.time}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var p,B;(p=this._core)===null||p===void 0||p.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(B=this._core)===null||B===void 0||B.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},CC=new class{init(p){var B;this._core=p,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this),document?.addEventListener("visibilitychange",this._visibilityChangeHandler),(B=this._core)===null||B===void 0||B.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var p,B;const M=document?.visibilityState==="visible";(p=this._core)===null||p===void 0||p.store.set("activityMonitor",{isActive:M}),(B=this._core)===null||B===void 0||B.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:M})}_reset(){var p;(p=this._core)===null||p===void 0||p.store.clear("activityMonitor")}_dispose(){document?.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this),this._reset()}},GE=new class{init(p){var B;this._core=p,this._bindAppActivityEvent(),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this),(B=this._core)===null||B===void 0||B.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var p,B,M,G,O;const{MINI_APP_NAMESPACE:z,IN_TT_MINI_GAME:X,IN_WX_MINI_GAME:gA}=((p=this._core)===null||p===void 0?void 0:p.utils)||{};X||gA?((B=z?.onShow)===null||B===void 0||B.call(z,()=>{var DA,GA;(DA=this._core)===null||DA===void 0||DA.store.set("activityMonitor",{isActive:!0}),(GA=this._core)===null||GA===void 0||GA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(M=z?.onHide)===null||M===void 0||M.call(z,()=>{var DA,GA;(DA=this._core)===null||DA===void 0||DA.store.set("activityMonitor",{isActive:!1}),(GA=this._core)===null||GA===void 0||GA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):((G=z?.onAppShow)===null||G===void 0||G.call(z,()=>{var DA,GA;(DA=this._core)===null||DA===void 0||DA.store.set("activityMonitor",{isActive:!0}),(GA=this._core)===null||GA===void 0||GA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(O=z?.onAppHide)===null||O===void 0||O.call(z,()=>{var DA,GA;(DA=this._core)===null||DA===void 0||DA.store.set("activityMonitor",{isActive:!1}),(GA=this._core)===null||GA===void 0||GA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var p;(p=this._core)===null||p===void 0||p.store.clear("activityMonitor")}_dispose(){const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this),this._reset()}},bE=new class{init(p){const{IN_MINI_APP:B,IN_WX_MINI_PLUGIN:M}=p.helper;M||(B?GE.init(p):CC.init(p))}};const Qd="none",kE="online";var al=new class{init(p){this._core=p,this._activateNetworkMonitoring(),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return mA(this,void 0,void 0,function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)})}_deactivateNetworkMonitoring(){this._onOnlineCallback!==null&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),this._onOfflineCallback!==null&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(p){var B,M;const{isConnected:G,networkType:O}=p;(B=this._core)===null||B===void 0||B.store.set("netWorkMonitor",{isNetworkOnline:G,networkType:O}),(M=this._core)===null||M===void 0||M.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:G,networkType:O})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:kE})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:Qd})}_reset(){var p;this._deactivateNetworkMonitoring(),(p=this._core)===null||p===void 0||p.store.clear("netWorkMonitor")}_dispose(){var p,B;(p=this._core)===null||p===void 0||p.notificationCenter.unSubscribeInnerEvent((B=this._core)===null||B===void 0?void 0:B.InnerEvent.DESTROY,this._dispose,this),this._reset()}},pI=new class{init(p){this._core=p,this._activateNetworkMonitoring(),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return mA(this,void 0,void 0,function*(){try{const{utils:{MINI_APP_NAMESPACE:p}}=this._core;this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),p.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(p){console.error(p)}})}_deactivateNetworkMonitoring(){if(this._mpNetworkStatusCallback!==null){const{utils:{MINI_APP_NAMESPACE:p}}=this._core;p.offNetworkStatusChange&&p.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null}}_onNetworkStatusChange(p){var B,M;const{isConnected:G,networkType:O}=p;(B=this._core)===null||B===void 0||B.store.set("netWorkMonitor",{isNetworkOnline:G,networkType:O}),(M=this._core)===null||M===void 0||M.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:G,networkType:O})}_reset(){var p;this._deactivateNetworkMonitoring(),(p=this._core)===null||p===void 0||p.store.clear("netWorkMonitor")}_dispose(){var p,B;(p=this._core)===null||p===void 0||p.notificationCenter.unSubscribeInnerEvent((B=this._core)===null||B===void 0?void 0:B.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Fu=new class{init(p){const{IN_MINI_APP:B}=p.utils;B?pI.init(p):al.init(p)}},Ou=new class{constructor(){this.name="SystemStateMonitor"}install(p){bE.init(p),Fu.init(p)}};const hC=new Set(["tui_room_svr.*","callkit_records_svr.*","room_engine_srv.*","room_engine_http_srv.*","room_engine_mic.*","live_engine_srv.*","live_engine_http_srv.*","live_engine_pk.*","trtc_ai_service.*","call_engine_srv.*"]),Tr="tui_room_svr.*";var ug=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=hC}install(p){this._core=p;const{notificationCenter:B,InnerEvent:M,helper:G}=p;B.subscribeInnerEvent(M.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),B.subscribeInnerEvent(M.LOGOUT,this._reset,this),B.subscribeInnerEvent(M.DESTROY,this._dispose,this),B.subscribeInnerEvent("im_open_push.msg_push",B.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),G.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),G.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(p){return mA(this,void 0,void 0,function*(){const B="transferBusinessCommand";try{const{serviceCommand:M=Tr}=p||{};if(!this._isValidTransferredCommand(M))throw new this._core.helper.ChatError({code:2995,functionName:B});return{code:0,data:(yield function(O,z){return mA(this,void 0,void 0,function*(){const{helper:X,channel:gA}=z,{serviceCommand:DA=Tr,data:GA}=O||{};let KA={};try{KA=typeof GA=="string"?JSON.parse(GA):GA}catch(At){console.warn(At)}const re=X.generateProtocolData({servcmd:DA,data:KA}),Qe=`${re.head.seq}${DA}`;return gA.sendPacket(re,{requestId:Qe,shouldRejectOnError:!1})})}(p,this._core))||{}}}catch(M){throw console.warn(M),new this._core.helper.ChatError({code:M?.errorCode,message:M?.errorInfo,data:{},functionName:B})}})}_onCloudConfigUpdate(p={}){try{if(typeof p.rtc_cmd!="string")return;const B=JSON.parse(p.rtc_cmd);Array.isArray(B)&&(this._transferredCommands=new Set([...this._transferredCommands,...B]))}catch(B){console.log(B)}}_isValidTransferredCommand(p=""){const B=`${p?.split(".")[0]}.*`;return this._transferredCommands.has(B)}_onServerPushBusinessCommand(p){const{OuterEvent:B,notificationCenter:M}=this._core,{MsgContent:G}=p||{},{ROOM_CUSTOM_DATA_RECEIVED:O}=B;M.emitOuterEvent(O,{name:O,data:G})}_reset(){this._transferredCommands=hC}_dispose(){const{notificationCenter:p,InnerEvent:B}=this._core;this._reset(),p.unSubscribeInnerEvent(B.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),p.unSubscribeInnerEvent(B.LOGOUT,this._reset,this),p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this),p.unSubscribeInnerEvent("im_open_push.msg_push",p.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const kc=new class{init(p){this.core=p}};function Pu(p){return mA(this,void 0,void 0,function*(){var B;const{message:M,user:G,appStore:O,constants:{OuterConstant:z}}=kc.core,X=O.conversationStore.getConversationMap();if(X.has(p)){const DA=(B=X.get(p))===null||B===void 0?void 0:B.userProfile;if(DA&&p.startsWith(z.CONV_C2C)){const{avatar:GA,nick:KA}=DA;kc.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:p,latestAvatar:GA,latestNick:KA,isSentByMe:!1})}}const{data:gA}=(yield G.userProfile.getMyProfile())||{};if(gA){const{avatar:DA,nick:GA}=gA;M.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:p,latestAvatar:DA,latestNick:GA,isSentByMe:!0})}})}function Ll(p){return mA(this,void 0,void 0,function*(){const B=p.map(M=>M.revoker);try{const M=yield function(G){return mA(this,void 0,void 0,function*(){var O,z;const X=yield(O=kc.core.user.userProfile)===null||O===void 0?void 0:O.getUserProfile({userIDList:G});return X?.data?(z=X.data)===null||z===void 0?void 0:z.reduce((gA,{userID:DA,nick:GA,avatar:KA})=>(gA[DA]={nick:GA||"",avatar:KA||""},gA),{}):null})}(B);M&&p.forEach(G=>{const{revoker:O}=G;M[O]&&(G.revokerInfo.nick=M[O].nick||"",G.revokerInfo.avatar=M[O].avatar||"",G.revokerInfo.userID=O)})}catch(M){console.debug(M)}})}const pd=1,ta=2,mI=20,Us=2500,BC=1,gl=300;function md(p){return mA(this,void 0,void 0,function*(){var B,M;const{appStore:G,utils:{isEmpty:O},common:{getCurrentUserID:z},notificationCenter:X,OuterEvent:gA,OuterConstant:{CONV_C2C:DA}}=kc.core,{messageList:GA,conversationID:KA}=p,re=G.conversationStore.getConversationMap();let Qe=(B=re.get(KA))===null||B===void 0?void 0:B.peerReadTime;if(!Qe){const lt=KA.replace(DA,""),dt=yield function(xt){return mA(this,void 0,void 0,function*(){const Wt={To_Account:xt};return kc.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:Wt})})}([lt]);if(dt){const{ReadTime:xt}=dt;Qe=xt?.[0],re.has(KA)&&(re.get(KA).peerReadTime=Qe)}}if(re.has(KA)){const lt=(M=re.get(KA))===null||M===void 0?void 0:M.lastMessage;O(lt)||lt.fromAccount===z()&<.lastTime<=Qe&&!lt.isPeerRead&&(lt.isPeerRead=!0,G.conversationStore.updateConversation(KA,{lastMessage:lt}))}const At=[];GA.forEach(lt=>{lt.time<=Qe&&!lt.isPeerRead&<.flow==="out"&&(lt.isPeerRead=!0,At.push(lt))}),At.length>0&&X.emitOuterEvent(gA.MESSAGE_READ_BY_PEER,{name:gA.MESSAGE_READ_BY_PEER,data:At})})}var fI=new class{init(p){this._core=p,p.helper.registerApi({apiName:"getMessageList",context:this}),p.helper.registerApi({apiName:"getMessageListHopping",context:this}),p.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(p){return mA(this,void 0,void 0,function*(){try{const{message:B,OuterConstant:{Direction:M,CONV_C2C:G,CONV_GROUP:O},InnerEvent:{HISTORY_MESSAGE_FETCHED:z},notificationCenter:X}=this._core,{conversationID:gA,nextReqMessageID:DA}=p,GA=mI;if(gA==="@TIM#SYSTEM")return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const KA=this._getAvailableLocalMessagesCount({conversationID:gA,nextReqMessageID:DA});if(this._needFetchHistoryMessageList({conversationID:gA,availableLocalMessagesCount:KA,targetCount:GA})){let re=null;if(gA.startsWith(O)?re=yield B.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:gA,sequence:Number(DA),count:GA,direction:M.FORWARD,shouldMarkCompleted:!0}):gA.startsWith(G)&&(re=yield B.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:gA,messageID:DA,count:GA,direction:M.FORWARD,shouldMarkCompleted:!0})),re){const{nextReqMessageIDFromServer:Qe,hasNoMoreHistoryMessage:At,messageList:lt}=re,dt=B.messageDataHandler.prependLocalMessageList({messageList:lt,conversationID:gA});(function(so){const{appStore:hi,message:qo,OuterConstant:cn}=kc.core,yi=hi.conversationStore.getConversation(so),to=qo.messageDataHandler.getLocalMessageList(so);if(!yi||to.length===0||so===cn.CONV_SYSTEM)return;const rs=[];for(let bt=0;btOA.isRevoked).length;be=rs.length-yi.unreadCount-bt}else be=rs.length-yi.unreadCount;for(let bt=0;btso.isRevoked);yield Ll(Wt),X.emitInnerEvent(z,dt);const Ki={nextReqMessageID:At?"":String(Qe),messageList:xt,isCompleted:At},Eo=xt.map(so=>so.sequence);return{code:0,data:Ki,successLog:{message:`conversationID: ${gA} nextReqMessageID: ${DA} availableLocalMessagesCount: ${KA} sequenceList: ${JSON.stringify(Eo)}`}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:gA,nextReqMessageID:DA,count:GA}),successLog:{message:`conversationID: ${gA} nextReqMessageID: ${DA} availableLocalMessagesCount: ${KA}}`}}}catch(B){const{code:M,message:G}=B||{};throw new this._core.helper.ChatError({code:M,message:G,moreMessage:`options: ${this._core.utils.safeStringify(p)}`})}})}getMessageListHopping(p){return mA(this,void 0,void 0,function*(){var B,M;const{OuterConstant:{Direction:G,CONV_C2C:O,CONV_GROUP:z},utils:{safeStringify:X}}=this._core,{conversationID:gA,sequence:DA,time:GA,direction:KA=G.FORWARD}=p,{utils:{isEmpty:re},message:Qe,notificationCenter:At,InnerEvent:{HISTORY_MESSAGE_FETCHED:lt}}=this._core;if(![G.BACKWARD,G.FORWARD].includes(KA))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${X(p)}`});let{count:dt=mI}=p;dt=dt>mI?mI:dt;let xt=null;if(gA.startsWith(z)){if(xt=yield Qe.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:gA,sequence:DA,count:dt,direction:KA}),xt){const{nextReqMessageIDFromServer:Wt,hasNoMoreHistoryMessage:Ki,messageList:Eo,invisibleSequenceList:so}=xt;if(this._core.message.messageDataHandler.storeSparseMessageList(Eo),At.emitInnerEvent(lt,Eo),KA===G.FORWARD){const hi=Ki&&Wt<1;return{code:0,data:{messageList:Eo,isCompleted:hi,nextMessageSeq:hi?"":Wt}}}if(KA===G.BACKWARD){if(re(Eo)&&re(so))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const hi=((B=Eo?.[Eo.length-1])===null||B===void 0?void 0:B.sequence)||0,qo=((M=so?.[so.length-1])===null||M===void 0?void 0:M.sequence)||0;return{code:0,data:{messageList:Eo.filter(cn=>cn.sequence>=DA),isCompleted:!Ki,nextMessageSeq:Ki?Math.max(hi,qo)+1:""}}}return{code:0,data:xt}}}else if(gA.startsWith(O)&&(xt=yield Qe.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:gA,count:dt+1,time:GA,direction:KA}),xt)){const{messageList:Wt,lastMessageTime:Ki,hasNoMoreHistoryMessage:Eo}=xt;return At.emitInnerEvent(lt,Wt),Eo||(KA===G.FORWARD?Wt.shift():Wt.pop()),Qe.messageDataHandler.storeSparseMessageList(Wt),yield md({messageList:Wt,conversationID:gA}),{code:0,data:{messageList:Wt,isCompleted:Eo,nextMessageTime:Eo?"":Ki}}}})}clearHistoryMessage(p){return mA(this,void 0,void 0,function*(){var B;const{appStore:M,common:{ChatError:G,getCurrentUserID:O},OuterConstant:{CONV_C2C:z,CONV_GROUP:X},apiMap:gA,message:DA}=this._core,GA=M.conversationStore.getConversation(p);if(!GA)throw new G({code:Us});const KA={fromAccount:O()},{type:re}=GA;re===z?(KA.type=pd,KA.toAccount=p.replace(z,"")):re===X&&(KA.type=ta,KA.toGroupID=p.replace(X,""));try{return yield(B=gA?.setMessageRead)===null||B===void 0?void 0:B.call(gA,{conversationID:p}),(yield function(At){return mA(this,void 0,void 0,function*(){const{fromAccount:lt,type:dt,toAccount:xt,toGroupID:Wt}=At,Ki={From_Account:lt,Type:dt,To_Account:xt,ToGroupid:Wt};return kc.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:Ki})})}(KA))&&(DA.messageDataHandler.deleteConversationMessageList(p),DA.messageHistory.completedHistoryConversations.delete(p),DA.messageHistory.clearHistoryMessageListFetchAnchors(p),this._updateConversationLastMessage(p)),{code:0,data:{conversationID:p},successLog:{message:`convID:${p}`}}}catch(Qe){const{errorCode:At}=Qe;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:At,moreMessage:`convID:${p}`})}})}_updateConversationLastMessage(p){const{appStore:B}=this._core;B.conversationStore.updateConversation(p,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:p,nextReqMessageID:B}){const{OuterConstant:{CONV_C2C:M,CONV_GROUP:G}}=this._core,O=this._core.message.messageDataHandler.getLocalMessageList(p),{length:z}=O;if(!B)return z;let X=-1;return p?.startsWith(M)?X=O.findIndex(gA=>gA.ID===B):p?.startsWith(G)&&(X=O.findIndex(gA=>B.includes("-")?gA.ID===B:String(gA.sequence)===B)),X===-1?0:X}_needFetchHistoryMessageList({conversationID:p,availableLocalMessagesCount:B,targetCount:M}){const{message:G}=this._core;return BB.startsWith(O)?Qe.ID===M:String(Qe.sequence)===M),KA=re>G?re-G:0,DA=re):KA=gA>G?gA-G:0,GA.messageList=X.slice(KA,re),GA.isCompleted=DA<=G&&z.messageHistory.completedHistoryConversations.has(B),GA.isCompleted?GA.nextReqMessageID="":GA.nextReqMessageID=this._generateNextReqMessageID({conversationID:B,targetIndex:KA}),B.startsWith(O)&&(yield Pu(B),yield md({messageList:GA.messageList,conversationID:B})),GA})}_generateNextReqMessageID({conversationID:p,targetIndex:B}){const M=this._core.message.messageDataHandler.getLocalMessageList(p);return p.startsWith("C2C")?M[B].ID:String(M[B].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}},Ha=new class{constructor(){this._lastMessageSequenceMapOnDisconnect=new Map,this._lastMessageTimeMapOnDisconnect=new Map}init(p){this._core=p;const{common:{workflowManager:B},constants:{WORKFLOW_NAME:M,WORKFLOW_STEP:G,InnerEvent:O}}=p;B.registerWorkflowStep(M.SYNC_SERVER_INFO_AFTER_RE_ONLINE,G.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),B.registerWorkflowStep(M.SYNC_SERVER_INFO_AFTER_RE_ONLINE,G.C2C_HISTORY_MESSAGE_RECOVER,this._syncC2COfflineMessage,this),p.notificationCenter.subscribeInnerEvent(O.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncGroupOfflineMessage(p){const{conversationList:B}=p?.result||{},{OuterConstant:M,utils:{isArray:G}}=this._core;if(G(B)){const O=B.filter(z=>z.type===M.CONV_GROUP&&z.groupProfile.type!==M.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(O)}}_recoverGroupHistoryMessage(p){return mA(this,void 0,void 0,function*(){const{OuterConstant:B}=this._core,M=[],G=[];return yield Promise.all(p?.map(O=>mA(this,void 0,void 0,function*(){const{groupProfile:{groupID:z}={},lastMessage:{lastSequence:X}={}}=O,gA=`${B.CONV_GROUP}${z}`;let DA=this._getLocalLastMessageSequence(gA);this._shouldRecoverHistory({localLastMessageSequence:DA,serverLastMessageSequence:X})&&(yield this._recoverGroupHistoryForConversation({conversationID:gA,localLastMessageSequence:DA,serverLastMessageSequence:X,groupTipList:G})),M.push(gA.replace(B.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:M,groupTipList:G}})}_recoverGroupHistoryForConversation(p){return mA(this,arguments,void 0,function*({conversationID:B,localLastMessageSequence:M,serverLastMessageSequence:G,groupTipList:O}){try{const{utils:{isArray:z,isObject:X,isEmpty:gA},OuterEvent:DA,OuterConstant:GA,notificationCenter:KA,message:re,appStore:Qe,common:{getMessagePreviewText:At,buildLastMessage:lt}}=this._core,dt=G-M,xt=Math.min(20,dt),Wt={},Ki=yield re.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:B,sequence:M+xt,direction:GA.Direction.FORWARD,count:xt}),{nextReqMessageIDFromServer:Eo,hasNoMoreHistoryMessage:so,messageList:hi,serverGroupTipList:qo}=Ki;z(qo)&&O.push(...qo);const cn=so&&Eo<0,yi=[];if(z(hi)&&(hi.forEach(to=>{re.messageReceiver.groupMessageReceiver.updateMessageProfile(to),to.from===GA.CONV_SYSTEM&&(to.isSystemMessage=!1),re.messageDataHandler.storeConversationMessage(to)&&!gA(to.payload)&&(yi.push(to),to._isExcludedFromLastMessage||(Wt.lastMessage=lt(to)))}),yi.length>0&&KA.emitOuterEvent(DA.MESSAGE_RECEIVED,{name:DA.MESSAGE_RECEIVED,data:yi})),!cn&&hi.length>0){const to=hi[hi.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:B,localLastMessageSequence:to,serverLastMessageSequence:G,groupTipList:O})}X(Wt.lastMessage)&&(Wt.lastMessage.messageForShow=At(Wt.lastMessage.type,Wt.lastMessage.payload),Qe.conversationStore.updateConversation(B,Wt))}catch(z){this._core.ssoLog.error("_recoverGroupHistoryForConversation",`Recovery failed for conversation:${B}`,{error:z})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:p}=this._core,B=p.messageDataHandler.getContinuousMessagesByConversation();for(const[M,G]of B){const O=Array.from(G.values());if(O?.length>0){const z=O[O.length-1];M.startsWith("C2C")?this._lastMessageTimeMapOnDisconnect.set(M,z.time):M.startsWith("GROUP")&&this._lastMessageSequenceMapOnDisconnect.set(M,z.sequence)}}}_getLocalLastMessageSequence(p){const{message:B}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(p))return this._lastMessageSequenceMapOnDisconnect.get(p);const M=B.messageDataHandler.getLocalMessageList(p),G=M[M.length-1];return G?.sequence}_shouldRecoverHistory(p){const{localLastMessageSequence:B,serverLastMessageSequence:M}=p;if(typeof B!="number"||typeof M!="number")return!1;const G=M-B;return M!==0&&B>0&&G>=BC&&G{z.type===M.CONV_C2C&&O.push(z)}),this._recoverC2CHistoryMessage(O)}}_recoverC2CHistoryMessage(p){return mA(this,void 0,void 0,function*(){yield Promise.all(p?.map(B=>mA(this,void 0,void 0,function*(){const{conversationID:M,lastMessage:{lastTime:G}={}}=B,O=this._getLocalLastMessageTime(M);this._shouldRecoverC2CHistory({localLastMessageTime:O,serverLastMessageTime:G})&&(yield this._recoverHistoryForC2CConversation({conversationID:M,localLastMessageTime:O,serverLastMessageTime:G}))})))})}_shouldRecoverC2CHistory(p){const{localLastMessageTime:B,serverLastMessageTime:M}=p,G=M-B;return B>0&&G>=1&&G<=600}_recoverHistoryForC2CConversation(p){return mA(this,void 0,void 0,function*(){var B;const{conversationID:M,localLastMessageTime:G,serverLastMessageTime:O}=p,{utils:{isArray:z,isObject:X,isEmpty:gA,safeStringify:DA},OuterEvent:GA,OuterConstant:KA,notificationCenter:re,message:Qe,appStore:At,common:{getMessagePreviewText:lt,buildLastMessage:dt}}=this._core;try{const xt={},Wt=yield Qe.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,direction:KA.Direction.BACKWARD,time:G,count:20});if(gA(Wt))return;const{hasNoMoreHistoryMessage:Ki,messageList:Eo}=Wt,so=[];z(Eo)&&(Eo.forEach(qo=>{Qe.messageDataHandler.storeConversationMessage(qo)&&!gA(qo.payload)&&(so.push(qo),qo._isExcludedFromLastMessage||(xt.lastMessage=dt(qo)))}),so.length>0&&re.emitOuterEvent(GA.MESSAGE_RECEIVED,{name:GA.MESSAGE_RECEIVED,data:so}));const hi=(B=Eo[Eo.length-1])===null||B===void 0?void 0:B.time;!Ki&&hi>O&&(yield this._recoverHistoryForC2CConversation({conversationID:M,localLastMessageTime:hi,serverLastMessageTime:O})),X(xt.lastMessage)&&(xt.lastMessage.messageForShow=lt(xt.lastMessage.type,xt.lastMessage.payload),At.conversationStore.updateConversation(M,xt))}catch(xt){this._core.ssoLog.error("_recoverHistoryForC2CConversation",`Recovery failed for conversation:${M} error: ${DA(xt)}`)}})}_getLocalLastMessageTime(p){const{message:B}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(p))return this._lastMessageTimeMapOnDisconnect.get(p);const M=B.messageDataHandler.getLocalMessageList(p),G=M[M.length-1];return G?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},QC=new class{constructor(){this.name="HistoryMessage"}install(p){this._core=p,kc.init(p),fI.init(p),Ha.init(p),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.LOGOUT,this._reset,this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(B.LOGOUT,this._reset,this),p.unSubscribeInnerEvent(B.DESTROY,this.dispose,this),Ha.dispose()}_reset(){Ha.reset()}},Ja=new class{init(p){this.core=p}},fr=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(p){const{helper:{registerExperimentalAPI:B}}=p;this._core=p,B("reportModalView",this),B("reportTUIFeatureUsage",this),B("reportRoomEngineEvent",this)}reportModalView(p){const{ssoLog:B,utils:{safeStringify:M,isString:G}}=this._core;try{if(!G(p))throw new Error("reportModalView data is not a string");B.createSSOLogData({method:"reportModalView",message:p,eventType:30}).end(!0)}catch(O){B.debug(`reportModalView Report failed: ${M(O)}`)}}reportTUIFeatureUsage(p){const{ssoLog:B,utils:{safeStringify:M,isEmpty:G}}=this._core,{atomicStoreID:O}=p;try{G(O)||this._reportedAtomicStoreIDs.has(O)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${p.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:O}),this._reportedAtomicStoreIDs.add(O))}catch(z){B.debug(`reportTUIFeatureUsage Report failed: ${M(z)}`)}}reportRoomEngineEvent(p){const{utils:{safeStringify:B},ssoLog:M}=this._core;try{M.debug(`reportRoomEngineEvent Report: ${B(p)}`);const{eventId:G,eventCode:O,eventResult:z,eventMessage:X,moreMessage:gA,extensionMessage:DA}=p;M.createSSOLogData({method:DA,code:G,message:X,eventType:30,costTime:O,uiPlatform:z,moreMessage:gA}).end(!0)}catch(G){M.debug(`reportRoomEngineEvent Report failed: ${B(G)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},fd=new class{constructor(){this.name="DataReport"}install(p){this._core=p;const{notificationCenter:B,InnerEvent:{LOGOUT:M,DESTROY:G}}=p;Ja.init(p),fr.init(p),B.subscribeInnerEvent(M,this._reset,this),B.subscribeInnerEvent(G,this._dispose,this)}_reset(){fr.reset()}_dispose(){const{notificationCenter:p,InnerEvent:{LOGOUT:B,DESTROY:M}}=this._core;p.unSubscribeInnerEvent(B,this._reset,this),p.unSubscribeInnerEvent(M,this._dispose,this),fr.dispose()}};let xu=ma.STANDARD,yr=[];xu=ma.BASIC,yr=[dC,lh,Io,Ou,ug,QC,fd];function Lc(p,B){const{operationType:M,memberInfoList:G,operatorInfo:O}=p||{};let z={};if(tn(G)?tn(O)||(z=O):M!==ga.JOINED&&M!==ga.KICKED&&M!==ga.ADMIN_SET&&M!==ga.ADMIN_CANCELED||(z=Object.assign({},G[0])),!tn(z)){const{nick:X="",avatar:gA=""}=z;B.nick=X,B.avatar=gA}}const cl=p=>({lastTime:p?.time||p?.lastTime||0,lastSequence:p?.sequence||p?.lastSequence||0,fromAccount:p?.from||p?.fromAccount||"",messageForShow:XI(p?.type,p?.payload),payload:p?.payload||null,type:p?.type||"",isRevoked:p?.isRevoked||!1,cloudCustomData:p?.cloudCustomData||"",onlineOnlyFlag:p?._onlineOnlyFlag||!1,nick:p?.nick||"",nameCard:p?.nameCard||"",version:p?.version||0,isPeerRead:p?.isPeerRead||!1,revoker:p?.revoker||null});var Og=Object.freeze({__proto__:null,ChatError:dn,WorkflowManager:us,buildAndSendPacket:ic,buildLastMessage:cl,get builtInPlugins(){return yr},checkBusinessCapabilityBits:el,deepMerge:Va,getCurrentUserID:$s,getErrorMessage:bl,getMessagePreviewText:XI,isC2CConv:p=>c(p)&&p.slice(0,3)===Gg.CONV_C2C,isCommunity:fa,isGroupConv:p=>c(p)&&p.slice(0,5)===Gg.CONV_GROUP,isInternational:Lu,isTopic:ea,isUnlimitedAVChatRoom:function(){var p;return!!(!((p=ve.store.get("instance"))===null||p===void 0)&&p.unlimitedAVChatRoom)},liteChatInstanceMap:Pn,registerInterceptor:wr,registerValidateConfig:Gc,requireAuth:hn,get sdkEdition(){return xu},setGroupTipsUserInfo:Lc,t:EC,updateGroupAtInfo:(p,B)=>{const{CONV_AT_ME:M,CONV_AT_ALL:G,CONV_AT_ALL_AT_ME:O}=Sn;if(function(gA,DA){const{CONV_AT_ME:GA,CONV_AT_ALL:KA,CONV_AT_ALL_AT_ME:re}=Sn,{groupID:Qe,sequence:At}=gA;let lt=!1;return fa({groupID:Qe})&&DA.forEach(dt=>{dt.messageSequence===At&&(dt.atTypeArray.includes(GA)&&gA.groupAtType.includes(KA)&&(dt.atTypeArray=[re]),dt.atTypeArray.includes(KA)&&gA.groupAtType.includes(GA)&&(dt.atTypeArray=[re],dt.__random=gA.__random,dt.__sequence=gA.__sequence),lt=!0)}),lt}(p,B))return;let z=[...p.groupAtType];z.includes(M)&&z.includes(G)&&(z=[O]);const X={from:p.from,groupID:p.groupID,topicID:p.topicID,messageSequence:p.sequence,atTypeArray:z,__random:p.__random,__sequence:p.__sequence};B.push(X)},validateAndExecute:kl,validateParameters:dd});class Jo{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return Jo._instance||(Jo._instance=new Jo),Jo._instance}static setInstance(B){Jo._instance=B}installBuiltInPlugin(B){B&&this._installPlugin(B,this._builtInPlugins)}installExternalPlugin(B){B&&this._installPlugin(B,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(B,M){let G=[];G=C(B)?B:[B];const O=G.findIndex(X=>X?.name==="AVChatRoom"),z=O>-1?G.splice(O,1):[];G.forEach(X=>{this._isPluginInstalled(X.name)||(X&&Se(X.install)?(M.add(X.name),Se(X.getInstalledSubPlugins)?(z?.forEach(gA=>M.add(gA?.name)),X.install(ss.getInstance().exposeApiForPlugin(),z)):X.install(ss.getInstance().exposeApiForPlugin()),Se(X.handleLoginSuccess)&&this._isLoggedIn()&&X.handleLoginSuccess()):Se(X)?(M.add(X.name),X(ss.getInstance().exposeApiForPlugin()),Se(X.handleLoginSuccess)&&this._isLoggedIn()&&X.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(B){return this._builtInPlugins.has(B)||this._externalPlugins.has(B)}_isLoggedIn(){var B;return((B=ve.store.get("login"))===null||B===void 0?void 0:B.isLoggedIn)===!0}}var nc=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(p){return this._conversationMap.get(p)}updateConversation(p,B,M){const{emit:G=!0,needSort:O=!1}=M||{},z=this._conversationMap.get(p);z&&!tn(B)&&(Object.keys(B).forEach(X=>{z[X]=B[X]}),G&&ve.notificationCenter.emitInnerEvent(Ci.CONVERSATION_UPDATED,{needSort:O}))}deleteConversation(p){this._conversationMap.has(p)&&(this._conversationMap.delete(p),ve.notificationCenter.emitInnerEvent(Ci.CONVERSATION_UPDATED))}},eg=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(p){return this._groupMap.get(p)}updateGroup(p,B){const M=this._groupMap.get(p);M&&!tn(B)&&Object.keys(B).forEach(G=>{M[G]=B[G]})}},Ul=new class{constructor(){this._messagesByConversation=new Map}updateMessage(p,B,M){var G;const{operation:O,updateUnreadCount:z=!0}=M,X=vo(M,["operation","updateUnreadCount"]),gA=[];for(const DA of B){const GA=(G=this._messagesByConversation.get(p))===null||G===void 0?void 0:G.get(DA);if(!GA)return!1;Object.keys(X).forEach(KA=>{GA[KA]=X[KA]}),gA.push(GA)}return this._emitMessageStoreOperationEvent(O,{conversationID:p,messageList:gA,updateUnreadCount:z}),gA}getMessagesByConversation(p){var B;return[...((B=this._messagesByConversation.get(p))===null||B===void 0?void 0:B.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(p,B){const{conversationID:M}=B;ea(M)?ve.notificationCenter.emitInnerEvent(lg[p],B):ve.notificationCenter.emitInnerEvent(p,B)}},ia=new class{constructor(){this.userProfileMap=new Map,this.friendMap=new Map}getUserProfileMap(){return this.userProfileMap}getFriendMap(){return this.friendMap}getUserProfile(p){return this.userProfileMap.get(p)}getFriend(p){return this.friendMap.get(p)}},uh=Object.freeze({__proto__:null,conversationStore:nc,groupStore:eg,messageStore:Ul,userStore:ia});class ss{static getInstance(){return ss._instance||(ss._instance=new ss),ss._instance}static setInstance(B){ss._instance=B}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:ve.notificationCenter.subscribeOuterEvent.bind(ve.notificationCenter),off:ve.notificationCenter.unSubscribeOuterEvent.bind(ve.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:Jo.getInstance().installExternalPlugin.bind(Jo.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(B){ve.ssoLog.debug("registerPlugin",B)}statKeyFeatureUsage(B){ve.ssoLog.debug("statTUIKeyFeatures",B)}setLogLevel(B){ve.ssoLog.debug("setLogLevel",B),ve.ssoLog.setLogLevel(B)}setApplicationID(B){ve.store.set("instance",{applicationID:B})}getApiMap(){return this._apiMap}setApiMap(B){this._apiMap=B}registerApi(B){const{common:{timeManager:M},utils:{safeStringify:G}}=ve,{apiName:O,context:z,methodName:X=O,matcher:gA}=B;this._apiHandlersMap[O]||(this._apiHandlersMap[O]=[]),this._apiHandlersMap[O].push({context:z,methodName:X,matcher:gA}),this._apiMap[O]&&this._apiHandlersMap[O].length!==1||(this._apiMap[O]=(...DA)=>{const GA=M.getServerTimeMs();let KA=0;O==="login"&&(KA=4),Cr.includes(O)&&ve.ssoLog.debug(O,`${O} start params: ${G(DA)}`),kl(X,DA);const re=this._apiHandlersMap[O];for(const Qe of re)if(!Qe.matcher||Qe.matcher(DA))try{const At=Qe.context[Qe.methodName].bind(Qe.context)(...DA);return this._isPromiseLike(At)?this._handleAsyncResult(At,O,KA,GA):(this._reportApiSuccessLog({result:At,apiName:O,eventType:KA,startTime:GA}),At)}catch(At){throw ve.ssoLog.error(O,`${O} fail ${At?.message||At?.errorMessage})`,{error:At,costTime:M.getServerTimeMs()-GA,eventType:KA,method:O}),At}})}registerExperimentalAPI(B,M,G){const O=G||B;this._experimentalApiMap[B]=M[O].bind(M)}destroy(){return mA(this,void 0,void 0,function*(){var B,M;try{!((B=ve.store.get("login"))===null||B===void 0)&&B.isLogin&&(yield this._apiMap.logout()),ve.notificationCenter.emitInnerEvent(Ci.DESTROY)}catch(G){console.debug("destroy error: ",G)}finally{ve.notificationCenter.emitOuterEvent(Ts.SDK_DESTROY,{SDKAppID:(M=ve.store.get("instance"))===null||M===void 0?void 0:M.sdkAppId}),Pn.clear(),Jo.getInstance().clear(),us.getInstance().destroy(),ve.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:Ci,InnerEventSubType:ve.notificationCenter.InnerEventSubType,OuterEvent:Ts,OuterConstant:Sn,SignalingEvent:lo,helper:Object.assign(Object.assign(Object.assign({},ve.utils),ve.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:wr,registerValidateConfig:Gc,checkBusinessCapabilityBits:el,registerWorkflowStep:us.getInstance().registerWorkflowStep.bind(us.getInstance()),ChatError:dn}),apiMap:this._apiMap},ve),{constants:Object.assign(Object.assign({},zI),ve.constants),common:Object.assign(Object.assign(Object.assign({},Og),ve.common),{workflowManager:us.getInstance()}),utils:ve.utils,appStore:uh})}callExperimentalAPI(B,M){return ve.ssoLog.debug(`callExperimentalAPI.${B} start params: ${ve.utils.safeStringify(M)}`),this._experimentalApiMap[B]?this._experimentalApiMap[B](M):(ve.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${B} not found, params: ${ve.utils.safeStringify(M)}`),Promise.reject(new dn({code:Po.INVALID_OPERATION})))}_isPromiseLike(B){return B!==null&&typeof B=="object"&&typeof B.then=="function"}_handleAsyncResult(B,M,G,O){return B.then(z=>(this._reportApiSuccessLog({result:z,apiName:M,eventType:G,startTime:O}),z)).catch(z=>{throw ve.ssoLog.error(M,`${M} fail ${z?.message||z?.errorMessage})`,{error:z,costTime:ve.common.timeManager.getServerTimeMs()-O,eventType:G,method:M,startTime:O}),z})}_reportApiSuccessLog(B){let{result:M,apiName:G,startTime:O,eventType:z}=B;const{timeManager:X}=ve.common,{successLog:{message:gA,moreMessage:DA}={message:"",moreMessage:""}}=M||{},GA=X.getServerTimeMs();G==="login"&&(O+=X.getTimeOffsetWithServer()),Cr.includes(G)&&ve.ssoLog.info(G,`${G} success ${gA} ${DA}`,{costTime:GA-O,eventType:z,message:gA,moreMessage:DA,startTime:O}),M?.successLog&&delete M.successLog}}class tu{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:B,store:M}=ve;M.set("login",{isReady:!1}),ss.getInstance().registerApi({apiName:"login",context:this}),ss.getInstance().registerApi({apiName:"logout",context:this}),ss.getInstance().registerApi({apiName:"getLoginUser",context:this}),ss.getInstance().registerApi({apiName:"isReady",context:this}),ss.getInstance().registerApi({apiName:"getServerTime",context:this}),ss.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),B.subscribeInnerEvent(Ci.RECONNECTED,this._reLogin,this),ve.notificationCenter.subscribeInnerEvent(Ci.DESTROY,this._dispose,this)}login(B){return mA(this,void 0,void 0,function*(){var M;const{sdkEdition:G}=ve.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new dn({functionName:"login",code:Po.REPEAT_LOGIN});const O=yield this._performLogin(B);this._validateAfterLogin(O),this._handleLoginSuccess(O),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const z=(M=ve.channel.getSocketAdapter())===null||M===void 0?void 0:M.getId(),{appId:X,href:gA}=ve.store.get("instance")||{},{instanceID:DA,customStatus:GA}=O||{};return{code:0,data:O,successLog:{message:G,moreMessage:`socketID:${z} instanceID:${DA} customStatus:${GA} href: ${gA} appId: ${X}`}}}catch(O){const{errorCode:z}=O;z!==Po.REPEAT_LOGIN&&(this._latestLoginAt=0);const X=new dn({functionName:"login",code:z});throw console.error(X),X}})}_reLogin(){return mA(this,void 0,void 0,function*(){var B;try{if(!this._isLoginIn())return;const M=yield ku(this._customLoginInfo);if(M){const{instanceID:G,customStatus:O}=M;ve.store.set("login",{statusInstanceId:G}),us.getInstance().executeWorkflow(dr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:O,statusType:Nu.USER_STATUS_ONLINE});const z=(B=ve.channel.getSocketAdapter())===null||B===void 0?void 0:B.getId();ve.ssoLog.info("reLogin",`socketId:${z} instanceId:${G}`)}}catch(M){console.warn(M)}})}logout(){return mA(this,arguments,void 0,function*(B=Ag.USER_INITIATED){const{ssoLog:M}=ve;M.debug("logout",`logout start logoutReason: ${B}`);try{yield this._performLogout(B),M.info("logout","logout success"),ve.ssoLog.uploadSSOLogData()}catch(G){const{errorCode:O}=G;throw new dn({functionName:"logout",code:O})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?$s():""}isReady(){var B;return(B=ve.store.get("login"))===null||B===void 0?void 0:B.isReady}setCustomLoginInfo(B=""){this._customLoginInfo=B}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),us.getInstance().reset(),ve.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:B}=ve.common;return B.getServerTimeMs()}_updateAndEmitSDKReady(){ve.store.set("login",{isReady:!0}),setTimeout(()=>{ve.notificationCenter.emitOuterEvent(Ts.SDK_READY,{name:Ts.SDK_READY})},1)}_updateAndEmitSDKNotReady(){ve.store.set("login",{isReady:!1}),ve.notificationCenter.emitOuterEvent(Ts.SDK_NOT_READY,{name:Ts.SDK_NOT_READY})}_validateAfterLogin(B){const M="login";if(!B)throw new dn({functionName:M,message:"login response is empty"});const{tinyID:G,a2Key:O}=B||{};if(!G)throw new dn({functionName:M,code:Po.NO_TINYID});if(!O)throw new dn({functionName:M,code:Po.NO_A2KEY})}_createRepeatLoginResponse(){var B;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:bl({code:"RepeatLogin",replacement1:(B=ve.store.get("login"))===null||B===void 0?void 0:B.userId}),repeatLogin:!0}}}_performLogin(B){return mA(this,void 0,void 0,function*(){const{userID:M,userSig:G}=B;return ve.store.set("login",{userId:M,userSig:G}),this._latestLoginAt=Date.now(),ku(this._customLoginInfo)})}_ensureAsyncComplete(){return mA(this,void 0,void 0,function*(){yield new Promise(B=>{setTimeout(()=>B(null),1)})})}_handleLoginSuccess(B){const{timeManager:M}=ve.common,{helloInterval:G,timeStamp:O,customStatus:z,purchaseBits:X}=B,gA=1e3*O;M.calculateTimeOffsetWithServer(this._latestLoginAt,gA),this._helloInterval=G||120,this._updateLoginStore(B),ve.user.userStatus.setCustomStatus(z),us.getInstance().executeWorkflow(dr.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:X}),ve.common.taskScheduler.addTask({id:Gu,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(B){return function(M){return mA(this,void 0,void 0,function*(){const{logoutReason:G}=M,O="im_open_status.wslogout",z=ve.common.generateProtocolData({servcmd:O,data:{wslogout_type:G,isWebUniapp:0}}),X=`${z.head.seq}${O}`;return yield ve.channel.sendPacket(z,{requestId:X})})}({logoutReason:B})}_updateLoginStore(B){const{a2Key:M,tinyID:G,instanceID:O,authKey:z}=B;ve.store.set("login",{a2Key:M,tinyID:G,statusInstanceId:O,authKey:z,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return mA(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const B="im_open_status.wshello",M=ve.common.generateProtocolData({servcmd:B,data:{isWebUniapp:0}}),G=`${M.head.seq}${B}`;return ve.channel.sendPacket(M,{requestId:G})}()}catch(B){ve.ssoLog.warn("_sendOnlinePresenceRequest",` error:${B.message}`)}})}_isLoginIn(){var B;return((B=ve.store.get("login"))===null||B===void 0?void 0:B.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){ve.common.taskScheduler.removeTask(Gu),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",ve.store.clear("login"),ve.store.set("login",{isReady:!1}),ve.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:B}=ve;B.unSubscribeInnerEvent(Ci.RECONNECTED,this._reLogin,this),B.unSubscribeInnerEvent(Ci.DESTROY,this._dispose,this)}}const Wn={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},Uc={logout:!0};class sc{constructor(){this.loginAction=new tu,this.kickedOutHandler=new Nc,this.loginAction.init(),this.kickedOutHandler.init(),Gc({auth:Uc,params:Wn})}}var Dr,Kr,tg;(function(p){p.CONV_C2C="C2C",p.CONV_GROUP="GROUP",p.CONV_TOPIC="TOPIC",p.CONV_SYSTEM="@TIM#SYSTEM"})(Dr||(Dr={})),function(p){p.MSG_PRIORITY_HIGH="High",p.MSG_PRIORITY_NORMAL="Normal",p.MSG_PRIORITY_LOW="Low",p.MSG_PRIORITY_LOWEST="Lowest"}(Kr||(Kr={})),function(p){p.MSG_TEXT="TIMTextElem",p.MSG_CUSTOM="TIMCustomElem",p.MSG_LOCATION="TIMLocationElem",p.MSG_FACE="TIMFaceElem",p.MSG_IMAGE="TIMImageElem",p.MSG_AUDIO="TIMSoundElem",p.MSG_FILE="TIMFileElem",p.MSG_VIDEO="TIMVideoFileElem",p.MSG_GRP_TIP="TIMGroupTipElem",p.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",p.MSG_MERGER="TIMRelayElem"}(tg||(tg={}));const LE={1:Kr.MSG_PRIORITY_HIGH,2:Kr.MSG_PRIORITY_NORMAL,3:Kr.MSG_PRIORITY_LOW,4:Kr.MSG_PRIORITY_LOWEST},pC=0,Eh=1;var uo;(function(p){p.IN="in",p.OUT="out"})(uo||(uo={}));const Fc=2,Fl={};function mC(p){if(!p)return 0;if(Fl[p]===void 0){const B=new Date,M=`3${B.getHours()}`.slice(-2),G=`0${B.getMinutes()}`.slice(-2),O=`0${B.getSeconds()}`.slice(-2);Fl[p]=parseInt([M,G,O,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${Fl[p]}`)}else Fl[p]+=1;return Fl[p]}class fC{constructor(B){this.ID="",this.random=0,this.sequence=0,this.nameCard="",this.isRead=!1,this.isPeerRead=!1,this.isDeleted=!1,this.isResend=!1,this.hasRiskContent=!1,this._onlineOnlyFlag=!1,this.atUserList=[],this._groupAtInfoList=[],this.isBroadcastMessage=!1,this.priority=Kr.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:M=ve.common.timeManager.getServerTimeSeconds()||0,senderTinyID:G,currentUser:O,needReadReceipt:z,isSupportExtension:X,customModerationConfigurationId:gA,to:DA,from:GA,nick:KA="",avatar:re="",time:Qe,messageControlInfo:At,tinyID:lt,cloudCustomData:dt="",messageLifeTime:xt,messageVersion:Wt=0,conversationType:Ki,sequence:Eo,checkResult:so=0,isPlaceMessage:hi=0,messageFlagBits:qo,receiverList:cn,isSystemMessage:yi=!1,status:to=Ng.SUCCESS,revokeReason:rs="",conversationSubType:be,clientSequence:bt,protocol:OA="JSON",revokerInfo:oi={userID:"",nick:"",avatar:""},readReceiptInfo:ms={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:si,groupProfile:Dn,atUserList:Ni,flow:yo,isRead:yt=!1,priority:St=Kr.MSG_PRIORITY_NORMAL,onlineOnlyFlag:Cg=!1,nameCard:qn="",quoteInfo:io}=B;var Wr;this.clientTime=M,this.senderTinyID=G||lt,this.needReadReceipt=z===!0||z===1,this.isSupportExtension=X===!0||X===1,this._cmConfigID=gA,this.to=DA,this.nick=KA,this.avatar=re,this.protocol=OA,this.random=si===void 0?(Wr=Wr||99999999,Math.round(Math.random()*Wr)):si,this.time=Qe||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!At?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!At?.excludedFromUnreadCount,this.isModified=!!Wt,this.cloudCustomData=dt,this.messageLifeTime=xt,this.from=GA||null,this.sequence=Eo||0,this.conversationType=Ki||Dr.CONV_C2C,this.hasRiskContent=so>1,this.version=Wt,this.isPlaceMessage=hi,this.isRevoked=hi===2||qo===8,this.isSystemMessage=yi,this.readReceiptInfo=ms,this.revokeReason=rs,this.revokerInfo=oi,this._receiverList=cn,this.conversationSubType=be,this.revoker=oi?.revoker||"",this.clientSequence=bt||Eo||0,this.status=to,this.atUserList=Ni||[],this.flow=yo,this.isRead=yt,this.priority=St,this._onlineOnlyFlag=Cg,this.nameCard=qn,this.quoteInfo=io,this.reInitialize(O),this._initC2CReadReceiptInfo(B),this._extractGroupInfo(Dn)}getElements(){return this._elements}isOnlineMessage(){return this.messageLifeTime===0}setElement(B){Array.isArray(B)?this._elements=B:this._elements=[B],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(B=>B.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(B){this._relayFlag=B}validateBeforeSend(){var B,M,G;return this._relayFlag?{isValid:!0}:((B=this._elements)===null||B===void 0?void 0:B.length)>0?(G=(M=this._elements[0])===null||M===void 0?void 0:M.validateBeforeSend)===null||G===void 0?void 0:G.call(M):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(B){const{readReceiptSentByPeer:M,timestamp:G=0}=B;this.conversationType===Dr.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=M===1,this.readReceiptInfo.timestamp=G)}_extractGroupInfo(B){if(!B)return;const{From_AccountNick:M,From_AccountHeadurl:G,MsgFrom_AccountExtraInfo:O,GroupType:z}=B,{NameCard:X}=O||{};typeof M=="string"&&(this.nick=M),typeof G=="string"&&(this.avatar=G),typeof X=="string"&&(this.nameCard=X),this.conversationSubType=z}reInitialize(B){B===this.from&&(this.isRead=!0),this._initSequence(B),this._concatConversationID(B),this.generateMessageID()}_concatConversationID(B){let M="";const G=this.conversationType;G!==Dr.CONV_SYSTEM?(M=G===Dr.CONV_C2C?B===this.from?this.to:this.from:this.to,this.conversationID=M?`${G}${M}`:null):this.conversationID=Dr.CONV_SYSTEM}_initSequence(B){this.clientSequence===0&&B&&(this.clientSequence=mC(B)),this.sequence===0&&this.conversationType===Dr.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Dr.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(B){this.isRead=B}}class Ol{static parseServerPushElement(B){const{MsgContent:M={}}=B,{Data:G,Ext:O,Desc:z}=M;return new Ol({data:G,description:z,extension:O})}constructor(B){this.type=tg.MSG_CUSTOM;const{data:M="",description:G="",extension:O=""}=B;this.content={data:M,description:G,extension:O}}transformToServerFormat(B){const{isMergerMessage:M=!1}=B||{},G=M?this.payload:this.content,{data:O,description:z,extension:X}=G;return{MsgType:this.type,MsgContent:{Data:O,Ext:X,Desc:z}}}validateBeforeSend(){const{isEmpty:B}=ve.utils,M=[this.content.data,this.content.description,this.content.extension].some(G=>!B(G));return{isValid:M,error:M?null:{message:"content can not be empty"}}}}class iu{static parseServerPushElement(B){const{MsgContent:M={Text:""}}=B,{Text:G}=M;return new iu({text:G})}constructor(B){this.type=tc.MSG_TEXT,this.content={text:B.text||""}}validateBeforeSend(){var B,M;return((M=(B=this.content)===null||B===void 0?void 0:B.text)===null||M===void 0?void 0:M.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(B){const{isMergerMessage:M=!1}=B||{},G=M?this.payload:this.content,{text:O}=G;return{MsgType:this.type,MsgContent:{Text:O}}}}var yI=new class{constructor(){this._elementClassMap={[tg.MSG_CUSTOM]:Ol,[tg.MSG_TEXT]:iu}}init(){ss.getInstance().registerApi({apiName:"createCustomMessage",context:this}),ss.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(p,B){var M;(M=B).prototype!==void 0&&"constructor"in M.prototype&&(this._elementClassMap[p]=B)}getElementClass(p){return this._elementClassMap[p]}createMessage(p){const{from:B,flow:M=uo.OUT}=p,{userId:G}=ve.store.get("login")||{};this._isSendByCurrentInstance({from:B,flow:M,currentUser:G})?this._updateWithSenderInfo(p):this._isMultiEndpointSyncMessage({from:B,flow:M,currentUser:G})&&(p.flow=uo.OUT);const O=Object.assign(Object.assign({},p),{currentUser:G});return new fC(O)}createCustomMessage(p){const B=$s(),M=this.createMessage(Object.assign(Object.assign({},p),{from:B})),G=this._elementClassMap[tg.MSG_CUSTOM];if(!M)return null;if(G){const O=new G(p.payload);M.setElement(O)}return M}createTextMessage(p){var B;if(!p)return null;const M=typeof p.payload=="string"?p.payload:((B=p?.payload)===null||B===void 0?void 0:B.text)||"",G=new iu({text:M}),O=$s(),z=ve.message.messageFactory.createMessage(Object.assign(Object.assign({},p),{from:O}));return z.setElement(G),z}_updateWithSenderInfo(p){var B,M;const{nick:G,avatar:O,conversationType:z,to:X}=p,{userId:gA,tinyID:DA}=ve.store.get("login")||{},GA=ia.getUserProfile(gA);return p.nick=G||GA?.nick||"",p.avatar=O||GA?.avatar||"",p.tinyID=p.tinyID||DA||"",p.from=gA,p.status=Ng.UNSENT,p.flow=uo.OUT,z===Gg.CONV_GROUP&&(p.nameCard=(M=(B=eg.getGroup(X))===null||B===void 0?void 0:B.selfInfo)===null||M===void 0?void 0:M.nameCard),p}_isMultiEndpointSyncMessage(p){const{from:B,flow:M,currentUser:G}=p;return B===G&&M===uo.IN}_isSendByCurrentInstance(p){const{from:B,flow:M,currentUser:G}=p;return B===G&&M===uo.OUT}};const DI={PushFlag:0,Title:"",Desc:"",Ext:"",ApnsInfo:{Sound:"",BadgeMode:0,IsVoipPush:void 0,Image:"",InterruptionLevel:"active",ContentAvailable:0},AndroidInfo:{Sound:"",XiaoMiChannelID:"",OPPOChannelID:"",GoogleChannelID:"",VIVOClassification:1,VIVOCategory:"",HuaWeiCategory:"",OPPOCategory:"",HuaWeiImage:"",HonorImage:"",GoogleImage:"",HonorImportance:"",MeizuNotifyType:void 0}},UE={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},Pl={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function xl(p,B){return Object.keys(B).forEach(M=>{const{range:G,defaultValue:O}=B[M];p[M]=G.includes(p[M])?p[M]:O}),p}function Pg(p){const B=p.lastIndexOf(".");return B===-1?p:p.slice(0,B)}function rc(p){const{androidInfo:B={},androidOPPOChannelID:M=""}=p,G=B.OPPOChannelID||M,O=xl(B,UE),{sound:z="",FCMChannelID:X=""}=O,gA=vo(O,["sound","FCMChannelID"]);return Object.assign(Object.assign({},gA),{Sound:Pg(z),OPPOChannelID:G,GoogleChannelID:X})}function yd(p){const{apnsInfo:B={},ignoreIOSBadge:M=!1,disableVoipPush:G}=p,O=xl(B,Pl),{ignoreIOSBadge:z,disableVoipPush:X,enableIOSBackgroundNotification:gA}=O,DA=vo(O,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),GA=z===!0||M===!0?1:0;let KA;return n(G)||(KA=G===!1?1:0),n(X)||(KA=X===!1?1:0),Object.assign(Object.assign({},DA),{BadgeMode:GA,IsVoipPush:KA,ContentAvailable:gA?1:0})}function FE(p){return ve.utils.isPlainObject(p)?{PushFlag:p.disablePush===!0?1:0,Title:p.title||"",Desc:p.description||"",Ext:p.extension||"",ApnsInfo:yd(p),AndroidInfo:rc(p)}:DI}function Oc(p){const{From_AccountHeadurl:B,From_AccountNick:M,IsNeedReadReceipt:G,IsPeerRead:O,IsSyncMsg:z,MsgBody:X,MsgClientTime:gA,MsgLifeTime:DA,MsgRandom:GA,MsgSeq:KA,MsgTimeStamp:re,SendMsgControl:Qe,SupportMessageExtension:At,TinyId:lt,MsgCheckResult:dt,CloudCustomData:xt,MsgVersion:Wt,MsgFlagBits:Ki,RevokerInfo:Eo,InnerSdkCustomData:so}=p;let hi,{From_Account:qo,To_Account:cn}=p;if(z===1){const yi=cn;cn=qo,qo=yi}if(Eo){const{Reason:yi,Revoker_Account:to,Revoker_FromUin:rs}=Eo;hi={reason:yi,revoker:to,revokerFromUin:rs,userID:to}}return{from:qo,avatar:B,nick:M,needReadReceipt:G===1,isSyncMessage:z,clientTime:gA,messageLifeTime:DA,random:GA,sequence:KA,time:re,messageControlInfo:{excludedFromLastMessage:Qe?.NoLastMsg===1,excludedFromUnreadCount:Qe?.NoUnread===1},isSupportExtension:At,to:cn,tinyID:lt,checkResult:dt,cloudCustomData:xt,revokerInfo:hi,messageVersion:Wt,messageFlagBits:Ki,readReceiptSentByPeer:O,elements:ig(X),onlineOnlyFlag:DA===0,quoteInfo:Yu(so)}}function ou(p){const{From_Account:B,MsgBody:M,MsgClientTime:G,MsgRandom:O,MsgSeq:z,MsgTimeStamp:X,To_Account:gA,MsgVersion:DA,CloudCustomData:GA,MsgCheckResult:KA}=p;return{from:B,clientTime:G,random:O,sequence:z,time:X,to:gA,elements:ig(M),messageVersion:DA,cloudCustomData:GA,checkResult:KA}}function ho(p){const{ClientSeq:B,From_Account:M,GroupInfo:G,MsgBody:O,MsgClientTime:z,MsgRandom:X,MsgSeq:gA,MsgTimeStamp:DA,SendMsgControl:GA,SupportMessageExtension:KA,TinyId:re,CloudCustomData:Qe,MsgVersion:At,MsgCheckResult:lt,NeedReadReceipt:dt,IsPlaceMsg:xt,RevokerInfo:Wt,GroupAtInfo:Ki,OnlineOnlyFlag:Eo,InnerSdkCustomData:so}=p;let hi,qo=Kr.MSG_PRIORITY_NORMAL;if(Object.keys(LE).includes(String(p.MsgPriority))&&(qo=LE[p.MsgPriority]),Wt){const{Reason:yi,Revoker_Account:to,Revoker_FromUin:rs}=Wt;hi={reason:yi,revoker:to,revokerFromUin:rs,userID:to}}const cn=function(yi){const to=[];return Array.isArray(yi)&&yi.forEach(rs=>{rs.GroupAtAllFlag===pC?to.push(rs.GroupAt_Account):rs.GroupAtAllFlag===Eh&&to.push(Sn.MSG_AT_ALL)}),to}(Ki);return{clientSequence:B,from:M,groupProfile:G,clientTime:z,priority:qo,random:X,sequence:gA,time:DA,messageControlInfo:{excludedFromLastMessage:GA?.NoLastMsg===1,excludedFromUnreadCount:GA?.NoUnread===1},isSupportExtension:KA,tinyID:re,cloudCustomData:Qe,messageVersion:At,checkResult:lt,needReadReceipt:dt,isPlaceMessage:xt,revokerInfo:hi,atUserList:cn,elements:ig(O),to:OE(p),onlineOnlyFlag:Eo===1,quoteInfo:Yu(so)}}function OE(p){const{utils:{isEmpty:B},constants:{IS_TOPIC_MESSAGE:M}}=ve,{ToGroupId:G,GroupInfo:{MillionGroupFlag:O=0,TopicId:z}={}}=p;return O!==M||B(z)?G:z}function ig(p){if(!p)return null;if(Array.isArray(p))return p.map(M=>{const G=ve.message.messageFactory.getElementClass(M.MsgType);return G?.parseServerPushElement(M)});const B=ve.message.messageFactory.getElementClass(p.MsgType);return B?.parseServerPushElement(p)}function nu(p){const{From_Account:B,MsgBody:M,MsgClientTime:G,MsgRandom:O,MsgSeq:z,MsgTimeStamp:X,GroupId:gA,TopicId:DA,MsgVersion:GA,CloudCustomData:KA,MsgCheckResult:re}=p;return{from:B,clientTime:G,random:O,sequence:z,time:X,groupID:gA,topicID:DA,elements:ig(M),messageVersion:GA,cloudCustomData:KA,checkResult:re}}function Yu(p){const{utils:{isString:B,safeStringify:M},ssoLog:G}=ve;if(!B(p))return null;try{const{messageID:O,messageTime:z,messageSequence:X}=JSON.parse(p).businessQuote;return{msgID:O,messageTime:z,messageSequence:X}}catch(O){return G.debug("_parseServerQuoteInfo",M(O)),null}}function Pc({conversationUpdateFields:p,message:B}){const{conversationID:M,conversationType:G,conversationSubType:O,flow:z,_isExcludedFromUnreadCount:X,_isExcludedFromLastMessage:gA}=B,DA=gA?"":cl(B),GA=!X&&z===uo.IN;p.has(M)?(p.get(M).lastMessage=DA,GA&&p.get(M).unreadCount++):p.set(M,{conversationID:M,type:G,subType:O,unreadCount:GA?1:0,lastMessage:DA})}function SI(p){return p.filter(B=>{const M=!tn(B?._elements),G=B?.isPlaceMessage===1;return M||ve.ssoLog.error("emptyMessageBody",`from:${B.from} to:${B.to} sequence:${B.sequence}`),M&&!G})}function ll(p){const{messageDataHandler:B}=ve.message;return!B.isInMessageList(p)&&!B.isMessageSentByCurrentInstance(p)}var Il=Object.freeze({__proto__:null,autoIncrementIndex:mC,createAndroidPushInfo:rc,createApnsPushInfo:yd,createOfflinePushInfo:FE,filterValidMessages:SI,getAndroidSoundName:Pg,parseServerGroupMessage:ho,parseServerPushC2CModifyMessage:ou,parseServerPushGroupModifyMessage:nu,parseServerPushMessage:Oc,parseServerPushMessageElement:ig,shouldStoreMessage:ll,updateConversationFields:Pc});const{isPlainObject:qa}=ve.utils;function PE(p,B={}){const{onlineUserOnly:M,messageControlInfo:G}=B;let{offlinePushInfo:O}=B;p.conversationType===Dr.CONV_C2C&&M===!0&&(O?O.disablePush=!0:O={disablePush:!0});let z="";typeof p.cloudCustomData=="string"&&p.cloudCustomData.length>0&&(z=p.cloudCustomData);const X=[];if(G&&qa(G)){const{excludedFromUnreadCount:gA,excludedFromLastMessage:DA,excludedFromContentModeration:GA}=G;gA===!0&&X.push("NoUnread"),DA===!0&&X.push("NoLastMsg"),GA===!0&&X.push("NoMsgCheck")}return{onlineUserOnly:M,cloudCustomData:z,messageControlInfo:X,offlinePushInfo:O}}function la(p){const{webhookInfo:{disableCloudMessagePreHook:B=!1,disableCloudMessagePostHook:M=!1}={}}=p||{};if(!B&&!M)return;const G=[];return B&&G.push("ForbidBeforeSendMsgCallback"),M&&G.push("ForbidAfterSendMsgCallback"),G}function Gs(p,B){return mA(this,void 0,void 0,function*(){const M=p.conversationType===Dr.CONV_GROUP?function(O,z){var X;const gA=PE(O,z),{onlineUserOnly:DA,cloudCustomData:GA,messageControlInfo:KA,offlinePushInfo:re}=gA,Qe=JSON.parse(JSON.stringify(O.transformElementsToServerFormat()));let At;return C(O._receiverList)&&O._receiverList.length>0&&(At=O._receiverList,O._receiverList.length>50&&(At=O._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:(X=ve.store.get("login"))===null||X===void 0?void 0:X.userId,GroupId:O.to,MsgBody:Qe,CloudCustomData:GA,Random:O.random,MsgPriority:O.priority,ClientSeq:O.clientSequence,GroupAtInfo:O._groupAtInfoList,OnlineOnlyFlag:DA?1:0,MsgClientTime:O.clientTime,OfflinePushInfo:FE(re),SendMsgControl:DA?void 0:KA,NeedReadReceipt:O.needReadReceipt===!0?1:0,To_Account:At,SupportMessageExtension:O.isSupportExtension===!0?1:0,IsRelayMsg:O._relayFlag===!0?1:0,CustomModerationConfigID:O._cmConfigID,ForbidCallbackControl:la(z),InnerSdkCustomData:xE(O)}}}(p,B):function(O,z){var X;const gA=PE(O,z),{onlineUserOnly:DA,cloudCustomData:GA,messageControlInfo:KA,offlinePushInfo:re}=gA,Qe=DA===!0?0:void 0,At=JSON.parse(JSON.stringify(O.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:(X=ve.store.get("login"))===null||X===void 0?void 0:X.userId,To_Account:O.to,MsgBody:At,CloudCustomData:GA,MsgSeq:O.sequence,MsgRandom:O.random,MsgLifeTime:Qe,From_AccountNick:O.nick,From_AccountHeadurl:O.avatar,SendMsgControl:Qe!==0?KA:void 0,MsgClientTime:O.clientTime,IsNeedReadReceipt:O.needReadReceipt===!0?1:0,SupportMessageExtension:O.isSupportExtension===!0?1:0,IsRelayMsg:O._relayFlag===!0?1:0,CustomModerationConfigID:O._cmConfigID,OfflinePushInfo:FE(re),ForbidCallbackControl:la(z),InnerSdkCustomData:xE(O)}}}(p,B),G=yield ic(M);return G?{time:G.MsgTime,messageDropReason:G.MsgDropReason,sequence:G.MsgSeq}:null})}function Or(p){return mA(this,void 0,void 0,function*(){const{from:B,to:M,version:G=0,sequence:O,random:z,time:X,type:gA,cloudCustomData:DA}=p,GA={From_Account:B,To_Account:M,MsgVersion:G,MsgSeq:O,MsgRandom:z,MsgTime:X,MsgType:gA,MsgBody:p.transformElementsToServerFormat(),CloudCustomData:DA},KA=yield ic({servcmd:"openim.modify_c2c_msg",data:GA});if(KA){const{MsgBody:re,MsgVersion:Qe,CloudCustomData:At}=KA;return{elements:ig(re),messageVersion:Qe,cloudCustomData:At}}})}function ul(p){return mA(this,void 0,void 0,function*(){const{to:B,version:M=0,sequence:G,cloudCustomData:O}=p,z={GroupId:B,MsgVersion:M,MsgSeq:G,MsgBody:p.transformElementsToServerFormat(),CloudCustomData:O},X=yield ic({servcmd:"openim.modify_group_msg",data:z});if(X){const{MsgBody:gA,MsgVersion:DA,CloudCustomData:GA}=X;return{elements:ig(gA),messageVersion:DA,cloudCustomData:GA}}})}function Yl(p){return mA(this,void 0,void 0,function*(){const{groupID:B,count:M,messageSequence:G,messageSequenceList:O,getType:z}=p,X={GroupId:B,ReqMsgNumber:M,WithRecalledMsg:1,Version:1,GetType:z};return G&&(X.ReqMsgSeq=G),C(O)&&O.length>0&&(X.ReqMsgSeqList=O),yield ic({servcmd:"group_open_http_svc.group_msg_get",data:X})})}function xc(p){return mA(this,void 0,void 0,function*(){const{peerAccount:B,count:M,lastMessageTime:G,messageKey:O,direction:z}=p;return ic({servcmd:"openim.getroammsg",data:{Peer_Account:B,MaxCnt:M,WithRecalledMsg:1,LastMsgTime:G,MsgKey:O,GetDirection:z}})})}function xE(p){if(ve.utils.isObject(p.quoteInfo)){const{msgID:B,messageSequence:M,messageTime:G}=p.quoteInfo;return JSON.stringify({businessQuote:{messageID:B,messageSequence:M,messageTime:G}})}}var Yc=Object.freeze({__proto__:null,createMessagePackOptions:PE,generateForbidCallbackControl:la,getC2CRoamingMessagesByAnchor:xc,getGroupRoamingMessagesByAnchor:Yl,getRoamingMessages:function(p){return mA(this,void 0,void 0,function*(){const{peerAccount:B,count:M,lastMessageTime:G,messageKey:O}=p;return(yield ic({servcmd:"openim.getroammsg",data:{Peer_Account:B,MaxCnt:M||15,LastMsgTime:G||0,MsgKey:O,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:Or,modifyGroupMessage:ul,sendMessage:Gs});const{isPlainObject:Vu}=ve.utils,{MSG_AUDIO:yC,MSG_FILE:su,MSG_IMAGE:dh,MSG_VIDEO:Hu,MSG_MERGER:vI}=Sn;class El{constructor(){this._sendProtocolMap=new Map}init(){ss.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:B=>![yC,su,dh,Hu,vI].includes(B[0].type)})}registerSendProtocol(B,M,G){this._sendProtocolMap.set(B,M.bind(G))}sendMessage(B,M){return mA(this,void 0,void 0,function*(){const{TOTAL_COUNT:G,SEND_COST:O,SUCCESS_COUNT:z,FAILED_COUNT:X}=dI;if(!(B instanceof fC))throw new dn({code:Po.MSG_INSTANCE_REQUIRED});const gA=B.validateBeforeSend();if(!gA.isValid){const{code:KA,message:re=""}=gA.error||{};throw new dn({code:KA,message:re})}this._reportMessageSendQuality({name:G,message:B});let DA=!1;const{messageDataHandler:GA}=ve.message||{};try{const{messageControlInfo:KA}=M||{};let re=null;GA.addRandomOfSentMessage(B.random);const Qe=Date.now(),At=this._getSendProtocol(B);if(B.conversationType===Dr.CONV_C2C?(DA=M?.onlineUserOnly===!0,re=yield At(B,M)):B.conversationType===Dr.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(B),re=yield At(B,M)),re){const{messageDropReason:lt,sequence:dt,time:xt}=re;if(this._updateNickAndAvatarOfSentMessageByMe(B),lt&&this._logRateLimitInfo(B,dt,lt),this._reportMessageSendQuality({name:z,message:B}),this._reportMessageSendQuality({name:O,message:B,startTs:Qe}),B.isResend===!0){const Wt=GA.findMessage(B.ID);Wt&&(ve.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${Wt.ID}`),GA.deleteConversationMessage(Wt))}return B.status=Ng.SUCCESS,B.time=xt,B.conversationType===Dr.CONV_GROUP&&(B.sequence=dt),DA?B._onlineOnlyFlag=!0:(GA.storeConversationMessage(B),this._applySentMessageControlInfo(B,KA),this._emitOnlineMessageSent(B)),B.type===tc.MSG_STREAM?{code:0,data:{message:B,streamMessageID:re.streamMessageID}}:{code:0,data:{message:B}}}}catch(KA){B.status=Ng.FAIL,GA.removeRandomOfSentMessage(B.random);let{errorCode:re}=KA||{},Qe=KA?.errorInfo||KA?.message||"";throw this._hasRiskContent(re)&&(B.hasRiskContent=!0),DA||this._isRejectedByRestApi(re)||GA.storeConversationMessage(B),this._reportMessageSendQuality({name:X,message:B,error:KA}),new dn({code:re,message:Qe,data:{message:B},moreMessage:`type:${B.type} from:${B.from} to:${B.to}`})}})}_hasRiskContent(B){return B===80001||B===80004}_isRejectedByRestApi(B){return B>=10100&&B<=10200||B>=120001&&B<=13e4}_emitOnlineMessageSent(B){const M=B._isExcludedFromLastMessage?"":B,{conversationID:G,conversationType:O}=B,z=ea(G)?Ci.TOPIC_NEW_MESSAGE:Ci.NEW_MESSAGE;ve.notificationCenter.emitInnerEvent(z,{result:{conversationUpdateFieldList:[{conversationID:G,type:O,message:B,lastMessage:M,unreadCount:0}]}})}_applySentMessageControlInfo(B,M){M&&Vu(M)&&(M.excludedFromLastMessage===!0&&(B._isExcludedFromLastMessage=!0),M.excludedFromUnreadCount===!0&&(B._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(B,M,G){const O=`from:${B.from} to:${B.to} sequence:${M} messageDropReason:${G}`;ve.ssoLog.warn("messageDropReason",O)}_updateNickAndAvatarOfSentMessageByMe(B){const{messageDataHandler:M}=ve.message||{};let G=!1;const{conversationID:O}=B,z=M.getLatestMsgSentByMe(O);if(z){const{nick:X,avatar:gA}=z;X===B.nick&&gA===B.avatar||(G=!0),G&&M.updateNickAndAvatarOfSentMessage({conversationID:O,latestNick:B.nick,latestAvatar:B.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(B){return mA(this,void 0,void 0,function*(){var M,G,O;const{to:z,from:X}=B;let gA=z,DA=eg.getGroup(gA);if(fa({groupID:gA})&&DA?.isSupportTopic)throw new dn({code:Po.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(ea(z)&&([gA]=z.split(xa.TOPIC),DA=eg.getGroup(gA)),!DA&&typeof((M=ss.getInstance().getApiMap())===null||M===void 0?void 0:M.getGroupProfile)=="function"){const GA=yield ss.getInstance().getApiMap().getGroupProfile({groupID:gA});if(((O=(G=GA?.data)===null||G===void 0?void 0:G.group)===null||O===void 0?void 0:O.type)===Sn.GRP_AVCHATROOM){const KA=bl({code:Po.MSG_SEND_FAIL_NOT_IN_AV,replacement1:X,replacement2:gA});throw new dn({code:Po.MSG_SEND_FAIL_NOT_IN_AV,message:KA})}}return!0})}_reportMessageSendQuality(B){ve.notificationCenter.emitInnerEvent(Ci.QUALITY_STAT,{label:kg.MESSAGE_SEND_SUCCESS_RATE,data:B})}_getSendProtocol(B){return this._sendProtocolMap.get(B.type)||Gs}}var DC=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){ve.notificationCenter.subscribeInnerEvent(Ci.LOGOUT,this._reset,this),ve.notificationCenter.subscribeInnerEvent(Ci.DESTROY,this._dispose,this)}get _messagesByConversation(){return Ul.getMessages()}storeConversationMessage(p,B=!1){if(jn)return!0;const{conversationID:M}=p;if(!M||(this._messagesByConversation.has(M)||this._messagesByConversation.set(M,new Map),this._shouldSkipStoreMessage(p,B)))return!1;const G=this._getUniqueIdOfMessage(p);return this._messagesByConversation.get(M).set(G,p),this._updateLatestMessageMap(p),!0}_updateLatestMessageMap(p){const{conversationID:B}=p;p.flow==="out"?this._setLatestMsgSentByMe(B,p):B.startsWith("C2C")&&this._setLatestMsgSentByPeer(B,p)}_shouldSkipStoreMessage(p,B){const M=this._getUniqueIdOfMessage(p),G=this._messagesByConversation.get(p.conversationID);if(G?.has(M)){const O=G?.get(M);if(!B||O?.isModified===!0)return!0}return!1}deleteConversationMessage(p){var B;const{conversationID:M=""}=p,G=this._getUniqueIdOfMessage(p);this._messagesByConversation.has(M)&&((B=this._messagesByConversation.get(M))===null||B===void 0||B.delete(G))}modifyConversationMessage(p,B){var M;if(!this._messagesByConversation.has(p)&&!this._sparseMessagesByConversation.has(p))return{isUpdated:!1,message:null};const G=this._getUniqueIdOfMessage(B),O=this._getMessageFromLocalMessage(p,G);if(O){const{messageVersion:z,elements:X,cloudCustomData:gA,checkResult:DA=0}=B,GA=DA>1;if(ve.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${O.version} remoteVersion:${z}`),O.versionO.ID===p)||null,B)break;if(!B){const G=Array.from(this._sparseMessagesByConversation.values());for(const O of G)if(B=O.get(p)||null,B)break}return B}deleteConversationMessageList(p){this._messagesByConversation.has(p)&&(this._messagesByConversation.delete(p),this._latestMessageSentByMeMap.delete(p),this._latestMessageSentByPeerMap.delete(p)),this._sparseMessagesByConversation.has(p)&&this._sparseMessagesByConversation.delete(p)}revokeMessage({conversationID:p,sequence:B,random:M,revoker:G}){const O=this._messagesByConversation.get(p);let z=null;if(O){const X=Array.from(O.values());if(z=this._findMessageBySequenceAndRandom({messageList:X,random:M,sequence:B}),z){const gA=this._getUniqueIdOfMessage(z);return Ul.updateMessage(p,[gA],{isRevoked:!0,revoker:G,operation:qr.revoke}),z}}if(this._sparseMessagesByConversation.has(p)){const X=Array.from(this._sparseMessagesByConversation.get(p).values());if(z=this._findMessageBySequenceAndRandom({messageList:X,random:M,sequence:B}),z)return z.isRevoked=!0,z.revoker=G,z}}_findMessageBySequenceAndRandom({messageList:p,sequence:B,random:M}){for(let G=0;G0){const X=new Map([...O,...z.entries()]);this._messagesByConversation.set(M,X),this._updateLatestMessageSentByMe(M),this._updateLatestMessageSentByPeer(M)}return G}storeSparseMessageList(p){if(p.length===0)return;const{conversationID:B}=p[0],M=p.length;this._sparseMessagesByConversation.has(B)||this._sparseMessagesByConversation.set(B,new Map);const G=this._sparseMessagesByConversation.get(B);for(let O=0;O=0;G--)if(M[G].flow==="out"){this._setLatestMsgSentByMe(p,M[G]);break}}}_updateLatestMessageSentByPeer(p){var B;const M=Array.from(((B=this._messagesByConversation.get(p))===null||B===void 0?void 0:B.values())||[]);if(M.length!==0&&p.startsWith("C2C")){for(let G=M.length-1;G>=0;G--)if(M[G].flow==="in"){this._setLatestMsgSentByPeer(p,M[G]);break}}}_getUniqueIdOfMessage(p){const{from:B,to:M,random:G,sequence:O,time:z}=p;return`${B}-${M}-${G}-${O}-${z}`}_setLatestMsgSentByPeer(p,B){this._latestMessageSentByPeerMap.set(p,B)}_setLatestMsgSentByMe(p,B){this._latestMessageSentByMeMap.set(p,B)}getLatestMsgSentByPeer(p){return this._latestMessageSentByPeerMap.get(p)}getLatestMsgSentByMe(p){return this._latestMessageSentByMeMap.get(p)}addRandomOfSentMessage(p){this._randomOfSentMessageList.add(p)}removeRandomOfSentMessage(p){this._randomOfSentMessageList.delete(p)}updateNickAndAvatarOfSentMessage(p){const{conversationID:B="",latestAvatar:M,latestNick:G,isSentByMe:O=!0}=p,z=this._messagesByConversation.get(B);if(!z)return;const X=Array.from(z.values()),gA=O?"out":"in";X.forEach(DA=>{const{nick:GA,avatar:KA,flow:re}=DA;re===gA&&(GA!==G&&(DA.nick=G),KA!==M&&(DA.avatar=M))})}isInMessageList(p){var B;const{conversationID:M}=p;if(!M||!this._messagesByConversation.has(M))return!1;const G=this._getUniqueIdOfMessage(p);return(B=this._messagesByConversation.get(M))===null||B===void 0?void 0:B.has(G)}isMessageSentByCurrentInstance(p){const{random:B}=p;return this._randomOfSentMessageList.has(B)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(p){const B=this._messagesByConversation.get(p);return B?[...B.values()]:[]}getSparseMessageList(p){const B=this._sparseMessagesByConversation.get(p);return B?[...B.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),ve.notificationCenter.unSubscribeInnerEvent(Ci.LOGOUT,this._reset,this),ve.notificationCenter.unSubscribeInnerEvent(Ci.DESTROY,this._dispose,this)}};function Ia(p,B){const M=nc.getConversation(p);if(M?.lastMessage){const{lastMessage:G}=M,{lastTime:O,lastSequence:z,version:X}=G,{time:gA,sequence:DA,messageVersion:GA,elements:KA,cloudCustomData:re}=B;O===gA&&z===DA&&X!==GA&&(G.type=KA[0].type,G.payload=KA[0].content,G.messageForShow=XI(G.type,G.payload),G.cloudCustomData=re,G.version=GA,nc.updateConversation(p,{lastMessage:G}))}}class ac{init(){ss.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(B){return mA(this,void 0,void 0,function*(){const{to:M,payload:G,sequence:O,conversationType:z,random:X,time:gA,from:DA,type:GA}=B;if(this._canModifyMessageElement(GA)){const KA=B?._elements||[];KA.length>=1&&(KA[0].type=GA,KA[0].content=G)}try{let KA=null,re=null;if(z===Dr.CONV_C2C?KA=yield Or(B):z===Dr.CONV_GROUP&&(KA=yield ul(B)),KA){let Qe=`${z}${M}`;return M===$s()&&z===Dr.CONV_C2C&&(Qe=`${z}${DA}`),re={conversationType:z,from:DA,to:M,time:gA,random:X,sequence:O,elements:KA?.elements,cloudCustomData:KA?.cloudCustomData,messageVersion:KA?.messageVersion,conversationID:Qe},this._handleModifyMessageSuccess(re),{code:0,data:{message:B},successLog:{message:`to:${M}`}}}}catch(KA){const{errorCode:re}=KA||{};throw new dn({functionName:"modifyMessage",code:re,moreMessage:`to:${M}`})}})}_handleModifyMessageSuccess(B){const{conversationID:M}=B,{isUpdated:G,message:O}=ve.message.messageDataHandler.modifyConversationMessage(M,B);G===!0&&ve.notificationCenter.emitOuterEvent(Ts.MESSAGE_MODIFIED,{name:Ts.MESSAGE_MODIFIED,data:[O]}),ve.notificationCenter.emitInnerEvent(Ci.MESSAGE_MODIFIED,{conversationID:M,message:O}),Ia(M,B)}_canModifyMessageElement(B){return[tg.MSG_TEXT,tg.MSG_CUSTOM,tg.MSG_LOCATION,tg.MSG_FACE].includes(B)}}class Eg{init(){const{notificationCenter:B}=ve,{InnerEventSubType:M}=B;us.getInstance().registerWorkflowStep(dr.RECEIVE_C2C_NEW_MESSAGE,jt.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),us.getInstance().registerWorkflowStep(dr.RECEIVE_C2C_NEW_MESSAGE,jt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),us.getInstance().registerWorkflowStep(dr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,jt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),B.subscribeInnerEvent(Ci.MESSAGE_PUSH,M.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),B.subscribeInnerEvent(Ci.MESSAGE_PUSH,M.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),B.subscribeInnerEvent(Ci.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(B){us.getInstance().executeWorkflow(dr.RECEIVE_C2C_NEW_MESSAGE,B)}_handleC2CMessagePush(B){const M=B.data||{},{messageDataHandler:G}=ve.message||{},O=[],z=new Map;return M.C2cMsgArray.forEach(X=>{const gA=this._generateC2CMessage(X);this._updateMessageProfile(gA);let DA=gA.isModified===1;G.isMessageSentByCurrentInstance(gA)?gA.isModified=DA:DA=!1,gA._onlineOnlyFlag?G.isMessageSentByCurrentInstance(gA)||O.push(gA):ll(gA)&&(G.storeConversationMessage(gA)&&Pc({conversationUpdateFields:z,message:gA}),G.isMessageSentByCurrentInstance(gA)&&!DA||O.push(gA))}),{conversationUpdateFieldList:[...z.values()],messages:O}}_emitMessageEventsAfterReceiveNewMessage(B){var M;const{messages:G=[]}=((M=B.result)===null||M===void 0?void 0:M[jt.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(G)}_emitMessageEventsAfterSyncUnreadMessage(B){var M;const{messages:G=[]}=((M=B.result)===null||M===void 0?void 0:M[jt.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(G)}_emitMessageEvents(B){const M=B?.filter(O=>O?.isModified===!0)||[];M.length>0&&ve.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:M});const G=B?.filter(O=>!O?.isModified);G.length>0&&ve.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:G})}_generateC2CMessage(B){const M=Dr.CONV_C2C,G=Oc(B),O=ve.message.messageFactory.createMessage(Object.assign(Object.assign({},G),{conversationType:M,flow:uo.IN})),{elements:z}=G;return O.setElement(z),O}_updateMessageProfile(B){var M;const{messageDataHandler:G}=ve.message||{},O=(M=ve.store.get("login"))===null||M===void 0?void 0:M.userId,{from:z,nick:X,avatar:gA,conversationID:DA=""}=B;if(z!==O){const GA=G.getLatestMsgSentByPeer(DA);if(GA){const{nick:KA,avatar:re}=GA;n(X)||n(gA)?(B.nick=c(KA)?KA:B.nick,B.avatar=c(re)?re:B.avatar):X===KA&&gA===re||(G.updateNickAndAvatarOfSentMessage({conversationID:DA,latestNick:X,latestAvatar:gA,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:DA,nick:X,avatar:gA}))}}else{const GA=G.getLatestMsgSentByMe(DA);!GA||X===GA.nick&&gA===GA.avatar||G.updateNickAndAvatarOfSentMessage({conversationID:DA,latestNick:X,latestAvatar:gA,isSentByMe:!0})}}_updateConversationUserProfile(B){const{conversationID:M,nick:G,avatar:O}=B,z=nc.getConversation(M),{userProfile:X={}}=z||{};X.avatar===O&&X.nick===G||nc.updateConversation(M,{userProfile:Object.assign(Object.assign({},X),{nick:G,avatar:O})})}_updateMessageListDueToModify(B){const{conversationID:M}=B,{isUpdated:G,message:O}=ve.message.messageDataHandler.modifyConversationMessage(M,B);G===!0&&ve.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[O]}),ve.notificationCenter.emitInnerEvent("ModifyMessageSuccess",B),Ia(M,B)}_handleC2CMessageModify(B){B.C2cMsgModNotifys.forEach(M=>{var G;const O=Dr.CONV_C2C;let z=ou(M);const{to:X,from:gA}=z;let DA=`${O}${X}`;X===((G=ve.store.get("login"))===null||G===void 0?void 0:G.userId)&&(DA=`${O}${gA}`),z=Object.assign({conversationType:O,conversationID:DA},z),this._updateMessageListDueToModify(z)})}_dispose(){const{notificationCenter:B}=ve,{InnerEventSubType:M}=B;ve.notificationCenter.unSubscribeInnerEvent(Ci.MESSAGE_PUSH,M.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),ve.notificationCenter.unSubscribeInnerEvent(Ci.MESSAGE_PUSH,M.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),ve.notificationCenter.unSubscribeInnerEvent(Ci.DESTROY,this._dispose,this)}}class MI{init(){const{notificationCenter:B}=ve,{InnerEventSubType:M}=B;us.getInstance().registerWorkflowStep(dr.RECEIVE_GROUP_NEW_MESSAGE,jt.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),us.getInstance().registerWorkflowStep(dr.RECEIVE_GROUP_NEW_MESSAGE,jt.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),B.subscribeInnerEvent(Ci.MESSAGE_PUSH,M.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),B.subscribeInnerEvent(Ci.MESSAGE_PUSH,M.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),B.subscribeInnerEvent(Ci.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(B){this._canExecuteReceiverNewMessageWorkFlow(B)&&us.getInstance().executeWorkflow(dr.RECEIVE_GROUP_NEW_MESSAGE,B)}_handleGroupMessagePush(B){const M=B.data||{},{messageDataHandler:G}=ve.message,O=[],z=new Map,X=M?.GroupMsgArray;return X?.forEach(gA=>{if(gA.GroupInfo.NotVisible===1)return;const DA=this._generateGroupMessage(gA);this.updateMessageProfile(DA);let GA=DA.isModified===1;G.isMessageSentByCurrentInstance(DA)?DA.isModified=GA:GA=!1,DA._onlineOnlyFlag?G.isMessageSentByCurrentInstance(DA)||O.push(DA):ll(DA)&&G.storeConversationMessage(DA)&&(O.push(DA),Pc({conversationUpdateFields:z,message:DA}))}),{conversationUpdateFieldList:[...z.values()],messages:O}}_emitMessageEvents(B){var M;const{messages:G}=((M=B.result)===null||M===void 0?void 0:M[jt.HANDLE_GROUP_NEW_MESSAGE])||{},O=G?.filter(X=>X?.isModified===!0)||[];O.length>0&&ve.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:O});const z=G?.filter(X=>!X?.isModified)||[];z.length>0&&ve.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:z})}_generateGroupMessage(B){const M=Dr.CONV_GROUP,G=ho(B),O=ve.message.messageFactory.createMessage(Object.assign(Object.assign({},G),{conversationType:M,flow:uo.IN})),{elements:z}=G;return O.setElement(z),O}updateMessageProfile(B){var M;const{messageDataHandler:G}=ve.message||{},O=(M=ve.store.get("login"))===null||M===void 0?void 0:M.userId,{from:z,nick:X,avatar:gA,conversationID:DA="",_elements:GA}=B;if(z===O){const KA=G.getLatestMsgSentByMe(DA);!KA||X===KA.nick&&gA===KA.avatar||G.updateNickAndAvatarOfSentMessage({conversationID:DA,latestNick:X,latestAvatar:gA,isSentByMe:!0})}else if(z===Sn.CONV_SYSTEM){const{operationType:KA,memberInfoList:re,operatorInfo:Qe}=GA;let At={};if(tn(re)?tn(Qe)||(At=Qe):[ga.JOINED,ga.KICKED,ga.ADMIN_SET,ga.ADMIN_CANCELED].includes(KA)&&(At=Object.assign({},re[0])),!tn(At)){const{nick:lt="",avatar:dt=""}=At;B.nick=lt,B.avatar=dt}}}_updateMessageListDueToModify(B){const{conversationID:M}=B,{isUpdated:G,message:O}=ve.message.messageDataHandler.modifyConversationMessage(M,B);G===!0&&ve.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[O]}),Ia(M,B)}_handleGroupMessageModify(B){B.GroupMsgModNotifys.forEach(M=>{const G=Dr.CONV_GROUP;let O=nu(M);const{topicID:z,groupID:X}=O,gA=z||X,DA=`${G}${gA}`;O=Object.assign({conversationType:G,conversationID:DA,to:gA},O),this._updateMessageListDueToModify(O)})}_dispose(){const{notificationCenter:B}=ve,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:M,GROUP_MESSAGE_MODIFIED:G}}=B;B.unSubscribeInnerEvent(Ci.MESSAGE_PUSH,M,this._handleGroupMessagePush,this),B.unSubscribeInnerEvent(Ci.MESSAGE_PUSH,G,this._handleGroupMessageModify,this),B.unSubscribeInnerEvent(Ci.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(B){var M,G;const{GroupId:O,GroupType:z}=((G=(M=B?.GroupMsgArray)===null||M===void 0?void 0:M[0])===null||G===void 0?void 0:G.GroupInfo)||{},X=z===RE.GRP_AVCHATROOM;return!(!eg.getGroup(O)&&X)}}var YE=new class{constructor(){this.c2cMessageReceiver=new Eg,this.groupMessageReceiver=new MI}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const Ju={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:p=>!(!p.startsWith("C2C")&&!p.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:p=>function(B){var M;return typeof B?.text!="string"||typeof B.text=="string"&&((M=B?.text)===null||M===void 0?void 0:M.length)===0?"payload.text must be a string":!0}(p)}}},qu={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var RI=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(p){return mA(this,void 0,void 0,function*(){try{const{conversationID:B,count:M,direction:G,sequence:O,messageSequenceList:z,shouldMarkCompleted:X=!1,getType:gA}=p,DA=B.replace(Gg.CONV_GROUP,""),GA=[];let KA=O;if(G===_c.BACKWARD){if(typeof O!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};KA=O+M-1}const re=yield Yl({groupID:DA,count:M,messageSequence:KA,messageSequenceList:z,getType:gA});if(re){const{RspMsgList:Qe=[],NextReqMsgSeq:At=0,IsFinished:lt,InvisibleMsgSeq:dt}=re,xt=`groupID:${DA} sequence:${O} reqSeq:${KA} direction:${G} complete:${lt} nextSequence:${At} remoteMsgCount:${Qe.length} invisibleSequenceList:${dt}`,Wt=[];for(let so=0;so=O),Ki&&X&&this.completedHistoryConversations.add(B);const Eo=SI(Wt);return ve.ssoLog.info("getGroupRoamingMessagesByAnchor",xt),{messageList:Eo,invisibleSequenceList:dt,nextReqMessageIDFromServer:At,hasNoMoreHistoryMessage:Ki,serverGroupTipList:GA}}}catch(B){const{errorCode:M,errorInfo:G}=B||{};throw new dn({code:M,message:G})}})}clearHistoryMessageListFetchAnchors(p){this._historyMessageListFetchAnchors.delete(p)}isHistoryMessageFetchCompleted(p){return this.completedHistoryConversations.has(p)}_parseMessage(p){var B;const M=Gg.CONV_GROUP;p.Event===4&&(p.MsgBody.MsgType=Sn.MSG_GRP_TIP);const G=ho(p),O=yI.createMessage(Object.assign(Object.assign({},G),{conversationType:M,flow:"in"}));return Lc(((B=G.elements)===null||B===void 0?void 0:B.content)||{},O),O.setElement(G.elements),O}getC2CRoamingMessagesByAnchor(p){return mA(this,void 0,void 0,function*(){var B;try{const{conversationID:M,count:G,messageID:O,time:z,direction:X,shouldMarkCompleted:gA=!1}=p;let DA=z,GA="";if(!z){const Qe=O?ve.message.messageDataHandler.findMessage(O):null;if(DA=Qe?.time||0,O&&this._historyMessageListFetchAnchors.has(M)){const At=this._historyMessageListFetchAnchors.get(M);DA=At.lastMessageTime,GA=At.messageKey}}const KA=M.replace(Gg.CONV_C2C,""),re=yield xc({count:G,lastMessageTime:DA,messageKey:GA,peerAccount:KA,direction:X});if(re){const{MsgList:Qe=[],Complete:At,MsgKey:lt,LastMsgTime:dt}=re;this._historyMessageListFetchAnchors.set(M,{messageKey:lt,lastMessageTime:dt});const xt=[];for(let so=0;so{const{tag:O,value:z}=G;O&&O.indexOf(dg)>-1?M.profileCustomField.push({key:O,value:z}):Vl.has(O)&&(M[Vl.get(O)]=z)}),Object.assign(Object.assign({},Ka),M)}parseProfileItem(p=[]){const B=[];return p.forEach(M=>{B.push({tag:M.Tag,value:M.Value})}),B}parseProfileList(p=[]){const B=[];return p.forEach(M=>{B.push({tag:M.Tag,value:M.ValueBytes})}),B}convertParamsToProfile(p){const B=[];return Object.keys(p).forEach(M=>{M!==hr&&B.push({tag:xr[M.toUpperCase()],value:p[M]})}),p.profileCustomField&&C(p.profileCustomField)&&p.profileCustomField.forEach(M=>{B.push({tag:M.key,value:M.value})}),B}normalizeProfileFields(p){const B={},M=[];return p.forEach(G=>{const{tag:O,value:z}=G;if(O&&O.indexOf(dg)>-1&&M.push({key:O,value:z}),Vl.has(O)&&z!==void 0){const X=Vl.get(O);B[X]=z}}),M.length>0&&(B.profileCustomField=M),B}};const{generateProtocolData:wI}=ve.common;function ru(p){return mA(this,void 0,void 0,function*(){const B="profile.portrait_get_all",M={From_Account:$s(),UserItem:[]};p.forEach(X=>{M.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:X})});const G=wI({servcmd:B,data:M}),O=`${G.head.seq}${B}`,z=yield ve.channel.sendPacket(G,{requestId:O});if(z)return function(X){const{ActionStatus:gA,ErrorCode:DA,ErrorDisplay:GA,ErrorInfo:KA,UserProfileItem:re}=X,Qe=[];return re.map(At=>{const{To_Account:lt,CustomSequence:dt,ResultCode:xt,ResultInfo:Wt,StandardSequence:Ki,ProfileItem:Eo}=At,so=ya.parseProfileItem(Eo);Qe.push({userId:lt,customSequence:dt,resultCode:xt,resultInfo:Wt,standardSequence:Ki,profileItem:so})}),{actionStatus:gA,errorCode:DA,errorDisplay:GA,errorInfo:KA,userProfile:Qe}}(z)})}function Da(p){return ia.getFriendMap().has(p)}const{isEmpty:Cl}=ve.utils;class VE{constructor(){this._strangerProfileMap=new Map}init(){ss.getInstance().registerApi({apiName:"getMyProfile",context:this}),ss.getInstance().registerApi({apiName:"getUserProfile",context:this}),ss.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=ya.createProfile.bind(ya);const{notificationCenter:B}=ve;us.getInstance().registerWorkflowStep(dr.SYNC_SERVER_INFO_AFTER_LOGIN,jt.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),B.subscribeInnerEvent(Ci.MESSAGE_PUSH,B.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),B.subscribeInnerEvent(Ci.LOGOUT,this._reset,this),B.subscribeInnerEvent(Ci.DESTROY,this._dispose,this)}getMyProfile(){return mA(this,void 0,void 0,function*(){try{const B=$s(),M=yield ru([B]);if(M){const G=this._handleProfileFormResponse(M)[0];return ia.getUserProfileMap().set(B,G),{code:0,data:G}}}catch(B){const{errorCode:M,errorInfo:G}=B;throw new dn({functionName:"getMyProfile",code:M,message:G})}})}getUserProfile(B){return mA(this,void 0,void 0,function*(){try{let{userIDList:M}=B;const{userIdListToRequest:G,profileFromCache:O}=this._filterRequestAndCacheUsers(M);if(G.length===0)return{code:0,data:O,successLog:{message:`userIDList.length:${M.length}`}};G.length>xg&&(ve.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),G.length=xg);const{data:z,error:X}=yield this._batchFetchUserProfiles(G),gA=G.length,DA=z.length,GA=gA-DA;if(O.length===0&&gA===GA&&!Cl(X))throw X;if(C(z))return z.forEach(re=>{Da(re.userID)?ia.getUserProfileMap().set(re.userID,re):this._strangerProfileMap.set(re.userID,re)}),{code:0,data:z.concat(O),successLog:{message:`getUserProfile query:${gA} success:${DA} fail:${GA} from cache:${O.length}`}}}catch(M){throw new dn(M)}})}getMyProfileCacheThenServer(){return mA(this,void 0,void 0,function*(){const B=$s(),M=ia.getUserProfileMap().has(B);return M?{code:0,data:M}:this.getMyProfile()})}updateMyProfile(B){return mA(this,void 0,void 0,function*(){const M=$s(),G={};for(const z in B)B[z]!==void 0&&(G[z]=B[z]);const O=ya.convertParamsToProfile(G);try{yield function(GA){return mA(this,void 0,void 0,function*(){const KA="profile.portrait_set",re=wI({servcmd:KA,data:GA}),Qe=`${re.head.seq}${KA}`,At=yield ve.channel.sendPacket(re,{requestId:Qe});if(At){const{ActionStatus:lt,ErrorCode:dt,ErrorDisplay:xt,ErrorInfo:Wt}=At;return{actionStatus:lt,errorCode:dt,errorDisplay:xt,errorInfo:Wt}}})}({From_Account:M,ProfileItem:O});const X=ia.getUserProfile(M);let gA;gA=X?Object.assign(Object.assign({},X),G):ya.createProfile(M,O);const DA=!_g(X,gA,["lastUpdatedTime"]);return gA.lastUpdatedTime=Date.now(),ia.getUserProfileMap().set(M,gA),DA&&this._emitProfileUpdated(gA),{code:0,data:gA,successLog:{message:`profileArray: ${ve.utils.safeStringify(O)}`}}}catch(z){const{errorCode:X,errorInfo:gA}=z;throw new dn({functionName:"updateMyProfile",code:X,message:gA,moreMessage:`params: ${ve.utils.safeStringify(B)}`})}})}updateMyNickAndAvatar(B){return mA(this,void 0,void 0,function*(){const M=$s(),G=Date.now(),O=ia.getUserProfile(M);let z={};z=O?Object.assign(O,B):ya.createProfile(M,B),z.lastUpdatedTime=G,ia.getUserProfileMap().set(M,z)})}_onProfileDataModify(B){const M=function(z){const{Profile_Account:X,PushType:gA,ProfileList:DA}=z;return{userId:X,pushType:gA,profileList:ya.parseProfileList(DA)}}(B.ProfileDataMod[0]);if(Cl(M))return;const{isProfileUpdated:G,profile:O}=this._handleProfileModified(M);G&&this._emitProfileUpdated(O)}_emitProfileUpdated(B){ve.notificationCenter.emitInnerEvent(Ci.PROFILE_UPDATE,{name:Ci.PROFILE_UPDATE,data:[B]}),ve.notificationCenter.emitOuterEvent(Ts.PROFILE_UPDATED,{name:Ts.PROFILE_UPDATED,data:[B]}),nc.updateConversation(`C2C${B?.userID}`,{userProfile:B})}_dispose(){const{notificationCenter:B}=ve;B.unSubscribeInnerEvent(Ci.LOGOUT,this._reset,this),B.unSubscribeInnerEvent(Ci.MESSAGE_PUSH,B.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),B.unSubscribeInnerEvent(Ci.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(B){const{userId:M,profileList:G}=B,O=ia.getUserProfile(M);if(!($s()===M||Da(M)&&O))return{isProfileUpdated:!1,profile:null};const z=ya.normalizeProfileFields(G),X=Object.keys(z).some(KA=>KA===hr?this._isCustomFieldChanged(O.profileCustomField,z.profileCustomField):O[KA]!==z[KA]);if(!X)return{isProfileUpdated:!1,profile:O};const gA=Date.now(),DA=Object.prototype.hasOwnProperty.call(z,hr)?this._mergeProfileCustomField(O.profileCustomField,z.profileCustomField):O.profileCustomField,GA=Object.assign(Object.assign(Object.assign({},O),z),{profileCustomField:DA,lastUpdatedTime:gA});return ia.getUserProfileMap().set(M,GA),{isProfileUpdated:X,profile:GA}}_filterRequestAndCacheUsers(B){const M=[],G=[];return B.forEach(O=>{const z=ia.getUserProfileMap().has(O);Da(O)&&z?G.push(ia.getUserProfile(O)):this._isStrangerAndProfileValid(O)?G.push(this._strangerProfileMap.get(O)):M.push(O)}),{userIdListToRequest:M,profileFromCache:G}}_handleProfileFormResponse(B){const{userProfile:M}=B;if(!Array.isArray(M))return[];const G=M.filter(z=>z.userId!=="@TLS#NOT_FOUND"&&z.userId!==""&&!Cl(z.profileItem)),O=Date.now();return G.map(z=>{const X=ya.createProfile(z.userId,z.profileItem);return X.lastUpdatedTime=O,X})}_isStrangerAndProfileValid(B){var M;if(!Da(B)){const{lastUpdatedTime:G=0}=this._strangerProfileMap.get(B)||{},O=((M=ve.store.get("cloudConfig"))===null||M===void 0?void 0:M.stranger_profile_expiration_time)||6e5;return Date.now()-G<=O}return!1}_chunkUserIDList(B,M){return Array.from({length:Math.ceil(B.length/M)},(G,O)=>B.slice(O*M,(O+1)*M))}_batchFetchUserProfiles(B){return mA(this,void 0,void 0,function*(){const M=[],G=[];let O={};return this._chunkUserIDList(B,100).forEach(z=>{M.push(ru(z))}),(yield Promise.allSettled(M)).forEach(z=>{if(z.status==="fulfilled"){const X=z.value,gA=this._handleProfileFormResponse(X);C(gA)&&G.push(...gA)}else if(z.status==="rejected"){const{code:X,message:gA}=z.reason||{};O={errorCode:X,message:gA}}}),{data:G,error:O}})}_isCustomFieldChanged(B=[],M=[]){if(!C(M)||M.length===0)return!1;if(!C(B)||B.length===0)return!0;const G=new Map(B.map(O=>[O.key,O.value]));return M.some(O=>G.get(O.key)!==O.value)}_mergeProfileCustomField(B=[],M=[]){const G=C(B)?B.map(O=>Object.assign({},O)):[];return C(M)&&M.length!==0&&M.forEach(({key:O,value:z})=>{const X=G.find(gA=>gA.key===O);X?X.value=z:G.push({key:O,value:z})}),G}_reset(){ia.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const au=new Map,HE=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let p=0,B=HE.length;p>(-2*z&6)):0)O="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(O);try{return decodeURIComponent(escape(M))}catch(G){return console.warn(G),""}}const{isEmpty:gu}=ve.utils,{generateProtocolData:Vt}=ve.common;function Ku(p){return mA(this,void 0,void 0,function*(){const B="im_open_status.ws_get_user_status",M=Vt({servcmd:B,data:{To_Account:p}}),G=`${M.head.seq}${B}`,O=yield ve.channel.sendPacket(M,{requestId:G});if(O)return function(z){const{ErrorCode:X,ErrorInfo:gA,ErrorList:DA=[],UserStatusList:GA=[]}=z,KA=GA.map(Qe=>{const{To_Account:At,Status:lt,CustomStatus:dt,Detail:xt=[]}=Qe;return{userID:At,statusType:lt,customStatus:jr(dt),onlineDevices:ju(xt)}}),re=DA.map(Qe=>{const{To_Account:At,Invalid_Account:lt,ErrorCode:dt,ErrorInfo:xt}=Qe;return{userID:gu(lt)?At:lt,code:dt,message:xt}});return{errorCode:X,errorInfo:gA,successUserList:KA,failureUserList:re}}(O)})}function ju(p){const B=[];return p?.forEach(M=>{const{Platform:G,Status:O}=M;O==="Online"&&B.push(G)}),B}class SC{constructor(){this._customStatus=""}init(){const{notificationCenter:B}=ve;ss.getInstance().registerApi({apiName:"getUserStatus",context:this}),ss.getInstance().registerApi({apiName:"setSelfStatus",context:this}),ss.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),ss.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),us.getInstance().registerWorkflowStep(dr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,jt.USER_STATUS_UPDATE,this._onReOnline,this),B.subscribeInnerEvent(Ci.MESSAGE_PUSH,B.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),B.subscribeInnerEvent(Ci.LOGOUT,this._reset,this),B.subscribeInnerEvent(Ci.DESTROY,this._dispose,this)}setSelfStatus(B){return mA(this,void 0,void 0,function*(){const M=$s(),{customStatus:G}=B;try{return yield function(O){return mA(this,void 0,void 0,function*(){const z="im_open_status.ws_set_custom_status",X=Vt({servcmd:z,data:{CustomStatus:O}}),gA=`${X.head.seq}${z}`,DA=yield ve.channel.sendPacket(X,{requestId:gA});if(DA){const{ErrorCode:GA,ErrorInfo:KA}=DA;return{errorCode:GA,errorInfo:KA}}})}(G),this._customStatus=G,{code:0,data:{userID:M,statusType:gc,customStatus:G},successLog:{message:`customStatus: ${G}`}}}catch(O){const{errorCode:z,errorInfo:X}=O;throw new dn({functionName:"setSelfStatus",code:z,message:X})}})}getUserStatus(B){return mA(this,void 0,void 0,function*(){const{userIDList:M=[]}=B;if(this._isOnlyMeInArray(M))return this._getMyStatus();const G=yield this._getUserStatus(M);return Object.assign(Object.assign({},G),{successLog:{message:`userIDList length: ${M.length}`}})})}setCustomStatus(B){const M=jr(B);this._customStatus=M}subscribeUserStatus(B){return mA(this,void 0,void 0,function*(){try{const{userIDList:M=[]}=B;this._checkBusinessCapabilityBits("subscribeUserStatus");const G=this._getMaxUserCount("subscribe"),O=this._sliceUserIDList(M,G),z=yield function(gA){return mA(this,void 0,void 0,function*(){const{channel:DA}=ve,GA="im_open_status.ws_status_subscribe",KA=Vt({servcmd:GA,data:{To_Account:gA}}),re=`${KA.head.seq}${GA}`;return yield DA.sendPacket(KA,{requestId:re})})}(O),X=this._parseResponse(z);return{code:0,data:{failureUserList:X},successLog:{message:`userID length:${M.length} failCount: ${X.length}`}}}catch(M){const{errorCode:G}=M;throw new dn({functionName:"subscribeUserStatus",code:G})}})}unsubscribeUserStatus(B){return mA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:M=[]}=B,G=this._getMaxUserCount("unsubscribe"),O=this._sliceUserIDList(M,G),z=yield function(gA){return mA(this,void 0,void 0,function*(){const{channel:DA}=ve,GA="im_open_status.ws_status_unsubscribe";let KA={};KA=gA.length===0?{UnsubscribeAll:1}:{To_Account:gA};const re=Vt({servcmd:GA,data:KA}),Qe=`${re.head.seq}${GA}`;return yield DA.sendPacket(re,{requestId:Qe})})}(O),X=this._parseResponse(z);return{code:0,data:{failureUserList:X},successLog:{message:`userID length:${M.length} failCount: ${X.length}`}}}catch(M){const{errorCode:G}=M;throw new dn({functionName:"unsubscribeUserStatus",code:G})}})}_onUserStatusUpdate(B){const{UserStatusList:M=[]}=B||{},G=M.map(O=>{const{To_Account:z,Status:X,CustomStatus:gA,Platform:DA}=O,GA={userID:z,statusType:X,customStatus:jr(gA)};return DA&&(GA.onlineDevices=DA),GA});this._emitUserStatusUpdatedEvent(G)}_onReOnline(B){const M=jr(B.data.customStatus);if(this._customStatus===M)return;this._customStatus=M;const G={userID:$s(),statusType:gc,customStatus:M};this._emitUserStatusUpdatedEvent(G)}_emitUserStatusUpdatedEvent(B){ve.notificationCenter.emitOuterEvent(Ts.USER_STATUS_UPDATED,{name:Ts.USER_STATUS_UPDATED,data:B})}_sliceUserIDList(B,M){return B.slice(0,M)}_parseResponse(B){const{ErrorList:M=[]}=B;return M.map(G=>{const{To_Account:O,Invalid_Account:z,ErrorCode:X,ErrorInfo:gA}=G;return{userID:ve.utils.isEmpty(z)?O:z,code:X,message:gA}})}_checkBusinessCapabilityBits(B){if(!ve.store.get("commercialConfig").get(Nr))throw new dn({functionName:B,code:Po.NO_USE,replacement1:B})}_getMaxUserCount(B){const M=ve.store.get("cloudConfig")||{},G={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}},{key:O,default:z}=G[B],X=M[O]||z;return parseInt(X,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:$s(),statusType:gc,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(B){return mA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const M=this._getMaxUserCount("query"),G=this._sliceUserIDList(B,M),O=yield Ku(G),{successUserList:z,failureUserList:X}=O||{};return{code:0,data:{successUserList:z,failureUserList:X}}}catch(M){const{errorCode:G}=M;throw new dn({functionName:"getUserStatus",code:G})}})}_isOnlyMeInArray(B){const M=$s();return B.length===1&&B.indexOf(M)>-1}_dispose(){const{notificationCenter:B}=ve;B.unSubscribeInnerEvent(Ci.MESSAGE_PUSH,B.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),B.unSubscribeInnerEvent(Ci.DESTROY,this._dispose,this),B.unSubscribeInnerEvent(Ci.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const K={getUserProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},updateMyProfile:{nick:{required:!1,rules:["string"],allowEmpty:!0},avatar:{required:!1,rules:["string"],allowEmpty:!0},gender:{required:!1,rules:["string"],allowEmpty:!0},selfSignature:{required:!1,rules:["string"],allowEmpty:!0},allowType:{required:!1,rules:["string"],allowEmpty:!0},birthday:{required:!1,rules:["number"],allowEmpty:!1},language:{required:!1,rules:["string"],allowEmpty:!0},messageSettings:{required:!1,rules:["string"],allowEmpty:!0},adminForbidType:{required:!1,rules:["string"],allowEmpty:!0},level:{required:!1,rules:["number"],allowEmpty:!1},role:{required:!1,rules:["number"],allowEmpty:!0},profileCustomField:{required:!1,rules:["array"],allowEmpty:!0,customValidator:function(p){for(const B of p){if(typeof B!="object")return"Each item in profileCustomField must be an object";if(typeof B?.key!="string")return"Each item.key in profileCustomField must be a string";if(!B?.key.startsWith(dg))return'Each item.key in profileCustomField must start with "Tag_Profile_Custom"'}return!0}}},setSelfStatus:{customStatus:{required:!0,rules:["string"],allowEmpty:!0}},getUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!1,rules:["array"],allowEmpty:!0}}},U={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class sA{constructor(){this.userProfile=new VE,this.userStatus=new SC,this.userProfile.init(),this.userStatus.init(),Gc({auth:U,params:K})}}function k(p){const B=[];if(!c(p))return B;const M=p.length;if(M===0)return B;for(let G=M-1;G>=0;G--)p[G]==="1"&&B.push(2**(M-G-1));return B}var x,iA,uA;(function(p){p.NOT_START="notStart",p.PENDING="pending",p.RESOLVED="resolved",p.REJECTED="rejected"})(x||(x={})),function(p){p[p.C2C=1]="C2C",p[p.GROUP=2]="GROUP"}(iA||(iA={})),function(p){p[p.C2C=8]="C2C",p[p.GROUP=2]="GROUP"}(uA||(uA={}));class _A{constructor(){this._name="SyncConversationHandler",this._pagingStatus=x.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:B}=ve;us.getInstance().registerWorkflowStep(dr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,jt.CONVERSATION_RECOVER,this._syncConversationList,this),us.getInstance().registerWorkflowStep(dr.SYNC_SERVER_INFO_AFTER_LOGIN,jt.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),B.subscribeInnerEvent(Ci.LOGOUT,this._reset,this),B.subscribeInnerEvent(Ci.DESTROY,this._dispose,this),ve.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===x.RESOLVED}_syncConversationListAfterLogin(){return mA(this,void 0,void 0,function*(){return this._pagingStatus=x.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return mA(this,void 0,void 0,function*(){const{ssoLog:B,utils:{safeStringify:M}}=ve;B.debug("_syncConversationList","start");try{const G=yield this._pagingGetConversationList(!0);this._pagingStatus=x.RESOLVED;const{conversationList:O=[]}=G||{};return B.info("_syncConversationList",`success count:${O.length}`),G}catch(G){const O=new dn(G);B.error("_syncConversationList",`fail ${M(G)}`,{error:O})}})}_pagingGetConversationList(B){return mA(this,void 0,void 0,function*(){try{const M=[];this._pagingStatus=x.PENDING;const G=yield function(re){return mA(this,void 0,void 0,function*(){const{fromAccount:Qe,pagingTimeStamp:At,pagingStartIndex:lt,pagingPinnedTimeStamp:dt,pagingPinnedStartIndex:xt}=re;return ic({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:Qe,StartIndex:lt,TimeStamp:At,TopStartIndex:xt,TopTimeStamp:dt}})})}({fromAccount:$s(),pagingTimeStamp:B?this._pagingTimeStamp:0,pagingStartIndex:B?this._pagingStartIndex:0,pagingPinnedTimeStamp:B?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:B?this._pagingPinnedStartIndex:0}),{CompleteFlag:O,SessionItem:z=[],TimeStamp:X,StartIndex:gA,TopTimeStamp:DA,TopStartIndex:GA}=G||{};let KA=[];if(O===1&&(this._pagingStatus=x.RESOLVED),z.length>0&&(KA=this._getConversationOptions(z),M.push(...KA)),ve.notificationCenter.emitInnerEvent(Ci.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:KA}),this._pagingTimeStamp=X,this._pagingStartIndex=gA,this._pagingPinnedTimeStamp=DA,this._pagingPinnedStartIndex=GA,O!==1){const{conversationList:re}=yield this._pagingGetConversationList(B);M.push(...re)}return{conversationList:M}}catch(M){throw M}})}_getConversationOptions(B){const{utils:{isUndefined:M}}=ve,G=this._convertConversationKey(B);return this._filterValidConversations(G).map(O=>(M(O.lastMsg)&&(O.lastMsg={elements:[]}),O.type===iA.C2C?this._assembleC2COption(O):this._assembleGroupOption(O)))}_filterValidConversations(B){return B.filter(({type:M,userID:G})=>M===iA.C2C&&!function(O){let z;return O.startsWith(Sn.CONV_C2C)&&(z=O.replace(Sn.CONV_C2C,"")),z==="@TLS#ERROR"||z==="@TLS#NOT_FOUND"}(G)||M===2)}_assembleC2COption(B){var M,G,O,z,X,gA,DA,GA;const KA=this._createUserprofile(B);return{conversationID:`${Sn.CONV_C2C}${B.userID}`,type:Sn.CONV_C2C,lastMessage:{lastTime:B.time,lastSequence:B.sequence,fromAccount:B.lastC2CMsgFromAccount,type:!((M=B.lastMsg)===null||M===void 0)&&M.elements[0]?(G=B.lastMsg)===null||G===void 0?void 0:G.elements[0].type:null,payload:!((O=B.lastMsg)===null||O===void 0)&&O.elements[0]?this._amendLayersOverLimitProp(B.lastMsg.elements[0].content):null,cloudCustomData:((gA=(X=(z=B.lastMsg)===null||z===void 0?void 0:z.elements)===null||X===void 0?void 0:X[0])===null||gA===void 0?void 0:gA.cloudCustomData)||"",isRevoked:B.lastMessageFlag===uA.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(B),revoker:((GA=(DA=B.lastMsg)===null||DA===void 0?void 0:DA.revokerInfo)===null||GA===void 0?void 0:GA.revoker)||null},unreadCount:0,userProfile:KA,peerReadTime:B.peerReadTime,isPinned:B.isPinned===1,customData:B.customMark||"",markList:k(B.standardMark),conversationGroupList:[],remark:B.friendRemark||"",messageRemindType:this._transMsgRemindType(B.messageRemindType)}}_createUserprofile(B){var M;const{userID:G,nick:O,peerAvatar:z}=B,X=[{tag:"Tag_Profile_IM_Nick",value:O},{tag:"Tag_Profile_IM_Image",value:z}];return(M=ve.user.userProfile)===null||M===void 0?void 0:M.createProfile(G,X)}_computeIsPeerRead(B){const M=$s(),{lastC2CMsgFromAccount:G,time:O,c2cPeerReadTime:z}=B;return G===M&&O<=z}_assembleGroupOption(B){var M,G,O,z,X;return{conversationID:`${Sn.CONV_GROUP}${B.groupID}`,type:Sn.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:B.time,lastSequence:B.sequence,fromAccount:B.msgGroupFromAccount},this._patchTypeAndPayload(B)),{cloudCustomData:((O=(G=(M=B.lastMsg)===null||M===void 0?void 0:M.elements)===null||G===void 0?void 0:G[0])===null||O===void 0?void 0:O.cloudCustomData)||"",isRevoked:B.lastMessageFlag===uA.GROUP,onlineOnlyFlag:!1,nick:B.msgGroupFromNickName||"",nameCard:B.msgGroupFromCardName||"",revoker:((X=(z=B.lastMsg)===null||z===void 0?void 0:z.revokerInfo)===null||X===void 0?void 0:X.revoker)||null}),groupProfile:{groupID:B.groupID,name:B.groupNick,avatar:B.groupImage,type:B.groupType,nextMessageSeq:B.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(B),peerReadTime:0,isPinned:B.isPinned===1,version:0,customData:B.customMark||"",markList:k(B.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(B.messageRemindType),subType:B.groupType}}_convertConversationKey(B){return B.map(M=>({type:M.Type,userID:M.To_Account,nick:M.C2cNick,peerAvatar:M.C2cImage,time:M.MsgTimeStamp,sequence:M.MsgSeq,lastC2CMsgFromAccount:M.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(M.LastMsg),lastMessageFlag:M.LastMsgFlags,c2cPeerReadTime:M.C2cPeerReadTime,peerReadTime:M.C2cPeerReadTime,friendRemark:M.C2cRemark,isPinned:M.TopFlags,standardMark:M.StandardMark,customMark:M.CustomMark,messageRemindType:M.MsgRecvOption,groupID:M.ToAccount,groupNick:M.GroupNick,groupImage:M.GroupImage,groupType:M.GroupType,nextMessageSeq:M.GroupNextMsgSeq,msgGroupFromAccount:M.MsgGroupFrom_Account,msgGroupFromNickName:M.MsgGroupFromNickName,msgGroupFromCardName:M.MsgGroupFromCardName,unreadCount:M.UnreadMsgCount,noUnreadCount:M.GroupIgnoredUnreadSeqCount}))}_convertLastMsgKey(B){var M,G,O;const{utils:{isEmpty:z}}=ve;if(z(B))return null;let X="",gA=null;if(!z(B.GroupTips)){const{From_Account:DA,GroupName:GA}=((M=B.GroupTips)===null||M===void 0?void 0:M.GroupInfo)||{};X=Sn.MSG_GRP_TIP,gA=Object.assign(Object.assign({},this._parseContent(X,B.GroupTips.MsgBody)),{groupProfile:{from:DA,groupName:GA}})}return B.MsgBody&&(X=(G=B.MsgBody[0])===null||G===void 0?void 0:G.MsgType,gA=this._parseContent(X,B.MsgBody[0])),{event:B.Event,elements:[{type:X,content:gA,cloudCustomData:B.CloudCustomData}],revokerInfo:{revoker:(O=B.RevokerInfo)===null||O===void 0?void 0:O.Revoker_Account}}}_parseContent(B,M){var G;if(!M)return M;const O=ve.message.messageFactory.getElementClass(B);return O?(G=O.parseServerPushElement(M))===null||G===void 0?void 0:G.content:M}_amendLayersOverLimitProp(B){const{LayersOverLimit:M}=B;return vo(B,["LayersOverLimit"]).layersOverLimit=M===1,B}_transMsgRemindType(B){let M="";return B===0?M=Sn.MSG_REMIND_ACPT_AND_NOTE:B===1?M=Sn.MSG_REMIND_DISCARD:B===2?M=Sn.MSG_REMIND_ACPT_NOT_NOTE:B===3&&(M=Sn.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),M}_patchTypeAndPayload(B){var M;const{utils:{isUndefined:G}}=ve,{event:O,elements:z=[]}=B.lastMsg||{};return G(O)?{type:z[0]?z[0].type:null,payload:z[0]?this._amendLayersOverLimitProp(z[0].content):null}:{type:Sn.MSG_GRP_TIP,payload:((M=z?.[0])===null||M===void 0?void 0:M.content)||{}}}_computeGroupUnreadCount(B){const{unreadCount:M=0,noUnreadCount:G=0}=B,O=M-G;return O>0?O:0}_reset(){this._pagingStatus=x.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:B}=ve;B.unSubscribeInnerEvent(Ci.LOGOUT,this._reset,this),B.unSubscribeInnerEvent(Ci.DESTROY,this._dispose,this)}}class ie{constructor(){this.syncConversationHandler=new _A,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Aa}`);var ye={create:function(p){var B,M;const{SDKAppID:G,testEnv:O=!1,devMode:z=!1,unlimitedAVChatRoom:X=!1,scene:gA="",oversea:DA=!1,instance:GA,disableIndependentDomain:KA=!1,proxyServer:re=""}=p;let Qe=G;if(!function(lt){if(typeof lt=="number")return!0;const dt=Number(lt);return!Number.isNaN(dt)}(Qe))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(Qe=Number(Qe),Pn.has(Qe))return Pn.get(Qe);let At=null;if(GA)At=GA,At._workflowManager&&us.setInstance(At._workflowManager),At._pluginManager&&At._pluginManager.installBuiltInPlugin(yr),GA.isReady()&&((M=(B=us.getInstance()).executeWorkflow)===null||M===void 0||M.call(B,dr.SYNC_SERVER_INFO_AFTER_LOGIN));else{const lt=function(){function so(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${so()+so()}${so()}${so()}${so()}${so()}${so()}${so()}`}();ve.init({sdkAppId:Qe,instanceId:lt,testEnv:O,devMode:z,unlimitedAVChatRoom:X,disableIndependentDomain:KA,scene:gA,oversea:DA,sdkEdition:xu,version:Aa,proxyServer:re}),us.getInstance().init(),ve.message=new dl,ve.user=new sA,ve.login=new sc,ve.conversation=new ie,Jo.getInstance().installBuiltInPlugin(yr),At=ss.getInstance().exposeApiForClient(),At._workflowManager=us.getInstance(),At._pluginManager=Jo.getInstance();const{utils:{IS_WORKER_AVAILABLE:dt,USER_AGENT:xt,getPlatformType:Wt,isIOSWebView:Ki}}=ve,Eo=`instanceID:${lt} SDKAppID:${G} platform:${jA} host:${Wt()} isIOSWebView:${Ki} workerAvailable:${dt} UserAgent:${xt}`;ve.ssoLog.info("sdkConstruct",Eo)}return Pn.set(Qe,At),At},TSignaling:lo,EVENT:Ts,VERSION:Aa,TYPES:Sn};return ye})}(yY)),yY.exports}var YL={exports:{}},DY={exports:{}},TaA=DY.exports,TZ;function NaA(){return TZ||(TZ=1,function(e,i){(function(n,c){e.exports=c()})(TaA,function(){function n(A,t){return t.forEach(function(o){o&&typeof o!="string"&&!Array.isArray(o)&&Object.keys(o).forEach(function(a){if(a!=="default"&&!(a in A)){var l=Object.getOwnPropertyDescriptor(o,a);Object.defineProperty(A,a,l.get?l:{enumerable:!0,get:function(){return o[a]}})}})}),Object.freeze(A)}var c=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof Dg<"u"?Dg:typeof self<"u"?self:{};function I(A){return A&&A.__esModule&&Object.prototype.hasOwnProperty.call(A,"default")?A.default:A}var C=function(A){return A&&A.Math===Math&&A},m=C(typeof globalThis=="object"&&globalThis)||C(typeof window=="object"&&window)||C(typeof self=="object"&&self)||C(typeof c=="object"&&c)||C(typeof c=="object"&&c)||function(){return this}()||Function("return this")(),R={},_=function(A){try{return!!A()}catch{return!0}},T=!_(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),b=!_(function(){var A=function(){}.bind();return typeof A!="function"||A.hasOwnProperty("prototype")}),J=b,cA=Function.prototype.call,eA=J?cA.bind(cA):function(){return cA.apply(cA,arguments)},CA={},IA={}.propertyIsEnumerable,oA=Object.getOwnPropertyDescriptor,vA=oA&&!IA.call({1:2},1);CA.f=vA?function(A){var t=oA(this,A);return!!t&&t.enumerable}:IA;var qA,Ae,HA=function(A,t){return{enumerable:!(1&A),configurable:!(2&A),writable:!(4&A),value:t}},se=b,WA=Function.prototype,Ye=WA.call,We=se&&WA.bind.bind(Ye,Ye),Pe=se?We:function(A){return function(){return Ye.apply(A,arguments)}},we=Pe,et=we({}.toString),Xe=we("".slice),ae=function(A){return Xe(et(A),8,-1)},Je=_,pt=ae,$t=Object,Pt=Pe("".split),ii=Je(function(){return!$t("z").propertyIsEnumerable(0)})?function(A){return pt(A)==="String"?Pt(A,""):$t(A)}:$t,ki=function(A){return A==null},ao=ki,Ji=TypeError,Vi=function(A){if(ao(A))throw new Ji("Can't call method on "+A);return A},wn=ii,Fi=Vi,en=function(A){return wn(Fi(A))},Ro=typeof document=="object"&&document.all,oo=Ro===void 0&&Ro!==void 0?function(A){return typeof A=="function"||A===Ro}:function(A){return typeof A=="function"},Ai=oo,no=function(A){return typeof A=="object"?A!==null:Ai(A)},Ri=m,pn=oo,jA=function(A,t){return arguments.length<2?(o=Ri[A],pn(o)?o:void 0):Ri[A]&&Ri[A][t];var o},ue=Pe({}.isPrototypeOf),He=m.navigator,Lt=He&&He.userAgent,ct=Lt?String(Lt):"",Ct=m,ei=ct,Ht=Ct.process,Le=Ct.Deno,it=Ht&&Ht.versions||Le&&Le.version,Tt=it&&it.v8;Tt&&(Ae=(qA=Tt.split("."))[0]>0&&qA[0]<4?1:+(qA[0]+qA[1])),!Ae&&ei&&(!(qA=ei.match(/Edge\/(\d+)/))||qA[1]>=74)&&(qA=ei.match(/Chrome\/(\d+)/))&&(Ae=+qA[1]);var Gt=Ae,Hi=Gt,po=_,To=m.String,Zi=!!Object.getOwnPropertySymbols&&!po(function(){var A=Symbol("symbol detection");return!To(A)||!(Object(A)instanceof Symbol)||!Symbol.sham&&Hi&&Hi<41}),wo=Zi&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Cn=jA,an=oo,Vo=ue,jn=Object,vo=wo?function(A){return typeof A=="symbol"}:function(A){var t=Cn("Symbol");return an(t)&&Vo(t.prototype,jn(A))},mA=String,xs=function(A){try{return mA(A)}catch{return"Object"}},Zs=oo,mn=xs,Fr=TypeError,qi=function(A){if(Zs(A))return A;throw new Fr(mn(A)+" is not a function")},tn=qi,Ks=ki,_n=function(A,t){var o=A[t];return Ks(o)?void 0:tn(o)},Is=eA,qt=oo,$a=no,Ls=TypeError,Bs={exports:{}},Un=m,Ir=Object.defineProperty,Fn=function(A,t){try{Ir(Un,A,{value:t,configurable:!0,writable:!0})}catch{Un[A]=t}return t},rr=m,fo=Fn,es="__core-js_shared__",vc=Bs.exports=rr[es]||fo(es,{});(vc.versions||(vc.versions=[])).push({version:"3.47.0",mode:"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru), 2025 CoreJS Company (core-js.io)",license:"https://github.com/zloirock/core-js/blob/v3.47.0/LICENSE",source:"https://github.com/zloirock/core-js"});var ts=Bs.exports,ur=ts,On=function(A,t){return ur[A]||(ur[A]=t||{})},vg=Vi,yn=Object,ce=function(A){return yn(vg(A))},ot=ce,Zt=Pe({}.hasOwnProperty),Ho=Object.hasOwn||function(A,t){return Zt(ot(A),t)},Ba=Pe,WI=0,gn=Math.random(),ro=Ba(1.1.toString),Mc=function(A){return"Symbol("+(A===void 0?"":A)+")_"+ro(++WI+gn,36)},gg=On,Mg=Ho,Qa=Mc,Fo=Zi,Aa=wo,Uo=m.Symbol,Zc=gg("wks"),Xs=Aa?Uo.for||Uo:Uo&&Uo.withoutSetter||Qa,is=function(A){return Mg(Zc,A)||(Zc[A]=Fo&&Mg(Uo,A)?Uo[A]:Xs("Symbol."+A)),Zc[A]},Rg=eA,Rc=no,ws=vo,Fa=_n,Qs=function(A,t){var o,a;if(t==="string"&&qt(o=A.toString)&&!$a(a=Is(o,A))||qt(o=A.valueOf)&&!$a(a=Is(o,A))||t!=="string"&&qt(o=A.toString)&&!$a(a=Is(o,A)))return a;throw new Ls("Can't convert object to primitive value")},Tn=TypeError,pa=is("toPrimitive"),_s=function(A,t){if(!Rc(A)||ws(A))return A;var o,a=Fa(A,pa);if(a){if(t===void 0&&(t="default"),o=Rg(a,A,t),!Rc(o)||ws(o))return o;throw new Tn("Can't convert object to primitive value")}return t===void 0&&(t="number"),Qs(A,t)},Oa=_s,Ta=vo,$=function(A){var t=Oa(A,"string");return Ta(t)?t:t+""},j=no,RA=m.document,ZA=j(RA)&&j(RA.createElement),ne=function(A){return ZA?RA.createElement(A):{}},De=ne,Ke=!T&&!_(function(){return Object.defineProperty(De("div"),"a",{get:function(){return 7}}).a!==7}),qe=T,Et=eA,ft=CA,Nt=HA,Kt=en,di=$,Bt=Ho,Jt=Ke,$i=Object.getOwnPropertyDescriptor;R.f=qe?$i:function(A,t){if(A=Kt(A),t=di(t),Jt)try{return $i(A,t)}catch{}if(Bt(A,t))return Nt(!Et(ft.f,A,t),A[t])};var eo={},os=T&&_(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),Ti=no,on=String,wg=TypeError,Er=function(A){if(Ti(A))return A;throw new wg(on(A)+" is not an object")},Mr=T,js=Ke,Tl=os,ns=Er,uI=$,ec=TypeError,wc=Object.defineProperty,Tu=Object.getOwnPropertyDescriptor,Na="enumerable",Nl="configurable",ve="writable";eo.f=Mr?Tl?function(A,t,o){if(ns(A),t=uI(t),ns(o),typeof A=="function"&&t==="prototype"&&"value"in o&&ve in o&&!o[ve]){var a=Tu(A,t);a&&a[ve]&&(A[t]=o.value,o={configurable:Nl in o?o[Nl]:a[Nl],enumerable:Na in o?o[Na]:a[Na],writable:!1})}return wc(A,t,o)}:wc:function(A,t,o){if(ns(A),t=uI(t),ns(o),js)try{return wc(A,t,o)}catch{}if("get"in o||"set"in o)throw new ec("Accessors not supported");return"value"in o&&(A[t]=o.value),A};var Se=eo,_g=HA,cg=T?function(A,t,o){return Se.f(A,t,_g(1,o))}:function(A,t,o){return A[t]=o,A},Tg={exports:{}},Ts=T,Rr=Ho,Ci=Function.prototype,lo=Ts&&Object.getOwnPropertyDescriptor,Xc=Rr(Ci,"name"),tc={PROPER:Xc&&function(){}.name==="something",CONFIGURABLE:Xc&&(!Ts||Ts&&lo(Ci,"name").configurable)},Ng=oo,qr=ts,_c=Pe(Function.toString);Ng(qr.inspectSource)||(qr.inspectSource=function(A){return _c(A)});var $c,lg,Nu,ME=qr.inspectSource,Gg=oo,Pa=m.WeakMap,Tc=Gg(Pa)&&/native code/.test(String(Pa)),RE=Mc,xa=On("keys"),ga=function(A){return xa[A]||(xa[A]=RE(A))},bg={},EI=Tc,Sn=m,Po=no,ma=cg,dr=Ho,jt=ts,Xt=ga,kg=bg,dI="Object already initialized",Cr=Sn.TypeError,zI=Sn.WeakMap;if(EI||jt.state){var Ag=jt.state||(jt.state=new zI);Ag.get=Ag.get,Ag.has=Ag.has,Ag.set=Ag.set,$c=function(A,t){if(Ag.has(A))throw new Cr(dI);return t.facade=A,Ag.set(A,t),t},lg=function(A){return Ag.get(A)||{}},Nu=function(A){return Ag.has(A)}}else{var ca=Xt("state");kg[ca]=!0,$c=function(A,t){if(dr(A,ca))throw new Cr(dI);return t.facade=A,ma(A,ca,t),t},lg=function(A){return dr(A,ca)?A[ca]:{}},Nu=function(A){return dr(A,ca)}}var ps={set:$c,get:lg,has:Nu,enforce:function(A){return Nu(A)?lg(A):$c(A,{})},getterFor:function(A){return function(t){var o;if(!Po(t)||(o=lg(t)).type!==A)throw new Cr("Incompatible receiver, "+A+" required");return o}}},Ns=Pe,Gu=_,Lg=oo,Ya=Ho,Al=T,ZI=tc.CONFIGURABLE,wE=ME,CI=ps.enforce,bu=ps.get,Gl=String,Nc=Object.defineProperty,ku=Ns("".slice),Lu=Ns("".replace),bl=Ns([].join),dn=Al&&!Gu(function(){return Nc(function(){},"length",{value:8}).length!==8}),hn=String(String).split("String"),dd=Tg.exports=function(A,t,o){ku(Gl(t),0,7)==="Symbol("&&(t="["+Lu(Gl(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),o&&o.getter&&(t="get "+t),o&&o.setter&&(t="set "+t),(!Ya(A,"name")||ZI&&A.name!==t)&&(Al?Nc(A,"name",{value:t,configurable:!0}):A.name=t),dn&&o&&Ya(o,"arity")&&A.length!==o.arity&&Nc(A,"length",{value:o.arity});try{o&&Ya(o,"constructor")&&o.constructor?Al&&Nc(A,"prototype",{writable:!1}):A.prototype&&(A.prototype=void 0)}catch{}var a=CI(A);return Ya(a,"source")||(a.source=bl(hn,typeof t=="string"?t:"")),A};Function.prototype.toString=dd(function(){return Lg(this)&&bu(this).source||wE(this)},"toString");var hI=Tg.exports,BI=oo,_E=eo,Cd=hI,kl=Fn,wr=function(A,t,o,a){a||(a={});var l=a.enumerable,d=a.name!==void 0?a.name:t;if(BI(o)&&Cd(o,d,a),a.global)l?A[t]=o:kl(t,o);else{try{a.unsafe?A[t]&&(l=!0):delete A[t]}catch{}l?A[t]=o:_E.f(A,t,{value:o,enumerable:!1,configurable:!a.nonConfigurable,writable:!a.nonWritable})}return A},Gc={},el=Math.ceil,us=Math.floor,Pn=Math.trunc||function(A){var t=+A;return(t>0?us:el)(t)},fa=Pn,ea=function(A){var t=+A;return t!=t||t===0?0:fa(t)},tl=ea,hd=Math.max,ic=Math.min,Ig=function(A,t){var o=tl(A);return o<0?hd(o+t,0):ic(o,t)},TE=ea,oc=Math.min,$s=function(A){var t=TE(A);return t>0?oc(t,9007199254740991):0},ar=$s,Va=function(A){return ar(A.length)},Bd=en,EC=Ig,Uu=Va,XI=function(A){return function(t,o,a){var l=Bd(t),d=Uu(l);if(d===0)return!A&&-1;var h,y=EC(a,d);if(A&&o!=o){for(;d>y;)if((h=l[y++])!=h)return!0}else for(;d>y;y++)if((A||y in l)&&l[y]===o)return A||y||0;return!A&&-1}},il={includes:XI(!0),indexOf:XI(!1)},ol=Ho,$I=en,QI=il.indexOf,nl=bg,sl=Pe([].push),Ga=function(A,t){var o,a=$I(A),l=0,d=[];for(o in a)!ol(nl,o)&&ol(a,o)&&sl(d,o);for(;t.length>l;)ol(a,o=t[l++])&&(~QI(d,o)||sl(d,o));return d},Ug=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Nn=Ga,Ar=Ug.concat("length","prototype");Gc.f=Object.getOwnPropertyNames||function(A){return Nn(A,Ar)};var bc={};bc.f=Object.getOwnPropertySymbols;var Au=jA,eu=Gc,NE=bc,lh=Er,dC=Pe([].concat),Ih=Au("Reflect","ownKeys")||function(A){var t=eu.f(lh(A)),o=NE.f;return o?dC(t,o(A)):t},rl=Ho,Fg=Ih,Io=R,CC=eo,GE=function(A,t,o){for(var a=Fg(t),l=CC.f,d=Io.f,h=0;hh;)DI.f(A,o=l[h++],a[o]);return A};var Pg,rc=jA("document","documentElement"),yd=Er,FE=Fl,Oc=Ug,ou=bg,ho=rc,OE=ne,ig="prototype",nu="script",Yu=ga("IE_PROTO"),Pc=function(){},SI=function(A){return"<"+nu+">"+A+""},ll=function(A){A.write(SI("")),A.close();var t=A.parentWindow.Object;return A=null,t},Il=function(){try{Pg=new ActiveXObject("htmlfile")}catch{}Il=typeof document<"u"?document.domain&&Pg?ll(Pg):function(){var t,o=OE("iframe"),a="java"+nu+":";return o.style.display="none",ho.appendChild(o),o.src=String(a),(t=o.contentWindow.document).open(),t.write(SI("document.F=Object")),t.close(),t.F}():ll(Pg);for(var A=Oc.length;A--;)delete Il[ig][Oc[A]];return Il()};ou[Yu]=!0;var qa=Object.create||function(A,t){var o;return A!==null?(Pc[ig]=yd(A),o=new Pc,Pc[ig]=null,o[Yu]=A):o=Il(),t===void 0?o:FE.f(o,t)},PE=is,la=qa,Gs=eo.f,Or=PE("unscopables"),ul=Array.prototype;ul[Or]===void 0&&Gs(ul,Or,{configurable:!0,value:la(null)});var Yl=function(A){ul[Or][A]=!0},xc=il.includes,xE=Yl;Us({target:"Array",proto:!0,forced:_(function(){return!Array(1).includes()})},{includes:function(A){return xc(this,A,arguments.length>1?arguments[1]:void 0)}}),xE("includes");var Yc,Vu,yC,su={},dh=!_(function(){function A(){}return A.prototype.constructor=null,Object.getPrototypeOf(new A)!==A.prototype}),Hu=Ho,vI=oo,El=ce,DC=dh,Ia=ga("IE_PROTO"),ac=Object,Eg=ac.prototype,MI=DC?ac.getPrototypeOf:function(A){var t=El(A);if(Hu(t,Ia))return t[Ia];var o=t.constructor;return vI(o)&&t instanceof o?o.prototype:t instanceof ac?Eg:null},YE=_,Ju=oo,qu=no,RI=MI,dl=wr,Pr=is("iterator"),xr=!1;[].keys&&("next"in(yC=[].keys())?(Vu=RI(RI(yC)))!==Object.prototype&&(Yc=Vu):xr=!0);var dg=!qu(Yc)||YE(function(){var A={};return Yc[Pr].call(A)!==A});dg&&(Yc={}),Ju(Yc[Pr])||dl(Yc,Pr,function(){return this});var hr={IteratorPrototype:Yc,BUGGY_SAFARI_ITERATORS:xr},Nr=eo.f,gc=Ho,xg=is("toStringTag"),Ka=function(A,t,o){A&&!o&&(A=A.prototype),A&&!gc(A,xg)&&Nr(A,xg,{configurable:!0,value:t})},Vl=hr.IteratorPrototype,ya=qa,wI=HA,ru=Ka,Da=su,Cl=function(){return this},VE=function(A,t,o,a){var l=t+" Iterator";return A.prototype=ya(Vl,{next:wI(+!a,o)}),ru(A,l,!1),Da[l]=Cl,A},au=Pe,HE=qi,jr=no,gu=function(A){return jr(A)||A===null},Vt=String,Ku=TypeError,ju=function(A,t,o){try{return au(HE(Object.getOwnPropertyDescriptor(A,t)[o]))}catch{}},SC=no,K=Vi,U=function(A){if(gu(A))return A;throw new Ku("Can't set "+Vt(A)+" as a prototype")},sA=Object.setPrototypeOf||("__proto__"in{}?function(){var A,t=!1,o={};try{(A=ju(Object.prototype,"__proto__","set"))(o,[]),t=o instanceof Array}catch{}return function(a,l){return K(a),U(l),SC(a)&&(t?A(a,l):a.__proto__=l),a}}():void 0),k=Us,x=eA,iA=oo,uA=VE,_A=MI,ie=sA,ye=Ka,p=cg,B=wr,M=su,G=tc.PROPER,O=tc.CONFIGURABLE,z=hr.IteratorPrototype,X=hr.BUGGY_SAFARI_ITERATORS,gA=is("iterator"),DA="keys",GA="values",KA="entries",re=function(){return this},Qe=function(A,t,o,a,l,d,h){uA(o,t,a);var y,S,L,V=function(je){if(je===l&&oe)return oe;if(!X&&je&&je in hA)return hA[je];switch(je){case DA:case GA:case KA:return function(){return new o(this,je)}}return function(){return new o(this)}},H=t+" Iterator",lA=!1,hA=A.prototype,MA=hA[gA]||hA["@@iterator"]||l&&hA[l],oe=!X&&MA||V(l),fe=t==="Array"&&hA.entries||MA;if(fe&&(y=_A(fe.call(new A)))!==Object.prototype&&y.next&&(_A(y)!==z&&(ie?ie(y,z):iA(y[gA])||B(y,gA,re)),ye(y,H,!0)),G&&l===GA&&MA&&MA.name!==GA&&(O?p(hA,"name",GA):(lA=!0,oe=function(){return x(MA,this)})),l)if(S={values:V(GA),keys:d?oe:V(DA),entries:V(KA)},h)for(L in S)(X||lA||!(L in hA))&&B(hA,L,S[L]);else k({target:t,proto:!0,forced:X||lA},S);return hA[gA]!==oe&&B(hA,gA,oe,{name:l}),M[t]=oe,S},At=function(A,t){return{value:A,done:t}},lt=en,dt=Yl,xt=su,Wt=ps,Ki=eo.f,Eo=Qe,so=At,hi=T,qo="Array Iterator",cn=Wt.set,yi=Wt.getterFor(qo),to=Eo(Array,"Array",function(A,t){cn(this,{type:qo,target:lt(A),index:0,kind:t})},function(){var A=yi(this),t=A.target,o=A.index++;if(!t||o>=t.length)return A.target=null,so(void 0,!0);switch(A.kind){case"keys":return so(o,!1);case"values":return so(t[o],!1)}return so([o,t[o]],!1)},"values"),rs=xt.Arguments=xt.Array;if(dt("keys"),dt("values"),dt("entries"),hi&&rs.name!=="values")try{Ki(rs,"name",{value:"values"})}catch{}var be=qi,bt=ce,OA=ii,oi=Va,ms=TypeError,si="Reduce of empty array with no initial value",Dn=function(A){return function(t,o,a,l){var d=bt(t),h=OA(d),y=oi(d);if(be(o),y===0&&a<2)throw new ms(si);var S=A?y-1:0,L=A?-1:1;if(a<2)for(;;){if(S in h){l=h[S],S+=L;break}if(S+=L,A?S<0:y<=S)throw new ms(si)}for(;A?S>=0:y>S;S+=L)S in h&&(l=o(l,h[S],S,d));return l}},Ni={left:Dn(!1),right:Dn(!0)},yo=_,yt=function(A,t){var o=[][A];return!!o&&yo(function(){o.call(null,t||function(){return 1},1)})},St=m,Cg=ct,qn=ae,io=function(A){return Cg.slice(0,A.length)===A},Wr=io("Bun/")?"BUN":io("Cloudflare-Workers")?"CLOUDFLARE":io("Deno/")?"DENO":io("Node.js/")?"NODE":St.Bun&&typeof Bun.version=="string"?"BUN":St.Deno&&typeof Deno.version=="object"?"DENO":qn(St.process)==="process"?"NODE":St.window&&St.document?"BROWSER":"REST",cc=Wr==="NODE",In=Ni.left;Us({target:"Array",proto:!0,forced:!cc&&Gt>79&&Gt<83||!yt("reduce")},{reduce:function(A){var t=arguments.length;return In(this,A,t,t>1?arguments[1]:void 0)}});var ua=Ni.right;Us({target:"Array",proto:!0,forced:!cc&&Gt>79&&Gt<83||!yt("reduceRight")},{reduceRight:function(A){return ua(this,A,arguments.length,arguments.length>1?arguments[1]:void 0)}});var Sa=ae,oa=Array.isArray||function(A){return Sa(A)==="Array"},q=Us,QA=oa,yA=Pe([].reverse),NA=[1,2];q({target:"Array",proto:!0,forced:String(NA)===String(NA.reverse())},{reverse:function(){return QA(this)&&(this.length=this.length),yA(this)}});var ee=xs,Ne=TypeError,he=Pe([].slice),Ue=he,de=Math.floor,Ve=function(A,t){var o=A.length;if(o<8)for(var a,l,d=1;d0;)A[l]=A[--l];l!==d++&&(A[l]=a)}else for(var h=de(o/2),y=Ve(Ue(A,0,h),t),S=Ve(Ue(A,h),t),L=y.length,V=S.length,H=0,lA=0;H3)){if(Rm)return!0;if(gi)return gi<603;var A,t,o,a,l="";for(A=65;A<76;A++){switch(t=String.fromCharCode(A),A){case 66:case 69:case 70:case 72:o=3;break;case 68:case 71:o=4;break;default:o=2}for(a=0;a<47;a++)_o.push({k:t+a,v:o})}for(_o.sort(function(d,h){return h.v-d.v}),a=0;a<_o.length;a++)t=_o[a].k.charAt(0),l.charAt(l.length-1)!==t&&(l+=t);return l!=="DGBEFHACIJK"}});fn({target:"Array",proto:!0,forced:hg||!Hl||!Dd||!Vc},{sort:function(A){A!==void 0&&ai(A);var t=Yr(this);if(Vc)return A===void 0?Es(t):Es(t,A);var o,a,l=[],d=nn(t);for(a=0;atr(S)?1:-1}}(A)),o=nn(l),a=0;ao||S!=S?1/0*h:h*S},fD=Math.fround||function(A){return mD(A,11920928955078125e-23,34028234663852886e22,11754943508222875e-54)},jM=Array,_T=Math.abs,Sd=Math.pow,TT=Math.floor,yD=Math.log,NT=Math.LN2,DD={pack:function(A,t,o){var a,l,d,h=jM(o),y=8*o-t-1,S=(1<>1,V=t===23?Sd(2,-24)-Sd(2,-77):0,H=A<0||A===0&&1/A<0?1:0,lA=0;for((A=_T(A))!=A||A===1/0?(l=A!=A?1:0,a=S):(a=TT(yD(A)/NT),A*(d=Sd(2,-a))<1&&(a--,d*=2),(A+=a+L>=1?V/d:V*Sd(2,1-L))*d>=2&&(a++,d/=2),a+L>=S?(l=0,a=S):a+L>=1?(l=(A*d-1)*Sd(2,t),a+=L):(l=A*Sd(2,L-1)*Sd(2,t),a=0));t>=8;)h[lA++]=255&l,l/=256,t-=8;for(a=a<0;)h[lA++]=255&a,a/=256,y-=8;return h[lA-1]|=128*H,h},unpack:function(A,t){var o,a=A.length,l=8*a-t-1,d=(1<>1,y=l-7,S=a-1,L=A[S--],V=127&L;for(L>>=7;y>0;)V=256*V+A[S--],y-=8;for(o=V&(1<<-y)-1,V>>=-y,y+=t;y>0;)o=256*o+A[S--],y-=8;if(V===0)V=1-h;else{if(V===d)return o?NaN:L?-1/0:1/0;o+=Sd(2,t),V-=h}return(L?-1:1)*o*Sd(2,V-t)}},GT=ce,WM=Ig,bT=Va,zM=function(A){for(var t=GT(this),o=bT(t),a=arguments.length,l=WM(a>1?arguments[1]:void 0,o),d=a>2?arguments[2]:void 0,h=d===void 0?o:WM(d,o);h>l;)t[l++]=A;return t},kT=oo,LT=no,SD=sA,vD=function(A,t,o){var a,l;return SD&&kT(a=t.constructor)&&a!==o&<(l=a.prototype)&&l!==o.prototype&&SD(A,l),A},UQ=m,Gm=Pe,bm=T,vd=_r,UT=cg,FT=Og,km=cu,MD=_,Ch=TI,OT=ea,PT=$s,Lm=_m,ZM=fD,RD=DD,Um=MI,XM=sA,xT=zM,YT=he,$M=vD,Md=GE,Fm=Ka,Rd=ps,JE=tc.PROPER,Om=tc.CONFIGURABLE,vC="ArrayBuffer",hh="DataView",Zu="prototype",Wi="Wrong index",Pm=Rd.getterFor(vC),fs=Rd.getterFor(hh),AR=Rd.set,Xu=UQ[vC],as=Xu,Bh=as&&as[Zu],Jl=UQ[hh],Ic=Jl&&Jl[Zu],qE=Object.prototype,FQ=UQ.Array,EB=UQ.RangeError,VT=Gm(xT),HT=Gm([].reverse),OQ=RD.pack,PQ=RD.unpack,eR=function(A){return[255&A]},tR=function(A){return[255&A,A>>8&255]},wD=function(A){return[255&A,A>>8&255,A>>16&255,A>>24&255]},MC=function(A){return A[3]<<24|A[2]<<16|A[1]<<8|A[0]},dB=function(A){return OQ(ZM(A),23,4)},_D=function(A){return OQ(A,52,8)},xQ=function(A,t,o){FT(A[Zu],t,{configurable:!0,get:function(){return o(this)[t]}})},wd=function(A,t,o,a){var l=fs(A),d=Lm(o),h=!!a;if(d+t>l.byteLength)throw new EB(Wi);var y=l.bytes,S=d+l.byteOffset,L=YT(y,S,S+t);return h?L:HT(L)},_d=function(A,t,o,a,l,d){var h=fs(A),y=Lm(o),S=a(+l),L=!!d;if(y+t>h.byteLength)throw new EB(Wi);for(var V=h.bytes,H=y+h.byteOffset,lA=0;lA>24)},setUint8:function(A,t){TD(this,A,t<<24>>24)}},{unsafe:!0})}else Bh=(as=function(A){Ch(this,Bh);var t=Lm(A);AR(this,{type:vC,bytes:VT(FQ(t),0),byteLength:t}),bm||(this.byteLength=t,this.detached=!1)})[Zu],Ic=(Jl=function(A,t,o){Ch(this,Ic),Ch(A,Bh);var a=Pm(A),l=a.byteLength,d=OT(t);if(d<0||d>l)throw new EB("Wrong offset");if(d+(o=o===void 0?l-d:PT(o))>l)throw new EB("Wrong length");AR(this,{type:hh,buffer:A,byteLength:o,byteOffset:d,bytes:a.bytes}),bm||(this.buffer=A,this.byteLength=o,this.byteOffset=d)})[Zu],bm&&(xQ(as,"byteLength",Pm),xQ(Jl,"buffer",fs),xQ(Jl,"byteLength",fs),xQ(Jl,"byteOffset",fs)),km(Ic,{getInt8:function(A){return wd(this,1,A)[0]<<24>>24},getUint8:function(A){return wd(this,1,A)[0]},getInt16:function(A){var t=wd(this,2,A,arguments.length>1&&arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(A){var t=wd(this,2,A,arguments.length>1&&arguments[1]);return t[1]<<8|t[0]},getInt32:function(A){return MC(wd(this,4,A,arguments.length>1&&arguments[1]))},getUint32:function(A){return MC(wd(this,4,A,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(A){return PQ(wd(this,4,A,arguments.length>1&&arguments[1]),23)},getFloat64:function(A){return PQ(wd(this,8,A,arguments.length>1&&arguments[1]),52)},setInt8:function(A,t){_d(this,1,A,eR,t)},setUint8:function(A,t){_d(this,1,A,eR,t)},setInt16:function(A,t){_d(this,2,A,tR,t,arguments.length>2&&arguments[2])},setUint16:function(A,t){_d(this,2,A,tR,t,arguments.length>2&&arguments[2])},setInt32:function(A,t){_d(this,4,A,wD,t,arguments.length>2&&arguments[2])},setUint32:function(A,t){_d(this,4,A,wD,t,arguments.length>2&&arguments[2])},setFloat32:function(A,t){_d(this,4,A,dB,t,arguments.length>2&&arguments[2])},setFloat64:function(A,t){_d(this,8,A,_D,t,arguments.length>2&&arguments[2])}});Fm(as,vC),Fm(Jl,hh);var xm={ArrayBuffer:as,DataView:Jl},oR=jA,JT=Og,Ym=T,CB=is("species"),Vm=function(A){var t=oR(A);Ym&&t&&!t[CB]&&JT(t,CB,{configurable:!0,get:function(){return this}})},qT=Vm,ND="ArrayBuffer",GD=xm[ND];Us({global:!0,constructor:!0,forced:m[ND]!==GD},{ArrayBuffer:GD}),qT(ND);var VQ=ae,KE=Pe,$u=function(A){if(VQ(A)==="Function")return KE(A)},bD=Us,Qh=$u,Hm=_,nR=Er,HQ=Ig,sR=$s,kD=xm.ArrayBuffer,bs=xm.DataView,JQ=bs.prototype,Td=Qh(kD.prototype.slice),LD=Qh(JQ.getUint8),KT=Qh(JQ.setUint8);bD({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:Hm(function(){return!new kD(2).slice(1,void 0).byteLength})},{slice:function(A,t){if(Td&&t===void 0)return Td(nR(this),A);for(var o=nR(this).byteLength,a=HQ(A,o),l=HQ(t===void 0?o:t,o),d=new kD(sR(l-a)),h=new bs(this),y=new bs(d),S=0;ad;d++)if((y=je(A[d]))&&lS(Fd,y))return y;return new NC(!1)}a=EN(A,l)}for(S=lA?A.next:a.next;!(L=lN(S,a)).done;){try{y=je(L.value)}catch(_e){IS(a,"throw",_e)}if(typeof y=="object"&&y&&lS(Fd,y))return y}return new NC(!1)},ES=is("iterator"),dS=!1;try{var s=0,r={next:function(){return{done:!!s++}},return:function(){dS=!0}};r[ES]=function(){return this},Array.from(r,function(){throw 2})}catch{}var g=function(A,t){try{if(!t&&!dS)return!1}catch{return!1}var o=!1;try{var a={};a[ES]=function(){return{next:function(){return{done:o=!0}}}},A(a)}catch{}return o},u=wB,E=Nh.CONSTRUCTOR||!g(function(A){u.all(A).then(void 0,function(){})}),f=eA,D=qi,v=Zr,N=RB,P=uS;Us({target:"Promise",stat:!0,forced:E},{all:function(A){var t=this,o=v.f(t),a=o.resolve,l=o.reject,d=N(function(){var h=D(t.resolve),y=[],S=0,L=1;P(A,function(V){var H=S++,lA=!1;L++,f(h,t,V).then(function(hA){lA||(lA=!0,y[H]=hA,--L||a(y))},l)}),--L||a(y)});return d.error&&l(d.value),o.promise}});var W=Us,nA=Nh.CONSTRUCTOR,EA=wB,wA=jA,kA=oo,VA=wr,LA=EA&&EA.prototype;if(W({target:"Promise",proto:!0,forced:nA,real:!0},{catch:function(A){return this.then(void 0,A)}}),kA(EA)){var SA=wA("Promise").prototype.catch;LA.catch!==SA&&VA(LA,"catch",SA,{unsafe:!0})}var PA=eA,zA=qi,Ee=Zr,Ie=RB,Li=uS;Us({target:"Promise",stat:!0,forced:E},{race:function(A){var t=this,o=Ee.f(t),a=o.reject,l=Ie(function(){var d=zA(t.resolve);Li(A,function(h){PA(d,t,h).then(o.resolve,a)})});return l.error&&a(l.value),o.promise}});var Ui=Zr;Us({target:"Promise",stat:!0,forced:Nh.CONSTRUCTOR},{reject:function(A){var t=Ui.f(this);return(0,t.reject)(A),t.promise}});var Yt=Er,Oi=no,Bn=Zr,Re=function(A,t){if(Yt(A),Oi(t)&&t.constructor===A)return t;var o=Bn.f(A);return(0,o.resolve)(t),o.promise},Mt=Us,FA=Nh.CONSTRUCTOR,ci=Re;jA("Promise"),Mt({target:"Promise",stat:!0,forced:FA},{resolve:function(A){return ci(this,A)}});var xn=Us,Pi=wB,Vr=_,ji=jA,Br=oo,Ut=cR,Ft=Re,oE=wr,hs=Pi&&Pi.prototype;if(xn({target:"Promise",proto:!0,real:!0,forced:!!Pi&&Vr(function(){hs.finally.call({then:function(){}},function(){})})},{finally:function(A){var t=Ut(this,ji("Promise")),o=Br(A);return this.then(o?function(a){return Ft(t,A()).then(function(){return a})}:A,o?function(a){return Ft(t,A()).then(function(){throw a})}:A)}}),Br(Pi)){var Do=ji("Promise").prototype.finally;hs.finally!==Do&&oE(hs,"finally",Do,{unsafe:!0})}var Bl=no,GC=ae,Gr=is("match"),Hg=function(A){var t;return Bl(A)&&((t=A[Gr])!==void 0?!!t:GC(A)==="RegExp")},bI=_,Ec=m.RegExp,uf=!bI(function(){var A=!0;try{Ec(".","d")}catch{A=!1}var t={},o="",a=A?"dgimsy":"gimsy",l=function(y,S){Object.defineProperty(t,y,{get:function(){return o+=S,!0}})},d={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var h in A&&(d.hasIndices="d"),d)l(h,d[h]);return Object.getOwnPropertyDescriptor(Ec.prototype,"flags").get.call(t)!==a||o!==a}),Ep=Er,ja=function(){var A=Ep(this),t="";return A.hasIndices&&(t+="d"),A.global&&(t+="g"),A.ignoreCase&&(t+="i"),A.multiline&&(t+="m"),A.dotAll&&(t+="s"),A.unicode&&(t+="u"),A.unicodeSets&&(t+="v"),A.sticky&&(t+="y"),t},Kl=eA,kI=Ho,nE=ue,Jg={correct:uf},Bg=ja,CS=RegExp.prototype,JR=Jg.correct?function(A){return A.flags}:function(A){return Jg.correct||!nE(CS,A)||kI(A,"flags")?A.flags:Kl(Bg,A)},qR=_,KR=m.RegExp,CN=qR(function(){var A=KR("a","y");return A.lastIndex=2,A.exec("abcd")!==null}),nH=CN||qR(function(){return!KR("a","y").sticky}),hF=CN||qR(function(){var A=KR("^r","gy");return A.lastIndex=2,A.exec("str")!==null}),dp={BROKEN_CARET:hF,MISSED_STICKY:nH,UNSUPPORTED_Y:CN},hN=eo.f,BN=_,QN=m.RegExp,pN=BN(function(){var A=QN(".","s");return!(A.dotAll&&A.test(` -`)&&A.flags==="s")}),BF=_,sH=m.RegExp,QF=BF(function(){var A=sH("(?b)","g");return A.exec("b").groups.a!=="b"||"b".replace(A,"$c")!=="bc"}),Ef=T,mN=m,df=Pe,fN=Tr,rH=vD,aH=cg,gH=qa,cH=Gc.f,jR=ue,pF=Hg,yN=yr,mF=JR,hS=dp,DN=function(A,t,o){o in A||hN(A,o,{configurable:!0,get:function(){return t[o]},set:function(a){t[o]=a}})},WR=wr,zR=_,lH=Ho,SN=ps.enforce,ZR=Vm,fF=pN,Cf=QF,IH=is("match"),kB=mN.RegExp,hf=kB.prototype,uH=mN.SyntaxError,yF=df(hf.exec),Bf=df("".charAt),DF=df("".replace),vN=df("".indexOf),MN=df("".slice),EH=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,sE=/a/g,LB=/a/g,SF=new kB(sE)!==sE,vF=hS.MISSED_STICKY,dH=hS.UNSUPPORTED_Y,RN=Ef&&(!SF||vF||fF||Cf||zR(function(){return LB[IH]=!1,kB(sE)!==sE||kB(LB)===LB||String(kB(sE,"i"))!=="/a/i"}));if(fN("RegExp",RN)){for(var UB=function(A,t){var o,a,l,d,h,y,S=jR(hf,this),L=pF(A),V=t===void 0,H=[],lA=A;if(!S&&L&&V&&A.constructor===UB)return A;if((L||jR(hf,A))&&(A=A.source,V&&(t=mF(lA))),A=A===void 0?"":yN(A),t=t===void 0?"":yN(t),lA=A,fF&&"dotAll"in sE&&(a=!!t&&vN(t,"s")>-1)&&(t=DF(t,/s/g,"")),o=t,vF&&"sticky"in sE&&(l=!!t&&vN(t,"y")>-1)&&dH&&(t=DF(t,/y/g,"")),Cf&&(d=function(hA){for(var MA,oe=hA.length,fe=0,je="",_e=[],vi=gH(null),Fe=!1,Dt=!1,pi=0,Mi="";fe<=oe;fe++){if((MA=Bf(hA,fe))==="\\")MA+=Bf(hA,++fe);else if(MA==="]")Fe=!1;else if(!Fe)switch(!0){case MA==="[":Fe=!0;break;case MA==="(":if(je+=MA,MN(hA,fe+1,fe+3)==="?:")continue;yF(EH,MN(hA,fe+1))&&(fe+=2,Dt=!0),pi++;continue;case(MA===">"&&Dt):if(Mi===""||lH(vi,Mi))throw new uH("Invalid capture group name");vi[Mi]=!0,_e[_e.length]=[Mi,pi],Dt=!1,Mi="";continue}Dt?Mi+=MA:je+=MA}return[je,_e]}(A),A=d[0],H=d[1]),h=rH(kB(A,t),S?this:hf,UB),(a||l||H.length)&&(y=SN(h),a&&(y.dotAll=!0,y.raw=UB(function(hA){for(var MA,oe=hA.length,fe=0,je="",_e=!1;fe<=oe;fe++)(MA=Bf(hA,fe))!=="\\"?_e||MA!=="."?(MA==="["?_e=!0:MA==="]"&&(_e=!1),je+=MA):je+="[\\s\\S]":je+=MA+Bf(hA,++fe);return je}(A),o)),l&&(y.sticky=!0),H.length&&(y.groups=H)),A!==lA)try{aH(h,"source",lA===""?"(?:)":lA)}catch{}return h},wN=cH(kB),_N=0;wN.length>_N;)DN(UB,kB,wN[_N++]);hf.constructor=UB,UB.prototype=hf,WR(mN,"RegExp",UB,{constructor:!0})}ZR("RegExp");var Qf=eA,Cp=Pe,FB=yr,CH=ja,pf=dp,MF=qa,RF=ps.get,hH=pN,BH=QF,QH=On("native-string-replace",String.prototype.replace),hp=RegExp.prototype.exec,TN=hp,pH=Cp("".charAt),mH=Cp("".indexOf),wF=Cp("".replace),BS=Cp("".slice),NN=function(){var A=/a/,t=/b*/g;return Qf(hp,A,"a"),Qf(hp,t,"a"),A.lastIndex!==0||t.lastIndex!==0}(),_F=pf.BROKEN_CARET,GN=/()??/.exec("")[1]!==void 0;(NN||GN||_F||hH||BH)&&(TN=function(A){var t,o,a,l,d,h,y,S=this,L=RF(S),V=FB(A),H=L.raw;if(H)return H.lastIndex=S.lastIndex,t=Qf(TN,H,V),S.lastIndex=H.lastIndex,t;var lA=L.groups,hA=_F&&S.sticky,MA=Qf(CH,S),oe=S.source,fe=0,je=V;if(hA&&(MA=wF(MA,"y",""),mH(MA,"g")===-1&&(MA+="g"),je=BS(V,S.lastIndex),S.lastIndex>0&&(!S.multiline||S.multiline&&pH(V,S.lastIndex-1)!==` -`)&&(oe="(?: "+oe+")",je=" "+je,fe++),o=new RegExp("^(?:"+oe+")",MA)),GN&&(o=new RegExp("^"+oe+"$(?!\\s)",MA)),NN&&(a=S.lastIndex),l=Qf(hp,hA?o:S,je),hA?l?(l.input=BS(l.input,fe),l[0]=BS(l[0],fe),l.index=S.lastIndex,S.lastIndex+=l[0].length):S.lastIndex=0:NN&&l&&(S.lastIndex=S.global?l.index+l[0].length:a),GN&&l&&l.length>1&&Qf(QH,l[0],o,function(){for(d=1;d0;(a>>>=1)&&(t+=t))1&a&&(o+=t);return o},mf=Vi,ff=GF(yH),ew=GF("".slice),bF=Math.ceil,bN=function(A){return function(t,o,a){var l,d,h=Aw(mf(t)),y=fH(o),S=h.length,L=a===void 0?" ":Aw(a);return y<=S||L===""?h:((d=ff(L,bF((l=y-S)/L.length))).length>l&&(d=ew(d,0,l)),A?h+d:d+h)}},kN={start:bN(!1)},LN=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(ct),DH=kN.start;Us({target:"String",proto:!0,forced:LN},{padStart:function(A){return DH(this,A,arguments.length>1?arguments[1]:void 0)}});var kF=eA,UN=wr,LF=QS,FN=_,ON=is,SH=ON("species"),UF=RegExp.prototype,tw=Pe,vH=ea,yf=yr,Df=Vi,PN=tw("".charAt),FF=tw("".charCodeAt),MH=tw("".slice),OF=function(A){return function(t,o){var a,l,d=yf(Df(t)),h=vH(o),y=d.length;return h<0||h>=y?A?"":void 0:(a=FF(d,h))<55296||a>56319||h+1===y||(l=FF(d,h+1))<56320||l>57343?A?PN(d,h):a:A?MH(d,h,h+2):l-56320+(a-55296<<10)+65536}},iw={codeAt:OF(!1),charAt:OF(!0)},RH=iw.charAt,ow=Pe,wH=ce,_H=Math.floor,xN=ow("".charAt),YN=ow("".replace),VN=ow("".slice),TH=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,NH=/\$([$&'`]|\d{1,2})/g,PF=function(A,t,o,a,l,d){var h=o+A.length,y=a.length,S=NH;return l!==void 0&&(l=wH(l),S=TH),YN(d,S,function(L,V){var H;switch(xN(V,0)){case"$":return"$";case"&":return A;case"`":return VN(t,0,o);case"'":return VN(t,h);case"<":H=l[VN(V,1,-1)];break;default:var lA=+V;if(lA===0)return L;if(lA>y){var hA=_H(lA/10);return hA===0?L:hA<=y?a[hA-1]===void 0?xN(V,1):a[hA-1]+xN(V,1):L}H=a[lA-1]}return H===void 0?"":H})},xF=eA,GH=Er,YF=oo,bH=ae,VF=QS,kH=TypeError,LH=Nd,HF=eA,nw=Pe,UH=function(A,t,o,a){var l=ON(A),d=!FN(function(){var L={};return L[l]=function(){return 7},""[A](L)!==7}),h=d&&!FN(function(){var L=!1,V=/a/,H;return V.exec=function(){return L=!0,null},V[l](""),!L});if(!d||!h||o){var y=/./[l],S=t(l,""[A],function(L,V,H,lA,hA){var MA=V.exec;return MA===LF||MA===UF.exec?d&&!hA?{done:!0,value:kF(y,V,H,lA)}:{done:!0,value:kF(L,H,V,lA)}:{done:!1}});UN(String.prototype,A,S[0]),UN(UF,l,S[1])}},FH=_,OH=Er,JF=oo,PH=no,xH=ea,qF=$s,Bp=yr,sw=Vi,KF=function(A,t,o){return t+(o?RH(A,t).length:1)},rw=_n,jF=PF,WF=JR,YH=function(A,t){var o=A.exec;if(YF(o)){var a=xF(o,A,t);return a!==null&&GH(a),a}if(bH(A)==="RegExp")return xF(VF,A,t);throw new kH("RegExp#exec called on incompatible receiver")},aw=is("replace"),HN=Math.max,VH=Math.min,zF=nw([].concat),JN=nw([].push),gw=nw("".indexOf),ZF=nw("".slice),HH=function(A){return A===void 0?A:String(A)},JH="a".replace(/./,"$0")==="$0",XF=!!/./[aw]&&/./[aw]("a","$0")==="",qH=!FH(function(){var A=/./;return A.exec=function(){var t=[];return t.groups={a:"7"},t},"".replace(A,"$")!=="7"});UH("replace",function(A,t,o){var a=XF?"$":"$0";return[function(l,d){var h=sw(this),y=PH(l)?rw(l,aw):void 0;return y?HF(y,l,h,d):HF(t,Bp(h),l,d)},function(l,d){var h=OH(this),y=Bp(l);if(typeof d=="string"&&gw(d,a)===-1&&gw(d,"$<")===-1){var S=o(t,h,y,d);if(S.done)return S.value}var L=JF(d);L||(d=Bp(d));var V,H=Bp(WF(h)),lA=gw(H,"g")!==-1;lA&&(V=gw(H,"u")!==-1,h.lastIndex=0);for(var hA,MA=[];(hA=YH(h,y))!==null&&(JN(MA,hA),lA);)Bp(hA[0])===""&&(h.lastIndex=KF(y,qF(h.lastIndex),V));for(var oe="",fe=0,je=0;je=fe&&(oe+=ZF(y,fe,Fe)+_e,fe=Fe+vi.length)}return oe+ZF(y,fe)}]},!qH||!JH||XF);var cw=` -\v\f\r                 \u2028\u2029\uFEFF`,KH=Vi,jH=yr,qN=cw,KN=Pe("".replace),$F=RegExp("^["+qN+"]+"),WH=RegExp("(^|[^"+qN+"])["+qN+"]+$"),zH=function(A){return function(t){var o=jH(KH(t));return 1&A&&(o=KN(o,$F,"")),2&A&&(o=KN(o,WH,"$1")),o}},ZH={trim:zH(3)},XH=tc.PROPER,$H=_,AO=cw,AJ=ZH.trim;Us({target:"String",proto:!0,forced:function(A){return $H(function(){return!!AO[A]()||"​…᠎"[A]()!=="​…᠎"||XH&&AO[A].name!==A})}("trim")},{trim:function(){return AJ(this)}});var Eu,Sf,lw,jN={exports:{}},eJ=_r,WN=T,LI=m,eO=oo,tO=no,vf=Ho,Iw=fr,zN=xs,ZN=cg,XN=wr,iO=Og,tJ=ue,$N=MI,Qp=sA,iJ=is,oJ=Mc,AG=ps.enforce,Oh=LI.Int8Array,Mf=Oh&&Oh.prototype,oO=LI.Uint8ClampedArray,nO=oO&&oO.prototype,bC=Oh&&$N(Oh),Od=Mf&&$N(Mf),nJ=Object.prototype,eG=LI.TypeError,sO=iJ("toStringTag"),tG=oJ("TYPED_ARRAY_TAG"),pS="TypedArrayConstructor",Pd=eJ&&!!Qp&&Iw(LI.opera)!=="Opera",rO=!1,OB={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},aO={BigInt64Array:8,BigUint64Array:8},uw=function(A){if(!tO(A))return!1;var t=Iw(A);return vf(OB,t)||vf(aO,t)};for(Eu in OB)(lw=(Sf=LI[Eu])&&Sf.prototype)?AG(lw)[pS]=Sf:Pd=!1;for(Eu in aO)(lw=(Sf=LI[Eu])&&Sf.prototype)&&(AG(lw)[pS]=Sf);if((!Pd||!eO(bC)||bC===Function.prototype)&&(bC=function(){throw new eG("Incorrect invocation")},Pd))for(Eu in OB)LI[Eu]&&Qp(LI[Eu],bC);if((!Pd||!Od||Od===nJ)&&(Od=bC.prototype,Pd))for(Eu in OB)LI[Eu]&&Qp(LI[Eu].prototype,Od);if(Pd&&$N(nO)!==Od&&Qp(nO,Od),WN&&!vf(Od,sO))for(Eu in rO=!0,iO(Od,sO,{configurable:!0,get:function(){return tO(this)?this[tG]:void 0}}),OB)LI[Eu]&&ZN(LI[Eu],tG,Eu);var xd={NATIVE_ARRAY_BUFFER_VIEWS:Pd,TYPED_ARRAY_TAG:rO&&tG,aTypedArray:function(A){if(uw(A))return A;throw new eG("Target is not a typed array")},aTypedArrayConstructor:function(A){if(eO(A)&&(!Qp||tJ(bC,A)))return A;throw new eG(zN(A)+" is not a typed array constructor")},exportTypedArrayMethod:function(A,t,o,a){if(WN){if(o)for(var l in OB){var d=LI[l];if(d&&vf(d.prototype,A))try{delete d.prototype[A]}catch{try{d.prototype[A]=t}catch{}}}Od[A]&&!o||XN(Od,A,o?t:Pd&&Mf[A]||t,a)}},exportTypedArrayStaticMethod:function(A,t,o){var a,l;if(WN){if(Qp){if(o){for(a in OB)if((l=LI[a])&&vf(l,A))try{delete l[A]}catch{}}if(bC[A]&&!o)return;try{return XN(bC,A,o?t:Pd&&bC[A]||t)}catch{}}for(a in OB)!(l=LI[a])||l[A]&&!o||XN(l,A,t)}},isTypedArray:uw,TypedArray:bC,TypedArrayPrototype:Od},iG=m,mS=_,Ew=g,sJ=xd.NATIVE_ARRAY_BUFFER_VIEWS,gO=iG.ArrayBuffer,pp=iG.Int8Array,cO=!sJ||!mS(function(){pp(1)})||!mS(function(){new pp(-1)})||!Ew(function(A){new pp,new pp(null),new pp(1.5),new pp(A)},!0)||mS(function(){return new pp(new gO(2),1,void 0).length!==1}),rJ=no,aJ=Math.floor,lO=Number.isInteger||function(A){return!rJ(A)&&isFinite(A)&&aJ(A)===A},gJ=ea,cJ=RangeError,dw=function(A){var t=gJ(A);if(t<0)throw new cJ("The argument can't be less than 0");return t},lJ=RangeError,IO=function(A,t){var o=dw(A);if(o%t)throw new lJ("Wrong offset");return o},IJ=Math.round,uO=fr,uJ=_s,EJ=TypeError,Cw=function(A){var t=uJ(A,"number");if(typeof t=="number")throw new EJ("Can't convert number to bigint");return BigInt(t)},EO=og,dO=eA,dJ=yh,CJ=ce,CO=Va,hO=ZE,hJ=Fh,BO=sS,QO=function(A){var t=uO(A);return t==="BigInt64Array"||t==="BigUint64Array"},BJ=xd.aTypedArrayConstructor,QJ=Cw,hw=function(A){var t,o,a,l,d,h,y,S,L=dJ(this),V=CJ(A),H=arguments.length,lA=H>1?arguments[1]:void 0,hA=lA!==void 0,MA=hJ(V);if(MA&&!BO(MA))for(S=(y=hO(V,MA)).next,V=[];!(h=dO(S,y)).done;)V.push(h.value);for(hA&&H>2&&(lA=EO(lA,arguments[2])),o=CO(V),a=new(BJ(L))(o),l=QO(a),t=0;o>t;t++)d=hA?lA(V[t],t):V[t],a[t]=l?QJ(d):+d;return a},oG=oa,nG=OD,pJ=no,mJ=is("species"),pO=Array,fJ=function(A){var t;return oG(A)&&(t=A.constructor,(nG(t)&&(t===pO||oG(t.prototype))||pJ(t)&&(t=t[mJ])===null)&&(t=void 0)),t===void 0?pO:t},mO=og,yJ=ii,DJ=ce,fO=Va,SJ=function(A,t){return new(fJ(A))(t===0?0:t)},sG=Pe([].push),yO=function(A){var t=A===1,o=A===2,a=A===3,l=A===4,d=A===6,h=A===7,y=A===5||d;return function(S,L,V,H){for(var lA,hA,MA=DJ(S),oe=yJ(MA),fe=fO(oe),je=mO(L,V),_e=0,vi=H||SJ,Fe=t?vi(S,fe):o||h?vi(S,0):void 0;fe>_e;_e++)if((y||_e in oe)&&(hA=je(lA=oe[_e],_e,MA),A))if(t)Fe[_e]=hA;else if(hA)switch(A){case 3:return!0;case 5:return lA;case 6:return _e;case 2:sG(Fe,lA)}else switch(A){case 4:return!1;case 7:sG(Fe,lA)}return d?-1:a||l?l:Fe}},DO={forEach:yO(0)},vJ=Va,SO=Us,vO=m,MO=eA,RO=T,MJ=cO,fS=xd,wO=xm,_O=TI,RJ=HA,PB=cg,wJ=lO,_J=$s,TO=_m,rG=IO,NO=function(A){var t=IJ(A);return t<0?0:t>255?255:255&t},aG=$,mp=Ho,TJ=fr,gG=no,cG=vo,NJ=qa,lG=ue,Bw=sA,GJ=Gc.f,GO=hw,bO=DO.forEach,Qw=Vm,bJ=Og,kO=eo,LO=R,UO=function(A,t,o){for(var a=0,l=arguments.length>2?o:vJ(t),d=new A(l);l>a;)d[a]=t[a++];return d},kJ=vD,IG=ps.get,LJ=ps.set,fp=ps.enforce,FO=kO.f,UJ=LO.f,uG=vO.RangeError,OO=wO.ArrayBuffer,FJ=OO.prototype,OJ=wO.DataView,Rf=fS.NATIVE_ARRAY_BUFFER_VIEWS,PO=fS.TYPED_ARRAY_TAG,xO=fS.TypedArray,yS=fS.TypedArrayPrototype,DS=fS.isTypedArray,yp="BYTES_PER_ELEMENT",pw="Wrong length",mw=function(A,t){bJ(A,t,{configurable:!0,get:function(){return IG(this)[t]}})},YO=function(A){var t;return lG(FJ,A)||(t=TJ(A))==="ArrayBuffer"||t==="SharedArrayBuffer"},EG=function(A,t){return DS(A)&&!cG(t)&&t in A&&wJ(+t)&&t>=0},fw=function(A,t){return t=aG(t),EG(A,t)?RJ(2,A[t]):UJ(A,t)},VO=function(A,t,o){return t=aG(t),!(EG(A,t)&&gG(o)&&mp(o,"value"))||mp(o,"get")||mp(o,"set")||o.configurable||mp(o,"writable")&&!o.writable||mp(o,"enumerable")&&!o.enumerable?FO(A,t,o):(A[t]=o.value,A)};RO?(Rf||(LO.f=fw,kO.f=VO,mw(yS,"buffer"),mw(yS,"byteOffset"),mw(yS,"byteLength"),mw(yS,"length")),SO({target:"Object",stat:!0,forced:!Rf},{getOwnPropertyDescriptor:fw,defineProperty:VO}),jN.exports=function(A,t,o){var a=A.match(/\d+/)[0]/8,l=A+(o?"Clamped":"")+"Array",d="get"+A,h="set"+A,y=vO[l],S=y,L=S&&S.prototype,V={},H=function(hA,MA){FO(hA,MA,{get:function(){return function(oe,fe){var je=IG(oe);return je.view[d](fe*a+je.byteOffset,!0)}(this,MA)},set:function(oe){return function(fe,je,_e){var vi=IG(fe);vi.view[h](je*a+vi.byteOffset,o?NO(_e):_e,!0)}(this,MA,oe)},enumerable:!0})};Rf?MJ&&(S=t(function(hA,MA,oe,fe){return _O(hA,L),kJ(gG(MA)?YO(MA)?fe!==void 0?new y(MA,rG(oe,a),fe):oe!==void 0?new y(MA,rG(oe,a)):new y(MA):DS(MA)?UO(S,MA):MO(GO,S,MA):new y(TO(MA)),hA,S)}),Bw&&Bw(S,xO),bO(GJ(y),function(hA){hA in S||PB(S,hA,y[hA])}),S.prototype=L):(S=t(function(hA,MA,oe,fe){_O(hA,L);var je,_e,vi,Fe=0,Dt=0;if(gG(MA)){if(!YO(MA))return DS(MA)?UO(S,MA):MO(GO,S,MA);je=MA,Dt=rG(oe,a);var pi=MA.byteLength;if(fe===void 0){if(pi%a)throw new uG(pw);if((_e=pi-Dt)<0)throw new uG(pw)}else if((_e=_J(fe)*a)+Dt>pi)throw new uG(pw);vi=_e/a}else vi=TO(MA),je=new OO(_e=vi*a);for(LJ(hA,{buffer:je,byteOffset:Dt,byteLength:_e,length:vi,view:new OJ(je)});Fe1?arguments[1]:void 0,t>2?arguments[2]:void 0)},dG(function(){var A=0;return new Int8Array(2).fill({valueOf:function(){return A++}}),A!==1})),(0,xd.exportTypedArrayStaticMethod)("from",hw,cO);var qO=m,KO=eA,hG=xd,jO=Va,JJ=IO,qJ=ce,WO=_,KJ=qO.RangeError,BG=qO.Int8Array,QG=BG&&BG.prototype,pG=QG&&QG.set,mG=hG.aTypedArray,zO=hG.exportTypedArrayMethod,yw=!WO(function(){var A=new Uint8ClampedArray(2);return KO(pG,A,{length:1,0:3},1),A[1]!==3}),ZO=yw&&hG.NATIVE_ARRAY_BUFFER_VIEWS&&WO(function(){var A=new BG(2);return A.set(1),A.set("2",1),A[0]!==0||A[1]!==2});zO("set",function(A){mG(this);var t=JJ(arguments.length>1?arguments[1]:void 0,1),o=qJ(A);if(yw)return KO(pG,this,o,t);var a=this.length,l=jO(o),d=0;if(l+t>a)throw new KJ("Wrong length");for(;d0&&1/a<0?1:-1:o>a}}(A))},!Dw||RG);var $O=Us,wG=eA,vS=Pe,_G=Vi,TG=oo,zJ=no,AP=Hg,MS=yr,ZJ=_n,RS=JR,eP=PF,XJ=is("replace"),tP=TypeError,Yd=vS("".indexOf);vS("".replace);var wS=vS("".slice),$J=Math.max;$O({target:"String",proto:!0},{replaceAll:function(A,t){var o,a,l,d,h,y,S,L,V,H=_G(this),lA=0,hA="";if(zJ(A)){if(AP(A)&&(o=MS(_G(RS(A))),!~Yd(o,"g")))throw new tP("`.replaceAll` does not allow non-global regexes");if(a=ZJ(A,XJ))return wG(a,A,H,t)}for(l=MS(H),d=MS(A),(h=TG(t))||(t=MS(t)),y=d.length,S=$J(1,y),L=Yd(l,d);L!==-1;)V=h?MS(t(d,L,l)):eP(d,l,L,[],void 0,t),hA+=wS(l,lA,L)+V,lA=L+y,L=L+S>l.length?-1:Yd(l,d,L+S);return lA1?arguments[1]:void 0)},oP=m,nP=NG,tq=GG,vw=eq,iq=cg,sP=function(A){if(A&&A.forEach!==vw)try{iq(A,"forEach",vw)}catch{A.forEach=vw}};for(var bG in nP)nP[bG]&&sP(oP[bG]&&oP[bG].prototype);sP(tq);var Mw=m,rP=NG,oq=GG,_S=to,TS=cg,nq=Ka,kG=is("iterator"),LG=_S.values,aP=function(A,t){if(A){if(A[kG]!==LG)try{TS(A,kG,LG)}catch{A[kG]=LG}if(nq(A,t,!0),rP[t]){for(var o in _S)if(A[o]!==_S[o])try{TS(A,o,_S[o])}catch{A[o]=_S[o]}}}};for(var UG in rP)aP(Mw[UG]&&Mw[UG].prototype,UG);aP(oq,"DOMTokenList");var FG=wC.clear;Us({global:!0,bind:!0,enumerable:!0,forced:m.clearImmediate!==FG},{clearImmediate:FG});var NS=m,sq=Nd,rq=oo,aq=Wr,gq=ct,cq=he,lq=pB,OG=NS.Function,Iq=/MSIE .\./.test(gq)||aq==="BUN"&&function(){var A=NS.Bun.version.split(".");return A.length<3||A[0]==="0"&&(A[1]<3||A[1]==="3"&&A[2]==="0")}(),gP=Us,cP=m,Rw=wC.set,uq=function(A,t){var o=1;return Iq?function(a,l){var d=lq(arguments.length,1)>o,h=rq(a)?a:OG(a),y=d?cq(arguments,o):[],S=d?function(){sq(h,this,y)}:h;return A(S)}:A},PG=cP.setImmediate?uq(Rw):Rw;gP({global:!0,bind:!0,enumerable:!0,forced:cP.setImmediate!==PG},{setImmediate:PG});var Ph=iw.charAt,Eq=yr,ww=ps,dq=Qe,lP=At,IP="String Iterator",Cq=ww.set,uP=ww.getterFor(IP);dq(String,"String",function(A){Cq(this,{type:IP,string:Eq(A),index:0})},function(){var A,t=uP(this),o=t.string,a=t.index;return a>=o.length?lP(void 0,!0):(A=Ph(o,a),t.index+=A.length,lP(A,!1))});var hq=_,Bq=T,Qq=is("iterator"),EP=!hq(function(){var A=new URL("b?a=1&b=2&c=3","https://a"),t=A.searchParams,o=new URLSearchParams("a=1&a=2&b=3"),a="";return A.pathname="c%20d",t.forEach(function(l,d){t.delete("b"),a+=d+l}),o.delete("a",2),o.delete("b",void 0),!t.size&&!Bq||!t.sort||A.href!=="https://a/c%20d?a=1&c=3"||t.get("c")!=="3"||String(new URLSearchParams("?a=1"))!=="a=1"||!t[Qq]||new URL("https://a@b").username!=="a"||new URLSearchParams(new URLSearchParams("a=b")).get("a")!=="b"||new URL("https://тест").host!=="xn--e1aybc"||new URL("https://a#б").hash!=="#%D0%B1"||a!=="a1c3"||new URL("https://x",void 0).host!=="x"}),dP=T,pq=Pe,xG=eA,YG=_,VG=Ol,mq=bc,fq=CA,yq=ce,CP=ii,Dp=Object.assign,hP=Object.defineProperty,BP=pq([].concat),Dq=!Dp||YG(function(){if(dP&&Dp({b:1},Dp(hP({},"a",{enumerable:!0,get:function(){hP(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var A={},t={},o=Symbol("assign detection"),a="abcdefghijklmnopqrst";return A[o]=7,a.split("").forEach(function(l){t[l]=l}),Dp({},A)[o]!==7||VG(Dp({},t)).join("")!==a})?function(A,t){for(var o=yq(A),a=arguments.length,l=1,d=mq.f,h=fq.f;a>l;)for(var y,S=CP(arguments[l++]),L=d?BP(VG(S),d(S)):VG(S),V=L.length,H=0;V>H;)y=L[H++],dP&&!xG(h,S,y)||(o[y]=S[y]);return o}:Dp,Sq=Er,vq=cS,Mq=T,Rq=eo,QP=HA,wq=og,GS=eA,pP=ce,mP=function(A,t,o,a){try{return a?t(Sq(o)[0],o[1]):t(o)}catch(l){vq(A,"throw",l)}},HG=sS,_q=OD,Tq=Va,bS=function(A,t,o){Mq?Rq.f(A,t,QP(0,o)):A[t]=o},JG=ZE,Nq=Fh,fP=Array,xB=Pe,qG=2147483647,yP=/[^\0-\u007E]/,KG=/[.\u3002\uFF0E\uFF61]/g,DP="Overflow: input needs wider integers to process",SP=RangeError,Gq=xB(KG.exec),YB=Math.floor,_w=String.fromCharCode,Tw=xB("".charCodeAt),rE=xB([].join),VB=xB([].push),va=xB("".replace),vP=xB("".split),bq=xB("".toLowerCase),MP=function(A){return A+22+75*(A<26)},jG=function(A,t,o){var a=0;for(A=o?YB(A/700):A>>1,A+=YB(A/t);A>455;)A=YB(A/35),a+=36;return YB(a+36*A/(A+38))},kq=function(A){var t=[];A=function(je){for(var _e=[],vi=0,Fe=je.length;vi=55296&&Dt<=56319&&vi=d&&aYB((qG-h)/H))throw new SP(DP);for(h+=(V-d)*H,d=V,o=0;oqG)throw new SP(DP);if(a===d){for(var lA=h,hA=36;;){var MA=hA<=y?1:hA>=y+26?26:hA-y;if(lAl;){if(t=+arguments[l++],Lq(t,1114111)!==t)throw new Uq(t+" is not a valid code point");o[l]=t<65536?xh(t):xh(55296+((t-=65536)>>10),t%1024+56320)}return LS(o,"")}});var Sp=Us,Tf=m,vp=QR,WG=jA,zn=eA,aE=Pe,Nf=T,zG=EP,wP=wr,Fq=Og,Oq=cu,Pq=Ka,xq=VE,US=ps,_P=TI,ZG=oo,Yq=Ho,Vq=og,Hq=fr,Jq=Er,TP=no,jl=yr,Kq=qa,NP=HA,GP=ZE,jq=Fh,Nw=At,Gf=pB,Wq=_t,zq=is("iterator"),Mp="URLSearchParams",XG=Mp+"Iterator",bP=US.set,Ql=US.getterFor(Mp),Yh=US.getterFor(XG),kP=vp("fetch"),bf=vp("Request"),FS=vp("Headers"),$G=bf&&bf.prototype,LP=FS&&FS.prototype,UP=Tf.TypeError,Zq=Tf.encodeURIComponent,Xq=String.fromCharCode,$q=WG("String","fromCodePoint"),AK=parseInt,Gw=aE("".charAt),bw=aE([].join),Vh=aE([].push),FP=aE("".replace),eK=aE([].shift),OP=aE([].splice),PP=aE("".split),xP=aE("".slice),Ab=aE(/./.exec),YP=/\+/g,tK=/^[0-9a-f]+$/i,VP=function(A,t){var o=xP(A,t,t+2);return Ab(tK,o)?AK(o,16):NaN},iK=function(A){for(var t=0,o=128;o>0&&A&o;o>>=1)t++;return t},oK=function(A){var t=null;switch(A.length){case 1:t=A[0];break;case 2:t=(31&A[0])<<6|63&A[1];break;case 3:t=(15&A[0])<<12|(63&A[1])<<6|63&A[2];break;case 4:t=(7&A[0])<<18|(63&A[1])<<12|(63&A[2])<<6|63&A[3]}return t>1114111?null:t},HP=function(A){for(var t=(A=FP(A,YP," ")).length,o="",a=0;at){o+="%",a++;continue}var d=VP(A,a+1);if(d!=d){o+=l,a++;continue}a+=2;var h=iK(d);if(h===0)l=Xq(d);else{if(h===1||h>4){o+="�",a++;continue}for(var y=[d],S=1;St||Gw(A,a)!=="%");){var L=VP(A,a+1);if(L!=L){a+=3;break}if(L>191||L<128)break;Vh(y,L),a+=2,S++}if(y.length!==h){o+="�";continue}var V=oK(y);V===null?o+="�":l=$q(V)}}o+=l,a++}return o},nK=/[!'()~]|%20/g,sK={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},rK=function(A){return sK[A]},JP=function(A){return FP(Zq(A),nK,rK)},eb=xq(function(A,t){bP(this,{type:XG,target:Ql(A).entries,index:0,kind:t})},Mp,function(){var A=Yh(this),t=A.target,o=A.index++;if(!t||o>=t.length)return A.target=null,Nw(void 0,!0);var a=t[o];switch(A.kind){case"keys":return Nw(a.key,!1);case"values":return Nw(a.value,!1)}return Nw([a.key,a.value],!1)},!0),qP=function(A){this.entries=[],this.url=null,A!==void 0&&(TP(A)?this.parseObject(A):this.parseQuery(typeof A=="string"?Gw(A,0)==="?"?xP(A,1):A:jl(A)))};qP.prototype={type:Mp,bindURL:function(A){this.url=A,this.update()},parseObject:function(A){var t,o,a,l,d,h,y,S=this.entries,L=jq(A);if(L)for(o=(t=GP(A,L)).next;!(a=zn(o,t)).done;){if(d=(l=GP(Jq(a.value))).next,(h=zn(d,l)).done||(y=zn(d,l)).done||!zn(d,l).done)throw new UP("Expected sequence with length 2");Vh(S,{key:jl(h.value),value:jl(y.value)})}else for(var V in A)Yq(A,V)&&Vh(S,{key:V,value:jl(A[V])})},parseQuery:function(A){if(A)for(var t,o,a=this.entries,l=PP(A,"&"),d=0;d0?arguments[0]:void 0));Nf||(this.size=A.entries.length)},Rp=kf.prototype;if(Oq(Rp,{append:function(A,t){var o=Ql(this);Gf(arguments.length,2),Vh(o.entries,{key:jl(A),value:jl(t)}),Nf||this.size++,o.updateURL()},delete:function(A){for(var t=Ql(this),o=Gf(arguments.length,1),a=t.entries,l=jl(A),d=o<2?void 0:arguments[1],h=d===void 0?d:jl(d),y=0;yo.key?1:-1}),A.updateURL()},forEach:function(A){for(var t,o=Ql(this).entries,a=Vq(A,arguments.length>1?arguments[1]:void 0),l=0;l1?KP(arguments[1]):{})}}),ZG(bf)){var ib=function(A){return _P(this,$G),new bf(A,arguments.length>1?KP(arguments[1]):{})};$G.constructor=ib,ib.prototype=$G,Sp({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:ib})}}var gE,gK=Us,ob=T,jP=EP,nb=m,WP=og,XE=Pe,kw=wr,$E=Og,cK=TI,sb=Ho,rb=Dq,HB=function(A){var t=pP(A),o=_q(this),a=arguments.length,l=a>1?arguments[1]:void 0,d=l!==void 0;d&&(l=wq(l,a>2?arguments[2]:void 0));var h,y,S,L,V,H,lA=Nq(t),hA=0;if(!lA||this===fP&&HG(lA))for(h=Tq(t),y=o?new this(h):fP(h);h>hA;hA++)H=d?l(t[hA],hA):t[hA],bS(y,hA,H);else for(y=o?new this:[],V=(L=JG(t,lA)).next;!(S=GS(V,L)).done;hA++)H=d?mP(L,l,[S.value,hA],!0):S.value,bS(y,hA,H);return y.length=hA,y},Vd=he,ab=iw.codeAt,lK=function(A){var t,o,a=[],l=vP(va(bq(A),KG,"."),".");for(t=0;t?@[\\\]^|]/,pK=/[\0\t\n\r #/:<>?@[\\\]^|]/,mK=/^[\u0000-\u0020]+/,fK=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,yK=/[\t\n\r]/g,Ff=function(A){var t,o,a,l;if(typeof A=="number"){for(t=[],o=0;o<4;o++)hK(t,A%256),A=Jh(A/256);return OS(t,".")}if(typeof A=="object"){for(t="",a=function(d){for(var h=null,y=1,S=null,L=0,V=0;V<8;V++)d[V]!==0?(L>y&&(h=S,y=L),S=null,L=0):(S===null&&(S=V),++L);return L>y?S:h}(A),o=0;o<8;o++)l&&A[o]===0||(l&&(l=!1),a===o?(t+=o?":":"::",l=!0):(t+=CK(A[o],16),o<7&&(t+=":")));return"["+t+"]"}return A},Of={},ix=rb({},Of,{" ":1,'"':1,"<":1,">":1,"`":1}),Eb=rb({},ix,{"#":1,"?":1,"{":1,"}":1}),qB=rb({},Eb,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),Jd=function(A,t){var o=ab(A,0);return o>32&&o<127&&!sb(t,A)?A:encodeURIComponent(A)},qh={ftp:21,file:null,http:80,https:443,ws:80,wss:443},Pf=function(A,t){var o;return A.length===2&&Hd(PS,Ad(A,0))&&((o=Ad(A,1))===":"||!t&&o==="|")},db=function(A){var t;return A.length>1&&Pf(wp(A,0,2))&&(A.length===2||(t=Ad(A,2))==="/"||t==="\\"||t==="?"||t==="#")},xS=function(A){return A==="."||Pw(A)==="%2e"},ox=function(A){return(A=Pw(A))===".."||A==="%2e."||A===".%2e"||A==="%2e%2e"},cE={},du={},KB={},kC={},jB={},Vw={},nx={},YS={},Hw={},Jw={},qw={},Kw={},jw={},Ww={},Cb={},zw={},xf={},LC={},VS={},Cu={},Wl={},Zw=function(A,t,o){var a,l,d,h=Hh(A);if(t){if(l=this.parse(h))throw new cb(l);this.searchParams=null}else{if(o!==void 0&&(a=new Zw(o,!0)),l=this.parse(h,null,a))throw new cb(l);(d=dK(new EK)).bindURL(this),this.searchParams=d}};Zw.prototype={type:"URL",parse:function(A,t,o){var a,l,d,h,y=this,S=t||cE,L=0,V="",H=!1,lA=!1,hA=!1;for(A=Hh(A),t||(y.scheme="",y.username="",y.password="",y.host=null,y.port=null,y.path=[],y.query=null,y.fragment=null,y.cannotBeABaseURL=!1,A=Fw(A,mK,""),A=Fw(A,fK,"$1")),A=Fw(A,yK,""),a=HB(A);L<=a.length;){switch(l=a[L],S){case cE:if(!l||!Hd(PS,l)){if(t)return Ib;S=KB;continue}V+=Pw(l),S=du;break;case du:if(l&&(Hd(BK,l)||l==="+"||l==="-"||l==="."))V+=Pw(l);else{if(l!==":"){if(t)return Ib;V="",S=KB,L=0;continue}if(t&&(y.isSpecial()!==sb(qh,V)||V==="file"&&(y.includesCredentials()||y.port!==null)||y.scheme==="file"&&!y.host))return;if(y.scheme=V,t)return void(y.isSpecial()&&qh[y.scheme]===y.port&&(y.port=null));V="",y.scheme==="file"?S=Ww:y.isSpecial()&&o&&o.scheme===y.scheme?S=kC:y.isSpecial()?S=YS:a[L+1]==="/"?(S=jB,L++):(y.cannotBeABaseURL=!0,Uf(y.path,""),S=VS)}break;case KB:if(!o||o.cannotBeABaseURL&&l!=="#")return Ib;if(o.cannotBeABaseURL&&l==="#"){y.scheme=o.scheme,y.path=Vd(o.path),y.query=o.query,y.fragment="",y.cannotBeABaseURL=!0,S=Wl;break}S=o.scheme==="file"?Ww:Vw;continue;case kC:if(l!=="/"||a[L+1]!=="/"){S=Vw;continue}S=Hw,L++;break;case jB:if(l==="/"){S=Jw;break}S=LC;continue;case Vw:if(y.scheme=o.scheme,l===gE)y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,y.path=Vd(o.path),y.query=o.query;else if(l==="/"||l==="\\"&&y.isSpecial())S=nx;else if(l==="?")y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,y.path=Vd(o.path),y.query="",S=Cu;else{if(l!=="#"){y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,y.path=Vd(o.path),y.path.length--,S=LC;continue}y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,y.path=Vd(o.path),y.query=o.query,y.fragment="",S=Wl}break;case nx:if(!y.isSpecial()||l!=="/"&&l!=="\\"){if(l!=="/"){y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,S=LC;continue}S=Jw}else S=Hw;break;case YS:if(S=Hw,l!=="/"||Ad(V,L+1)!=="/")continue;L++;break;case Hw:if(l!=="/"&&l!=="\\"){S=Jw;continue}break;case Jw:if(l==="@"){H&&(V="%40"+V),H=!0,d=HB(V);for(var MA=0;MA65535)return xw;y.port=y.isSpecial()&&je===qh[y.scheme]?null:je,V=""}if(t)return;S=xf;continue}return xw}V+=l;break;case Ww:if(y.scheme="file",l==="/"||l==="\\")S=Cb;else{if(!o||o.scheme!=="file"){S=LC;continue}switch(l){case gE:y.host=o.host,y.path=Vd(o.path),y.query=o.query;break;case"?":y.host=o.host,y.path=Vd(o.path),y.query="",S=Cu;break;case"#":y.host=o.host,y.path=Vd(o.path),y.query=o.query,y.fragment="",S=Wl;break;default:db(OS(Vd(a,L),""))||(y.host=o.host,y.path=Vd(o.path),y.shortenPath()),S=LC;continue}}break;case Cb:if(l==="/"||l==="\\"){S=zw;break}o&&o.scheme==="file"&&!db(OS(Vd(a,L),""))&&(Pf(o.path[0],!0)?Uf(y.path,o.path[0]):y.host=o.host),S=LC;continue;case zw:if(l===gE||l==="/"||l==="\\"||l==="?"||l==="#"){if(!t&&Pf(V))S=LC;else if(V===""){if(y.host="",t)return;S=xf}else{if(h=y.parseHost(V))return h;if(y.host==="localhost"&&(y.host=""),t)return;V="",S=xf}continue}V+=l;break;case xf:if(y.isSpecial()){if(S=LC,l!=="/"&&l!=="\\")continue}else if(t||l!=="?")if(t||l!=="#"){if(l!==gE&&(S=LC,l!=="/"))continue}else y.fragment="",S=Wl;else y.query="",S=Cu;break;case LC:if(l===gE||l==="/"||l==="\\"&&y.isSpecial()||!t&&(l==="?"||l==="#")){if(ox(V)?(y.shortenPath(),l==="/"||l==="\\"&&y.isSpecial()||Uf(y.path,"")):xS(V)?l==="/"||l==="\\"&&y.isSpecial()||Uf(y.path,""):(y.scheme==="file"&&!y.path.length&&Pf(V)&&(y.host&&(y.host=""),V=Ad(V,0)+":"),Uf(y.path,V)),V="",y.scheme==="file"&&(l===gE||l==="?"||l==="#"))for(;y.path.length>1&&y.path[0]==="";)Ow(y.path);l==="?"?(y.query="",S=Cu):l==="#"&&(y.fragment="",S=Wl)}else V+=Jd(l,Eb);break;case VS:l==="?"?(y.query="",S=Cu):l==="#"?(y.fragment="",S=Wl):l!==gE&&(y.path[0]+=Jd(l,Of));break;case Cu:t||l!=="#"?l!==gE&&(l==="'"&&y.isSpecial()?y.query+="%27":y.query+=l==="#"?"%23":Jd(l,Of)):(y.fragment="",S=Wl);break;case Wl:l!==gE&&(y.fragment+=Jd(l,ix))}L++}},parseHost:function(A){var t,o,a;if(Ad(A,0)==="["){if(Ad(A,A.length-1)!=="]"||(t=function(l){var d,h,y,S,L,V,H,lA=[0,0,0,0,0,0,0,0],hA=0,MA=null,oe=0,fe=function(){return Ad(l,oe)};if(fe()===":"){if(Ad(l,1)!==":")return;oe+=2,MA=++hA}for(;fe();){if(hA===8)return;if(fe()!==":"){for(d=h=0;h<4&&Hd(ex,fe());)d=16*d+Uw(fe(),16),oe++,h++;if(fe()==="."){if(h===0||(oe-=h,hA>6))return;for(y=0;fe();){if(S=null,y>0){if(!(fe()==="."&&y<4))return;oe++}if(!Hd(ub,fe()))return;for(;Hd(ub,fe());){if(L=Uw(fe(),10),S===null)S=L;else{if(S===0)return;S=10*S+L}if(S>255)return;oe++}lA[hA]=256*lA[hA]+S,++y!==2&&y!==4||hA++}if(y!==4)return;break}if(fe()===":"){if(oe++,!fe())return}else if(fe())return;lA[hA++]=d}else{if(MA!==null)return;oe++,MA=++hA}}if(MA!==null)for(V=hA-MA,hA=7;hA!==0&&V>0;)H=lA[hA],lA[hA--]=lA[MA+V-1],lA[MA+--V]=H;else if(hA!==8)return;return lA}(wp(A,1,-1)),!t))return JB;this.host=t}else if(this.isSpecial()){if(A=lK(A),Hd(tx,A)||(t=function(l){var d,h,y,S,L,V,H,lA=lb(l,".");if(lA.length&&lA[lA.length-1]===""&&lA.length--,(d=lA.length)>4)return l;for(h=[],y=0;y1&&Ad(S,0)==="0"&&(L=Hd(Yw,S)?16:8,S=wp(S,L===8?1:2)),S==="")V=0;else{if(!Hd(L===10?Ax:L===8?QK:ex,S))return l;V=Uw(S,L)}Uf(h,V)}for(y=0;y=XP(256,5-d))return null}else if(V>255)return null;for(H=$P(h),y=0;y1?arguments[1]:void 0,a=uK(t,new Zw(A,!1,o));ob||(t.href=a.serialize(),t.origin=a.getOrigin(),t.protocol=a.getProtocol(),t.username=a.getUsername(),t.password=a.getPassword(),t.host=a.getHost(),t.hostname=a.getHostname(),t.port=a.getPort(),t.pathname=a.getPathname(),t.search=a.getSearch(),t.searchParams=a.getSearchParams(),t.hash=a.getHash())},zl=Kh.prototype,Zl=function(A,t){return{get:function(){return Lw(this)[A]()},set:t&&function(o){return Lw(this)[t](o)},configurable:!0,enumerable:!0}};if(ob&&($E(zl,"href",Zl("serialize","setHref")),$E(zl,"origin",Zl("getOrigin")),$E(zl,"protocol",Zl("getProtocol","setProtocol")),$E(zl,"username",Zl("getUsername","setUsername")),$E(zl,"password",Zl("getPassword","setPassword")),$E(zl,"host",Zl("getHost","setHost")),$E(zl,"hostname",Zl("getHostname","setHostname")),$E(zl,"port",Zl("getPort","setPort")),$E(zl,"pathname",Zl("getPathname","setPathname")),$E(zl,"search",Zl("getSearch","setSearch")),$E(zl,"searchParams",Zl("getSearchParams")),$E(zl,"hash",Zl("getHash","setHash"))),kw(zl,"toJSON",function(){return Lw(this).serialize()},{enumerable:!0}),kw(zl,"toString",function(){return Lw(this).serialize()},{enumerable:!0}),Lf){var sx=Lf.createObjectURL,Xw=Lf.revokeObjectURL;sx&&kw(Kh,"createObjectURL",WP(sx,Lf)),Xw&&kw(Kh,"revokeObjectURL",WP(Xw,Lf))}IK(Kh,"URL"),gK({global:!0,constructor:!0,forced:!jP,sham:!ob},{URL:Kh});var rx=eA;Us({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return rx(URL.prototype.toString,this)}});let ax=!0,$w=!0;function HS(A,t,o){const a=A.match(t);return a&&a.length>=o&&parseFloat(a[o],10)}function WB(A,t,o){if(!A.RTCPeerConnection)return;const a=A.RTCPeerConnection.prototype,l=a.addEventListener;a.addEventListener=function(h,y){if(h!==t)return l.apply(this,arguments);const S=L=>{const V=o(L);V&&(y.handleEvent?y.handleEvent(V):y(V))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(y,S),l.apply(this,[h,S])};const d=a.removeEventListener;a.removeEventListener=function(h,y){if(h!==t||!this._eventMap||!this._eventMap[t])return d.apply(this,arguments);if(!this._eventMap[t].has(y))return d.apply(this,arguments);const S=this._eventMap[t].get(y);return this._eventMap[t].delete(y),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,d.apply(this,[h,S])},Object.defineProperty(a,"on"+t,{get(){return this["_on"+t]},set(h){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),h&&this.addEventListener(t,this["_on"+t]=h)},enumerable:!0,configurable:!0})}function gx(A){return typeof A!="boolean"?new Error("Argument type: "+typeof A+". Please use a boolean."):(ax=A,A?"adapter.js logging disabled":"adapter.js logging enabled")}function DK(A){return typeof A!="boolean"?new Error("Argument type: "+typeof A+". Please use a boolean."):($w=!A,"adapter.js deprecation warnings "+(A?"disabled":"enabled"))}function A0(){if(typeof window=="object"){if(ax)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function JS(A,t){$w&&console.warn(A+" is deprecated, please use "+t+" instead.")}function hb(A){return Object.prototype.toString.call(A)==="[object Object]"}function Bb(A){return hb(A)?Object.keys(A).reduce(function(t,o){const a=hb(A[o]),l=a?Bb(A[o]):A[o],d=a&&!Object.keys(l).length;return l===void 0||d?t:Object.assign(t,{[o]:l})},{}):A}function Qb(A,t,o){t&&!o.has(t.id)&&(o.set(t.id,t),Object.keys(t).forEach(a=>{a.endsWith("Id")?Qb(A,A.get(t[a]),o):a.endsWith("Ids")&&t[a].forEach(l=>{Qb(A,A.get(l),o)})}))}function cx(A,t,o){const a=o?"outbound-rtp":"inbound-rtp",l=new Map;if(t===null)return l;const d=[];return A.forEach(h=>{h.type==="track"&&h.trackIdentifier===t.id&&d.push(h)}),d.forEach(h=>{A.forEach(y=>{y.type===a&&y.trackId===h.id&&Qb(A,y,l)})}),l}const pb=A0;function lx(A,t){const o=A&&A.navigator;if(!o.mediaDevices)return;const a=function(h){if(typeof h!="object"||h.mandatory||h.optional)return h;const y={};return Object.keys(h).forEach(S=>{if(S==="require"||S==="advanced"||S==="mediaSource")return;const L=typeof h[S]=="object"?h[S]:{ideal:h[S]};L.exact!==void 0&&typeof L.exact=="number"&&(L.min=L.max=L.exact);const V=function(H,lA){return H?H+lA.charAt(0).toUpperCase()+lA.slice(1):lA==="deviceId"?"sourceId":lA};if(L.ideal!==void 0){y.optional=y.optional||[];let H={};typeof L.ideal=="number"?(H[V("min",S)]=L.ideal,y.optional.push(H),H={},H[V("max",S)]=L.ideal,y.optional.push(H)):(H[V("",S)]=L.ideal,y.optional.push(H))}L.exact!==void 0&&typeof L.exact!="number"?(y.mandatory=y.mandatory||{},y.mandatory[V("",S)]=L.exact):["min","max"].forEach(H=>{L[H]!==void 0&&(y.mandatory=y.mandatory||{},y.mandatory[V(H,S)]=L[H])})}),h.advanced&&(y.optional=(y.optional||[]).concat(h.advanced)),y},l=function(h,y){if(t.version>=61)return y(h);if((h=JSON.parse(JSON.stringify(h)))&&typeof h.audio=="object"){const S=function(L,V,H){V in L&&!(H in L)&&(L[H]=L[V],delete L[V])};S((h=JSON.parse(JSON.stringify(h))).audio,"autoGainControl","googAutoGainControl"),S(h.audio,"noiseSuppression","googNoiseSuppression"),h.audio=a(h.audio)}if(h&&typeof h.video=="object"){let S=h.video.facingMode;S=S&&(typeof S=="object"?S:{ideal:S});const L=t.version<66;if(S&&(S.exact==="user"||S.exact==="environment"||S.ideal==="user"||S.ideal==="environment")&&(!o.mediaDevices.getSupportedConstraints||!o.mediaDevices.getSupportedConstraints().facingMode||L)){let V;if(delete h.video.facingMode,S.exact==="environment"||S.ideal==="environment"?V=["back","rear"]:S.exact!=="user"&&S.ideal!=="user"||(V=["front"]),V)return o.mediaDevices.enumerateDevices().then(H=>{H=H.filter(hA=>hA.kind==="videoinput");let lA=H.find(hA=>V.some(MA=>hA.label.toLowerCase().includes(MA)));return!lA&&H.length&&V.includes("back")&&(lA=H[H.length-1]),lA&&(h.video.deviceId=S.exact?{exact:lA.deviceId}:{ideal:lA.deviceId}),h.video=a(h.video),pb("chrome: "+JSON.stringify(h)),y(h)})}h.video=a(h.video)}return pb("chrome: "+JSON.stringify(h)),y(h)},d=function(h){return t.version>=64?h:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[h.name]||h.name,message:h.message,constraint:h.constraint||h.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(o.getUserMedia=function(h,y,S){l(h,L=>{o.webkitGetUserMedia(L,y,V=>{S&&S(d(V))})})}.bind(o),o.mediaDevices.getUserMedia){const h=o.mediaDevices.getUserMedia.bind(o.mediaDevices);o.mediaDevices.getUserMedia=function(y){return l(y,S=>h(S).then(L=>{if(S.audio&&!L.getAudioTracks().length||S.video&&!L.getVideoTracks().length)throw L.getTracks().forEach(V=>{V.stop()}),new DOMException("","NotFoundError");return L},L=>Promise.reject(d(L))))}}}function Ix(A){A.MediaStream=A.MediaStream||A.webkitMediaStream}function ux(A){if(typeof A=="object"&&A.RTCPeerConnection&&!("ontrack"in A.RTCPeerConnection.prototype)){Object.defineProperty(A.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(o){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=o)},enumerable:!0,configurable:!0});const t=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=o=>{o.stream.addEventListener("addtrack",a=>{let l;l=A.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(h=>h.track&&h.track.id===a.track.id):{track:a.track};const d=new Event("track");d.track=a.track,d.receiver=l,d.transceiver={receiver:l},d.streams=[o.stream],this.dispatchEvent(d)}),o.stream.getTracks().forEach(a=>{let l;l=A.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(h=>h.track&&h.track.id===a.id):{track:a};const d=new Event("track");d.track=a,d.receiver=l,d.transceiver={receiver:l},d.streams=[o.stream],this.dispatchEvent(d)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else WB(A,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function mb(A){if(typeof A=="object"&&A.RTCPeerConnection&&!("getSenders"in A.RTCPeerConnection.prototype)&&"createDTMFSender"in A.RTCPeerConnection.prototype){const t=function(l,d){return{track:d,get dtmf(){return this._dtmf===void 0&&(d.kind==="audio"?this._dtmf=l.createDTMFSender(d):this._dtmf=null),this._dtmf},_pc:l}};if(!A.RTCPeerConnection.prototype.getSenders){A.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const l=A.RTCPeerConnection.prototype.addTrack;A.RTCPeerConnection.prototype.addTrack=function(h,y){let S=l.apply(this,arguments);return S||(S=t(this,h),this._senders.push(S)),S};const d=A.RTCPeerConnection.prototype.removeTrack;A.RTCPeerConnection.prototype.removeTrack=function(h){d.apply(this,arguments);const y=this._senders.indexOf(h);y!==-1&&this._senders.splice(y,1)}}const o=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(l){this._senders=this._senders||[],o.apply(this,[l]),l.getTracks().forEach(d=>{this._senders.push(t(this,d))})};const a=A.RTCPeerConnection.prototype.removeStream;A.RTCPeerConnection.prototype.removeStream=function(l){this._senders=this._senders||[],a.apply(this,[l]),l.getTracks().forEach(d=>{const h=this._senders.find(y=>y.track===d);h&&this._senders.splice(this._senders.indexOf(h),1)})}}else if(typeof A=="object"&&A.RTCPeerConnection&&"getSenders"in A.RTCPeerConnection.prototype&&"createDTMFSender"in A.RTCPeerConnection.prototype&&A.RTCRtpSender&&!("dtmf"in A.RTCRtpSender.prototype)){const t=A.RTCPeerConnection.prototype.getSenders;A.RTCPeerConnection.prototype.getSenders=function(){const o=t.apply(this,[]);return o.forEach(a=>a._pc=this),o},Object.defineProperty(A.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Ex(A){if(!A.RTCPeerConnection)return;const t=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){const[o,a,l]=arguments;if(arguments.length>0&&typeof o=="function")return t.apply(this,arguments);if(t.length===0&&(arguments.length===0||typeof o!="function"))return t.apply(this,[]);const d=function(y){const S={};return y.result().forEach(L=>{const V={id:L.id,timestamp:L.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[L.type]||L.type};L.names().forEach(H=>{V[H]=L.stat(H)}),S[V.id]=V}),S},h=function(y){return new Map(Object.keys(y).map(S=>[S,y[S]]))};if(arguments.length>=2){const y=function(S){a(h(d(S)))};return t.apply(this,[y,o])}return new Promise((y,S)=>{t.apply(this,[function(L){y(h(d(L)))},S])}).then(a,l)}}function fb(A){if(!(typeof A=="object"&&A.RTCPeerConnection&&A.RTCRtpSender&&A.RTCRtpReceiver))return;if(!("getStats"in A.RTCRtpSender.prototype)){const o=A.RTCPeerConnection.prototype.getSenders;o&&(A.RTCPeerConnection.prototype.getSenders=function(){const l=o.apply(this,[]);return l.forEach(d=>d._pc=this),l});const a=A.RTCPeerConnection.prototype.addTrack;a&&(A.RTCPeerConnection.prototype.addTrack=function(){const l=a.apply(this,arguments);return l._pc=this,l}),A.RTCRtpSender.prototype.getStats=function(){const l=this;return this._pc.getStats().then(d=>cx(d,l.track,!0))}}if(!("getStats"in A.RTCRtpReceiver.prototype)){const o=A.RTCPeerConnection.prototype.getReceivers;o&&(A.RTCPeerConnection.prototype.getReceivers=function(){const a=o.apply(this,[]);return a.forEach(l=>l._pc=this),a}),WB(A,"track",a=>(a.receiver._pc=a.srcElement,a)),A.RTCRtpReceiver.prototype.getStats=function(){const a=this;return this._pc.getStats().then(l=>cx(l,a.track,!1))}}if(!("getStats"in A.RTCRtpSender.prototype)||!("getStats"in A.RTCRtpReceiver.prototype))return;const t=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof A.MediaStreamTrack){const o=arguments[0];let a,l,d;return this.getSenders().forEach(h=>{h.track===o&&(a?d=!0:a=h)}),this.getReceivers().forEach(h=>(h.track===o&&(l?d=!0:l=h),h.track===o)),d||a&&l?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):a?a.getStats():l?l.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function dx(A){A.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(d=>this._shimmedLocalStreams[d][0])};const t=A.RTCPeerConnection.prototype.addTrack;A.RTCPeerConnection.prototype.addTrack=function(d,h){if(!h)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const y=t.apply(this,arguments);return this._shimmedLocalStreams[h.id]?this._shimmedLocalStreams[h.id].indexOf(y)===-1&&this._shimmedLocalStreams[h.id].push(y):this._shimmedLocalStreams[h.id]=[h,y],y};const o=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(d){this._shimmedLocalStreams=this._shimmedLocalStreams||{},d.getTracks().forEach(S=>{if(this.getSenders().find(L=>L.track===S))throw new DOMException("Track already exists.","InvalidAccessError")});const h=this.getSenders();o.apply(this,arguments);const y=this.getSenders().filter(S=>h.indexOf(S)===-1);this._shimmedLocalStreams[d.id]=[d].concat(y)};const a=A.RTCPeerConnection.prototype.removeStream;A.RTCPeerConnection.prototype.removeStream=function(d){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[d.id],a.apply(this,arguments)};const l=A.RTCPeerConnection.prototype.removeTrack;A.RTCPeerConnection.prototype.removeTrack=function(d){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},d&&Object.keys(this._shimmedLocalStreams).forEach(h=>{const y=this._shimmedLocalStreams[h].indexOf(d);y!==-1&&this._shimmedLocalStreams[h].splice(y,1),this._shimmedLocalStreams[h].length===1&&delete this._shimmedLocalStreams[h]}),l.apply(this,arguments)}}function Cx(A,t){if(!A.RTCPeerConnection)return;if(A.RTCPeerConnection.prototype.addTrack&&t.version>=65)return dx(A);const o=A.RTCPeerConnection.prototype.getLocalStreams;A.RTCPeerConnection.prototype.getLocalStreams=function(){const S=o.apply(this);return this._reverseStreams=this._reverseStreams||{},S.map(L=>this._reverseStreams[L.id])};const a=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(S){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},S.getTracks().forEach(L=>{if(this.getSenders().find(V=>V.track===L))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[S.id]){const L=new A.MediaStream(S.getTracks());this._streams[S.id]=L,this._reverseStreams[L.id]=S,S=L}a.apply(this,[S])};const l=A.RTCPeerConnection.prototype.removeStream;function d(S,L){let V=L.sdp;return Object.keys(S._reverseStreams||[]).forEach(H=>{const lA=S._reverseStreams[H],hA=S._streams[lA.id];V=V.replace(new RegExp(hA.id,"g"),lA.id)}),new RTCSessionDescription({type:L.type,sdp:V})}A.RTCPeerConnection.prototype.removeStream=function(S){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.apply(this,[this._streams[S.id]||S]),delete this._reverseStreams[this._streams[S.id]?this._streams[S.id].id:S.id],delete this._streams[S.id]},A.RTCPeerConnection.prototype.addTrack=function(S,L){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const V=[].slice.call(arguments,1);if(V.length!==1||!V[0].getTracks().find(lA=>lA===S))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(lA=>lA.track===S))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const H=this._streams[L.id];if(H)H.addTrack(S),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const lA=new A.MediaStream([S]);this._streams[L.id]=lA,this._reverseStreams[lA.id]=L,this.addStream(lA)}return this.getSenders().find(lA=>lA.track===S)},["createOffer","createAnswer"].forEach(function(S){const L=A.RTCPeerConnection.prototype[S],V={[S](){const H=arguments;return arguments.length&&typeof arguments[0]=="function"?L.apply(this,[lA=>{const hA=d(this,lA);H[0].apply(null,[hA])},lA=>{H[1]&&H[1].apply(null,lA)},arguments[2]]):L.apply(this,arguments).then(lA=>d(this,lA))}};A.RTCPeerConnection.prototype[S]=V[S]});const h=A.RTCPeerConnection.prototype.setLocalDescription;A.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(S,L){let V=L.sdp;return Object.keys(S._reverseStreams||[]).forEach(H=>{const lA=S._reverseStreams[H],hA=S._streams[lA.id];V=V.replace(new RegExp(lA.id,"g"),hA.id)}),new RTCSessionDescription({type:L.type,sdp:V})}(this,arguments[0]),h.apply(this,arguments)):h.apply(this,arguments)};const y=Object.getOwnPropertyDescriptor(A.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(A.RTCPeerConnection.prototype,"localDescription",{get(){const S=y.get.apply(this);return S.type===""?S:d(this,S)}}),A.RTCPeerConnection.prototype.removeTrack=function(S){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!S._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(S._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let L;this._streams=this._streams||{},Object.keys(this._streams).forEach(V=>{this._streams[V].getTracks().find(H=>S.track===H)&&(L=this._streams[V])}),L&&(L.getTracks().length===1?this.removeStream(this._reverseStreams[L.id]):L.removeTrack(S.track),this.dispatchEvent(new Event("negotiationneeded")))}}function qS(A,t){!A.RTCPeerConnection&&A.webkitRTCPeerConnection&&(A.RTCPeerConnection=A.webkitRTCPeerConnection),A.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(o){const a=A.RTCPeerConnection.prototype[o],l={[o](){return arguments[0]=new(o==="addIceCandidate"?A.RTCIceCandidate:A.RTCSessionDescription)(arguments[0]),a.apply(this,arguments)}};A.RTCPeerConnection.prototype[o]=l[o]})}function hx(A,t){WB(A,"negotiationneeded",o=>{const a=o.target;if(!(t.version<72||a.getConfiguration&&a.getConfiguration().sdpSemantics==="plan-b")||a.signalingState==="stable")return o})}var yb=Object.freeze({__proto__:null,shimMediaStream:Ix,shimOnTrack:ux,shimGetSendersWithDtmf:mb,shimGetStats:Ex,shimSenderReceiverGetStats:fb,shimAddTrackRemoveTrackWithNative:dx,shimAddTrackRemoveTrack:Cx,shimPeerConnection:qS,fixNegotiationNeeded:hx,shimGetUserMedia:lx,shimGetDisplayMedia:function(A,t){A.navigator.mediaDevices&&"getDisplayMedia"in A.navigator.mediaDevices||A.navigator.mediaDevices&&(typeof t=="function"?A.navigator.mediaDevices.getDisplayMedia=function(o){return t(o).then(a=>{const l=o.video&&o.video.width,d=o.video&&o.video.height,h=o.video&&o.video.frameRate;return o.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:a,maxFrameRate:h||3}},l&&(o.video.mandatory.maxWidth=l),d&&(o.video.mandatory.maxHeight=d),A.navigator.mediaDevices.getUserMedia(o)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function Bx(A,t){const o=A&&A.navigator,a=A&&A.MediaStreamTrack;if(o.getUserMedia=function(l,d,h){JS("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),o.mediaDevices.getUserMedia(l).then(d,h)},!(t.version>55&&"autoGainControl"in o.mediaDevices.getSupportedConstraints())){const l=function(h,y,S){y in h&&!(S in h)&&(h[S]=h[y],delete h[y])},d=o.mediaDevices.getUserMedia.bind(o.mediaDevices);if(o.mediaDevices.getUserMedia=function(h){return typeof h=="object"&&typeof h.audio=="object"&&(h=JSON.parse(JSON.stringify(h)),l(h.audio,"autoGainControl","mozAutoGainControl"),l(h.audio,"noiseSuppression","mozNoiseSuppression")),d(h)},a&&a.prototype.getSettings){const h=a.prototype.getSettings;a.prototype.getSettings=function(){const y=h.apply(this,arguments);return l(y,"mozAutoGainControl","autoGainControl"),l(y,"mozNoiseSuppression","noiseSuppression"),y}}if(a&&a.prototype.applyConstraints){const h=a.prototype.applyConstraints;a.prototype.applyConstraints=function(y){return this.kind==="audio"&&typeof y=="object"&&(y=JSON.parse(JSON.stringify(y)),l(y,"autoGainControl","mozAutoGainControl"),l(y,"noiseSuppression","mozNoiseSuppression")),h.apply(this,[y])}}}}function Qx(A){typeof A=="object"&&A.RTCTrackEvent&&"receiver"in A.RTCTrackEvent.prototype&&!("transceiver"in A.RTCTrackEvent.prototype)&&Object.defineProperty(A.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function e0(A,t){if(typeof A!="object"||!A.RTCPeerConnection&&!A.mozRTCPeerConnection)return;!A.RTCPeerConnection&&A.mozRTCPeerConnection&&(A.RTCPeerConnection=A.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(l){const d=A.RTCPeerConnection.prototype[l],h={[l](){return arguments[0]=new(l==="addIceCandidate"?A.RTCIceCandidate:A.RTCSessionDescription)(arguments[0]),d.apply(this,arguments)}};A.RTCPeerConnection.prototype[l]=h[l]});const o={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},a=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){const[l,d,h]=arguments;return a.apply(this,[l||null]).then(y=>{if(t.version<53&&!d)try{y.forEach(S=>{S.type=o[S.type]||S.type})}catch(S){if(S.name!=="TypeError")throw S;y.forEach((L,V)=>{y.set(V,Object.assign({},L,{type:o[L.type]||L.type}))})}return y}).then(d,h)}}function px(A){if(typeof A!="object"||!A.RTCPeerConnection||!A.RTCRtpSender||A.RTCRtpSender&&"getStats"in A.RTCRtpSender.prototype)return;const t=A.RTCPeerConnection.prototype.getSenders;t&&(A.RTCPeerConnection.prototype.getSenders=function(){const a=t.apply(this,[]);return a.forEach(l=>l._pc=this),a});const o=A.RTCPeerConnection.prototype.addTrack;o&&(A.RTCPeerConnection.prototype.addTrack=function(){const a=o.apply(this,arguments);return a._pc=this,a}),A.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Db(A){if(typeof A!="object"||!A.RTCPeerConnection||!A.RTCRtpSender||A.RTCRtpSender&&"getStats"in A.RTCRtpReceiver.prototype)return;const t=A.RTCPeerConnection.prototype.getReceivers;t&&(A.RTCPeerConnection.prototype.getReceivers=function(){const o=t.apply(this,[]);return o.forEach(a=>a._pc=this),o}),WB(A,"track",o=>(o.receiver._pc=o.srcElement,o)),A.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function mx(A){A.RTCPeerConnection&&!("removeStream"in A.RTCPeerConnection.prototype)&&(A.RTCPeerConnection.prototype.removeStream=function(t){JS("removeStream","removeTrack"),this.getSenders().forEach(o=>{o.track&&t.getTracks().includes(o.track)&&this.removeTrack(o)})})}function Sb(A){A.DataChannel&&!A.RTCDataChannel&&(A.RTCDataChannel=A.DataChannel)}function fx(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const t=A.RTCPeerConnection.prototype.addTransceiver;t&&(A.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let o=arguments[1]&&arguments[1].sendEncodings;o===void 0&&(o=[]),o=[...o];const a=o.length>0;a&&o.forEach(d=>{if("rid"in d&&!/^[a-z0-9]{0,16}$/i.test(d.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in d&&!(parseFloat(d.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in d&&!(parseFloat(d.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const l=t.apply(this,arguments);if(a){const{sender:d}=l,h=d.getParameters();(!("encodings"in h)||h.encodings.length===1&&Object.keys(h.encodings[0]).length===0)&&(h.encodings=o,d.sendEncodings=o,this.setParametersPromises.push(d.setParameters(h).then(()=>{delete d.sendEncodings}).catch(()=>{delete d.sendEncodings})))}return l})}function yx(A){if(typeof A!="object"||!A.RTCRtpSender)return;const t=A.RTCRtpSender.prototype.getParameters;t&&(A.RTCRtpSender.prototype.getParameters=function(){const o=t.apply(this,arguments);return"encodings"in o||(o.encodings=[].concat(this.sendEncodings||[{}])),o})}function Dx(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const t=A.RTCPeerConnection.prototype.createOffer;A.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function Sx(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const t=A.RTCPeerConnection.prototype.createAnswer;A.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var vx=Object.freeze({__proto__:null,shimOnTrack:Qx,shimPeerConnection:e0,shimSenderGetStats:px,shimReceiverGetStats:Db,shimRemoveStream:mx,shimRTCDataChannel:Sb,shimAddTransceiver:fx,shimGetParameters:yx,shimCreateOffer:Dx,shimCreateAnswer:Sx,shimGetUserMedia:Bx,shimGetDisplayMedia:function(A,t){A.navigator.mediaDevices&&"getDisplayMedia"in A.navigator.mediaDevices||A.navigator.mediaDevices&&(A.navigator.mediaDevices.getDisplayMedia=function(o){if(!o||!o.video){const a=new DOMException("getDisplayMedia without video constraints is undefined");return a.name="NotFoundError",a.code=8,Promise.reject(a)}return o.video===!0?o.video={mediaSource:t}:o.video.mediaSource=t,A.navigator.mediaDevices.getUserMedia(o)})}});function Mx(A){if(typeof A=="object"&&A.RTCPeerConnection){if("getLocalStreams"in A.RTCPeerConnection.prototype||(A.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in A.RTCPeerConnection.prototype)){const t=A.RTCPeerConnection.prototype.addTrack;A.RTCPeerConnection.prototype.addStream=function(o){this._localStreams||(this._localStreams=[]),this._localStreams.includes(o)||this._localStreams.push(o),o.getAudioTracks().forEach(a=>t.call(this,a,o)),o.getVideoTracks().forEach(a=>t.call(this,a,o))},A.RTCPeerConnection.prototype.addTrack=function(o,...a){return a&&a.forEach(l=>{this._localStreams?this._localStreams.includes(l)||this._localStreams.push(l):this._localStreams=[l]}),t.apply(this,arguments)}}"removeStream"in A.RTCPeerConnection.prototype||(A.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const o=this._localStreams.indexOf(t);if(o===-1)return;this._localStreams.splice(o,1);const a=t.getTracks();this.getSenders().forEach(l=>{a.includes(l.track)&&this.removeTrack(l)})})}}function Rx(A){if(typeof A=="object"&&A.RTCPeerConnection&&("getRemoteStreams"in A.RTCPeerConnection.prototype||(A.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in A.RTCPeerConnection.prototype))){Object.defineProperty(A.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(o){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=o),this.addEventListener("track",this._onaddstreampoly=a=>{a.streams.forEach(l=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(l))return;this._remoteStreams.push(l);const d=new Event("addstream");d.stream=l,this.dispatchEvent(d)})})}});const t=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(){const o=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(a){a.streams.forEach(l=>{if(o._remoteStreams||(o._remoteStreams=[]),o._remoteStreams.indexOf(l)>=0)return;o._remoteStreams.push(l);const d=new Event("addstream");d.stream=l,o.dispatchEvent(d)})}),t.apply(o,arguments)}}}function vb(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const t=A.RTCPeerConnection.prototype,o=t.createOffer,a=t.createAnswer,l=t.setLocalDescription,d=t.setRemoteDescription,h=t.addIceCandidate;t.createOffer=function(S,L){const V=arguments.length>=2?arguments[2]:arguments[0],H=o.apply(this,[V]);return L?(H.then(S,L),Promise.resolve()):H},t.createAnswer=function(S,L){const V=arguments.length>=2?arguments[2]:arguments[0],H=a.apply(this,[V]);return L?(H.then(S,L),Promise.resolve()):H};let y=function(S,L,V){const H=l.apply(this,[S]);return V?(H.then(L,V),Promise.resolve()):H};t.setLocalDescription=y,y=function(S,L,V){const H=d.apply(this,[S]);return V?(H.then(L,V),Promise.resolve()):H},t.setRemoteDescription=y,y=function(S,L,V){const H=h.apply(this,[S]);return V?(H.then(L,V),Promise.resolve()):H},t.addIceCandidate=y}function Mb(A){const t=A&&A.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const o=t.mediaDevices,a=o.getUserMedia.bind(o);t.mediaDevices.getUserMedia=l=>a(_x(l))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(o,a,l){t.mediaDevices.getUserMedia(o).then(a,l)}.bind(t))}function _x(A){return A&&A.video!==void 0?Object.assign({},A,{video:Bb(A.video)}):A}function Tx(A){if(!A.RTCPeerConnection)return;const t=A.RTCPeerConnection;A.RTCPeerConnection=function(o,a){if(o&&o.iceServers){const l=[];for(let d=0;dt.generateCertificate})}function Nx(A){typeof A=="object"&&A.RTCTrackEvent&&"receiver"in A.RTCTrackEvent.prototype&&!("transceiver"in A.RTCTrackEvent.prototype)&&Object.defineProperty(A.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function t0(A){const t=A.RTCPeerConnection.prototype.createOffer;A.RTCPeerConnection.prototype.createOffer=function(o){if(o){o.offerToReceiveAudio!==void 0&&(o.offerToReceiveAudio=!!o.offerToReceiveAudio);const a=this.getTransceivers().find(d=>d.receiver.track.kind==="audio");o.offerToReceiveAudio===!1&&a?a.direction==="sendrecv"?a.setDirection?a.setDirection("sendonly"):a.direction="sendonly":a.direction==="recvonly"&&(a.setDirection?a.setDirection("inactive"):a.direction="inactive"):o.offerToReceiveAudio!==!0||a||this.addTransceiver("audio",{direction:"recvonly"}),o.offerToReceiveVideo!==void 0&&(o.offerToReceiveVideo=!!o.offerToReceiveVideo);const l=this.getTransceivers().find(d=>d.receiver.track.kind==="video");o.offerToReceiveVideo===!1&&l?l.direction==="sendrecv"?l.setDirection?l.setDirection("sendonly"):l.direction="sendonly":l.direction==="recvonly"&&(l.setDirection?l.setDirection("inactive"):l.direction="inactive"):o.offerToReceiveVideo!==!0||l||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Gx(A){typeof A!="object"||A.AudioContext||(A.AudioContext=A.webkitAudioContext)}var bx=Object.freeze({__proto__:null,shimLocalStreamsAPI:Mx,shimRemoteStreamsAPI:Rx,shimCallbacksAPI:vb,shimGetUserMedia:Mb,shimConstraints:_x,shimRTCIceServerUrls:Tx,shimTrackEventTransceiver:Nx,shimCreateOfferLegacy:t0,shimAudioContext:Gx}),kx={exports:{}};(function(A){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(o){return o.trim().split(` +`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(M)),this._worker.postMessage({type:Er,url:B})}send(B){var M,G;try{(M=this._worker)===null||M===void 0||M.postMessage({type:On,data:B})}catch(O){(G=this._onSendFail)===null||G===void 0||G.call(this,O)}}bindSocketHandlers(B){const{onOpen:M,onMessage:G,onClose:O,onError:z,onSendFail:X}=B;if(this._worker){const cA={[yn]:M,[ce]:G,[ot]:O,[Zt]:z,[Ho]:X};this._onSendFail=X,this._worker.onmessage=DA=>{var GA;const{type:KA}=DA?.data||{};typeof cA[KA]=="function"&&((GA=cA[KA])===null||GA===void 0||GA.call(cA,DA?.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:Mg}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class WI{}var gn,ro=new class{constructor(){this._store=new Map}get(p){return this._store.get(p)}getStorage(p){return Fi?ii?my.getStorageSync({key:p}).data:no.getStorageSync(p):this._canUseLocalStorage()?localStorage.getItem(p):{}}set(p,B){const M=this._store.get(p)||{};B instanceof Map?this._store.set(p,B):this._store.set(p,Object.assign(Object.assign({},M),B))}setStorage(p,B){Fi?ii?my.setStorageSync({key:p,data:JSON.stringify(B)}):no.setStorageSync(p,JSON.stringify(B)):this._canUseLocalStorage()&&localStorage.setItem(p,JSON.stringify(B))}clear(p){typeof p=="string"?this._store.set(p,{}):this._store.clear()}clearLocalStorage(p){this._canUseLocalStorage()&&(typeof p=="string"?localStorage.setItem(p,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return typeof window<"u"&&navigator&&navigator.cookieEnabled&&localStorage}};class Mc{connectSocket(B){return this._socket=no.connectSocket({url:B,header:{"content-type":"application/json"},multiple:!0,complete:()=>{}}),this._socket}send(B){var M;(M=this._socket)===null||M===void 0||M.send({data:B,fail:this._onSendFail})}bindSocketHandlers(B){const{onOpen:M,onMessage:G,onClose:O,onError:z,onSendFail:X}=B;this._socket&&(this._socket.onClose(O),this._socket.onOpen(M),this._socket.onMessage(cA=>G(cA?.data)),this._socket.onError(()=>z),this._onSendFail=X)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}(function(p){p[p.CONNECTED=0]="CONNECTED",p[p.CONNECTING=1]="CONNECTING",p[p.DISCONNECTED=2]="DISCONNECTED"})(gn||(gn={}));class cg{constructor(B){this._url="",this._readyState=gn.DISCONNECTED,this._url=B,this._id=b(),this._emitter=new Ls,ii?this._socket=new Mc:Xe||ao||pt||Je||ki||Pt?this._socket=new ts({onError:this._onError.bind(this)}):jn?this._socket=new WI:this._canUseWebWorker()?this._socket=new Ba:this._socket=new vc,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[gn.CONNECTED,gn.CONNECTING].includes(this._readyState)||(this._readyState=gn.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(B){this._readyState!==gn.CONNECTED?this.reconnect():this._socket.send(B)}reconnect(){[gn.CONNECTED,gn.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(B,M,G){this._emitter.on(B,M,G)}off(B,M,G){this._emitter.off(B,M,G)}isConnected(){return this._readyState===gn.CONNECTED}disconnect(){this._readyState=gn.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(B){this._readyState===gn.CONNECTING&&(this._readyState=gn.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:B}))}_onMessage(B){this._emitter.emit("message",B)}_onClose(B){this._readyState=gn.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:B})}_onError(B){this._readyState=gn.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:B})}_onSendFail(B){this._readyState=gn.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:B})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}_canUseWebWorker(){const B=ro.get("cloudConfig")||{};return(n(B.isWorkerEnabled)||B.isWorkerEnabled==="1")&&wo}}const Rg={[Ye.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[Ye.KOREA]:[[3e7,4e7],[173e7,174e7]],[Ye.GERMANY]:[[4e7,5e7],[174e7,175e7]],[Ye.IND]:[[5e7,6e7],[175e7,176e7]],[Ye.JPN]:[[6e7,7e7],[176e7,177e7]],[Ye.USA]:[[7e7,8e7],[177e7,178e7]],[Ye.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[Ye.KSA]:[[9e7,1e8],[179e7,18e8]]};function Qa(p){var B;if(!((B=ro.get("instance"))===null||B===void 0)&&B.oversea)return Ye.OVERSEA;for(const M of Object.keys(Rg))for(const[G,O]of Rg[M])if(p>=G&&p`${re}=${KA[re]}`).join("&"));var KA;return M?`${p}/binfo?${GA}&compress=gzip`:`${p}/info?${GA}`}function is(p){const B=ro.get("instance"),{sdkAppId:M,testEnv:G,proxyServer:O}=B,z=Qa(M);if(G)return Xs(We.TEST[z].DEFAULT,{isBinary:p});if(!tn(O))return Xs(O,{isBinary:p});const X=We.PRODUCTION[z],cA=Ai&&X.ANYCAST,DA=Ai,GA=!!X.BACKUP_CN;return Xs({[Fo.INITIAL]:()=>(Uo=Fo.DEFAULT,X.DEFAULT),[Fo.DEFAULT]:()=>(Uo=Fo.IPV6,X.IPV6),[Fo.IPV6]:()=>(Uo=Fo.BACKUP,X.BACKUP),[Fo.BACKUP]:()=>DA?(Uo=Fo.BACKUP_WEB_ONLY,function(KA){const re=Math.floor(10001*Math.random())+1e4;return KA.replace("*",String(re))}(X.BACKUP_WEB_ONLY)):GA?(Uo=Fo.BACKUP_CN,X.BACKUP_CN):cA?(Uo=Fo.ANYCAST,X.ANYCAST):X.DEFAULT,[Fo.BACKUP_WEB_ONLY]:()=>GA?(Uo=Fo.BACKUP_CN,X.BACKUP_CN):cA?(Uo=Fo.ANYCAST,X.ANYCAST):X.DEFAULT,[Fo.BACKUP_CN]:()=>(Uo=cA?Fo.ANYCAST:Fo.DEFAULT,X[Uo]),[Fo.ANYCAST]:()=>(Uo=Fo.DEFAULT,X.ANYCAST="",X.DEFAULT)}[Uo](),{isBinary:p})}var wg=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(p,B){const M=Date.now(),G=M-p;this._timeOffsetWithServer=B+G-M}};const Rc=16;var ws=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(p){const{id:B}=p;this.removeTask(B),this._tasks.push(p),this._taskMap.set(B,p),this._sort(),this._scheduleNextTask()}_createTask(p){const{id:B,callback:M,context:G,isOnce:O=!1,intervalMs:z=Rc}=p,X=Math.max(z,Rc);return{id:B,nextExecuteTime:Date.now()+X,intervalMs:z,callback:M,context:G,isOnce:O}}addTask(p){const B=this._createTask(p);this._addTaskToScheduler(B)}addOnceTask(p){const B=this._createTask(Object.assign(Object.assign({},p),{isOnce:!0}));this._addTaskToScheduler(B)}removeTask(p){const B=this._tasks.findIndex(M=>M.id===p);B>-1&&(this._tasks.splice(B,1),this._taskMap.delete(p),this._scheduleNextTask())}updateTaskInterval(p,B){const M=this._taskMap.get(p);M&&(M.intervalMs=B,M.nextExecuteTime=Date.now()+B,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((p,B)=>p.nextExecuteTime-B.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const p=this._tasks[0];if(p){const B=Math.max(0,p.nextExecuteTime-Date.now());this._timer=setTimeout(()=>this._execute(),B)}}_execute(){const p=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=p;){const B=this._tasks[0];try{B.context?B.callback.call(B.context):B.callback(),B.isOnce?this.removeTask(B.id):(B.nextExecuteTime=p+B.intervalMs,this._sort())}catch(M){console.warn(`Task ${B.id} execution failed:`,M),B.isOnce&&this.removeTask(B.id)}}this._scheduleNextTask()}};function Fa(p){const B=[];for(let M=0;M=55296&&G<=56319){const O=p.charCodeAt(++M)-56320+(G-55296<<10)+65536;B.push(240|O>>18,128|O>>12&63,128|O>>6&63,128|63&O)}else G<=127?B.push(G):G<=2047?B.push(192|G>>6,128|63&G):B.push(224|G>>12,128|G>>6&63,128|63&G)}return new Uint8Array(B)}function Qs(p){const B=Array.isArray(p)?[]:Object.create(null);for(const M in p)Object.prototype.hasOwnProperty.call(p,M)&&_(M)&&p[M]!=null&&(p[M]===null||typeof p[M]!="object"?B[M]=p[M]:B[M]=Qs(p[M]));return B}function Tn(p,B){if(CA.includes(p))return 0;const M=Fa(JSON.stringify(B));let G=4294967295;const{length:O}=M;for(let z=0;z>>=1:G=G>>>1^3988292384}return(4294967295^G)>>>0}function pa(p){const{servcmd:B,data:M}=p,G=function(z){const X=ro.get("login")||{},cA=ro.get("instance")||{};return{servcmd:z,ver:"v4",platform:jA,websdkappid:537048168,websdkversion:"1.7.3",a2:X.a2Key||void 0,tinyid:X.tinyID||void 0,status_instid:X.statusInstanceId||0,sdkappid:cA.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:X.a2Key?void 0:X.userId,usersig:X.a2Key?void 0:X.userSig,sdkability:478343027,sdkability_ext:gA(""),cappid:cA.applicationID||0,tjgID:"",seq:Ta(),cs:0}}(B),O=Qs(M);return G.cs=Tn(B,O),{head:G,body:O}}function _s(p){const{servcmd:B,data:M}=p,G=function(z){const X=ro.get("login")||{},cA=ro.get("instance")||{};return{servcmd:z,ver:"v4",platform:jA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:cA.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:X.statusInstanceId||0,sdkability:478343027,sdkability_ext:gA(""),cappid:cA.applicationID||0,seq:Ta(),cs:0}}(B),O=Qs(M);return G.cs=Tn(B,O),{head:G,body:O}}let Oa=b();function Ta(){return Oa=Oa<2415919103?Oa+1:b(),Oa}function $(){var p;const B=ro.get("login")||{},M=ro.get("instance")||{};return{sdk_type:30,sdk_app_id:M.sdkAppId,sdk_version:"1.6.18",tiny_id:Number(B.tinyID),user_id:B.userId||((p=ro.get("webPush"))===null||p===void 0?void 0:p.userId),platform:jA,instance_id:M.instanceId,trace_id:new Date().getTime()}}var j,RA=Object.freeze({__proto__:null,calcBodyCRC:Tn,filterProtocolDataInvalidFields:Qs,generateCosSpecifiedData:function(p){const{servcmd:B,data:M}=p,G=function(z){const X=ro.get("login")||{},cA=ro.get("instance")||{};return{servcmd:z,ver:"v4",platform:jA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:cA.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:X.userId,usersig:X.userSig,status_instid:X.statusInstanceId||0,sdkability:478343027,sdkability_ext:gA(""),cappid:cA.applicationID||0,seq:Ta(),cs:0}}(B),O=Qs(M);return G.cs=Tn(B,O),{head:G,body:O}},generateProtocolData:pa,generateSSOLogProtocolData:_s,generateSequence:Ta,getCommonHead:$,getHostSite:Qa,taskScheduler:ws,timeManager:wg});(function(p){p[p.info=4]="info",p[p.warning=5]="warning",p[p.error=6]="error"})(j||(j={}));const ZA={method:"extension",networkType:"network_type",eventType:"event_type",code:"error_code",message:"error_message",moreMessage:"more_message",duplicate:"duplicate",costTime:"cost_time",level:"level",uiPlatform:"ui_platform",timestamp:"timestamp"};class ne{constructor(B){this.level=j.info,this._canSendLog=!0,this._logCreatedAt=wg.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();const{method:M,eventType:G=0,message:O="",costTime:z=0,error:X,uiPlatform:cA,moreMessage:DA="",code:GA=0,startTime:KA=0}=B||{};this.eventType=G,this.method=M,this.message=O,this.costTime=z,this.moreMessage=`${DA} startTime:${KA}`,this.code=GA,X&&this.setError(X),tn(cA)||(this.uiPlatform=cA)}setMoreMessage(B){this.moreMessage=`${this.moreMessage} ${B}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=wg.getTimeOffsetWithServer()}end(B=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=wg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),B&&this._ssoLogModule.uploadSSOLogData())}setError(B){var M;return B instanceof Error?this._canSendLog?(!((M=ro.get("netWorkMonitor"))===null||M===void 0)&&M.isNetworkOnline&&(B.errorCode&&(this.code=B.errorCode),B.errorMessage&&this.setMoreMessage(B.errorMessage)),this.level=j.error,this):this:(console.warn("SSOLogData.setError value not instanceof Error, please check!"),this)}setLogInfo(B){return Object.keys(B).forEach(M=>{Object.keys(ZA).includes(M)&&(this[M]=B[M])}),this}setSSOLogModule(B){this._ssoLogModule=B}_convertSSOLogDataKeyToServe(){const B={};return Object.keys(this).forEach(M=>{const G=M;ZA[G]&&(B[ZA[G]]=this[G])}),B}_getUiPlatform(){var B;const M=(B=ro.get("instance"))===null||B===void 0?void 0:B.scene;if(typeof M=="string"){const G=Number(M);return isNaN(G)?void 0:G}}_getSDKEdition(){var B;return(B=ro.get("instance"))===null||B===void 0?void 0:B.sdkEdition}}var De;(function(p){p.RECONNECTED="reconnected",p.CLOUD_CONFIG_UPDATE="cloud_config_update",p.SOCKET_DISCONNECTED="socket_disconnected"})(De||(De={}));var Ke=De;const qe=20,Et=6e4,ft=[4,5,6],Nt="report-logger";var Kt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=qe,this._maxThreshold=100,this._waitingTime=Et,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=IA.DEBUG,this._throttleConfig={global:{throttleTime:se,maxCount:WA},single:{throttleTime:Ae,maxCount:HA}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,es.subscribeInnerEvent(Ke.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),ws.addTask({id:Nt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(p){const{evt_rpt_threshold:B=qe,evt_rpt_waiting:M=Et,evt_rpt_level:G=ft,evt_rpt_sdkappid_bl:O="",evt_rpt_tinyid_wl:z="",evt_rpt_global_throttle_time:X=se,evt_rpt_global_throttle_count:cA=WA,evt_rpt_single_throttle_time:DA=Ae,evt_rpt_single_throttle_count:GA=HA}=p||{};this._sdkAppIdBlackList=O.split(",").map(KA=>Number(KA)),this._waitingTime=Number(M),this._minThreshold=B,this._reportLevel=G,this._tinyIdWhiteList=z.split(","),this._throttleConfig={global:{throttleTime:X,maxCount:cA},single:{throttleTime:DA,maxCount:GA}}}createSSOLogData(p){const B=new ne(p);return B.setSSOLogModule(this),this._ssoLogMap.set(p.method,B),B}getSSOLogData(p){return this._ssoLogMap.get(p)||{}}pushToLogQueue(p){p&&(this._logQueue.push(p),this._shouldUploadImmediately()&&this.uploadSSOLogData())}setLogLevel(p){[IA.DEBUG,IA.ERROR,IA.INFO,IA.NONE,IA.WARN].includes(p)&&(this._logLevel=p)}debug(p,B="",M){this._log(IA.DEBUG,p,B,M)}info(p,B="",M){this._log(IA.INFO,p,B,M)}warn(p,B="",M){this._log(IA.WARN,p,B,M)}error(p,B="",M){this._log(IA.ERROR,p,B,M)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this.uploadSSOLogData()}uploadSSOLogData(){return mA(this,void 0,void 0,function*(){if(this._logQueue.length===0)return;const p=this._logQueue.slice();this._logQueue=[];try{const B=this._filterLogs(p);if(B.length===0)return void(this._lastReportAt=Date.now());const M={Header:$(),Event:B};tn(M.Header.user_id)||(yield function(G){const O="imopenstat.tim_web_report_v2",z=_s({servcmd:O,data:G}),X=`${z.head.seq}${O}`;return Gl.sendPacket(z,{requestId:X})}(M))}catch(B){this._requeueFailedLogs(p),this.debug("uploadSSOLogData",_n(B))}finally{this._lastReportAt=Date.now()}})}_requeueFailedLogs(p){this._logQueue=p.concat(this._logQueue);const B=this._logQueue.length-200;B>0&&(this._logQueue.splice(0,B),this.debug("uploadSSOLogData",`log queue overflow, dropped ${B} oldest logs`))}_savePlatFormInfo(){var p,B;if(Xe){const M=(B=(p=wx.getAccountInfoSync)===null||p===void 0?void 0:p.call(wx))===null||B===void 0?void 0:B.miniProgram;if(M){const{appId:G,envVersion:O}=M;ro.set("instance",{appId:G,envVersion:O})}}else Ai&&ro.set("instance",{href:window.location.href})}_filterLogs(p){const{tinyID:B}=ro.get("login")||{},{sdkAppId:M}=ro.get("instance")||{};return this._sdkAppIdBlackList.includes(M)&&!this._tinyIdWhiteList.includes(B)?[]:p.filter(G=>this._reportLevel.includes(G.level))}_checkThrottle(p){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(p)}_checkGlobalThrottle(){const p=Date.now();if(p-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=p;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(p){const B=Date.now(),M=this._singleThrottleMap.get(p);return M?B-M.startTime>=this._throttleConfig.single.throttleTime?(M.count=1,M.startTime=B,!1):M.count>=this._throttleConfig.single.maxCount||(M.count++,!1):(this._singleThrottleMap.set(p,{count:1,startTime:B}),!1)}_shouldLog(p){return p>=this._logLevel&&this._logLevel!==IA.NONE}_shouldReport(p){return this._reportLevel.includes(qA[p])}_formatLog(p,B,M,G){const O=new Date,z=`${O.getHours()}:${O.getMinutes()}:${O.getSeconds()}:${O.getMilliseconds()}`,X=`<${IA[p]}>`;return Gt||Fi?[`${oA} [${z}] ${X} [${B}] ${M}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",oA,"",`[${z}] ${X} [${B}] ${M} params: ${_n(G)}`]}_log(p,B,M,G){if(this._shouldLog(p)){const O=this._formatLog(p,B,M,G);vA[p].apply(console,O)}if(this._shouldReport(p)){const O=this._getThrottleKey(B,M,G);this._checkThrottle(O)||this.createSSOLogData(Object.assign(Object.assign({message:M},G),{method:B})).end()}}_getThrottleKey(p,B,M){const G=`${p}${B}${_n(Object.assign(Object.assign({},M),{costTime:""}))}`,O=Fa(JSON.stringify(G));let z=4294967295;const{length:X}=O;for(let cA=0;cA>>=1:z=z>>>1^3988292384}return`${(4294967295^z)>>>0}`}reset(){console.log("SSO_LOG_MODULE.reset"),ws.removeTask(Nt),es.unSubscribeInnerEvent(Ke.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=qe,this._maxThreshold=100,this._waitingTime=Et,this._logQueue=[],this._logLevel=IA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const di=15e3,Bt="Channel",Jt="channel_schedule_task",$i="channel_reconnect_task",eo="connected",os="connecting",Ti="disconnected",on=1e3,_g="network_status_change",dr="activity_status_change",Mr="send_fail",js="reconnect_failed",Nl="socket_error",ns="socket_close";function uI(p){return uI=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(B){return typeof B}:function(B){return B&&typeof Symbol=="function"&&B.constructor===Symbol&&B!==Symbol.prototype?"symbol":typeof B},uI(p)}function ec(p){throw new Error('Could not dynamically require "'+p+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var wc,Tu={exports:{}},Na=(wc||(wc=1,function(p){p.exports=function B(M,G,O){function z(DA,GA){if(!G[DA]){if(!M[DA]){if(!GA&&ec)return ec(DA);if(X)return X(DA,!0);var KA=new Error("Cannot find module '"+DA+"'");throw KA.code="MODULE_NOT_FOUND",KA}var re=G[DA]={exports:{}};M[DA][0].call(re.exports,function(Qe){return z(M[DA][1][Qe]||Qe)},re,re.exports,B,M,G,O)}return G[DA].exports}for(var X=ec,cA=0;cA>>6:(Qe<65536?re[dt++]=224|Qe>>>12:(re[dt++]=240|Qe>>>18,re[dt++]=128|Qe>>>12&63),re[dt++]=128|Qe>>>6&63),re[dt++]=128|63&Qe);return re},G.buf2binstring=function(KA){return GA(KA,KA.length)},G.binstring2buf=function(KA){for(var re=new O.Buf8(KA.length),Qe=0,At=re.length;Qe>10&1023,Wt[At++]=56320|1023<)}return GA(Wt,At)},G.utf8border=function(KA,re){var Qe;for((re=re||KA.length)>KA.length&&(re=KA.length),Qe=re-1;0<=Qe&&(192&KA[Qe])==128;)Qe--;return Qe<0||Qe===0?re:Qe+cA[KA[Qe]]>re?Qe:re}},{"./common":1}],3:[function(B,M,G){M.exports=function(O,z,X,cA){for(var DA=65535&O,GA=O>>>16&65535,KA=0;X!==0;){for(X-=KA=2e3>>1:z>>>1;X[cA]=z}return X}();M.exports=function(z,X,cA,DA){var GA=O,KA=DA+cA;z^=-1;for(var re=DA;re>>8^GA[255&(z^X[re])];return-1^z}},{}],6:[function(B,M,G){M.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(B,M,G){M.exports=function(O,z){var X,cA,DA,GA,KA,re,Qe,At,lt,dt,xt,Wt,Ki,Eo,so,hi,qo,cn,yi,to,rs,be,bt,OA,oi;X=O.state,cA=O.next_in,OA=O.input,DA=cA+(O.avail_in-5),GA=O.next_out,oi=O.output,KA=GA-(z-O.avail_out),re=GA+(O.avail_out-257),Qe=X.dmax,At=X.wsize,lt=X.whave,dt=X.wnext,xt=X.window,Wt=X.hold,Ki=X.bits,Eo=X.lencode,so=X.distcode,hi=(1<>>=yi=cn>>>24,Ki-=yi,(yi=cn>>>16&255)==0)oi[GA++]=65535&cn;else{if(!(16&yi)){if(!(64&yi)){cn=Eo[(65535&cn)+(Wt&(1<>>=yi,Ki-=yi),Ki<15&&(Wt+=OA[cA++]<>>=yi=cn>>>24,Ki-=yi,!(16&(yi=cn>>>16&255))){if(!(64&yi)){cn=so[(65535&cn)+(Wt&(1<>>=yi,Ki-=yi,(yi=GA-KA)>3,Wt&=(1<<(Ki-=to<<3))-1,O.next_in=cA,O.next_out=GA,O.avail_in=cA>>24&255)+(be>>>8&65280)+((65280&be)<<8)+((255&be)<<24)}function Wt(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new O.Buf16(320),this.work=new O.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Ki(be){var bt;return be&&be.state?(bt=be.state,be.total_in=be.total_out=bt.total=0,be.msg="",bt.wrap&&(be.adler=1&bt.wrap),bt.mode=At,bt.last=0,bt.havedict=0,bt.dmax=32768,bt.head=null,bt.hold=0,bt.bits=0,bt.lencode=bt.lendyn=new O.Buf32(lt),bt.distcode=bt.distdyn=new O.Buf32(dt),bt.sane=1,bt.back=-1,re):Qe}function Eo(be){var bt;return be&&be.state?((bt=be.state).wsize=0,bt.whave=0,bt.wnext=0,Ki(be)):Qe}function so(be,bt){var OA,oi;return be&&be.state?(oi=be.state,bt<0?(OA=0,bt=-bt):(OA=1+(bt>>4),bt<48&&(bt&=15)),bt&&(bt<8||15=si.wsize?(O.arraySet(si.window,bt,OA-si.wsize,si.wsize,0),si.wnext=0,si.whave=si.wsize):(oi<(ms=si.wsize-si.wnext)&&(ms=oi),O.arraySet(si.window,bt,OA-oi,ms,si.wnext),(oi-=ms)?(O.arraySet(si.window,bt,OA-oi,oi,0),si.wnext=oi,si.whave=si.wsize):(si.wnext+=ms,si.wnext===si.wsize&&(si.wnext=0),si.whave>>8&255,OA.check=X(OA.check,Ue,2,0),St=yt=0,OA.mode=2;break}if(OA.flags=0,OA.head&&(OA.head.done=!1),!(1&OA.wrap)||(((255&yt)<<8)+(yt>>8))%31){be.msg="incorrect header check",OA.mode=30;break}if((15&yt)!=8){be.msg="unknown compression method",OA.mode=30;break}if(St-=4,yA=8+(15&(yt>>>=4)),OA.wbits===0)OA.wbits=yA;else if(yA>OA.wbits){be.msg="invalid window size",OA.mode=30;break}OA.dmax=1<>8&1),512&OA.flags&&(Ue[0]=255&yt,Ue[1]=yt>>>8&255,OA.check=X(OA.check,Ue,2,0)),St=yt=0,OA.mode=3;case 3:for(;St<32;){if(Ni===0)break A;Ni--,yt+=oi[si++]<>>8&255,Ue[2]=yt>>>16&255,Ue[3]=yt>>>24&255,OA.check=X(OA.check,Ue,4,0)),St=yt=0,OA.mode=4;case 4:for(;St<16;){if(Ni===0)break A;Ni--,yt+=oi[si++]<>8),512&OA.flags&&(Ue[0]=255&yt,Ue[1]=yt>>>8&255,OA.check=X(OA.check,Ue,2,0)),St=yt=0,OA.mode=5;case 5:if(1024&OA.flags){for(;St<16;){if(Ni===0)break A;Ni--,yt+=oi[si++]<>>8&255,OA.check=X(OA.check,Ue,2,0)),St=yt=0}else OA.head&&(OA.head.extra=null);OA.mode=6;case 6:if(1024&OA.flags&&(Ni<(io=OA.length)&&(io=Ni),io&&(OA.head&&(yA=OA.head.extra_len-OA.length,OA.head.extra||(OA.head.extra=new Array(OA.head.extra_len)),O.arraySet(OA.head.extra,oi,si,io,yA)),512&OA.flags&&(OA.check=X(OA.check,oi,io,si)),Ni-=io,si+=io,OA.length-=io),OA.length))break A;OA.length=0,OA.mode=7;case 7:if(2048&OA.flags){if(Ni===0)break A;for(io=0;yA=oi[si+io++],OA.head&&yA&&OA.length<65536&&(OA.head.name+=String.fromCharCode(yA)),yA&&io>9&1,OA.head.done=!0),be.adler=OA.check=0,OA.mode=12;break;case 10:for(;St<32;){if(Ni===0)break A;Ni--,yt+=oi[si++]<>>=7&St,St-=7&St,OA.mode=27;break}for(;St<3;){if(Ni===0)break A;Ni--,yt+=oi[si++]<>>=1)){case 0:OA.mode=14;break;case 1:if(to(OA),OA.mode=20,bt!==6)break;yt>>>=2,St-=2;break A;case 2:OA.mode=17;break;case 3:be.msg="invalid block type",OA.mode=30}yt>>>=2,St-=2;break;case 14:for(yt>>>=7&St,St-=7&St;St<32;){if(Ni===0)break A;Ni--,yt+=oi[si++]<>>16^65535)){be.msg="invalid stored block lengths",OA.mode=30;break}if(OA.length=65535&yt,St=yt=0,OA.mode=15,bt===6)break A;case 15:OA.mode=16;case 16:if(io=OA.length){if(Ni>>=5,St-=5,OA.ndist=1+(31&yt),yt>>>=5,St-=5,OA.ncode=4+(15&yt),yt>>>=4,St-=4,286>>=3,St-=3}for(;OA.have<19;)OA.lens[de[OA.have++]]=0;if(OA.lencode=OA.lendyn,OA.lenbits=7,ee={bits:OA.lenbits},NA=DA(0,OA.lens,0,19,OA.lencode,0,OA.work,ee),OA.lenbits=ee.bits,NA){be.msg="invalid code lengths set",OA.mode=30;break}OA.have=0,OA.mode=19;case 19:for(;OA.have>>16&255,Sa=65535&he,!((In=he>>>24)<=St);){if(Ni===0)break A;Ni--,yt+=oi[si++]<>>=In,St-=In,OA.lens[OA.have++]=Sa;else{if(Sa===16){for(Ne=In+2;St>>=In,St-=In,OA.have===0){be.msg="invalid bit length repeat",OA.mode=30;break}yA=OA.lens[OA.have-1],io=3+(3&yt),yt>>>=2,St-=2}else if(Sa===17){for(Ne=In+3;St>>=In)),yt>>>=3,St-=3}else{for(Ne=In+7;St>>=In)),yt>>>=7,St-=7}if(OA.have+io>OA.nlen+OA.ndist){be.msg="invalid bit length repeat",OA.mode=30;break}for(;io--;)OA.lens[OA.have++]=yA}}if(OA.mode===30)break;if(OA.lens[256]===0){be.msg="invalid code -- missing end-of-block",OA.mode=30;break}if(OA.lenbits=9,ee={bits:OA.lenbits},NA=DA(GA,OA.lens,0,OA.nlen,OA.lencode,0,OA.work,ee),OA.lenbits=ee.bits,NA){be.msg="invalid literal/lengths set",OA.mode=30;break}if(OA.distbits=6,OA.distcode=OA.distdyn,ee={bits:OA.distbits},NA=DA(KA,OA.lens,OA.nlen,OA.ndist,OA.distcode,0,OA.work,ee),OA.distbits=ee.bits,NA){be.msg="invalid distances set",OA.mode=30;break}if(OA.mode=20,bt===6)break A;case 20:OA.mode=21;case 21:if(6<=Ni&&258<=yo){be.next_out=Dn,be.avail_out=yo,be.next_in=si,be.avail_in=Ni,OA.hold=yt,OA.bits=St,cA(be,qn),Dn=be.next_out,ms=be.output,yo=be.avail_out,si=be.next_in,oi=be.input,Ni=be.avail_in,yt=OA.hold,St=OA.bits,OA.mode===12&&(OA.back=-1);break}for(OA.back=0;ua=(he=OA.lencode[yt&(1<>>16&255,Sa=65535&he,!((In=he>>>24)<=St);){if(Ni===0)break A;Ni--,yt+=oi[si++]<>oa)])>>>16&255,Sa=65535&he,!(oa+(In=he>>>24)<=St);){if(Ni===0)break A;Ni--,yt+=oi[si++]<>>=oa,St-=oa,OA.back+=oa}if(yt>>>=In,St-=In,OA.back+=In,OA.length=Sa,ua===0){OA.mode=26;break}if(32&ua){OA.back=-1,OA.mode=12;break}if(64&ua){be.msg="invalid literal/length code",OA.mode=30;break}OA.extra=15&ua,OA.mode=22;case 22:if(OA.extra){for(Ne=OA.extra;St>>=OA.extra,St-=OA.extra,OA.back+=OA.extra}OA.was=OA.length,OA.mode=23;case 23:for(;ua=(he=OA.distcode[yt&(1<>>16&255,Sa=65535&he,!((In=he>>>24)<=St);){if(Ni===0)break A;Ni--,yt+=oi[si++]<>oa)])>>>16&255,Sa=65535&he,!(oa+(In=he>>>24)<=St);){if(Ni===0)break A;Ni--,yt+=oi[si++]<>>=oa,St-=oa,OA.back+=oa}if(yt>>>=In,St-=In,OA.back+=In,64&ua){be.msg="invalid distance code",OA.mode=30;break}OA.offset=Sa,OA.extra=15&ua,OA.mode=24;case 24:if(OA.extra){for(Ne=OA.extra;St>>=OA.extra,St-=OA.extra,OA.back+=OA.extra}if(OA.offset>OA.dmax){be.msg="invalid distance too far back",OA.mode=30;break}OA.mode=25;case 25:if(yo===0)break A;if(io=qn-yo,OA.offset>io){if((io=OA.offset-io)>OA.whave&&OA.sane){be.msg="invalid distance too far back",OA.mode=30;break}io>OA.wnext?(io-=OA.wnext,Wr=OA.wsize-io):Wr=OA.wnext-io,io>OA.length&&(io=OA.length),cc=OA.window}else cc=ms,Wr=Dn-OA.offset,io=OA.length;for(yoqo?(yi=Wr[cc+dt[bt]],to=St[hg+dt[bt]]):(yi=96,to=0),Wt=1<>Dn)+(Ki-=Wt)]=cn<<24|yi<<16|to,Ki!==0;);for(Wt=1<>=1;if(Wt!==0?(yt&=Wt-1,yt+=Wt):yt=0,bt++,--qn[be]==0){if(be===oi)break;be=KA[re+dt[bt]]}if(ms{const cA=new Uint8Array(X).slice(4);let DA;try{DA=Na.inflate(cA,{to:"string"})}catch(GA){console.error("inflate error",GA)}return DA})(p.data):function(X){const cA=new Uint8Array(X);let DA="",GA=0;const{length:KA}=cA;for(;GA0)for(let lt=0;lt{var G;const{uplinkData:O,canResend:z,resolve:X,reject:cA,timeout:DA}=B;if(z){this._pendingRequests.set(M,{resolve:X,reject:cA,timestamp:Date.now(),uplinkData:O,timeout:DA,canResend:z});const GA=this._isBinarySupported?Fa(O).buffer:O;(G=this._socketAdapter)===null||G===void 0||G.send(GA)}else this._pendingRequests.delete(M)})}_onConnect(p){const{socketId:B,event:M={}}=p||{};this._connectionId=B,this._connectionEstablishedTime=Date.now();const G=Date.now()-this._connectionStartTime,O=`${Bt}.onConnect cost:${G} ms. socketID:${B} res:${JSON.stringify(M)}`;if(this._ssoLog({method:"onConnect",message:O}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const z=`${Bt}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:z}),es.emitInnerEvent(Ke.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:eo,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(p){const B=pa({servcmd:"openim.ws_msg_push_ack",data:{SessionData:p}});this.sendPacket(B)}_executeScheduledTaskIfReady(){return mA(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var p;return((p=this._socketAdapter)===null||p===void 0?void 0:p.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return mA(this,void 0,void 0,function*(){var p;const B=pa({servcmd:"heartbeat.alive",data:{}});try{const M=`${B.head.seq}${B.head.servcmd}`;yield this.sendPacket(B,{requestId:M,timeout:3e3})}catch(M){const G=(p=ro.get("netWorkMonitor"))===null||p===void 0?void 0:p.isNetworkOnline,O=`${Bt}.sendHeartbeat failed. isNetWorkOnline:${G} error: ${_n(M)}`;this._ssoLog({method:"sendHeartbeatError",message:O}),this._handleConnectStateChange({state:Ti,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return mA(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=ao?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(p){const B=`${Bt}.networkStatusChange ${JSON.stringify(p)}`;this._ssoLog({method:"networkStatusChange",message:B});const{isNetworkOnline:M,networkType:G}=p;M&&G!=="none"?this._handleConnectStateChange({state:eo,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:_g}):this._handleConnectStateChange({state:Ti,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:_g})}isPrivateNetWork(){const p=ro.get("instance")||{};return p.proxyServer&&!p.fileDownloadProxy}_handleConnectStateChange(p){const{state:B,shouldAttemptReconnect:M,shouldEmitEvent:G,reason:O}=p,z=`${Bt}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${M} shouldEmitEvent: ${G} reason: ${O}`;this._currentConnectState!==B&&(this._ssoLog({method:"handleConnectStateChange",message:z}),G&&(Kt.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${B}`),es.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:B}}),this._currentConnectState=B,B===Ti&&es.emitInnerEvent(Ke.SOCKET_DISCONNECTED)),M&&(this._resetReconnectDelay(),ws.addTask({id:$i,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(p){var B,M;const G=(M=(B=this._socketAdapter)===null||B===void 0?void 0:B._ws)===null||M===void 0?void 0:M.readyState,O=`${Bt}.activityStatusChange ${JSON.stringify(p)} readyState: ${G}`;Kt.debug("activityStatusChange",O),G===3&&this._handleConnectStateChange({state:Ti,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:dr})}_resetReconnectDelay(){var p;Kt.debug(`${Bt}._resetReconnectDelay`),ws.removeTask($i);const B=(p=ro.get("activityMonitor"))===null||p===void 0?void 0:p.isActive;this._intendedDelay=B?on:1e3}_scheduleReconnectWithBackoff(){var p;const B=(p=ro.get("activityMonitor"))===null||p===void 0?void 0:p.isActive;this._intendedDelay=B?Math.min(5e3,Math.max(on,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const M=new Date().toTimeString().slice(0,8),G=`${Bt}.scheduleReconnectWithBackoff timeStr: ${M} intendedDelay: ${this._intendedDelay}`;Kt.debug(G),this.reconnect(),ws.updateTaskInterval($i,this._intendedDelay)}_ssoLog(p){const{method:B,message:M}=p;Kt.info(B,M)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(p){mA(this,void 0,void 0,function*(){const B=p.split("/")[2];if(!B.startsWith("ws"))return;const M=`https://${B}/v3/netcheck/getconninfo?${p.slice(p.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield qi({method:"GET",url:M,data:{}})}catch(G){Kt.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${G.message}`)}})}(this._url),function(p){mA(this,void 0,void 0,function*(){const B=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${p.slice(p.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield qi({method:"GET",url:B,data:{}})}catch(M){Kt.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${M.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[p,B]of this._pendingRequests.entries()){const{reject:M,timestamp:G,timeout:O}=B;Date.now()-G>=O&&(this._pendingRequests.delete(p),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),M({errorCode:Zs,errorInfo:"NETWORK_TIMEOUT",data:{requestId:p}}))}}_updateIsBinarySupported(){var p;if(!((p=ro.get("instance"))===null||p===void 0)&&p.devMode)return void(this._isBinarySupported=!1);const B=Vo();if((ii||Xe&&B==="windows"||wn)&&(this._isBinarySupported=!1),ao){const{uniRuntimeVersion:M=""}=no.getSystemInfoSync();(function(G){const O=G.split(".").map(Number),[z=0,X=0,cA=0]=O;return z>2||!(z<2)&&(X>2||!(X<2)&&cA>=6)})(M)||(this._isBinarySupported=!1)}}_isCompressedData(p){const B=new Uint8Array(p);return B[0]===67&&B[1]===79&&B[2]===77&&B[3]===80}};const ve={init:function(p){ro.set("instance",p),Gl.init()},destroy:function(){Gl.dispose(),ro.clear(),ws.dispose()},notificationCenter:es,channel:Gl,store:ro,ssoLog:Kt,utils:$a,common:RA,constants:we},Se=p=>typeof p=="function";function Tg(p,B,M){const G=M||[];if(!p||!B)return!1;const O=Object.keys(p).filter(X=>!G.includes(X)),z=Object.keys(B).filter(X=>!G.includes(X));return O.length===z.length&&O.every(X=>!!B.hasOwnProperty(X)&&(typeof p[X]=="object"&&p[X]!==null?Tg(p[X],B[X],M):p[X]===B[X]))}var lg;(function(p){p.SDK_READY="sdkStateReady",p.SDK_NOT_READY="sdkStateNotReady",p.SDK_DESTROY="sdkDestroy",p.MESSAGE_RECEIVED="onMessageReceived",p.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",p.MESSAGE_MODIFIED="onMessageModified",p.MESSAGE_REVOKED="onMessageRevoked",p.MESSAGE_READ_BY_PEER="onMessageReadByPeer",p.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",p.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",p.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",p.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",p.CONVERSATION_LIST_UPDATED="onConversationListUpdated",p.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",p.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",p.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",p.GROUP_LIST_UPDATED="onGroupListUpdated",p.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",p.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",p.TOPIC_CREATED="onTopicCreated",p.TOPIC_DELETED="onTopicDeleted",p.TOPIC_UPDATED="onTopicUpdated",p.PROFILE_UPDATED="onProfileUpdated",p.USER_STATUS_UPDATED="onUserStatusUpdated",p.BLACKLIST_UPDATED="blacklistUpdated",p.FRIEND_LIST_UPDATED="onFriendListUpdated",p.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",p.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",p.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",p.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",p.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",p.KICKED_OUT="kickedOut",p.ERROR="error",p.NET_STATE_CHANGE="netStateChange",p.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",p.SERVER_CONFIG_UPDATED="onServerConfigUpdated",p.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated",p.WEB_PUSH_MESSAGE_RECEIVED="onWebPushMessageReceived",p.GROUP_ONLINE_MEMBER_COUNT_CHANGED="onGroupOnlineMemberCountChanged",p.RICH_STATUS_CHANGED="onRichStatusChanged"})(lg||(lg={}));var Ng,Ts=lg;(function(p){p.LOGOUT="logout",p.DESTROY="destroy",p.CLOUD_CONFIG_UPDATE="cloud_config_update",p.PROFILE_UPDATE="profile_updated",p.ERROR="error",p.RECONNECTED="reconnected",p.FORCE_OFFLINE="im_open_status.stat_forceoffline",p.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",p.OVERLOAD_PUSH="OverLoadPush.notify2",p.NEW_MESSAGE="new_message",p.MESSAGE_PUSH="im_open_push.msg_push",p.MESSAGE_DELETED="message_deleted",p.MESSAGE_REVOKED="message_revoked",p.MESSAGE_MODIFIED="message_modified",p.SOCKET_DISCONNECTED="socket_disconnected",p.CONVERSATION_UPDATED="conversation_updated",p.TOPIC_MESSAGE_DELETED="topic_message_deleted",p.TOPIC_MESSAGE_REVOKED="topic_message_revoked",p.TOPIC_MESSAGE_MODIFIED="topic_message_modified",p.TOPIC_NEW_MESSAGE="topic_new_message",p.QUALITY_STAT="quality_stat",p.SYNC_CONVERSATION_LIST="sync_conversation_list",p.HISTORY_MESSAGE_FETCHED="history_message_fetched"})(Ng||(Ng={}));var Rr,Ci=Ng;(function(p){p.NEW_INVITATION_RECEIVED="newInvitationReceived",p.INVITEE_ACCEPTED="ts_invitee_accepted",p.INVITEE_REJECTED="ts_invitee_rejected",p.INVITATION_CANCELLED="ts_invitation_cancelled",p.INVITATION_TIMEOUT="ts_invitation_timeout",p.INVITATION_MODIFIED="ts_invitation_modified"})(Rr||(Rr={}));var lo=Rr;const Xc=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),tc={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem",MSG_STREAM:"TIMStreamElem"};var Gg;(function(p){p.UNSENT="unSend",p.SUCCESS="success",p.FAIL="fail"})(Gg||(Gg={}));const qr={modify:Ci.MESSAGE_MODIFIED,delete:Ci.MESSAGE_DELETED,revoke:Ci.MESSAGE_REVOKED};var _c;(function(p){p[p.FORWARD=0]="FORWARD",p[p.BACKWARD=1]="BACKWARD"})(_c||(_c={}));const $c=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},tc),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:Gg,Direction:_c}),Ig={[qr.modify]:Ci.TOPIC_MESSAGE_MODIFIED,[qr.delete]:Ci.TOPIC_MESSAGE_DELETED,[qr.revoke]:Ci.TOPIC_MESSAGE_REVOKED},Nu={GENDER_UNKNOWN:"Gender_Type_Unknown",GENDER_FEMALE:"Gender_Type_Female",GENDER_MALE:"Gender_Type_Male",USER_STATUS_UNKNOWN:0,USER_STATUS_ONLINE:1,USER_STATUS_OFFLINE:2,USER_STATUS_UNLOGINED:3,USER_NOT_FOUND:"@TLS#NOT_FOUND"},ME=Object.assign({},Nu),bg={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},Pa=Object.assign(Object.assign(Object.assign(Object.assign({},bg),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),Tc=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),RE={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},xa={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},ga={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},kg=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},RE),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),{GROUP_ID_PREFIX:xa,GROUP_TIPS_OPERATION_TYPE:ga}),EI={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},Sn=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Xc),$c),ME),Pa),Tc),kg),EI),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),Po={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},ma={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},Cr={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message",RECEIVE_GROUP_TIPS_NOTIFICATION:"receive-group-tips-notification"},jt={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover",HANDLE_GROUP_TIPS_NOTIFICATION:"handle-group-tips-notification",C2C_HISTORY_MESSAGE_RECOVER:"c2c-history-message-recover",FRIEND_APPLICATION_LIST_RECOVER:"friend-application-list-recover",EMIT_GROUP_TIPS_EVENT:"emit-group-tips-event",STREAM_MESSAGE_RECOVER:"stream-message-recover"},Xt={[Cr.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:jt.USER_STATUS_UPDATE},{stepId:jt.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:jt.UNREAD_MESSAGE_SYNC,dependency:jt.C2C_HISTORY_MESSAGE_RECOVER},{stepId:jt.CONVERSATION_RECOVER},{stepId:jt.HISTORY_MESSAGE_RECOVER,dependency:jt.CONVERSATION_RECOVER},{stepId:jt.BLACKLIST_RECOVER},{stepId:jt.FRIEND_RECOVER},{stepId:jt.FRIEND_APPLICATION_LIST_RECOVER},{stepId:jt.GROUP_REVOKED_NOTICE_RECOVER,dependency:jt.HISTORY_MESSAGE_RECOVER},{stepId:jt.GROUP_TIPS_RECOVER,dependency:jt.HISTORY_MESSAGE_RECOVER},{stepId:jt.TOPIC_REQUEST_INFO_RESET},{stepId:jt.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:jt.UNREAD_MESSAGE_SYNC},{stepId:jt.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:jt.UNREAD_MESSAGE_SYNC},{stepId:jt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[jt.UNREAD_MESSAGE_SYNC,jt.CONVERSATION_RECOVER]},{stepId:jt.EMIT_C2C_MESSAGE_EVENT,dependency:[jt.UNREAD_MESSAGE_SYNC,jt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:jt.C2C_HISTORY_MESSAGE_RECOVER,dependency:jt.CONVERSATION_RECOVER},{stepId:jt.STREAM_MESSAGE_RECOVER}],[Cr.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:jt.COMMERCIAL_CONFIG_UPDATE},{stepId:jt.CLOUD_CONFIG_SYNC},{stepId:jt.USER_PROFILE_SYNC},{stepId:jt.UNREAD_MESSAGE_SYNC},{stepId:jt.FRIEND_AND_BLACKLIST_SYNC},{stepId:jt.GROUP_LIST_SYNC},{stepId:jt.CONVERSATION_LIST_SYNC},{stepId:jt.SIGNALING_MESSAGE_RECOVER,dependency:jt.UNREAD_MESSAGE_SYNC},{stepId:jt.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[jt.UNREAD_MESSAGE_SYNC]},{stepId:jt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[jt.UNREAD_MESSAGE_SYNC,jt.CONVERSATION_LIST_SYNC]},{stepId:jt.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[jt.GROUP_LIST_SYNC,jt.CONVERSATION_LIST_SYNC]},{stepId:jt.CONVERSATION_GROUP_LIST_SYNC},{stepId:jt.CONVERSATION_GROUP_UPDATE,dependency:[jt.CONVERSATION_LIST_SYNC,jt.CONVERSATION_GROUP_LIST_SYNC]},{stepId:jt.QUALITY_REPORT}],[Cr.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:jt.HANDLE_C2C_NEW_MESSAGE},{stepId:jt.UNREAD_MESSAGE_SYNC},{stepId:jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:jt.HANDLE_C2C_NEW_MESSAGE},{stepId:jt.EMIT_C2C_MESSAGE_EVENT,dependency:[jt.HANDLE_C2C_NEW_MESSAGE,jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:jt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[jt.UNREAD_MESSAGE_SYNC]}],[Cr.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:jt.HANDLE_GROUP_NEW_MESSAGE},{stepId:jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:jt.HANDLE_GROUP_NEW_MESSAGE},{stepId:jt.UPDATE_GROUP_NEXT_SEQUENCE,dependency:jt.HANDLE_GROUP_NEW_MESSAGE},{stepId:jt.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:jt.HANDLE_GROUP_NEW_MESSAGE},{stepId:jt.EMIT_GROUP_MESSAGE_EVENT,dependency:[jt.HANDLE_GROUP_NEW_MESSAGE,jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[Cr.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:jt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:jt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:jt.EMIT_GROUP_TIPS_EVENT,dependency:[jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,jt.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},Lg={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},dI={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},hr=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","sendMessageReadReceipt","getMessageReadReceiptList","getGroupMessageReadMemberList","createMergerMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var zI=Object.freeze({__proto__:null,ERROR_CODE:Po,InnerEvent:Ci,NEED_LOG_API:hr,OuterConstant:Sn,OuterEvent:Ts,PUSH:EI,QUALITY_METRICS:Lg,SDK_EDITION:ma,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:dI,SignalingEvent:lo,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Xt,WORKFLOW_NAME:Cr,WORKFLOW_STEP:jt}),Ag,ca,ps;(function(p){p[p.USER_INITIATED=0]="USER_INITIATED",p[p.KICKED_OUT=1]="KICKED_OUT"})(Ag||(Ag={})),function(p){p[p.multipleAccount=1]="multipleAccount",p[p.multipleDevice=2]="multipleDevice",p[p.restApi=3]="restApi"}(ca||(ca={})),function(p){p[p.multipleDevice=3002]="multipleDevice",p[p.multipleAccount=3003]="multipleAccount",p[p.usersigExpired=70001]="usersigExpired",p[p.restApi=20002]="restApi"}(ps||(ps={}));const Ns={[ca.multipleAccount]:"multipleAccount",[ca.multipleDevice]:"multipleDevice",[ca.restApi]:"REST_API_Kick",[ps.multipleAccount]:"multipleAccount",[ps.multipleDevice]:"multipleDevice",[ps.restApi]:"REST_API_Kick",[ps.usersigExpired]:"userSigExpired"},Gu="login_online_presence_task",{ERROR:Ug,DESTROY:Ya,FORCE_OFFLINE:Al}=Ci,{KICKED_OUT_MULT_ACCOUNT:ZI,KICKED_OUT_MULT_DEVICE:wE,KICKED_OUT_REST_API:CI,ACCOUNT_A2KEY_EXPIRED:bu,MSG_A2KEY_EXPIRED:bl}=Po;class Nc{init(){const{notificationCenter:B}=ve;B.subscribeInnerEvent(Al,this._handleForceOfflineFromServerPush,this),B.subscribeInnerEvent(Ug,bl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),B.subscribeInnerEvent(Ug,bu,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),B.subscribeInnerEvent(Ug,ZI,this._handleForceOfflineFromResponse,this),B.subscribeInnerEvent(Ug,wE,this._handleForceOfflineFromResponse,this),B.subscribeInnerEvent(Ug,CI,this._handleForceOfflineFromResponse,this),B.subscribeInnerEvent(Ya,this._dispose,this)}_handleForceOfflineFromServerPush(B){var M;if(((M=ve.store.get("login"))===null||M===void 0?void 0:M.isLoggedIn)===!0){const{EventArray:G=[]}=B?.body||{};this._extractKickedOutMessages(G).forEach(O=>{const{KickoutMsgNotify:{KickType:z,NewInstInfo:X,Instid:cA}}=O;this._isCurrentInstanceKickedOut(cA)&&this._processKickedOutReasonInfo({kickedOutReasonCode:z,newInstanceInfo:X})})}}_extractKickedOutMessages(B){return B.reduce((M,G)=>[...M,...G.C2cNotifyMsgArray||[]],[]).filter(M=>{var G;return this._isKickedOut((G=M?.KickoutMsgNotify)===null||G===void 0?void 0:G.KickType)})}_handleForceOfflineFromResponse(B){const{errorCode:M}=B;this._processKickedOutReasonInfo({kickedOutReasonCode:M})}_processKickedOutReasonInfo(B){return mA(this,void 0,void 0,function*(){const{kickedOutReasonCode:M}=B,{ssoLog:G,utils:{safeStringify:O}}=ve;try{this._logKickedOutEvent(B),this._shouldLogoutAfterKickedOut(M)?yield ve.login.loginAction.logout(Ag.KICKED_OUT):ve.login.loginAction.handleLogoutCompleted()}catch(z){G.debug("_processKickedOutReasonInfo",` fail ${O(z)}`)}finally{ve.notificationCenter.emitOuterEvent(Ts.KICKED_OUT,{data:{type:Ns[M]},name:Ts.KICKED_OUT})}})}_logKickedOutEvent(B){const{kickedOutReasonCode:M,newInstanceInfo:G={}}=B,O=`type:${Ns[M]} newInstanceInfo: ${JSON.stringify(G)}`;ve.ssoLog.warn("kickedOut",O)}_isKickedOut(B){return[ca.multipleAccount,ca.multipleDevice,ca.restApi].includes(B)}_isChatLoginEvent(B){const{requestHead:M}=B||{};return M?.idtype!==1}_shouldLogoutAfterKickedOut(B){return![ps.usersigExpired,ca.restApi].includes(B)}_isCurrentInstanceKickedOut(B){const{isLoggedIn:M,statusInstanceId:G}=ve.store.get("login")||{};return M===!0&&B===G}_dispose(){const{notificationCenter:B}=ve;B.unSubscribeInnerEvent(Al,this._handleForceOfflineFromServerPush,this),B.unSubscribeInnerEvent(Ug,bu,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Ug,bl,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Ug,ZI,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Ug,wE,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Ug,CI,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Ya,this._dispose,this)}}function ku(p){return mA(this,void 0,void 0,function*(){const B="im_open_status.wslogin",M=ve.common.generateProtocolData({servcmd:B,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:p}}),G=`${M.head.seq}${B}`,O=yield ve.channel.sendPacket(M,{timeout:9e4,requestId:G});if(O){const{HelloInterval:z,InstId:X,TinyId:cA,TimeStamp:DA,CustomStatus:GA,PurchaseBits:KA,A2Key:re,RichMsgAuthKey:Qe,ErrorCode:At,ErrorInfo:lt,ActionStatus:dt}=O;return{helloInterval:z,instanceID:X,tinyID:cA,timeStamp:DA,customStatus:GA,purchaseBits:KA,a2Key:re,authKey:Qe,errorCode:At,errorInfo:lt,actionStatus:dt}}})}function Lu(){const{store:p}=ve;return Qa(p.get("instance").sdkAppId)!==Ye.CHINA}function kl(p){var B;try{const M=ro.getStorage("errorMessage");if(!p||!M)return"";const G=((B=JSON.parse(M))===null||B===void 0?void 0:B.errorMessage)||{},{code:O,replacement1:z="",replacement2:X=""}=p;if(!O)return"";const cA=Lu()?`${O}_en`:`${O}_cn`;let DA=G[G[cA]?cA:O]||"";return DA&&(z&&(DA=DA.replace("$replacement1",z)),X&&(DA=DA.replace("$replacement2",X))),DA}catch(M){return console.warn("Error parsing stored error messages:",M),""}}class dn extends Error{constructor(B={}){B.code=B.code||B.errorCode;let{functionName:M="Unknown",code:G,message:O="",data:z="",moreMessage:X="",errorMessage:cA=""}=B;cA=(G?kl(B):"")||cA||O;let DA=G?`${M} failed. error: {"message": ${cA}, "code": ${G}}`:`${M} failed. error: {"message": ${cA}}`;DA=`${DA} ${X}`,super(),this.code=G,this.errorCode=G,this.errorMessage=cA,this.message=DA,this.data=z}}function hn(p,B){var M;if(p&&((M=ve.store.get("login"))===null||M===void 0?void 0:M.isLoggedIn)!==!0)throw new dn({code:Po.USER_NOT_LOGGED_IN,functionName:B})}function dd(p,B,M){if(Array.isArray(p))for(let G=0;G{return GA===(KA=G,Object.prototype.toString.call(KA).match(/^\[object (.*)\]$/)[1].toLowerCase());var KA})){for(let KA=0;KA{const{interceptor:O,context:z}=G;O.apply(z,[M])})}(p)}function wr(p,B){BI.push({interceptor:p,context:B})}function Gc(p){const{params:B,auth:M}=p;B&&typeof B=="object"&&Object.assign(Cd,B),M&&typeof M=="object"&&Object.assign(_E,M)}function el(p){return ve.store.get("commercialConfig").get(p)}class us{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(B,M)=>{const G=Date.now();M?(this._stepStartTimes.set(`${B}-${M}`,G),ve.ssoLog.debug("_executeWorkflowStep",`[Workflow ${B}] Step ${M} started at ${new Date(G).toISOString()}`)):(this._workflowStartTimes.set(B,G),ve.ssoLog.debug("_executeWorkflowStep",`[Workflow ${B}] started at ${new Date(G).toISOString()}`))},success:(B,M)=>{const G=Date.now();if(M){const O=this._stepStartTimes.get(`${B}-${M}`),z=O?G-O:0;this._stepStartTimes.delete(`${B}-${M}`),ve.ssoLog.debug("_executeWorkflowStep",`[Workflow ${B}] Step ${M} completed successfully at ${new Date(G).toISOString()} (${z}ms)`)}else{const O=this._workflowStartTimes.get(B),z=O?G-O:0;this._workflowStartTimes.delete(B),ve.ssoLog.debug("_executeWorkflowStep",`[Workflow ${B}] completed successfully at ${new Date(G).toISOString()} (${z}ms)`)}},error:(B,M,G)=>{const{ssoLog:O,utils:{safeStringify:z}}=ve,X=Date.now();if(M){const cA=this._stepStartTimes.get(`${B}-${M}`),DA=cA?X-cA:0;this._stepStartTimes.delete(`${B}-${M}`),O.error("_executeWorkflowStep",`[Workflow ${B}] Step ${M} failed at ${new Date(X).toISOString()} (${DA}ms) ${z(G)}`,{error:G})}else{const cA=this._workflowStartTimes.get(B),DA=cA?X-cA:0;this._workflowStartTimes.delete(B),O.error("_executeWorkflowStep",`[Workflow ${B}] failed at ${new Date(X).toISOString()} (${DA}ms) ${z(G)}`,{error:G})}}}}static getInstance(){return us._instance||(us._instance=new us),us._instance}static setInstance(B){us._instance=B}init(){this._initializeWorkflows()}registerWorkflowStep(B,M,G,O){if(!this._handlers.has(B))return void ve.ssoLog.debug("registerWorkflowStep",`Workflow '${B}' not defined in core`);if(!Xt[B].find(X=>X.stepId===M))return void ve.ssoLog.debug("registerWorkflowStep",`Step '${M}' not defined in workflow '${B}'`);const z=this._handlers.get(B);z.has(M)||z.set(M,O?G.bind(O):G)}executeWorkflow(B,M){return mA(this,void 0,void 0,function*(){if(!this._validateWorkflow(B))return;ve.ssoLog.debug("executeWorkflow",`[Workflow ${B}] Started execution at ${new Date().toISOString()}`);const G=Xt[B],O={},z={cancelled:!1};this._activeWorkflows.set(B,{cancelToken:z});try{const X=new Map;G.forEach(DA=>{X.set(DA.stepId,DA)});const cA={workflowName:B,pendingSteps:new Set(G.map(DA=>DA.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:X,stepResults:O,data:M,cancelToken:z};yield new Promise((DA,GA)=>{const KA=()=>{if(z.cancelled)return void DA();this._getExecutableSteps({pendingSteps:cA.pendingSteps,completedSteps:cA.completedSteps,stepMap:cA.stepMap,workflowName:B}).filter(re=>!cA.runningSteps.has(re)).forEach(re=>{cA.completedSteps.has(re)||cA.runningSteps.has(re)||this._executeWorkflowStep(re,cA,{onComplete:()=>{if(cA.pendingSteps.size===0)return void DA();this._getExecutableSteps({pendingSteps:cA.pendingSteps,completedSteps:cA.completedSteps,stepMap:cA.stepMap,workflowName:B}).filter(Qe=>!cA.runningSteps.has(Qe)).length===0&&cA.runningSteps.size===0&&(ve.ssoLog.debug("executeWorkflow",`Workflow ${B} completed with some steps skipped due to dependency failures`),DA())},onError:GA,onStepComplete:KA})})};KA()}),ve.ssoLog.debug("executeWorkflow",`[Workflow ${B}] Completed execution at ${new Date().toISOString()}`)}catch(X){ve.ssoLog.error("executeWorkflow",`[Workflow ${B}] Failed execution at ${new Date().toISOString()}`,{error:X})}finally{this._activeWorkflows.delete(B)}})}_executeWorkflowStep(B,M,G){return mA(this,void 0,void 0,function*(){const{workflowName:O,runningSteps:z,stepMap:X,stepResults:cA,data:DA}=M;z.add(B),this._logWorkflowExecution(O,B,"start");try{const GA=X.get(B);let KA=null;GA?.dependency&&(c(GA.dependency)?KA=cA[GA.dependency]:Array.isArray(GA.dependency)&&(KA={},GA.dependency.forEach(Qe=>{KA[Qe]=cA[Qe]})));const re=this._handlers.get(O).get(B);if(re){const Qe=yield Promise.resolve(re({data:DA,result:KA}));cA[B]=Qe,this._logWorkflowExecution(O,B,"success")}M.completedSteps.add(B)}catch(GA){const KA=`[Workflow].${O}.${B}`,{errorCode:re,errorInfo:Qe=`${KA} failed`}=GA||{},At=new dn({functionName:KA,code:re,message:Qe});ve.ssoLog.error(KA,Qe,{error:At}),this._logWorkflowExecution(O,B,"error",GA),G.onError(GA)}finally{z.delete(B),M.pendingSteps.delete(B),G.onStepComplete(),G.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Xt).forEach(B=>{this._handlers.has(B)||this._handlers.set(B,new Map)})}_cancelWorkFlow(B){const M=this._activeWorkflows.get(B);if(!M)return;const{cancelToken:G}=M;G.cancelled=!0,this._activeWorkflows.delete(B)}_cancelAllWorkflows(){Object.keys(Xt).forEach(B=>{this._cancelWorkFlow(B)})}_validateWorkflow(B){return Xt[B]?!!this._handlers.get(B):!1}_getExecutableSteps(B){const{pendingSteps:M,completedSteps:G,stepMap:O,workflowName:z}=B;return Array.from(M).filter(X=>{const cA=O.get(X)||{},{dependency:DA,skipIfDependencyMissing:GA=!0}=cA;if(!DA)return!0;if(c(DA))return this._isStepRegistered({workflowName:z,stepId:DA})?G.has(DA):!GA;if(C(DA)){if(DA.filter(KA=>!this._isStepRegistered({workflowName:z,stepId:KA})).length>0&&GA)return!1;for(const KA of DA)if(!G.has(KA))return!1;return!0}return!1})}_isStepRegistered(B){var M;const{workflowName:G,stepId:O}=B;return(M=this._handlers.get(G))===null||M===void 0?void 0:M.has(O)}_logWorkflowExecution(B,M,G,O){this._logHandlers[G](B,M)}}const Pn=new Map,fa=({type:p,groupID:B})=>p===Sn.GRP_COMMUNITY||`${B}`.startsWith(xa.COMMUNITY)&&!`${B}`.includes(xa.TOPIC),ea=(p="")=>{const B=p.startsWith("GROUP")?p.replace("GROUP",""):p;return B.startsWith(xa.COMMUNITY)&&`${B}`.includes(xa.TOPIC)},tl="openim",hd="million_group_open_http_svc";function ic(p){return mA(this,void 0,void 0,function*(){const{servcmd:B,data:M}=function(z){const{data:X}=z;return ug(X)||TE(X)}(p)?function(z){let{servcmd:X,data:cA}=z;return TE(cA)?function(DA){const{servcmd:GA,data:KA}=DA;let{GroupId:re=""}=KA;const Qe=re;return[re]=Qe.split(xa.TOPIC),{servcmd:oc(GA),data:Object.assign(Object.assign({},KA),{GroupId:re,TopicId:Qe})}}(z):(ug(cA)&&(X=oc(X)),{servcmd:X,data:cA})}(p):p,G=ve.common.generateProtocolData({servcmd:B,data:M}),O=`${G.head.seq}${B}`;return ve.channel.sendPacket(G,{requestId:O,timeout:p.timeout})})}function ug(p){const{Type:B,GroupId:M,GroupIdList:G=[]}=p,O=M||G[0]||"";return fa({type:B,groupID:O})}function TE(p){const{GroupId:B=""}=p;return ea(B)}function oc(p){if(p.includes(tl))return p;const B=p.split(".")[1];return`${hd}.${B}`}function $s(){var p;return(p=ve.store.get("login"))===null||p===void 0?void 0:p.userId}const ar=p=>C(p)||m(p),Va=(p,B,M,G)=>{if(!ar(p)||!ar(B))return 0;let O=0;const z=Object.keys(B);let X;for(let cA=0,DA=z.length;cA{if(n(B))return"";if(p===Sn.MSG_TEXT)return B.text||"";const M=Uu[p];return M?EC(M):""},il=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],ol="im_sdk_config_mgr.fetch_config",$I="im_sdk_config_mgr.push_configv2",QI="cloud-config",nl=2996,sl=new class{init(p){this.core=p}};function Ga(p){return mA(this,void 0,void 0,function*(){const{sdkAppId:B}=sl.core.store.get("instance")||{},M=sl.core.helper.generateProtocolData({servcmd:ol,data:{uint32_sdkappid:B,uint64_version:p}}),G=`${M.head.seq}${ol}`;return sl.core.channel.sendPacket(M,{requestId:G})})}var Fg=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(p){this._core=p;const{notificationCenter:B,InnerEvent:M,helper:G,constants:{WORKFLOW_NAME:O,WORKFLOW_STEP:z},channel:X}=p;B.subscribeInnerEvent($I,this._handlePushedConfig,this),G.registerWorkflowStep(O.SYNC_SERVER_INFO_AFTER_LOGIN,z.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),B.subscribeInnerEvent(M.LOGOUT,this._reset,this),B.subscribeInnerEvent(M.DESTROY,this._dispose,this),G.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(il),X.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(p){return mA(this,void 0,void 0,function*(){var B;const M={code:0,data:""};return p&&(M.data=((B=this._core.store.get("cloudConfig"))===null||B===void 0?void 0:B[p])||""),M})}checkMethodCallOverLimit(p){if(!this._cmdFrequencyLimitMap.has(p))return;if(!this._methodCallFrequencyMap.has(p))return void this._methodCallFrequencyMap.set(p,{startTime:Date.now(),methodCallCounter:1});const{count:B,interval:M}=this._cmdFrequencyLimitMap.get(p);let{startTime:G,methodCallCounter:O}=this._methodCallFrequencyMap.get(p);if(Date.now()-G>1e3*M)this._methodCallFrequencyMap.set(p,{startTime:Date.now(),methodCallCounter:1});else if(O+=1,this._methodCallFrequencyMap.set(p,{startTime:G,methodCallCounter:O}),O>B)throw new this._core.helper.ChatError({code:nl,replacement1:p})}_handlePushedConfig(p){return mA(this,void 0,void 0,function*(){const{ssoLog:B,utils:{safeStringify:M}}=this._core;B.info("_handlePushedConfig",M(p)),yield this._updateCloudConfig(p)})}_handleLoginSuccess(){return mA(this,void 0,void 0,function*(){const{ssoLog:p,utils:{safeStringify:B}}=this._core;try{if(this._canFetch()){const M=yield Ga(this._version);p.info("_fetchCloudConfigIfLogin",B(M)),yield this._updateCloudConfig(M)}this._core.helper.taskScheduler.addTask({id:QI,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(M){p.debug("_fetchCloudConfigIfLogin",B(M))}})}_fetchCloudConfigIfReady(){return mA(this,void 0,void 0,function*(){const{ssoLog:p,utils:{safeStringify:B}}=this._core;if(this._canFetch())try{const M=yield Ga(this._version);p.info("_fetchCloudConfigIfReady",B(M)),yield this._updateCloudConfig(M)}catch(M){p.error("_fetchCloudConfigIfReady",B(M))}})}_updateCloudConfig(p){return mA(this,void 0,void 0,function*(){const B=this._parseCloudConfig(p);B&&(this._core.store.set("cloudConfig",B),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,B),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:B}}))})}_canFetch(){const{isLoggedIn:p}=this._core.store.get("login")||{};return p&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(p){const{int32_error_code:B,str_error_message:M,str_json_config:G,uint32_expired_time:O,uint32_sdkappid:z,uint64_version:X}=p;let cA=null;if(B===0){if(this._version!==X)try{cA=JSON.parse(G),this._version=X}catch{}this._expirationTime=Date.now()+1e3*O}else this._expirationTime=B===void 0?Date.now()+36e5:Date.now()+12e4;return cA}_parseCmdFreqLimit(){return mA(this,void 0,void 0,function*(){var p;let B=(p=yield this.getServerConfig("cmd_frequency_limit"))===null||p===void 0?void 0:p.data;const{isEmpty:M}=this._core.utils;if(!M(B))try{B=JSON.parse(B),this._updateCmdFreqLimitMap(B)}catch(G){console.warn(G)}})}_updateCmdFreqLimitMap(p){p.forEach(B=>{this._cmdFrequencyLimitMap.set(B.cmd,{interval:B.interval,count:B.count})})}_reset(){this._core.helper.taskScheduler.removeTask(QI),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(il),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent($I,this._handlePushedConfig,this),p.unSubscribeInnerEvent(B.LOGOUT,this._reset,this),p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this),this._reset()}};class Nn{constructor(B=0,M=0){this.high=B,this.low=M}equal(B){return B!==null&&this.low===B.low&&this.high===B.high}toString(){const B=Number(this.high).toString(16);let M=Number(this.low).toString(16);if(M.length<8){let G=8-M.length;for(;G;)M=`0${M}`,G--}return B+M}}const Ar={SEARCH_GRP_SNS:new Nn(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Nn(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Nn(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Nn(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Nn(0,Math.pow(2,6)).toString(),USER_STATUS:new Nn(0,Math.pow(2,7)).toString(),CONV_MARK:new Nn(0,Math.pow(2,9)).toString(),CONV_GROUP:new Nn(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Nn(0,Math.pow(2,11)).toString(),MSG_EXT:new Nn(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Nn(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Nn(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Nn(Math.pow(2,7)).toString(),PLUGIN_CS:new Nn(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Nn(Math.pow(2,9)).toString(),PLUGIN_BOT:new Nn(Math.pow(2,10)).toString(),MSG_REACTION:new Nn(Math.pow(2,16)).toString(),FOLLOW:new Nn(Math.pow(2,20)).toString()},bc="CommercialConfig",Au="commercial-config";var eu=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(p){this._core=p;const{helper:B,notificationCenter:M,constants:{WORKFLOW_NAME:G,WORKFLOW_STEP:O,InnerEvent:z}}=p;M.subscribeInnerEvent(z.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),M.subscribeInnerEvent(z.LOGOUT,this._handleLogout,this),M.subscribeInnerEvent(z.DESTROY,this._dispose,this),B.registerWorkflowStep(G.SYNC_SERVER_INFO_AFTER_LOGIN,O.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),p.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),p.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(p){return mA(this,void 0,void 0,function*(){const B=parseInt(p,10).toString(2),{length:M}=B;let G,O=!0;for(let z=M-1,X=0;z>=0;z--,X++)if(B.charAt(z)==="1"&&(G=X<32?new Nn(0,2**X).toString():new Nn(2**(X-32),0).toString(),!this._featureMap.get(G))){O=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${bc}.isFeatureEnabled decimalNumber:${p} key:${G} ret:${O}`),{code:0,data:{enabled:O}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return mA(this,void 0,void 0,function*(){var p;const{ssoLog:B,utils:{safeStringify:M},common:{buildAndSendPacket:G}}=this._core;try{this._isFetching=!0;const O=yield G({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:(p=this._core.store.get("instance"))===null||p===void 0?void 0:p.sdkAppId}});O&&(this._parseCommercialConfig(O),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(O){B.error("_fetchAndParseCommercialConfig",M(O))}finally{this._isFetching=!1}})}_syncCommercialConfig(p){return mA(this,void 0,void 0,function*(){const{purchaseBits:B}=p?.data||{};B&&(this._parsePurchaseBits(B),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:Au,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var p;const B=(p=this._core.store.get("login"))===null||p===void 0?void 0:p.isLoggedIn,M=Date.now()>=this._expirationTime;return B&&!this._isFetching&&M}_handlePushedConfig(p){p?.body&&(this._parseCommercialConfig(p.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return mA(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(p){const{ssoLog:B}=this._core;if(typeof p!="object")return;const{int32_error_code:M,str_error_message:G,str_purchase_bits:O,uint32_expired_time:z}=p;M===0?(this._parsePurchaseBits(O),this._expirationTime=Date.now()+1e3*z):M===void 0?(B.warn("_parseCommercialConfig",`${bc}._parseCommercialConfig failed. Invalid message format:`,p),this._expirationTime=Date.now()+36e5):(B.warn("_parseCommercialConfig",`${bc}._parseCommercialConfig errorCode:${M} errorMessage:${G}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(p){return p&&typeof p=="string"&&p.length>=1&&p.length<=64&&/[01]{1,64}/.test(p)}_parsePurchaseBits(p){const{ssoLog:B,utils:{safeStringify:M}}=this._core;if(this._isValidPurchaseBits(p)){this._purchaseBits=p,this._featureMap.clear(),this._methodKeyMap.clear();let G=null;for(let O=p.length-1,z=0;O>=0;O--,z++)if(G=z<32?new Nn(0,2**z).toString():new Nn(2**(z-32),0).toString(),p[O]==="1"){this._featureMap.set(G,!0);const X=this._getKeyByValue(Ar,G);X&&this._methodKeyMap.set(X,!0)}else{this._featureMap.set(G,!1);const X=this._getKeyByValue(Ar,G);X&&this._methodKeyMap.set(X,!1)}}else B.warn("_parsePurchaseBits",`${bc}.parsePurchaseBits invalid purchases:${M(p)}`)}_getKeyByValue(p,B){const M=Object.entries(p).find(([G,O])=>O===B);return M?M[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(Au),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},NE=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(p){this._core=p;const{notificationCenter:B,InnerEvent:M,channel:G}=this._core;B.subscribeInnerEvent(M.OVERLOAD_PUSH,this._handleOverLoadPush,this),B.subscribeInnerEvent(M.LOGOUT,this._reset,this),B.subscribeInnerEvent(M.DESTROY,this._dispose,this),G.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(p){if(!this._serverOverloadInfoMap.has(p))return;const{overloadStartTimestamp:B,delaySeconds:M}=this._serverOverloadInfoMap.get(p);if(Date.now()-B<=1e3*M)throw new this._core.helper.ChatError({functionName:p,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(p)}_handleOverLoadPush(p){const{OverLoadServCmd:B,DelaySecs:M}=p;this._serverOverloadInfoMap.set(B,{overloadStartTimestamp:Date.now(),delaySeconds:M})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(B.OVERLOAD_PUSH,this._handleOverLoadPush,this),p.unSubscribeInnerEvent(B.LOGOUT,this._reset,this),p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this)}},lh=new class{constructor(){this.name="ConfigCenter"}install(p){sl.init(p),Fg.install(p),eu.install(p),NE.install(p)}},dC=new class{constructor(){this.name="ErrorMessage",this._core=null}install(p){return mA(this,void 0,void 0,function*(){if(this._core=p,this._canFetch()){const B=yield this._fetchErrorMessage();if(!B)return;const M=this._parseResponse(B);this._saveErrorMessage(M)}})}_canFetch(){const p=this._core.store.getStorage("errorMessage");return!p||this._isExpired(p)}_saveErrorMessage(p){this._core.store.setStorage("errorMessage",{errorMessage:p,errorMessageSavedTime:new Date().getTime()})}_fetchErrorMessage(){return mA(this,void 0,void 0,function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(p){console.error(p)}})}_isExpired(p){if(!p)return!0;const{errorMessageSavedTime:B}=p;return B&&new Date().getTime()-B>=6048e5}_parseResponse(p){if(typeof p=="string"){const B=p.split(`; +`),M={},G=new RegExp(/'/g);for(let O=0;O{var Eo,so,hi;const qo=function(cn,yi){const{From_Account:to,From_AccountHeadurl:rs,From_AccountNick:be,IsNeedReadReceipt:bt,MsgBody:OA,MsgClientTime:oi,MsgRandom:ms,MsgSeq:si,MsgTimeStamp:Dn,SendMsgControl:Ni,SupportMessageExtension:yo,To_Account:yt,TinyId:St,MsgCheckResult:hg,CloudCustomData:qn,IsPeerRead:io,MsgFlagBits:Wr,MsgVersion:cc,EventArray:In}=cn;return{from:to,avatar:rs,nick:be,needReadReceipt:bt===1,readReceiptSentByPeer:io,clientTime:oi,messageFlagBits:Wr,random:ms,sequence:si,time:Dn,messageControlInfo:Ni,isSupportExtension:yo,to:yt,tinyID:St,checkResult:hg,cloudCustomData:qn,messageVersion:cc,eventArray:In,elements:yi.message.messageHelper.parseServerPushMessageElement(OA)}}(Ki,dt);if(!((hi=(so=(Eo=Ki?.EventArray)===null||Eo===void 0?void 0:Eo[0])===null||so===void 0?void 0:so.hasOwnProperty)===null||hi===void 0)&&hi.call(so,"C2cNotifyMsgArray"))Wt.push(...function(cn){var yi;const to=[];return(yi=cn.EventArray)===null||yi===void 0||yi.forEach(rs=>{var be,bt;const{C2cNotifyMsgArray:OA}=rs,oi=(bt=(be=OA?.[0])===null||be===void 0?void 0:be.WithdrawC2cMsgNotify)===null||bt===void 0?void 0:bt.C2cWithdrawInfoArray;Array.isArray(oi)&&to.push(...oi)}),to}(Ki));else{const cn=dt.message.messageFactory.createMessage(Object.assign(Object.assign({},qo),{conversationType:"C2C",flow:"in"})),{elements:yi}=qo;cn.setElement(yi),xt.push(cn)}}),{unreadMessageList:xt,revokedMessageList:Wt}}(DA.MsgList,B);return{syncFlag:DA?.SyncFlag,unreadMessageList:Qe,revokedMessageList:At,unreadCountList:GA,overflowUnreadCountList:KA,cookie:DA?.Cookie,groupTipList:re}}catch(DA){console.warn(DA)}})}var rl,Og;(function(p){p[p.START_SYNC=0]="START_SYNC",p[p.SYNCING=1]="SYNCING",p[p.SYNC_COMPLETE=2]="SYNC_COMPLETE"})(rl||(rl={})),function(p){p[p.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",p[p.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(Og||(Og={}));var Io=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie="",this._localConversationIDListBeforeDisconnect=[]}install(p){this._core=p;const{constants:B}=p;p.helper.registerWorkflowStep(B.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,B.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),p.helper.registerWorkflowStep(B.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,B.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),p.helper.registerWorkflowStep(B.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,B.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.SOCKET_DISCONNECTED,this._handleDisconnect,this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.LOGOUT,this._reset,this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(p){return mA(this,void 0,void 0,function*(){const{isAfterReOnline:B=!1,isAfterNewMessageReceived:M=!1,isAfterLogin:G=!1}=p||{};let O=rl.START_SYNC;const z=[],X=[],cA=[],DA=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:O});){const GA=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:O,syncTriggerEvent:M?Og.NEW_MESSAGE_RECEIVED:Og.LOGIN_SUCCESS});if(!GA)break;const{unreadMessageList:KA=[],revokedMessageList:re=[],overflowUnreadCountList:Qe,unreadCountList:At,groupTipList:lt}=GA;if(this._cookie=GA?.cookie||"",O=GA?.syncFlag,this._parseAndSaveUnreadMessageList(KA),cA.push(...re),this._updateConversationUnreadOptions({unreadCountList:At,overflowUnreadCountList:Qe,conversationUpdateFieldList:z}),Array.isArray(lt)&&X.push(...lt),B){const{messages:dt}=this._handleNewMessageList(KA);DA.push(...dt)}}return B?{conversationUpdateFieldList:z,revokedMessageList:cA,unreadMessageMap:this._unreadDBMessageMap,groupTipList:X,messages:DA,isUnreadC2CMessage:!0}:{conversationUpdateFieldList:z,isInstantMessage:!G,isUnreadC2CMessage:!0,revokedMessageList:cA,unreadMessageMap:this._unreadDBMessageMap,groupTipList:X}})}_syncUnreadDBMessageAfterLogin(){return mA(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(p){return mA(this,void 0,void 0,function*(){if(p.data.Flag===1)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(p){const{unreadCountList:B,overflowUnreadCountList:M,conversationUpdateFieldList:G}=p,{constants:{OuterConstant:{CONV_C2C:O,CONV_SYSTEM:z}}}=this._core;B?.forEach(X=>{const{From_Account:cA,UnreadCount:DA}=X;if(cA!==z){const GA=G.find(({conversationID:KA})=>KA===`${O}${cA}`);GA?GA.unreadCount=DA:G.push({conversationID:`${O}${cA}`,unreadCount:DA,type:O})}}),M?.forEach(X=>{const{From_Account:cA,LastMsgTime:DA}=X;cA!==z&&(G.find(({conversationID:GA})=>GA===`${O}${cA}`)||G.push({conversationID:`${O}${cA}`,type:O,lastMsgTime:DA}))})}_syncUnreadDBMessageAfterReOnline(){return mA(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(p){var B;const{messageDataHandler:M}=this._core.message||{},G=(B=this._core.store.get("login"))===null||B===void 0?void 0:B.userId,{from:O,nick:z,avatar:X,conversationID:cA=""}=p;if(O!==G){const DA=M.getLatestMsgSentByPeer(cA);if(DA){const{nick:GA,avatar:KA}=DA;z&&X?z===GA&&X===KA||M.updateNickAndAvatarOfSentMessage({conversationID:cA,latestNick:z,latestAvatar:X,isSentByMe:!1}):(p.nick=GA,p.avatar=KA)}}else{const DA=M.getLatestMsgSentByMe(cA);!DA||z===DA.nick&&X===DA.avatar||M.updateNickAndAvatarOfSentMessage({conversationID:cA,latestNick:z,latestAvatar:X,isSentByMe:!0})}}_handleNewMessageList(p){const{messageDataHandler:B}=this._core.message||{},M=new Map,G=[];return p.forEach(O=>{this._updateMessageProfile(O);let z=O.isModified===1;if(B.isMessageSentByCurrentInstance(O)?O.isModified=z:z=!1,O.isOnlineMessage())O._onlineOnlyFlag=!0,B.isMessageSentByCurrentInstance(O)||G.push(O);else if(this._shouldStoreUnreadMessage(O)){if(B.storeConversationMessage(O)){const{conversationID:X,conversationType:cA,conversationSubType:DA,flow:GA,_isExcludedFromUnreadCount:KA,_isExcludedFromLastMessage:re}=O,Qe=re?"":O;M.has(X)?(M.get(X).lastMessage=Qe,GA==="in"&&(KA||M.get(X).unreadCount++)):M.set(X,{conversationID:X,type:cA,subType:DA,unreadCount:KA||GA!=="in"?0:1,lastMessage:Qe})}B.isMessageSentByCurrentInstance(O)&&!z||G.push(O)}}),{messages:G,conversationOptions:M}}_shouldStoreUnreadMessage(p){var B;const{conversationID:M}=p,{message:G,appStore:O,utils:{isEmpty:z}}=this._core||{},X=Array.from(((B=O.conversationStore.getConversationMap())===null||B===void 0?void 0:B.keys())||[]),cA=this._getLocalLastMessageTime(M);return!G.messageDataHandler.isInMessageList(p)&&X.includes(M)&&this._localConversationIDListBeforeDisconnect.includes(M)&&!z(cA)}_fetchUnreadDBMessage(p){return mA(this,void 0,void 0,function*(){const{ssoLog:B,utils:{safeStringify:M}}=this._core;try{B.debug("_fetchUnreadDBMessage",`unread-message-synchronizer._fetchUnreadDBMessage options:${M(p)}`);const O=yield Ih(p,this._core);if(!O)return null;const{syncFlag:z,unreadMessageList:X,revokedMessageList:cA,cookie:DA,unreadCountList:GA,overflowUnreadCountList:KA,groupTipList:re}=O;return this._parseAndSaveUnreadMessageList(X),{syncFlag:z,cookie:DA,unreadMessageList:X,revokedMessageList:cA,unreadCountList:GA,overflowUnreadCountList:KA,groupTipList:re}}catch(G){console.log(G)}})}_canContinueSync({cookie:p,syncFlag:B}){var M;return B===rl.START_SYNC||B===rl.SYNCING&&!(!((M=this._core)===null||M===void 0)&&M.helper.isEmpty(p))}_parseAndSaveUnreadMessageList(p){p.forEach(B=>{const{ID:M}=B;this._unreadDBMessageMap.set(M,B)})}_handleDisconnect(){var p;const{appStore:B}=this._core;this._localConversationIDListBeforeDisconnect=Array.from(((p=B.conversationStore.getConversationMap())===null||p===void 0?void 0:p.keys())||[])}_getLocalLastMessageTime(p){const{message:B}=this._core,M=B.messageDataHandler.getLocalMessageList(p),G=M[M.length-1];return G?.time}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var p,B;(p=this._core)===null||p===void 0||p.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(B=this._core)===null||B===void 0||B.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},CC=new class{init(p){var B;this._core=p,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this),document?.addEventListener("visibilitychange",this._visibilityChangeHandler),(B=this._core)===null||B===void 0||B.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var p,B;const M=document?.visibilityState==="visible";(p=this._core)===null||p===void 0||p.store.set("activityMonitor",{isActive:M}),(B=this._core)===null||B===void 0||B.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:M})}_reset(){var p;(p=this._core)===null||p===void 0||p.store.clear("activityMonitor")}_dispose(){document?.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this),this._reset()}},GE=new class{init(p){var B;this._core=p,this._bindAppActivityEvent(),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this),(B=this._core)===null||B===void 0||B.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var p,B,M,G,O;const{MINI_APP_NAMESPACE:z,IN_TT_MINI_GAME:X,IN_WX_MINI_GAME:cA}=((p=this._core)===null||p===void 0?void 0:p.utils)||{};X||cA?((B=z?.onShow)===null||B===void 0||B.call(z,()=>{var DA,GA;(DA=this._core)===null||DA===void 0||DA.store.set("activityMonitor",{isActive:!0}),(GA=this._core)===null||GA===void 0||GA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(M=z?.onHide)===null||M===void 0||M.call(z,()=>{var DA,GA;(DA=this._core)===null||DA===void 0||DA.store.set("activityMonitor",{isActive:!1}),(GA=this._core)===null||GA===void 0||GA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):((G=z?.onAppShow)===null||G===void 0||G.call(z,()=>{var DA,GA;(DA=this._core)===null||DA===void 0||DA.store.set("activityMonitor",{isActive:!0}),(GA=this._core)===null||GA===void 0||GA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(O=z?.onAppHide)===null||O===void 0||O.call(z,()=>{var DA,GA;(DA=this._core)===null||DA===void 0||DA.store.set("activityMonitor",{isActive:!1}),(GA=this._core)===null||GA===void 0||GA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var p;(p=this._core)===null||p===void 0||p.store.clear("activityMonitor")}_dispose(){const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this),this._reset()}},bE=new class{init(p){const{IN_MINI_APP:B,IN_WX_MINI_PLUGIN:M}=p.helper;M||(B?GE.init(p):CC.init(p))}};const Qd="none",kE="online";var al=new class{init(p){this._core=p,this._activateNetworkMonitoring(),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return mA(this,void 0,void 0,function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)})}_deactivateNetworkMonitoring(){this._onOnlineCallback!==null&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),this._onOfflineCallback!==null&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(p){var B,M;const{isConnected:G,networkType:O}=p;(B=this._core)===null||B===void 0||B.store.set("netWorkMonitor",{isNetworkOnline:G,networkType:O}),(M=this._core)===null||M===void 0||M.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:G,networkType:O})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:kE})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:Qd})}_reset(){var p;this._deactivateNetworkMonitoring(),(p=this._core)===null||p===void 0||p.store.clear("netWorkMonitor")}_dispose(){var p,B;(p=this._core)===null||p===void 0||p.notificationCenter.unSubscribeInnerEvent((B=this._core)===null||B===void 0?void 0:B.InnerEvent.DESTROY,this._dispose,this),this._reset()}},pI=new class{init(p){this._core=p,this._activateNetworkMonitoring(),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return mA(this,void 0,void 0,function*(){try{const{utils:{MINI_APP_NAMESPACE:p}}=this._core;this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),p.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(p){console.error(p)}})}_deactivateNetworkMonitoring(){if(this._mpNetworkStatusCallback!==null){const{utils:{MINI_APP_NAMESPACE:p}}=this._core;p.offNetworkStatusChange&&p.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null}}_onNetworkStatusChange(p){var B,M;const{isConnected:G,networkType:O}=p;(B=this._core)===null||B===void 0||B.store.set("netWorkMonitor",{isNetworkOnline:G,networkType:O}),(M=this._core)===null||M===void 0||M.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:G,networkType:O})}_reset(){var p;this._deactivateNetworkMonitoring(),(p=this._core)===null||p===void 0||p.store.clear("netWorkMonitor")}_dispose(){var p,B;(p=this._core)===null||p===void 0||p.notificationCenter.unSubscribeInnerEvent((B=this._core)===null||B===void 0?void 0:B.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Fu=new class{init(p){const{IN_MINI_APP:B}=p.utils;B?pI.init(p):al.init(p)}},Ou=new class{constructor(){this.name="SystemStateMonitor"}install(p){bE.init(p),Fu.init(p)}};const hC=new Set(["tui_room_svr.*","callkit_records_svr.*","room_engine_srv.*","room_engine_http_srv.*","room_engine_mic.*","live_engine_srv.*","live_engine_http_srv.*","live_engine_pk.*","trtc_ai_service.*","call_engine_srv.*"]),Tr="tui_room_svr.*";var Eg=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=hC}install(p){this._core=p;const{notificationCenter:B,InnerEvent:M,helper:G}=p;B.subscribeInnerEvent(M.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),B.subscribeInnerEvent(M.LOGOUT,this._reset,this),B.subscribeInnerEvent(M.DESTROY,this._dispose,this),B.subscribeInnerEvent("im_open_push.msg_push",B.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),G.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),G.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(p){return mA(this,void 0,void 0,function*(){const B="transferBusinessCommand";try{const{serviceCommand:M=Tr}=p||{};if(!this._isValidTransferredCommand(M))throw new this._core.helper.ChatError({code:2995,functionName:B});return{code:0,data:(yield function(O,z){return mA(this,void 0,void 0,function*(){const{helper:X,channel:cA}=z,{serviceCommand:DA=Tr,data:GA}=O||{};let KA={};try{KA=typeof GA=="string"?JSON.parse(GA):GA}catch(At){console.warn(At)}const re=X.generateProtocolData({servcmd:DA,data:KA}),Qe=`${re.head.seq}${DA}`;return cA.sendPacket(re,{requestId:Qe,shouldRejectOnError:!1})})}(p,this._core))||{}}}catch(M){throw console.warn(M),new this._core.helper.ChatError({code:M?.errorCode,message:M?.errorInfo,data:{},functionName:B})}})}_onCloudConfigUpdate(p={}){try{if(typeof p.rtc_cmd!="string")return;const B=JSON.parse(p.rtc_cmd);Array.isArray(B)&&(this._transferredCommands=new Set([...this._transferredCommands,...B]))}catch(B){console.log(B)}}_isValidTransferredCommand(p=""){const B=`${p?.split(".")[0]}.*`;return this._transferredCommands.has(B)}_onServerPushBusinessCommand(p){const{OuterEvent:B,notificationCenter:M}=this._core,{MsgContent:G}=p||{},{ROOM_CUSTOM_DATA_RECEIVED:O}=B;M.emitOuterEvent(O,{name:O,data:G})}_reset(){this._transferredCommands=hC}_dispose(){const{notificationCenter:p,InnerEvent:B}=this._core;this._reset(),p.unSubscribeInnerEvent(B.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),p.unSubscribeInnerEvent(B.LOGOUT,this._reset,this),p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this),p.unSubscribeInnerEvent("im_open_push.msg_push",p.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const kc=new class{init(p){this.core=p}};function Pu(p){return mA(this,void 0,void 0,function*(){var B;const{message:M,user:G,appStore:O,constants:{OuterConstant:z}}=kc.core,X=O.conversationStore.getConversationMap();if(X.has(p)){const DA=(B=X.get(p))===null||B===void 0?void 0:B.userProfile;if(DA&&p.startsWith(z.CONV_C2C)){const{avatar:GA,nick:KA}=DA;kc.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:p,latestAvatar:GA,latestNick:KA,isSentByMe:!1})}}const{data:cA}=(yield G.userProfile.getMyProfile())||{};if(cA){const{avatar:DA,nick:GA}=cA;M.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:p,latestAvatar:DA,latestNick:GA,isSentByMe:!0})}})}function Ul(p){return mA(this,void 0,void 0,function*(){const B=p.map(M=>M.revoker);try{const M=yield function(G){return mA(this,void 0,void 0,function*(){var O,z;const X=yield(O=kc.core.user.userProfile)===null||O===void 0?void 0:O.getUserProfile({userIDList:G});return X?.data?(z=X.data)===null||z===void 0?void 0:z.reduce((cA,{userID:DA,nick:GA,avatar:KA})=>(cA[DA]={nick:GA||"",avatar:KA||""},cA),{}):null})}(B);M&&p.forEach(G=>{const{revoker:O}=G;M[O]&&(G.revokerInfo.nick=M[O].nick||"",G.revokerInfo.avatar=M[O].avatar||"",G.revokerInfo.userID=O)})}catch(M){console.debug(M)}})}const pd=1,ta=2,mI=20,Us=2500,BC=1,gl=300;function md(p){return mA(this,void 0,void 0,function*(){var B,M;const{appStore:G,utils:{isEmpty:O},common:{getCurrentUserID:z},notificationCenter:X,OuterEvent:cA,OuterConstant:{CONV_C2C:DA}}=kc.core,{messageList:GA,conversationID:KA}=p,re=G.conversationStore.getConversationMap();let Qe=(B=re.get(KA))===null||B===void 0?void 0:B.peerReadTime;if(!Qe){const lt=KA.replace(DA,""),dt=yield function(xt){return mA(this,void 0,void 0,function*(){const Wt={To_Account:xt};return kc.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:Wt})})}([lt]);if(dt){const{ReadTime:xt}=dt;Qe=xt?.[0],re.has(KA)&&(re.get(KA).peerReadTime=Qe)}}if(re.has(KA)){const lt=(M=re.get(KA))===null||M===void 0?void 0:M.lastMessage;O(lt)||lt.fromAccount===z()&<.lastTime<=Qe&&!lt.isPeerRead&&(lt.isPeerRead=!0,G.conversationStore.updateConversation(KA,{lastMessage:lt}))}const At=[];GA.forEach(lt=>{lt.time<=Qe&&!lt.isPeerRead&<.flow==="out"&&(lt.isPeerRead=!0,At.push(lt))}),At.length>0&&X.emitOuterEvent(cA.MESSAGE_READ_BY_PEER,{name:cA.MESSAGE_READ_BY_PEER,data:At})})}var fI=new class{init(p){this._core=p,p.helper.registerApi({apiName:"getMessageList",context:this}),p.helper.registerApi({apiName:"getMessageListHopping",context:this}),p.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(p){return mA(this,void 0,void 0,function*(){try{const{message:B,OuterConstant:{Direction:M,CONV_C2C:G,CONV_GROUP:O},InnerEvent:{HISTORY_MESSAGE_FETCHED:z},notificationCenter:X}=this._core,{conversationID:cA,nextReqMessageID:DA}=p,GA=mI;if(cA==="@TIM#SYSTEM")return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const KA=this._getAvailableLocalMessagesCount({conversationID:cA,nextReqMessageID:DA});if(this._needFetchHistoryMessageList({conversationID:cA,availableLocalMessagesCount:KA,targetCount:GA})){let re=null;if(cA.startsWith(O)?re=yield B.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:cA,sequence:Number(DA),count:GA,direction:M.FORWARD,shouldMarkCompleted:!0}):cA.startsWith(G)&&(re=yield B.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:cA,messageID:DA,count:GA,direction:M.FORWARD,shouldMarkCompleted:!0})),re){const{nextReqMessageIDFromServer:Qe,hasNoMoreHistoryMessage:At,messageList:lt}=re,dt=B.messageDataHandler.prependLocalMessageList({messageList:lt,conversationID:cA});(function(so){const{appStore:hi,message:qo,OuterConstant:cn}=kc.core,yi=hi.conversationStore.getConversation(so),to=qo.messageDataHandler.getLocalMessageList(so);if(!yi||to.length===0||so===cn.CONV_SYSTEM)return;const rs=[];for(let bt=0;btOA.isRevoked).length;be=rs.length-yi.unreadCount-bt}else be=rs.length-yi.unreadCount;for(let bt=0;btso.isRevoked);yield Ul(Wt),X.emitInnerEvent(z,dt);const Ki={nextReqMessageID:At?"":String(Qe),messageList:xt,isCompleted:At},Eo=xt.map(so=>so.sequence);return{code:0,data:Ki,successLog:{message:`conversationID: ${cA} nextReqMessageID: ${DA} availableLocalMessagesCount: ${KA} sequenceList: ${JSON.stringify(Eo)}`}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:cA,nextReqMessageID:DA,count:GA}),successLog:{message:`conversationID: ${cA} nextReqMessageID: ${DA} availableLocalMessagesCount: ${KA}}`}}}catch(B){const{code:M,message:G}=B||{};throw new this._core.helper.ChatError({code:M,message:G,moreMessage:`options: ${this._core.utils.safeStringify(p)}`})}})}getMessageListHopping(p){return mA(this,void 0,void 0,function*(){var B,M;const{OuterConstant:{Direction:G,CONV_C2C:O,CONV_GROUP:z},utils:{safeStringify:X}}=this._core,{conversationID:cA,sequence:DA,time:GA,direction:KA=G.FORWARD}=p,{utils:{isEmpty:re},message:Qe,notificationCenter:At,InnerEvent:{HISTORY_MESSAGE_FETCHED:lt}}=this._core;if(![G.BACKWARD,G.FORWARD].includes(KA))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${X(p)}`});let{count:dt=mI}=p;dt=dt>mI?mI:dt;let xt=null;if(cA.startsWith(z)){if(xt=yield Qe.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:cA,sequence:DA,count:dt,direction:KA}),xt){const{nextReqMessageIDFromServer:Wt,hasNoMoreHistoryMessage:Ki,messageList:Eo,invisibleSequenceList:so}=xt;if(this._core.message.messageDataHandler.storeSparseMessageList(Eo),At.emitInnerEvent(lt,Eo),KA===G.FORWARD){const hi=Ki&&Wt<1;return{code:0,data:{messageList:Eo,isCompleted:hi,nextMessageSeq:hi?"":Wt}}}if(KA===G.BACKWARD){if(re(Eo)&&re(so))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const hi=((B=Eo?.[Eo.length-1])===null||B===void 0?void 0:B.sequence)||0,qo=((M=so?.[so.length-1])===null||M===void 0?void 0:M.sequence)||0;return{code:0,data:{messageList:Eo.filter(cn=>cn.sequence>=DA),isCompleted:!Ki,nextMessageSeq:Ki?Math.max(hi,qo)+1:""}}}return{code:0,data:xt}}}else if(cA.startsWith(O)&&(xt=yield Qe.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:cA,count:dt+1,time:GA,direction:KA}),xt)){const{messageList:Wt,lastMessageTime:Ki,hasNoMoreHistoryMessage:Eo}=xt;return At.emitInnerEvent(lt,Wt),Eo||(KA===G.FORWARD?Wt.shift():Wt.pop()),Qe.messageDataHandler.storeSparseMessageList(Wt),yield md({messageList:Wt,conversationID:cA}),{code:0,data:{messageList:Wt,isCompleted:Eo,nextMessageTime:Eo?"":Ki}}}})}clearHistoryMessage(p){return mA(this,void 0,void 0,function*(){var B;const{appStore:M,common:{ChatError:G,getCurrentUserID:O},OuterConstant:{CONV_C2C:z,CONV_GROUP:X},apiMap:cA,message:DA}=this._core,GA=M.conversationStore.getConversation(p);if(!GA)throw new G({code:Us});const KA={fromAccount:O()},{type:re}=GA;re===z?(KA.type=pd,KA.toAccount=p.replace(z,"")):re===X&&(KA.type=ta,KA.toGroupID=p.replace(X,""));try{return yield(B=cA?.setMessageRead)===null||B===void 0?void 0:B.call(cA,{conversationID:p}),(yield function(At){return mA(this,void 0,void 0,function*(){const{fromAccount:lt,type:dt,toAccount:xt,toGroupID:Wt}=At,Ki={From_Account:lt,Type:dt,To_Account:xt,ToGroupid:Wt};return kc.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:Ki})})}(KA))&&(DA.messageDataHandler.deleteConversationMessageList(p),DA.messageHistory.completedHistoryConversations.delete(p),DA.messageHistory.clearHistoryMessageListFetchAnchors(p),this._updateConversationLastMessage(p)),{code:0,data:{conversationID:p},successLog:{message:`convID:${p}`}}}catch(Qe){const{errorCode:At}=Qe;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:At,moreMessage:`convID:${p}`})}})}_updateConversationLastMessage(p){const{appStore:B}=this._core;B.conversationStore.updateConversation(p,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:p,nextReqMessageID:B}){const{OuterConstant:{CONV_C2C:M,CONV_GROUP:G}}=this._core,O=this._core.message.messageDataHandler.getLocalMessageList(p),{length:z}=O;if(!B)return z;let X=-1;return p?.startsWith(M)?X=O.findIndex(cA=>cA.ID===B):p?.startsWith(G)&&(X=O.findIndex(cA=>B.includes("-")?cA.ID===B:String(cA.sequence)===B)),X===-1?0:X}_needFetchHistoryMessageList({conversationID:p,availableLocalMessagesCount:B,targetCount:M}){const{message:G}=this._core;return BB.startsWith(O)?Qe.ID===M:String(Qe.sequence)===M),KA=re>G?re-G:0,DA=re):KA=cA>G?cA-G:0,GA.messageList=X.slice(KA,re),GA.isCompleted=DA<=G&&z.messageHistory.completedHistoryConversations.has(B),GA.isCompleted?GA.nextReqMessageID="":GA.nextReqMessageID=this._generateNextReqMessageID({conversationID:B,targetIndex:KA}),B.startsWith(O)&&(yield Pu(B),yield md({messageList:GA.messageList,conversationID:B})),GA})}_generateNextReqMessageID({conversationID:p,targetIndex:B}){const M=this._core.message.messageDataHandler.getLocalMessageList(p);return p.startsWith("C2C")?M[B].ID:String(M[B].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}},Ha=new class{constructor(){this._lastMessageSequenceMapOnDisconnect=new Map,this._lastMessageTimeMapOnDisconnect=new Map}init(p){this._core=p;const{common:{workflowManager:B},constants:{WORKFLOW_NAME:M,WORKFLOW_STEP:G,InnerEvent:O}}=p;B.registerWorkflowStep(M.SYNC_SERVER_INFO_AFTER_RE_ONLINE,G.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),B.registerWorkflowStep(M.SYNC_SERVER_INFO_AFTER_RE_ONLINE,G.C2C_HISTORY_MESSAGE_RECOVER,this._syncC2COfflineMessage,this),p.notificationCenter.subscribeInnerEvent(O.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncGroupOfflineMessage(p){const{conversationList:B}=p?.result||{},{OuterConstant:M,utils:{isArray:G}}=this._core;if(G(B)){const O=B.filter(z=>z.type===M.CONV_GROUP&&z.groupProfile.type!==M.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(O)}}_recoverGroupHistoryMessage(p){return mA(this,void 0,void 0,function*(){const{OuterConstant:B}=this._core,M=[],G=[];return yield Promise.all(p?.map(O=>mA(this,void 0,void 0,function*(){const{groupProfile:{groupID:z}={},lastMessage:{lastSequence:X}={}}=O,cA=`${B.CONV_GROUP}${z}`;let DA=this._getLocalLastMessageSequence(cA);this._shouldRecoverHistory({localLastMessageSequence:DA,serverLastMessageSequence:X})&&(yield this._recoverGroupHistoryForConversation({conversationID:cA,localLastMessageSequence:DA,serverLastMessageSequence:X,groupTipList:G})),M.push(cA.replace(B.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:M,groupTipList:G}})}_recoverGroupHistoryForConversation(p){return mA(this,arguments,void 0,function*({conversationID:B,localLastMessageSequence:M,serverLastMessageSequence:G,groupTipList:O}){try{const{utils:{isArray:z,isObject:X,isEmpty:cA},OuterEvent:DA,OuterConstant:GA,notificationCenter:KA,message:re,appStore:Qe,common:{getMessagePreviewText:At,buildLastMessage:lt}}=this._core,dt=G-M,xt=Math.min(20,dt),Wt={},Ki=yield re.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:B,sequence:M+xt,direction:GA.Direction.FORWARD,count:xt}),{nextReqMessageIDFromServer:Eo,hasNoMoreHistoryMessage:so,messageList:hi,serverGroupTipList:qo}=Ki;z(qo)&&O.push(...qo);const cn=so&&Eo<0,yi=[];if(z(hi)&&(hi.forEach(to=>{re.messageReceiver.groupMessageReceiver.updateMessageProfile(to),to.from===GA.CONV_SYSTEM&&(to.isSystemMessage=!1),re.messageDataHandler.storeConversationMessage(to)&&!cA(to.payload)&&(yi.push(to),to._isExcludedFromLastMessage||(Wt.lastMessage=lt(to)))}),yi.length>0&&KA.emitOuterEvent(DA.MESSAGE_RECEIVED,{name:DA.MESSAGE_RECEIVED,data:yi})),!cn&&hi.length>0){const to=hi[hi.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:B,localLastMessageSequence:to,serverLastMessageSequence:G,groupTipList:O})}X(Wt.lastMessage)&&(Wt.lastMessage.messageForShow=At(Wt.lastMessage.type,Wt.lastMessage.payload),Qe.conversationStore.updateConversation(B,Wt))}catch(z){this._core.ssoLog.error("_recoverGroupHistoryForConversation",`Recovery failed for conversation:${B}`,{error:z})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:p}=this._core,B=p.messageDataHandler.getContinuousMessagesByConversation();for(const[M,G]of B){const O=Array.from(G.values());if(O?.length>0){const z=O[O.length-1];M.startsWith("C2C")?this._lastMessageTimeMapOnDisconnect.set(M,z.time):M.startsWith("GROUP")&&this._lastMessageSequenceMapOnDisconnect.set(M,z.sequence)}}}_getLocalLastMessageSequence(p){const{message:B}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(p))return this._lastMessageSequenceMapOnDisconnect.get(p);const M=B.messageDataHandler.getLocalMessageList(p),G=M[M.length-1];return G?.sequence}_shouldRecoverHistory(p){const{localLastMessageSequence:B,serverLastMessageSequence:M}=p;if(typeof B!="number"||typeof M!="number")return!1;const G=M-B;return M!==0&&B>0&&G>=BC&&G{z.type===M.CONV_C2C&&O.push(z)}),this._recoverC2CHistoryMessage(O)}}_recoverC2CHistoryMessage(p){return mA(this,void 0,void 0,function*(){yield Promise.all(p?.map(B=>mA(this,void 0,void 0,function*(){const{conversationID:M,lastMessage:{lastTime:G}={}}=B,O=this._getLocalLastMessageTime(M);this._shouldRecoverC2CHistory({localLastMessageTime:O,serverLastMessageTime:G})&&(yield this._recoverHistoryForC2CConversation({conversationID:M,localLastMessageTime:O,serverLastMessageTime:G}))})))})}_shouldRecoverC2CHistory(p){const{localLastMessageTime:B,serverLastMessageTime:M}=p,G=M-B;return B>0&&G>=1&&G<=600}_recoverHistoryForC2CConversation(p){return mA(this,void 0,void 0,function*(){var B;const{conversationID:M,localLastMessageTime:G,serverLastMessageTime:O}=p,{utils:{isArray:z,isObject:X,isEmpty:cA,safeStringify:DA},OuterEvent:GA,OuterConstant:KA,notificationCenter:re,message:Qe,appStore:At,common:{getMessagePreviewText:lt,buildLastMessage:dt}}=this._core;try{const xt={},Wt=yield Qe.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,direction:KA.Direction.BACKWARD,time:G,count:20});if(cA(Wt))return;const{hasNoMoreHistoryMessage:Ki,messageList:Eo}=Wt,so=[];z(Eo)&&(Eo.forEach(qo=>{Qe.messageDataHandler.storeConversationMessage(qo)&&!cA(qo.payload)&&(so.push(qo),qo._isExcludedFromLastMessage||(xt.lastMessage=dt(qo)))}),so.length>0&&re.emitOuterEvent(GA.MESSAGE_RECEIVED,{name:GA.MESSAGE_RECEIVED,data:so}));const hi=(B=Eo[Eo.length-1])===null||B===void 0?void 0:B.time;!Ki&&hi>O&&(yield this._recoverHistoryForC2CConversation({conversationID:M,localLastMessageTime:hi,serverLastMessageTime:O})),X(xt.lastMessage)&&(xt.lastMessage.messageForShow=lt(xt.lastMessage.type,xt.lastMessage.payload),At.conversationStore.updateConversation(M,xt))}catch(xt){this._core.ssoLog.error("_recoverHistoryForC2CConversation",`Recovery failed for conversation:${M} error: ${DA(xt)}`)}})}_getLocalLastMessageTime(p){const{message:B}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(p))return this._lastMessageTimeMapOnDisconnect.get(p);const M=B.messageDataHandler.getLocalMessageList(p),G=M[M.length-1];return G?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},QC=new class{constructor(){this.name="HistoryMessage"}install(p){this._core=p,kc.init(p),fI.init(p),Ha.init(p),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.LOGOUT,this._reset,this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(B.LOGOUT,this._reset,this),p.unSubscribeInnerEvent(B.DESTROY,this.dispose,this),Ha.dispose()}_reset(){Ha.reset()}},Ja=new class{init(p){this.core=p}},yr=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(p){const{helper:{registerExperimentalAPI:B}}=p;this._core=p,B("reportModalView",this),B("reportTUIFeatureUsage",this),B("reportRoomEngineEvent",this)}reportModalView(p){const{ssoLog:B,utils:{safeStringify:M,isString:G}}=this._core;try{if(!G(p))throw new Error("reportModalView data is not a string");B.createSSOLogData({method:"reportModalView",message:p,eventType:30}).end(!0)}catch(O){B.debug(`reportModalView Report failed: ${M(O)}`)}}reportTUIFeatureUsage(p){const{ssoLog:B,utils:{safeStringify:M,isEmpty:G}}=this._core,{atomicStoreID:O}=p;try{G(O)||this._reportedAtomicStoreIDs.has(O)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${p.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:O}),this._reportedAtomicStoreIDs.add(O))}catch(z){B.debug(`reportTUIFeatureUsage Report failed: ${M(z)}`)}}reportRoomEngineEvent(p){const{utils:{safeStringify:B},ssoLog:M}=this._core;try{M.debug(`reportRoomEngineEvent Report: ${B(p)}`);const{eventId:G,eventCode:O,eventResult:z,eventMessage:X,moreMessage:cA,extensionMessage:DA}=p;M.createSSOLogData({method:DA,code:G,message:X,eventType:30,costTime:O,uiPlatform:z,moreMessage:cA}).end(!0)}catch(G){M.debug(`reportRoomEngineEvent Report failed: ${B(G)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},fd=new class{constructor(){this.name="DataReport"}install(p){this._core=p;const{notificationCenter:B,InnerEvent:{LOGOUT:M,DESTROY:G}}=p;Ja.init(p),yr.init(p),B.subscribeInnerEvent(M,this._reset,this),B.subscribeInnerEvent(G,this._dispose,this)}_reset(){yr.reset()}_dispose(){const{notificationCenter:p,InnerEvent:{LOGOUT:B,DESTROY:M}}=this._core;p.unSubscribeInnerEvent(B,this._reset,this),p.unSubscribeInnerEvent(M,this._dispose,this),yr.dispose()}};let xu=ma.STANDARD,Dr=[];xu=ma.BASIC,Dr=[dC,lh,Io,Ou,Eg,QC,fd];function Lc(p,B){const{operationType:M,memberInfoList:G,operatorInfo:O}=p||{};let z={};if(tn(G)?tn(O)||(z=O):M!==ga.JOINED&&M!==ga.KICKED&&M!==ga.ADMIN_SET&&M!==ga.ADMIN_CANCELED||(z=Object.assign({},G[0])),!tn(z)){const{nick:X="",avatar:cA=""}=z;B.nick=X,B.avatar=cA}}const cl=p=>({lastTime:p?.time||p?.lastTime||0,lastSequence:p?.sequence||p?.lastSequence||0,fromAccount:p?.from||p?.fromAccount||"",messageForShow:XI(p?.type,p?.payload),payload:p?.payload||null,type:p?.type||"",isRevoked:p?.isRevoked||!1,cloudCustomData:p?.cloudCustomData||"",onlineOnlyFlag:p?._onlineOnlyFlag||!1,nick:p?.nick||"",nameCard:p?.nameCard||"",version:p?.version||0,isPeerRead:p?.isPeerRead||!1,revoker:p?.revoker||null});var Pg=Object.freeze({__proto__:null,ChatError:dn,WorkflowManager:us,buildAndSendPacket:ic,buildLastMessage:cl,get builtInPlugins(){return Dr},checkBusinessCapabilityBits:el,deepMerge:Va,getCurrentUserID:$s,getErrorMessage:kl,getMessagePreviewText:XI,isC2CConv:p=>c(p)&&p.slice(0,3)===bg.CONV_C2C,isCommunity:fa,isGroupConv:p=>c(p)&&p.slice(0,5)===bg.CONV_GROUP,isInternational:Lu,isTopic:ea,isUnlimitedAVChatRoom:function(){var p;return!!(!((p=ve.store.get("instance"))===null||p===void 0)&&p.unlimitedAVChatRoom)},liteChatInstanceMap:Pn,registerInterceptor:wr,registerValidateConfig:Gc,requireAuth:hn,get sdkEdition(){return xu},setGroupTipsUserInfo:Lc,t:EC,updateGroupAtInfo:(p,B)=>{const{CONV_AT_ME:M,CONV_AT_ALL:G,CONV_AT_ALL_AT_ME:O}=Sn;if(function(cA,DA){const{CONV_AT_ME:GA,CONV_AT_ALL:KA,CONV_AT_ALL_AT_ME:re}=Sn,{groupID:Qe,sequence:At}=cA;let lt=!1;return fa({groupID:Qe})&&DA.forEach(dt=>{dt.messageSequence===At&&(dt.atTypeArray.includes(GA)&&cA.groupAtType.includes(KA)&&(dt.atTypeArray=[re]),dt.atTypeArray.includes(KA)&&cA.groupAtType.includes(GA)&&(dt.atTypeArray=[re],dt.__random=cA.__random,dt.__sequence=cA.__sequence),lt=!0)}),lt}(p,B))return;let z=[...p.groupAtType];z.includes(M)&&z.includes(G)&&(z=[O]);const X={from:p.from,groupID:p.groupID,topicID:p.topicID,messageSequence:p.sequence,atTypeArray:z,__random:p.__random,__sequence:p.__sequence};B.push(X)},validateAndExecute:Ll,validateParameters:dd});class Jo{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return Jo._instance||(Jo._instance=new Jo),Jo._instance}static setInstance(B){Jo._instance=B}installBuiltInPlugin(B){B&&this._installPlugin(B,this._builtInPlugins)}installExternalPlugin(B){B&&this._installPlugin(B,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(B,M){let G=[];G=C(B)?B:[B];const O=G.findIndex(X=>X?.name==="AVChatRoom"),z=O>-1?G.splice(O,1):[];G.forEach(X=>{this._isPluginInstalled(X.name)||(X&&Se(X.install)?(M.add(X.name),Se(X.getInstalledSubPlugins)?(z?.forEach(cA=>M.add(cA?.name)),X.install(ss.getInstance().exposeApiForPlugin(),z)):X.install(ss.getInstance().exposeApiForPlugin()),Se(X.handleLoginSuccess)&&this._isLoggedIn()&&X.handleLoginSuccess()):Se(X)?(M.add(X.name),X(ss.getInstance().exposeApiForPlugin()),Se(X.handleLoginSuccess)&&this._isLoggedIn()&&X.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(B){return this._builtInPlugins.has(B)||this._externalPlugins.has(B)}_isLoggedIn(){var B;return((B=ve.store.get("login"))===null||B===void 0?void 0:B.isLoggedIn)===!0}}var nc=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(p){return this._conversationMap.get(p)}updateConversation(p,B,M){const{emit:G=!0,needSort:O=!1}=M||{},z=this._conversationMap.get(p);z&&!tn(B)&&(Object.keys(B).forEach(X=>{z[X]=B[X]}),G&&ve.notificationCenter.emitInnerEvent(Ci.CONVERSATION_UPDATED,{needSort:O}))}deleteConversation(p){this._conversationMap.has(p)&&(this._conversationMap.delete(p),ve.notificationCenter.emitInnerEvent(Ci.CONVERSATION_UPDATED))}},eg=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(p){return this._groupMap.get(p)}updateGroup(p,B){const M=this._groupMap.get(p);M&&!tn(B)&&Object.keys(B).forEach(G=>{M[G]=B[G]})}},Fl=new class{constructor(){this._messagesByConversation=new Map}updateMessage(p,B,M){var G;const{operation:O,updateUnreadCount:z=!0}=M,X=vo(M,["operation","updateUnreadCount"]),cA=[];for(const DA of B){const GA=(G=this._messagesByConversation.get(p))===null||G===void 0?void 0:G.get(DA);if(!GA)return!1;Object.keys(X).forEach(KA=>{GA[KA]=X[KA]}),cA.push(GA)}return this._emitMessageStoreOperationEvent(O,{conversationID:p,messageList:cA,updateUnreadCount:z}),cA}getMessagesByConversation(p){var B;return[...((B=this._messagesByConversation.get(p))===null||B===void 0?void 0:B.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(p,B){const{conversationID:M}=B;ea(M)?ve.notificationCenter.emitInnerEvent(Ig[p],B):ve.notificationCenter.emitInnerEvent(p,B)}},ia=new class{constructor(){this.userProfileMap=new Map,this.friendMap=new Map}getUserProfileMap(){return this.userProfileMap}getFriendMap(){return this.friendMap}getUserProfile(p){return this.userProfileMap.get(p)}getFriend(p){return this.friendMap.get(p)}},uh=Object.freeze({__proto__:null,conversationStore:nc,groupStore:eg,messageStore:Fl,userStore:ia});class ss{static getInstance(){return ss._instance||(ss._instance=new ss),ss._instance}static setInstance(B){ss._instance=B}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:ve.notificationCenter.subscribeOuterEvent.bind(ve.notificationCenter),off:ve.notificationCenter.unSubscribeOuterEvent.bind(ve.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:Jo.getInstance().installExternalPlugin.bind(Jo.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(B){ve.ssoLog.debug("registerPlugin",B)}statKeyFeatureUsage(B){ve.ssoLog.debug("statTUIKeyFeatures",B)}setLogLevel(B){ve.ssoLog.debug("setLogLevel",B),ve.ssoLog.setLogLevel(B)}setApplicationID(B){ve.store.set("instance",{applicationID:B})}getApiMap(){return this._apiMap}setApiMap(B){this._apiMap=B}registerApi(B){const{common:{timeManager:M},utils:{safeStringify:G}}=ve,{apiName:O,context:z,methodName:X=O,matcher:cA}=B;this._apiHandlersMap[O]||(this._apiHandlersMap[O]=[]),this._apiHandlersMap[O].push({context:z,methodName:X,matcher:cA}),this._apiMap[O]&&this._apiHandlersMap[O].length!==1||(this._apiMap[O]=(...DA)=>{const GA=M.getServerTimeMs();let KA=0;O==="login"&&(KA=4),hr.includes(O)&&ve.ssoLog.debug(O,`${O} start params: ${G(DA)}`),Ll(X,DA);const re=this._apiHandlersMap[O];for(const Qe of re)if(!Qe.matcher||Qe.matcher(DA))try{const At=Qe.context[Qe.methodName].bind(Qe.context)(...DA);return this._isPromiseLike(At)?this._handleAsyncResult(At,O,KA,GA):(this._reportApiSuccessLog({result:At,apiName:O,eventType:KA,startTime:GA}),At)}catch(At){throw ve.ssoLog.error(O,`${O} fail ${At?.message||At?.errorMessage})`,{error:At,costTime:M.getServerTimeMs()-GA,eventType:KA,method:O}),At}})}registerExperimentalAPI(B,M,G){const O=G||B;this._experimentalApiMap[B]=M[O].bind(M)}destroy(){return mA(this,void 0,void 0,function*(){var B,M;try{!((B=ve.store.get("login"))===null||B===void 0)&&B.isLogin&&(yield this._apiMap.logout()),ve.notificationCenter.emitInnerEvent(Ci.DESTROY)}catch(G){console.debug("destroy error: ",G)}finally{ve.notificationCenter.emitOuterEvent(Ts.SDK_DESTROY,{SDKAppID:(M=ve.store.get("instance"))===null||M===void 0?void 0:M.sdkAppId}),Pn.clear(),Jo.getInstance().clear(),us.getInstance().destroy(),ve.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:Ci,InnerEventSubType:ve.notificationCenter.InnerEventSubType,OuterEvent:Ts,OuterConstant:Sn,SignalingEvent:lo,helper:Object.assign(Object.assign(Object.assign({},ve.utils),ve.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:wr,registerValidateConfig:Gc,checkBusinessCapabilityBits:el,registerWorkflowStep:us.getInstance().registerWorkflowStep.bind(us.getInstance()),ChatError:dn}),apiMap:this._apiMap},ve),{constants:Object.assign(Object.assign({},zI),ve.constants),common:Object.assign(Object.assign(Object.assign({},Pg),ve.common),{workflowManager:us.getInstance()}),utils:ve.utils,appStore:uh})}callExperimentalAPI(B,M){return ve.ssoLog.debug(`callExperimentalAPI.${B} start params: ${ve.utils.safeStringify(M)}`),this._experimentalApiMap[B]?this._experimentalApiMap[B](M):(ve.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${B} not found, params: ${ve.utils.safeStringify(M)}`),Promise.reject(new dn({code:Po.INVALID_OPERATION})))}_isPromiseLike(B){return B!==null&&typeof B=="object"&&typeof B.then=="function"}_handleAsyncResult(B,M,G,O){return B.then(z=>(this._reportApiSuccessLog({result:z,apiName:M,eventType:G,startTime:O}),z)).catch(z=>{throw ve.ssoLog.error(M,`${M} fail ${z?.message||z?.errorMessage})`,{error:z,costTime:ve.common.timeManager.getServerTimeMs()-O,eventType:G,method:M,startTime:O}),z})}_reportApiSuccessLog(B){let{result:M,apiName:G,startTime:O,eventType:z}=B;const{timeManager:X}=ve.common,{successLog:{message:cA,moreMessage:DA}={message:"",moreMessage:""}}=M||{},GA=X.getServerTimeMs();G==="login"&&(O+=X.getTimeOffsetWithServer()),hr.includes(G)&&ve.ssoLog.info(G,`${G} success ${cA} ${DA}`,{costTime:GA-O,eventType:z,message:cA,moreMessage:DA,startTime:O}),M?.successLog&&delete M.successLog}}class tu{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:B,store:M}=ve;M.set("login",{isReady:!1}),ss.getInstance().registerApi({apiName:"login",context:this}),ss.getInstance().registerApi({apiName:"logout",context:this}),ss.getInstance().registerApi({apiName:"getLoginUser",context:this}),ss.getInstance().registerApi({apiName:"isReady",context:this}),ss.getInstance().registerApi({apiName:"getServerTime",context:this}),ss.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),B.subscribeInnerEvent(Ci.RECONNECTED,this._reLogin,this),ve.notificationCenter.subscribeInnerEvent(Ci.DESTROY,this._dispose,this)}login(B){return mA(this,void 0,void 0,function*(){var M;const{sdkEdition:G}=ve.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new dn({functionName:"login",code:Po.REPEAT_LOGIN});const O=yield this._performLogin(B);this._validateAfterLogin(O),this._handleLoginSuccess(O),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const z=(M=ve.channel.getSocketAdapter())===null||M===void 0?void 0:M.getId(),{appId:X,href:cA}=ve.store.get("instance")||{},{instanceID:DA,customStatus:GA}=O||{};return{code:0,data:O,successLog:{message:G,moreMessage:`socketID:${z} instanceID:${DA} customStatus:${GA} href: ${cA} appId: ${X}`}}}catch(O){const{errorCode:z}=O;z!==Po.REPEAT_LOGIN&&(this._latestLoginAt=0);const X=new dn({functionName:"login",code:z});throw console.error(X),X}})}_reLogin(){return mA(this,void 0,void 0,function*(){var B;try{if(!this._isLoginIn())return;const M=yield ku(this._customLoginInfo);if(M){const{instanceID:G,customStatus:O}=M;ve.store.set("login",{statusInstanceId:G}),us.getInstance().executeWorkflow(Cr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:O,statusType:Nu.USER_STATUS_ONLINE});const z=(B=ve.channel.getSocketAdapter())===null||B===void 0?void 0:B.getId();ve.ssoLog.info("reLogin",`socketId:${z} instanceId:${G}`)}}catch(M){console.warn(M)}})}logout(){return mA(this,arguments,void 0,function*(B=Ag.USER_INITIATED){const{ssoLog:M}=ve;M.debug("logout",`logout start logoutReason: ${B}`);try{yield this._performLogout(B),M.info("logout","logout success"),ve.ssoLog.uploadSSOLogData()}catch(G){const{errorCode:O}=G;throw new dn({functionName:"logout",code:O})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?$s():""}isReady(){var B;return(B=ve.store.get("login"))===null||B===void 0?void 0:B.isReady}setCustomLoginInfo(B=""){this._customLoginInfo=B}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),us.getInstance().reset(),ve.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:B}=ve.common;return B.getServerTimeMs()}_updateAndEmitSDKReady(){ve.store.set("login",{isReady:!0}),setTimeout(()=>{ve.notificationCenter.emitOuterEvent(Ts.SDK_READY,{name:Ts.SDK_READY})},1)}_updateAndEmitSDKNotReady(){ve.store.set("login",{isReady:!1}),ve.notificationCenter.emitOuterEvent(Ts.SDK_NOT_READY,{name:Ts.SDK_NOT_READY})}_validateAfterLogin(B){const M="login";if(!B)throw new dn({functionName:M,message:"login response is empty"});const{tinyID:G,a2Key:O}=B||{};if(!G)throw new dn({functionName:M,code:Po.NO_TINYID});if(!O)throw new dn({functionName:M,code:Po.NO_A2KEY})}_createRepeatLoginResponse(){var B;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:kl({code:"RepeatLogin",replacement1:(B=ve.store.get("login"))===null||B===void 0?void 0:B.userId}),repeatLogin:!0}}}_performLogin(B){return mA(this,void 0,void 0,function*(){const{userID:M,userSig:G}=B;return ve.store.set("login",{userId:M,userSig:G}),this._latestLoginAt=Date.now(),ku(this._customLoginInfo)})}_ensureAsyncComplete(){return mA(this,void 0,void 0,function*(){yield new Promise(B=>{setTimeout(()=>B(null),1)})})}_handleLoginSuccess(B){const{timeManager:M}=ve.common,{helloInterval:G,timeStamp:O,customStatus:z,purchaseBits:X}=B,cA=1e3*O;M.calculateTimeOffsetWithServer(this._latestLoginAt,cA),this._helloInterval=G||120,this._updateLoginStore(B),ve.user.userStatus.setCustomStatus(z),us.getInstance().executeWorkflow(Cr.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:X}),ve.common.taskScheduler.addTask({id:Gu,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(B){return function(M){return mA(this,void 0,void 0,function*(){const{logoutReason:G}=M,O="im_open_status.wslogout",z=ve.common.generateProtocolData({servcmd:O,data:{wslogout_type:G,isWebUniapp:0}}),X=`${z.head.seq}${O}`;return yield ve.channel.sendPacket(z,{requestId:X})})}({logoutReason:B})}_updateLoginStore(B){const{a2Key:M,tinyID:G,instanceID:O,authKey:z}=B;ve.store.set("login",{a2Key:M,tinyID:G,statusInstanceId:O,authKey:z,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return mA(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const B="im_open_status.wshello",M=ve.common.generateProtocolData({servcmd:B,data:{isWebUniapp:0}}),G=`${M.head.seq}${B}`;return ve.channel.sendPacket(M,{requestId:G})}()}catch(B){ve.ssoLog.warn("_sendOnlinePresenceRequest",` error:${B.message}`)}})}_isLoginIn(){var B;return((B=ve.store.get("login"))===null||B===void 0?void 0:B.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){ve.common.taskScheduler.removeTask(Gu),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",ve.store.clear("login"),ve.store.set("login",{isReady:!1}),ve.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:B}=ve;B.unSubscribeInnerEvent(Ci.RECONNECTED,this._reLogin,this),B.unSubscribeInnerEvent(Ci.DESTROY,this._dispose,this)}}const Wn={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},Uc={logout:!0};class sc{constructor(){this.loginAction=new tu,this.kickedOutHandler=new Nc,this.loginAction.init(),this.kickedOutHandler.init(),Gc({auth:Uc,params:Wn})}}var Sr,Kr,tg;(function(p){p.CONV_C2C="C2C",p.CONV_GROUP="GROUP",p.CONV_TOPIC="TOPIC",p.CONV_SYSTEM="@TIM#SYSTEM"})(Sr||(Sr={})),function(p){p.MSG_PRIORITY_HIGH="High",p.MSG_PRIORITY_NORMAL="Normal",p.MSG_PRIORITY_LOW="Low",p.MSG_PRIORITY_LOWEST="Lowest"}(Kr||(Kr={})),function(p){p.MSG_TEXT="TIMTextElem",p.MSG_CUSTOM="TIMCustomElem",p.MSG_LOCATION="TIMLocationElem",p.MSG_FACE="TIMFaceElem",p.MSG_IMAGE="TIMImageElem",p.MSG_AUDIO="TIMSoundElem",p.MSG_FILE="TIMFileElem",p.MSG_VIDEO="TIMVideoFileElem",p.MSG_GRP_TIP="TIMGroupTipElem",p.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",p.MSG_MERGER="TIMRelayElem"}(tg||(tg={}));const LE={1:Kr.MSG_PRIORITY_HIGH,2:Kr.MSG_PRIORITY_NORMAL,3:Kr.MSG_PRIORITY_LOW,4:Kr.MSG_PRIORITY_LOWEST},pC=0,Eh=1;var uo;(function(p){p.IN="in",p.OUT="out"})(uo||(uo={}));const Fc=2,Ol={};function mC(p){if(!p)return 0;if(Ol[p]===void 0){const B=new Date,M=`3${B.getHours()}`.slice(-2),G=`0${B.getMinutes()}`.slice(-2),O=`0${B.getSeconds()}`.slice(-2);Ol[p]=parseInt([M,G,O,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${Ol[p]}`)}else Ol[p]+=1;return Ol[p]}class fC{constructor(B){this.ID="",this.random=0,this.sequence=0,this.nameCard="",this.isRead=!1,this.isPeerRead=!1,this.isDeleted=!1,this.isResend=!1,this.hasRiskContent=!1,this._onlineOnlyFlag=!1,this.atUserList=[],this._groupAtInfoList=[],this.isBroadcastMessage=!1,this.priority=Kr.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:M=ve.common.timeManager.getServerTimeSeconds()||0,senderTinyID:G,currentUser:O,needReadReceipt:z,isSupportExtension:X,customModerationConfigurationId:cA,to:DA,from:GA,nick:KA="",avatar:re="",time:Qe,messageControlInfo:At,tinyID:lt,cloudCustomData:dt="",messageLifeTime:xt,messageVersion:Wt=0,conversationType:Ki,sequence:Eo,checkResult:so=0,isPlaceMessage:hi=0,messageFlagBits:qo,receiverList:cn,isSystemMessage:yi=!1,status:to=Gg.SUCCESS,revokeReason:rs="",conversationSubType:be,clientSequence:bt,protocol:OA="JSON",revokerInfo:oi={userID:"",nick:"",avatar:""},readReceiptInfo:ms={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:si,groupProfile:Dn,atUserList:Ni,flow:yo,isRead:yt=!1,priority:St=Kr.MSG_PRIORITY_NORMAL,onlineOnlyFlag:hg=!1,nameCard:qn="",quoteInfo:io}=B;var Wr;this.clientTime=M,this.senderTinyID=G||lt,this.needReadReceipt=z===!0||z===1,this.isSupportExtension=X===!0||X===1,this._cmConfigID=cA,this.to=DA,this.nick=KA,this.avatar=re,this.protocol=OA,this.random=si===void 0?(Wr=Wr||99999999,Math.round(Math.random()*Wr)):si,this.time=Qe||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!At?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!At?.excludedFromUnreadCount,this.isModified=!!Wt,this.cloudCustomData=dt,this.messageLifeTime=xt,this.from=GA||null,this.sequence=Eo||0,this.conversationType=Ki||Sr.CONV_C2C,this.hasRiskContent=so>1,this.version=Wt,this.isPlaceMessage=hi,this.isRevoked=hi===2||qo===8,this.isSystemMessage=yi,this.readReceiptInfo=ms,this.revokeReason=rs,this.revokerInfo=oi,this._receiverList=cn,this.conversationSubType=be,this.revoker=oi?.revoker||"",this.clientSequence=bt||Eo||0,this.status=to,this.atUserList=Ni||[],this.flow=yo,this.isRead=yt,this.priority=St,this._onlineOnlyFlag=hg,this.nameCard=qn,this.quoteInfo=io,this.reInitialize(O),this._initC2CReadReceiptInfo(B),this._extractGroupInfo(Dn)}getElements(){return this._elements}isOnlineMessage(){return this.messageLifeTime===0}setElement(B){Array.isArray(B)?this._elements=B:this._elements=[B],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(B=>B.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(B){this._relayFlag=B}validateBeforeSend(){var B,M,G;return this._relayFlag?{isValid:!0}:((B=this._elements)===null||B===void 0?void 0:B.length)>0?(G=(M=this._elements[0])===null||M===void 0?void 0:M.validateBeforeSend)===null||G===void 0?void 0:G.call(M):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(B){const{readReceiptSentByPeer:M,timestamp:G=0}=B;this.conversationType===Sr.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=M===1,this.readReceiptInfo.timestamp=G)}_extractGroupInfo(B){if(!B)return;const{From_AccountNick:M,From_AccountHeadurl:G,MsgFrom_AccountExtraInfo:O,GroupType:z}=B,{NameCard:X}=O||{};typeof M=="string"&&(this.nick=M),typeof G=="string"&&(this.avatar=G),typeof X=="string"&&(this.nameCard=X),this.conversationSubType=z}reInitialize(B){B===this.from&&(this.isRead=!0),this._initSequence(B),this._concatConversationID(B),this.generateMessageID()}_concatConversationID(B){let M="";const G=this.conversationType;G!==Sr.CONV_SYSTEM?(M=G===Sr.CONV_C2C?B===this.from?this.to:this.from:this.to,this.conversationID=M?`${G}${M}`:null):this.conversationID=Sr.CONV_SYSTEM}_initSequence(B){this.clientSequence===0&&B&&(this.clientSequence=mC(B)),this.sequence===0&&this.conversationType===Sr.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Sr.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(B){this.isRead=B}}class Pl{static parseServerPushElement(B){const{MsgContent:M={}}=B,{Data:G,Ext:O,Desc:z}=M;return new Pl({data:G,description:z,extension:O})}constructor(B){this.type=tg.MSG_CUSTOM;const{data:M="",description:G="",extension:O=""}=B;this.content={data:M,description:G,extension:O}}transformToServerFormat(B){const{isMergerMessage:M=!1}=B||{},G=M?this.payload:this.content,{data:O,description:z,extension:X}=G;return{MsgType:this.type,MsgContent:{Data:O,Ext:X,Desc:z}}}validateBeforeSend(){const{isEmpty:B}=ve.utils,M=[this.content.data,this.content.description,this.content.extension].some(G=>!B(G));return{isValid:M,error:M?null:{message:"content can not be empty"}}}}class iu{static parseServerPushElement(B){const{MsgContent:M={Text:""}}=B,{Text:G}=M;return new iu({text:G})}constructor(B){this.type=tc.MSG_TEXT,this.content={text:B.text||""}}validateBeforeSend(){var B,M;return((M=(B=this.content)===null||B===void 0?void 0:B.text)===null||M===void 0?void 0:M.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(B){const{isMergerMessage:M=!1}=B||{},G=M?this.payload:this.content,{text:O}=G;return{MsgType:this.type,MsgContent:{Text:O}}}}var yI=new class{constructor(){this._elementClassMap={[tg.MSG_CUSTOM]:Pl,[tg.MSG_TEXT]:iu}}init(){ss.getInstance().registerApi({apiName:"createCustomMessage",context:this}),ss.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(p,B){var M;(M=B).prototype!==void 0&&"constructor"in M.prototype&&(this._elementClassMap[p]=B)}getElementClass(p){return this._elementClassMap[p]}createMessage(p){const{from:B,flow:M=uo.OUT}=p,{userId:G}=ve.store.get("login")||{};this._isSendByCurrentInstance({from:B,flow:M,currentUser:G})?this._updateWithSenderInfo(p):this._isMultiEndpointSyncMessage({from:B,flow:M,currentUser:G})&&(p.flow=uo.OUT);const O=Object.assign(Object.assign({},p),{currentUser:G});return new fC(O)}createCustomMessage(p){const B=$s(),M=this.createMessage(Object.assign(Object.assign({},p),{from:B})),G=this._elementClassMap[tg.MSG_CUSTOM];if(!M)return null;if(G){const O=new G(p.payload);M.setElement(O)}return M}createTextMessage(p){var B;if(!p)return null;const M=typeof p.payload=="string"?p.payload:((B=p?.payload)===null||B===void 0?void 0:B.text)||"",G=new iu({text:M}),O=$s(),z=ve.message.messageFactory.createMessage(Object.assign(Object.assign({},p),{from:O}));return z.setElement(G),z}_updateWithSenderInfo(p){var B,M;const{nick:G,avatar:O,conversationType:z,to:X}=p,{userId:cA,tinyID:DA}=ve.store.get("login")||{},GA=ia.getUserProfile(cA);return p.nick=G||GA?.nick||"",p.avatar=O||GA?.avatar||"",p.tinyID=p.tinyID||DA||"",p.from=cA,p.status=Gg.UNSENT,p.flow=uo.OUT,z===bg.CONV_GROUP&&(p.nameCard=(M=(B=eg.getGroup(X))===null||B===void 0?void 0:B.selfInfo)===null||M===void 0?void 0:M.nameCard),p}_isMultiEndpointSyncMessage(p){const{from:B,flow:M,currentUser:G}=p;return B===G&&M===uo.IN}_isSendByCurrentInstance(p){const{from:B,flow:M,currentUser:G}=p;return B===G&&M===uo.OUT}};const DI={PushFlag:0,Title:"",Desc:"",Ext:"",ApnsInfo:{Sound:"",BadgeMode:0,IsVoipPush:void 0,Image:"",InterruptionLevel:"active",ContentAvailable:0},AndroidInfo:{Sound:"",XiaoMiChannelID:"",OPPOChannelID:"",GoogleChannelID:"",VIVOClassification:1,VIVOCategory:"",HuaWeiCategory:"",OPPOCategory:"",HuaWeiImage:"",HonorImage:"",GoogleImage:"",HonorImportance:"",MeizuNotifyType:void 0}},UE={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},xl={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function Yl(p,B){return Object.keys(B).forEach(M=>{const{range:G,defaultValue:O}=B[M];p[M]=G.includes(p[M])?p[M]:O}),p}function xg(p){const B=p.lastIndexOf(".");return B===-1?p:p.slice(0,B)}function rc(p){const{androidInfo:B={},androidOPPOChannelID:M=""}=p,G=B.OPPOChannelID||M,O=Yl(B,UE),{sound:z="",FCMChannelID:X=""}=O,cA=vo(O,["sound","FCMChannelID"]);return Object.assign(Object.assign({},cA),{Sound:xg(z),OPPOChannelID:G,GoogleChannelID:X})}function yd(p){const{apnsInfo:B={},ignoreIOSBadge:M=!1,disableVoipPush:G}=p,O=Yl(B,xl),{ignoreIOSBadge:z,disableVoipPush:X,enableIOSBackgroundNotification:cA}=O,DA=vo(O,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),GA=z===!0||M===!0?1:0;let KA;return n(G)||(KA=G===!1?1:0),n(X)||(KA=X===!1?1:0),Object.assign(Object.assign({},DA),{BadgeMode:GA,IsVoipPush:KA,ContentAvailable:cA?1:0})}function FE(p){return ve.utils.isPlainObject(p)?{PushFlag:p.disablePush===!0?1:0,Title:p.title||"",Desc:p.description||"",Ext:p.extension||"",ApnsInfo:yd(p),AndroidInfo:rc(p)}:DI}function Oc(p){const{From_AccountHeadurl:B,From_AccountNick:M,IsNeedReadReceipt:G,IsPeerRead:O,IsSyncMsg:z,MsgBody:X,MsgClientTime:cA,MsgLifeTime:DA,MsgRandom:GA,MsgSeq:KA,MsgTimeStamp:re,SendMsgControl:Qe,SupportMessageExtension:At,TinyId:lt,MsgCheckResult:dt,CloudCustomData:xt,MsgVersion:Wt,MsgFlagBits:Ki,RevokerInfo:Eo,InnerSdkCustomData:so}=p;let hi,{From_Account:qo,To_Account:cn}=p;if(z===1){const yi=cn;cn=qo,qo=yi}if(Eo){const{Reason:yi,Revoker_Account:to,Revoker_FromUin:rs}=Eo;hi={reason:yi,revoker:to,revokerFromUin:rs,userID:to}}return{from:qo,avatar:B,nick:M,needReadReceipt:G===1,isSyncMessage:z,clientTime:cA,messageLifeTime:DA,random:GA,sequence:KA,time:re,messageControlInfo:{excludedFromLastMessage:Qe?.NoLastMsg===1,excludedFromUnreadCount:Qe?.NoUnread===1},isSupportExtension:At,to:cn,tinyID:lt,checkResult:dt,cloudCustomData:xt,revokerInfo:hi,messageVersion:Wt,messageFlagBits:Ki,readReceiptSentByPeer:O,elements:ig(X),onlineOnlyFlag:DA===0,quoteInfo:Yu(so)}}function ou(p){const{From_Account:B,MsgBody:M,MsgClientTime:G,MsgRandom:O,MsgSeq:z,MsgTimeStamp:X,To_Account:cA,MsgVersion:DA,CloudCustomData:GA,MsgCheckResult:KA}=p;return{from:B,clientTime:G,random:O,sequence:z,time:X,to:cA,elements:ig(M),messageVersion:DA,cloudCustomData:GA,checkResult:KA}}function ho(p){const{ClientSeq:B,From_Account:M,GroupInfo:G,MsgBody:O,MsgClientTime:z,MsgRandom:X,MsgSeq:cA,MsgTimeStamp:DA,SendMsgControl:GA,SupportMessageExtension:KA,TinyId:re,CloudCustomData:Qe,MsgVersion:At,MsgCheckResult:lt,NeedReadReceipt:dt,IsPlaceMsg:xt,RevokerInfo:Wt,GroupAtInfo:Ki,OnlineOnlyFlag:Eo,InnerSdkCustomData:so}=p;let hi,qo=Kr.MSG_PRIORITY_NORMAL;if(Object.keys(LE).includes(String(p.MsgPriority))&&(qo=LE[p.MsgPriority]),Wt){const{Reason:yi,Revoker_Account:to,Revoker_FromUin:rs}=Wt;hi={reason:yi,revoker:to,revokerFromUin:rs,userID:to}}const cn=function(yi){const to=[];return Array.isArray(yi)&&yi.forEach(rs=>{rs.GroupAtAllFlag===pC?to.push(rs.GroupAt_Account):rs.GroupAtAllFlag===Eh&&to.push(Sn.MSG_AT_ALL)}),to}(Ki);return{clientSequence:B,from:M,groupProfile:G,clientTime:z,priority:qo,random:X,sequence:cA,time:DA,messageControlInfo:{excludedFromLastMessage:GA?.NoLastMsg===1,excludedFromUnreadCount:GA?.NoUnread===1},isSupportExtension:KA,tinyID:re,cloudCustomData:Qe,messageVersion:At,checkResult:lt,needReadReceipt:dt,isPlaceMessage:xt,revokerInfo:hi,atUserList:cn,elements:ig(O),to:OE(p),onlineOnlyFlag:Eo===1,quoteInfo:Yu(so)}}function OE(p){const{utils:{isEmpty:B},constants:{IS_TOPIC_MESSAGE:M}}=ve,{ToGroupId:G,GroupInfo:{MillionGroupFlag:O=0,TopicId:z}={}}=p;return O!==M||B(z)?G:z}function ig(p){if(!p)return null;if(Array.isArray(p))return p.map(M=>{const G=ve.message.messageFactory.getElementClass(M.MsgType);return G?.parseServerPushElement(M)});const B=ve.message.messageFactory.getElementClass(p.MsgType);return B?.parseServerPushElement(p)}function nu(p){const{From_Account:B,MsgBody:M,MsgClientTime:G,MsgRandom:O,MsgSeq:z,MsgTimeStamp:X,GroupId:cA,TopicId:DA,MsgVersion:GA,CloudCustomData:KA,MsgCheckResult:re}=p;return{from:B,clientTime:G,random:O,sequence:z,time:X,groupID:cA,topicID:DA,elements:ig(M),messageVersion:GA,cloudCustomData:KA,checkResult:re}}function Yu(p){const{utils:{isString:B,safeStringify:M},ssoLog:G}=ve;if(!B(p))return null;try{const{messageID:O,messageTime:z,messageSequence:X}=JSON.parse(p).businessQuote;return{msgID:O,messageTime:z,messageSequence:X}}catch(O){return G.debug("_parseServerQuoteInfo",M(O)),null}}function Pc({conversationUpdateFields:p,message:B}){const{conversationID:M,conversationType:G,conversationSubType:O,flow:z,_isExcludedFromUnreadCount:X,_isExcludedFromLastMessage:cA}=B,DA=cA?"":cl(B),GA=!X&&z===uo.IN;p.has(M)?(p.get(M).lastMessage=DA,GA&&p.get(M).unreadCount++):p.set(M,{conversationID:M,type:G,subType:O,unreadCount:GA?1:0,lastMessage:DA})}function SI(p){return p.filter(B=>{const M=!tn(B?._elements),G=B?.isPlaceMessage===1;return M||ve.ssoLog.error("emptyMessageBody",`from:${B.from} to:${B.to} sequence:${B.sequence}`),M&&!G})}function ll(p){const{messageDataHandler:B}=ve.message;return!B.isInMessageList(p)&&!B.isMessageSentByCurrentInstance(p)}var Il=Object.freeze({__proto__:null,autoIncrementIndex:mC,createAndroidPushInfo:rc,createApnsPushInfo:yd,createOfflinePushInfo:FE,filterValidMessages:SI,getAndroidSoundName:xg,parseServerGroupMessage:ho,parseServerPushC2CModifyMessage:ou,parseServerPushGroupModifyMessage:nu,parseServerPushMessage:Oc,parseServerPushMessageElement:ig,shouldStoreMessage:ll,updateConversationFields:Pc});const{isPlainObject:qa}=ve.utils;function PE(p,B={}){const{onlineUserOnly:M,messageControlInfo:G}=B;let{offlinePushInfo:O}=B;p.conversationType===Sr.CONV_C2C&&M===!0&&(O?O.disablePush=!0:O={disablePush:!0});let z="";typeof p.cloudCustomData=="string"&&p.cloudCustomData.length>0&&(z=p.cloudCustomData);const X=[];if(G&&qa(G)){const{excludedFromUnreadCount:cA,excludedFromLastMessage:DA,excludedFromContentModeration:GA}=G;cA===!0&&X.push("NoUnread"),DA===!0&&X.push("NoLastMsg"),GA===!0&&X.push("NoMsgCheck")}return{onlineUserOnly:M,cloudCustomData:z,messageControlInfo:X,offlinePushInfo:O}}function la(p){const{webhookInfo:{disableCloudMessagePreHook:B=!1,disableCloudMessagePostHook:M=!1}={}}=p||{};if(!B&&!M)return;const G=[];return B&&G.push("ForbidBeforeSendMsgCallback"),M&&G.push("ForbidAfterSendMsgCallback"),G}function Gs(p,B){return mA(this,void 0,void 0,function*(){const M=p.conversationType===Sr.CONV_GROUP?function(O,z){var X;const cA=PE(O,z),{onlineUserOnly:DA,cloudCustomData:GA,messageControlInfo:KA,offlinePushInfo:re}=cA,Qe=JSON.parse(JSON.stringify(O.transformElementsToServerFormat()));let At;return C(O._receiverList)&&O._receiverList.length>0&&(At=O._receiverList,O._receiverList.length>50&&(At=O._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:(X=ve.store.get("login"))===null||X===void 0?void 0:X.userId,GroupId:O.to,MsgBody:Qe,CloudCustomData:GA,Random:O.random,MsgPriority:O.priority,ClientSeq:O.clientSequence,GroupAtInfo:O._groupAtInfoList,OnlineOnlyFlag:DA?1:0,MsgClientTime:O.clientTime,OfflinePushInfo:FE(re),SendMsgControl:DA?void 0:KA,NeedReadReceipt:O.needReadReceipt===!0?1:0,To_Account:At,SupportMessageExtension:O.isSupportExtension===!0?1:0,IsRelayMsg:O._relayFlag===!0?1:0,CustomModerationConfigID:O._cmConfigID,ForbidCallbackControl:la(z),InnerSdkCustomData:xE(O)}}}(p,B):function(O,z){var X;const cA=PE(O,z),{onlineUserOnly:DA,cloudCustomData:GA,messageControlInfo:KA,offlinePushInfo:re}=cA,Qe=DA===!0?0:void 0,At=JSON.parse(JSON.stringify(O.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:(X=ve.store.get("login"))===null||X===void 0?void 0:X.userId,To_Account:O.to,MsgBody:At,CloudCustomData:GA,MsgSeq:O.sequence,MsgRandom:O.random,MsgLifeTime:Qe,From_AccountNick:O.nick,From_AccountHeadurl:O.avatar,SendMsgControl:Qe!==0?KA:void 0,MsgClientTime:O.clientTime,IsNeedReadReceipt:O.needReadReceipt===!0?1:0,SupportMessageExtension:O.isSupportExtension===!0?1:0,IsRelayMsg:O._relayFlag===!0?1:0,CustomModerationConfigID:O._cmConfigID,OfflinePushInfo:FE(re),ForbidCallbackControl:la(z),InnerSdkCustomData:xE(O)}}}(p,B),G=yield ic(M);return G?{time:G.MsgTime,messageDropReason:G.MsgDropReason,sequence:G.MsgSeq}:null})}function Or(p){return mA(this,void 0,void 0,function*(){const{from:B,to:M,version:G=0,sequence:O,random:z,time:X,type:cA,cloudCustomData:DA}=p,GA={From_Account:B,To_Account:M,MsgVersion:G,MsgSeq:O,MsgRandom:z,MsgTime:X,MsgType:cA,MsgBody:p.transformElementsToServerFormat(),CloudCustomData:DA},KA=yield ic({servcmd:"openim.modify_c2c_msg",data:GA});if(KA){const{MsgBody:re,MsgVersion:Qe,CloudCustomData:At}=KA;return{elements:ig(re),messageVersion:Qe,cloudCustomData:At}}})}function ul(p){return mA(this,void 0,void 0,function*(){const{to:B,version:M=0,sequence:G,cloudCustomData:O}=p,z={GroupId:B,MsgVersion:M,MsgSeq:G,MsgBody:p.transformElementsToServerFormat(),CloudCustomData:O},X=yield ic({servcmd:"openim.modify_group_msg",data:z});if(X){const{MsgBody:cA,MsgVersion:DA,CloudCustomData:GA}=X;return{elements:ig(cA),messageVersion:DA,cloudCustomData:GA}}})}function Vl(p){return mA(this,void 0,void 0,function*(){const{groupID:B,count:M,messageSequence:G,messageSequenceList:O,getType:z}=p,X={GroupId:B,ReqMsgNumber:M,WithRecalledMsg:1,Version:1,GetType:z};return G&&(X.ReqMsgSeq=G),C(O)&&O.length>0&&(X.ReqMsgSeqList=O),yield ic({servcmd:"group_open_http_svc.group_msg_get",data:X})})}function xc(p){return mA(this,void 0,void 0,function*(){const{peerAccount:B,count:M,lastMessageTime:G,messageKey:O,direction:z}=p;return ic({servcmd:"openim.getroammsg",data:{Peer_Account:B,MaxCnt:M,WithRecalledMsg:1,LastMsgTime:G,MsgKey:O,GetDirection:z}})})}function xE(p){if(ve.utils.isObject(p.quoteInfo)){const{msgID:B,messageSequence:M,messageTime:G}=p.quoteInfo;return JSON.stringify({businessQuote:{messageID:B,messageSequence:M,messageTime:G}})}}var Yc=Object.freeze({__proto__:null,createMessagePackOptions:PE,generateForbidCallbackControl:la,getC2CRoamingMessagesByAnchor:xc,getGroupRoamingMessagesByAnchor:Vl,getRoamingMessages:function(p){return mA(this,void 0,void 0,function*(){const{peerAccount:B,count:M,lastMessageTime:G,messageKey:O}=p;return(yield ic({servcmd:"openim.getroammsg",data:{Peer_Account:B,MaxCnt:M||15,LastMsgTime:G||0,MsgKey:O,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:Or,modifyGroupMessage:ul,sendMessage:Gs});const{isPlainObject:Vu}=ve.utils,{MSG_AUDIO:yC,MSG_FILE:su,MSG_IMAGE:dh,MSG_VIDEO:Hu,MSG_MERGER:vI}=Sn;class El{constructor(){this._sendProtocolMap=new Map}init(){ss.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:B=>![yC,su,dh,Hu,vI].includes(B[0].type)})}registerSendProtocol(B,M,G){this._sendProtocolMap.set(B,M.bind(G))}sendMessage(B,M){return mA(this,void 0,void 0,function*(){const{TOTAL_COUNT:G,SEND_COST:O,SUCCESS_COUNT:z,FAILED_COUNT:X}=dI;if(!(B instanceof fC))throw new dn({code:Po.MSG_INSTANCE_REQUIRED});const cA=B.validateBeforeSend();if(!cA.isValid){const{code:KA,message:re=""}=cA.error||{};throw new dn({code:KA,message:re})}this._reportMessageSendQuality({name:G,message:B});let DA=!1;const{messageDataHandler:GA}=ve.message||{};try{const{messageControlInfo:KA}=M||{};let re=null;GA.addRandomOfSentMessage(B.random);const Qe=Date.now(),At=this._getSendProtocol(B);if(B.conversationType===Sr.CONV_C2C?(DA=M?.onlineUserOnly===!0,re=yield At(B,M)):B.conversationType===Sr.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(B),re=yield At(B,M)),re){const{messageDropReason:lt,sequence:dt,time:xt}=re;if(this._updateNickAndAvatarOfSentMessageByMe(B),lt&&this._logRateLimitInfo(B,dt,lt),this._reportMessageSendQuality({name:z,message:B}),this._reportMessageSendQuality({name:O,message:B,startTs:Qe}),B.isResend===!0){const Wt=GA.findMessage(B.ID);Wt&&(ve.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${Wt.ID}`),GA.deleteConversationMessage(Wt))}return B.status=Gg.SUCCESS,B.time=xt,B.conversationType===Sr.CONV_GROUP&&(B.sequence=dt),DA?B._onlineOnlyFlag=!0:(GA.storeConversationMessage(B),this._applySentMessageControlInfo(B,KA),this._emitOnlineMessageSent(B)),B.type===tc.MSG_STREAM?{code:0,data:{message:B,streamMessageID:re.streamMessageID}}:{code:0,data:{message:B}}}}catch(KA){B.status=Gg.FAIL,GA.removeRandomOfSentMessage(B.random);let{errorCode:re}=KA||{},Qe=KA?.errorInfo||KA?.message||"";throw this._hasRiskContent(re)&&(B.hasRiskContent=!0),DA||this._isRejectedByRestApi(re)||GA.storeConversationMessage(B),this._reportMessageSendQuality({name:X,message:B,error:KA}),new dn({code:re,message:Qe,data:{message:B},moreMessage:`type:${B.type} from:${B.from} to:${B.to}`})}})}_hasRiskContent(B){return B===80001||B===80004}_isRejectedByRestApi(B){return B>=10100&&B<=10200||B>=120001&&B<=13e4}_emitOnlineMessageSent(B){const M=B._isExcludedFromLastMessage?"":B,{conversationID:G,conversationType:O}=B,z=ea(G)?Ci.TOPIC_NEW_MESSAGE:Ci.NEW_MESSAGE;ve.notificationCenter.emitInnerEvent(z,{result:{conversationUpdateFieldList:[{conversationID:G,type:O,message:B,lastMessage:M,unreadCount:0}]}})}_applySentMessageControlInfo(B,M){M&&Vu(M)&&(M.excludedFromLastMessage===!0&&(B._isExcludedFromLastMessage=!0),M.excludedFromUnreadCount===!0&&(B._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(B,M,G){const O=`from:${B.from} to:${B.to} sequence:${M} messageDropReason:${G}`;ve.ssoLog.warn("messageDropReason",O)}_updateNickAndAvatarOfSentMessageByMe(B){const{messageDataHandler:M}=ve.message||{};let G=!1;const{conversationID:O}=B,z=M.getLatestMsgSentByMe(O);if(z){const{nick:X,avatar:cA}=z;X===B.nick&&cA===B.avatar||(G=!0),G&&M.updateNickAndAvatarOfSentMessage({conversationID:O,latestNick:B.nick,latestAvatar:B.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(B){return mA(this,void 0,void 0,function*(){var M,G,O;const{to:z,from:X}=B;let cA=z,DA=eg.getGroup(cA);if(fa({groupID:cA})&&DA?.isSupportTopic)throw new dn({code:Po.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(ea(z)&&([cA]=z.split(xa.TOPIC),DA=eg.getGroup(cA)),!DA&&typeof((M=ss.getInstance().getApiMap())===null||M===void 0?void 0:M.getGroupProfile)=="function"){const GA=yield ss.getInstance().getApiMap().getGroupProfile({groupID:cA});if(((O=(G=GA?.data)===null||G===void 0?void 0:G.group)===null||O===void 0?void 0:O.type)===Sn.GRP_AVCHATROOM){const KA=kl({code:Po.MSG_SEND_FAIL_NOT_IN_AV,replacement1:X,replacement2:cA});throw new dn({code:Po.MSG_SEND_FAIL_NOT_IN_AV,message:KA})}}return!0})}_reportMessageSendQuality(B){ve.notificationCenter.emitInnerEvent(Ci.QUALITY_STAT,{label:Lg.MESSAGE_SEND_SUCCESS_RATE,data:B})}_getSendProtocol(B){return this._sendProtocolMap.get(B.type)||Gs}}var DC=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){ve.notificationCenter.subscribeInnerEvent(Ci.LOGOUT,this._reset,this),ve.notificationCenter.subscribeInnerEvent(Ci.DESTROY,this._dispose,this)}get _messagesByConversation(){return Fl.getMessages()}storeConversationMessage(p,B=!1){if(jn)return!0;const{conversationID:M}=p;if(!M||(this._messagesByConversation.has(M)||this._messagesByConversation.set(M,new Map),this._shouldSkipStoreMessage(p,B)))return!1;const G=this._getUniqueIdOfMessage(p);return this._messagesByConversation.get(M).set(G,p),this._updateLatestMessageMap(p),!0}_updateLatestMessageMap(p){const{conversationID:B}=p;p.flow==="out"?this._setLatestMsgSentByMe(B,p):B.startsWith("C2C")&&this._setLatestMsgSentByPeer(B,p)}_shouldSkipStoreMessage(p,B){const M=this._getUniqueIdOfMessage(p),G=this._messagesByConversation.get(p.conversationID);if(G?.has(M)){const O=G?.get(M);if(!B||O?.isModified===!0)return!0}return!1}deleteConversationMessage(p){var B;const{conversationID:M=""}=p,G=this._getUniqueIdOfMessage(p);this._messagesByConversation.has(M)&&((B=this._messagesByConversation.get(M))===null||B===void 0||B.delete(G))}modifyConversationMessage(p,B){var M;if(!this._messagesByConversation.has(p)&&!this._sparseMessagesByConversation.has(p))return{isUpdated:!1,message:null};const G=this._getUniqueIdOfMessage(B),O=this._getMessageFromLocalMessage(p,G);if(O){const{messageVersion:z,elements:X,cloudCustomData:cA,checkResult:DA=0}=B,GA=DA>1;if(ve.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${O.version} remoteVersion:${z}`),O.versionO.ID===p)||null,B)break;if(!B){const G=Array.from(this._sparseMessagesByConversation.values());for(const O of G)if(B=O.get(p)||null,B)break}return B}deleteConversationMessageList(p){this._messagesByConversation.has(p)&&(this._messagesByConversation.delete(p),this._latestMessageSentByMeMap.delete(p),this._latestMessageSentByPeerMap.delete(p)),this._sparseMessagesByConversation.has(p)&&this._sparseMessagesByConversation.delete(p)}revokeMessage({conversationID:p,sequence:B,random:M,revoker:G}){const O=this._messagesByConversation.get(p);let z=null;if(O){const X=Array.from(O.values());if(z=this._findMessageBySequenceAndRandom({messageList:X,random:M,sequence:B}),z){const cA=this._getUniqueIdOfMessage(z);return Fl.updateMessage(p,[cA],{isRevoked:!0,revoker:G,operation:qr.revoke}),z}}if(this._sparseMessagesByConversation.has(p)){const X=Array.from(this._sparseMessagesByConversation.get(p).values());if(z=this._findMessageBySequenceAndRandom({messageList:X,random:M,sequence:B}),z)return z.isRevoked=!0,z.revoker=G,z}}_findMessageBySequenceAndRandom({messageList:p,sequence:B,random:M}){for(let G=0;G0){const X=new Map([...O,...z.entries()]);this._messagesByConversation.set(M,X),this._updateLatestMessageSentByMe(M),this._updateLatestMessageSentByPeer(M)}return G}storeSparseMessageList(p){if(p.length===0)return;const{conversationID:B}=p[0],M=p.length;this._sparseMessagesByConversation.has(B)||this._sparseMessagesByConversation.set(B,new Map);const G=this._sparseMessagesByConversation.get(B);for(let O=0;O=0;G--)if(M[G].flow==="out"){this._setLatestMsgSentByMe(p,M[G]);break}}}_updateLatestMessageSentByPeer(p){var B;const M=Array.from(((B=this._messagesByConversation.get(p))===null||B===void 0?void 0:B.values())||[]);if(M.length!==0&&p.startsWith("C2C")){for(let G=M.length-1;G>=0;G--)if(M[G].flow==="in"){this._setLatestMsgSentByPeer(p,M[G]);break}}}_getUniqueIdOfMessage(p){const{from:B,to:M,random:G,sequence:O,time:z}=p;return`${B}-${M}-${G}-${O}-${z}`}_setLatestMsgSentByPeer(p,B){this._latestMessageSentByPeerMap.set(p,B)}_setLatestMsgSentByMe(p,B){this._latestMessageSentByMeMap.set(p,B)}getLatestMsgSentByPeer(p){return this._latestMessageSentByPeerMap.get(p)}getLatestMsgSentByMe(p){return this._latestMessageSentByMeMap.get(p)}addRandomOfSentMessage(p){this._randomOfSentMessageList.add(p)}removeRandomOfSentMessage(p){this._randomOfSentMessageList.delete(p)}updateNickAndAvatarOfSentMessage(p){const{conversationID:B="",latestAvatar:M,latestNick:G,isSentByMe:O=!0}=p,z=this._messagesByConversation.get(B);if(!z)return;const X=Array.from(z.values()),cA=O?"out":"in";X.forEach(DA=>{const{nick:GA,avatar:KA,flow:re}=DA;re===cA&&(GA!==G&&(DA.nick=G),KA!==M&&(DA.avatar=M))})}isInMessageList(p){var B;const{conversationID:M}=p;if(!M||!this._messagesByConversation.has(M))return!1;const G=this._getUniqueIdOfMessage(p);return(B=this._messagesByConversation.get(M))===null||B===void 0?void 0:B.has(G)}isMessageSentByCurrentInstance(p){const{random:B}=p;return this._randomOfSentMessageList.has(B)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(p){const B=this._messagesByConversation.get(p);return B?[...B.values()]:[]}getSparseMessageList(p){const B=this._sparseMessagesByConversation.get(p);return B?[...B.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),ve.notificationCenter.unSubscribeInnerEvent(Ci.LOGOUT,this._reset,this),ve.notificationCenter.unSubscribeInnerEvent(Ci.DESTROY,this._dispose,this)}};function Ia(p,B){const M=nc.getConversation(p);if(M?.lastMessage){const{lastMessage:G}=M,{lastTime:O,lastSequence:z,version:X}=G,{time:cA,sequence:DA,messageVersion:GA,elements:KA,cloudCustomData:re}=B;O===cA&&z===DA&&X!==GA&&(G.type=KA[0].type,G.payload=KA[0].content,G.messageForShow=XI(G.type,G.payload),G.cloudCustomData=re,G.version=GA,nc.updateConversation(p,{lastMessage:G}))}}class ac{init(){ss.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(B){return mA(this,void 0,void 0,function*(){const{to:M,payload:G,sequence:O,conversationType:z,random:X,time:cA,from:DA,type:GA}=B;if(this._canModifyMessageElement(GA)){const KA=B?._elements||[];KA.length>=1&&(KA[0].type=GA,KA[0].content=G)}try{let KA=null,re=null;if(z===Sr.CONV_C2C?KA=yield Or(B):z===Sr.CONV_GROUP&&(KA=yield ul(B)),KA){let Qe=`${z}${M}`;return M===$s()&&z===Sr.CONV_C2C&&(Qe=`${z}${DA}`),re={conversationType:z,from:DA,to:M,time:cA,random:X,sequence:O,elements:KA?.elements,cloudCustomData:KA?.cloudCustomData,messageVersion:KA?.messageVersion,conversationID:Qe},this._handleModifyMessageSuccess(re),{code:0,data:{message:B},successLog:{message:`to:${M}`}}}}catch(KA){const{errorCode:re}=KA||{};throw new dn({functionName:"modifyMessage",code:re,moreMessage:`to:${M}`})}})}_handleModifyMessageSuccess(B){const{conversationID:M}=B,{isUpdated:G,message:O}=ve.message.messageDataHandler.modifyConversationMessage(M,B);G===!0&&ve.notificationCenter.emitOuterEvent(Ts.MESSAGE_MODIFIED,{name:Ts.MESSAGE_MODIFIED,data:[O]}),ve.notificationCenter.emitInnerEvent(Ci.MESSAGE_MODIFIED,{conversationID:M,message:O}),Ia(M,B)}_canModifyMessageElement(B){return[tg.MSG_TEXT,tg.MSG_CUSTOM,tg.MSG_LOCATION,tg.MSG_FACE].includes(B)}}class dg{init(){const{notificationCenter:B}=ve,{InnerEventSubType:M}=B;us.getInstance().registerWorkflowStep(Cr.RECEIVE_C2C_NEW_MESSAGE,jt.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),us.getInstance().registerWorkflowStep(Cr.RECEIVE_C2C_NEW_MESSAGE,jt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),us.getInstance().registerWorkflowStep(Cr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,jt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),B.subscribeInnerEvent(Ci.MESSAGE_PUSH,M.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),B.subscribeInnerEvent(Ci.MESSAGE_PUSH,M.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),B.subscribeInnerEvent(Ci.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(B){us.getInstance().executeWorkflow(Cr.RECEIVE_C2C_NEW_MESSAGE,B)}_handleC2CMessagePush(B){const M=B.data||{},{messageDataHandler:G}=ve.message||{},O=[],z=new Map;return M.C2cMsgArray.forEach(X=>{const cA=this._generateC2CMessage(X);this._updateMessageProfile(cA);let DA=cA.isModified===1;G.isMessageSentByCurrentInstance(cA)?cA.isModified=DA:DA=!1,cA._onlineOnlyFlag?G.isMessageSentByCurrentInstance(cA)||O.push(cA):ll(cA)&&(G.storeConversationMessage(cA)&&Pc({conversationUpdateFields:z,message:cA}),G.isMessageSentByCurrentInstance(cA)&&!DA||O.push(cA))}),{conversationUpdateFieldList:[...z.values()],messages:O}}_emitMessageEventsAfterReceiveNewMessage(B){var M;const{messages:G=[]}=((M=B.result)===null||M===void 0?void 0:M[jt.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(G)}_emitMessageEventsAfterSyncUnreadMessage(B){var M;const{messages:G=[]}=((M=B.result)===null||M===void 0?void 0:M[jt.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(G)}_emitMessageEvents(B){const M=B?.filter(O=>O?.isModified===!0)||[];M.length>0&&ve.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:M});const G=B?.filter(O=>!O?.isModified);G.length>0&&ve.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:G})}_generateC2CMessage(B){const M=Sr.CONV_C2C,G=Oc(B),O=ve.message.messageFactory.createMessage(Object.assign(Object.assign({},G),{conversationType:M,flow:uo.IN})),{elements:z}=G;return O.setElement(z),O}_updateMessageProfile(B){var M;const{messageDataHandler:G}=ve.message||{},O=(M=ve.store.get("login"))===null||M===void 0?void 0:M.userId,{from:z,nick:X,avatar:cA,conversationID:DA=""}=B;if(z!==O){const GA=G.getLatestMsgSentByPeer(DA);if(GA){const{nick:KA,avatar:re}=GA;n(X)||n(cA)?(B.nick=c(KA)?KA:B.nick,B.avatar=c(re)?re:B.avatar):X===KA&&cA===re||(G.updateNickAndAvatarOfSentMessage({conversationID:DA,latestNick:X,latestAvatar:cA,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:DA,nick:X,avatar:cA}))}}else{const GA=G.getLatestMsgSentByMe(DA);!GA||X===GA.nick&&cA===GA.avatar||G.updateNickAndAvatarOfSentMessage({conversationID:DA,latestNick:X,latestAvatar:cA,isSentByMe:!0})}}_updateConversationUserProfile(B){const{conversationID:M,nick:G,avatar:O}=B,z=nc.getConversation(M),{userProfile:X={}}=z||{};X.avatar===O&&X.nick===G||nc.updateConversation(M,{userProfile:Object.assign(Object.assign({},X),{nick:G,avatar:O})})}_updateMessageListDueToModify(B){const{conversationID:M}=B,{isUpdated:G,message:O}=ve.message.messageDataHandler.modifyConversationMessage(M,B);G===!0&&ve.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[O]}),ve.notificationCenter.emitInnerEvent("ModifyMessageSuccess",B),Ia(M,B)}_handleC2CMessageModify(B){B.C2cMsgModNotifys.forEach(M=>{var G;const O=Sr.CONV_C2C;let z=ou(M);const{to:X,from:cA}=z;let DA=`${O}${X}`;X===((G=ve.store.get("login"))===null||G===void 0?void 0:G.userId)&&(DA=`${O}${cA}`),z=Object.assign({conversationType:O,conversationID:DA},z),this._updateMessageListDueToModify(z)})}_dispose(){const{notificationCenter:B}=ve,{InnerEventSubType:M}=B;ve.notificationCenter.unSubscribeInnerEvent(Ci.MESSAGE_PUSH,M.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),ve.notificationCenter.unSubscribeInnerEvent(Ci.MESSAGE_PUSH,M.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),ve.notificationCenter.unSubscribeInnerEvent(Ci.DESTROY,this._dispose,this)}}class MI{init(){const{notificationCenter:B}=ve,{InnerEventSubType:M}=B;us.getInstance().registerWorkflowStep(Cr.RECEIVE_GROUP_NEW_MESSAGE,jt.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),us.getInstance().registerWorkflowStep(Cr.RECEIVE_GROUP_NEW_MESSAGE,jt.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),B.subscribeInnerEvent(Ci.MESSAGE_PUSH,M.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),B.subscribeInnerEvent(Ci.MESSAGE_PUSH,M.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),B.subscribeInnerEvent(Ci.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(B){this._canExecuteReceiverNewMessageWorkFlow(B)&&us.getInstance().executeWorkflow(Cr.RECEIVE_GROUP_NEW_MESSAGE,B)}_handleGroupMessagePush(B){const M=B.data||{},{messageDataHandler:G}=ve.message,O=[],z=new Map,X=M?.GroupMsgArray;return X?.forEach(cA=>{if(cA.GroupInfo.NotVisible===1)return;const DA=this._generateGroupMessage(cA);this.updateMessageProfile(DA);let GA=DA.isModified===1;G.isMessageSentByCurrentInstance(DA)?DA.isModified=GA:GA=!1,DA._onlineOnlyFlag?G.isMessageSentByCurrentInstance(DA)||O.push(DA):ll(DA)&&G.storeConversationMessage(DA)&&(O.push(DA),Pc({conversationUpdateFields:z,message:DA}))}),{conversationUpdateFieldList:[...z.values()],messages:O}}_emitMessageEvents(B){var M;const{messages:G}=((M=B.result)===null||M===void 0?void 0:M[jt.HANDLE_GROUP_NEW_MESSAGE])||{},O=G?.filter(X=>X?.isModified===!0)||[];O.length>0&&ve.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:O});const z=G?.filter(X=>!X?.isModified)||[];z.length>0&&ve.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:z})}_generateGroupMessage(B){const M=Sr.CONV_GROUP,G=ho(B),O=ve.message.messageFactory.createMessage(Object.assign(Object.assign({},G),{conversationType:M,flow:uo.IN})),{elements:z}=G;return O.setElement(z),O}updateMessageProfile(B){var M;const{messageDataHandler:G}=ve.message||{},O=(M=ve.store.get("login"))===null||M===void 0?void 0:M.userId,{from:z,nick:X,avatar:cA,conversationID:DA="",_elements:GA}=B;if(z===O){const KA=G.getLatestMsgSentByMe(DA);!KA||X===KA.nick&&cA===KA.avatar||G.updateNickAndAvatarOfSentMessage({conversationID:DA,latestNick:X,latestAvatar:cA,isSentByMe:!0})}else if(z===Sn.CONV_SYSTEM){const{operationType:KA,memberInfoList:re,operatorInfo:Qe}=GA;let At={};if(tn(re)?tn(Qe)||(At=Qe):[ga.JOINED,ga.KICKED,ga.ADMIN_SET,ga.ADMIN_CANCELED].includes(KA)&&(At=Object.assign({},re[0])),!tn(At)){const{nick:lt="",avatar:dt=""}=At;B.nick=lt,B.avatar=dt}}}_updateMessageListDueToModify(B){const{conversationID:M}=B,{isUpdated:G,message:O}=ve.message.messageDataHandler.modifyConversationMessage(M,B);G===!0&&ve.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[O]}),Ia(M,B)}_handleGroupMessageModify(B){B.GroupMsgModNotifys.forEach(M=>{const G=Sr.CONV_GROUP;let O=nu(M);const{topicID:z,groupID:X}=O,cA=z||X,DA=`${G}${cA}`;O=Object.assign({conversationType:G,conversationID:DA,to:cA},O),this._updateMessageListDueToModify(O)})}_dispose(){const{notificationCenter:B}=ve,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:M,GROUP_MESSAGE_MODIFIED:G}}=B;B.unSubscribeInnerEvent(Ci.MESSAGE_PUSH,M,this._handleGroupMessagePush,this),B.unSubscribeInnerEvent(Ci.MESSAGE_PUSH,G,this._handleGroupMessageModify,this),B.unSubscribeInnerEvent(Ci.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(B){var M,G;const{GroupId:O,GroupType:z}=((G=(M=B?.GroupMsgArray)===null||M===void 0?void 0:M[0])===null||G===void 0?void 0:G.GroupInfo)||{},X=z===RE.GRP_AVCHATROOM;return!(!eg.getGroup(O)&&X)}}var YE=new class{constructor(){this.c2cMessageReceiver=new dg,this.groupMessageReceiver=new MI}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const Ju={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:p=>!(!p.startsWith("C2C")&&!p.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:p=>function(B){var M;return typeof B?.text!="string"||typeof B.text=="string"&&((M=B?.text)===null||M===void 0?void 0:M.length)===0?"payload.text must be a string":!0}(p)}}},qu={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var RI=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(p){return mA(this,void 0,void 0,function*(){try{const{conversationID:B,count:M,direction:G,sequence:O,messageSequenceList:z,shouldMarkCompleted:X=!1,getType:cA}=p,DA=B.replace(bg.CONV_GROUP,""),GA=[];let KA=O;if(G===_c.BACKWARD){if(typeof O!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};KA=O+M-1}const re=yield Vl({groupID:DA,count:M,messageSequence:KA,messageSequenceList:z,getType:cA});if(re){const{RspMsgList:Qe=[],NextReqMsgSeq:At=0,IsFinished:lt,InvisibleMsgSeq:dt}=re,xt=`groupID:${DA} sequence:${O} reqSeq:${KA} direction:${G} complete:${lt} nextSequence:${At} remoteMsgCount:${Qe.length} invisibleSequenceList:${dt}`,Wt=[];for(let so=0;so=O),Ki&&X&&this.completedHistoryConversations.add(B);const Eo=SI(Wt);return ve.ssoLog.info("getGroupRoamingMessagesByAnchor",xt),{messageList:Eo,invisibleSequenceList:dt,nextReqMessageIDFromServer:At,hasNoMoreHistoryMessage:Ki,serverGroupTipList:GA}}}catch(B){const{errorCode:M,errorInfo:G}=B||{};throw new dn({code:M,message:G})}})}clearHistoryMessageListFetchAnchors(p){this._historyMessageListFetchAnchors.delete(p)}isHistoryMessageFetchCompleted(p){return this.completedHistoryConversations.has(p)}_parseMessage(p){var B;const M=bg.CONV_GROUP;p.Event===4&&(p.MsgBody.MsgType=Sn.MSG_GRP_TIP);const G=ho(p),O=yI.createMessage(Object.assign(Object.assign({},G),{conversationType:M,flow:"in"}));return Lc(((B=G.elements)===null||B===void 0?void 0:B.content)||{},O),O.setElement(G.elements),O}getC2CRoamingMessagesByAnchor(p){return mA(this,void 0,void 0,function*(){var B;try{const{conversationID:M,count:G,messageID:O,time:z,direction:X,shouldMarkCompleted:cA=!1}=p;let DA=z,GA="";if(!z){const Qe=O?ve.message.messageDataHandler.findMessage(O):null;if(DA=Qe?.time||0,O&&this._historyMessageListFetchAnchors.has(M)){const At=this._historyMessageListFetchAnchors.get(M);DA=At.lastMessageTime,GA=At.messageKey}}const KA=M.replace(bg.CONV_C2C,""),re=yield xc({count:G,lastMessageTime:DA,messageKey:GA,peerAccount:KA,direction:X});if(re){const{MsgList:Qe=[],Complete:At,MsgKey:lt,LastMsgTime:dt}=re;this._historyMessageListFetchAnchors.set(M,{messageKey:lt,lastMessageTime:dt});const xt=[];for(let so=0;so{const{tag:O,value:z}=G;O&&O.indexOf(Cg)>-1?M.profileCustomField.push({key:O,value:z}):Hl.has(O)&&(M[Hl.get(O)]=z)}),Object.assign(Object.assign({},Ka),M)}parseProfileItem(p=[]){const B=[];return p.forEach(M=>{B.push({tag:M.Tag,value:M.Value})}),B}parseProfileList(p=[]){const B=[];return p.forEach(M=>{B.push({tag:M.Tag,value:M.ValueBytes})}),B}convertParamsToProfile(p){const B=[];return Object.keys(p).forEach(M=>{M!==Br&&B.push({tag:xr[M.toUpperCase()],value:p[M]})}),p.profileCustomField&&C(p.profileCustomField)&&p.profileCustomField.forEach(M=>{B.push({tag:M.key,value:M.value})}),B}normalizeProfileFields(p){const B={},M=[];return p.forEach(G=>{const{tag:O,value:z}=G;if(O&&O.indexOf(Cg)>-1&&M.push({key:O,value:z}),Hl.has(O)&&z!==void 0){const X=Hl.get(O);B[X]=z}}),M.length>0&&(B.profileCustomField=M),B}};const{generateProtocolData:wI}=ve.common;function ru(p){return mA(this,void 0,void 0,function*(){const B="profile.portrait_get_all",M={From_Account:$s(),UserItem:[]};p.forEach(X=>{M.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:X})});const G=wI({servcmd:B,data:M}),O=`${G.head.seq}${B}`,z=yield ve.channel.sendPacket(G,{requestId:O});if(z)return function(X){const{ActionStatus:cA,ErrorCode:DA,ErrorDisplay:GA,ErrorInfo:KA,UserProfileItem:re}=X,Qe=[];return re.map(At=>{const{To_Account:lt,CustomSequence:dt,ResultCode:xt,ResultInfo:Wt,StandardSequence:Ki,ProfileItem:Eo}=At,so=ya.parseProfileItem(Eo);Qe.push({userId:lt,customSequence:dt,resultCode:xt,resultInfo:Wt,standardSequence:Ki,profileItem:so})}),{actionStatus:cA,errorCode:DA,errorDisplay:GA,errorInfo:KA,userProfile:Qe}}(z)})}function Da(p){return ia.getFriendMap().has(p)}const{isEmpty:Cl}=ve.utils;class VE{constructor(){this._strangerProfileMap=new Map}init(){ss.getInstance().registerApi({apiName:"getMyProfile",context:this}),ss.getInstance().registerApi({apiName:"getUserProfile",context:this}),ss.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=ya.createProfile.bind(ya);const{notificationCenter:B}=ve;us.getInstance().registerWorkflowStep(Cr.SYNC_SERVER_INFO_AFTER_LOGIN,jt.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),B.subscribeInnerEvent(Ci.MESSAGE_PUSH,B.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),B.subscribeInnerEvent(Ci.LOGOUT,this._reset,this),B.subscribeInnerEvent(Ci.DESTROY,this._dispose,this)}getMyProfile(){return mA(this,void 0,void 0,function*(){try{const B=$s(),M=yield ru([B]);if(M){const G=this._handleProfileFormResponse(M)[0];return ia.getUserProfileMap().set(B,G),{code:0,data:G}}}catch(B){const{errorCode:M,errorInfo:G}=B;throw new dn({functionName:"getMyProfile",code:M,message:G})}})}getUserProfile(B){return mA(this,void 0,void 0,function*(){try{let{userIDList:M}=B;const{userIdListToRequest:G,profileFromCache:O}=this._filterRequestAndCacheUsers(M);if(G.length===0)return{code:0,data:O,successLog:{message:`userIDList.length:${M.length}`}};G.length>Yg&&(ve.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),G.length=Yg);const{data:z,error:X}=yield this._batchFetchUserProfiles(G),cA=G.length,DA=z.length,GA=cA-DA;if(O.length===0&&cA===GA&&!Cl(X))throw X;if(C(z))return z.forEach(re=>{Da(re.userID)?ia.getUserProfileMap().set(re.userID,re):this._strangerProfileMap.set(re.userID,re)}),{code:0,data:z.concat(O),successLog:{message:`getUserProfile query:${cA} success:${DA} fail:${GA} from cache:${O.length}`}}}catch(M){throw new dn(M)}})}getMyProfileCacheThenServer(){return mA(this,void 0,void 0,function*(){const B=$s(),M=ia.getUserProfileMap().has(B);return M?{code:0,data:M}:this.getMyProfile()})}updateMyProfile(B){return mA(this,void 0,void 0,function*(){const M=$s(),G={};for(const z in B)B[z]!==void 0&&(G[z]=B[z]);const O=ya.convertParamsToProfile(G);try{yield function(GA){return mA(this,void 0,void 0,function*(){const KA="profile.portrait_set",re=wI({servcmd:KA,data:GA}),Qe=`${re.head.seq}${KA}`,At=yield ve.channel.sendPacket(re,{requestId:Qe});if(At){const{ActionStatus:lt,ErrorCode:dt,ErrorDisplay:xt,ErrorInfo:Wt}=At;return{actionStatus:lt,errorCode:dt,errorDisplay:xt,errorInfo:Wt}}})}({From_Account:M,ProfileItem:O});const X=ia.getUserProfile(M);let cA;cA=X?Object.assign(Object.assign({},X),G):ya.createProfile(M,O);const DA=!Tg(X,cA,["lastUpdatedTime"]);return cA.lastUpdatedTime=Date.now(),ia.getUserProfileMap().set(M,cA),DA&&this._emitProfileUpdated(cA),{code:0,data:cA,successLog:{message:`profileArray: ${ve.utils.safeStringify(O)}`}}}catch(z){const{errorCode:X,errorInfo:cA}=z;throw new dn({functionName:"updateMyProfile",code:X,message:cA,moreMessage:`params: ${ve.utils.safeStringify(B)}`})}})}updateMyNickAndAvatar(B){return mA(this,void 0,void 0,function*(){const M=$s(),G=Date.now(),O=ia.getUserProfile(M);let z={};z=O?Object.assign(O,B):ya.createProfile(M,B),z.lastUpdatedTime=G,ia.getUserProfileMap().set(M,z)})}_onProfileDataModify(B){const M=function(z){const{Profile_Account:X,PushType:cA,ProfileList:DA}=z;return{userId:X,pushType:cA,profileList:ya.parseProfileList(DA)}}(B.ProfileDataMod[0]);if(Cl(M))return;const{isProfileUpdated:G,profile:O}=this._handleProfileModified(M);G&&this._emitProfileUpdated(O)}_emitProfileUpdated(B){ve.notificationCenter.emitInnerEvent(Ci.PROFILE_UPDATE,{name:Ci.PROFILE_UPDATE,data:[B]}),ve.notificationCenter.emitOuterEvent(Ts.PROFILE_UPDATED,{name:Ts.PROFILE_UPDATED,data:[B]}),nc.updateConversation(`C2C${B?.userID}`,{userProfile:B})}_dispose(){const{notificationCenter:B}=ve;B.unSubscribeInnerEvent(Ci.LOGOUT,this._reset,this),B.unSubscribeInnerEvent(Ci.MESSAGE_PUSH,B.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),B.unSubscribeInnerEvent(Ci.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(B){const{userId:M,profileList:G}=B,O=ia.getUserProfile(M);if(!($s()===M||Da(M)&&O))return{isProfileUpdated:!1,profile:null};const z=ya.normalizeProfileFields(G),X=Object.keys(z).some(KA=>KA===Br?this._isCustomFieldChanged(O.profileCustomField,z.profileCustomField):O[KA]!==z[KA]);if(!X)return{isProfileUpdated:!1,profile:O};const cA=Date.now(),DA=Object.prototype.hasOwnProperty.call(z,Br)?this._mergeProfileCustomField(O.profileCustomField,z.profileCustomField):O.profileCustomField,GA=Object.assign(Object.assign(Object.assign({},O),z),{profileCustomField:DA,lastUpdatedTime:cA});return ia.getUserProfileMap().set(M,GA),{isProfileUpdated:X,profile:GA}}_filterRequestAndCacheUsers(B){const M=[],G=[];return B.forEach(O=>{const z=ia.getUserProfileMap().has(O);Da(O)&&z?G.push(ia.getUserProfile(O)):this._isStrangerAndProfileValid(O)?G.push(this._strangerProfileMap.get(O)):M.push(O)}),{userIdListToRequest:M,profileFromCache:G}}_handleProfileFormResponse(B){const{userProfile:M}=B;if(!Array.isArray(M))return[];const G=M.filter(z=>z.userId!=="@TLS#NOT_FOUND"&&z.userId!==""&&!Cl(z.profileItem)),O=Date.now();return G.map(z=>{const X=ya.createProfile(z.userId,z.profileItem);return X.lastUpdatedTime=O,X})}_isStrangerAndProfileValid(B){var M;if(!Da(B)){const{lastUpdatedTime:G=0}=this._strangerProfileMap.get(B)||{},O=((M=ve.store.get("cloudConfig"))===null||M===void 0?void 0:M.stranger_profile_expiration_time)||6e5;return Date.now()-G<=O}return!1}_chunkUserIDList(B,M){return Array.from({length:Math.ceil(B.length/M)},(G,O)=>B.slice(O*M,(O+1)*M))}_batchFetchUserProfiles(B){return mA(this,void 0,void 0,function*(){const M=[],G=[];let O={};return this._chunkUserIDList(B,100).forEach(z=>{M.push(ru(z))}),(yield Promise.allSettled(M)).forEach(z=>{if(z.status==="fulfilled"){const X=z.value,cA=this._handleProfileFormResponse(X);C(cA)&&G.push(...cA)}else if(z.status==="rejected"){const{code:X,message:cA}=z.reason||{};O={errorCode:X,message:cA}}}),{data:G,error:O}})}_isCustomFieldChanged(B=[],M=[]){if(!C(M)||M.length===0)return!1;if(!C(B)||B.length===0)return!0;const G=new Map(B.map(O=>[O.key,O.value]));return M.some(O=>G.get(O.key)!==O.value)}_mergeProfileCustomField(B=[],M=[]){const G=C(B)?B.map(O=>Object.assign({},O)):[];return C(M)&&M.length!==0&&M.forEach(({key:O,value:z})=>{const X=G.find(cA=>cA.key===O);X?X.value=z:G.push({key:O,value:z})}),G}_reset(){ia.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const au=new Map,HE=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let p=0,B=HE.length;p>(-2*z&6)):0)O="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(O);try{return decodeURIComponent(escape(M))}catch(G){return console.warn(G),""}}const{isEmpty:gu}=ve.utils,{generateProtocolData:Vt}=ve.common;function Ku(p){return mA(this,void 0,void 0,function*(){const B="im_open_status.ws_get_user_status",M=Vt({servcmd:B,data:{To_Account:p}}),G=`${M.head.seq}${B}`,O=yield ve.channel.sendPacket(M,{requestId:G});if(O)return function(z){const{ErrorCode:X,ErrorInfo:cA,ErrorList:DA=[],UserStatusList:GA=[]}=z,KA=GA.map(Qe=>{const{To_Account:At,Status:lt,CustomStatus:dt,Detail:xt=[]}=Qe;return{userID:At,statusType:lt,customStatus:jr(dt),onlineDevices:ju(xt)}}),re=DA.map(Qe=>{const{To_Account:At,Invalid_Account:lt,ErrorCode:dt,ErrorInfo:xt}=Qe;return{userID:gu(lt)?At:lt,code:dt,message:xt}});return{errorCode:X,errorInfo:cA,successUserList:KA,failureUserList:re}}(O)})}function ju(p){const B=[];return p?.forEach(M=>{const{Platform:G,Status:O}=M;O==="Online"&&B.push(G)}),B}class SC{constructor(){this._customStatus=""}init(){const{notificationCenter:B}=ve;ss.getInstance().registerApi({apiName:"getUserStatus",context:this}),ss.getInstance().registerApi({apiName:"setSelfStatus",context:this}),ss.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),ss.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),us.getInstance().registerWorkflowStep(Cr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,jt.USER_STATUS_UPDATE,this._onReOnline,this),B.subscribeInnerEvent(Ci.MESSAGE_PUSH,B.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),B.subscribeInnerEvent(Ci.LOGOUT,this._reset,this),B.subscribeInnerEvent(Ci.DESTROY,this._dispose,this)}setSelfStatus(B){return mA(this,void 0,void 0,function*(){const M=$s(),{customStatus:G}=B;try{return yield function(O){return mA(this,void 0,void 0,function*(){const z="im_open_status.ws_set_custom_status",X=Vt({servcmd:z,data:{CustomStatus:O}}),cA=`${X.head.seq}${z}`,DA=yield ve.channel.sendPacket(X,{requestId:cA});if(DA){const{ErrorCode:GA,ErrorInfo:KA}=DA;return{errorCode:GA,errorInfo:KA}}})}(G),this._customStatus=G,{code:0,data:{userID:M,statusType:gc,customStatus:G},successLog:{message:`customStatus: ${G}`}}}catch(O){const{errorCode:z,errorInfo:X}=O;throw new dn({functionName:"setSelfStatus",code:z,message:X})}})}getUserStatus(B){return mA(this,void 0,void 0,function*(){const{userIDList:M=[]}=B;if(this._isOnlyMeInArray(M))return this._getMyStatus();const G=yield this._getUserStatus(M);return Object.assign(Object.assign({},G),{successLog:{message:`userIDList length: ${M.length}`}})})}setCustomStatus(B){const M=jr(B);this._customStatus=M}subscribeUserStatus(B){return mA(this,void 0,void 0,function*(){try{const{userIDList:M=[]}=B;this._checkBusinessCapabilityBits("subscribeUserStatus");const G=this._getMaxUserCount("subscribe"),O=this._sliceUserIDList(M,G),z=yield function(cA){return mA(this,void 0,void 0,function*(){const{channel:DA}=ve,GA="im_open_status.ws_status_subscribe",KA=Vt({servcmd:GA,data:{To_Account:cA}}),re=`${KA.head.seq}${GA}`;return yield DA.sendPacket(KA,{requestId:re})})}(O),X=this._parseResponse(z);return{code:0,data:{failureUserList:X},successLog:{message:`userID length:${M.length} failCount: ${X.length}`}}}catch(M){const{errorCode:G}=M;throw new dn({functionName:"subscribeUserStatus",code:G})}})}unsubscribeUserStatus(B){return mA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:M=[]}=B,G=this._getMaxUserCount("unsubscribe"),O=this._sliceUserIDList(M,G),z=yield function(cA){return mA(this,void 0,void 0,function*(){const{channel:DA}=ve,GA="im_open_status.ws_status_unsubscribe";let KA={};KA=cA.length===0?{UnsubscribeAll:1}:{To_Account:cA};const re=Vt({servcmd:GA,data:KA}),Qe=`${re.head.seq}${GA}`;return yield DA.sendPacket(re,{requestId:Qe})})}(O),X=this._parseResponse(z);return{code:0,data:{failureUserList:X},successLog:{message:`userID length:${M.length} failCount: ${X.length}`}}}catch(M){const{errorCode:G}=M;throw new dn({functionName:"unsubscribeUserStatus",code:G})}})}_onUserStatusUpdate(B){const{UserStatusList:M=[]}=B||{},G=M.map(O=>{const{To_Account:z,Status:X,CustomStatus:cA,Platform:DA}=O,GA={userID:z,statusType:X,customStatus:jr(cA)};return DA&&(GA.onlineDevices=DA),GA});this._emitUserStatusUpdatedEvent(G)}_onReOnline(B){const M=jr(B.data.customStatus);if(this._customStatus===M)return;this._customStatus=M;const G={userID:$s(),statusType:gc,customStatus:M};this._emitUserStatusUpdatedEvent(G)}_emitUserStatusUpdatedEvent(B){ve.notificationCenter.emitOuterEvent(Ts.USER_STATUS_UPDATED,{name:Ts.USER_STATUS_UPDATED,data:B})}_sliceUserIDList(B,M){return B.slice(0,M)}_parseResponse(B){const{ErrorList:M=[]}=B;return M.map(G=>{const{To_Account:O,Invalid_Account:z,ErrorCode:X,ErrorInfo:cA}=G;return{userID:ve.utils.isEmpty(z)?O:z,code:X,message:cA}})}_checkBusinessCapabilityBits(B){if(!ve.store.get("commercialConfig").get(Nr))throw new dn({functionName:B,code:Po.NO_USE,replacement1:B})}_getMaxUserCount(B){const M=ve.store.get("cloudConfig")||{},G={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}},{key:O,default:z}=G[B],X=M[O]||z;return parseInt(X,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:$s(),statusType:gc,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(B){return mA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const M=this._getMaxUserCount("query"),G=this._sliceUserIDList(B,M),O=yield Ku(G),{successUserList:z,failureUserList:X}=O||{};return{code:0,data:{successUserList:z,failureUserList:X}}}catch(M){const{errorCode:G}=M;throw new dn({functionName:"getUserStatus",code:G})}})}_isOnlyMeInArray(B){const M=$s();return B.length===1&&B.indexOf(M)>-1}_dispose(){const{notificationCenter:B}=ve;B.unSubscribeInnerEvent(Ci.MESSAGE_PUSH,B.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),B.unSubscribeInnerEvent(Ci.DESTROY,this._dispose,this),B.unSubscribeInnerEvent(Ci.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const K={getUserProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},updateMyProfile:{nick:{required:!1,rules:["string"],allowEmpty:!0},avatar:{required:!1,rules:["string"],allowEmpty:!0},gender:{required:!1,rules:["string"],allowEmpty:!0},selfSignature:{required:!1,rules:["string"],allowEmpty:!0},allowType:{required:!1,rules:["string"],allowEmpty:!0},birthday:{required:!1,rules:["number"],allowEmpty:!1},language:{required:!1,rules:["string"],allowEmpty:!0},messageSettings:{required:!1,rules:["string"],allowEmpty:!0},adminForbidType:{required:!1,rules:["string"],allowEmpty:!0},level:{required:!1,rules:["number"],allowEmpty:!1},role:{required:!1,rules:["number"],allowEmpty:!0},profileCustomField:{required:!1,rules:["array"],allowEmpty:!0,customValidator:function(p){for(const B of p){if(typeof B!="object")return"Each item in profileCustomField must be an object";if(typeof B?.key!="string")return"Each item.key in profileCustomField must be a string";if(!B?.key.startsWith(Cg))return'Each item.key in profileCustomField must start with "Tag_Profile_Custom"'}return!0}}},setSelfStatus:{customStatus:{required:!0,rules:["string"],allowEmpty:!0}},getUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!1,rules:["array"],allowEmpty:!0}}},U={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class sA{constructor(){this.userProfile=new VE,this.userStatus=new SC,this.userProfile.init(),this.userStatus.init(),Gc({auth:U,params:K})}}function k(p){const B=[];if(!c(p))return B;const M=p.length;if(M===0)return B;for(let G=M-1;G>=0;G--)p[G]==="1"&&B.push(2**(M-G-1));return B}var x,iA,uA;(function(p){p.NOT_START="notStart",p.PENDING="pending",p.RESOLVED="resolved",p.REJECTED="rejected"})(x||(x={})),function(p){p[p.C2C=1]="C2C",p[p.GROUP=2]="GROUP"}(iA||(iA={})),function(p){p[p.C2C=8]="C2C",p[p.GROUP=2]="GROUP"}(uA||(uA={}));class _A{constructor(){this._name="SyncConversationHandler",this._pagingStatus=x.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:B}=ve;us.getInstance().registerWorkflowStep(Cr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,jt.CONVERSATION_RECOVER,this._syncConversationList,this),us.getInstance().registerWorkflowStep(Cr.SYNC_SERVER_INFO_AFTER_LOGIN,jt.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),B.subscribeInnerEvent(Ci.LOGOUT,this._reset,this),B.subscribeInnerEvent(Ci.DESTROY,this._dispose,this),ve.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===x.RESOLVED}_syncConversationListAfterLogin(){return mA(this,void 0,void 0,function*(){return this._pagingStatus=x.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return mA(this,void 0,void 0,function*(){const{ssoLog:B,utils:{safeStringify:M}}=ve;B.debug("_syncConversationList","start");try{const G=yield this._pagingGetConversationList(!0);this._pagingStatus=x.RESOLVED;const{conversationList:O=[]}=G||{};return B.info("_syncConversationList",`success count:${O.length}`),G}catch(G){const O=new dn(G);B.error("_syncConversationList",`fail ${M(G)}`,{error:O})}})}_pagingGetConversationList(B){return mA(this,void 0,void 0,function*(){try{const M=[];this._pagingStatus=x.PENDING;const G=yield function(re){return mA(this,void 0,void 0,function*(){const{fromAccount:Qe,pagingTimeStamp:At,pagingStartIndex:lt,pagingPinnedTimeStamp:dt,pagingPinnedStartIndex:xt}=re;return ic({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:Qe,StartIndex:lt,TimeStamp:At,TopStartIndex:xt,TopTimeStamp:dt}})})}({fromAccount:$s(),pagingTimeStamp:B?this._pagingTimeStamp:0,pagingStartIndex:B?this._pagingStartIndex:0,pagingPinnedTimeStamp:B?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:B?this._pagingPinnedStartIndex:0}),{CompleteFlag:O,SessionItem:z=[],TimeStamp:X,StartIndex:cA,TopTimeStamp:DA,TopStartIndex:GA}=G||{};let KA=[];if(O===1&&(this._pagingStatus=x.RESOLVED),z.length>0&&(KA=this._getConversationOptions(z),M.push(...KA)),ve.notificationCenter.emitInnerEvent(Ci.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:KA}),this._pagingTimeStamp=X,this._pagingStartIndex=cA,this._pagingPinnedTimeStamp=DA,this._pagingPinnedStartIndex=GA,O!==1){const{conversationList:re}=yield this._pagingGetConversationList(B);M.push(...re)}return{conversationList:M}}catch(M){throw M}})}_getConversationOptions(B){const{utils:{isUndefined:M}}=ve,G=this._convertConversationKey(B);return this._filterValidConversations(G).map(O=>(M(O.lastMsg)&&(O.lastMsg={elements:[]}),O.type===iA.C2C?this._assembleC2COption(O):this._assembleGroupOption(O)))}_filterValidConversations(B){return B.filter(({type:M,userID:G})=>M===iA.C2C&&!function(O){let z;return O.startsWith(Sn.CONV_C2C)&&(z=O.replace(Sn.CONV_C2C,"")),z==="@TLS#ERROR"||z==="@TLS#NOT_FOUND"}(G)||M===2)}_assembleC2COption(B){var M,G,O,z,X,cA,DA,GA;const KA=this._createUserprofile(B);return{conversationID:`${Sn.CONV_C2C}${B.userID}`,type:Sn.CONV_C2C,lastMessage:{lastTime:B.time,lastSequence:B.sequence,fromAccount:B.lastC2CMsgFromAccount,type:!((M=B.lastMsg)===null||M===void 0)&&M.elements[0]?(G=B.lastMsg)===null||G===void 0?void 0:G.elements[0].type:null,payload:!((O=B.lastMsg)===null||O===void 0)&&O.elements[0]?this._amendLayersOverLimitProp(B.lastMsg.elements[0].content):null,cloudCustomData:((cA=(X=(z=B.lastMsg)===null||z===void 0?void 0:z.elements)===null||X===void 0?void 0:X[0])===null||cA===void 0?void 0:cA.cloudCustomData)||"",isRevoked:B.lastMessageFlag===uA.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(B),revoker:((GA=(DA=B.lastMsg)===null||DA===void 0?void 0:DA.revokerInfo)===null||GA===void 0?void 0:GA.revoker)||null},unreadCount:0,userProfile:KA,peerReadTime:B.peerReadTime,isPinned:B.isPinned===1,customData:B.customMark||"",markList:k(B.standardMark),conversationGroupList:[],remark:B.friendRemark||"",messageRemindType:this._transMsgRemindType(B.messageRemindType)}}_createUserprofile(B){var M;const{userID:G,nick:O,peerAvatar:z}=B,X=[{tag:"Tag_Profile_IM_Nick",value:O},{tag:"Tag_Profile_IM_Image",value:z}];return(M=ve.user.userProfile)===null||M===void 0?void 0:M.createProfile(G,X)}_computeIsPeerRead(B){const M=$s(),{lastC2CMsgFromAccount:G,time:O,c2cPeerReadTime:z}=B;return G===M&&O<=z}_assembleGroupOption(B){var M,G,O,z,X;return{conversationID:`${Sn.CONV_GROUP}${B.groupID}`,type:Sn.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:B.time,lastSequence:B.sequence,fromAccount:B.msgGroupFromAccount},this._patchTypeAndPayload(B)),{cloudCustomData:((O=(G=(M=B.lastMsg)===null||M===void 0?void 0:M.elements)===null||G===void 0?void 0:G[0])===null||O===void 0?void 0:O.cloudCustomData)||"",isRevoked:B.lastMessageFlag===uA.GROUP,onlineOnlyFlag:!1,nick:B.msgGroupFromNickName||"",nameCard:B.msgGroupFromCardName||"",revoker:((X=(z=B.lastMsg)===null||z===void 0?void 0:z.revokerInfo)===null||X===void 0?void 0:X.revoker)||null}),groupProfile:{groupID:B.groupID,name:B.groupNick,avatar:B.groupImage,type:B.groupType,nextMessageSeq:B.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(B),peerReadTime:0,isPinned:B.isPinned===1,version:0,customData:B.customMark||"",markList:k(B.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(B.messageRemindType),subType:B.groupType}}_convertConversationKey(B){return B.map(M=>({type:M.Type,userID:M.To_Account,nick:M.C2cNick,peerAvatar:M.C2cImage,time:M.MsgTimeStamp,sequence:M.MsgSeq,lastC2CMsgFromAccount:M.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(M.LastMsg),lastMessageFlag:M.LastMsgFlags,c2cPeerReadTime:M.C2cPeerReadTime,peerReadTime:M.C2cPeerReadTime,friendRemark:M.C2cRemark,isPinned:M.TopFlags,standardMark:M.StandardMark,customMark:M.CustomMark,messageRemindType:M.MsgRecvOption,groupID:M.ToAccount,groupNick:M.GroupNick,groupImage:M.GroupImage,groupType:M.GroupType,nextMessageSeq:M.GroupNextMsgSeq,msgGroupFromAccount:M.MsgGroupFrom_Account,msgGroupFromNickName:M.MsgGroupFromNickName,msgGroupFromCardName:M.MsgGroupFromCardName,unreadCount:M.UnreadMsgCount,noUnreadCount:M.GroupIgnoredUnreadSeqCount}))}_convertLastMsgKey(B){var M,G,O;const{utils:{isEmpty:z}}=ve;if(z(B))return null;let X="",cA=null;if(!z(B.GroupTips)){const{From_Account:DA,GroupName:GA}=((M=B.GroupTips)===null||M===void 0?void 0:M.GroupInfo)||{};X=Sn.MSG_GRP_TIP,cA=Object.assign(Object.assign({},this._parseContent(X,B.GroupTips.MsgBody)),{groupProfile:{from:DA,groupName:GA}})}return B.MsgBody&&(X=(G=B.MsgBody[0])===null||G===void 0?void 0:G.MsgType,cA=this._parseContent(X,B.MsgBody[0])),{event:B.Event,elements:[{type:X,content:cA,cloudCustomData:B.CloudCustomData}],revokerInfo:{revoker:(O=B.RevokerInfo)===null||O===void 0?void 0:O.Revoker_Account}}}_parseContent(B,M){var G;if(!M)return M;const O=ve.message.messageFactory.getElementClass(B);return O?(G=O.parseServerPushElement(M))===null||G===void 0?void 0:G.content:M}_amendLayersOverLimitProp(B){const{LayersOverLimit:M}=B;return vo(B,["LayersOverLimit"]).layersOverLimit=M===1,B}_transMsgRemindType(B){let M="";return B===0?M=Sn.MSG_REMIND_ACPT_AND_NOTE:B===1?M=Sn.MSG_REMIND_DISCARD:B===2?M=Sn.MSG_REMIND_ACPT_NOT_NOTE:B===3&&(M=Sn.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),M}_patchTypeAndPayload(B){var M;const{utils:{isUndefined:G}}=ve,{event:O,elements:z=[]}=B.lastMsg||{};return G(O)?{type:z[0]?z[0].type:null,payload:z[0]?this._amendLayersOverLimitProp(z[0].content):null}:{type:Sn.MSG_GRP_TIP,payload:((M=z?.[0])===null||M===void 0?void 0:M.content)||{}}}_computeGroupUnreadCount(B){const{unreadCount:M=0,noUnreadCount:G=0}=B,O=M-G;return O>0?O:0}_reset(){this._pagingStatus=x.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:B}=ve;B.unSubscribeInnerEvent(Ci.LOGOUT,this._reset,this),B.unSubscribeInnerEvent(Ci.DESTROY,this._dispose,this)}}class ie{constructor(){this.syncConversationHandler=new _A,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Aa}`);var ye={create:function(p){var B,M;const{SDKAppID:G,testEnv:O=!1,devMode:z=!1,unlimitedAVChatRoom:X=!1,scene:cA="",oversea:DA=!1,instance:GA,disableIndependentDomain:KA=!1,proxyServer:re=""}=p;let Qe=G;if(!function(lt){if(typeof lt=="number")return!0;const dt=Number(lt);return!Number.isNaN(dt)}(Qe))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(Qe=Number(Qe),Pn.has(Qe))return Pn.get(Qe);let At=null;if(GA)At=GA,At._workflowManager&&us.setInstance(At._workflowManager),At._pluginManager&&At._pluginManager.installBuiltInPlugin(Dr),GA.isReady()&&((M=(B=us.getInstance()).executeWorkflow)===null||M===void 0||M.call(B,Cr.SYNC_SERVER_INFO_AFTER_LOGIN));else{const lt=function(){function so(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${so()+so()}${so()}${so()}${so()}${so()}${so()}${so()}`}();ve.init({sdkAppId:Qe,instanceId:lt,testEnv:O,devMode:z,unlimitedAVChatRoom:X,disableIndependentDomain:KA,scene:cA,oversea:DA,sdkEdition:xu,version:Aa,proxyServer:re}),us.getInstance().init(),ve.message=new dl,ve.user=new sA,ve.login=new sc,ve.conversation=new ie,Jo.getInstance().installBuiltInPlugin(Dr),At=ss.getInstance().exposeApiForClient(),At._workflowManager=us.getInstance(),At._pluginManager=Jo.getInstance();const{utils:{IS_WORKER_AVAILABLE:dt,USER_AGENT:xt,getPlatformType:Wt,isIOSWebView:Ki}}=ve,Eo=`instanceID:${lt} SDKAppID:${G} platform:${jA} host:${Wt()} isIOSWebView:${Ki} workerAvailable:${dt} UserAgent:${xt}`;ve.ssoLog.info("sdkConstruct",Eo)}return Pn.set(Qe,At),At},TSignaling:lo,EVENT:Ts,VERSION:Aa,TYPES:Sn};return ye})}(yY)),yY.exports}var YL={exports:{}},DY={exports:{}},TaA=DY.exports,TZ;function NaA(){return TZ||(TZ=1,function(e,i){(function(n,c){e.exports=c()})(TaA,function(){function n(A,t){return t.forEach(function(o){o&&typeof o!="string"&&!Array.isArray(o)&&Object.keys(o).forEach(function(a){if(a!=="default"&&!(a in A)){var l=Object.getOwnPropertyDescriptor(o,a);Object.defineProperty(A,a,l.get?l:{enumerable:!0,get:function(){return o[a]}})}})}),Object.freeze(A)}var c=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof Sg<"u"?Sg:typeof self<"u"?self:{};function I(A){return A&&A.__esModule&&Object.prototype.hasOwnProperty.call(A,"default")?A.default:A}var C=function(A){return A&&A.Math===Math&&A},m=C(typeof globalThis=="object"&&globalThis)||C(typeof window=="object"&&window)||C(typeof self=="object"&&self)||C(typeof c=="object"&&c)||C(typeof c=="object"&&c)||function(){return this}()||Function("return this")(),R={},_=function(A){try{return!!A()}catch{return!0}},T=!_(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),b=!_(function(){var A=function(){}.bind();return typeof A!="function"||A.hasOwnProperty("prototype")}),J=b,gA=Function.prototype.call,eA=J?gA.bind(gA):function(){return gA.apply(gA,arguments)},CA={},IA={}.propertyIsEnumerable,oA=Object.getOwnPropertyDescriptor,vA=oA&&!IA.call({1:2},1);CA.f=vA?function(A){var t=oA(this,A);return!!t&&t.enumerable}:IA;var qA,Ae,HA=function(A,t){return{enumerable:!(1&A),configurable:!(2&A),writable:!(4&A),value:t}},se=b,WA=Function.prototype,Ye=WA.call,We=se&&WA.bind.bind(Ye,Ye),Pe=se?We:function(A){return function(){return Ye.apply(A,arguments)}},we=Pe,et=we({}.toString),Xe=we("".slice),ae=function(A){return Xe(et(A),8,-1)},Je=_,pt=ae,$t=Object,Pt=Pe("".split),ii=Je(function(){return!$t("z").propertyIsEnumerable(0)})?function(A){return pt(A)==="String"?Pt(A,""):$t(A)}:$t,ki=function(A){return A==null},ao=ki,Ji=TypeError,Vi=function(A){if(ao(A))throw new Ji("Can't call method on "+A);return A},wn=ii,Fi=Vi,en=function(A){return wn(Fi(A))},Ro=typeof document=="object"&&document.all,oo=Ro===void 0&&Ro!==void 0?function(A){return typeof A=="function"||A===Ro}:function(A){return typeof A=="function"},Ai=oo,no=function(A){return typeof A=="object"?A!==null:Ai(A)},Ri=m,pn=oo,jA=function(A,t){return arguments.length<2?(o=Ri[A],pn(o)?o:void 0):Ri[A]&&Ri[A][t];var o},ue=Pe({}.isPrototypeOf),He=m.navigator,Lt=He&&He.userAgent,ct=Lt?String(Lt):"",Ct=m,ei=ct,Ht=Ct.process,Le=Ct.Deno,it=Ht&&Ht.versions||Le&&Le.version,Tt=it&&it.v8;Tt&&(Ae=(qA=Tt.split("."))[0]>0&&qA[0]<4?1:+(qA[0]+qA[1])),!Ae&&ei&&(!(qA=ei.match(/Edge\/(\d+)/))||qA[1]>=74)&&(qA=ei.match(/Chrome\/(\d+)/))&&(Ae=+qA[1]);var Gt=Ae,Hi=Gt,po=_,To=m.String,Zi=!!Object.getOwnPropertySymbols&&!po(function(){var A=Symbol("symbol detection");return!To(A)||!(Object(A)instanceof Symbol)||!Symbol.sham&&Hi&&Hi<41}),wo=Zi&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Cn=jA,an=oo,Vo=ue,jn=Object,vo=wo?function(A){return typeof A=="symbol"}:function(A){var t=Cn("Symbol");return an(t)&&Vo(t.prototype,jn(A))},mA=String,xs=function(A){try{return mA(A)}catch{return"Object"}},Zs=oo,mn=xs,Fr=TypeError,qi=function(A){if(Zs(A))return A;throw new Fr(mn(A)+" is not a function")},tn=qi,Ks=ki,_n=function(A,t){var o=A[t];return Ks(o)?void 0:tn(o)},Is=eA,qt=oo,$a=no,Ls=TypeError,Bs={exports:{}},Un=m,ur=Object.defineProperty,Fn=function(A,t){try{ur(Un,A,{value:t,configurable:!0,writable:!0})}catch{Un[A]=t}return t},rr=m,fo=Fn,es="__core-js_shared__",vc=Bs.exports=rr[es]||fo(es,{});(vc.versions||(vc.versions=[])).push({version:"3.47.0",mode:"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru), 2025 CoreJS Company (core-js.io)",license:"https://github.com/zloirock/core-js/blob/v3.47.0/LICENSE",source:"https://github.com/zloirock/core-js"});var ts=Bs.exports,Er=ts,On=function(A,t){return Er[A]||(Er[A]=t||{})},Mg=Vi,yn=Object,ce=function(A){return yn(Mg(A))},ot=ce,Zt=Pe({}.hasOwnProperty),Ho=Object.hasOwn||function(A,t){return Zt(ot(A),t)},Ba=Pe,WI=0,gn=Math.random(),ro=Ba(1.1.toString),Mc=function(A){return"Symbol("+(A===void 0?"":A)+")_"+ro(++WI+gn,36)},cg=On,Rg=Ho,Qa=Mc,Fo=Zi,Aa=wo,Uo=m.Symbol,Zc=cg("wks"),Xs=Aa?Uo.for||Uo:Uo&&Uo.withoutSetter||Qa,is=function(A){return Rg(Zc,A)||(Zc[A]=Fo&&Rg(Uo,A)?Uo[A]:Xs("Symbol."+A)),Zc[A]},wg=eA,Rc=no,ws=vo,Fa=_n,Qs=function(A,t){var o,a;if(t==="string"&&qt(o=A.toString)&&!$a(a=Is(o,A))||qt(o=A.valueOf)&&!$a(a=Is(o,A))||t!=="string"&&qt(o=A.toString)&&!$a(a=Is(o,A)))return a;throw new Ls("Can't convert object to primitive value")},Tn=TypeError,pa=is("toPrimitive"),_s=function(A,t){if(!Rc(A)||ws(A))return A;var o,a=Fa(A,pa);if(a){if(t===void 0&&(t="default"),o=wg(a,A,t),!Rc(o)||ws(o))return o;throw new Tn("Can't convert object to primitive value")}return t===void 0&&(t="number"),Qs(A,t)},Oa=_s,Ta=vo,$=function(A){var t=Oa(A,"string");return Ta(t)?t:t+""},j=no,RA=m.document,ZA=j(RA)&&j(RA.createElement),ne=function(A){return ZA?RA.createElement(A):{}},De=ne,Ke=!T&&!_(function(){return Object.defineProperty(De("div"),"a",{get:function(){return 7}}).a!==7}),qe=T,Et=eA,ft=CA,Nt=HA,Kt=en,di=$,Bt=Ho,Jt=Ke,$i=Object.getOwnPropertyDescriptor;R.f=qe?$i:function(A,t){if(A=Kt(A),t=di(t),Jt)try{return $i(A,t)}catch{}if(Bt(A,t))return Nt(!Et(ft.f,A,t),A[t])};var eo={},os=T&&_(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),Ti=no,on=String,_g=TypeError,dr=function(A){if(Ti(A))return A;throw new _g(on(A)+" is not an object")},Mr=T,js=Ke,Nl=os,ns=dr,uI=$,ec=TypeError,wc=Object.defineProperty,Tu=Object.getOwnPropertyDescriptor,Na="enumerable",Gl="configurable",ve="writable";eo.f=Mr?Nl?function(A,t,o){if(ns(A),t=uI(t),ns(o),typeof A=="function"&&t==="prototype"&&"value"in o&&ve in o&&!o[ve]){var a=Tu(A,t);a&&a[ve]&&(A[t]=o.value,o={configurable:Gl in o?o[Gl]:a[Gl],enumerable:Na in o?o[Na]:a[Na],writable:!1})}return wc(A,t,o)}:wc:function(A,t,o){if(ns(A),t=uI(t),ns(o),js)try{return wc(A,t,o)}catch{}if("get"in o||"set"in o)throw new ec("Accessors not supported");return"value"in o&&(A[t]=o.value),A};var Se=eo,Tg=HA,lg=T?function(A,t,o){return Se.f(A,t,Tg(1,o))}:function(A,t,o){return A[t]=o,A},Ng={exports:{}},Ts=T,Rr=Ho,Ci=Function.prototype,lo=Ts&&Object.getOwnPropertyDescriptor,Xc=Rr(Ci,"name"),tc={PROPER:Xc&&function(){}.name==="something",CONFIGURABLE:Xc&&(!Ts||Ts&&lo(Ci,"name").configurable)},Gg=oo,qr=ts,_c=Pe(Function.toString);Gg(qr.inspectSource)||(qr.inspectSource=function(A){return _c(A)});var $c,Ig,Nu,ME=qr.inspectSource,bg=oo,Pa=m.WeakMap,Tc=bg(Pa)&&/native code/.test(String(Pa)),RE=Mc,xa=On("keys"),ga=function(A){return xa[A]||(xa[A]=RE(A))},kg={},EI=Tc,Sn=m,Po=no,ma=lg,Cr=Ho,jt=ts,Xt=ga,Lg=kg,dI="Object already initialized",hr=Sn.TypeError,zI=Sn.WeakMap;if(EI||jt.state){var Ag=jt.state||(jt.state=new zI);Ag.get=Ag.get,Ag.has=Ag.has,Ag.set=Ag.set,$c=function(A,t){if(Ag.has(A))throw new hr(dI);return t.facade=A,Ag.set(A,t),t},Ig=function(A){return Ag.get(A)||{}},Nu=function(A){return Ag.has(A)}}else{var ca=Xt("state");Lg[ca]=!0,$c=function(A,t){if(Cr(A,ca))throw new hr(dI);return t.facade=A,ma(A,ca,t),t},Ig=function(A){return Cr(A,ca)?A[ca]:{}},Nu=function(A){return Cr(A,ca)}}var ps={set:$c,get:Ig,has:Nu,enforce:function(A){return Nu(A)?Ig(A):$c(A,{})},getterFor:function(A){return function(t){var o;if(!Po(t)||(o=Ig(t)).type!==A)throw new hr("Incompatible receiver, "+A+" required");return o}}},Ns=Pe,Gu=_,Ug=oo,Ya=Ho,Al=T,ZI=tc.CONFIGURABLE,wE=ME,CI=ps.enforce,bu=ps.get,bl=String,Nc=Object.defineProperty,ku=Ns("".slice),Lu=Ns("".replace),kl=Ns([].join),dn=Al&&!Gu(function(){return Nc(function(){},"length",{value:8}).length!==8}),hn=String(String).split("String"),dd=Ng.exports=function(A,t,o){ku(bl(t),0,7)==="Symbol("&&(t="["+Lu(bl(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),o&&o.getter&&(t="get "+t),o&&o.setter&&(t="set "+t),(!Ya(A,"name")||ZI&&A.name!==t)&&(Al?Nc(A,"name",{value:t,configurable:!0}):A.name=t),dn&&o&&Ya(o,"arity")&&A.length!==o.arity&&Nc(A,"length",{value:o.arity});try{o&&Ya(o,"constructor")&&o.constructor?Al&&Nc(A,"prototype",{writable:!1}):A.prototype&&(A.prototype=void 0)}catch{}var a=CI(A);return Ya(a,"source")||(a.source=kl(hn,typeof t=="string"?t:"")),A};Function.prototype.toString=dd(function(){return Ug(this)&&bu(this).source||wE(this)},"toString");var hI=Ng.exports,BI=oo,_E=eo,Cd=hI,Ll=Fn,wr=function(A,t,o,a){a||(a={});var l=a.enumerable,d=a.name!==void 0?a.name:t;if(BI(o)&&Cd(o,d,a),a.global)l?A[t]=o:Ll(t,o);else{try{a.unsafe?A[t]&&(l=!0):delete A[t]}catch{}l?A[t]=o:_E.f(A,t,{value:o,enumerable:!1,configurable:!a.nonConfigurable,writable:!a.nonWritable})}return A},Gc={},el=Math.ceil,us=Math.floor,Pn=Math.trunc||function(A){var t=+A;return(t>0?us:el)(t)},fa=Pn,ea=function(A){var t=+A;return t!=t||t===0?0:fa(t)},tl=ea,hd=Math.max,ic=Math.min,ug=function(A,t){var o=tl(A);return o<0?hd(o+t,0):ic(o,t)},TE=ea,oc=Math.min,$s=function(A){var t=TE(A);return t>0?oc(t,9007199254740991):0},ar=$s,Va=function(A){return ar(A.length)},Bd=en,EC=ug,Uu=Va,XI=function(A){return function(t,o,a){var l=Bd(t),d=Uu(l);if(d===0)return!A&&-1;var h,y=EC(a,d);if(A&&o!=o){for(;d>y;)if((h=l[y++])!=h)return!0}else for(;d>y;y++)if((A||y in l)&&l[y]===o)return A||y||0;return!A&&-1}},il={includes:XI(!0),indexOf:XI(!1)},ol=Ho,$I=en,QI=il.indexOf,nl=kg,sl=Pe([].push),Ga=function(A,t){var o,a=$I(A),l=0,d=[];for(o in a)!ol(nl,o)&&ol(a,o)&&sl(d,o);for(;t.length>l;)ol(a,o=t[l++])&&(~QI(d,o)||sl(d,o));return d},Fg=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Nn=Ga,Ar=Fg.concat("length","prototype");Gc.f=Object.getOwnPropertyNames||function(A){return Nn(A,Ar)};var bc={};bc.f=Object.getOwnPropertySymbols;var Au=jA,eu=Gc,NE=bc,lh=dr,dC=Pe([].concat),Ih=Au("Reflect","ownKeys")||function(A){var t=eu.f(lh(A)),o=NE.f;return o?dC(t,o(A)):t},rl=Ho,Og=Ih,Io=R,CC=eo,GE=function(A,t,o){for(var a=Og(t),l=CC.f,d=Io.f,h=0;hh;)DI.f(A,o=l[h++],a[o]);return A};var xg,rc=jA("document","documentElement"),yd=dr,FE=Ol,Oc=Fg,ou=kg,ho=rc,OE=ne,ig="prototype",nu="script",Yu=ga("IE_PROTO"),Pc=function(){},SI=function(A){return"<"+nu+">"+A+""},ll=function(A){A.write(SI("")),A.close();var t=A.parentWindow.Object;return A=null,t},Il=function(){try{xg=new ActiveXObject("htmlfile")}catch{}Il=typeof document<"u"?document.domain&&xg?ll(xg):function(){var t,o=OE("iframe"),a="java"+nu+":";return o.style.display="none",ho.appendChild(o),o.src=String(a),(t=o.contentWindow.document).open(),t.write(SI("document.F=Object")),t.close(),t.F}():ll(xg);for(var A=Oc.length;A--;)delete Il[ig][Oc[A]];return Il()};ou[Yu]=!0;var qa=Object.create||function(A,t){var o;return A!==null?(Pc[ig]=yd(A),o=new Pc,Pc[ig]=null,o[Yu]=A):o=Il(),t===void 0?o:FE.f(o,t)},PE=is,la=qa,Gs=eo.f,Or=PE("unscopables"),ul=Array.prototype;ul[Or]===void 0&&Gs(ul,Or,{configurable:!0,value:la(null)});var Vl=function(A){ul[Or][A]=!0},xc=il.includes,xE=Vl;Us({target:"Array",proto:!0,forced:_(function(){return!Array(1).includes()})},{includes:function(A){return xc(this,A,arguments.length>1?arguments[1]:void 0)}}),xE("includes");var Yc,Vu,yC,su={},dh=!_(function(){function A(){}return A.prototype.constructor=null,Object.getPrototypeOf(new A)!==A.prototype}),Hu=Ho,vI=oo,El=ce,DC=dh,Ia=ga("IE_PROTO"),ac=Object,dg=ac.prototype,MI=DC?ac.getPrototypeOf:function(A){var t=El(A);if(Hu(t,Ia))return t[Ia];var o=t.constructor;return vI(o)&&t instanceof o?o.prototype:t instanceof ac?dg:null},YE=_,Ju=oo,qu=no,RI=MI,dl=wr,Pr=is("iterator"),xr=!1;[].keys&&("next"in(yC=[].keys())?(Vu=RI(RI(yC)))!==Object.prototype&&(Yc=Vu):xr=!0);var Cg=!qu(Yc)||YE(function(){var A={};return Yc[Pr].call(A)!==A});Cg&&(Yc={}),Ju(Yc[Pr])||dl(Yc,Pr,function(){return this});var Br={IteratorPrototype:Yc,BUGGY_SAFARI_ITERATORS:xr},Nr=eo.f,gc=Ho,Yg=is("toStringTag"),Ka=function(A,t,o){A&&!o&&(A=A.prototype),A&&!gc(A,Yg)&&Nr(A,Yg,{configurable:!0,value:t})},Hl=Br.IteratorPrototype,ya=qa,wI=HA,ru=Ka,Da=su,Cl=function(){return this},VE=function(A,t,o,a){var l=t+" Iterator";return A.prototype=ya(Hl,{next:wI(+!a,o)}),ru(A,l,!1),Da[l]=Cl,A},au=Pe,HE=qi,jr=no,gu=function(A){return jr(A)||A===null},Vt=String,Ku=TypeError,ju=function(A,t,o){try{return au(HE(Object.getOwnPropertyDescriptor(A,t)[o]))}catch{}},SC=no,K=Vi,U=function(A){if(gu(A))return A;throw new Ku("Can't set "+Vt(A)+" as a prototype")},sA=Object.setPrototypeOf||("__proto__"in{}?function(){var A,t=!1,o={};try{(A=ju(Object.prototype,"__proto__","set"))(o,[]),t=o instanceof Array}catch{}return function(a,l){return K(a),U(l),SC(a)&&(t?A(a,l):a.__proto__=l),a}}():void 0),k=Us,x=eA,iA=oo,uA=VE,_A=MI,ie=sA,ye=Ka,p=lg,B=wr,M=su,G=tc.PROPER,O=tc.CONFIGURABLE,z=Br.IteratorPrototype,X=Br.BUGGY_SAFARI_ITERATORS,cA=is("iterator"),DA="keys",GA="values",KA="entries",re=function(){return this},Qe=function(A,t,o,a,l,d,h){uA(o,t,a);var y,S,L,V=function(je){if(je===l&&oe)return oe;if(!X&&je&&je in hA)return hA[je];switch(je){case DA:case GA:case KA:return function(){return new o(this,je)}}return function(){return new o(this)}},H=t+" Iterator",lA=!1,hA=A.prototype,MA=hA[cA]||hA["@@iterator"]||l&&hA[l],oe=!X&&MA||V(l),fe=t==="Array"&&hA.entries||MA;if(fe&&(y=_A(fe.call(new A)))!==Object.prototype&&y.next&&(_A(y)!==z&&(ie?ie(y,z):iA(y[cA])||B(y,cA,re)),ye(y,H,!0)),G&&l===GA&&MA&&MA.name!==GA&&(O?p(hA,"name",GA):(lA=!0,oe=function(){return x(MA,this)})),l)if(S={values:V(GA),keys:d?oe:V(DA),entries:V(KA)},h)for(L in S)(X||lA||!(L in hA))&&B(hA,L,S[L]);else k({target:t,proto:!0,forced:X||lA},S);return hA[cA]!==oe&&B(hA,cA,oe,{name:l}),M[t]=oe,S},At=function(A,t){return{value:A,done:t}},lt=en,dt=Vl,xt=su,Wt=ps,Ki=eo.f,Eo=Qe,so=At,hi=T,qo="Array Iterator",cn=Wt.set,yi=Wt.getterFor(qo),to=Eo(Array,"Array",function(A,t){cn(this,{type:qo,target:lt(A),index:0,kind:t})},function(){var A=yi(this),t=A.target,o=A.index++;if(!t||o>=t.length)return A.target=null,so(void 0,!0);switch(A.kind){case"keys":return so(o,!1);case"values":return so(t[o],!1)}return so([o,t[o]],!1)},"values"),rs=xt.Arguments=xt.Array;if(dt("keys"),dt("values"),dt("entries"),hi&&rs.name!=="values")try{Ki(rs,"name",{value:"values"})}catch{}var be=qi,bt=ce,OA=ii,oi=Va,ms=TypeError,si="Reduce of empty array with no initial value",Dn=function(A){return function(t,o,a,l){var d=bt(t),h=OA(d),y=oi(d);if(be(o),y===0&&a<2)throw new ms(si);var S=A?y-1:0,L=A?-1:1;if(a<2)for(;;){if(S in h){l=h[S],S+=L;break}if(S+=L,A?S<0:y<=S)throw new ms(si)}for(;A?S>=0:y>S;S+=L)S in h&&(l=o(l,h[S],S,d));return l}},Ni={left:Dn(!1),right:Dn(!0)},yo=_,yt=function(A,t){var o=[][A];return!!o&&yo(function(){o.call(null,t||function(){return 1},1)})},St=m,hg=ct,qn=ae,io=function(A){return hg.slice(0,A.length)===A},Wr=io("Bun/")?"BUN":io("Cloudflare-Workers")?"CLOUDFLARE":io("Deno/")?"DENO":io("Node.js/")?"NODE":St.Bun&&typeof Bun.version=="string"?"BUN":St.Deno&&typeof Deno.version=="object"?"DENO":qn(St.process)==="process"?"NODE":St.window&&St.document?"BROWSER":"REST",cc=Wr==="NODE",In=Ni.left;Us({target:"Array",proto:!0,forced:!cc&&Gt>79&&Gt<83||!yt("reduce")},{reduce:function(A){var t=arguments.length;return In(this,A,t,t>1?arguments[1]:void 0)}});var ua=Ni.right;Us({target:"Array",proto:!0,forced:!cc&&Gt>79&&Gt<83||!yt("reduceRight")},{reduceRight:function(A){return ua(this,A,arguments.length,arguments.length>1?arguments[1]:void 0)}});var Sa=ae,oa=Array.isArray||function(A){return Sa(A)==="Array"},q=Us,QA=oa,yA=Pe([].reverse),NA=[1,2];q({target:"Array",proto:!0,forced:String(NA)===String(NA.reverse())},{reverse:function(){return QA(this)&&(this.length=this.length),yA(this)}});var ee=xs,Ne=TypeError,he=Pe([].slice),Ue=he,de=Math.floor,Ve=function(A,t){var o=A.length;if(o<8)for(var a,l,d=1;d0;)A[l]=A[--l];l!==d++&&(A[l]=a)}else for(var h=de(o/2),y=Ve(Ue(A,0,h),t),S=Ve(Ue(A,h),t),L=y.length,V=S.length,H=0,lA=0;H3)){if(Rm)return!0;if(gi)return gi<603;var A,t,o,a,l="";for(A=65;A<76;A++){switch(t=String.fromCharCode(A),A){case 66:case 69:case 70:case 72:o=3;break;case 68:case 71:o=4;break;default:o=2}for(a=0;a<47;a++)_o.push({k:t+a,v:o})}for(_o.sort(function(d,h){return h.v-d.v}),a=0;a<_o.length;a++)t=_o[a].k.charAt(0),l.charAt(l.length-1)!==t&&(l+=t);return l!=="DGBEFHACIJK"}});fn({target:"Array",proto:!0,forced:Bg||!Jl||!Dd||!Vc},{sort:function(A){A!==void 0&&ai(A);var t=Yr(this);if(Vc)return A===void 0?Es(t):Es(t,A);var o,a,l=[],d=nn(t);for(a=0;atr(S)?1:-1}}(A)),o=nn(l),a=0;ao||S!=S?1/0*h:h*S},fD=Math.fround||function(A){return mD(A,11920928955078125e-23,34028234663852886e22,11754943508222875e-54)},jM=Array,_T=Math.abs,Sd=Math.pow,TT=Math.floor,yD=Math.log,NT=Math.LN2,DD={pack:function(A,t,o){var a,l,d,h=jM(o),y=8*o-t-1,S=(1<>1,V=t===23?Sd(2,-24)-Sd(2,-77):0,H=A<0||A===0&&1/A<0?1:0,lA=0;for((A=_T(A))!=A||A===1/0?(l=A!=A?1:0,a=S):(a=TT(yD(A)/NT),A*(d=Sd(2,-a))<1&&(a--,d*=2),(A+=a+L>=1?V/d:V*Sd(2,1-L))*d>=2&&(a++,d/=2),a+L>=S?(l=0,a=S):a+L>=1?(l=(A*d-1)*Sd(2,t),a+=L):(l=A*Sd(2,L-1)*Sd(2,t),a=0));t>=8;)h[lA++]=255&l,l/=256,t-=8;for(a=a<0;)h[lA++]=255&a,a/=256,y-=8;return h[lA-1]|=128*H,h},unpack:function(A,t){var o,a=A.length,l=8*a-t-1,d=(1<>1,y=l-7,S=a-1,L=A[S--],V=127&L;for(L>>=7;y>0;)V=256*V+A[S--],y-=8;for(o=V&(1<<-y)-1,V>>=-y,y+=t;y>0;)o=256*o+A[S--],y-=8;if(V===0)V=1-h;else{if(V===d)return o?NaN:L?-1/0:1/0;o+=Sd(2,t),V-=h}return(L?-1:1)*o*Sd(2,V-t)}},GT=ce,WM=ug,bT=Va,zM=function(A){for(var t=GT(this),o=bT(t),a=arguments.length,l=WM(a>1?arguments[1]:void 0,o),d=a>2?arguments[2]:void 0,h=d===void 0?o:WM(d,o);h>l;)t[l++]=A;return t},kT=oo,LT=no,SD=sA,vD=function(A,t,o){var a,l;return SD&&kT(a=t.constructor)&&a!==o&<(l=a.prototype)&&l!==o.prototype&&SD(A,l),A},UQ=m,Gm=Pe,bm=T,vd=_r,UT=lg,FT=Pg,km=cu,MD=_,Ch=TI,OT=ea,PT=$s,Lm=_m,ZM=fD,RD=DD,Um=MI,XM=sA,xT=zM,YT=he,$M=vD,Md=GE,Fm=Ka,Rd=ps,JE=tc.PROPER,Om=tc.CONFIGURABLE,vC="ArrayBuffer",hh="DataView",Zu="prototype",Wi="Wrong index",Pm=Rd.getterFor(vC),fs=Rd.getterFor(hh),AR=Rd.set,Xu=UQ[vC],as=Xu,Bh=as&&as[Zu],ql=UQ[hh],Ic=ql&&ql[Zu],qE=Object.prototype,FQ=UQ.Array,EB=UQ.RangeError,VT=Gm(xT),HT=Gm([].reverse),OQ=RD.pack,PQ=RD.unpack,eR=function(A){return[255&A]},tR=function(A){return[255&A,A>>8&255]},wD=function(A){return[255&A,A>>8&255,A>>16&255,A>>24&255]},MC=function(A){return A[3]<<24|A[2]<<16|A[1]<<8|A[0]},dB=function(A){return OQ(ZM(A),23,4)},_D=function(A){return OQ(A,52,8)},xQ=function(A,t,o){FT(A[Zu],t,{configurable:!0,get:function(){return o(this)[t]}})},wd=function(A,t,o,a){var l=fs(A),d=Lm(o),h=!!a;if(d+t>l.byteLength)throw new EB(Wi);var y=l.bytes,S=d+l.byteOffset,L=YT(y,S,S+t);return h?L:HT(L)},_d=function(A,t,o,a,l,d){var h=fs(A),y=Lm(o),S=a(+l),L=!!d;if(y+t>h.byteLength)throw new EB(Wi);for(var V=h.bytes,H=y+h.byteOffset,lA=0;lA>24)},setUint8:function(A,t){TD(this,A,t<<24>>24)}},{unsafe:!0})}else Bh=(as=function(A){Ch(this,Bh);var t=Lm(A);AR(this,{type:vC,bytes:VT(FQ(t),0),byteLength:t}),bm||(this.byteLength=t,this.detached=!1)})[Zu],Ic=(ql=function(A,t,o){Ch(this,Ic),Ch(A,Bh);var a=Pm(A),l=a.byteLength,d=OT(t);if(d<0||d>l)throw new EB("Wrong offset");if(d+(o=o===void 0?l-d:PT(o))>l)throw new EB("Wrong length");AR(this,{type:hh,buffer:A,byteLength:o,byteOffset:d,bytes:a.bytes}),bm||(this.buffer=A,this.byteLength=o,this.byteOffset=d)})[Zu],bm&&(xQ(as,"byteLength",Pm),xQ(ql,"buffer",fs),xQ(ql,"byteLength",fs),xQ(ql,"byteOffset",fs)),km(Ic,{getInt8:function(A){return wd(this,1,A)[0]<<24>>24},getUint8:function(A){return wd(this,1,A)[0]},getInt16:function(A){var t=wd(this,2,A,arguments.length>1&&arguments[1]);return(t[1]<<8|t[0])<<16>>16},getUint16:function(A){var t=wd(this,2,A,arguments.length>1&&arguments[1]);return t[1]<<8|t[0]},getInt32:function(A){return MC(wd(this,4,A,arguments.length>1&&arguments[1]))},getUint32:function(A){return MC(wd(this,4,A,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(A){return PQ(wd(this,4,A,arguments.length>1&&arguments[1]),23)},getFloat64:function(A){return PQ(wd(this,8,A,arguments.length>1&&arguments[1]),52)},setInt8:function(A,t){_d(this,1,A,eR,t)},setUint8:function(A,t){_d(this,1,A,eR,t)},setInt16:function(A,t){_d(this,2,A,tR,t,arguments.length>2&&arguments[2])},setUint16:function(A,t){_d(this,2,A,tR,t,arguments.length>2&&arguments[2])},setInt32:function(A,t){_d(this,4,A,wD,t,arguments.length>2&&arguments[2])},setUint32:function(A,t){_d(this,4,A,wD,t,arguments.length>2&&arguments[2])},setFloat32:function(A,t){_d(this,4,A,dB,t,arguments.length>2&&arguments[2])},setFloat64:function(A,t){_d(this,8,A,_D,t,arguments.length>2&&arguments[2])}});Fm(as,vC),Fm(ql,hh);var xm={ArrayBuffer:as,DataView:ql},oR=jA,JT=Pg,Ym=T,CB=is("species"),Vm=function(A){var t=oR(A);Ym&&t&&!t[CB]&&JT(t,CB,{configurable:!0,get:function(){return this}})},qT=Vm,ND="ArrayBuffer",GD=xm[ND];Us({global:!0,constructor:!0,forced:m[ND]!==GD},{ArrayBuffer:GD}),qT(ND);var VQ=ae,KE=Pe,$u=function(A){if(VQ(A)==="Function")return KE(A)},bD=Us,Qh=$u,Hm=_,nR=dr,HQ=ug,sR=$s,kD=xm.ArrayBuffer,bs=xm.DataView,JQ=bs.prototype,Td=Qh(kD.prototype.slice),LD=Qh(JQ.getUint8),KT=Qh(JQ.setUint8);bD({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:Hm(function(){return!new kD(2).slice(1,void 0).byteLength})},{slice:function(A,t){if(Td&&t===void 0)return Td(nR(this),A);for(var o=nR(this).byteLength,a=HQ(A,o),l=HQ(t===void 0?o:t,o),d=new kD(sR(l-a)),h=new bs(this),y=new bs(d),S=0;ad;d++)if((y=je(A[d]))&&lS(Fd,y))return y;return new NC(!1)}a=EN(A,l)}for(S=lA?A.next:a.next;!(L=lN(S,a)).done;){try{y=je(L.value)}catch(_e){IS(a,"throw",_e)}if(typeof y=="object"&&y&&lS(Fd,y))return y}return new NC(!1)},ES=is("iterator"),dS=!1;try{var s=0,r={next:function(){return{done:!!s++}},return:function(){dS=!0}};r[ES]=function(){return this},Array.from(r,function(){throw 2})}catch{}var g=function(A,t){try{if(!t&&!dS)return!1}catch{return!1}var o=!1;try{var a={};a[ES]=function(){return{next:function(){return{done:o=!0}}}},A(a)}catch{}return o},u=wB,E=Nh.CONSTRUCTOR||!g(function(A){u.all(A).then(void 0,function(){})}),f=eA,D=qi,v=Zr,N=RB,P=uS;Us({target:"Promise",stat:!0,forced:E},{all:function(A){var t=this,o=v.f(t),a=o.resolve,l=o.reject,d=N(function(){var h=D(t.resolve),y=[],S=0,L=1;P(A,function(V){var H=S++,lA=!1;L++,f(h,t,V).then(function(hA){lA||(lA=!0,y[H]=hA,--L||a(y))},l)}),--L||a(y)});return d.error&&l(d.value),o.promise}});var W=Us,nA=Nh.CONSTRUCTOR,EA=wB,wA=jA,kA=oo,VA=wr,LA=EA&&EA.prototype;if(W({target:"Promise",proto:!0,forced:nA,real:!0},{catch:function(A){return this.then(void 0,A)}}),kA(EA)){var SA=wA("Promise").prototype.catch;LA.catch!==SA&&VA(LA,"catch",SA,{unsafe:!0})}var PA=eA,zA=qi,Ee=Zr,Ie=RB,Li=uS;Us({target:"Promise",stat:!0,forced:E},{race:function(A){var t=this,o=Ee.f(t),a=o.reject,l=Ie(function(){var d=zA(t.resolve);Li(A,function(h){PA(d,t,h).then(o.resolve,a)})});return l.error&&a(l.value),o.promise}});var Ui=Zr;Us({target:"Promise",stat:!0,forced:Nh.CONSTRUCTOR},{reject:function(A){var t=Ui.f(this);return(0,t.reject)(A),t.promise}});var Yt=dr,Oi=no,Bn=Zr,Re=function(A,t){if(Yt(A),Oi(t)&&t.constructor===A)return t;var o=Bn.f(A);return(0,o.resolve)(t),o.promise},Mt=Us,FA=Nh.CONSTRUCTOR,ci=Re;jA("Promise"),Mt({target:"Promise",stat:!0,forced:FA},{resolve:function(A){return ci(this,A)}});var xn=Us,Pi=wB,Vr=_,ji=jA,Qr=oo,Ut=cR,Ft=Re,oE=wr,hs=Pi&&Pi.prototype;if(xn({target:"Promise",proto:!0,real:!0,forced:!!Pi&&Vr(function(){hs.finally.call({then:function(){}},function(){})})},{finally:function(A){var t=Ut(this,ji("Promise")),o=Qr(A);return this.then(o?function(a){return Ft(t,A()).then(function(){return a})}:A,o?function(a){return Ft(t,A()).then(function(){throw a})}:A)}}),Qr(Pi)){var Do=ji("Promise").prototype.finally;hs.finally!==Do&&oE(hs,"finally",Do,{unsafe:!0})}var Bl=no,GC=ae,Gr=is("match"),Jg=function(A){var t;return Bl(A)&&((t=A[Gr])!==void 0?!!t:GC(A)==="RegExp")},bI=_,Ec=m.RegExp,uf=!bI(function(){var A=!0;try{Ec(".","d")}catch{A=!1}var t={},o="",a=A?"dgimsy":"gimsy",l=function(y,S){Object.defineProperty(t,y,{get:function(){return o+=S,!0}})},d={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var h in A&&(d.hasIndices="d"),d)l(h,d[h]);return Object.getOwnPropertyDescriptor(Ec.prototype,"flags").get.call(t)!==a||o!==a}),Ep=dr,ja=function(){var A=Ep(this),t="";return A.hasIndices&&(t+="d"),A.global&&(t+="g"),A.ignoreCase&&(t+="i"),A.multiline&&(t+="m"),A.dotAll&&(t+="s"),A.unicode&&(t+="u"),A.unicodeSets&&(t+="v"),A.sticky&&(t+="y"),t},jl=eA,kI=Ho,nE=ue,qg={correct:uf},Qg=ja,CS=RegExp.prototype,JR=qg.correct?function(A){return A.flags}:function(A){return qg.correct||!nE(CS,A)||kI(A,"flags")?A.flags:jl(Qg,A)},qR=_,KR=m.RegExp,CN=qR(function(){var A=KR("a","y");return A.lastIndex=2,A.exec("abcd")!==null}),nH=CN||qR(function(){return!KR("a","y").sticky}),hF=CN||qR(function(){var A=KR("^r","gy");return A.lastIndex=2,A.exec("str")!==null}),dp={BROKEN_CARET:hF,MISSED_STICKY:nH,UNSUPPORTED_Y:CN},hN=eo.f,BN=_,QN=m.RegExp,pN=BN(function(){var A=QN(".","s");return!(A.dotAll&&A.test(` +`)&&A.flags==="s")}),BF=_,sH=m.RegExp,QF=BF(function(){var A=sH("(?b)","g");return A.exec("b").groups.a!=="b"||"b".replace(A,"$c")!=="bc"}),Ef=T,mN=m,df=Pe,fN=Tr,rH=vD,aH=lg,gH=qa,cH=Gc.f,jR=ue,pF=Jg,yN=Dr,mF=JR,hS=dp,DN=function(A,t,o){o in A||hN(A,o,{configurable:!0,get:function(){return t[o]},set:function(a){t[o]=a}})},WR=wr,zR=_,lH=Ho,SN=ps.enforce,ZR=Vm,fF=pN,Cf=QF,IH=is("match"),kB=mN.RegExp,hf=kB.prototype,uH=mN.SyntaxError,yF=df(hf.exec),Bf=df("".charAt),DF=df("".replace),vN=df("".indexOf),MN=df("".slice),EH=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,sE=/a/g,LB=/a/g,SF=new kB(sE)!==sE,vF=hS.MISSED_STICKY,dH=hS.UNSUPPORTED_Y,RN=Ef&&(!SF||vF||fF||Cf||zR(function(){return LB[IH]=!1,kB(sE)!==sE||kB(LB)===LB||String(kB(sE,"i"))!=="/a/i"}));if(fN("RegExp",RN)){for(var UB=function(A,t){var o,a,l,d,h,y,S=jR(hf,this),L=pF(A),V=t===void 0,H=[],lA=A;if(!S&&L&&V&&A.constructor===UB)return A;if((L||jR(hf,A))&&(A=A.source,V&&(t=mF(lA))),A=A===void 0?"":yN(A),t=t===void 0?"":yN(t),lA=A,fF&&"dotAll"in sE&&(a=!!t&&vN(t,"s")>-1)&&(t=DF(t,/s/g,"")),o=t,vF&&"sticky"in sE&&(l=!!t&&vN(t,"y")>-1)&&dH&&(t=DF(t,/y/g,"")),Cf&&(d=function(hA){for(var MA,oe=hA.length,fe=0,je="",_e=[],vi=gH(null),Fe=!1,Dt=!1,pi=0,Mi="";fe<=oe;fe++){if((MA=Bf(hA,fe))==="\\")MA+=Bf(hA,++fe);else if(MA==="]")Fe=!1;else if(!Fe)switch(!0){case MA==="[":Fe=!0;break;case MA==="(":if(je+=MA,MN(hA,fe+1,fe+3)==="?:")continue;yF(EH,MN(hA,fe+1))&&(fe+=2,Dt=!0),pi++;continue;case(MA===">"&&Dt):if(Mi===""||lH(vi,Mi))throw new uH("Invalid capture group name");vi[Mi]=!0,_e[_e.length]=[Mi,pi],Dt=!1,Mi="";continue}Dt?Mi+=MA:je+=MA}return[je,_e]}(A),A=d[0],H=d[1]),h=rH(kB(A,t),S?this:hf,UB),(a||l||H.length)&&(y=SN(h),a&&(y.dotAll=!0,y.raw=UB(function(hA){for(var MA,oe=hA.length,fe=0,je="",_e=!1;fe<=oe;fe++)(MA=Bf(hA,fe))!=="\\"?_e||MA!=="."?(MA==="["?_e=!0:MA==="]"&&(_e=!1),je+=MA):je+="[\\s\\S]":je+=MA+Bf(hA,++fe);return je}(A),o)),l&&(y.sticky=!0),H.length&&(y.groups=H)),A!==lA)try{aH(h,"source",lA===""?"(?:)":lA)}catch{}return h},wN=cH(kB),_N=0;wN.length>_N;)DN(UB,kB,wN[_N++]);hf.constructor=UB,UB.prototype=hf,WR(mN,"RegExp",UB,{constructor:!0})}ZR("RegExp");var Qf=eA,Cp=Pe,FB=Dr,CH=ja,pf=dp,MF=qa,RF=ps.get,hH=pN,BH=QF,QH=On("native-string-replace",String.prototype.replace),hp=RegExp.prototype.exec,TN=hp,pH=Cp("".charAt),mH=Cp("".indexOf),wF=Cp("".replace),BS=Cp("".slice),NN=function(){var A=/a/,t=/b*/g;return Qf(hp,A,"a"),Qf(hp,t,"a"),A.lastIndex!==0||t.lastIndex!==0}(),_F=pf.BROKEN_CARET,GN=/()??/.exec("")[1]!==void 0;(NN||GN||_F||hH||BH)&&(TN=function(A){var t,o,a,l,d,h,y,S=this,L=RF(S),V=FB(A),H=L.raw;if(H)return H.lastIndex=S.lastIndex,t=Qf(TN,H,V),S.lastIndex=H.lastIndex,t;var lA=L.groups,hA=_F&&S.sticky,MA=Qf(CH,S),oe=S.source,fe=0,je=V;if(hA&&(MA=wF(MA,"y",""),mH(MA,"g")===-1&&(MA+="g"),je=BS(V,S.lastIndex),S.lastIndex>0&&(!S.multiline||S.multiline&&pH(V,S.lastIndex-1)!==` +`)&&(oe="(?: "+oe+")",je=" "+je,fe++),o=new RegExp("^(?:"+oe+")",MA)),GN&&(o=new RegExp("^"+oe+"$(?!\\s)",MA)),NN&&(a=S.lastIndex),l=Qf(hp,hA?o:S,je),hA?l?(l.input=BS(l.input,fe),l[0]=BS(l[0],fe),l.index=S.lastIndex,S.lastIndex+=l[0].length):S.lastIndex=0:NN&&l&&(S.lastIndex=S.global?l.index+l[0].length:a),GN&&l&&l.length>1&&Qf(QH,l[0],o,function(){for(d=1;d0;(a>>>=1)&&(t+=t))1&a&&(o+=t);return o},mf=Vi,ff=GF(yH),ew=GF("".slice),bF=Math.ceil,bN=function(A){return function(t,o,a){var l,d,h=Aw(mf(t)),y=fH(o),S=h.length,L=a===void 0?" ":Aw(a);return y<=S||L===""?h:((d=ff(L,bF((l=y-S)/L.length))).length>l&&(d=ew(d,0,l)),A?h+d:d+h)}},kN={start:bN(!1)},LN=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(ct),DH=kN.start;Us({target:"String",proto:!0,forced:LN},{padStart:function(A){return DH(this,A,arguments.length>1?arguments[1]:void 0)}});var kF=eA,UN=wr,LF=QS,FN=_,ON=is,SH=ON("species"),UF=RegExp.prototype,tw=Pe,vH=ea,yf=Dr,Df=Vi,PN=tw("".charAt),FF=tw("".charCodeAt),MH=tw("".slice),OF=function(A){return function(t,o){var a,l,d=yf(Df(t)),h=vH(o),y=d.length;return h<0||h>=y?A?"":void 0:(a=FF(d,h))<55296||a>56319||h+1===y||(l=FF(d,h+1))<56320||l>57343?A?PN(d,h):a:A?MH(d,h,h+2):l-56320+(a-55296<<10)+65536}},iw={codeAt:OF(!1),charAt:OF(!0)},RH=iw.charAt,ow=Pe,wH=ce,_H=Math.floor,xN=ow("".charAt),YN=ow("".replace),VN=ow("".slice),TH=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,NH=/\$([$&'`]|\d{1,2})/g,PF=function(A,t,o,a,l,d){var h=o+A.length,y=a.length,S=NH;return l!==void 0&&(l=wH(l),S=TH),YN(d,S,function(L,V){var H;switch(xN(V,0)){case"$":return"$";case"&":return A;case"`":return VN(t,0,o);case"'":return VN(t,h);case"<":H=l[VN(V,1,-1)];break;default:var lA=+V;if(lA===0)return L;if(lA>y){var hA=_H(lA/10);return hA===0?L:hA<=y?a[hA-1]===void 0?xN(V,1):a[hA-1]+xN(V,1):L}H=a[lA-1]}return H===void 0?"":H})},xF=eA,GH=dr,YF=oo,bH=ae,VF=QS,kH=TypeError,LH=Nd,HF=eA,nw=Pe,UH=function(A,t,o,a){var l=ON(A),d=!FN(function(){var L={};return L[l]=function(){return 7},""[A](L)!==7}),h=d&&!FN(function(){var L=!1,V=/a/,H;return V.exec=function(){return L=!0,null},V[l](""),!L});if(!d||!h||o){var y=/./[l],S=t(l,""[A],function(L,V,H,lA,hA){var MA=V.exec;return MA===LF||MA===UF.exec?d&&!hA?{done:!0,value:kF(y,V,H,lA)}:{done:!0,value:kF(L,H,V,lA)}:{done:!1}});UN(String.prototype,A,S[0]),UN(UF,l,S[1])}},FH=_,OH=dr,JF=oo,PH=no,xH=ea,qF=$s,Bp=Dr,sw=Vi,KF=function(A,t,o){return t+(o?RH(A,t).length:1)},rw=_n,jF=PF,WF=JR,YH=function(A,t){var o=A.exec;if(YF(o)){var a=xF(o,A,t);return a!==null&&GH(a),a}if(bH(A)==="RegExp")return xF(VF,A,t);throw new kH("RegExp#exec called on incompatible receiver")},aw=is("replace"),HN=Math.max,VH=Math.min,zF=nw([].concat),JN=nw([].push),gw=nw("".indexOf),ZF=nw("".slice),HH=function(A){return A===void 0?A:String(A)},JH="a".replace(/./,"$0")==="$0",XF=!!/./[aw]&&/./[aw]("a","$0")==="",qH=!FH(function(){var A=/./;return A.exec=function(){var t=[];return t.groups={a:"7"},t},"".replace(A,"$")!=="7"});UH("replace",function(A,t,o){var a=XF?"$":"$0";return[function(l,d){var h=sw(this),y=PH(l)?rw(l,aw):void 0;return y?HF(y,l,h,d):HF(t,Bp(h),l,d)},function(l,d){var h=OH(this),y=Bp(l);if(typeof d=="string"&&gw(d,a)===-1&&gw(d,"$<")===-1){var S=o(t,h,y,d);if(S.done)return S.value}var L=JF(d);L||(d=Bp(d));var V,H=Bp(WF(h)),lA=gw(H,"g")!==-1;lA&&(V=gw(H,"u")!==-1,h.lastIndex=0);for(var hA,MA=[];(hA=YH(h,y))!==null&&(JN(MA,hA),lA);)Bp(hA[0])===""&&(h.lastIndex=KF(y,qF(h.lastIndex),V));for(var oe="",fe=0,je=0;je=fe&&(oe+=ZF(y,fe,Fe)+_e,fe=Fe+vi.length)}return oe+ZF(y,fe)}]},!qH||!JH||XF);var cw=` +\v\f\r                 \u2028\u2029\uFEFF`,KH=Vi,jH=Dr,qN=cw,KN=Pe("".replace),$F=RegExp("^["+qN+"]+"),WH=RegExp("(^|[^"+qN+"])["+qN+"]+$"),zH=function(A){return function(t){var o=jH(KH(t));return 1&A&&(o=KN(o,$F,"")),2&A&&(o=KN(o,WH,"$1")),o}},ZH={trim:zH(3)},XH=tc.PROPER,$H=_,AO=cw,AJ=ZH.trim;Us({target:"String",proto:!0,forced:function(A){return $H(function(){return!!AO[A]()||"​…᠎"[A]()!=="​…᠎"||XH&&AO[A].name!==A})}("trim")},{trim:function(){return AJ(this)}});var Eu,Sf,lw,jN={exports:{}},eJ=_r,WN=T,LI=m,eO=oo,tO=no,vf=Ho,Iw=yr,zN=xs,ZN=lg,XN=wr,iO=Pg,tJ=ue,$N=MI,Qp=sA,iJ=is,oJ=Mc,AG=ps.enforce,Oh=LI.Int8Array,Mf=Oh&&Oh.prototype,oO=LI.Uint8ClampedArray,nO=oO&&oO.prototype,bC=Oh&&$N(Oh),Od=Mf&&$N(Mf),nJ=Object.prototype,eG=LI.TypeError,sO=iJ("toStringTag"),tG=oJ("TYPED_ARRAY_TAG"),pS="TypedArrayConstructor",Pd=eJ&&!!Qp&&Iw(LI.opera)!=="Opera",rO=!1,OB={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},aO={BigInt64Array:8,BigUint64Array:8},uw=function(A){if(!tO(A))return!1;var t=Iw(A);return vf(OB,t)||vf(aO,t)};for(Eu in OB)(lw=(Sf=LI[Eu])&&Sf.prototype)?AG(lw)[pS]=Sf:Pd=!1;for(Eu in aO)(lw=(Sf=LI[Eu])&&Sf.prototype)&&(AG(lw)[pS]=Sf);if((!Pd||!eO(bC)||bC===Function.prototype)&&(bC=function(){throw new eG("Incorrect invocation")},Pd))for(Eu in OB)LI[Eu]&&Qp(LI[Eu],bC);if((!Pd||!Od||Od===nJ)&&(Od=bC.prototype,Pd))for(Eu in OB)LI[Eu]&&Qp(LI[Eu].prototype,Od);if(Pd&&$N(nO)!==Od&&Qp(nO,Od),WN&&!vf(Od,sO))for(Eu in rO=!0,iO(Od,sO,{configurable:!0,get:function(){return tO(this)?this[tG]:void 0}}),OB)LI[Eu]&&ZN(LI[Eu],tG,Eu);var xd={NATIVE_ARRAY_BUFFER_VIEWS:Pd,TYPED_ARRAY_TAG:rO&&tG,aTypedArray:function(A){if(uw(A))return A;throw new eG("Target is not a typed array")},aTypedArrayConstructor:function(A){if(eO(A)&&(!Qp||tJ(bC,A)))return A;throw new eG(zN(A)+" is not a typed array constructor")},exportTypedArrayMethod:function(A,t,o,a){if(WN){if(o)for(var l in OB){var d=LI[l];if(d&&vf(d.prototype,A))try{delete d.prototype[A]}catch{try{d.prototype[A]=t}catch{}}}Od[A]&&!o||XN(Od,A,o?t:Pd&&Mf[A]||t,a)}},exportTypedArrayStaticMethod:function(A,t,o){var a,l;if(WN){if(Qp){if(o){for(a in OB)if((l=LI[a])&&vf(l,A))try{delete l[A]}catch{}}if(bC[A]&&!o)return;try{return XN(bC,A,o?t:Pd&&bC[A]||t)}catch{}}for(a in OB)!(l=LI[a])||l[A]&&!o||XN(l,A,t)}},isTypedArray:uw,TypedArray:bC,TypedArrayPrototype:Od},iG=m,mS=_,Ew=g,sJ=xd.NATIVE_ARRAY_BUFFER_VIEWS,gO=iG.ArrayBuffer,pp=iG.Int8Array,cO=!sJ||!mS(function(){pp(1)})||!mS(function(){new pp(-1)})||!Ew(function(A){new pp,new pp(null),new pp(1.5),new pp(A)},!0)||mS(function(){return new pp(new gO(2),1,void 0).length!==1}),rJ=no,aJ=Math.floor,lO=Number.isInteger||function(A){return!rJ(A)&&isFinite(A)&&aJ(A)===A},gJ=ea,cJ=RangeError,dw=function(A){var t=gJ(A);if(t<0)throw new cJ("The argument can't be less than 0");return t},lJ=RangeError,IO=function(A,t){var o=dw(A);if(o%t)throw new lJ("Wrong offset");return o},IJ=Math.round,uO=yr,uJ=_s,EJ=TypeError,Cw=function(A){var t=uJ(A,"number");if(typeof t=="number")throw new EJ("Can't convert number to bigint");return BigInt(t)},EO=og,dO=eA,dJ=yh,CJ=ce,CO=Va,hO=ZE,hJ=Fh,BO=sS,QO=function(A){var t=uO(A);return t==="BigInt64Array"||t==="BigUint64Array"},BJ=xd.aTypedArrayConstructor,QJ=Cw,hw=function(A){var t,o,a,l,d,h,y,S,L=dJ(this),V=CJ(A),H=arguments.length,lA=H>1?arguments[1]:void 0,hA=lA!==void 0,MA=hJ(V);if(MA&&!BO(MA))for(S=(y=hO(V,MA)).next,V=[];!(h=dO(S,y)).done;)V.push(h.value);for(hA&&H>2&&(lA=EO(lA,arguments[2])),o=CO(V),a=new(BJ(L))(o),l=QO(a),t=0;o>t;t++)d=hA?lA(V[t],t):V[t],a[t]=l?QJ(d):+d;return a},oG=oa,nG=OD,pJ=no,mJ=is("species"),pO=Array,fJ=function(A){var t;return oG(A)&&(t=A.constructor,(nG(t)&&(t===pO||oG(t.prototype))||pJ(t)&&(t=t[mJ])===null)&&(t=void 0)),t===void 0?pO:t},mO=og,yJ=ii,DJ=ce,fO=Va,SJ=function(A,t){return new(fJ(A))(t===0?0:t)},sG=Pe([].push),yO=function(A){var t=A===1,o=A===2,a=A===3,l=A===4,d=A===6,h=A===7,y=A===5||d;return function(S,L,V,H){for(var lA,hA,MA=DJ(S),oe=yJ(MA),fe=fO(oe),je=mO(L,V),_e=0,vi=H||SJ,Fe=t?vi(S,fe):o||h?vi(S,0):void 0;fe>_e;_e++)if((y||_e in oe)&&(hA=je(lA=oe[_e],_e,MA),A))if(t)Fe[_e]=hA;else if(hA)switch(A){case 3:return!0;case 5:return lA;case 6:return _e;case 2:sG(Fe,lA)}else switch(A){case 4:return!1;case 7:sG(Fe,lA)}return d?-1:a||l?l:Fe}},DO={forEach:yO(0)},vJ=Va,SO=Us,vO=m,MO=eA,RO=T,MJ=cO,fS=xd,wO=xm,_O=TI,RJ=HA,PB=lg,wJ=lO,_J=$s,TO=_m,rG=IO,NO=function(A){var t=IJ(A);return t<0?0:t>255?255:255&t},aG=$,mp=Ho,TJ=yr,gG=no,cG=vo,NJ=qa,lG=ue,Bw=sA,GJ=Gc.f,GO=hw,bO=DO.forEach,Qw=Vm,bJ=Pg,kO=eo,LO=R,UO=function(A,t,o){for(var a=0,l=arguments.length>2?o:vJ(t),d=new A(l);l>a;)d[a]=t[a++];return d},kJ=vD,IG=ps.get,LJ=ps.set,fp=ps.enforce,FO=kO.f,UJ=LO.f,uG=vO.RangeError,OO=wO.ArrayBuffer,FJ=OO.prototype,OJ=wO.DataView,Rf=fS.NATIVE_ARRAY_BUFFER_VIEWS,PO=fS.TYPED_ARRAY_TAG,xO=fS.TypedArray,yS=fS.TypedArrayPrototype,DS=fS.isTypedArray,yp="BYTES_PER_ELEMENT",pw="Wrong length",mw=function(A,t){bJ(A,t,{configurable:!0,get:function(){return IG(this)[t]}})},YO=function(A){var t;return lG(FJ,A)||(t=TJ(A))==="ArrayBuffer"||t==="SharedArrayBuffer"},EG=function(A,t){return DS(A)&&!cG(t)&&t in A&&wJ(+t)&&t>=0},fw=function(A,t){return t=aG(t),EG(A,t)?RJ(2,A[t]):UJ(A,t)},VO=function(A,t,o){return t=aG(t),!(EG(A,t)&&gG(o)&&mp(o,"value"))||mp(o,"get")||mp(o,"set")||o.configurable||mp(o,"writable")&&!o.writable||mp(o,"enumerable")&&!o.enumerable?FO(A,t,o):(A[t]=o.value,A)};RO?(Rf||(LO.f=fw,kO.f=VO,mw(yS,"buffer"),mw(yS,"byteOffset"),mw(yS,"byteLength"),mw(yS,"length")),SO({target:"Object",stat:!0,forced:!Rf},{getOwnPropertyDescriptor:fw,defineProperty:VO}),jN.exports=function(A,t,o){var a=A.match(/\d+/)[0]/8,l=A+(o?"Clamped":"")+"Array",d="get"+A,h="set"+A,y=vO[l],S=y,L=S&&S.prototype,V={},H=function(hA,MA){FO(hA,MA,{get:function(){return function(oe,fe){var je=IG(oe);return je.view[d](fe*a+je.byteOffset,!0)}(this,MA)},set:function(oe){return function(fe,je,_e){var vi=IG(fe);vi.view[h](je*a+vi.byteOffset,o?NO(_e):_e,!0)}(this,MA,oe)},enumerable:!0})};Rf?MJ&&(S=t(function(hA,MA,oe,fe){return _O(hA,L),kJ(gG(MA)?YO(MA)?fe!==void 0?new y(MA,rG(oe,a),fe):oe!==void 0?new y(MA,rG(oe,a)):new y(MA):DS(MA)?UO(S,MA):MO(GO,S,MA):new y(TO(MA)),hA,S)}),Bw&&Bw(S,xO),bO(GJ(y),function(hA){hA in S||PB(S,hA,y[hA])}),S.prototype=L):(S=t(function(hA,MA,oe,fe){_O(hA,L);var je,_e,vi,Fe=0,Dt=0;if(gG(MA)){if(!YO(MA))return DS(MA)?UO(S,MA):MO(GO,S,MA);je=MA,Dt=rG(oe,a);var pi=MA.byteLength;if(fe===void 0){if(pi%a)throw new uG(pw);if((_e=pi-Dt)<0)throw new uG(pw)}else if((_e=_J(fe)*a)+Dt>pi)throw new uG(pw);vi=_e/a}else vi=TO(MA),je=new OO(_e=vi*a);for(LJ(hA,{buffer:je,byteOffset:Dt,byteLength:_e,length:vi,view:new OJ(je)});Fe1?arguments[1]:void 0,t>2?arguments[2]:void 0)},dG(function(){var A=0;return new Int8Array(2).fill({valueOf:function(){return A++}}),A!==1})),(0,xd.exportTypedArrayStaticMethod)("from",hw,cO);var qO=m,KO=eA,hG=xd,jO=Va,JJ=IO,qJ=ce,WO=_,KJ=qO.RangeError,BG=qO.Int8Array,QG=BG&&BG.prototype,pG=QG&&QG.set,mG=hG.aTypedArray,zO=hG.exportTypedArrayMethod,yw=!WO(function(){var A=new Uint8ClampedArray(2);return KO(pG,A,{length:1,0:3},1),A[1]!==3}),ZO=yw&&hG.NATIVE_ARRAY_BUFFER_VIEWS&&WO(function(){var A=new BG(2);return A.set(1),A.set("2",1),A[0]!==0||A[1]!==2});zO("set",function(A){mG(this);var t=JJ(arguments.length>1?arguments[1]:void 0,1),o=qJ(A);if(yw)return KO(pG,this,o,t);var a=this.length,l=jO(o),d=0;if(l+t>a)throw new KJ("Wrong length");for(;d0&&1/a<0?1:-1:o>a}}(A))},!Dw||RG);var $O=Us,wG=eA,vS=Pe,_G=Vi,TG=oo,zJ=no,AP=Jg,MS=Dr,ZJ=_n,RS=JR,eP=PF,XJ=is("replace"),tP=TypeError,Yd=vS("".indexOf);vS("".replace);var wS=vS("".slice),$J=Math.max;$O({target:"String",proto:!0},{replaceAll:function(A,t){var o,a,l,d,h,y,S,L,V,H=_G(this),lA=0,hA="";if(zJ(A)){if(AP(A)&&(o=MS(_G(RS(A))),!~Yd(o,"g")))throw new tP("`.replaceAll` does not allow non-global regexes");if(a=ZJ(A,XJ))return wG(a,A,H,t)}for(l=MS(H),d=MS(A),(h=TG(t))||(t=MS(t)),y=d.length,S=$J(1,y),L=Yd(l,d);L!==-1;)V=h?MS(t(d,L,l)):eP(d,l,L,[],void 0,t),hA+=wS(l,lA,L)+V,lA=L+y,L=L+S>l.length?-1:Yd(l,d,L+S);return lA1?arguments[1]:void 0)},oP=m,nP=NG,tq=GG,vw=eq,iq=lg,sP=function(A){if(A&&A.forEach!==vw)try{iq(A,"forEach",vw)}catch{A.forEach=vw}};for(var bG in nP)nP[bG]&&sP(oP[bG]&&oP[bG].prototype);sP(tq);var Mw=m,rP=NG,oq=GG,_S=to,TS=lg,nq=Ka,kG=is("iterator"),LG=_S.values,aP=function(A,t){if(A){if(A[kG]!==LG)try{TS(A,kG,LG)}catch{A[kG]=LG}if(nq(A,t,!0),rP[t]){for(var o in _S)if(A[o]!==_S[o])try{TS(A,o,_S[o])}catch{A[o]=_S[o]}}}};for(var UG in rP)aP(Mw[UG]&&Mw[UG].prototype,UG);aP(oq,"DOMTokenList");var FG=wC.clear;Us({global:!0,bind:!0,enumerable:!0,forced:m.clearImmediate!==FG},{clearImmediate:FG});var NS=m,sq=Nd,rq=oo,aq=Wr,gq=ct,cq=he,lq=pB,OG=NS.Function,Iq=/MSIE .\./.test(gq)||aq==="BUN"&&function(){var A=NS.Bun.version.split(".");return A.length<3||A[0]==="0"&&(A[1]<3||A[1]==="3"&&A[2]==="0")}(),gP=Us,cP=m,Rw=wC.set,uq=function(A,t){var o=1;return Iq?function(a,l){var d=lq(arguments.length,1)>o,h=rq(a)?a:OG(a),y=d?cq(arguments,o):[],S=d?function(){sq(h,this,y)}:h;return A(S)}:A},PG=cP.setImmediate?uq(Rw):Rw;gP({global:!0,bind:!0,enumerable:!0,forced:cP.setImmediate!==PG},{setImmediate:PG});var Ph=iw.charAt,Eq=Dr,ww=ps,dq=Qe,lP=At,IP="String Iterator",Cq=ww.set,uP=ww.getterFor(IP);dq(String,"String",function(A){Cq(this,{type:IP,string:Eq(A),index:0})},function(){var A,t=uP(this),o=t.string,a=t.index;return a>=o.length?lP(void 0,!0):(A=Ph(o,a),t.index+=A.length,lP(A,!1))});var hq=_,Bq=T,Qq=is("iterator"),EP=!hq(function(){var A=new URL("b?a=1&b=2&c=3","https://a"),t=A.searchParams,o=new URLSearchParams("a=1&a=2&b=3"),a="";return A.pathname="c%20d",t.forEach(function(l,d){t.delete("b"),a+=d+l}),o.delete("a",2),o.delete("b",void 0),!t.size&&!Bq||!t.sort||A.href!=="https://a/c%20d?a=1&c=3"||t.get("c")!=="3"||String(new URLSearchParams("?a=1"))!=="a=1"||!t[Qq]||new URL("https://a@b").username!=="a"||new URLSearchParams(new URLSearchParams("a=b")).get("a")!=="b"||new URL("https://тест").host!=="xn--e1aybc"||new URL("https://a#б").hash!=="#%D0%B1"||a!=="a1c3"||new URL("https://x",void 0).host!=="x"}),dP=T,pq=Pe,xG=eA,YG=_,VG=Pl,mq=bc,fq=CA,yq=ce,CP=ii,Dp=Object.assign,hP=Object.defineProperty,BP=pq([].concat),Dq=!Dp||YG(function(){if(dP&&Dp({b:1},Dp(hP({},"a",{enumerable:!0,get:function(){hP(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var A={},t={},o=Symbol("assign detection"),a="abcdefghijklmnopqrst";return A[o]=7,a.split("").forEach(function(l){t[l]=l}),Dp({},A)[o]!==7||VG(Dp({},t)).join("")!==a})?function(A,t){for(var o=yq(A),a=arguments.length,l=1,d=mq.f,h=fq.f;a>l;)for(var y,S=CP(arguments[l++]),L=d?BP(VG(S),d(S)):VG(S),V=L.length,H=0;V>H;)y=L[H++],dP&&!xG(h,S,y)||(o[y]=S[y]);return o}:Dp,Sq=dr,vq=cS,Mq=T,Rq=eo,QP=HA,wq=og,GS=eA,pP=ce,mP=function(A,t,o,a){try{return a?t(Sq(o)[0],o[1]):t(o)}catch(l){vq(A,"throw",l)}},HG=sS,_q=OD,Tq=Va,bS=function(A,t,o){Mq?Rq.f(A,t,QP(0,o)):A[t]=o},JG=ZE,Nq=Fh,fP=Array,xB=Pe,qG=2147483647,yP=/[^\0-\u007E]/,KG=/[.\u3002\uFF0E\uFF61]/g,DP="Overflow: input needs wider integers to process",SP=RangeError,Gq=xB(KG.exec),YB=Math.floor,_w=String.fromCharCode,Tw=xB("".charCodeAt),rE=xB([].join),VB=xB([].push),va=xB("".replace),vP=xB("".split),bq=xB("".toLowerCase),MP=function(A){return A+22+75*(A<26)},jG=function(A,t,o){var a=0;for(A=o?YB(A/700):A>>1,A+=YB(A/t);A>455;)A=YB(A/35),a+=36;return YB(a+36*A/(A+38))},kq=function(A){var t=[];A=function(je){for(var _e=[],vi=0,Fe=je.length;vi=55296&&Dt<=56319&&vi=d&&aYB((qG-h)/H))throw new SP(DP);for(h+=(V-d)*H,d=V,o=0;oqG)throw new SP(DP);if(a===d){for(var lA=h,hA=36;;){var MA=hA<=y?1:hA>=y+26?26:hA-y;if(lAl;){if(t=+arguments[l++],Lq(t,1114111)!==t)throw new Uq(t+" is not a valid code point");o[l]=t<65536?xh(t):xh(55296+((t-=65536)>>10),t%1024+56320)}return LS(o,"")}});var Sp=Us,Tf=m,vp=QR,WG=jA,zn=eA,aE=Pe,Nf=T,zG=EP,wP=wr,Fq=Pg,Oq=cu,Pq=Ka,xq=VE,US=ps,_P=TI,ZG=oo,Yq=Ho,Vq=og,Hq=yr,Jq=dr,TP=no,Wl=Dr,Kq=qa,NP=HA,GP=ZE,jq=Fh,Nw=At,Gf=pB,Wq=_t,zq=is("iterator"),Mp="URLSearchParams",XG=Mp+"Iterator",bP=US.set,Ql=US.getterFor(Mp),Yh=US.getterFor(XG),kP=vp("fetch"),bf=vp("Request"),FS=vp("Headers"),$G=bf&&bf.prototype,LP=FS&&FS.prototype,UP=Tf.TypeError,Zq=Tf.encodeURIComponent,Xq=String.fromCharCode,$q=WG("String","fromCodePoint"),AK=parseInt,Gw=aE("".charAt),bw=aE([].join),Vh=aE([].push),FP=aE("".replace),eK=aE([].shift),OP=aE([].splice),PP=aE("".split),xP=aE("".slice),Ab=aE(/./.exec),YP=/\+/g,tK=/^[0-9a-f]+$/i,VP=function(A,t){var o=xP(A,t,t+2);return Ab(tK,o)?AK(o,16):NaN},iK=function(A){for(var t=0,o=128;o>0&&A&o;o>>=1)t++;return t},oK=function(A){var t=null;switch(A.length){case 1:t=A[0];break;case 2:t=(31&A[0])<<6|63&A[1];break;case 3:t=(15&A[0])<<12|(63&A[1])<<6|63&A[2];break;case 4:t=(7&A[0])<<18|(63&A[1])<<12|(63&A[2])<<6|63&A[3]}return t>1114111?null:t},HP=function(A){for(var t=(A=FP(A,YP," ")).length,o="",a=0;at){o+="%",a++;continue}var d=VP(A,a+1);if(d!=d){o+=l,a++;continue}a+=2;var h=iK(d);if(h===0)l=Xq(d);else{if(h===1||h>4){o+="�",a++;continue}for(var y=[d],S=1;St||Gw(A,a)!=="%");){var L=VP(A,a+1);if(L!=L){a+=3;break}if(L>191||L<128)break;Vh(y,L),a+=2,S++}if(y.length!==h){o+="�";continue}var V=oK(y);V===null?o+="�":l=$q(V)}}o+=l,a++}return o},nK=/[!'()~]|%20/g,sK={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},rK=function(A){return sK[A]},JP=function(A){return FP(Zq(A),nK,rK)},eb=xq(function(A,t){bP(this,{type:XG,target:Ql(A).entries,index:0,kind:t})},Mp,function(){var A=Yh(this),t=A.target,o=A.index++;if(!t||o>=t.length)return A.target=null,Nw(void 0,!0);var a=t[o];switch(A.kind){case"keys":return Nw(a.key,!1);case"values":return Nw(a.value,!1)}return Nw([a.key,a.value],!1)},!0),qP=function(A){this.entries=[],this.url=null,A!==void 0&&(TP(A)?this.parseObject(A):this.parseQuery(typeof A=="string"?Gw(A,0)==="?"?xP(A,1):A:Wl(A)))};qP.prototype={type:Mp,bindURL:function(A){this.url=A,this.update()},parseObject:function(A){var t,o,a,l,d,h,y,S=this.entries,L=jq(A);if(L)for(o=(t=GP(A,L)).next;!(a=zn(o,t)).done;){if(d=(l=GP(Jq(a.value))).next,(h=zn(d,l)).done||(y=zn(d,l)).done||!zn(d,l).done)throw new UP("Expected sequence with length 2");Vh(S,{key:Wl(h.value),value:Wl(y.value)})}else for(var V in A)Yq(A,V)&&Vh(S,{key:V,value:Wl(A[V])})},parseQuery:function(A){if(A)for(var t,o,a=this.entries,l=PP(A,"&"),d=0;d0?arguments[0]:void 0));Nf||(this.size=A.entries.length)},Rp=kf.prototype;if(Oq(Rp,{append:function(A,t){var o=Ql(this);Gf(arguments.length,2),Vh(o.entries,{key:Wl(A),value:Wl(t)}),Nf||this.size++,o.updateURL()},delete:function(A){for(var t=Ql(this),o=Gf(arguments.length,1),a=t.entries,l=Wl(A),d=o<2?void 0:arguments[1],h=d===void 0?d:Wl(d),y=0;yo.key?1:-1}),A.updateURL()},forEach:function(A){for(var t,o=Ql(this).entries,a=Vq(A,arguments.length>1?arguments[1]:void 0),l=0;l1?KP(arguments[1]):{})}}),ZG(bf)){var ib=function(A){return _P(this,$G),new bf(A,arguments.length>1?KP(arguments[1]):{})};$G.constructor=ib,ib.prototype=$G,Sp({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:ib})}}var gE,gK=Us,ob=T,jP=EP,nb=m,WP=og,XE=Pe,kw=wr,$E=Pg,cK=TI,sb=Ho,rb=Dq,HB=function(A){var t=pP(A),o=_q(this),a=arguments.length,l=a>1?arguments[1]:void 0,d=l!==void 0;d&&(l=wq(l,a>2?arguments[2]:void 0));var h,y,S,L,V,H,lA=Nq(t),hA=0;if(!lA||this===fP&&HG(lA))for(h=Tq(t),y=o?new this(h):fP(h);h>hA;hA++)H=d?l(t[hA],hA):t[hA],bS(y,hA,H);else for(y=o?new this:[],V=(L=JG(t,lA)).next;!(S=GS(V,L)).done;hA++)H=d?mP(L,l,[S.value,hA],!0):S.value,bS(y,hA,H);return y.length=hA,y},Vd=he,ab=iw.codeAt,lK=function(A){var t,o,a=[],l=vP(va(bq(A),KG,"."),".");for(t=0;t?@[\\\]^|]/,pK=/[\0\t\n\r #/:<>?@[\\\]^|]/,mK=/^[\u0000-\u0020]+/,fK=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,yK=/[\t\n\r]/g,Ff=function(A){var t,o,a,l;if(typeof A=="number"){for(t=[],o=0;o<4;o++)hK(t,A%256),A=Jh(A/256);return OS(t,".")}if(typeof A=="object"){for(t="",a=function(d){for(var h=null,y=1,S=null,L=0,V=0;V<8;V++)d[V]!==0?(L>y&&(h=S,y=L),S=null,L=0):(S===null&&(S=V),++L);return L>y?S:h}(A),o=0;o<8;o++)l&&A[o]===0||(l&&(l=!1),a===o?(t+=o?":":"::",l=!0):(t+=CK(A[o],16),o<7&&(t+=":")));return"["+t+"]"}return A},Of={},ix=rb({},Of,{" ":1,'"':1,"<":1,">":1,"`":1}),Eb=rb({},ix,{"#":1,"?":1,"{":1,"}":1}),qB=rb({},Eb,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),Jd=function(A,t){var o=ab(A,0);return o>32&&o<127&&!sb(t,A)?A:encodeURIComponent(A)},qh={ftp:21,file:null,http:80,https:443,ws:80,wss:443},Pf=function(A,t){var o;return A.length===2&&Hd(PS,Ad(A,0))&&((o=Ad(A,1))===":"||!t&&o==="|")},db=function(A){var t;return A.length>1&&Pf(wp(A,0,2))&&(A.length===2||(t=Ad(A,2))==="/"||t==="\\"||t==="?"||t==="#")},xS=function(A){return A==="."||Pw(A)==="%2e"},ox=function(A){return(A=Pw(A))===".."||A==="%2e."||A===".%2e"||A==="%2e%2e"},cE={},du={},KB={},kC={},jB={},Vw={},nx={},YS={},Hw={},Jw={},qw={},Kw={},jw={},Ww={},Cb={},zw={},xf={},LC={},VS={},Cu={},zl={},Zw=function(A,t,o){var a,l,d,h=Hh(A);if(t){if(l=this.parse(h))throw new cb(l);this.searchParams=null}else{if(o!==void 0&&(a=new Zw(o,!0)),l=this.parse(h,null,a))throw new cb(l);(d=dK(new EK)).bindURL(this),this.searchParams=d}};Zw.prototype={type:"URL",parse:function(A,t,o){var a,l,d,h,y=this,S=t||cE,L=0,V="",H=!1,lA=!1,hA=!1;for(A=Hh(A),t||(y.scheme="",y.username="",y.password="",y.host=null,y.port=null,y.path=[],y.query=null,y.fragment=null,y.cannotBeABaseURL=!1,A=Fw(A,mK,""),A=Fw(A,fK,"$1")),A=Fw(A,yK,""),a=HB(A);L<=a.length;){switch(l=a[L],S){case cE:if(!l||!Hd(PS,l)){if(t)return Ib;S=KB;continue}V+=Pw(l),S=du;break;case du:if(l&&(Hd(BK,l)||l==="+"||l==="-"||l==="."))V+=Pw(l);else{if(l!==":"){if(t)return Ib;V="",S=KB,L=0;continue}if(t&&(y.isSpecial()!==sb(qh,V)||V==="file"&&(y.includesCredentials()||y.port!==null)||y.scheme==="file"&&!y.host))return;if(y.scheme=V,t)return void(y.isSpecial()&&qh[y.scheme]===y.port&&(y.port=null));V="",y.scheme==="file"?S=Ww:y.isSpecial()&&o&&o.scheme===y.scheme?S=kC:y.isSpecial()?S=YS:a[L+1]==="/"?(S=jB,L++):(y.cannotBeABaseURL=!0,Uf(y.path,""),S=VS)}break;case KB:if(!o||o.cannotBeABaseURL&&l!=="#")return Ib;if(o.cannotBeABaseURL&&l==="#"){y.scheme=o.scheme,y.path=Vd(o.path),y.query=o.query,y.fragment="",y.cannotBeABaseURL=!0,S=zl;break}S=o.scheme==="file"?Ww:Vw;continue;case kC:if(l!=="/"||a[L+1]!=="/"){S=Vw;continue}S=Hw,L++;break;case jB:if(l==="/"){S=Jw;break}S=LC;continue;case Vw:if(y.scheme=o.scheme,l===gE)y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,y.path=Vd(o.path),y.query=o.query;else if(l==="/"||l==="\\"&&y.isSpecial())S=nx;else if(l==="?")y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,y.path=Vd(o.path),y.query="",S=Cu;else{if(l!=="#"){y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,y.path=Vd(o.path),y.path.length--,S=LC;continue}y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,y.path=Vd(o.path),y.query=o.query,y.fragment="",S=zl}break;case nx:if(!y.isSpecial()||l!=="/"&&l!=="\\"){if(l!=="/"){y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,S=LC;continue}S=Jw}else S=Hw;break;case YS:if(S=Hw,l!=="/"||Ad(V,L+1)!=="/")continue;L++;break;case Hw:if(l!=="/"&&l!=="\\"){S=Jw;continue}break;case Jw:if(l==="@"){H&&(V="%40"+V),H=!0,d=HB(V);for(var MA=0;MA65535)return xw;y.port=y.isSpecial()&&je===qh[y.scheme]?null:je,V=""}if(t)return;S=xf;continue}return xw}V+=l;break;case Ww:if(y.scheme="file",l==="/"||l==="\\")S=Cb;else{if(!o||o.scheme!=="file"){S=LC;continue}switch(l){case gE:y.host=o.host,y.path=Vd(o.path),y.query=o.query;break;case"?":y.host=o.host,y.path=Vd(o.path),y.query="",S=Cu;break;case"#":y.host=o.host,y.path=Vd(o.path),y.query=o.query,y.fragment="",S=zl;break;default:db(OS(Vd(a,L),""))||(y.host=o.host,y.path=Vd(o.path),y.shortenPath()),S=LC;continue}}break;case Cb:if(l==="/"||l==="\\"){S=zw;break}o&&o.scheme==="file"&&!db(OS(Vd(a,L),""))&&(Pf(o.path[0],!0)?Uf(y.path,o.path[0]):y.host=o.host),S=LC;continue;case zw:if(l===gE||l==="/"||l==="\\"||l==="?"||l==="#"){if(!t&&Pf(V))S=LC;else if(V===""){if(y.host="",t)return;S=xf}else{if(h=y.parseHost(V))return h;if(y.host==="localhost"&&(y.host=""),t)return;V="",S=xf}continue}V+=l;break;case xf:if(y.isSpecial()){if(S=LC,l!=="/"&&l!=="\\")continue}else if(t||l!=="?")if(t||l!=="#"){if(l!==gE&&(S=LC,l!=="/"))continue}else y.fragment="",S=zl;else y.query="",S=Cu;break;case LC:if(l===gE||l==="/"||l==="\\"&&y.isSpecial()||!t&&(l==="?"||l==="#")){if(ox(V)?(y.shortenPath(),l==="/"||l==="\\"&&y.isSpecial()||Uf(y.path,"")):xS(V)?l==="/"||l==="\\"&&y.isSpecial()||Uf(y.path,""):(y.scheme==="file"&&!y.path.length&&Pf(V)&&(y.host&&(y.host=""),V=Ad(V,0)+":"),Uf(y.path,V)),V="",y.scheme==="file"&&(l===gE||l==="?"||l==="#"))for(;y.path.length>1&&y.path[0]==="";)Ow(y.path);l==="?"?(y.query="",S=Cu):l==="#"&&(y.fragment="",S=zl)}else V+=Jd(l,Eb);break;case VS:l==="?"?(y.query="",S=Cu):l==="#"?(y.fragment="",S=zl):l!==gE&&(y.path[0]+=Jd(l,Of));break;case Cu:t||l!=="#"?l!==gE&&(l==="'"&&y.isSpecial()?y.query+="%27":y.query+=l==="#"?"%23":Jd(l,Of)):(y.fragment="",S=zl);break;case zl:l!==gE&&(y.fragment+=Jd(l,ix))}L++}},parseHost:function(A){var t,o,a;if(Ad(A,0)==="["){if(Ad(A,A.length-1)!=="]"||(t=function(l){var d,h,y,S,L,V,H,lA=[0,0,0,0,0,0,0,0],hA=0,MA=null,oe=0,fe=function(){return Ad(l,oe)};if(fe()===":"){if(Ad(l,1)!==":")return;oe+=2,MA=++hA}for(;fe();){if(hA===8)return;if(fe()!==":"){for(d=h=0;h<4&&Hd(ex,fe());)d=16*d+Uw(fe(),16),oe++,h++;if(fe()==="."){if(h===0||(oe-=h,hA>6))return;for(y=0;fe();){if(S=null,y>0){if(!(fe()==="."&&y<4))return;oe++}if(!Hd(ub,fe()))return;for(;Hd(ub,fe());){if(L=Uw(fe(),10),S===null)S=L;else{if(S===0)return;S=10*S+L}if(S>255)return;oe++}lA[hA]=256*lA[hA]+S,++y!==2&&y!==4||hA++}if(y!==4)return;break}if(fe()===":"){if(oe++,!fe())return}else if(fe())return;lA[hA++]=d}else{if(MA!==null)return;oe++,MA=++hA}}if(MA!==null)for(V=hA-MA,hA=7;hA!==0&&V>0;)H=lA[hA],lA[hA--]=lA[MA+V-1],lA[MA+--V]=H;else if(hA!==8)return;return lA}(wp(A,1,-1)),!t))return JB;this.host=t}else if(this.isSpecial()){if(A=lK(A),Hd(tx,A)||(t=function(l){var d,h,y,S,L,V,H,lA=lb(l,".");if(lA.length&&lA[lA.length-1]===""&&lA.length--,(d=lA.length)>4)return l;for(h=[],y=0;y1&&Ad(S,0)==="0"&&(L=Hd(Yw,S)?16:8,S=wp(S,L===8?1:2)),S==="")V=0;else{if(!Hd(L===10?Ax:L===8?QK:ex,S))return l;V=Uw(S,L)}Uf(h,V)}for(y=0;y=XP(256,5-d))return null}else if(V>255)return null;for(H=$P(h),y=0;y1?arguments[1]:void 0,a=uK(t,new Zw(A,!1,o));ob||(t.href=a.serialize(),t.origin=a.getOrigin(),t.protocol=a.getProtocol(),t.username=a.getUsername(),t.password=a.getPassword(),t.host=a.getHost(),t.hostname=a.getHostname(),t.port=a.getPort(),t.pathname=a.getPathname(),t.search=a.getSearch(),t.searchParams=a.getSearchParams(),t.hash=a.getHash())},Zl=Kh.prototype,Xl=function(A,t){return{get:function(){return Lw(this)[A]()},set:t&&function(o){return Lw(this)[t](o)},configurable:!0,enumerable:!0}};if(ob&&($E(Zl,"href",Xl("serialize","setHref")),$E(Zl,"origin",Xl("getOrigin")),$E(Zl,"protocol",Xl("getProtocol","setProtocol")),$E(Zl,"username",Xl("getUsername","setUsername")),$E(Zl,"password",Xl("getPassword","setPassword")),$E(Zl,"host",Xl("getHost","setHost")),$E(Zl,"hostname",Xl("getHostname","setHostname")),$E(Zl,"port",Xl("getPort","setPort")),$E(Zl,"pathname",Xl("getPathname","setPathname")),$E(Zl,"search",Xl("getSearch","setSearch")),$E(Zl,"searchParams",Xl("getSearchParams")),$E(Zl,"hash",Xl("getHash","setHash"))),kw(Zl,"toJSON",function(){return Lw(this).serialize()},{enumerable:!0}),kw(Zl,"toString",function(){return Lw(this).serialize()},{enumerable:!0}),Lf){var sx=Lf.createObjectURL,Xw=Lf.revokeObjectURL;sx&&kw(Kh,"createObjectURL",WP(sx,Lf)),Xw&&kw(Kh,"revokeObjectURL",WP(Xw,Lf))}IK(Kh,"URL"),gK({global:!0,constructor:!0,forced:!jP,sham:!ob},{URL:Kh});var rx=eA;Us({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return rx(URL.prototype.toString,this)}});let ax=!0,$w=!0;function HS(A,t,o){const a=A.match(t);return a&&a.length>=o&&parseFloat(a[o],10)}function WB(A,t,o){if(!A.RTCPeerConnection)return;const a=A.RTCPeerConnection.prototype,l=a.addEventListener;a.addEventListener=function(h,y){if(h!==t)return l.apply(this,arguments);const S=L=>{const V=o(L);V&&(y.handleEvent?y.handleEvent(V):y(V))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(y,S),l.apply(this,[h,S])};const d=a.removeEventListener;a.removeEventListener=function(h,y){if(h!==t||!this._eventMap||!this._eventMap[t])return d.apply(this,arguments);if(!this._eventMap[t].has(y))return d.apply(this,arguments);const S=this._eventMap[t].get(y);return this._eventMap[t].delete(y),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,d.apply(this,[h,S])},Object.defineProperty(a,"on"+t,{get(){return this["_on"+t]},set(h){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),h&&this.addEventListener(t,this["_on"+t]=h)},enumerable:!0,configurable:!0})}function gx(A){return typeof A!="boolean"?new Error("Argument type: "+typeof A+". Please use a boolean."):(ax=A,A?"adapter.js logging disabled":"adapter.js logging enabled")}function DK(A){return typeof A!="boolean"?new Error("Argument type: "+typeof A+". Please use a boolean."):($w=!A,"adapter.js deprecation warnings "+(A?"disabled":"enabled"))}function A0(){if(typeof window=="object"){if(ax)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function JS(A,t){$w&&console.warn(A+" is deprecated, please use "+t+" instead.")}function hb(A){return Object.prototype.toString.call(A)==="[object Object]"}function Bb(A){return hb(A)?Object.keys(A).reduce(function(t,o){const a=hb(A[o]),l=a?Bb(A[o]):A[o],d=a&&!Object.keys(l).length;return l===void 0||d?t:Object.assign(t,{[o]:l})},{}):A}function Qb(A,t,o){t&&!o.has(t.id)&&(o.set(t.id,t),Object.keys(t).forEach(a=>{a.endsWith("Id")?Qb(A,A.get(t[a]),o):a.endsWith("Ids")&&t[a].forEach(l=>{Qb(A,A.get(l),o)})}))}function cx(A,t,o){const a=o?"outbound-rtp":"inbound-rtp",l=new Map;if(t===null)return l;const d=[];return A.forEach(h=>{h.type==="track"&&h.trackIdentifier===t.id&&d.push(h)}),d.forEach(h=>{A.forEach(y=>{y.type===a&&y.trackId===h.id&&Qb(A,y,l)})}),l}const pb=A0;function lx(A,t){const o=A&&A.navigator;if(!o.mediaDevices)return;const a=function(h){if(typeof h!="object"||h.mandatory||h.optional)return h;const y={};return Object.keys(h).forEach(S=>{if(S==="require"||S==="advanced"||S==="mediaSource")return;const L=typeof h[S]=="object"?h[S]:{ideal:h[S]};L.exact!==void 0&&typeof L.exact=="number"&&(L.min=L.max=L.exact);const V=function(H,lA){return H?H+lA.charAt(0).toUpperCase()+lA.slice(1):lA==="deviceId"?"sourceId":lA};if(L.ideal!==void 0){y.optional=y.optional||[];let H={};typeof L.ideal=="number"?(H[V("min",S)]=L.ideal,y.optional.push(H),H={},H[V("max",S)]=L.ideal,y.optional.push(H)):(H[V("",S)]=L.ideal,y.optional.push(H))}L.exact!==void 0&&typeof L.exact!="number"?(y.mandatory=y.mandatory||{},y.mandatory[V("",S)]=L.exact):["min","max"].forEach(H=>{L[H]!==void 0&&(y.mandatory=y.mandatory||{},y.mandatory[V(H,S)]=L[H])})}),h.advanced&&(y.optional=(y.optional||[]).concat(h.advanced)),y},l=function(h,y){if(t.version>=61)return y(h);if((h=JSON.parse(JSON.stringify(h)))&&typeof h.audio=="object"){const S=function(L,V,H){V in L&&!(H in L)&&(L[H]=L[V],delete L[V])};S((h=JSON.parse(JSON.stringify(h))).audio,"autoGainControl","googAutoGainControl"),S(h.audio,"noiseSuppression","googNoiseSuppression"),h.audio=a(h.audio)}if(h&&typeof h.video=="object"){let S=h.video.facingMode;S=S&&(typeof S=="object"?S:{ideal:S});const L=t.version<66;if(S&&(S.exact==="user"||S.exact==="environment"||S.ideal==="user"||S.ideal==="environment")&&(!o.mediaDevices.getSupportedConstraints||!o.mediaDevices.getSupportedConstraints().facingMode||L)){let V;if(delete h.video.facingMode,S.exact==="environment"||S.ideal==="environment"?V=["back","rear"]:S.exact!=="user"&&S.ideal!=="user"||(V=["front"]),V)return o.mediaDevices.enumerateDevices().then(H=>{H=H.filter(hA=>hA.kind==="videoinput");let lA=H.find(hA=>V.some(MA=>hA.label.toLowerCase().includes(MA)));return!lA&&H.length&&V.includes("back")&&(lA=H[H.length-1]),lA&&(h.video.deviceId=S.exact?{exact:lA.deviceId}:{ideal:lA.deviceId}),h.video=a(h.video),pb("chrome: "+JSON.stringify(h)),y(h)})}h.video=a(h.video)}return pb("chrome: "+JSON.stringify(h)),y(h)},d=function(h){return t.version>=64?h:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[h.name]||h.name,message:h.message,constraint:h.constraint||h.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(o.getUserMedia=function(h,y,S){l(h,L=>{o.webkitGetUserMedia(L,y,V=>{S&&S(d(V))})})}.bind(o),o.mediaDevices.getUserMedia){const h=o.mediaDevices.getUserMedia.bind(o.mediaDevices);o.mediaDevices.getUserMedia=function(y){return l(y,S=>h(S).then(L=>{if(S.audio&&!L.getAudioTracks().length||S.video&&!L.getVideoTracks().length)throw L.getTracks().forEach(V=>{V.stop()}),new DOMException("","NotFoundError");return L},L=>Promise.reject(d(L))))}}}function Ix(A){A.MediaStream=A.MediaStream||A.webkitMediaStream}function ux(A){if(typeof A=="object"&&A.RTCPeerConnection&&!("ontrack"in A.RTCPeerConnection.prototype)){Object.defineProperty(A.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(o){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=o)},enumerable:!0,configurable:!0});const t=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=o=>{o.stream.addEventListener("addtrack",a=>{let l;l=A.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(h=>h.track&&h.track.id===a.track.id):{track:a.track};const d=new Event("track");d.track=a.track,d.receiver=l,d.transceiver={receiver:l},d.streams=[o.stream],this.dispatchEvent(d)}),o.stream.getTracks().forEach(a=>{let l;l=A.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(h=>h.track&&h.track.id===a.id):{track:a};const d=new Event("track");d.track=a,d.receiver=l,d.transceiver={receiver:l},d.streams=[o.stream],this.dispatchEvent(d)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else WB(A,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function mb(A){if(typeof A=="object"&&A.RTCPeerConnection&&!("getSenders"in A.RTCPeerConnection.prototype)&&"createDTMFSender"in A.RTCPeerConnection.prototype){const t=function(l,d){return{track:d,get dtmf(){return this._dtmf===void 0&&(d.kind==="audio"?this._dtmf=l.createDTMFSender(d):this._dtmf=null),this._dtmf},_pc:l}};if(!A.RTCPeerConnection.prototype.getSenders){A.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const l=A.RTCPeerConnection.prototype.addTrack;A.RTCPeerConnection.prototype.addTrack=function(h,y){let S=l.apply(this,arguments);return S||(S=t(this,h),this._senders.push(S)),S};const d=A.RTCPeerConnection.prototype.removeTrack;A.RTCPeerConnection.prototype.removeTrack=function(h){d.apply(this,arguments);const y=this._senders.indexOf(h);y!==-1&&this._senders.splice(y,1)}}const o=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(l){this._senders=this._senders||[],o.apply(this,[l]),l.getTracks().forEach(d=>{this._senders.push(t(this,d))})};const a=A.RTCPeerConnection.prototype.removeStream;A.RTCPeerConnection.prototype.removeStream=function(l){this._senders=this._senders||[],a.apply(this,[l]),l.getTracks().forEach(d=>{const h=this._senders.find(y=>y.track===d);h&&this._senders.splice(this._senders.indexOf(h),1)})}}else if(typeof A=="object"&&A.RTCPeerConnection&&"getSenders"in A.RTCPeerConnection.prototype&&"createDTMFSender"in A.RTCPeerConnection.prototype&&A.RTCRtpSender&&!("dtmf"in A.RTCRtpSender.prototype)){const t=A.RTCPeerConnection.prototype.getSenders;A.RTCPeerConnection.prototype.getSenders=function(){const o=t.apply(this,[]);return o.forEach(a=>a._pc=this),o},Object.defineProperty(A.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function Ex(A){if(!A.RTCPeerConnection)return;const t=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){const[o,a,l]=arguments;if(arguments.length>0&&typeof o=="function")return t.apply(this,arguments);if(t.length===0&&(arguments.length===0||typeof o!="function"))return t.apply(this,[]);const d=function(y){const S={};return y.result().forEach(L=>{const V={id:L.id,timestamp:L.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[L.type]||L.type};L.names().forEach(H=>{V[H]=L.stat(H)}),S[V.id]=V}),S},h=function(y){return new Map(Object.keys(y).map(S=>[S,y[S]]))};if(arguments.length>=2){const y=function(S){a(h(d(S)))};return t.apply(this,[y,o])}return new Promise((y,S)=>{t.apply(this,[function(L){y(h(d(L)))},S])}).then(a,l)}}function fb(A){if(!(typeof A=="object"&&A.RTCPeerConnection&&A.RTCRtpSender&&A.RTCRtpReceiver))return;if(!("getStats"in A.RTCRtpSender.prototype)){const o=A.RTCPeerConnection.prototype.getSenders;o&&(A.RTCPeerConnection.prototype.getSenders=function(){const l=o.apply(this,[]);return l.forEach(d=>d._pc=this),l});const a=A.RTCPeerConnection.prototype.addTrack;a&&(A.RTCPeerConnection.prototype.addTrack=function(){const l=a.apply(this,arguments);return l._pc=this,l}),A.RTCRtpSender.prototype.getStats=function(){const l=this;return this._pc.getStats().then(d=>cx(d,l.track,!0))}}if(!("getStats"in A.RTCRtpReceiver.prototype)){const o=A.RTCPeerConnection.prototype.getReceivers;o&&(A.RTCPeerConnection.prototype.getReceivers=function(){const a=o.apply(this,[]);return a.forEach(l=>l._pc=this),a}),WB(A,"track",a=>(a.receiver._pc=a.srcElement,a)),A.RTCRtpReceiver.prototype.getStats=function(){const a=this;return this._pc.getStats().then(l=>cx(l,a.track,!1))}}if(!("getStats"in A.RTCRtpSender.prototype)||!("getStats"in A.RTCRtpReceiver.prototype))return;const t=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof A.MediaStreamTrack){const o=arguments[0];let a,l,d;return this.getSenders().forEach(h=>{h.track===o&&(a?d=!0:a=h)}),this.getReceivers().forEach(h=>(h.track===o&&(l?d=!0:l=h),h.track===o)),d||a&&l?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):a?a.getStats():l?l.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function dx(A){A.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(d=>this._shimmedLocalStreams[d][0])};const t=A.RTCPeerConnection.prototype.addTrack;A.RTCPeerConnection.prototype.addTrack=function(d,h){if(!h)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const y=t.apply(this,arguments);return this._shimmedLocalStreams[h.id]?this._shimmedLocalStreams[h.id].indexOf(y)===-1&&this._shimmedLocalStreams[h.id].push(y):this._shimmedLocalStreams[h.id]=[h,y],y};const o=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(d){this._shimmedLocalStreams=this._shimmedLocalStreams||{},d.getTracks().forEach(S=>{if(this.getSenders().find(L=>L.track===S))throw new DOMException("Track already exists.","InvalidAccessError")});const h=this.getSenders();o.apply(this,arguments);const y=this.getSenders().filter(S=>h.indexOf(S)===-1);this._shimmedLocalStreams[d.id]=[d].concat(y)};const a=A.RTCPeerConnection.prototype.removeStream;A.RTCPeerConnection.prototype.removeStream=function(d){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[d.id],a.apply(this,arguments)};const l=A.RTCPeerConnection.prototype.removeTrack;A.RTCPeerConnection.prototype.removeTrack=function(d){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},d&&Object.keys(this._shimmedLocalStreams).forEach(h=>{const y=this._shimmedLocalStreams[h].indexOf(d);y!==-1&&this._shimmedLocalStreams[h].splice(y,1),this._shimmedLocalStreams[h].length===1&&delete this._shimmedLocalStreams[h]}),l.apply(this,arguments)}}function Cx(A,t){if(!A.RTCPeerConnection)return;if(A.RTCPeerConnection.prototype.addTrack&&t.version>=65)return dx(A);const o=A.RTCPeerConnection.prototype.getLocalStreams;A.RTCPeerConnection.prototype.getLocalStreams=function(){const S=o.apply(this);return this._reverseStreams=this._reverseStreams||{},S.map(L=>this._reverseStreams[L.id])};const a=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(S){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},S.getTracks().forEach(L=>{if(this.getSenders().find(V=>V.track===L))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[S.id]){const L=new A.MediaStream(S.getTracks());this._streams[S.id]=L,this._reverseStreams[L.id]=S,S=L}a.apply(this,[S])};const l=A.RTCPeerConnection.prototype.removeStream;function d(S,L){let V=L.sdp;return Object.keys(S._reverseStreams||[]).forEach(H=>{const lA=S._reverseStreams[H],hA=S._streams[lA.id];V=V.replace(new RegExp(hA.id,"g"),lA.id)}),new RTCSessionDescription({type:L.type,sdp:V})}A.RTCPeerConnection.prototype.removeStream=function(S){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.apply(this,[this._streams[S.id]||S]),delete this._reverseStreams[this._streams[S.id]?this._streams[S.id].id:S.id],delete this._streams[S.id]},A.RTCPeerConnection.prototype.addTrack=function(S,L){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const V=[].slice.call(arguments,1);if(V.length!==1||!V[0].getTracks().find(lA=>lA===S))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(lA=>lA.track===S))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const H=this._streams[L.id];if(H)H.addTrack(S),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const lA=new A.MediaStream([S]);this._streams[L.id]=lA,this._reverseStreams[lA.id]=L,this.addStream(lA)}return this.getSenders().find(lA=>lA.track===S)},["createOffer","createAnswer"].forEach(function(S){const L=A.RTCPeerConnection.prototype[S],V={[S](){const H=arguments;return arguments.length&&typeof arguments[0]=="function"?L.apply(this,[lA=>{const hA=d(this,lA);H[0].apply(null,[hA])},lA=>{H[1]&&H[1].apply(null,lA)},arguments[2]]):L.apply(this,arguments).then(lA=>d(this,lA))}};A.RTCPeerConnection.prototype[S]=V[S]});const h=A.RTCPeerConnection.prototype.setLocalDescription;A.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(S,L){let V=L.sdp;return Object.keys(S._reverseStreams||[]).forEach(H=>{const lA=S._reverseStreams[H],hA=S._streams[lA.id];V=V.replace(new RegExp(lA.id,"g"),hA.id)}),new RTCSessionDescription({type:L.type,sdp:V})}(this,arguments[0]),h.apply(this,arguments)):h.apply(this,arguments)};const y=Object.getOwnPropertyDescriptor(A.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(A.RTCPeerConnection.prototype,"localDescription",{get(){const S=y.get.apply(this);return S.type===""?S:d(this,S)}}),A.RTCPeerConnection.prototype.removeTrack=function(S){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!S._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(S._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let L;this._streams=this._streams||{},Object.keys(this._streams).forEach(V=>{this._streams[V].getTracks().find(H=>S.track===H)&&(L=this._streams[V])}),L&&(L.getTracks().length===1?this.removeStream(this._reverseStreams[L.id]):L.removeTrack(S.track),this.dispatchEvent(new Event("negotiationneeded")))}}function qS(A,t){!A.RTCPeerConnection&&A.webkitRTCPeerConnection&&(A.RTCPeerConnection=A.webkitRTCPeerConnection),A.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(o){const a=A.RTCPeerConnection.prototype[o],l={[o](){return arguments[0]=new(o==="addIceCandidate"?A.RTCIceCandidate:A.RTCSessionDescription)(arguments[0]),a.apply(this,arguments)}};A.RTCPeerConnection.prototype[o]=l[o]})}function hx(A,t){WB(A,"negotiationneeded",o=>{const a=o.target;if(!(t.version<72||a.getConfiguration&&a.getConfiguration().sdpSemantics==="plan-b")||a.signalingState==="stable")return o})}var yb=Object.freeze({__proto__:null,shimMediaStream:Ix,shimOnTrack:ux,shimGetSendersWithDtmf:mb,shimGetStats:Ex,shimSenderReceiverGetStats:fb,shimAddTrackRemoveTrackWithNative:dx,shimAddTrackRemoveTrack:Cx,shimPeerConnection:qS,fixNegotiationNeeded:hx,shimGetUserMedia:lx,shimGetDisplayMedia:function(A,t){A.navigator.mediaDevices&&"getDisplayMedia"in A.navigator.mediaDevices||A.navigator.mediaDevices&&(typeof t=="function"?A.navigator.mediaDevices.getDisplayMedia=function(o){return t(o).then(a=>{const l=o.video&&o.video.width,d=o.video&&o.video.height,h=o.video&&o.video.frameRate;return o.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:a,maxFrameRate:h||3}},l&&(o.video.mandatory.maxWidth=l),d&&(o.video.mandatory.maxHeight=d),A.navigator.mediaDevices.getUserMedia(o)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function Bx(A,t){const o=A&&A.navigator,a=A&&A.MediaStreamTrack;if(o.getUserMedia=function(l,d,h){JS("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),o.mediaDevices.getUserMedia(l).then(d,h)},!(t.version>55&&"autoGainControl"in o.mediaDevices.getSupportedConstraints())){const l=function(h,y,S){y in h&&!(S in h)&&(h[S]=h[y],delete h[y])},d=o.mediaDevices.getUserMedia.bind(o.mediaDevices);if(o.mediaDevices.getUserMedia=function(h){return typeof h=="object"&&typeof h.audio=="object"&&(h=JSON.parse(JSON.stringify(h)),l(h.audio,"autoGainControl","mozAutoGainControl"),l(h.audio,"noiseSuppression","mozNoiseSuppression")),d(h)},a&&a.prototype.getSettings){const h=a.prototype.getSettings;a.prototype.getSettings=function(){const y=h.apply(this,arguments);return l(y,"mozAutoGainControl","autoGainControl"),l(y,"mozNoiseSuppression","noiseSuppression"),y}}if(a&&a.prototype.applyConstraints){const h=a.prototype.applyConstraints;a.prototype.applyConstraints=function(y){return this.kind==="audio"&&typeof y=="object"&&(y=JSON.parse(JSON.stringify(y)),l(y,"autoGainControl","mozAutoGainControl"),l(y,"noiseSuppression","mozNoiseSuppression")),h.apply(this,[y])}}}}function Qx(A){typeof A=="object"&&A.RTCTrackEvent&&"receiver"in A.RTCTrackEvent.prototype&&!("transceiver"in A.RTCTrackEvent.prototype)&&Object.defineProperty(A.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function e0(A,t){if(typeof A!="object"||!A.RTCPeerConnection&&!A.mozRTCPeerConnection)return;!A.RTCPeerConnection&&A.mozRTCPeerConnection&&(A.RTCPeerConnection=A.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(l){const d=A.RTCPeerConnection.prototype[l],h={[l](){return arguments[0]=new(l==="addIceCandidate"?A.RTCIceCandidate:A.RTCSessionDescription)(arguments[0]),d.apply(this,arguments)}};A.RTCPeerConnection.prototype[l]=h[l]});const o={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},a=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){const[l,d,h]=arguments;return a.apply(this,[l||null]).then(y=>{if(t.version<53&&!d)try{y.forEach(S=>{S.type=o[S.type]||S.type})}catch(S){if(S.name!=="TypeError")throw S;y.forEach((L,V)=>{y.set(V,Object.assign({},L,{type:o[L.type]||L.type}))})}return y}).then(d,h)}}function px(A){if(typeof A!="object"||!A.RTCPeerConnection||!A.RTCRtpSender||A.RTCRtpSender&&"getStats"in A.RTCRtpSender.prototype)return;const t=A.RTCPeerConnection.prototype.getSenders;t&&(A.RTCPeerConnection.prototype.getSenders=function(){const a=t.apply(this,[]);return a.forEach(l=>l._pc=this),a});const o=A.RTCPeerConnection.prototype.addTrack;o&&(A.RTCPeerConnection.prototype.addTrack=function(){const a=o.apply(this,arguments);return a._pc=this,a}),A.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Db(A){if(typeof A!="object"||!A.RTCPeerConnection||!A.RTCRtpSender||A.RTCRtpSender&&"getStats"in A.RTCRtpReceiver.prototype)return;const t=A.RTCPeerConnection.prototype.getReceivers;t&&(A.RTCPeerConnection.prototype.getReceivers=function(){const o=t.apply(this,[]);return o.forEach(a=>a._pc=this),o}),WB(A,"track",o=>(o.receiver._pc=o.srcElement,o)),A.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function mx(A){A.RTCPeerConnection&&!("removeStream"in A.RTCPeerConnection.prototype)&&(A.RTCPeerConnection.prototype.removeStream=function(t){JS("removeStream","removeTrack"),this.getSenders().forEach(o=>{o.track&&t.getTracks().includes(o.track)&&this.removeTrack(o)})})}function Sb(A){A.DataChannel&&!A.RTCDataChannel&&(A.RTCDataChannel=A.DataChannel)}function fx(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const t=A.RTCPeerConnection.prototype.addTransceiver;t&&(A.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let o=arguments[1]&&arguments[1].sendEncodings;o===void 0&&(o=[]),o=[...o];const a=o.length>0;a&&o.forEach(d=>{if("rid"in d&&!/^[a-z0-9]{0,16}$/i.test(d.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in d&&!(parseFloat(d.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in d&&!(parseFloat(d.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const l=t.apply(this,arguments);if(a){const{sender:d}=l,h=d.getParameters();(!("encodings"in h)||h.encodings.length===1&&Object.keys(h.encodings[0]).length===0)&&(h.encodings=o,d.sendEncodings=o,this.setParametersPromises.push(d.setParameters(h).then(()=>{delete d.sendEncodings}).catch(()=>{delete d.sendEncodings})))}return l})}function yx(A){if(typeof A!="object"||!A.RTCRtpSender)return;const t=A.RTCRtpSender.prototype.getParameters;t&&(A.RTCRtpSender.prototype.getParameters=function(){const o=t.apply(this,arguments);return"encodings"in o||(o.encodings=[].concat(this.sendEncodings||[{}])),o})}function Dx(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const t=A.RTCPeerConnection.prototype.createOffer;A.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function Sx(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const t=A.RTCPeerConnection.prototype.createAnswer;A.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var vx=Object.freeze({__proto__:null,shimOnTrack:Qx,shimPeerConnection:e0,shimSenderGetStats:px,shimReceiverGetStats:Db,shimRemoveStream:mx,shimRTCDataChannel:Sb,shimAddTransceiver:fx,shimGetParameters:yx,shimCreateOffer:Dx,shimCreateAnswer:Sx,shimGetUserMedia:Bx,shimGetDisplayMedia:function(A,t){A.navigator.mediaDevices&&"getDisplayMedia"in A.navigator.mediaDevices||A.navigator.mediaDevices&&(A.navigator.mediaDevices.getDisplayMedia=function(o){if(!o||!o.video){const a=new DOMException("getDisplayMedia without video constraints is undefined");return a.name="NotFoundError",a.code=8,Promise.reject(a)}return o.video===!0?o.video={mediaSource:t}:o.video.mediaSource=t,A.navigator.mediaDevices.getUserMedia(o)})}});function Mx(A){if(typeof A=="object"&&A.RTCPeerConnection){if("getLocalStreams"in A.RTCPeerConnection.prototype||(A.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in A.RTCPeerConnection.prototype)){const t=A.RTCPeerConnection.prototype.addTrack;A.RTCPeerConnection.prototype.addStream=function(o){this._localStreams||(this._localStreams=[]),this._localStreams.includes(o)||this._localStreams.push(o),o.getAudioTracks().forEach(a=>t.call(this,a,o)),o.getVideoTracks().forEach(a=>t.call(this,a,o))},A.RTCPeerConnection.prototype.addTrack=function(o,...a){return a&&a.forEach(l=>{this._localStreams?this._localStreams.includes(l)||this._localStreams.push(l):this._localStreams=[l]}),t.apply(this,arguments)}}"removeStream"in A.RTCPeerConnection.prototype||(A.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const o=this._localStreams.indexOf(t);if(o===-1)return;this._localStreams.splice(o,1);const a=t.getTracks();this.getSenders().forEach(l=>{a.includes(l.track)&&this.removeTrack(l)})})}}function Rx(A){if(typeof A=="object"&&A.RTCPeerConnection&&("getRemoteStreams"in A.RTCPeerConnection.prototype||(A.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in A.RTCPeerConnection.prototype))){Object.defineProperty(A.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(o){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=o),this.addEventListener("track",this._onaddstreampoly=a=>{a.streams.forEach(l=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(l))return;this._remoteStreams.push(l);const d=new Event("addstream");d.stream=l,this.dispatchEvent(d)})})}});const t=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(){const o=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(a){a.streams.forEach(l=>{if(o._remoteStreams||(o._remoteStreams=[]),o._remoteStreams.indexOf(l)>=0)return;o._remoteStreams.push(l);const d=new Event("addstream");d.stream=l,o.dispatchEvent(d)})}),t.apply(o,arguments)}}}function vb(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const t=A.RTCPeerConnection.prototype,o=t.createOffer,a=t.createAnswer,l=t.setLocalDescription,d=t.setRemoteDescription,h=t.addIceCandidate;t.createOffer=function(S,L){const V=arguments.length>=2?arguments[2]:arguments[0],H=o.apply(this,[V]);return L?(H.then(S,L),Promise.resolve()):H},t.createAnswer=function(S,L){const V=arguments.length>=2?arguments[2]:arguments[0],H=a.apply(this,[V]);return L?(H.then(S,L),Promise.resolve()):H};let y=function(S,L,V){const H=l.apply(this,[S]);return V?(H.then(L,V),Promise.resolve()):H};t.setLocalDescription=y,y=function(S,L,V){const H=d.apply(this,[S]);return V?(H.then(L,V),Promise.resolve()):H},t.setRemoteDescription=y,y=function(S,L,V){const H=h.apply(this,[S]);return V?(H.then(L,V),Promise.resolve()):H},t.addIceCandidate=y}function Mb(A){const t=A&&A.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const o=t.mediaDevices,a=o.getUserMedia.bind(o);t.mediaDevices.getUserMedia=l=>a(_x(l))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(o,a,l){t.mediaDevices.getUserMedia(o).then(a,l)}.bind(t))}function _x(A){return A&&A.video!==void 0?Object.assign({},A,{video:Bb(A.video)}):A}function Tx(A){if(!A.RTCPeerConnection)return;const t=A.RTCPeerConnection;A.RTCPeerConnection=function(o,a){if(o&&o.iceServers){const l=[];for(let d=0;dt.generateCertificate})}function Nx(A){typeof A=="object"&&A.RTCTrackEvent&&"receiver"in A.RTCTrackEvent.prototype&&!("transceiver"in A.RTCTrackEvent.prototype)&&Object.defineProperty(A.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function t0(A){const t=A.RTCPeerConnection.prototype.createOffer;A.RTCPeerConnection.prototype.createOffer=function(o){if(o){o.offerToReceiveAudio!==void 0&&(o.offerToReceiveAudio=!!o.offerToReceiveAudio);const a=this.getTransceivers().find(d=>d.receiver.track.kind==="audio");o.offerToReceiveAudio===!1&&a?a.direction==="sendrecv"?a.setDirection?a.setDirection("sendonly"):a.direction="sendonly":a.direction==="recvonly"&&(a.setDirection?a.setDirection("inactive"):a.direction="inactive"):o.offerToReceiveAudio!==!0||a||this.addTransceiver("audio",{direction:"recvonly"}),o.offerToReceiveVideo!==void 0&&(o.offerToReceiveVideo=!!o.offerToReceiveVideo);const l=this.getTransceivers().find(d=>d.receiver.track.kind==="video");o.offerToReceiveVideo===!1&&l?l.direction==="sendrecv"?l.setDirection?l.setDirection("sendonly"):l.direction="sendonly":l.direction==="recvonly"&&(l.setDirection?l.setDirection("inactive"):l.direction="inactive"):o.offerToReceiveVideo!==!0||l||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function Gx(A){typeof A!="object"||A.AudioContext||(A.AudioContext=A.webkitAudioContext)}var bx=Object.freeze({__proto__:null,shimLocalStreamsAPI:Mx,shimRemoteStreamsAPI:Rx,shimCallbacksAPI:vb,shimGetUserMedia:Mb,shimConstraints:_x,shimRTCIceServerUrls:Tx,shimTrackEventTransceiver:Nx,shimCreateOfferLegacy:t0,shimAudioContext:Gx}),kx={exports:{}};(function(A){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(o){return o.trim().split(` `).map(a=>a.trim())},t.splitSections=function(o){return o.split(` m=`).map((a,l)=>(l>0?"m="+a:a).trim()+`\r `)},t.getDescription=function(o){const a=t.splitSections(o);return a&&a[0]},t.getMediaSections=function(o){const a=t.splitSections(o);return a.shift(),a},t.matchPrefix=function(o,a){return t.splitLines(o).filter(l=>l.indexOf(a)===0)},t.parseCandidate=function(o){let a;a=o.indexOf("a=candidate:")===0?o.substring(12).split(" "):o.substring(10).split(" ");const l={foundation:a[0],component:{1:"rtp",2:"rtcp"}[a[1]]||a[1],protocol:a[2].toLowerCase(),priority:parseInt(a[3],10),ip:a[4],address:a[4],port:parseInt(a[5],10),type:a[7]};for(let d=8;d(o.candidate&&Object.defineProperty(o,"candidate",{value:new A.RTCIceCandidate(o.candidate),writable:"false"}),o))}function Rb(A){!A.RTCIceCandidate||A.RTCIceCandidate&&"relayProtocol"in A.RTCIceCandidate.prototype||WB(A,"icecandidate",t=>{if(t.candidate){const o=qd.parseCandidate(t.candidate.candidate);o.type==="relay"&&(t.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[o.priority>>24])}return t})}function KS(A,t){if(!A.RTCPeerConnection)return;"sctp"in A.RTCPeerConnection.prototype||Object.defineProperty(A.RTCPeerConnection.prototype,"sctp",{get(){return this._sctp===void 0?null:this._sctp}});const o=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,t.browser==="chrome"&&t.version>=76){const{sdpSemantics:a}=this.getConfiguration();a==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(function(a){if(!a||!a.sdp)return!1;const l=qd.splitSections(a.sdp);return l.shift(),l.some(d=>{const h=qd.parseMLine(d);return h&&h.kind==="application"&&h.protocol.indexOf("SCTP")!==-1})}(arguments[0])){const a=function(S){const L=S.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(L===null||L.length<2)return-1;const V=parseInt(L[1],10);return V!=V?-1:V}(arguments[0]),l=function(S){let L=65536;return t.browser==="firefox"&&(L=t.version<57?S===-1?16384:2147483637:t.version<60?t.version===57?65535:65536:2147483637),L}(a),d=function(S,L){let V=65536;t.browser==="firefox"&&t.version===57&&(V=65535);const H=qd.matchPrefix(S.sdp,"a=max-message-size:");return H.length>0?V=parseInt(H[0].substring(19),10):t.browser==="firefox"&&L!==-1&&(V=2147483637),V}(arguments[0],a);let h;h=l===0&&d===0?Number.POSITIVE_INFINITY:l===0||d===0?Math.max(l,d):Math.min(l,d);const y={};Object.defineProperty(y,"maxMessageSize",{get:()=>h}),this._sctp=y}return o.apply(this,arguments)}}function o0(A){if(!A.RTCPeerConnection||!("createDataChannel"in A.RTCPeerConnection.prototype))return;function t(a,l){const d=a.send;a.send=function(){const h=arguments[0],y=h.length||h.size||h.byteLength;if(a.readyState==="open"&&l.sctp&&y>l.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+l.sctp.maxMessageSize+" bytes)");return d.apply(a,arguments)}}const o=A.RTCPeerConnection.prototype.createDataChannel;A.RTCPeerConnection.prototype.createDataChannel=function(){const a=o.apply(this,arguments);return t(a,this),a},WB(A,"datachannel",a=>(t(a.channel,a.target),a))}function wb(A){if(!A.RTCPeerConnection||"connectionState"in A.RTCPeerConnection.prototype)return;const t=A.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(o){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),o&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=o)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(o=>{const a=t[o];t[o]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=l=>{const d=l.target;if(d._lastConnectionState!==d.connectionState){d._lastConnectionState=d.connectionState;const h=new Event("connectionstatechange",l);d.dispatchEvent(h)}return l},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),a.apply(this,arguments)}})}function n0(A,t){if(!A.RTCPeerConnection||t.browser==="chrome"&&t.version>=71||t.browser==="safari"&&t._safariVersion>=13.1)return;const o=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(a){if(a&&a.sdp&&a.sdp.indexOf(` a=extmap-allow-mixed`)!==-1){const l=a.sdp.split(` `).filter(d=>d.trim()!=="a=extmap-allow-mixed").join(` -`);A.RTCSessionDescription&&a instanceof A.RTCSessionDescription?arguments[0]=new A.RTCSessionDescription({type:a.type,sdp:l}):a.sdp=l}return o.apply(this,arguments)}}function s0(A,t){if(!A.RTCPeerConnection||!A.RTCPeerConnection.prototype)return;const o=A.RTCPeerConnection.prototype.addIceCandidate;o&&o.length!==0&&(A.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser==="chrome"&&t.version<78||t.browser==="firefox"&&t.version<68||t.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():o.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function r0(A,t){if(!A.RTCPeerConnection||!A.RTCPeerConnection.prototype)return;const o=A.RTCPeerConnection.prototype.setLocalDescription;o&&o.length!==0&&(A.RTCPeerConnection.prototype.setLocalDescription=function(){let a=arguments[0]||{};if(typeof a!="object"||a.type&&a.sdp)return o.apply(this,arguments);if(a={type:a.type,sdp:a.sdp},!a.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":a.type="offer";break;default:a.type="answer"}return a.sdp||a.type!=="offer"&&a.type!=="answer"?o.apply(this,[a]):(a.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(l=>o.apply(this,[l]))})}var SK=Object.freeze({__proto__:null,shimRTCIceCandidate:i0,shimRTCIceCandidateRelayProtocol:Rb,shimMaxMessageSize:KS,shimSendThrowTypeError:o0,shimConnectionState:wb,removeExtmapAllowMixed:n0,shimAddIceCandidateNullOrEmpty:s0,shimParameterlessSetLocalDescription:r0});(function({window:A}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const o=A0,a=function(d){const h={browser:null,version:null};if(d===void 0||!d.navigator||!d.navigator.userAgent)return h.browser="Not a browser.",h;const{navigator:y}=d;if(y.mozGetUserMedia)h.browser="firefox",h.version=parseInt(HS(y.userAgent,/Firefox\/(\d+)\./,1));else if(y.webkitGetUserMedia||d.isSecureContext===!1&&d.webkitRTCPeerConnection)h.browser="chrome",h.version=parseInt(HS(y.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!d.RTCPeerConnection||!y.userAgent.match(/AppleWebKit\/(\d+)\./))return h.browser="Not a supported browser.",h;h.browser="safari",h.version=parseInt(HS(y.userAgent,/AppleWebKit\/(\d+)\./,1)),h.supportsUnifiedPlan=d.RTCRtpTransceiver&&"currentDirection"in d.RTCRtpTransceiver.prototype,h._safariVersion=HS(y.userAgent,/Version\/(\d+(\.?\d+))/,1)}return h}(A),l={browserDetails:a,commonShim:SK,extractVersion:HS,disableLog:gx,disableWarnings:DK,sdp:Ux};switch(a.browser){case"chrome":if(!yb||!qS||!t.shimChrome)return o("Chrome shim is not included in this adapter release."),l;if(a.version===null)return o("Chrome shim can not determine version, not shimming."),l;o("adapter.js shimming chrome."),l.browserShim=yb,s0(A,a),r0(A),lx(A,a),Ix(A),qS(A,a),ux(A),Cx(A,a),mb(A),Ex(A),fb(A),hx(A,a),i0(A),Rb(A),wb(A),KS(A,a),o0(A),n0(A,a);break;case"firefox":if(!vx||!e0||!t.shimFirefox)return o("Firefox shim is not included in this adapter release."),l;o("adapter.js shimming firefox."),l.browserShim=vx,s0(A,a),r0(A),Bx(A,a),e0(A,a),Qx(A),mx(A),px(A),Db(A),Sb(A),fx(A),yx(A),Dx(A),Sx(A),i0(A),wb(A),KS(A,a),o0(A);break;case"safari":if(!bx||!t.shimSafari)return o("Safari shim is not included in this adapter release."),l;o("adapter.js shimming safari."),l.browserShim=bx,s0(A,a),r0(A),Tx(A),t0(A),vb(A),Mx(A),Rx(A),Nx(A),Mb(A),Gx(A),i0(A),Rb(A),KS(A,a),o0(A),n0(A,a);break;default:o("Unsupported browser!")}})({window:typeof window>"u"?void 0:window});var Co,Fx=Object.create,jS=Object.defineProperty,vK=Object.defineProperties,a0=Object.getOwnPropertyDescriptor,WS=Object.getOwnPropertyDescriptors,MK=Object.getOwnPropertyNames,g0=Object.getOwnPropertySymbols,Ox=Object.getPrototypeOf,_b=Object.prototype.hasOwnProperty,Px=Object.prototype.propertyIsEnumerable,xx=Reflect.get,zS=Math.pow,c0=(A,t,o)=>t in A?jS(A,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):A[t]=o,Di=(A,t)=>{for(var o in t||(t={}))_b.call(t,o)&&c0(A,o,t[o]);if(g0)for(var o of g0(t))Px.call(t,o)&&c0(A,o,t[o]);return A},So=(A,t)=>vK(A,WS(t)),Yx=(A,t)=>{var o={};for(var a in A)_b.call(A,a)&&t.indexOf(a)<0&&(o[a]=A[a]);if(A!=null&&g0)for(var a of g0(A))t.indexOf(a)<0&&Px.call(A,a)&&(o[a]=A[a]);return o},jh=(A,t)=>()=>(t||A((t={exports:{}}).exports,t),t.exports),Wh=(A,t)=>{for(var o in t)jS(A,o,{get:t[o],enumerable:!0})},dc=(A,t,o)=>(o=A!=null?Fx(Ox(A)):{},((a,l,d,h)=>{if(l&&typeof l=="object"||typeof l=="function")for(let y of MK(l))!_b.call(a,y)&&y!==d&&jS(a,y,{get:()=>l[y],enumerable:!(h=a0(l,y))||h.enumerable});return a})(!t&&A&&A.__esModule?o:jS(o,"default",{value:A,enumerable:!0}),A)),Qi=(A,t,o,a)=>{for(var l,d=a0(t,o),h=A.length-1;h>=0;h--)(l=A[h])&&(d=l(t,o,d)||d);return d&&jS(t,o,d),d},Y=(A,t,o)=>c0(A,typeof t!="symbol"?t+"":t,o),UI=(A,t,o)=>xx(Ox(A),o,t),XA=(A,t,o)=>new Promise((a,l)=>{var d=S=>{try{y(o.next(S))}catch(L){l(L)}},h=S=>{try{y(o.throw(S))}catch(L){l(L)}},y=S=>S.done?a(S.value):Promise.resolve(S.value).then(d,h);y((o=o.apply(A,t)).next())}),Xl=jh((A,t)=>{var o=Object.prototype.hasOwnProperty,a="~";function l(){}function d(L,V,H){this.fn=L,this.context=V,this.once=H||!1}function h(L,V,H,lA,hA){if(typeof H!="function")throw new TypeError("The listener must be a function");var MA=new d(H,lA||L,hA),oe=a?a+V:V;return L._events[oe]?L._events[oe].fn?L._events[oe]=[L._events[oe],MA]:L._events[oe].push(MA):(L._events[oe]=MA,L._eventsCount++),L}function y(L,V){--L._eventsCount===0?L._events=new l:delete L._events[V]}function S(){this._events=new l,this._eventsCount=0}Object.create&&(l.prototype=Object.create(null),new l().__proto__||(a=!1)),S.prototype.eventNames=function(){var L,V,H=[];if(this._eventsCount===0)return H;for(V in L=this._events)o.call(L,V)&&H.push(a?V.slice(1):V);return Object.getOwnPropertySymbols?H.concat(Object.getOwnPropertySymbols(L)):H},S.prototype.listeners=function(L){var V=a?a+L:L,H=this._events[V];if(!H)return[];if(H.fn)return[H.fn];for(var lA=0,hA=H.length,MA=new Array(hA);lA{var o=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(a){return a.encoding?"rtpmap:%d %s/%s/%s":a.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(a){return a.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(a){return a.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(a){return"extmap:%d"+(a.direction?"/%s":"%v")+(a["encrypt-uri"]?" %s":"%v")+" %s"+(a.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(a){return a.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(a){var l="candidate:%s %d %s %d %s %d typ %s";return l+=a.raddr!=null?" raddr %s rport %d":"%v%v",l+=a.tcptype!=null?" tcptype %s":"%v",a.generation!=null&&(l+=" generation %d"),l+=a["network-id"]!=null?" network-id %d":"%v",l+=a["network-cost"]!=null?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(a){var l="ssrc:%d";return a.attribute!=null&&(l+=" %s",a.value!=null&&(l+=":%s")),l}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(a){return a.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(a){return a.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(a){return"imageattr:%s %s %s"+(a.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(a){return"simulcast:%s %s"+(a.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(a){return"ts-refclk:%s"+(a.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(a){var l="mediaclk:";return l+=a.id!=null?"id=%s %s":"%v%s",l+=a.mediaClockValue!=null?"=%s":"",l+=a.rateNumerator!=null?" rate=%s":"",l+=a.rateDenominator!=null?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(o).forEach(function(a){o[a].forEach(function(l){l.reg||(l.reg=/(.*)/),l.format||(l.format="%s")})})}),Yf=jh(A=>{var t=function(h){return String(Number(h))===h?Number(h):h},o=function(h,y,S){var L=h.name&&h.names;h.push&&!y[h.push]?y[h.push]=[]:L&&!y[h.name]&&(y[h.name]={});var V=h.push?{}:L?y[h.name]:y;(function(H,lA,hA,MA){if(MA&&!hA)lA[MA]=t(H[1]);else for(var oe=0;oe1&&(h[S[0]]=void 0),h};A.parseParams=function(h){return h.split(/;\s?/).reduce(d,{})},A.parseFmtpConfig=A.parseParams,A.parsePayloads=function(h){return h.toString().split(" ").map(Number)},A.parseRemoteCandidates=function(h){for(var y=[],S=h.split(" ").map(t),L=0;L{var o=UC(),a=/%[sdv%]/g,l=function(S){var L=1,V=arguments,H=V.length;return S.replace(a,function(lA){if(L>=H)return lA;var hA=V[L];switch(L+=1,lA){case"%%":return"%";case"%s":return String(hA);case"%d":return Number(hA);case"%v":return""}})},d=function(S,L,V){var H=[S+"="+(L.format instanceof Function?L.format(L.push?V:V[L.name]):L.format)];if(L.names)for(var lA=0;lAo.apply(this,[l]))})}var SK=Object.freeze({__proto__:null,shimRTCIceCandidate:i0,shimRTCIceCandidateRelayProtocol:Rb,shimMaxMessageSize:KS,shimSendThrowTypeError:o0,shimConnectionState:wb,removeExtmapAllowMixed:n0,shimAddIceCandidateNullOrEmpty:s0,shimParameterlessSetLocalDescription:r0});(function({window:A}={},t={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const o=A0,a=function(d){const h={browser:null,version:null};if(d===void 0||!d.navigator||!d.navigator.userAgent)return h.browser="Not a browser.",h;const{navigator:y}=d;if(y.mozGetUserMedia)h.browser="firefox",h.version=parseInt(HS(y.userAgent,/Firefox\/(\d+)\./,1));else if(y.webkitGetUserMedia||d.isSecureContext===!1&&d.webkitRTCPeerConnection)h.browser="chrome",h.version=parseInt(HS(y.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!d.RTCPeerConnection||!y.userAgent.match(/AppleWebKit\/(\d+)\./))return h.browser="Not a supported browser.",h;h.browser="safari",h.version=parseInt(HS(y.userAgent,/AppleWebKit\/(\d+)\./,1)),h.supportsUnifiedPlan=d.RTCRtpTransceiver&&"currentDirection"in d.RTCRtpTransceiver.prototype,h._safariVersion=HS(y.userAgent,/Version\/(\d+(\.?\d+))/,1)}return h}(A),l={browserDetails:a,commonShim:SK,extractVersion:HS,disableLog:gx,disableWarnings:DK,sdp:Ux};switch(a.browser){case"chrome":if(!yb||!qS||!t.shimChrome)return o("Chrome shim is not included in this adapter release."),l;if(a.version===null)return o("Chrome shim can not determine version, not shimming."),l;o("adapter.js shimming chrome."),l.browserShim=yb,s0(A,a),r0(A),lx(A,a),Ix(A),qS(A,a),ux(A),Cx(A,a),mb(A),Ex(A),fb(A),hx(A,a),i0(A),Rb(A),wb(A),KS(A,a),o0(A),n0(A,a);break;case"firefox":if(!vx||!e0||!t.shimFirefox)return o("Firefox shim is not included in this adapter release."),l;o("adapter.js shimming firefox."),l.browserShim=vx,s0(A,a),r0(A),Bx(A,a),e0(A,a),Qx(A),mx(A),px(A),Db(A),Sb(A),fx(A),yx(A),Dx(A),Sx(A),i0(A),wb(A),KS(A,a),o0(A);break;case"safari":if(!bx||!t.shimSafari)return o("Safari shim is not included in this adapter release."),l;o("adapter.js shimming safari."),l.browserShim=bx,s0(A,a),r0(A),Tx(A),t0(A),vb(A),Mx(A),Rx(A),Nx(A),Mb(A),Gx(A),i0(A),Rb(A),KS(A,a),o0(A),n0(A,a);break;default:o("Unsupported browser!")}})({window:typeof window>"u"?void 0:window});var Co,Fx=Object.create,jS=Object.defineProperty,vK=Object.defineProperties,a0=Object.getOwnPropertyDescriptor,WS=Object.getOwnPropertyDescriptors,MK=Object.getOwnPropertyNames,g0=Object.getOwnPropertySymbols,Ox=Object.getPrototypeOf,_b=Object.prototype.hasOwnProperty,Px=Object.prototype.propertyIsEnumerable,xx=Reflect.get,zS=Math.pow,c0=(A,t,o)=>t in A?jS(A,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):A[t]=o,Di=(A,t)=>{for(var o in t||(t={}))_b.call(t,o)&&c0(A,o,t[o]);if(g0)for(var o of g0(t))Px.call(t,o)&&c0(A,o,t[o]);return A},So=(A,t)=>vK(A,WS(t)),Yx=(A,t)=>{var o={};for(var a in A)_b.call(A,a)&&t.indexOf(a)<0&&(o[a]=A[a]);if(A!=null&&g0)for(var a of g0(A))t.indexOf(a)<0&&Px.call(A,a)&&(o[a]=A[a]);return o},jh=(A,t)=>()=>(t||A((t={exports:{}}).exports,t),t.exports),Wh=(A,t)=>{for(var o in t)jS(A,o,{get:t[o],enumerable:!0})},dc=(A,t,o)=>(o=A!=null?Fx(Ox(A)):{},((a,l,d,h)=>{if(l&&typeof l=="object"||typeof l=="function")for(let y of MK(l))!_b.call(a,y)&&y!==d&&jS(a,y,{get:()=>l[y],enumerable:!(h=a0(l,y))||h.enumerable});return a})(!t&&A&&A.__esModule?o:jS(o,"default",{value:A,enumerable:!0}),A)),Qi=(A,t,o,a)=>{for(var l,d=a0(t,o),h=A.length-1;h>=0;h--)(l=A[h])&&(d=l(t,o,d)||d);return d&&jS(t,o,d),d},Y=(A,t,o)=>c0(A,typeof t!="symbol"?t+"":t,o),UI=(A,t,o)=>xx(Ox(A),o,t),XA=(A,t,o)=>new Promise((a,l)=>{var d=S=>{try{y(o.next(S))}catch(L){l(L)}},h=S=>{try{y(o.throw(S))}catch(L){l(L)}},y=S=>S.done?a(S.value):Promise.resolve(S.value).then(d,h);y((o=o.apply(A,t)).next())}),$l=jh((A,t)=>{var o=Object.prototype.hasOwnProperty,a="~";function l(){}function d(L,V,H){this.fn=L,this.context=V,this.once=H||!1}function h(L,V,H,lA,hA){if(typeof H!="function")throw new TypeError("The listener must be a function");var MA=new d(H,lA||L,hA),oe=a?a+V:V;return L._events[oe]?L._events[oe].fn?L._events[oe]=[L._events[oe],MA]:L._events[oe].push(MA):(L._events[oe]=MA,L._eventsCount++),L}function y(L,V){--L._eventsCount===0?L._events=new l:delete L._events[V]}function S(){this._events=new l,this._eventsCount=0}Object.create&&(l.prototype=Object.create(null),new l().__proto__||(a=!1)),S.prototype.eventNames=function(){var L,V,H=[];if(this._eventsCount===0)return H;for(V in L=this._events)o.call(L,V)&&H.push(a?V.slice(1):V);return Object.getOwnPropertySymbols?H.concat(Object.getOwnPropertySymbols(L)):H},S.prototype.listeners=function(L){var V=a?a+L:L,H=this._events[V];if(!H)return[];if(H.fn)return[H.fn];for(var lA=0,hA=H.length,MA=new Array(hA);lA{var o=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(a){return a.encoding?"rtpmap:%d %s/%s/%s":a.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(a){return a.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(a){return a.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(a){return"extmap:%d"+(a.direction?"/%s":"%v")+(a["encrypt-uri"]?" %s":"%v")+" %s"+(a.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(a){return a.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(a){var l="candidate:%s %d %s %d %s %d typ %s";return l+=a.raddr!=null?" raddr %s rport %d":"%v%v",l+=a.tcptype!=null?" tcptype %s":"%v",a.generation!=null&&(l+=" generation %d"),l+=a["network-id"]!=null?" network-id %d":"%v",l+=a["network-cost"]!=null?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(a){var l="ssrc:%d";return a.attribute!=null&&(l+=" %s",a.value!=null&&(l+=":%s")),l}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(a){return a.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(a){return a.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(a){return"imageattr:%s %s %s"+(a.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(a){return"simulcast:%s %s"+(a.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(a){return"ts-refclk:%s"+(a.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(a){var l="mediaclk:";return l+=a.id!=null?"id=%s %s":"%v%s",l+=a.mediaClockValue!=null?"=%s":"",l+=a.rateNumerator!=null?" rate=%s":"",l+=a.rateDenominator!=null?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(o).forEach(function(a){o[a].forEach(function(l){l.reg||(l.reg=/(.*)/),l.format||(l.format="%s")})})}),Yf=jh(A=>{var t=function(h){return String(Number(h))===h?Number(h):h},o=function(h,y,S){var L=h.name&&h.names;h.push&&!y[h.push]?y[h.push]=[]:L&&!y[h.name]&&(y[h.name]={});var V=h.push?{}:L?y[h.name]:y;(function(H,lA,hA,MA){if(MA&&!hA)lA[MA]=t(H[1]);else for(var oe=0;oe1&&(h[S[0]]=void 0),h};A.parseParams=function(h){return h.split(/;\s?/).reduce(d,{})},A.parseFmtpConfig=A.parseParams,A.parsePayloads=function(h){return h.toString().split(" ").map(Number)},A.parseRemoteCandidates=function(h){for(var y=[],S=h.split(" ").map(t),L=0;L{var o=UC(),a=/%[sdv%]/g,l=function(S){var L=1,V=arguments,H=V.length;return S.replace(a,function(lA){if(L>=H)return lA;var hA=V[L];switch(L+=1,lA){case"%%":return"%";case"%s":return String(hA);case"%d":return Number(hA);case"%v":return""}})},d=function(S,L,V){var H=[S+"="+(L.format instanceof Function?L.format(L.push?V:V[L.name]):L.format)];if(L.names)for(var lA=0;lA{var t=Yf(),o=RK(),a=UC();A.grammar=a,A.write=o,A.parse=t.parse,A.parseParams=t.parseParams,A.parseFmtpConfig=t.parseFmtpConfig,A.parsePayloads=t.parsePayloads,A.parseRemoteCandidates=t.parseRemoteCandidates,A.parseImageAttributes=t.parseImageAttributes,A.parseSimulcastStreamList=t.parseSimulcastStreamList}),ZS=jh((A,t)=>{var o=t.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(a){return a.encoding?"rtpmap:%d %s/%s/%s":a.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(a){return a.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(a){return a.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(a){return"extmap:%d"+(a.direction?"/%s":"%v")+(a["encrypt-uri"]?" %s":"%v")+" %s"+(a.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(a){return a.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(a){var l="candidate:%s %d %s %d %s %d typ %s";return l+=a.raddr!=null?" raddr %s rport %d":"%v%v",l+=a.tcptype!=null?" tcptype %s":"%v",a.generation!=null&&(l+=" generation %d"),l+=a["network-id"]!=null?" network-id %d":"%v",l+=a["network-cost"]!=null?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(a){var l="ssrc:%d";return a.attribute!=null&&(l+=" %s",a.value!=null&&(l+=":%s")),l}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(a){return a.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(a){return a.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(a){return"imageattr:%s %s %s"+(a.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(a){return"simulcast:%s %s"+(a.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(a){return"ts-refclk:%s"+(a.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(a){var l="mediaclk:";return l+=a.id!=null?"id=%s %s":"%v%s",l+=a.mediaClockValue!=null?"=%s":"",l+=a.rateNumerator!=null?" rate=%s":"",l+=a.rateDenominator!=null?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(o).forEach(function(a){o[a].forEach(function(l){l.reg||(l.reg=/(.*)/),l.format||(l.format="%s")})})}),Vx=jh(A=>{var t=function(h){return String(Number(h))===h?Number(h):h},o=function(h,y,S){var L=h.name&&h.names;h.push&&!y[h.push]?y[h.push]=[]:L&&!y[h.name]&&(y[h.name]={});var V=h.push?{}:L?y[h.name]:y;(function(H,lA,hA,MA){if(MA&&!hA)lA[MA]=t(H[1]);else for(var oe=0;oe1&&(h[S[0]]=void 0),h};A.parseParams=function(h){return h.split(/;\s?/).reduce(d,{})},A.parseFmtpConfig=A.parseParams,A.parsePayloads=function(h){return h.toString().split(" ").map(Number)},A.parseRemoteCandidates=function(h){for(var y=[],S=h.split(" ").map(t),L=0;L{var o=ZS(),a=/%[sdv%]/g,l=function(S){var L=1,V=arguments,H=V.length;return S.replace(a,function(lA){if(L>=H)return lA;var hA=V[L];switch(L+=1,lA){case"%%":return"%";case"%s":return String(hA);case"%d":return Number(hA);case"%v":return""}})},d=function(S,L,V){var H=[S+"="+(L.format instanceof Function?L.format(L.push?V:V[L.name]):L.format)];if(L.names)for(var lA=0;lA{var t=Vx(),o=Hx();A.write=o,A.parse=t.parse,A.parseParams=t.parseParams,A.parseFmtpConfig=t.parseFmtpConfig,A.parsePayloads=t.parsePayloads,A.parseRemoteCandidates=t.parseRemoteCandidates,A.parseImageAttributes=t.parseImageAttributes,A.parseSimulcastStreamList=t.parseSimulcastStreamList}),_K=dc(Xl()),zB=((Co=zB||{})[Co.INVALID_PARAMETER=4096]="INVALID_PARAMETER",Co[Co.INVALID_OPERATION=4097]="INVALID_OPERATION",Co[Co.NOT_SUPPORTED=4098]="NOT_SUPPORTED",Co[Co.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",Co[Co.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",Co[Co.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",Co[Co.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",Co[Co.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",Co[Co.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",Co[Co.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",Co[Co.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",Co[Co.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",Co[Co.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",Co[Co.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",Co[Co.CLIENT_BANNED=16448]="CLIENT_BANNED",Co[Co.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",Co[Co.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",Co[Co.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",Co[Co.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",Co[Co.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",Co[Co.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",Co[Co.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",Co[Co.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",Co[Co.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",Co[Co.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",Co[Co.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",Co[Co.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",Co[Co.API_CALL_ABORTED=16461]="API_CALL_ABORTED",Co[Co.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",Co[Co.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",Co[Co.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",Co[Co.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",Co[Co.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",Co[Co.UNKNOWN=65535]="UNKNOWN",Co),mt=zB,Jx=class extends Error{constructor(A){let{name:t="RtcError",message:o,code:a=mt.UNKNOWN,extraCode:l=0,constraint:d}=A,h="<".concat(function(S){for(let L in mt)if(mt[L]===S)return L;return"UNKNOWN"}(a)," 0x").concat(a.toString(16),">"),y="".concat(o).concat(d?" constraint: ".concat(d):"").concat(o!=null&&o.includes(h)?"":" ".concat(h));super(y),Y(this,"code"),Y(this,"extraCode"),Y(this,"message"),Y(this,"originMessage"),Y(this,"name"),Y(this,"constraint"),this.code=a,this.extraCode=l,this.name=t,this.message=y,this.constraint=d,this.originMessage=o}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},li=Jx,Nb=0,qx=!0,ZB=function(A){Nb=A;let t=new Date;t.setTime(t.getTime()+A),pA[qx?"info":"debug"]("baseTime from server: ".concat(t," offset: ").concat(A)),qx=!1},Kx=function(){return Nb},Vf=function(){return Date.now()+Nb},jx=function(){let A=new Date;return A.setTime(Vf()),A.toLocaleString()},Gb=function(A){let t=String(A.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),"".concat(A.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(t)},Kd={};Wh(Kd,{REPORT_TYPE:()=>O0,buildSSOPackage:()=>oQ,bytes2ms:()=>N0,calculateScaleResolutionDownNumber:()=>F0,concatArrayBuffers:()=>hv,convertObjectNumberToInt:()=>U0,copyProperties:()=>B2,deepClone:()=>iy,deepCloneBasic:()=>oy,deepMerge:()=>$h,delay:()=>OC,fibonacci:()=>Ay,formatedTime:()=>v2,getConstructorName:()=>Iv,getContainerFromElement:()=>tk,getEnv:()=>d2,getFirst16Bits:()=>R2,getInternalVersion:()=>D2,getLast16Bits:()=>P0,getLoggerUrl:()=>Xf,getMediaStreamTrackInfo:()=>rk,getMuteStateFromFlag:()=>kp,getNetworkType:()=>_0,getNumNetworkType:()=>$f,getReconnectionTimeout:()=>bp,getStringByteLength:()=>L0,getTestSignalDomain:()=>C2,getTurnServer:()=>S2,getUint32Version:()=>ok,getValueType:()=>Qg,getViewListFromView:()=>dv,glog:()=>p2,ipv4ToUint32:()=>Ev,isArray:()=>ka,isAudioWorkletSupported:()=>m2,isBoolean:()=>br,isConstructor:()=>ty,isEmpty:()=>b0,isFunction:()=>ba,isLangChinese:()=>Zd,isMediaStreamTrack:()=>Ak,isNumber:()=>Ys,isObject:()=>ed,isOverseaSdkAppId:()=>zd,isPlainObject:()=>uE,isPortrait:()=>ik,isPromise:()=>ey,isRemoteTrack:()=>ek,isRotate90Or270:()=>iQ,isSetSinkIdSupported:()=>f2,isString:()=>Ws,isUndefined:()=>ze,isVideoMixerOutputTrack:()=>Lp,loadImage:()=>Cv,loadVideo:()=>M2,ms2bytes:()=>Q2,ms2samples:()=>G0,normalizeUrl:()=>sk,performanceNow:()=>Oo,promiseAny:()=>uv,samples2ms:()=>$b,setNetworkTypeFromWebRTC:()=>T0,stringify:()=>Xd,stringifyIncludeValue:()=>k0,throttlePromise:()=>nk});var Wx={};Wh(Wx,{ASR_ROBOT_FROM_TYPE:()=>D0,AUDIO_MUTE_BIT:()=>qf,AUDIO_STAT_BIT:()=>iv,AUX_STAT_BIT:()=>tv,AUX_STREAM_MSID:()=>t2,BACKEND_ENV:()=>Hf,BASE_DOC_URL:()=>zh,BASE_HOST:()=>Zx,CAPABILITIES_KEYS:()=>Jb,CLASS_NAME:()=>OK,CLOUD_CONSOLE_URL:()=>GK,CROSS_ROOM_BIT:()=>Ob,DATA_CHANNEL_FROM_TYPE_BIT:()=>AQ,DATA_FREEZE_TIMING:()=>Vb,DOC_BILLING_CN:()=>E0,DOC_BILLING_OVERSEA:()=>Lb,DOC_URL:()=>bK,DTLS_STATE_UNKNOWN:()=>Zh,ENV_NAME:()=>XB,EXCHANGE_SDP_TIMEOUT:()=>r2,IS_WORKER:()=>I0,IS_WORKLET:()=>u0,KIBANA_EVENT:()=>Wa,LOCAL_STREAM_PUBLISH_STATE:()=>a2,LOGGER_CMD_TYPE:()=>OI,LOGGER_DOMAIN:()=>FI,LOGGER_DOMAIN_OVERSEA:()=>_p,LOG_LEVEL:()=>$B,LOG_LEVEL_NAME:()=>xK,MAIN_STREAM_MSID:()=>hu,MAX_RTT:()=>y0,MICROPHONE_COMMUNICATIONS:()=>PK,MICROPHONE_DEFAULT:()=>sv,MUTE_ALL_BIT:()=>e2,NAME:()=>JA,NETWORK_TYPE:()=>d0,NOT_SUPPORTED_H264:()=>m0,PAUSED_RETRY_COUNT:()=>Gp,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Hb,PEER_CONNECTION_STATE:()=>mo,PEER_LEAVE_REASON:()=>l2,RECOVER_CAPTURE_INTERVAL:()=>av,REMOTE_STREAM_TYPE_AUX:()=>Pb,REMOTE_STREAM_TYPE_MAIN:()=>h0,RENDER_FREEZE_TIMING:()=>g2,SCHEDULE_DOMAIN:()=>tQ,SCHEDULE_TIMEOUT:()=>c2,SDP_SEMANTICS_PLAN_B:()=>p0,SDP_SEMANTICS_UNIFIED_PLAN:()=>nv,SECOND_HOST:()=>Xx,SIGNAL_PING_PONG_INTERVAL:()=>IE,SIGNAL_PING_TIMEOUT:()=>$x,SIGNAL_RECONNECTION_COUNT:()=>kK,SMALL_STAT_BIT:()=>Fb,SPEAKER_DEFAULT:()=>f0,STORAGE_EXPIRES_TIME:()=>C0,STREAM_TYPE_BIG:()=>UK,STREAM_TYPE_SMALL:()=>FK,SUBSCRIBE_SMALL_RETRY_COUNT:()=>rv,SYNC_USER_LIST_INTERVAL:()=>LK,Scene:()=>Jf,THIRD_HOST:()=>NK,TRANSPORT_DIRECTION:()=>ir,TRTC_ERROR_ASSISTANCE:()=>$S,TRTC_QUALITY_BAD:()=>Kf,TRTC_QUALITY_DISCONNECTED:()=>n2,TRTC_QUALITY_EXCELLENT:()=>B0,TRTC_QUALITY_GOOD:()=>eQ,TRTC_QUALITY_POOR:()=>i2,TRTC_QUALITY_UNKNOWN:()=>xb,TRTC_QUALITY_VERY_BAD:()=>o2,UPDATE_OFFER_TIMEOUT:()=>s2,VIDEO_MUTE_BIT:()=>ov,VIDEO_STAT_BIT:()=>ev,WEBGL_ATTRIBUTES:()=>qb,audioProfileMap:()=>Tp,defaultBigVideoProfile:()=>Av,defaultSmallVideoProfile:()=>A2,getRetryCount:()=>jf,getScriptDir:()=>TK,innerVersion:()=>l0,loggerProxy:()=>kb,screenProfileMap:()=>Ub,setLoggerProxy:()=>XS,setRetryCount:()=>Q0,setVersion:()=>zx,version:()=>Wd,videoProfileMap:()=>FC});var l0="4.15.00.1600",Wd="5.0.0";function zx(A){Wd=A;let[t,o,a]=A.split(".").map(l=>parseInt(l,10));l0="".concat(t,".").concat(Math.min(15,o),".").concat(Math.min(15,a),".").concat(o.toString().padStart(2,"0")).concat(a.toString().padStart(2,"0"))}var bb,lE,I0=typeof importScripts<"u",u0=typeof registerProcessor<"u",TK=()=>{let A=I0?self.location.href:document.currentScript.src;return A.substring(0,A.lastIndexOf("/")+1)},kb="",XS=A=>kb=A,Zx="web.sdk.qcloud.com",Xx="web.sdk.tencent.cn",NK="web.sdk.cloud.tencent.cn",GK="https://console.cloud.tencent.com/trtc",zh="https://".concat(Zx,"/trtc/webrtc/doc"),bK="".concat(zh,"/zh-cn/"),E0="https://cloud.tencent.com/document/product/647/85386",Lb="https://trtc.io/document/56025",FI="https://yun.tim.qq.com",_p="https://apisgp.my-imcloud.com",$S="trtc_error_assistance",OI={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},XB={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},$B=((lE=$B||{})[lE.TRACE=0]="TRACE",lE[lE.DEBUG=1]="DEBUG",lE[lE.INFO=2]="INFO",lE[lE.WARN=3]="WARN",lE[lE.ERROR=4]="ERROR",lE[lE.NONE=5]="NONE",lE),$x=18e3,IE=2e3,d0={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},C0=6048e5,Tp={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},FC={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},Av=FC["480p_2"],A2=FC["120p_2"],Ub={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},JA={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADSTART:"loadstart",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",FULLSCREEN_CHANGE:"fullscreenchange",RESIZE:"resize",TIME_UPDATE:"timeupdate"},ir={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Hf={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Jf=((bb=Jf||{}).LIVE="live",bb.RTC="rtc",bb),ev=1,Fb=2,tv=4,iv=8,qf=64,ov=16,e2=112,Ob=128,AQ=256,hu="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",t2="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",h0=JA.MAIN,Pb=JA.AUXILIARY,xb=0,B0=1,eQ=2,i2=3,Kf=4,o2=5,n2=6,Zh="unknown",mo={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Yb=1/0;function Q0(A){Yb=A}function jf(){return Yb}var Np,kK=30,Wa={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",VIDEO_ENCODE_RESUME_DURING_CALL:"video-encode-resume-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call",AUDIO_ENCODE_RESUME_DURING_CALL:"audio-encode-resume-during-call",VIDEO_DECODE_FAILED_DURING_CALL:"video-decode-failed-during-call",VIDEO_DECODE_RESUME_DURING_CALL:"video-decode-resume-during-call",AUDIO_DECODE_FAILED_DURING_CALL:"audio-decode-failed-during-call",AUDIO_DECODE_RESUME_DURING_CALL:"audio-decode-resume-during-call",VIDEO_HARDWARE_DECODE_FAILED:"video-hardware-decode-failed",VIDEO_HARDWARE_DECODE_RESUME:"video-hardware-decode-resume"},LK=1e4,s2=1e4,r2=1e4,nv="unified-plan",p0="plan-b",m0=1028,a2=((Np=a2||{})[Np.UNPUBLISH=-1]="UNPUBLISH",Np[Np.PUBLISHING=0]="PUBLISHING",Np[Np.PUBLISHED=1]="PUBLISHED",Np),Vb=500,g2=1e3,UK=JA.BIG,FK=JA.SMALL,Hb=1e4,tQ={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},c2=2e3,OK={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Gp=5,sv="default",f0=sv,PK="communications",xK=Object.keys($B),l2=["normal leave","timeout leave","kick","role change"],rv=10,av=2e3,Jb=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],y0=1e4,D0=14,qb={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},I2=function(A,t,o,a){return new(o||(o=Promise))(function(l,d){function h(L){try{S(a.next(L))}catch(V){d(V)}}function y(L){try{S(a.throw(L))}catch(V){d(V)}}function S(L){L.done?l(L.value):function(V){return V instanceof o?V:new o(function(H){H(V)})}(L.value).then(h,y)}S((a=a.apply(A,[])).next())})},S0=Symbol(32),v0=Symbol(16),Kb=Symbol(8),Wf=class{constructor(A){this.g=A,this.consumed=0,A&&(this.need=A.next().value)}setG(A){this.g=A,this.demand(A.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(A,t){return t&&this.consume(),this.need=A,this.flush()}read(A){return I2(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((t,o)=>{var a;this.reject=o,this.resolve=l=>{delete this.lastReadPromise,delete this.resolve,delete this.need,t(l)},this.demand(A,!0)||(a=this.pull)===null||a===void 0||a.call(this,A)})})}readU32(){return this.read(S0)}readU16(){return this.read(v0)}readU8(){return this.read(Kb)}close(){var A;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(A=this.reject)===null||A===void 0||A.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let A=null,t=this.buffer.subarray(this.consumed),o=0,a=l=>t.length<(o=l);if(typeof this.need=="number"){if(a(this.need))return;A=t.subarray(0,o)}else if(this.need===S0){if(a(4))return;A=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===v0){if(a(2))return;A=t[0]<<8|t[1]}else if(this.need===Kb){if(a(1))return;A=t[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(a(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(t.subarray(0,o)),A=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(a(this.need.byteLength))return;new Uint8Array(this.need).set(t.subarray(0,o)),A=this.need}return this.consumed+=o,this.g?this.demand(this.g.next(A).value,!0):this.resolve&&this.resolve(A),A}write(A){if(A instanceof Uint8Array?this.malloc(A.length).set(A):"buffer"in A?this.malloc(A.byteLength).set(new Uint8Array(A.buffer,A.byteOffset,A.byteLength)):this.malloc(A.byteLength).set(new Uint8Array(A)),!this.g&&!this.resolve)return new Promise(t=>this.pull=t);this.flush()}writeU32(A){this.malloc(4).set([A>>24&255,A>>16&255,A>>8&255,255&A]),this.flush()}writeU16(A){this.malloc(2).set([A>>8&255,255&A]),this.flush()}writeU8(A){this.malloc(1)[0]=A,this.flush()}malloc(A){if(this.buffer){let t=this.buffer.length,o=t+A;if(o<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,o);else{let a=new Uint8Array(o);a.set(this.buffer),this.buffer=a}return this.buffer.subarray(t,o)}return this.buffer=new Uint8Array(A),this.buffer}};Wf.U32=S0,Wf.U16=v0,Wf.U8=Kb;var gv=128;function M0(A){let t=new Wf;for(;A>=128;)t.malloc(1)[0]=255&A|gv,A>>>=7;return t.malloc(1)[0]=255&A,t.buffer||new Uint8Array(0)}function R0(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=new Wf,a=t<<3;switch(typeof A){case"boolean":let l=o.malloc(2);l[0]=a,l[1]=A?1:0;break;case"number":o.malloc(1)[0]=a,o.write(M0(A));break;case"string":o.malloc(1)[0]=2|a;let d=new TextEncoder().encode(A);o.write(M0(d.length));let h=o.malloc(d.length);for(let S=0;S>>24&255),this.buffer.push(A>>>16&255),this.buffer.push(A>>>8&255),this.buffer.push(255&A)}writeInt16(A){this.buffer.push(A>>>8&255),this.buffer.push(255&A)}writeByte(A){this.buffer.push(255&A)}writeBytes(A){for(let t=0;t>>24&255,A[o+1]=t>>>16&255,A[o+2]=t>>>8&255,A[o+3]=255&t}function Bu(A,t){return A[t]<<24|A[t+1]<<16|A[t+2]<<8|A[t+3]}function E2(A,t){return A[t]}function Zf(A,t,o){return new TextDecoder().decode(function(a,l,d){return a.slice(l,l+d)}(A,t,o))}var cv=0,jb=2654435769,w0=16,Xh=2,lv=7;function Wb(A,t){let o=new u2,a=function(_e,vi,Fe){let Dt=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"AVQualityReportSvc.C2S";return{version:arguments.length>4&&arguments[4]!==void 0?arguments[4]:2e3,encryption:arguments.length>5&&arguments[5]!==void 0?arguments[5]:2,d2:"",d2Len:0,uinType:arguments.length>6&&arguments[6]!==void 0?arguments[6]:30,uin:"",uinLen:0,reqHead:{seqNumber:Fe,appId:_e,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:Dt,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:vi}}(t,A,cv);cv=cv+1&2147483647,o.writeInt32(0),o.writeInt32(a.version),o.writeByte(a.encryption);let l=new TextEncoder().encode(a.d2);o.writeInt32(l.length+4),l&&o.writeBytes(l),o.writeByte(a.uinType);let d=new TextEncoder().encode(a.uin);o.writeInt32(d.length+4),d.length&&o.writeBytes(d);let h=new u2;h.writeInt32(0),h.writeInt32(a.reqHead.seqNumber),h.writeInt32(a.reqHead.appId),h.writeByte(a.reqHead.appId>>>24&255),h.writeByte(a.reqHead.appId>>>16&255),h.writeByte(a.reqHead.appId>>>8&255),h.writeByte(255&a.reqHead.appId);for(let _e=4;_e<16;_e++)h.writeByte(0);let y=new TextEncoder().encode(a.reqHead.a2);h.writeInt32(y.length+4),y.length&&h.writeBytes(y);let S=new TextEncoder().encode(a.reqHead.serviceCmd);h.writeInt32(S.length+4),S.length&&h.writeBytes(S);let L=new TextEncoder().encode(a.reqHead.cookie);h.writeInt32(L.length+4),L.length&&h.writeBytes(L);let V=new TextEncoder().encode(a.reqHead.imei);h.writeInt32(V.length+4),V.length&&h.writeBytes(V);let H=new TextEncoder().encode(a.reqHead.ksid);h.writeInt32(H.length+4),H.length&&h.writeBytes(H);let lA=new TextEncoder().encode(a.reqHead.clientVersionInfo);h.writeInt16(lA.length+2),lA.length&&h.writeBytes(lA);let hA=h.length;h.data[0]=hA>>>24&255,h.data[1]=hA>>>16&255,h.data[2]=hA>>>8&255,h.data[3]=255&hA,Ws(A)&&(A=new TextEncoder().encode(A)),h.writeInt32(A.length+4),A.length&&h.writeBytes(A);let MA=new Uint8Array(h.data),oe=null;a.encryption===1?oe=new TextEncoder().encode(a.uin):a.encryption===2&&(oe=new Uint8Array(16)),oe&&(MA=function(_e,vi){let Fe=_e.length,Dt=(Fe+1+Xh+lv)%8;Dt&&(Dt=8-Dt);let pi=Fe+1+Xh+lv+Dt,Mi=new Uint8Array(pi),Wo=0,zo=new Uint8Array(8),vs=new Uint8Array(8),Zo=new Uint8Array(8),Vn=0;zo[0]=248&Math.floor(256*Math.random())|Dt,Vn=1;for(let wa=0;wa>>24&255,fe[1]=je>>>16&255,fe[2]=je>>>8&255,fe[3]=255&je,fe}function zb(A,t,o,a,l,d){for(let h=0;h<8;h++)A[h]^=a[h];(function(h,y,S,L){let V=Bu(h,0),H=Bu(h,4),lA=[];for(let MA=0;MA<4;MA++)lA[MA]=Bu(y,4*MA);let hA=0;for(let MA=0;MA>>=0,V+=(H<<4)+lA[0]^H+hA^(H>>>5)+lA[1],V>>>=0,H+=(V<<4)+lA[2]^V+hA^(V>>>5)+lA[3],H>>>=0;zf(S,V,L),zf(S,H,L+4)})(A,t,l,d);for(let h=0;h<8;h++)l[d+h]^=o[h];for(let h=0;h<8;h++)o[h]=A[h]}var d2=function(){return new URLSearchParams(location.search).get("trtc_env")||""},C2=function(A){return A.includes(".")?A:"".concat(A).concat(".rtc.qq.com")},zd=A=>Number(A)<14e8,Xf=function(A,t){let o;o=kb||(zd(A)?_p:FI);let a=Math.floor(Math.random()*zS(2,31));return"".concat(o,"/v5/AVQualityReportSvc/C2S?random=").concat(a,"&sdkappid=").concat(A,"&cmdtype=").concat(t)},Zb="unknown";function _0(){(function(){var d;h2||(h2=!0,(d=navigator.connection)==null||d.addEventListener("typechange",YK))})();let{userAgent:A,connection:t}=navigator,o=(A.match(/NetType\/\S+/)||[])[0]||"";o=o.toLowerCase().replace("nettype/",""),o==="3gnet"&&(o="3g");let a=t&&t.type&&t.type.toLowerCase(),l=t&&t.effectiveType&&t.effectiveType.toLowerCase();return l==="slow-2"&&(l="2g"),a?Xb(a,l):Zb}function YK(){pA.warn("netType changed",_0())}var h2=!1;function Xb(A,t){if(d0[A])return A;switch(A){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function T0(A){Zb=Xb(A)}function $f(){return d0[_0()]}function B2(A,t){for(let o of Reflect.ownKeys(t))if(o!=="constructor"&&o!=="prototype"&&o!=="name"){let a=Object.getOwnPropertyDescriptor(t,o)||"";Object.defineProperty(A,o,a)}return A}function N0(A){return $b(A/4,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function $b(A){return 1e3*A/(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function Q2(A){return 4*G0(A,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function G0(A){return A*(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)/1e3}var p2=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},Zd=()=>{let A=navigator.language;return A=A.substring(0,2),A==="zh"},uE=function(A){if(!A||typeof A!="object"||Object.prototype.toString.call(A)!="[object Object]")return!1;let t=Object.getPrototypeOf(A);if(t===null)return!0;let o=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof o=="function"&&o instanceof o&&Function.prototype.toString.call(o)===Function.prototype.toString.call(Object)};function Ay(A){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;return A<=1?t:Ay(A-1,t,(arguments.length>1&&arguments[1]!==void 0?arguments[1]:1)+t)}function bp(A){return A>8?3e4:1e3*Ay(A)}function Qg(A){return Reflect.apply(Object.prototype.toString,A,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ba=A=>typeof A=="function",ze=A=>A===void 0,Ws=A=>typeof A=="string",Ys=A=>typeof A=="number",br=A=>typeof A=="boolean",ed=A=>Qg(A)==="object",ka=A=>Qg(A)==="array",Ak=A=>Qg(A)==="MediaStreamTrack".toLowerCase(),ek=A=>A.isRemote,ey=A=>Qg(A)==="promise",ty=A=>ba(A)&&A.prototype.constructor===A,Iv=A=>ty(A)?A.prototype.constructor.name:"",m2=typeof AudioWorkletNode<"u",f2=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype;function uv(A){return new Promise((t,o)=>{let a=[];A.forEach(l=>{l.then(t).catch(d=>{a.push(d),a.length===A.length&&o(a)})})})}function Oo(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var y2=A=>+A<10?"0".concat(A):A,D2=A=>{let t=A.match(/^\d+\.\d+\.\d+/)[0];if(!t)return A;let o=t.split("."),a=y2(o[1])+y2(o[2]);return o[1]-15>0&&(o[1]="15"),o[2]-15>0&&(o[2]="15"),"".concat(o.join("."),".").concat(a)},VK=Object.prototype.hasOwnProperty;function b0(A){if(A==null)return!0;if(typeof A=="boolean")return!1;if(typeof A=="number")return A===0;if(typeof A=="string"||typeof A=="function"||Array.isArray(A))return A.length===0;if(A instanceof Error)return A.message==="";if(uE(A))switch(Object.prototype.toString.call(A)){case"[object File]":case"[object Map]":case"[object Set]":return A.size===0;case"[object Object]":for(let t in A)if(VK.call(A,t))return!1;return!0}return!1}function kp(A,t){return{userId:t,hasAudio:!!(A&iv),hasVideo:!!(A&ev),hasAuxiliary:!!(A&tv),hasSmall:!!(A&Fb),audioMuted:!!(A&qf),videoMuted:!!(A&ov),audioAvailable:!(!(A&iv)||A&qf),videoAvailable:!(!(A&ev)||A&ov),hasDatachannel:!!(A&AQ)}}function S2(A){let t={urls:A.url.startsWith("turn:")||A.url.startsWith("turns:")?A.url:"turn:".concat(A.url)};return!ze(A.username)&&!ze(A.credential)&&(t.username=A.username,t.credential=A.credential,t.credentialType="password",ze(A.credentialType)||(t.credentialType=A.credentialType)),t}function Ev(A){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(!Ws(A))return 0;let o=A.split(".");return t?(Number(o[0])<<24|Number(o[1])<<16|Number(o[2])<<8|Number(o[3]))>>>0:(Number(o[3])<<24|Number(o[2])<<16|Number(o[1])<<8|Number(o[0]))>>>0}var $h=function(A,t,o,a){if(!ed(A)||!ed(t))return 0;let l,d=0,h=Object.keys(t);for(let y=0,S=h.length;y{t[a]=iy(o)}),t}if(ed(A)){let t={};return Object.keys(A).forEach(o=>{t[o]=iy(A[o])}),t}return A}var dv=A=>{let t=[];if(ka(A))t=[...A];else if(Ws(A)){let o=document.getElementById(A);o&&t.push(o)}else A&&t.push(A);return t},tk=A=>Ws(A)?document.getElementById(A):A,v2=()=>(A=>{let t=S=>S<10?"0".concat(S):"".concat(S),o=A.getFullYear(),a=A.getMonth()+1,l=A.getDate(),d=t(A.getHours()),h=t(A.getMinutes()),y=t(A.getSeconds());return"".concat(o,"/").concat(a,"/").concat(l," ").concat(d,":").concat(h,":").concat(y)})(new Date);function Xd(A,t){let{keysToInclude:o,keysToExclude:a}=t;try{if(ka(A))return"[".concat(A.map(y=>Xd(y,{keysToInclude:o,keysToExclude:a})).join(","),"]");if(!uE(A)||!ka(o)&&!ka(a))return JSON.stringify(A);let l={},d=new Set(o),h=new Set(a);return Object.keys(A).forEach(y=>{(h.size===0&&d.has(y)||d.size===0&&!h.has(y))&&(l[y]=uE(A[y])||ka(A[y])?JSON.parse(Xd(A[y],{keysToExclude:a,keysToInclude:o})):A[y])}),JSON.stringify(l)}catch{return"{}"}}function k0(A){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],o=[];return Object.keys(A).forEach(a=>{t===A[a]&&o.push(a)}),Xd(A,{keysToInclude:o})}function L0(A){return A.replace(/[\u4e00-\u9fa5]/g,"aa").length}var ik=()=>{var A,t,o,a;return(A=window.screen)!=null&&A.orientation?!((a=(o=(t=window.screen)==null?void 0:t.orientation)==null?void 0:o.type)==null||!a.includes("portrait")):window.orientation===0||window.orientation===180},Cv=A=>XA(null,null,function*(){return new Promise((t,o)=>{let a;if(Ws(A))a=new Image,a.crossOrigin="anonymous",a.src=A;else if(a=A,a.complete)return void t(a);a.onload=()=>t(a),a.onerror=()=>{o(new li({code:mt.INVALID_PARAMETER,message:"load image failed, url: ".concat(A)}))}})}),ok=A=>{let t=A.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},U0=A=>(Object.keys(A).forEach(t=>{Ys(A[t])&&(t.startsWith("uint")||t.startsWith("int"))?A[t]=Math.floor(A[t]):(uE(A[t])||ka(A[t]))&&U0(A[t])}),A);function OC(A,t){return new Promise(o=>{let a=setTimeout(o,A);t&&t(a)})}function nk(A,t){let o=null;return function(){for(var a=arguments.length,l=new Array(a),d=0;do=null),o)}}function sk(A){return A.replace(/(^|[^:])\/{2,}/g,"$1/")}function rk(A){var t;try{let{width:o,height:a,frameRate:l,sampleRate:d,sampleSize:h,channelCount:y}=(t=A.getSettings)==null?void 0:t.call(A),S=A.kind===JA.AUDIO?"".concat(d,"x").concat(h,"@").concat(y):"".concat(o,"x").concat(a,"@").concat(l),L=A.stats?" stats: ".concat(JSON.stringify(A.stats).replaceAll('"',"")):"";return"".concat(A.id," ").concat(A.readyState," muted:").concat(A.muted," ").concat(A.kind," ").concat(A.label," ").concat(S).concat(L)}catch{return""}}function F0(A,t){return A.width*A.height===t.width*t.height?1:ik()&&t.width>t.height&&A.height>t.width?Math.max(A.width/t.height,A.height/t.width,1):Math.max(A.width/t.width,A.height/t.height,1)}function iQ(A){return A===90||A===270}function M2(A){return XA(this,null,function*(){return new Promise((t,o)=>{let a=document.createElement("video");a.crossOrigin="anonymous",a.src=A,a.muted=!0,a.loop=!0,a.playsInline=!0,a.play().then(()=>t(a)),a.onerror=()=>{o(a.error)}})})}function oy(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:new WeakMap;if(typeof A!="object"||A===null)return A;if(t.has(A))return t.get(A);if(Array.isArray(A)){let o=[];return t.set(A,o),A.forEach((a,l)=>{o[l]=oy(a,t)}),o}if(Object.prototype.toString.call(A)==="[object Object]"){let o={};return t.set(A,o),Reflect.ownKeys(A).forEach(a=>{o[a]=oy(A[a],t)}),o}return A}var O0=(A=>(A[A.END_REPORT=2001]="END_REPORT",A[A.LOG=2002]="LOG",A[A.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",A))(O0||{});function oQ(A,t,o,a){try{let l=function(d,h,y,S){let L={data:d,random:Math.floor(2147483648*Math.random()),sdkAppId:y};return ze(S)||(L=So(Di({},L),{gzip:+S})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:h,bytes_report_data:JSON.stringify(L)}}}(A,t,o,a);return Wb(R0(l),o)}catch{return JSON.stringify(A)}}function hv(A,t){let o=new Uint8Array(A.byteLength+t.byteLength);return o.set(new Uint8Array(A),0),o.set(new Uint8Array(t),A.byteLength),o.buffer}function P0(A){return(65535&A)>>>0}function R2(A){return(4294901760&A)>>>0}function Lp(A){return!!(A&&A instanceof CanvasCaptureMediaStreamTrack&&A.canvas.id.includes("trtc_mix"))}function HK(A){let t=function(o){try{let a={},l=0;a.totalLength=Bu(o,l),l+=4,a.version=Bu(o,l),l+=4,a.encryption=E2(o,l),l+=1,a.uinType=E2(o,l),l+=1,a.uinLength=Bu(o,l),l+=4,a.uin=a.uinLength>4?Zf(o,l,a.uinLength-4):"",l+=a.uinLength-4;let d=o.slice(l);return a.encryption===2?(o=function(h,y){let S=0,L=new Uint8Array(8).fill(0),V=new Uint8Array(h.slice(0,8)),H=x0(V,y),lA=7&H[0],hA=h.length-1-lA-Xh-lv,MA=new Uint8Array(hA),oe=0,fe=L,je=h.slice(0,8);S=8;let _e=1;_e+=lA;for(let Fe=1;Fe<=Xh;)if(_e<8)_e++,Fe++;else if(_e===8){let Dt=ny(h,S,fe,je,H,y);fe=Dt.ivPreCrypt,je=Dt.ivCurCrypt,H=Dt.debiBuf,S=Dt.bufPos,_e=0}let vi=hA;for(;vi>0;)if(_e<8)MA[oe++]=H[_e]^fe[_e],_e++,vi--;else if(_e===8){let Fe=ny(h,S,fe,je,H,y);fe=Fe.ivPreCrypt,je=Fe.ivCurCrypt,H=Fe.debiBuf,S=Fe.bufPos,_e=0}for(let Fe=1;Fe<=lv;)if(_e<8)H[_e],fe[_e],_e++,Fe++;else if(_e===8){if(S>=h.length)break;let Dt=ny(h,S,fe,je,H,y);if(!Dt.success)break;fe=Dt.ivPreCrypt,je=Dt.ivCurCrypt,H=Dt.debiBuf,S=Dt.bufPos,_e=0}return MA}(d,new Uint8Array(16).fill(0)),a.decrypted=!0,l=0):(o=d,l=0),a.rspHeadLength=Bu(o,l),l+=4,a.seqNo=Bu(o,l),l+=4,a.retCode=Bu(o,l),l+=4,a.retStrLength=Bu(o,l),l+=4,a.retStr=a.retStrLength?Zf(o,l,a.retStrLength-4):"",l+=a.retStrLength-4,a.serviceCmdLength=Bu(o,l),l+=4,a.serviceCmd=a.serviceCmdLength?Zf(o,l,a.serviceCmdLength-4):"",l+=a.serviceCmdLength-4,a.cookieLength=Bu(o,l),l+=4,a.cookie=a.cookieLength?Zf(o,l,a.cookieLength-4):"",l+=a.cookieLength-4,a.flag=Bu(o,l),l+=4,a.busiBuffLength=Bu(o,l),l+=4,a.busiBuff=a.busiBuffLength?Zf(o,l,a.busiBuffLength-4):"",l+=a.busiBuffLength-4,a}catch{}}(A);return t?.busiBuff}function x0(A,t){let o=A[0]<<24|A[1]<<16|A[2]<<8|A[3],a=A[4]<<24|A[5]<<16|A[6]<<8|A[7];o>>>=0,a>>>=0;let l=jb*w0>>>0;for(let d=0;d>>5)+t[3],a>>>=0,o-=(a<<4)+t[0]^a+l^(a>>>5)+t[1],o>>>=0,l-=jb,l>>>=0;return new Uint8Array([o>>>24&255,o>>>16&255,o>>>8&255,255&o,a>>>24&255,a>>>16&255,a>>>8&255,255&a])}function ny(A,t,o,a,l,d){if(t+8>A.length)return{success:!1};let h=new Uint8Array(a),y=A.slice(t,t+8),S=new Uint8Array(8);for(let L=0;L<8;L++)S[L]=l[L]^y[L];return{success:!0,ivPreCrypt:h,ivCurCrypt:y,debiBuf:x0(S,d),bufPos:t+8}}var Up=typeof TextDecoder<"u"?new TextDecoder:void 0;function nQ(A){let{url:t,body:o,method:a="POST",timeout:l,priority:d}=A;return new Promise((h,y)=>{if("fetch"in window)return fetch(t,{method:a,body:o,priority:d}).then(L=>L.clone().json().then(V=>({data:V}),()=>L.arrayBuffer().then(V=>({data:HK(new Uint8Array(V))||(Up?Up.decode(V):V)})))).then(h,y);let S=new XMLHttpRequest;S.onreadystatechange=()=>{if(S.readyState===4)if(S.status>=200&&S.status<300)try{let L=JSON.parse(S.response);h({data:L})}catch{h({data:S.response})}else y({status:S.status,statusText:S.statusText||"request failed!"})},S.timeout=l||5e3,S.open(a,t,!0),S.send(o)})}function ak(A){return XA(this,null,function*(){let t=Oo(),o=JSON.stringify(A);try{if(!CompressionStream||o.length<=2800)return o;let a=new Blob([o],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),l=yield(yield(yield new Response(a)).blob()).arrayBuffer();return pA.debug("compressJSON ".concat(o.length," -> ").concat(l.byteLength," ").concat(Oo()-t,"ms")),l}catch{return o}})}var w2=Object.prototype.hasOwnProperty,Fp=A=>typeof A=="function",td=A=>A===void 0,gk=A=>typeof A=="string",_2=A=>typeof A=="boolean",ck=A=>A.isRemote,T2=function(A){if(!A||typeof A!="object"||Object.prototype.toString.call(A)!="[object Object]")return!1;let t=Object.getPrototypeOf(A);if(t===null)return!0;let o=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof o=="function"&&o instanceof o&&Function.prototype.toString.call(o)===Function.prototype.toString.call(Object)},Bv=function(A){let{retryFunction:t,settings:o,onError:a,onRetrying:l,onRetryFailed:d,onRetrySuccess:h,context:y}=A;return function(){for(var S=arguments.length,L=new Array(S),V=0;VXA(this,null,function*(){let vi=y||this;try{let Fe=yield t.apply(vi,L);hA>0&&h&&h.call(this,hA),hA=0,je(Fe)}catch(Fe){let Dt=()=>{clearTimeout(MA),hA=0,oe=2,_e(Fe)},pi=()=>{oe!==2&&hA<(Fp(H)?H():H)?(hA++,oe=1,Fp(l)&&l.call(this,hA,Dt),MA=window.setTimeout(()=>{MA=-1,fe(je,_e)},Fp(lA)?lA(hA):lA)):(Dt(),Fp(d)&&d.call(this,Fe))};Fp(a)?a.call(this,{error:Fe,retry:pi,reject:_e,retryFuncArgs:L,retriedCount:hA}):pi()}});return new Promise(fe)}},lk=class hX{constructor(t){Y(this,"_parentPath"),Y(this,"userId"),Y(this,"remoteUserId"),Y(this,"id"),Y(this,"sdkAppId"),Y(this,"type"),Y(this,"isLocal"),this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=!_2(t.isLocal)||t.isLocal,this.type=this.isLocal?"":t.type}getFullId(){return this._parentPath&&this.id?"".concat(this._parentPath,"-").concat(this.id):this._parentPath?this._parentPath:this.id}createChild(t){let o=new hX({id:t.id,userId:td(t.userId)?this.userId:t.userId,sdkAppId:td(t.sdkAppId)?this.sdkAppId:t.sdkAppId,type:td(t.type)?this.type:t.type,isLocal:td(t.isLocal)?this.isLocal:t.isLocal,remoteUserId:td(t.remoteUserId)?this.remoteUserId:t.remoteUserId});return o.bindParent(this),o}bindParent(t){let o=t.getFullId();this._parentPath!==o&&(this.debug("bind logger parent: ".concat(t.id)),this._parentPath=o,this.userId=t.userId||this.userId,this.sdkAppId=t.sdkAppId||this.sdkAppId)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,o){let a=this.isLocal?this.userId:this.remoteUserId,l=this.getFullId();o.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&this.type!=="main"?"*":"").concat(l).concat(a?"|".concat(a):"","]")),pA.log(t,o,td(this.userId)||function(d){if(d==null)return!0;if(typeof d=="boolean")return!1;if(typeof d=="number")return d===0;if(typeof d=="string"||typeof d=="function"||Array.isArray(d))return d.length===0;if(d instanceof Error)return d.message==="";if(T2(d))switch(Object.prototype.toString.call(d)){case"[object File]":case"[object Map]":case"[object Set]":return d.size===0;case"[object Object]":for(let h in d)if(w2.call(d,h))return!1;return!0}return!1}(this.userId),this.userId,this.sdkAppId)}info(){for(var t=arguments.length,o=new Array(t),a=0;aH0,CHROME_MAJOR_VERSION:()=>nd,CHROME_VERSION:()=>A_,EDGE_VERSION:()=>uk,EDG_MAJOR_VERSION:()=>q0,EDG_VERSION:()=>Ek,ELECTRON_MAJOR_VERSION:()=>O2,FIREFOX_MAJOR_VERSION:()=>J0,FIREFOX_VERSION:()=>pv,HUAWEI_VERSION:()=>Sk,IE_VERSION:()=>KK,IOS_MAIN_VERSION:()=>$d,IOS_VERSION:()=>PI,IPADQQB_VERSION:()=>Dv,IS_ANDROID:()=>za,IS_ANDROID_WEBVIEW:()=>Rk,IS_ANY_SAFARI:()=>Hp,IS_CHROME:()=>$0,IS_CHROME_OS:()=>mk,IS_CHROMIUM_128_TO_143:()=>Iy,IS_CHROMIUM_BASE:()=>EE,IS_DESKTOP_IOS_CHROME:()=>Y2,IS_EDG:()=>ry,IS_EDGE:()=>sy,IS_ELECTRON:()=>jK,IS_FIREFOX:()=>gr,IS_HEADLESS_CHROME:()=>F2,IS_HONOR:()=>Dk,IS_HUAWEI:()=>yk,IS_HUAWEIBROWSER:()=>AB,IS_IE:()=>L2,IS_IE8:()=>qK,IS_IOS:()=>ng,IS_IOS_13_OR_14:()=>x2,IS_IOS_15_1:()=>P2,IS_IOS_CHROME:()=>_v,IS_IPAD:()=>Op,IS_IPADQQB:()=>z0,IS_IPAD_PRO:()=>V0,IS_IPHONE:()=>Pp,IS_IPOD:()=>b2,IS_LINUX:()=>cy,IS_LOCAL:()=>Jp,IS_MAC:()=>rQ,IS_MACQQB:()=>yv,IS_MIBROWSER:()=>Z0,IS_MQQB:()=>fv,IS_NATIVE_ANDROID:()=>k2,IS_OLD_ANDROID:()=>JK,IS_OPENHARMONY:()=>ly,IS_OPPOBROWSER:()=>vv,IS_SAFARI:()=>mg,IS_SAFARI_15_1:()=>WK,IS_SAMSUNGBROWSER:()=>Sv,IS_SOGOU:()=>j0,IS_SOGOUM:()=>mv,IS_TBS:()=>od,IS_UCBROWSER:()=>fk,IS_VIVOBROWSER:()=>Mv,IS_WECHAT:()=>sQ,IS_WIN:()=>gy,IS_WQQB:()=>W0,IS_WX:()=>U2,IS_X5MQQB:()=>Yp,IS_XWEB:()=>xp,MACQQB_VERSION:()=>pk,MI_VERSION:()=>Vp,MQQB_VERSION:()=>ay,OPENHARMONY_VERSION:()=>X0,OPPO_VERSION:()=>Mk,SAFARI_VERSION:()=>aQ,SAMSUNG_VERSION:()=>vk,SOGOUM_VERSION:()=>K0,SOGOU_VERSION:()=>dk,TBS_VERSION:()=>Ck,UA_DATA_STRING:()=>PC,USER_AGENT:()=>id,VIVO_VERSION:()=>Rv,WECHAT_VERSION:()=>Bk,WQQB_VERSION:()=>Qk,XWEB_VERSION:()=>hk,browserInfo:()=>cQ,getBrowserCoreNumber:()=>$l,getBrowserInfo:()=>_k,getChromeMajorVersion:()=>wv,getDeviceModel:()=>lQ,getDeviceModelFromUA:()=>Tk,getGPUInfo:()=>qp,getOSName:()=>pl,getOSNumber:()=>Kp,getOSString:()=>jp,getOSType:()=>Q,getTerminalType:()=>ys,getUserAgentData:()=>Tv,isAMDGPU:()=>Ey,isAppleSiliconGPU:()=>zK,isLocalStorageEnabled:()=>gQ,isMobile:()=>e_,isNvidiaGPU:()=>V2,isRealIOS:()=>Qv,isVersionLargerThan:()=>uy,isVersionSmallerThan:()=>wk});var id=typeof navigator>"u"?"":navigator.userAgent,Yn=A=>new RegExp(A,"i").test(id),pg=A=>{if(Yn(A)){let t=new RegExp("".concat(A,"\\/([\\d.]+)")),o=id.match(t);if(o&&o[1])return o[1]}return""},Y0=A=>{if(Yn(A)){let t=new RegExp("".concat(A,"\\/(\\d+)")),o=id.match(t);if(o&&o[1])return parseFloat(o[1])}return NaN},Ik=/AppleWebKit\/([\d.]+)/i.exec(id),G2=Ik?parseFloat(Ik[1]):NaN,Op=Yn("iPad"),V0=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Yn("Macintosh"),Pp=Yn("iPhone")&&!Op,b2=Yn("iPod"),ng=Pp||Op||b2||V0,Qv=()=>{try{return ng&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch{return ng}},za=Yn("Android"),H0=function(){if(za){let A=id.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(A){let t=A[1]&&parseFloat(A[1]),o=A[2]&&parseFloat(A[2]);if(t&&o)return parseFloat("".concat(A[1],".").concat(A[2]));if(t)return t}}return NaN}(),JK=za&&Yn("webkit")&&H0<2.3,k2=za&&H0<5&&G2<537,gr=Yn("Firefox"),pv=pg("Firefox"),J0=Y0("Firefox"),sy=Yn("Edge"),uk=pg("Edge"),ry=Yn("Edg"),Ek=pg("Edg"),q0=Y0("Edg"),mv=Yn("SogouMobileBrowser"),K0=pg("SogouMobileBrowser"),j0=Yn("MetaSr\\s"),dk=pg("MetaSr\\s"),od=Yn("TBS"),Ck=pg("TBS"),xp=Yn("XWEB"),hk=pg("XWEB"),qK=Yn("MSIE\\s8\\.0"),L2=Yn("MSIE\\/\\d+"),KK=function(){if(L2){let A=/MSIE\s(\d+)\.\d/.exec(id),t=A&&parseFloat(A[1]);return!t&&/Trident\/7.0/i.test(id)&&/rv:11.0/.test(id)&&(t=11),t}return NaN}(),sQ=Yn("(micromessenger|webbrowser)"),Bk=pg("MicroMessenger"),Yp=!od&&Yn("MQQBrowser")&&Yn("COVC"),fv=!od&&Yn("MQQBrowser")&&!Yn("COVC"),ay=fv||Yp?pg("MQQBrowser"):"",W0=!od&&Yn(" QQBrowser"),Qk=pg(" QQBrowser"),yv=!od&&Yn("QQBrowserLite"),pk=pg("QQBrowserLite"),z0=!od&&Yn("MQBHD"),Dv=pg("MQBHD"),gy=Yn("Windows"),rQ=!ng&&Yn("MAC OS X"),cy=!za&&Yn("Linux"),mk=Yn("CrOS"),U2=Yn("MicroMessenger"),fk=Yn("UCBrowser"),jK=Yn("Electron"),Z0=Yn("MiuiBrowser"),Vp=pg("MiuiBrowser"),AB=Yn("HuaweiBrowser"),yk=Yn("Huawei")||Yn("HUAWEI"),Dk=Yn("Honor")||Yn("HONOR"),Sk=pg("HuaweiBrowser"),Sv=Yn("SamsungBrowser"),vk=pg("SamsungBrowser"),vv=Yn("HeyTapBrowser"),Mk=pg("HeyTapBrowser"),Mv=Yn("VivoBrowser"),Rv=pg("VivoBrowser"),ly=Yn("OpenHarmony"),X0=pg("OpenHarmony"),wv=()=>Y0("Chrome"),_v=Yn("CriOS"),EE=Yn("Chrome"),$0=!sy&&!j0&&!mv&&!od&&!xp&&!ry&&!W0&&!Z0&&!AB&&!Sv&&!vv&&!Mv&&EE,F2=Yn("HeadlessChrome"),nd=wv(),Iy=EE&&nd>=128&&nd<=143,A_=pg("Chrome"),O2=Y0("Electron"),mg=!EE&&!fv&&!Yp&&!yv&&!z0&&Yn("Safari"),Hp=mg||ng,aQ=pg("Version"),Rk=/Android.*(wv|.0.0.0)/.test(id),PI=(()=>{if(V0)return aQ;if(ng){let A=id.match(/OS (\d+)_(\d+)/i);if(A&&A[1]){let t=A[1];return A[2]&&(t+=".".concat(A[2])),t}}return""})();function wk(A,t){let o=A.split(".").map(l=>Number(l)),a=t.split(".").map(l=>Number(l));for(let l=0;lh)return!1}return!1}function uy(A,t){let o=arguments.length>2&&arguments[2]!==void 0&&arguments[2],a=A.split(".").map(d=>Number(d)),l=t.split(".").map(d=>Number(d));for(let d=0;dy)return!0;if(h{let A=Number(PI.split(".")[0]);return A===14||A===13})(),Y2=_v&&aQ==="11.1.1",Jp=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),gQ=(()=>{let A;return()=>{if(A===void 0)try{A=!!window.localStorage}catch{A=!1}return A}})(),cQ=_k();function _k(){let A=new Map([[gr,["Firefox",pv]],[ry,["Edg",Ek]],[$0,["Chrome",A_]],[_v,["ChiOS",pg("CriOS")]],[mg&&!_v,["Safari",aQ]],[od,["TBS",Ck]],[xp,["XWEB",hk]],[sQ&&Pp,["WeChat",Bk]],[W0,["QQ(Win)",Qk]],[fv,["QQ(Mobile)",ay]],[Yp,["QQ(Mobile X5)",ay]],[yv,["QQ(Mac)",pk]],[z0,["QQ(iPad)",Dv]],[Z0,["MI",Vp]],[AB,["HW",Sk]],[Sv,["Samsung",vk]],[vv,["OPPO",Mk]],[Mv,["VIVO",Rv]],[sy,["EDGE",uk]],[mv,["SogouMobile",K0]],[j0,["Sogou",dk]]]),t="unknown",o="unknown";return A.has(!0)&&([t,o]=A.get(!0)),{name:t,version:o}}var Hr=null;function e_(){return Hr&&typeof Hr.mobile=="boolean"?Hr.mobile:za||ng||Pp||Op||ly}var PC="";function Tv(){return XA(this,null,function*(){if(Hr)return Hr;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return(Hr=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!PC&&(PC="UAData: ".concat(Hr.platform,"/").concat(Hr.platformVersion),Hr.architecture&&Hr.bitness&&(PC+=" ".concat(Hr.architecture,"/").concat(Hr.bitness)),Hr.mobile&&(PC+=" mobile"),Hr.model&&(PC+=" model: ".concat(Hr.model.replace(/\s+/g,"/"))),Hr.fullVersionList&&(PC+=" ".concat(Hr.fullVersionList.filter(A=>A.brand!=="Not/A)Brand").map(A=>"".concat(A.brand,"/").concat(A.version)).join(",")))),Hr}catch{return null}})}var Nv="";function qp(){try{if(Nv)return Nv;let A=document.createElement("canvas"),t=A.getContext("webgl")||A.getContext("experimental-webgl");if(!t)return"";let o=t.getExtension("WEBGL_debug_renderer_info");if(o){let a=t.getParameter(o.UNMASKED_VENDOR_WEBGL),l=t.getParameter(o.UNMASKED_RENDERER_WEBGL);return Nv="".concat(a," ").concat(l)}return""}catch{return""}}function Ey(){try{let A=qp();return A.includes("AMD")||A.includes("ATI")}catch{return!1}}function V2(){try{let A=qp();return A.includes("NVIDIA")||A.includes("GeForce")}catch{return!1}}function zK(){try{return qp().includes("Apple M")}catch{return!1}}function lQ(){return Hr?.model||Tk()||""}function Tk(){let A=id.match(/;\s*([^;)]+)\s+Build\//);return A!=null&&A[1]?A[1].trim():null}var H2=new Map([[za,"Android"],[ng,"iOS"],[gy,"Windows"],[rQ,"MacOS"],[cy,"Linux"],[mk,"ChromeOS"]]),pl=function(){return H2.get(!0)?H2.get(!0):Hr?Hr.platform:"unknown"};function Kp(){return gy?1:za?2:rQ?3:ng?4:cy?5:mk?6:ly?7:0}function $l(){return sQ||xp?4:EE?1:mg?2:gr?3:0}var jp=()=>{let A=pl();return Hr!=null&&Hr.platformVersion?A+="/".concat(Hr.platformVersion):ng?A+="/".concat(PI):za&&(A+="/".concat(H0)),A+="/".concat(cQ.name,"/").concat(mg&&!_v?cQ.version:cQ.version.split(".")[0]),Hr!=null&&Hr.architecture&&(A+="/".concat(Hr.architecture)),A};function ys(){return za?4:Pp?2:Op?3:rQ?12:gy?5:cy?13:ly?22:1}function Q(){return za?"Android":Pp?"iPhone":Op?"iPad":rQ?"Mac":gy?"Windows":cy?"Linux":"unknown"}var w,F=new(dc(Xl(),1)).default,tA=((w=tA||{}).ROOM_DESTROY="1",w.JOIN_START="21",w.JOIN_SCHEDULE_SUCCESS="22",w.JOIN_SIGNAL_CONNECTION_START="23",w.JOIN_SIGNAL_CONNECTION_END="24",w.JOIN_SEND_CMD="25",w.JOIN_RECEIVED_CMD_RES="26",w.JOIN_SUCCESS="27",w.JOIN_FAILED="28",w.LEAVE_START="51",w.LEAVE_SEND_CMD="52",w.LEAVE_SUCCESS="53",w.PUBLISH_START="61",w.SEND_FIRST_VIDEO_FRAME="62",w.PUBLISH_FAILED="63",w.SUBSCRIBE_START="81",w.SUBSCRIBE_SUCCESS="82",w.SUBSCRIBE_FAILED="84",w.UNSUBSCRIBE_SUCCESS="83",w.LOCAL_TRACK_CAPTURE_START="101",w.LOCAL_TRACK_CAPTURE_SUCCESS="102",w.LOCAL_TRACK_CAPTURE_FAILED="103",w.LOCAL_TRACK_PUBLISHED="104",w.LOCAL_TRACK_UNPUBLISHED="105",w.LOCAL_TRACK_REPLACED="106",w.SWITCH_DEVICE_SUCCESS="107",w.TRACK_MUTED="108",w.TRACK_UNMUTED="109",w.REMOTE_TRACK_SUBSCRIBED="110",w.REMOTE_TRACK_UNSUBSCRIBED="111",w.LOCAL_TRACK_RECAPTURE="112",w.LOCAL_AUDIO_STARTED="113",w.LOCAL_AUDIO_STOPPED="114",w.REMOTE_AUDIO_STARTED="115",w.REMOTE_AUDIO_STOPPED="116",w.LOCAL_TRACK_STOPPED="117",w.LOCAL_VIDEO_TRACK_PREPROCESSED="118",w.PLAY_TRACK_START="151",w.PLAYER_STATE_CHANGED="152",w.VIDEO_LOADED_DATA="153",w.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",w.AUDIO_CONTEXT_LONG_SUSPENDED="155",w.REMOTE_VIDEO_PLAY_START="156",w.REMOTE_VIDEO_PLAY_FINISH="157",w.SIGNAL_CONNECTION_STATE_CHANGED="201",w.PEER_CONNECTION_STATE_CHANGED="202",w.SINGLE_CONNECTION_STAT="203",w.SPC_RECONNECTED="204",w.HEARTBEAT_REPORT="251",w.RECEIVED_PUBLISHED_USER_LIST="252",w.REMOTE_PUBLISH_STATE_CHANGED="253",w.AUDIO_LEVEL_INTERVAL="260",w.NETWORK_QUALITY="261",w.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",w.QUALITY_LIMITATION_CHANGED="263",w.LOG="264",w.AUDIO_PROCESSOR_DEBUG="265",w.SSO_SWITCH="266",w.SEI_MESSAGE="267",w.USER_PAUSE_IN_PIP="268",w.USER_RESUME_IN_PIP="269",w.ENTER_PICTURE_IN_PICTURE="270",w.LEAVE_PICTURE_IN_PICTURE="271",w.SWITCH_ROOM_START="401",w.SWITCH_ROOM_SUCCESS="407",w.SWITCH_ROOM_FAILED="408",w),rA=tA,TA=new class{constructor(){Y(this,"enable",!1),Y(this,"ssoFailCount",0),F.on("22",A=>{let{schedule:t}=A;var o;(o=t?.config)!=null&&o.sso&&F.emit("266",{enable:!0})}),F.on("266",A=>{let{enable:t}=A;this.enable=t})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&F.emit("266",{enable:!1})}},te=class BX{constructor(){Y(this,"_isEnableUploadLog",!0),Y(this,"_localJoinedUser",new Map),Y(this,"_queue",[]),Y(this,"_timeoutId",-1),Y(this,"_logLevel",1),Y(this,"_logLevelToUpload",2),!I0&&!u0&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){F.on(rA.JOIN_SCHEDULE_SUCCESS,t=>{let{schedule:o}=t;var a;(a=o?.config)!=null&&a.logLevelToUpload&&$B[o.config.logLevelToUpload]&&(this._logLevelToUpload=o.config.logLevelToUpload)}),F.on(rA.JOIN_START,t=>{let{params:o}=t;this.addJoinedUser({userId:o.userId,sdkAppId:o.sdkAppId}),this.startUpload()}),F.on(rA.LEAVE_SUCCESS,t=>{let{room:o}=t;this.deleteJoinedUser(o.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(t){this._localJoinedUser.set(t.userId,t),this.startUpload()}deleteJoinedUser(t){this._localJoinedUser.delete(t)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let t={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return t;let o=0;for(;o{let{userId:d,sdkAppId:h}=l;t.map.has(d)?t.map.get(d).logs.push(a):t.map.set(d,{userId:d,sdkAppId:h,logs:[a]})});else if(Ws(a.userId)&&Ys(a.sdkAppId)){let{userId:l,sdkAppId:d}=a;t.map.has(l)?t.map.get(l).logs.push(a):t.map.set(l,{userId:l,sdkAppId:d,logs:[a]})}}return t.map.size>0&&(t.splicedQueue=this._queue.splice(0,o)),t}upload(){return XA(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:t,splicedQueue:o}=this.getLogsToUpload();if(t.size===0)return;try{let l=[...t.values()];for(let d=0;dlA.log).join(` -`)},V=JSON.stringify(L),H=TA.enable?oQ(L,2002,y):V;yield this.uploadLogWithRetry(H,y,H instanceof Uint8Array,V),S.forEach(lA=>lA.uploaded=!0)}}catch{}let a=o.filter(l=>!l.uploaded);a.length>0&&(this._queue=a.concat(this._queue))})}uploadLogWithRetry(t,o,a,l){return Bv({retryFunction:()=>nQ({url:Xf(o,OI.LOG),body:t,timeout:5e3,priority:"low"}).then(d=>{a&&d.data!=="ok"&&(TA.handleUploadFailed(),this.uploadLogWithRetry(l,o,!1,l))}),settings:{retries:3,timeout:2e3},onError:d=>{let{retry:h}=d;h()}})()}getPrefix(t){let o=new Date;return o.setTime(Vf()),"[".concat(Gb(o),"] <").concat($B[t],">")}getLogLevel(){return this._logLevel}setLogLevel(t){ze($B[t])||(this._logLevel!==t&&this.info("setLogLevel",t),this._logLevel=t)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(t){if(Ws(t))return t;try{return t instanceof Error?t.toString():JSON.stringify(t)}catch{return""}}addLogToQueue(t,o){let a=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],l=arguments.length>3?arguments[3]:void 0,d=arguments.length>4?arguments[4]:void 0,h={log:o.reduce((y,S)=>"".concat(y," ").concat(this.logChunkToString(S)).trim(),""),level:t,userId:l,sdkAppId:d,forAllJoinedClients:a};F.emit(rA.LOG,{log:h}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(h)}log(t,o){let a=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],l=arguments.length>3?arguments[3]:void 0,d=arguments.length>4?arguments[4]:void 0;var h;if(o.unshift(this.getPrefix(t)),this.addLogToQueue(t,o,a,l,d),t{let t=16*Math.random()|0;return(A=="x"?t:3&t|8).toString(16)})},$A=new class{constructor(){Y(this,"_prefix","TRTC"),Y(this,"_queue",new Map)}getRealKey(A){return"".concat(this._prefix,"_").concat(A)}checkStorage(){gQ()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(A=>{if(A.startsWith(this._prefix))try{let t=localStorage.getItem(A);if(!t)return!1;let o=JSON.parse(t);if(o&&o.expiresInlocalStorage.removeItem(A)))}doFlush(){if(gQ())try{for(let[A,t]of this._queue)localStorage.setItem(A,JSON.stringify(t))}catch(A){pA.warn(A)}}getItem(A){if(!gQ())return null;try{let t=localStorage.getItem(this.getRealKey(A));if(!t)return null;let o=JSON.parse(t);return o&&o.expiresIn>=Date.now()?o.value:null}catch(t){pA.warn(t)}}setItem(A,t){if(gQ())try{let o={expiresIn:Date.now()+C0,value:t};this._queue.set(this.getRealKey(A),o)}catch(o){pA.warn(o)}}deleteItem(A){if(!gQ())return!1;try{return A=this.getRealKey(A),this._queue.delete(A),localStorage.removeItem(A),!0}catch(t){return pA.warn(t),!1}}clear(){if(gQ())try{localStorage.clear()}catch(A){pA.warn(A)}}},ge={};Wh(ge,{HTTPS_API:()=>qk,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>A1,IS_GET_CAPABILITIES_SUPPORTED:()=>$2,IS_GET_SETTINGS_SUPPORTED:()=>Dy,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>Xk,IS_INSERTABLE_STREAM_SUPPORTED:()=>$p,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>hQ,IS_RTC_RTP_SENDER_SUPPORTED:()=>xC,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>c_,IS_SEI_SUPPORTED:()=>$k,IS_SPC_SUPPORTED:()=>Yv,basis:()=>t1,capabilityCheck:()=>tL,checkSystemRequirementsInternal:()=>Hk,decodeSupportStatus:()=>Vk,detectH264SupportedByFakeStreaming:()=>Z2,detectVideoCodecCapabilities:()=>Hv,detectVideoDecoderCapabilities:()=>oL,detectVideoEncoderCapabilities:()=>iL,encodeSupportStatus:()=>Fv,getBrowserInfo:()=>Lv,getDisplayResolution:()=>ad,getH264ProfileLevelIds:()=>n1,isAddTransceiverSupported:()=>AC,isBrowserSupported:()=>xk,isCanvasCaptureStreamAPISupported:()=>Pv,isCanvasSmallStreamSupported:()=>g_,isGetReceiversSupported:()=>yy,isGetSendersSupported:()=>xI,isGetTransceiversSupported:()=>CQ,isGetUserMediaSupported:()=>Kk,isMediaDevicesSupported:()=>Yk,isMediaSessionSupported:()=>e1,isMediaStreamTrackGeneratorSupported:()=>$K,isMediaStreamTrackProcessorSupported:()=>Uv,isReplaceTrackSupported:()=>X2,isRequestVideoFrameCallbackSupported:()=>Am,isSIMDSupported:()=>Vv,isScaleResolutionDownBySupported:()=>Wk,isScreenCaptureApiAvailable:()=>Xp,isSelectedCandidatePair:()=>Ov,isSetParametersSupported:()=>Zk,isSetSinkIdSupported:()=>ej,isSmallStreamSupported:()=>xv,isStopTransceiverSupported:()=>sa,isTRTCSupported:()=>Aj,isUnifiedPlanDefault:()=>zk,isUsedInHttpProtocol:()=>Qu,isWebAudioSupported:()=>jk,isWebCodecSupported:()=>l_,isWebCodecsSupported:()=>a_,isWebRTCSupported:()=>Sy,isWebTransportSupported:()=>vy});var Oe={};Wh(Oe,{AUDIO_LEVEL_SCALE:()=>sd,AlphaStitchingType:()=>Qy,AudioCodecPipelineType:()=>dQ,AudioDecoderDowngradeState:()=>Gv,AudioPlayerMode:()=>o_,AudioType:()=>J2,BASIC_TYPE:()=>Lk,BannedReason:()=>fg,CONNECTION_CLOSED_REASON:()=>zt,CheckPermissionType:()=>Qr,ClientEvent:()=>nt,CodecType:()=>bv,ConnectionEvent:()=>Ko,ConnectionState:()=>dy,DECODE_FAILED_ERROR_CODE:()=>kv,DenoiserMode:()=>Wp,DeviceType:()=>Uk,FacingMode:()=>Gk,FrameWorkType:()=>co,LeaveReason:()=>bk,LocalTrackEvent:()=>No,MULTI_VIDEO_DATA_TYPE:()=>By,MediaType:()=>t_,MediaTypeLabel:()=>ZK,MonitorEventId:()=>ml,MutedFlag:()=>or,NetworkQualityValue:()=>dE,PlayerState:()=>Qo,ReceiveMode:()=>AI,RemoteStreamType:()=>hy,RemoteTrackEvent:()=>Ds,RoomEvent:()=>Bo,SMALL_MODE:()=>Zp,SceneNumber:()=>Za,StreamEvent:()=>wi,StreamType:()=>EQ,SubscribeMediaType:()=>kk,TIMER_TYPE:()=>s_,TRACK_ACTION:()=>Nk,TRACK_KIND:()=>IQ,TrackEvent:()=>jo,UserRole:()=>Jc,UserRoleNumber:()=>ln,VideoCodec:()=>fl,VideoCodecPipelineType:()=>zp,VideoContentHint:()=>n_,VideoDecoderDowngradeState:()=>Cy,VideoPlayerMode:()=>i_,VideoType:()=>uQ});var ke,me,Qt,Ii,at,$e,dA,vt,st,Xi,Ei,co=(A=>(A[A.WEBRTC=30]="WEBRTC",A[A.WASM=37]="WASM",A))(co||{}),Ko=((Ei=Ko||{}).TRACK_ADDED="track-added",Ei.TRACK_UPDATED="track-updated",Ei.TRACK_SUBSCRIBED="track-subscribed",Ei.STREAM_ADDED="stream-added",Ei.STREAM_REMOVED="stream-removed",Ei.STREAM_UPDATED="stream-updated",Ei.STREAM_PUBLISHED="stream-published",Ei.STREAM_SUBSCRIBED="stream-subscribed",Ei.STREAM_UNSUBSCRIBED="stream-unsubscribed",Ei.STATE_CHANGED="state-changed",Ei.ERROR="error",Ei.CONNECTION_STATE_CHANGED="connection-state-changed",Ei.FIREWALL_RESTRICTION="firewall-restriction",Ei.SEI_MESSAGE="sei-message",Ei.CLOSED="closed",Ei),zt=(A=>(A.REMOTE_LEAVE="remote user exitRoom",A.REMOTE_UNPUBLISH="remote user unpublished",A.LOCAL_LEAVE="you exitRoom",A.LOCAL_UNPUBLISH="you unpublished",A.LOCAL_UNSUBSCRIBE="you unsubscribed",A.SWITCH_ROLE="you switch role to audience",A))(zt||{}),nt=((Xi=nt||{}).STREAM_ADDED="stream-added",Xi.STREAM_REMOVED="stream-removed",Xi.STREAM_UPDATED="stream-updated",Xi.STREAM_SUBSCRIBED="stream-subscribed",Xi.CONNECTION_STATE_CHANGED="connection-state-changed",Xi.PEER_JOIN="peer-join",Xi.PEER_LEAVE="peer-leave",Xi.MUTE_AUDIO="mute-audio",Xi.MUTE_VIDEO="mute-video",Xi.UNMUTE_AUDIO="unmute-audio",Xi.UNMUTE_VIDEO="unmute-video",Xi.CLIENT_BANNED="client-banned",Xi.NETWORK_QUALITY="network-quality",Xi.AUDIO_VOLUME="audio-volume",Xi.SEI_MESSAGE="sei-message",Xi.ERROR="error",Xi),wi=((st=wi||{}).PLAYER_STATE_CHANGED="player-state-changed",st.SCREEN_SHARING_STOPPED="screen-sharing-stopped",st.CONNECTION_STATE_CHANGED="connection-state-changed",st.DEVICE_AUTO_RECOVERED="device-auto-recovered",st.ERROR="error",st),No=((vt=No||{}).DEVICE_AUTO_RECOVERED="1",vt.DEVICE_RECOVER_FAILED="5",vt.DEVICE_CHANGED="2",vt.ERROR="3",vt.PUBLISH_STATE_CHANGED="4",vt.ENCODE_FAILED="6",vt.TRACK_ENDED="7",vt.RENDER="render",vt),Qo=(A=>(A.PAUSED="PAUSED",A.PLAYING="PLAYING",A.STOPPED="STOPPED",A))(Qo||{}),Bo=((dA=Bo||{}).PEER_JOIN="peer-join",dA.PEER_LEAVE="peer-leave",dA.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",dA.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",dA.BANNED="banned",dA.NETWORK_QUALITY="network-quality",dA.AUDIO_VOLUME="audio-volume",dA.SEI_MESSAGE="sei-message",dA.ERROR="error",dA.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",dA.REMOTE_PUBLISHED="remote-published",dA.REMOTE_UNPUBLISHED="remote-unpublished",dA.FIREWALL_RESTRICTION="firewall-restriction",dA.HEARTBEAT_REPORT="heartbeat-report",dA.CUSTOM_MESSAGE="custom-message",dA.LAYER_DATA="layerData",dA.FIRST_VIDEO_FRAME="first-video-frame",dA.FIRST_FRAME_RENDER="first-frame-render",dA.DUMP="dump",dA.AUDIO_FRAME="audio-frame",dA.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",dA.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",dA.NTP_TIME_UPDATED="ntp-time-updated",dA.DATA_CHANNEL_MESSAGE="data-channel-message",dA.ASR_ROBOT_PEER_JOIN="asr-robot-peer-join",dA.ASR_ROBOT_PEER_LEAVE="asr-robot-peer-leave",dA),jo=(($e=jo||{}).PLAYER_STATE_CHANGED="player-state-changed",$e.MUTE="mute",$e.UNMUTE="unmute",$e.ERROR="error",$e.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",$e.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",$e.FIRST_VIDEO_FRAME="first-video-frame",$e.FIRST_FRAME_RENDER="first-frame-render",$e.VIDEO_SIZE_CHANGED="video-size-changed",$e),Ds=(A=>(A.DECODE_FAILED="decode-failed",A.DECODE_FAILED_DURING_CALL="decode-failed-during-call",A.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",A.REMOTE_PUBLISH_CHANGED="remote-publish-changed",A.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",A))(Ds||{}),or=((at=or||{})[at.VIDEO=1]="VIDEO",at[at.SMALL=2]="SMALL",at[at.AUX=4]="AUX",at[at.AUDIO=8]="AUDIO",at[at.VIDEO_MUTE=16]="VIDEO_MUTE",at[at.AUX_MUTE=32]="AUX_MUTE",at[at.AUDIO_MUTE=64]="AUDIO_MUTE",at),Za=(A=>(A[A.RTC=1]="RTC",A[A.LIVE=2]="LIVE",A))(Za||{}),ln=(A=>(A[A.ANCHOR=20]="ANCHOR",A[A.AUDIENCE=21]="AUDIENCE",A))(ln||{}),Jc=(A=>(A.ANCHOR="anchor",A.AUDIENCE="audience",A))(Jc||{}),dy=(A=>(A.CONNECTED="CONNECTED",A.DISCONNECTED="DISCONNECTED",A.CONNECTING="CONNECTING",A.RECONNECTED="RECONNECTED",A.RECONNECTING="RECONNECTING",A))(dy||{}),Gv=((Ii=Gv||{}).INITIALIZED="INITIALIZED",Ii.STARTING="STARTING",Ii.STARTED="STARTED",Ii.FAILED="FAILED",Ii),Cy=(A=>(A.INITIALIZED="INITIALIZED",A.STARTING="STARTING",A.STARTED="STARTED",A.FAILED="FAILED",A))(Cy||{}),IQ=(A=>(A.AUDIO="audio",A.VIDEO="video",A.AUXILIARY="auxVideo",A))(IQ||{}),Nk=(A=>(A.ADD="add",A.REMOVE="remove",A))(Nk||{}),t_=(A=>(A[A.NULL=0]="NULL",A[A.AUDIO=1]="AUDIO",A[A.AUX_VIDEO=2]="AUX_VIDEO",A[A.BIG_VIDEO=4]="BIG_VIDEO",A[A.SMALL_VIDEO=8]="SMALL_VIDEO",A))(t_||{}),ZK={1:"audio",2:"auxVideo",4:"video"},J2=((Qt=J2||{})[Qt.opus=111]="opus",Qt),uQ=(A=>(A[A.h264=100]="h264",A[A.vp8=101]="vp8",A))(uQ||{}),EQ=(A=>(A.Big="big",A.Small="small",A))(EQ||{}),hy=(A=>(A.Main="main",A.Aux="auxiliary",A))(hy||{}),By=(A=>(A[A.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",A[A.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",A[A.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",A[A.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",A[A.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",A))(By||{}),ml=((me=ml||{})[me.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",me[me.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",me[me.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",me[me.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",me[me.MUTE_AUDIO=32772]="MUTE_AUDIO",me[me.MUTE_VIDEO=32773]="MUTE_VIDEO",me[me.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",me[me.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",me[me.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",me[me.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",me[me.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",me[me.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",me[me.SWITCH_CAMERA=32780]="SWITCH_CAMERA",me[me.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",me[me.REPLACE_VIDEO=32782]="REPLACE_VIDEO",me[me.REPLACE_AUDIO=32783]="REPLACE_AUDIO",me[me.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",me[me.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",me[me.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",me[me.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",me[me.JOIN=32788]="JOIN",me[me.LEAVE=32789]="LEAVE",me[me.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",me[me.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",me[me.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",me[me.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",me[me.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",me[me.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",me[me.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",me[me.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",me[me.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",me[me.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",me[me.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",me[me.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",me[me.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",me[me.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",me[me.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",me[me.PUBLISH_AUX=32805]="PUBLISH_AUX",me[me.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",me[me.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",me[me.VIDEO_ENCODER=4004]="VIDEO_ENCODER",me[me.VIDEO_DECODER=4005]="VIDEO_DECODER",me),dE=(A=>(A[A.UNKNOWN=0]="UNKNOWN",A[A.EXCELLENT=1]="EXCELLENT",A[A.GOOD=2]="GOOD",A[A.POOR=3]="POOR",A[A.BAD=4]="BAD",A[A.VERY_BAD=5]="VERY_BAD",A[A.DISCONNECTED=6]="DISCONNECTED",A))(dE||{}),AI=(A=>(A[A.MANUAL=0]="MANUAL",A[A.AUTO_AUDIO=1]="AUTO_AUDIO",A[A.AUTO_VIDEO=2]="AUTO_VIDEO",A[A.AUTO_ALL=3]="AUTO_ALL",A))(AI||{}),Gk=(A=>(A.user="user",A.environment="environment",A))(Gk||{}),i_=(A=>(A[A.ELEMENT=0]="ELEMENT",A[A.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",A[A.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",A))(i_||{}),o_=(A=>(A[A.ELEMENT=0]="ELEMENT",A[A.CONTEXT=1]="CONTEXT",A))(o_||{}),fg=(A=>(A.BANNED="banned",A.KICK="kick",A.USER_TIME_OUT="user_time_out",A.ROOM_DISBAND="room_disband",A))(fg||{}),bk=(A=>(A[A.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",A[A.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",A[A.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",A[A.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",A[A.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",A[A.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",A[A.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",A[A.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",A[A.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",A))(bk||{}),sd=1e8,Wp=(A=>(A[A.NORMAL=0]="NORMAL",A[A.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",A))(Wp||{}),kk=class{constructor(){Y(this,"mediaType",0)}set audio(A){A?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(1&this.mediaType)}set video(A){A?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(4&this.mediaType)}set auxiliary(A){A?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(2&this.mediaType)}set smallVideo(A){A?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(8&this.mediaType)}},Lk=(A=>(A.String="string",A.Number="number",A.Boolean="boolean",A.Array="array",A.Object="object",A))(Lk||{}),fl=(A=>(A.H264="h264",A.H265="h265",A.VP8="vp8",A.VP9="vp9",A.AV1="av1",A))(fl||{}),zp=(A=>(A[A.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",A[A.DUMP=1]="DUMP",A[A.SEI=2]="SEI",A[A.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",A))(zp||{}),dQ=(A=>(A[A.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",A[A.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",A[A.DUMP=2]="DUMP",A[A.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",A))(dQ||{}),bv=(A=>(A.WebRTC="webrtc",A.WebCodecs="webcodecs",A.WebAssembly="webassembly",A))(bv||{}),kv=((ke=kv||{})[ke.SUCCESS=0]="SUCCESS",ke[ke.FAILED=1]="FAILED",ke[ke.WEBCODEC_INIT=2]="WEBCODEC_INIT",ke[ke.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",ke[ke.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",ke[ke.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",ke[ke.WASM_INIT=6]="WASM_INIT",ke[ke.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",ke[ke.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",ke[ke.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",ke[ke.TEST=10]="TEST",ke[ke.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",ke),n_=(A=>(A.NONE="",A.DETAIL="detail",A.MOTION="motion",A.TEXT="text",A))(n_||{}),s_=(A=>(A.INTERVAL="interval",A.TIMEOUT="timeout",A.RAF="raf",A.RIC="ric",A.INTERVAL_IN_WORKER="intervalInWorker",A))(s_||{}),Zp=(A=>(A.CANVAS="canvas",A.API="api",A))(Zp||{}),Qr=(A=>(A[A.NONE=0]="NONE",A[A.MICROPHONE=1]="MICROPHONE",A[A.CAMERA=2]="CAMERA",A[A.BOTH=3]="BOTH",A))(Qr||{}),Uk=(A=>(A.CAMERA="camera",A.MICROPHONE="microphone",A))(Uk||{}),Qy=(A=>(A[A.none=0]="none",A[A.horizontal=1]="horizontal",A[A.vertical=2]="vertical",A))(Qy||{}),Go={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX",SWITCH_PLAYBACK_QUALITY_TIMEOUT:"SWITCH_PLAYBACK_QUALITY_TIMEOUT"},Cc={AVOID_REPEATED_CALL:A=>"previous ".concat(A.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(A){let{key:t,rule:o,fnName:a,value:l}=A;return"'".concat(t||o.name,"' is a required param when calling ").concat(a,"(), received: ").concat(l,".")},INVALID_PARAMETER_TYPE(A){let{key:t,rule:o,fnName:a,value:l}=A,d="".concat(t||o.name),h="";return h=Array.isArray(o.type)?o.type.join("|"):o.type,"'".concat(d,"' must be type of ").concat(h," when calling ").concat(a,"(), received type: ").concat(Qg(l),".")},INVALID_PARAMETER_EMPTY(A){let{key:t,rule:o,fnName:a,value:l}=A;return"'".concat(t||o.name,"' cannot be '").concat(l,"' when calling ").concat(a,"().")},INVALID_PARAMETER_INSTANCE(A){let{key:t,rule:o,fnName:a,value:l}=A,d="".concat(t||o.name),h="".concat(o.instanceOf.name||o.instanceOf);return"'".concat(d,"' must be instanceof ").concat(h," when calling ").concat(a,"(), received type: ").concat(Qg(l),".")},INVALID_PARAMETER_RANGE(A){let{key:t,rule:o,fnName:a,value:l}=A;return"'".concat(t||o.name,"' must be one of ").concat(o.values.join("|")," when calling ").concat(a,"(), received: ").concat(l,".")},INVALID_PARAMETER_MIN(A){let{key:t,rule:o,fnName:a,value:l}=A;return"the min value of ".concat(t||o.name," is ").concat(o.min,", received: ").concat(l,".")},INVALID_PARAMETER_MAX(A){let{key:t,rule:o,fnName:a,value:l}=A;return"the max value of ".concat(t||o.name," is ").concat(o.max,", received: ").concat(l,".")},API_CALL_TIMEOUT:A=>"".concat(A.commandDesc||A.command," timeout observed."),SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:A=>"SignalChannel setup failure: (errorCode: ".concat(A.errorCode,", errorMsg: ").concat(A.errorMsg," })."),ERROR_MESSAGE(A){let t="".concat(A.type," failed");return A.message&&(t="".concat(t,": ").concat(A.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:A=>"exchange sdp failed ".concat(A.errMsg,"."),UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:A=>"'".concat(A,"' must be validate string when useStringRoomId is true."),INVALID_ROOMID_INTEGER:A=>"'".concat(A,"' must be an integer between [1, 4294967294] when useStringRoomId is false."),INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED(A){let{error:t,code:o}=A;return"Failed to join room - ".concat(t," code: ").concat(o)},REJOIN_ROOM_FAILED:A=>"reJoin room: ".concat(A.roomId," failed, please check your network."),INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:A=>"duplicate ".concat(A," stream publishing, please unpublish your prev ").concat(A," stream and then re-publish."),INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED(A){let{message:t,userId:o,streamType:a}=A;return"failed to subscribe ".concat(o," ").concat(a," stream, reason: ").concat(t,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:A=>"switchRole failed, errCode: ".concat(A.code," errMsg: ").concat(A.message,"."),CLIENT_BANNED:A=>"client was banned because of ".concat(A.message,"."),INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:A=>"startPublishCDNStream failed, errMsg: ".concat(A.message,"."),STOP_PUBLISH_CDN_FAILED:A=>"stopPublishCDNStream failed, errMsg: ".concat(A.message,"."),INVALID_STREAM_ID:A=>"'".concat(A,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores."),START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:A=>"cannot replace ".concat(A.kind," track because stream has not ").concat(A.kind," track"),NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:A=>"startMixTranscode failed, errMsg: ".concat(A.message,"."),STOP_MIX_TRANSCODE_FAILED:A=>"stopMixTranscode failed, errMsg: ".concat(A.message,"."),MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO(A){let{key:t,rule:o,fnName:a,value:l}=A;return"'".concat(t||o.name,"' cannot be less than 0 when calling ").concat(a,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:A=>"'".concat(A,"' is required and must be between 1 and 15."),MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:A=>{let{key:t,fnName:o}=A;return"'".concat(t,"' is not found in the document object when calling ").concat(o,"().")},INVALID_ELEMENT_ID_TYPE:A=>{let{key:t,fnName:o,type:a}=A;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(o,"(), received: ").concat(a,".")},PLAY_FAILED:A=>"".concat(A.media," play failed, browser exception: ").concat(A.error.toString()),INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:A=>"".concat(A,"Track is not supported on your browser."),NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:A=>"".concat(A.signalResponse," failed, response code is ").concat(A.code," , errMsg: ").concat(A.message,"."),CATCH_HANDLER_ERROR(A){let{name:t,event:o}=A;return"an error was caught in ".concat(t,".on('").concat(o,"', handler), please check your code in 'handler'.")},API_NOT_EXIST(A){let{name:t}=A;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:A=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED(A){let{funName:t}=A;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:A=>"not support to sendSEIMessage".concat(A===!1?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:A=>{let{isSize:t,name:o,timesInSecond:a,maxSizeInSecond:l}=A;return"api ".concat(o," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(l," bytes"):a," in a second.")},CONNECTION_ABORTED:A=>"connection aborted due to: ".concat(A),API_CALL_ABORTED(A){let t;return t=A.message.includes("REMOTE_STREAM_NOT_EXIST")?"Subscribe ".concat(A.userId," ").concat(A.streamType," stream aborted, reason: remote user ").concat(A.userId," unpublished stream."):"API aborted, reason: ".concat(A.message),t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:A=>"'streamType' is required when 'userId' is not '*', calling ".concat(A,"()"),SWITCH_PLAYBACK_QUALITY_TIMEOUT:A=>"switchPlaybackQuality timeout: waiting for first frame of user ".concat(A.userId,".")},q2=(A,t)=>t?"".concat(zh,"/").concat(A,"/").concat(t):"".concat(zh,"/").concat(A,"/index.html"),Fk=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let A=localStorage==null?void 0:localStorage.getItem($S);if(A){A=JSON.parse(A);let t=document.createElement("script");t.type="text/javascript",t.text=A.message,document.body.appendChild(t);let o=window.TRTC_ERROR_INFO,a=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:o,TRTC_ERROR_LINK:a}}return{}};function sn(A){let{key:t,data:o,link:a,addDocLink:l=!0}=A,d="",h="",y="";ba(Cc[t])?d=Cc[t](o):Ws(Cc[t])&&(d=Cc[t]);let{TRTC_ERROR_INFO:S,TRTC_ERROR_LINK:L}=Fk();a?y="".concat(a.className,".html#").concat(a.fnName):L&&L[t]&&(ba(L[t])?y=L[t](o):Ws(L[t])&&(y=L[t]));let V=d;return Zd()&&(S&&S[t]&&(ba(S[t])?h=S[t](o):Ws(S[t])&&(h=S[t])),h&&(V=l?"".concat(h,` +`}}),Tb=jh(A=>{var t=Vx(),o=Hx();A.write=o,A.parse=t.parse,A.parseParams=t.parseParams,A.parseFmtpConfig=t.parseFmtpConfig,A.parsePayloads=t.parsePayloads,A.parseRemoteCandidates=t.parseRemoteCandidates,A.parseImageAttributes=t.parseImageAttributes,A.parseSimulcastStreamList=t.parseSimulcastStreamList}),_K=dc($l()),zB=((Co=zB||{})[Co.INVALID_PARAMETER=4096]="INVALID_PARAMETER",Co[Co.INVALID_OPERATION=4097]="INVALID_OPERATION",Co[Co.NOT_SUPPORTED=4098]="NOT_SUPPORTED",Co[Co.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",Co[Co.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",Co[Co.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",Co[Co.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",Co[Co.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",Co[Co.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",Co[Co.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",Co[Co.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",Co[Co.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",Co[Co.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",Co[Co.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",Co[Co.CLIENT_BANNED=16448]="CLIENT_BANNED",Co[Co.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",Co[Co.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",Co[Co.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",Co[Co.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",Co[Co.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",Co[Co.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",Co[Co.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",Co[Co.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",Co[Co.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",Co[Co.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",Co[Co.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",Co[Co.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",Co[Co.API_CALL_ABORTED=16461]="API_CALL_ABORTED",Co[Co.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",Co[Co.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",Co[Co.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",Co[Co.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",Co[Co.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",Co[Co.UNKNOWN=65535]="UNKNOWN",Co),mt=zB,Jx=class extends Error{constructor(A){let{name:t="RtcError",message:o,code:a=mt.UNKNOWN,extraCode:l=0,constraint:d}=A,h="<".concat(function(S){for(let L in mt)if(mt[L]===S)return L;return"UNKNOWN"}(a)," 0x").concat(a.toString(16),">"),y="".concat(o).concat(d?" constraint: ".concat(d):"").concat(o!=null&&o.includes(h)?"":" ".concat(h));super(y),Y(this,"code"),Y(this,"extraCode"),Y(this,"message"),Y(this,"originMessage"),Y(this,"name"),Y(this,"constraint"),this.code=a,this.extraCode=l,this.name=t,this.message=y,this.constraint=d,this.originMessage=o}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},li=Jx,Nb=0,qx=!0,ZB=function(A){Nb=A;let t=new Date;t.setTime(t.getTime()+A),pA[qx?"info":"debug"]("baseTime from server: ".concat(t," offset: ").concat(A)),qx=!1},Kx=function(){return Nb},Vf=function(){return Date.now()+Nb},jx=function(){let A=new Date;return A.setTime(Vf()),A.toLocaleString()},Gb=function(A){let t=String(A.getMilliseconds());return"padStart"in String.prototype&&(t=t.toString().padStart(3,"0")),"".concat(A.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(t)},Kd={};Wh(Kd,{REPORT_TYPE:()=>O0,buildSSOPackage:()=>oQ,bytes2ms:()=>N0,calculateScaleResolutionDownNumber:()=>F0,concatArrayBuffers:()=>hv,convertObjectNumberToInt:()=>U0,copyProperties:()=>B2,deepClone:()=>iy,deepCloneBasic:()=>oy,deepMerge:()=>$h,delay:()=>OC,fibonacci:()=>Ay,formatedTime:()=>v2,getConstructorName:()=>Iv,getContainerFromElement:()=>tk,getEnv:()=>d2,getFirst16Bits:()=>R2,getInternalVersion:()=>D2,getLast16Bits:()=>P0,getLoggerUrl:()=>Xf,getMediaStreamTrackInfo:()=>rk,getMuteStateFromFlag:()=>kp,getNetworkType:()=>_0,getNumNetworkType:()=>$f,getReconnectionTimeout:()=>bp,getStringByteLength:()=>L0,getTestSignalDomain:()=>C2,getTurnServer:()=>S2,getUint32Version:()=>ok,getValueType:()=>pg,getViewListFromView:()=>dv,glog:()=>p2,ipv4ToUint32:()=>Ev,isArray:()=>ka,isAudioWorkletSupported:()=>m2,isBoolean:()=>br,isConstructor:()=>ty,isEmpty:()=>b0,isFunction:()=>ba,isLangChinese:()=>Zd,isMediaStreamTrack:()=>Ak,isNumber:()=>Ys,isObject:()=>ed,isOverseaSdkAppId:()=>zd,isPlainObject:()=>uE,isPortrait:()=>ik,isPromise:()=>ey,isRemoteTrack:()=>ek,isRotate90Or270:()=>iQ,isSetSinkIdSupported:()=>f2,isString:()=>Ws,isUndefined:()=>ze,isVideoMixerOutputTrack:()=>Lp,loadImage:()=>Cv,loadVideo:()=>M2,ms2bytes:()=>Q2,ms2samples:()=>G0,normalizeUrl:()=>sk,performanceNow:()=>Oo,promiseAny:()=>uv,samples2ms:()=>$b,setNetworkTypeFromWebRTC:()=>T0,stringify:()=>Xd,stringifyIncludeValue:()=>k0,throttlePromise:()=>nk});var Wx={};Wh(Wx,{ASR_ROBOT_FROM_TYPE:()=>D0,AUDIO_MUTE_BIT:()=>qf,AUDIO_STAT_BIT:()=>iv,AUX_STAT_BIT:()=>tv,AUX_STREAM_MSID:()=>t2,BACKEND_ENV:()=>Hf,BASE_DOC_URL:()=>zh,BASE_HOST:()=>Zx,CAPABILITIES_KEYS:()=>Jb,CLASS_NAME:()=>OK,CLOUD_CONSOLE_URL:()=>GK,CROSS_ROOM_BIT:()=>Ob,DATA_CHANNEL_FROM_TYPE_BIT:()=>AQ,DATA_FREEZE_TIMING:()=>Vb,DOC_BILLING_CN:()=>E0,DOC_BILLING_OVERSEA:()=>Lb,DOC_URL:()=>bK,DTLS_STATE_UNKNOWN:()=>Zh,ENV_NAME:()=>XB,EXCHANGE_SDP_TIMEOUT:()=>r2,IS_WORKER:()=>I0,IS_WORKLET:()=>u0,KIBANA_EVENT:()=>Wa,LOCAL_STREAM_PUBLISH_STATE:()=>a2,LOGGER_CMD_TYPE:()=>OI,LOGGER_DOMAIN:()=>FI,LOGGER_DOMAIN_OVERSEA:()=>_p,LOG_LEVEL:()=>$B,LOG_LEVEL_NAME:()=>xK,MAIN_STREAM_MSID:()=>hu,MAX_RTT:()=>y0,MICROPHONE_COMMUNICATIONS:()=>PK,MICROPHONE_DEFAULT:()=>sv,MUTE_ALL_BIT:()=>e2,NAME:()=>JA,NETWORK_TYPE:()=>d0,NOT_SUPPORTED_H264:()=>m0,PAUSED_RETRY_COUNT:()=>Gp,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Hb,PEER_CONNECTION_STATE:()=>mo,PEER_LEAVE_REASON:()=>l2,RECOVER_CAPTURE_INTERVAL:()=>av,REMOTE_STREAM_TYPE_AUX:()=>Pb,REMOTE_STREAM_TYPE_MAIN:()=>h0,RENDER_FREEZE_TIMING:()=>g2,SCHEDULE_DOMAIN:()=>tQ,SCHEDULE_TIMEOUT:()=>c2,SDP_SEMANTICS_PLAN_B:()=>p0,SDP_SEMANTICS_UNIFIED_PLAN:()=>nv,SECOND_HOST:()=>Xx,SIGNAL_PING_PONG_INTERVAL:()=>IE,SIGNAL_PING_TIMEOUT:()=>$x,SIGNAL_RECONNECTION_COUNT:()=>kK,SMALL_STAT_BIT:()=>Fb,SPEAKER_DEFAULT:()=>f0,STORAGE_EXPIRES_TIME:()=>C0,STREAM_TYPE_BIG:()=>UK,STREAM_TYPE_SMALL:()=>FK,SUBSCRIBE_SMALL_RETRY_COUNT:()=>rv,SYNC_USER_LIST_INTERVAL:()=>LK,Scene:()=>Jf,THIRD_HOST:()=>NK,TRANSPORT_DIRECTION:()=>ir,TRTC_ERROR_ASSISTANCE:()=>$S,TRTC_QUALITY_BAD:()=>Kf,TRTC_QUALITY_DISCONNECTED:()=>n2,TRTC_QUALITY_EXCELLENT:()=>B0,TRTC_QUALITY_GOOD:()=>eQ,TRTC_QUALITY_POOR:()=>i2,TRTC_QUALITY_UNKNOWN:()=>xb,TRTC_QUALITY_VERY_BAD:()=>o2,UPDATE_OFFER_TIMEOUT:()=>s2,VIDEO_MUTE_BIT:()=>ov,VIDEO_STAT_BIT:()=>ev,WEBGL_ATTRIBUTES:()=>qb,audioProfileMap:()=>Tp,defaultBigVideoProfile:()=>Av,defaultSmallVideoProfile:()=>A2,getRetryCount:()=>jf,getScriptDir:()=>TK,innerVersion:()=>l0,loggerProxy:()=>kb,screenProfileMap:()=>Ub,setLoggerProxy:()=>XS,setRetryCount:()=>Q0,setVersion:()=>zx,version:()=>Wd,videoProfileMap:()=>FC});var l0="4.15.00.1600",Wd="5.0.0";function zx(A){Wd=A;let[t,o,a]=A.split(".").map(l=>parseInt(l,10));l0="".concat(t,".").concat(Math.min(15,o),".").concat(Math.min(15,a),".").concat(o.toString().padStart(2,"0")).concat(a.toString().padStart(2,"0"))}var bb,lE,I0=typeof importScripts<"u",u0=typeof registerProcessor<"u",TK=()=>{let A=I0?self.location.href:document.currentScript.src;return A.substring(0,A.lastIndexOf("/")+1)},kb="",XS=A=>kb=A,Zx="web.sdk.qcloud.com",Xx="web.sdk.tencent.cn",NK="web.sdk.cloud.tencent.cn",GK="https://console.cloud.tencent.com/trtc",zh="https://".concat(Zx,"/trtc/webrtc/doc"),bK="".concat(zh,"/zh-cn/"),E0="https://cloud.tencent.com/document/product/647/85386",Lb="https://trtc.io/document/56025",FI="https://yun.tim.qq.com",_p="https://apisgp.my-imcloud.com",$S="trtc_error_assistance",OI={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},XB={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},$B=((lE=$B||{})[lE.TRACE=0]="TRACE",lE[lE.DEBUG=1]="DEBUG",lE[lE.INFO=2]="INFO",lE[lE.WARN=3]="WARN",lE[lE.ERROR=4]="ERROR",lE[lE.NONE=5]="NONE",lE),$x=18e3,IE=2e3,d0={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},C0=6048e5,Tp={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},FC={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},Av=FC["480p_2"],A2=FC["120p_2"],Ub={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},JA={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADSTART:"loadstart",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",FULLSCREEN_CHANGE:"fullscreenchange",RESIZE:"resize",TIME_UPDATE:"timeupdate"},ir={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Hf={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Jf=((bb=Jf||{}).LIVE="live",bb.RTC="rtc",bb),ev=1,Fb=2,tv=4,iv=8,qf=64,ov=16,e2=112,Ob=128,AQ=256,hu="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",t2="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",h0=JA.MAIN,Pb=JA.AUXILIARY,xb=0,B0=1,eQ=2,i2=3,Kf=4,o2=5,n2=6,Zh="unknown",mo={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Yb=1/0;function Q0(A){Yb=A}function jf(){return Yb}var Np,kK=30,Wa={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",VIDEO_ENCODE_RESUME_DURING_CALL:"video-encode-resume-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call",AUDIO_ENCODE_RESUME_DURING_CALL:"audio-encode-resume-during-call",VIDEO_DECODE_FAILED_DURING_CALL:"video-decode-failed-during-call",VIDEO_DECODE_RESUME_DURING_CALL:"video-decode-resume-during-call",AUDIO_DECODE_FAILED_DURING_CALL:"audio-decode-failed-during-call",AUDIO_DECODE_RESUME_DURING_CALL:"audio-decode-resume-during-call",VIDEO_HARDWARE_DECODE_FAILED:"video-hardware-decode-failed",VIDEO_HARDWARE_DECODE_RESUME:"video-hardware-decode-resume"},LK=1e4,s2=1e4,r2=1e4,nv="unified-plan",p0="plan-b",m0=1028,a2=((Np=a2||{})[Np.UNPUBLISH=-1]="UNPUBLISH",Np[Np.PUBLISHING=0]="PUBLISHING",Np[Np.PUBLISHED=1]="PUBLISHED",Np),Vb=500,g2=1e3,UK=JA.BIG,FK=JA.SMALL,Hb=1e4,tQ={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},c2=2e3,OK={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},Gp=5,sv="default",f0=sv,PK="communications",xK=Object.keys($B),l2=["normal leave","timeout leave","kick","role change"],rv=10,av=2e3,Jb=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],y0=1e4,D0=14,qb={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},I2=function(A,t,o,a){return new(o||(o=Promise))(function(l,d){function h(L){try{S(a.next(L))}catch(V){d(V)}}function y(L){try{S(a.throw(L))}catch(V){d(V)}}function S(L){L.done?l(L.value):function(V){return V instanceof o?V:new o(function(H){H(V)})}(L.value).then(h,y)}S((a=a.apply(A,[])).next())})},S0=Symbol(32),v0=Symbol(16),Kb=Symbol(8),Wf=class{constructor(A){this.g=A,this.consumed=0,A&&(this.need=A.next().value)}setG(A){this.g=A,this.demand(A.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(A,t){return t&&this.consume(),this.need=A,this.flush()}read(A){return I2(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((t,o)=>{var a;this.reject=o,this.resolve=l=>{delete this.lastReadPromise,delete this.resolve,delete this.need,t(l)},this.demand(A,!0)||(a=this.pull)===null||a===void 0||a.call(this,A)})})}readU32(){return this.read(S0)}readU16(){return this.read(v0)}readU8(){return this.read(Kb)}close(){var A;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(A=this.reject)===null||A===void 0||A.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let A=null,t=this.buffer.subarray(this.consumed),o=0,a=l=>t.length<(o=l);if(typeof this.need=="number"){if(a(this.need))return;A=t.subarray(0,o)}else if(this.need===S0){if(a(4))return;A=t[0]<<24|t[1]<<16|t[2]<<8|t[3]}else if(this.need===v0){if(a(2))return;A=t[0]<<8|t[1]}else if(this.need===Kb){if(a(1))return;A=t[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(a(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(t.subarray(0,o)),A=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(a(this.need.byteLength))return;new Uint8Array(this.need).set(t.subarray(0,o)),A=this.need}return this.consumed+=o,this.g?this.demand(this.g.next(A).value,!0):this.resolve&&this.resolve(A),A}write(A){if(A instanceof Uint8Array?this.malloc(A.length).set(A):"buffer"in A?this.malloc(A.byteLength).set(new Uint8Array(A.buffer,A.byteOffset,A.byteLength)):this.malloc(A.byteLength).set(new Uint8Array(A)),!this.g&&!this.resolve)return new Promise(t=>this.pull=t);this.flush()}writeU32(A){this.malloc(4).set([A>>24&255,A>>16&255,A>>8&255,255&A]),this.flush()}writeU16(A){this.malloc(2).set([A>>8&255,255&A]),this.flush()}writeU8(A){this.malloc(1)[0]=A,this.flush()}malloc(A){if(this.buffer){let t=this.buffer.length,o=t+A;if(o<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,o);else{let a=new Uint8Array(o);a.set(this.buffer),this.buffer=a}return this.buffer.subarray(t,o)}return this.buffer=new Uint8Array(A),this.buffer}};Wf.U32=S0,Wf.U16=v0,Wf.U8=Kb;var gv=128;function M0(A){let t=new Wf;for(;A>=128;)t.malloc(1)[0]=255&A|gv,A>>>=7;return t.malloc(1)[0]=255&A,t.buffer||new Uint8Array(0)}function R0(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=new Wf,a=t<<3;switch(typeof A){case"boolean":let l=o.malloc(2);l[0]=a,l[1]=A?1:0;break;case"number":o.malloc(1)[0]=a,o.write(M0(A));break;case"string":o.malloc(1)[0]=2|a;let d=new TextEncoder().encode(A);o.write(M0(d.length));let h=o.malloc(d.length);for(let S=0;S>>24&255),this.buffer.push(A>>>16&255),this.buffer.push(A>>>8&255),this.buffer.push(255&A)}writeInt16(A){this.buffer.push(A>>>8&255),this.buffer.push(255&A)}writeByte(A){this.buffer.push(255&A)}writeBytes(A){for(let t=0;t>>24&255,A[o+1]=t>>>16&255,A[o+2]=t>>>8&255,A[o+3]=255&t}function Bu(A,t){return A[t]<<24|A[t+1]<<16|A[t+2]<<8|A[t+3]}function E2(A,t){return A[t]}function Zf(A,t,o){return new TextDecoder().decode(function(a,l,d){return a.slice(l,l+d)}(A,t,o))}var cv=0,jb=2654435769,w0=16,Xh=2,lv=7;function Wb(A,t){let o=new u2,a=function(_e,vi,Fe){let Dt=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"AVQualityReportSvc.C2S";return{version:arguments.length>4&&arguments[4]!==void 0?arguments[4]:2e3,encryption:arguments.length>5&&arguments[5]!==void 0?arguments[5]:2,d2:"",d2Len:0,uinType:arguments.length>6&&arguments[6]!==void 0?arguments[6]:30,uin:"",uinLen:0,reqHead:{seqNumber:Fe,appId:_e,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:Dt,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:vi}}(t,A,cv);cv=cv+1&2147483647,o.writeInt32(0),o.writeInt32(a.version),o.writeByte(a.encryption);let l=new TextEncoder().encode(a.d2);o.writeInt32(l.length+4),l&&o.writeBytes(l),o.writeByte(a.uinType);let d=new TextEncoder().encode(a.uin);o.writeInt32(d.length+4),d.length&&o.writeBytes(d);let h=new u2;h.writeInt32(0),h.writeInt32(a.reqHead.seqNumber),h.writeInt32(a.reqHead.appId),h.writeByte(a.reqHead.appId>>>24&255),h.writeByte(a.reqHead.appId>>>16&255),h.writeByte(a.reqHead.appId>>>8&255),h.writeByte(255&a.reqHead.appId);for(let _e=4;_e<16;_e++)h.writeByte(0);let y=new TextEncoder().encode(a.reqHead.a2);h.writeInt32(y.length+4),y.length&&h.writeBytes(y);let S=new TextEncoder().encode(a.reqHead.serviceCmd);h.writeInt32(S.length+4),S.length&&h.writeBytes(S);let L=new TextEncoder().encode(a.reqHead.cookie);h.writeInt32(L.length+4),L.length&&h.writeBytes(L);let V=new TextEncoder().encode(a.reqHead.imei);h.writeInt32(V.length+4),V.length&&h.writeBytes(V);let H=new TextEncoder().encode(a.reqHead.ksid);h.writeInt32(H.length+4),H.length&&h.writeBytes(H);let lA=new TextEncoder().encode(a.reqHead.clientVersionInfo);h.writeInt16(lA.length+2),lA.length&&h.writeBytes(lA);let hA=h.length;h.data[0]=hA>>>24&255,h.data[1]=hA>>>16&255,h.data[2]=hA>>>8&255,h.data[3]=255&hA,Ws(A)&&(A=new TextEncoder().encode(A)),h.writeInt32(A.length+4),A.length&&h.writeBytes(A);let MA=new Uint8Array(h.data),oe=null;a.encryption===1?oe=new TextEncoder().encode(a.uin):a.encryption===2&&(oe=new Uint8Array(16)),oe&&(MA=function(_e,vi){let Fe=_e.length,Dt=(Fe+1+Xh+lv)%8;Dt&&(Dt=8-Dt);let pi=Fe+1+Xh+lv+Dt,Mi=new Uint8Array(pi),Wo=0,zo=new Uint8Array(8),vs=new Uint8Array(8),Zo=new Uint8Array(8),Vn=0;zo[0]=248&Math.floor(256*Math.random())|Dt,Vn=1;for(let wa=0;wa>>24&255,fe[1]=je>>>16&255,fe[2]=je>>>8&255,fe[3]=255&je,fe}function zb(A,t,o,a,l,d){for(let h=0;h<8;h++)A[h]^=a[h];(function(h,y,S,L){let V=Bu(h,0),H=Bu(h,4),lA=[];for(let MA=0;MA<4;MA++)lA[MA]=Bu(y,4*MA);let hA=0;for(let MA=0;MA>>=0,V+=(H<<4)+lA[0]^H+hA^(H>>>5)+lA[1],V>>>=0,H+=(V<<4)+lA[2]^V+hA^(V>>>5)+lA[3],H>>>=0;zf(S,V,L),zf(S,H,L+4)})(A,t,l,d);for(let h=0;h<8;h++)l[d+h]^=o[h];for(let h=0;h<8;h++)o[h]=A[h]}var d2=function(){return new URLSearchParams(location.search).get("trtc_env")||""},C2=function(A){return A.includes(".")?A:"".concat(A).concat(".rtc.qq.com")},zd=A=>Number(A)<14e8,Xf=function(A,t){let o;o=kb||(zd(A)?_p:FI);let a=Math.floor(Math.random()*zS(2,31));return"".concat(o,"/v5/AVQualityReportSvc/C2S?random=").concat(a,"&sdkappid=").concat(A,"&cmdtype=").concat(t)},Zb="unknown";function _0(){(function(){var d;h2||(h2=!0,(d=navigator.connection)==null||d.addEventListener("typechange",YK))})();let{userAgent:A,connection:t}=navigator,o=(A.match(/NetType\/\S+/)||[])[0]||"";o=o.toLowerCase().replace("nettype/",""),o==="3gnet"&&(o="3g");let a=t&&t.type&&t.type.toLowerCase(),l=t&&t.effectiveType&&t.effectiveType.toLowerCase();return l==="slow-2"&&(l="2g"),a?Xb(a,l):Zb}function YK(){pA.warn("netType changed",_0())}var h2=!1;function Xb(A,t){if(d0[A])return A;switch(A){case"cellular":case"wimax":return t||"unknown";case"ethernet":return"wired";default:return"unknown"}}function T0(A){Zb=Xb(A)}function $f(){return d0[_0()]}function B2(A,t){for(let o of Reflect.ownKeys(t))if(o!=="constructor"&&o!=="prototype"&&o!=="name"){let a=Object.getOwnPropertyDescriptor(t,o)||"";Object.defineProperty(A,o,a)}return A}function N0(A){return $b(A/4,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function $b(A){return 1e3*A/(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function Q2(A){return 4*G0(A,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function G0(A){return A*(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)/1e3}var p2=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},Zd=()=>{let A=navigator.language;return A=A.substring(0,2),A==="zh"},uE=function(A){if(!A||typeof A!="object"||Object.prototype.toString.call(A)!="[object Object]")return!1;let t=Object.getPrototypeOf(A);if(t===null)return!0;let o=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof o=="function"&&o instanceof o&&Function.prototype.toString.call(o)===Function.prototype.toString.call(Object)};function Ay(A){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;return A<=1?t:Ay(A-1,t,(arguments.length>1&&arguments[1]!==void 0?arguments[1]:1)+t)}function bp(A){return A>8?3e4:1e3*Ay(A)}function pg(A){return Reflect.apply(Object.prototype.toString,A,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ba=A=>typeof A=="function",ze=A=>A===void 0,Ws=A=>typeof A=="string",Ys=A=>typeof A=="number",br=A=>typeof A=="boolean",ed=A=>pg(A)==="object",ka=A=>pg(A)==="array",Ak=A=>pg(A)==="MediaStreamTrack".toLowerCase(),ek=A=>A.isRemote,ey=A=>pg(A)==="promise",ty=A=>ba(A)&&A.prototype.constructor===A,Iv=A=>ty(A)?A.prototype.constructor.name:"",m2=typeof AudioWorkletNode<"u",f2=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype;function uv(A){return new Promise((t,o)=>{let a=[];A.forEach(l=>{l.then(t).catch(d=>{a.push(d),a.length===A.length&&o(a)})})})}function Oo(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var y2=A=>+A<10?"0".concat(A):A,D2=A=>{let t=A.match(/^\d+\.\d+\.\d+/)[0];if(!t)return A;let o=t.split("."),a=y2(o[1])+y2(o[2]);return o[1]-15>0&&(o[1]="15"),o[2]-15>0&&(o[2]="15"),"".concat(o.join("."),".").concat(a)},VK=Object.prototype.hasOwnProperty;function b0(A){if(A==null)return!0;if(typeof A=="boolean")return!1;if(typeof A=="number")return A===0;if(typeof A=="string"||typeof A=="function"||Array.isArray(A))return A.length===0;if(A instanceof Error)return A.message==="";if(uE(A))switch(Object.prototype.toString.call(A)){case"[object File]":case"[object Map]":case"[object Set]":return A.size===0;case"[object Object]":for(let t in A)if(VK.call(A,t))return!1;return!0}return!1}function kp(A,t){return{userId:t,hasAudio:!!(A&iv),hasVideo:!!(A&ev),hasAuxiliary:!!(A&tv),hasSmall:!!(A&Fb),audioMuted:!!(A&qf),videoMuted:!!(A&ov),audioAvailable:!(!(A&iv)||A&qf),videoAvailable:!(!(A&ev)||A&ov),hasDatachannel:!!(A&AQ)}}function S2(A){let t={urls:A.url.startsWith("turn:")||A.url.startsWith("turns:")?A.url:"turn:".concat(A.url)};return!ze(A.username)&&!ze(A.credential)&&(t.username=A.username,t.credential=A.credential,t.credentialType="password",ze(A.credentialType)||(t.credentialType=A.credentialType)),t}function Ev(A){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(!Ws(A))return 0;let o=A.split(".");return t?(Number(o[0])<<24|Number(o[1])<<16|Number(o[2])<<8|Number(o[3]))>>>0:(Number(o[3])<<24|Number(o[2])<<16|Number(o[1])<<8|Number(o[0]))>>>0}var $h=function(A,t,o,a){if(!ed(A)||!ed(t))return 0;let l,d=0,h=Object.keys(t);for(let y=0,S=h.length;y{t[a]=iy(o)}),t}if(ed(A)){let t={};return Object.keys(A).forEach(o=>{t[o]=iy(A[o])}),t}return A}var dv=A=>{let t=[];if(ka(A))t=[...A];else if(Ws(A)){let o=document.getElementById(A);o&&t.push(o)}else A&&t.push(A);return t},tk=A=>Ws(A)?document.getElementById(A):A,v2=()=>(A=>{let t=S=>S<10?"0".concat(S):"".concat(S),o=A.getFullYear(),a=A.getMonth()+1,l=A.getDate(),d=t(A.getHours()),h=t(A.getMinutes()),y=t(A.getSeconds());return"".concat(o,"/").concat(a,"/").concat(l," ").concat(d,":").concat(h,":").concat(y)})(new Date);function Xd(A,t){let{keysToInclude:o,keysToExclude:a}=t;try{if(ka(A))return"[".concat(A.map(y=>Xd(y,{keysToInclude:o,keysToExclude:a})).join(","),"]");if(!uE(A)||!ka(o)&&!ka(a))return JSON.stringify(A);let l={},d=new Set(o),h=new Set(a);return Object.keys(A).forEach(y=>{(h.size===0&&d.has(y)||d.size===0&&!h.has(y))&&(l[y]=uE(A[y])||ka(A[y])?JSON.parse(Xd(A[y],{keysToExclude:a,keysToInclude:o})):A[y])}),JSON.stringify(l)}catch{return"{}"}}function k0(A){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],o=[];return Object.keys(A).forEach(a=>{t===A[a]&&o.push(a)}),Xd(A,{keysToInclude:o})}function L0(A){return A.replace(/[\u4e00-\u9fa5]/g,"aa").length}var ik=()=>{var A,t,o,a;return(A=window.screen)!=null&&A.orientation?!((a=(o=(t=window.screen)==null?void 0:t.orientation)==null?void 0:o.type)==null||!a.includes("portrait")):window.orientation===0||window.orientation===180},Cv=A=>XA(null,null,function*(){return new Promise((t,o)=>{let a;if(Ws(A))a=new Image,a.crossOrigin="anonymous",a.src=A;else if(a=A,a.complete)return void t(a);a.onload=()=>t(a),a.onerror=()=>{o(new li({code:mt.INVALID_PARAMETER,message:"load image failed, url: ".concat(A)}))}})}),ok=A=>{let t=A.split(".");return+t[0]<<24|+t[1]<<16|+t[2]<<8|+t[3]},U0=A=>(Object.keys(A).forEach(t=>{Ys(A[t])&&(t.startsWith("uint")||t.startsWith("int"))?A[t]=Math.floor(A[t]):(uE(A[t])||ka(A[t]))&&U0(A[t])}),A);function OC(A,t){return new Promise(o=>{let a=setTimeout(o,A);t&&t(a)})}function nk(A,t){let o=null;return function(){for(var a=arguments.length,l=new Array(a),d=0;do=null),o)}}function sk(A){return A.replace(/(^|[^:])\/{2,}/g,"$1/")}function rk(A){var t;try{let{width:o,height:a,frameRate:l,sampleRate:d,sampleSize:h,channelCount:y}=(t=A.getSettings)==null?void 0:t.call(A),S=A.kind===JA.AUDIO?"".concat(d,"x").concat(h,"@").concat(y):"".concat(o,"x").concat(a,"@").concat(l),L=A.stats?" stats: ".concat(JSON.stringify(A.stats).replaceAll('"',"")):"";return"".concat(A.id," ").concat(A.readyState," muted:").concat(A.muted," ").concat(A.kind," ").concat(A.label," ").concat(S).concat(L)}catch{return""}}function F0(A,t){return A.width*A.height===t.width*t.height?1:ik()&&t.width>t.height&&A.height>t.width?Math.max(A.width/t.height,A.height/t.width,1):Math.max(A.width/t.width,A.height/t.height,1)}function iQ(A){return A===90||A===270}function M2(A){return XA(this,null,function*(){return new Promise((t,o)=>{let a=document.createElement("video");a.crossOrigin="anonymous",a.src=A,a.muted=!0,a.loop=!0,a.playsInline=!0,a.play().then(()=>t(a)),a.onerror=()=>{o(a.error)}})})}function oy(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:new WeakMap;if(typeof A!="object"||A===null)return A;if(t.has(A))return t.get(A);if(Array.isArray(A)){let o=[];return t.set(A,o),A.forEach((a,l)=>{o[l]=oy(a,t)}),o}if(Object.prototype.toString.call(A)==="[object Object]"){let o={};return t.set(A,o),Reflect.ownKeys(A).forEach(a=>{o[a]=oy(A[a],t)}),o}return A}var O0=(A=>(A[A.END_REPORT=2001]="END_REPORT",A[A.LOG=2002]="LOG",A[A.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",A))(O0||{});function oQ(A,t,o,a){try{let l=function(d,h,y,S){let L={data:d,random:Math.floor(2147483648*Math.random()),sdkAppId:y};return ze(S)||(L=So(Di({},L),{gzip:+S})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:h,bytes_report_data:JSON.stringify(L)}}}(A,t,o,a);return Wb(R0(l),o)}catch{return JSON.stringify(A)}}function hv(A,t){let o=new Uint8Array(A.byteLength+t.byteLength);return o.set(new Uint8Array(A),0),o.set(new Uint8Array(t),A.byteLength),o.buffer}function P0(A){return(65535&A)>>>0}function R2(A){return(4294901760&A)>>>0}function Lp(A){return!!(A&&A instanceof CanvasCaptureMediaStreamTrack&&A.canvas.id.includes("trtc_mix"))}function HK(A){let t=function(o){try{let a={},l=0;a.totalLength=Bu(o,l),l+=4,a.version=Bu(o,l),l+=4,a.encryption=E2(o,l),l+=1,a.uinType=E2(o,l),l+=1,a.uinLength=Bu(o,l),l+=4,a.uin=a.uinLength>4?Zf(o,l,a.uinLength-4):"",l+=a.uinLength-4;let d=o.slice(l);return a.encryption===2?(o=function(h,y){let S=0,L=new Uint8Array(8).fill(0),V=new Uint8Array(h.slice(0,8)),H=x0(V,y),lA=7&H[0],hA=h.length-1-lA-Xh-lv,MA=new Uint8Array(hA),oe=0,fe=L,je=h.slice(0,8);S=8;let _e=1;_e+=lA;for(let Fe=1;Fe<=Xh;)if(_e<8)_e++,Fe++;else if(_e===8){let Dt=ny(h,S,fe,je,H,y);fe=Dt.ivPreCrypt,je=Dt.ivCurCrypt,H=Dt.debiBuf,S=Dt.bufPos,_e=0}let vi=hA;for(;vi>0;)if(_e<8)MA[oe++]=H[_e]^fe[_e],_e++,vi--;else if(_e===8){let Fe=ny(h,S,fe,je,H,y);fe=Fe.ivPreCrypt,je=Fe.ivCurCrypt,H=Fe.debiBuf,S=Fe.bufPos,_e=0}for(let Fe=1;Fe<=lv;)if(_e<8)H[_e],fe[_e],_e++,Fe++;else if(_e===8){if(S>=h.length)break;let Dt=ny(h,S,fe,je,H,y);if(!Dt.success)break;fe=Dt.ivPreCrypt,je=Dt.ivCurCrypt,H=Dt.debiBuf,S=Dt.bufPos,_e=0}return MA}(d,new Uint8Array(16).fill(0)),a.decrypted=!0,l=0):(o=d,l=0),a.rspHeadLength=Bu(o,l),l+=4,a.seqNo=Bu(o,l),l+=4,a.retCode=Bu(o,l),l+=4,a.retStrLength=Bu(o,l),l+=4,a.retStr=a.retStrLength?Zf(o,l,a.retStrLength-4):"",l+=a.retStrLength-4,a.serviceCmdLength=Bu(o,l),l+=4,a.serviceCmd=a.serviceCmdLength?Zf(o,l,a.serviceCmdLength-4):"",l+=a.serviceCmdLength-4,a.cookieLength=Bu(o,l),l+=4,a.cookie=a.cookieLength?Zf(o,l,a.cookieLength-4):"",l+=a.cookieLength-4,a.flag=Bu(o,l),l+=4,a.busiBuffLength=Bu(o,l),l+=4,a.busiBuff=a.busiBuffLength?Zf(o,l,a.busiBuffLength-4):"",l+=a.busiBuffLength-4,a}catch{}}(A);return t?.busiBuff}function x0(A,t){let o=A[0]<<24|A[1]<<16|A[2]<<8|A[3],a=A[4]<<24|A[5]<<16|A[6]<<8|A[7];o>>>=0,a>>>=0;let l=jb*w0>>>0;for(let d=0;d>>5)+t[3],a>>>=0,o-=(a<<4)+t[0]^a+l^(a>>>5)+t[1],o>>>=0,l-=jb,l>>>=0;return new Uint8Array([o>>>24&255,o>>>16&255,o>>>8&255,255&o,a>>>24&255,a>>>16&255,a>>>8&255,255&a])}function ny(A,t,o,a,l,d){if(t+8>A.length)return{success:!1};let h=new Uint8Array(a),y=A.slice(t,t+8),S=new Uint8Array(8);for(let L=0;L<8;L++)S[L]=l[L]^y[L];return{success:!0,ivPreCrypt:h,ivCurCrypt:y,debiBuf:x0(S,d),bufPos:t+8}}var Up=typeof TextDecoder<"u"?new TextDecoder:void 0;function nQ(A){let{url:t,body:o,method:a="POST",timeout:l,priority:d}=A;return new Promise((h,y)=>{if("fetch"in window)return fetch(t,{method:a,body:o,priority:d}).then(L=>L.clone().json().then(V=>({data:V}),()=>L.arrayBuffer().then(V=>({data:HK(new Uint8Array(V))||(Up?Up.decode(V):V)})))).then(h,y);let S=new XMLHttpRequest;S.onreadystatechange=()=>{if(S.readyState===4)if(S.status>=200&&S.status<300)try{let L=JSON.parse(S.response);h({data:L})}catch{h({data:S.response})}else y({status:S.status,statusText:S.statusText||"request failed!"})},S.timeout=l||5e3,S.open(a,t,!0),S.send(o)})}function ak(A){return XA(this,null,function*(){let t=Oo(),o=JSON.stringify(A);try{if(!CompressionStream||o.length<=2800)return o;let a=new Blob([o],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),l=yield(yield(yield new Response(a)).blob()).arrayBuffer();return pA.debug("compressJSON ".concat(o.length," -> ").concat(l.byteLength," ").concat(Oo()-t,"ms")),l}catch{return o}})}var w2=Object.prototype.hasOwnProperty,Fp=A=>typeof A=="function",td=A=>A===void 0,gk=A=>typeof A=="string",_2=A=>typeof A=="boolean",ck=A=>A.isRemote,T2=function(A){if(!A||typeof A!="object"||Object.prototype.toString.call(A)!="[object Object]")return!1;let t=Object.getPrototypeOf(A);if(t===null)return!0;let o=Object.prototype.hasOwnProperty.call(t,"constructor")&&t.constructor;return typeof o=="function"&&o instanceof o&&Function.prototype.toString.call(o)===Function.prototype.toString.call(Object)},Bv=function(A){let{retryFunction:t,settings:o,onError:a,onRetrying:l,onRetryFailed:d,onRetrySuccess:h,context:y}=A;return function(){for(var S=arguments.length,L=new Array(S),V=0;VXA(this,null,function*(){let vi=y||this;try{let Fe=yield t.apply(vi,L);hA>0&&h&&h.call(this,hA),hA=0,je(Fe)}catch(Fe){let Dt=()=>{clearTimeout(MA),hA=0,oe=2,_e(Fe)},pi=()=>{oe!==2&&hA<(Fp(H)?H():H)?(hA++,oe=1,Fp(l)&&l.call(this,hA,Dt),MA=window.setTimeout(()=>{MA=-1,fe(je,_e)},Fp(lA)?lA(hA):lA)):(Dt(),Fp(d)&&d.call(this,Fe))};Fp(a)?a.call(this,{error:Fe,retry:pi,reject:_e,retryFuncArgs:L,retriedCount:hA}):pi()}});return new Promise(fe)}},lk=class hX{constructor(t){Y(this,"_parentPath"),Y(this,"userId"),Y(this,"remoteUserId"),Y(this,"id"),Y(this,"sdkAppId"),Y(this,"type"),Y(this,"isLocal"),this.id=t.id,this.userId=t.userId,this.sdkAppId=t.sdkAppId,this.remoteUserId=t.remoteUserId,this.isLocal=!_2(t.isLocal)||t.isLocal,this.type=this.isLocal?"":t.type}getFullId(){return this._parentPath&&this.id?"".concat(this._parentPath,"-").concat(this.id):this._parentPath?this._parentPath:this.id}createChild(t){let o=new hX({id:t.id,userId:td(t.userId)?this.userId:t.userId,sdkAppId:td(t.sdkAppId)?this.sdkAppId:t.sdkAppId,type:td(t.type)?this.type:t.type,isLocal:td(t.isLocal)?this.isLocal:t.isLocal,remoteUserId:td(t.remoteUserId)?this.remoteUserId:t.remoteUserId});return o.bindParent(this),o}bindParent(t){let o=t.getFullId();this._parentPath!==o&&(this.debug("bind logger parent: ".concat(t.id)),this._parentPath=o,this.userId=t.userId||this.userId,this.sdkAppId=t.sdkAppId||this.sdkAppId)}setUserId(t){this.userId=t}setSdkAppId(t){this.sdkAppId=t}log(t,o){let a=this.isLocal?this.userId:this.remoteUserId,l=this.getFullId();o.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&this.type!=="main"?"*":"").concat(l).concat(a?"|".concat(a):"","]")),pA.log(t,o,td(this.userId)||function(d){if(d==null)return!0;if(typeof d=="boolean")return!1;if(typeof d=="number")return d===0;if(typeof d=="string"||typeof d=="function"||Array.isArray(d))return d.length===0;if(d instanceof Error)return d.message==="";if(T2(d))switch(Object.prototype.toString.call(d)){case"[object File]":case"[object Map]":case"[object Set]":return d.size===0;case"[object Object]":for(let h in d)if(w2.call(d,h))return!1;return!0}return!1}(this.userId),this.userId,this.sdkAppId)}info(){for(var t=arguments.length,o=new Array(t),a=0;aH0,CHROME_MAJOR_VERSION:()=>nd,CHROME_VERSION:()=>A_,EDGE_VERSION:()=>uk,EDG_MAJOR_VERSION:()=>q0,EDG_VERSION:()=>Ek,ELECTRON_MAJOR_VERSION:()=>O2,FIREFOX_MAJOR_VERSION:()=>J0,FIREFOX_VERSION:()=>pv,HUAWEI_VERSION:()=>Sk,IE_VERSION:()=>KK,IOS_MAIN_VERSION:()=>$d,IOS_VERSION:()=>PI,IPADQQB_VERSION:()=>Dv,IS_ANDROID:()=>za,IS_ANDROID_WEBVIEW:()=>Rk,IS_ANY_SAFARI:()=>Hp,IS_CHROME:()=>$0,IS_CHROME_OS:()=>mk,IS_CHROMIUM_128_TO_143:()=>Iy,IS_CHROMIUM_BASE:()=>EE,IS_DESKTOP_IOS_CHROME:()=>Y2,IS_EDG:()=>ry,IS_EDGE:()=>sy,IS_ELECTRON:()=>jK,IS_FIREFOX:()=>gr,IS_HEADLESS_CHROME:()=>F2,IS_HONOR:()=>Dk,IS_HUAWEI:()=>yk,IS_HUAWEIBROWSER:()=>AB,IS_IE:()=>L2,IS_IE8:()=>qK,IS_IOS:()=>ng,IS_IOS_13_OR_14:()=>x2,IS_IOS_15_1:()=>P2,IS_IOS_CHROME:()=>_v,IS_IPAD:()=>Op,IS_IPADQQB:()=>z0,IS_IPAD_PRO:()=>V0,IS_IPHONE:()=>Pp,IS_IPOD:()=>b2,IS_LINUX:()=>cy,IS_LOCAL:()=>Jp,IS_MAC:()=>rQ,IS_MACQQB:()=>yv,IS_MIBROWSER:()=>Z0,IS_MQQB:()=>fv,IS_NATIVE_ANDROID:()=>k2,IS_OLD_ANDROID:()=>JK,IS_OPENHARMONY:()=>ly,IS_OPPOBROWSER:()=>vv,IS_SAFARI:()=>fg,IS_SAFARI_15_1:()=>WK,IS_SAMSUNGBROWSER:()=>Sv,IS_SOGOU:()=>j0,IS_SOGOUM:()=>mv,IS_TBS:()=>od,IS_UCBROWSER:()=>fk,IS_VIVOBROWSER:()=>Mv,IS_WECHAT:()=>sQ,IS_WIN:()=>gy,IS_WQQB:()=>W0,IS_WX:()=>U2,IS_X5MQQB:()=>Yp,IS_XWEB:()=>xp,MACQQB_VERSION:()=>pk,MI_VERSION:()=>Vp,MQQB_VERSION:()=>ay,OPENHARMONY_VERSION:()=>X0,OPPO_VERSION:()=>Mk,SAFARI_VERSION:()=>aQ,SAMSUNG_VERSION:()=>vk,SOGOUM_VERSION:()=>K0,SOGOU_VERSION:()=>dk,TBS_VERSION:()=>Ck,UA_DATA_STRING:()=>PC,USER_AGENT:()=>id,VIVO_VERSION:()=>Rv,WECHAT_VERSION:()=>Bk,WQQB_VERSION:()=>Qk,XWEB_VERSION:()=>hk,browserInfo:()=>cQ,getBrowserCoreNumber:()=>AI,getBrowserInfo:()=>_k,getChromeMajorVersion:()=>wv,getDeviceModel:()=>lQ,getDeviceModelFromUA:()=>Tk,getGPUInfo:()=>qp,getOSName:()=>pl,getOSNumber:()=>Kp,getOSString:()=>jp,getOSType:()=>Q,getTerminalType:()=>ys,getUserAgentData:()=>Tv,isAMDGPU:()=>Ey,isAppleSiliconGPU:()=>zK,isLocalStorageEnabled:()=>gQ,isMobile:()=>e_,isNvidiaGPU:()=>V2,isRealIOS:()=>Qv,isVersionLargerThan:()=>uy,isVersionSmallerThan:()=>wk});var id=typeof navigator>"u"?"":navigator.userAgent,Yn=A=>new RegExp(A,"i").test(id),mg=A=>{if(Yn(A)){let t=new RegExp("".concat(A,"\\/([\\d.]+)")),o=id.match(t);if(o&&o[1])return o[1]}return""},Y0=A=>{if(Yn(A)){let t=new RegExp("".concat(A,"\\/(\\d+)")),o=id.match(t);if(o&&o[1])return parseFloat(o[1])}return NaN},Ik=/AppleWebKit\/([\d.]+)/i.exec(id),G2=Ik?parseFloat(Ik[1]):NaN,Op=Yn("iPad"),V0=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Yn("Macintosh"),Pp=Yn("iPhone")&&!Op,b2=Yn("iPod"),ng=Pp||Op||b2||V0,Qv=()=>{try{return ng&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch{return ng}},za=Yn("Android"),H0=function(){if(za){let A=id.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(A){let t=A[1]&&parseFloat(A[1]),o=A[2]&&parseFloat(A[2]);if(t&&o)return parseFloat("".concat(A[1],".").concat(A[2]));if(t)return t}}return NaN}(),JK=za&&Yn("webkit")&&H0<2.3,k2=za&&H0<5&&G2<537,gr=Yn("Firefox"),pv=mg("Firefox"),J0=Y0("Firefox"),sy=Yn("Edge"),uk=mg("Edge"),ry=Yn("Edg"),Ek=mg("Edg"),q0=Y0("Edg"),mv=Yn("SogouMobileBrowser"),K0=mg("SogouMobileBrowser"),j0=Yn("MetaSr\\s"),dk=mg("MetaSr\\s"),od=Yn("TBS"),Ck=mg("TBS"),xp=Yn("XWEB"),hk=mg("XWEB"),qK=Yn("MSIE\\s8\\.0"),L2=Yn("MSIE\\/\\d+"),KK=function(){if(L2){let A=/MSIE\s(\d+)\.\d/.exec(id),t=A&&parseFloat(A[1]);return!t&&/Trident\/7.0/i.test(id)&&/rv:11.0/.test(id)&&(t=11),t}return NaN}(),sQ=Yn("(micromessenger|webbrowser)"),Bk=mg("MicroMessenger"),Yp=!od&&Yn("MQQBrowser")&&Yn("COVC"),fv=!od&&Yn("MQQBrowser")&&!Yn("COVC"),ay=fv||Yp?mg("MQQBrowser"):"",W0=!od&&Yn(" QQBrowser"),Qk=mg(" QQBrowser"),yv=!od&&Yn("QQBrowserLite"),pk=mg("QQBrowserLite"),z0=!od&&Yn("MQBHD"),Dv=mg("MQBHD"),gy=Yn("Windows"),rQ=!ng&&Yn("MAC OS X"),cy=!za&&Yn("Linux"),mk=Yn("CrOS"),U2=Yn("MicroMessenger"),fk=Yn("UCBrowser"),jK=Yn("Electron"),Z0=Yn("MiuiBrowser"),Vp=mg("MiuiBrowser"),AB=Yn("HuaweiBrowser"),yk=Yn("Huawei")||Yn("HUAWEI"),Dk=Yn("Honor")||Yn("HONOR"),Sk=mg("HuaweiBrowser"),Sv=Yn("SamsungBrowser"),vk=mg("SamsungBrowser"),vv=Yn("HeyTapBrowser"),Mk=mg("HeyTapBrowser"),Mv=Yn("VivoBrowser"),Rv=mg("VivoBrowser"),ly=Yn("OpenHarmony"),X0=mg("OpenHarmony"),wv=()=>Y0("Chrome"),_v=Yn("CriOS"),EE=Yn("Chrome"),$0=!sy&&!j0&&!mv&&!od&&!xp&&!ry&&!W0&&!Z0&&!AB&&!Sv&&!vv&&!Mv&&EE,F2=Yn("HeadlessChrome"),nd=wv(),Iy=EE&&nd>=128&&nd<=143,A_=mg("Chrome"),O2=Y0("Electron"),fg=!EE&&!fv&&!Yp&&!yv&&!z0&&Yn("Safari"),Hp=fg||ng,aQ=mg("Version"),Rk=/Android.*(wv|.0.0.0)/.test(id),PI=(()=>{if(V0)return aQ;if(ng){let A=id.match(/OS (\d+)_(\d+)/i);if(A&&A[1]){let t=A[1];return A[2]&&(t+=".".concat(A[2])),t}}return""})();function wk(A,t){let o=A.split(".").map(l=>Number(l)),a=t.split(".").map(l=>Number(l));for(let l=0;lh)return!1}return!1}function uy(A,t){let o=arguments.length>2&&arguments[2]!==void 0&&arguments[2],a=A.split(".").map(d=>Number(d)),l=t.split(".").map(d=>Number(d));for(let d=0;dy)return!0;if(h{let A=Number(PI.split(".")[0]);return A===14||A===13})(),Y2=_v&&aQ==="11.1.1",Jp=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),gQ=(()=>{let A;return()=>{if(A===void 0)try{A=!!window.localStorage}catch{A=!1}return A}})(),cQ=_k();function _k(){let A=new Map([[gr,["Firefox",pv]],[ry,["Edg",Ek]],[$0,["Chrome",A_]],[_v,["ChiOS",mg("CriOS")]],[fg&&!_v,["Safari",aQ]],[od,["TBS",Ck]],[xp,["XWEB",hk]],[sQ&&Pp,["WeChat",Bk]],[W0,["QQ(Win)",Qk]],[fv,["QQ(Mobile)",ay]],[Yp,["QQ(Mobile X5)",ay]],[yv,["QQ(Mac)",pk]],[z0,["QQ(iPad)",Dv]],[Z0,["MI",Vp]],[AB,["HW",Sk]],[Sv,["Samsung",vk]],[vv,["OPPO",Mk]],[Mv,["VIVO",Rv]],[sy,["EDGE",uk]],[mv,["SogouMobile",K0]],[j0,["Sogou",dk]]]),t="unknown",o="unknown";return A.has(!0)&&([t,o]=A.get(!0)),{name:t,version:o}}var Hr=null;function e_(){return Hr&&typeof Hr.mobile=="boolean"?Hr.mobile:za||ng||Pp||Op||ly}var PC="";function Tv(){return XA(this,null,function*(){if(Hr)return Hr;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return(Hr=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!PC&&(PC="UAData: ".concat(Hr.platform,"/").concat(Hr.platformVersion),Hr.architecture&&Hr.bitness&&(PC+=" ".concat(Hr.architecture,"/").concat(Hr.bitness)),Hr.mobile&&(PC+=" mobile"),Hr.model&&(PC+=" model: ".concat(Hr.model.replace(/\s+/g,"/"))),Hr.fullVersionList&&(PC+=" ".concat(Hr.fullVersionList.filter(A=>A.brand!=="Not/A)Brand").map(A=>"".concat(A.brand,"/").concat(A.version)).join(",")))),Hr}catch{return null}})}var Nv="";function qp(){try{if(Nv)return Nv;let A=document.createElement("canvas"),t=A.getContext("webgl")||A.getContext("experimental-webgl");if(!t)return"";let o=t.getExtension("WEBGL_debug_renderer_info");if(o){let a=t.getParameter(o.UNMASKED_VENDOR_WEBGL),l=t.getParameter(o.UNMASKED_RENDERER_WEBGL);return Nv="".concat(a," ").concat(l)}return""}catch{return""}}function Ey(){try{let A=qp();return A.includes("AMD")||A.includes("ATI")}catch{return!1}}function V2(){try{let A=qp();return A.includes("NVIDIA")||A.includes("GeForce")}catch{return!1}}function zK(){try{return qp().includes("Apple M")}catch{return!1}}function lQ(){return Hr?.model||Tk()||""}function Tk(){let A=id.match(/;\s*([^;)]+)\s+Build\//);return A!=null&&A[1]?A[1].trim():null}var H2=new Map([[za,"Android"],[ng,"iOS"],[gy,"Windows"],[rQ,"MacOS"],[cy,"Linux"],[mk,"ChromeOS"]]),pl=function(){return H2.get(!0)?H2.get(!0):Hr?Hr.platform:"unknown"};function Kp(){return gy?1:za?2:rQ?3:ng?4:cy?5:mk?6:ly?7:0}function AI(){return sQ||xp?4:EE?1:fg?2:gr?3:0}var jp=()=>{let A=pl();return Hr!=null&&Hr.platformVersion?A+="/".concat(Hr.platformVersion):ng?A+="/".concat(PI):za&&(A+="/".concat(H0)),A+="/".concat(cQ.name,"/").concat(fg&&!_v?cQ.version:cQ.version.split(".")[0]),Hr!=null&&Hr.architecture&&(A+="/".concat(Hr.architecture)),A};function ys(){return za?4:Pp?2:Op?3:rQ?12:gy?5:cy?13:ly?22:1}function Q(){return za?"Android":Pp?"iPhone":Op?"iPad":rQ?"Mac":gy?"Windows":cy?"Linux":"unknown"}var w,F=new(dc($l(),1)).default,tA=((w=tA||{}).ROOM_DESTROY="1",w.JOIN_START="21",w.JOIN_SCHEDULE_SUCCESS="22",w.JOIN_SIGNAL_CONNECTION_START="23",w.JOIN_SIGNAL_CONNECTION_END="24",w.JOIN_SEND_CMD="25",w.JOIN_RECEIVED_CMD_RES="26",w.JOIN_SUCCESS="27",w.JOIN_FAILED="28",w.LEAVE_START="51",w.LEAVE_SEND_CMD="52",w.LEAVE_SUCCESS="53",w.PUBLISH_START="61",w.SEND_FIRST_VIDEO_FRAME="62",w.PUBLISH_FAILED="63",w.SUBSCRIBE_START="81",w.SUBSCRIBE_SUCCESS="82",w.SUBSCRIBE_FAILED="84",w.UNSUBSCRIBE_SUCCESS="83",w.LOCAL_TRACK_CAPTURE_START="101",w.LOCAL_TRACK_CAPTURE_SUCCESS="102",w.LOCAL_TRACK_CAPTURE_FAILED="103",w.LOCAL_TRACK_PUBLISHED="104",w.LOCAL_TRACK_UNPUBLISHED="105",w.LOCAL_TRACK_REPLACED="106",w.SWITCH_DEVICE_SUCCESS="107",w.TRACK_MUTED="108",w.TRACK_UNMUTED="109",w.REMOTE_TRACK_SUBSCRIBED="110",w.REMOTE_TRACK_UNSUBSCRIBED="111",w.LOCAL_TRACK_RECAPTURE="112",w.LOCAL_AUDIO_STARTED="113",w.LOCAL_AUDIO_STOPPED="114",w.REMOTE_AUDIO_STARTED="115",w.REMOTE_AUDIO_STOPPED="116",w.LOCAL_TRACK_STOPPED="117",w.LOCAL_VIDEO_TRACK_PREPROCESSED="118",w.PLAY_TRACK_START="151",w.PLAYER_STATE_CHANGED="152",w.VIDEO_LOADED_DATA="153",w.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",w.AUDIO_CONTEXT_LONG_SUSPENDED="155",w.REMOTE_VIDEO_PLAY_START="156",w.REMOTE_VIDEO_PLAY_FINISH="157",w.SIGNAL_CONNECTION_STATE_CHANGED="201",w.PEER_CONNECTION_STATE_CHANGED="202",w.SINGLE_CONNECTION_STAT="203",w.SPC_RECONNECTED="204",w.HEARTBEAT_REPORT="251",w.RECEIVED_PUBLISHED_USER_LIST="252",w.REMOTE_PUBLISH_STATE_CHANGED="253",w.AUDIO_LEVEL_INTERVAL="260",w.NETWORK_QUALITY="261",w.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",w.QUALITY_LIMITATION_CHANGED="263",w.LOG="264",w.AUDIO_PROCESSOR_DEBUG="265",w.SSO_SWITCH="266",w.SEI_MESSAGE="267",w.USER_PAUSE_IN_PIP="268",w.USER_RESUME_IN_PIP="269",w.ENTER_PICTURE_IN_PICTURE="270",w.LEAVE_PICTURE_IN_PICTURE="271",w.SWITCH_ROOM_START="401",w.SWITCH_ROOM_SUCCESS="407",w.SWITCH_ROOM_FAILED="408",w),rA=tA,TA=new class{constructor(){Y(this,"enable",!1),Y(this,"ssoFailCount",0),F.on("22",A=>{let{schedule:t}=A;var o;(o=t?.config)!=null&&o.sso&&F.emit("266",{enable:!0})}),F.on("266",A=>{let{enable:t}=A;this.enable=t})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&F.emit("266",{enable:!1})}},te=class BX{constructor(){Y(this,"_isEnableUploadLog",!0),Y(this,"_localJoinedUser",new Map),Y(this,"_queue",[]),Y(this,"_timeoutId",-1),Y(this,"_logLevel",1),Y(this,"_logLevelToUpload",2),!I0&&!u0&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){F.on(rA.JOIN_SCHEDULE_SUCCESS,t=>{let{schedule:o}=t;var a;(a=o?.config)!=null&&a.logLevelToUpload&&$B[o.config.logLevelToUpload]&&(this._logLevelToUpload=o.config.logLevelToUpload)}),F.on(rA.JOIN_START,t=>{let{params:o}=t;this.addJoinedUser({userId:o.userId,sdkAppId:o.sdkAppId}),this.startUpload()}),F.on(rA.LEAVE_SUCCESS,t=>{let{room:o}=t;this.deleteJoinedUser(o.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(t){this._localJoinedUser.set(t.userId,t),this.startUpload()}deleteJoinedUser(t){this._localJoinedUser.delete(t)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let t={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return t;let o=0;for(;o{let{userId:d,sdkAppId:h}=l;t.map.has(d)?t.map.get(d).logs.push(a):t.map.set(d,{userId:d,sdkAppId:h,logs:[a]})});else if(Ws(a.userId)&&Ys(a.sdkAppId)){let{userId:l,sdkAppId:d}=a;t.map.has(l)?t.map.get(l).logs.push(a):t.map.set(l,{userId:l,sdkAppId:d,logs:[a]})}}return t.map.size>0&&(t.splicedQueue=this._queue.splice(0,o)),t}upload(){return XA(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:t,splicedQueue:o}=this.getLogsToUpload();if(t.size===0)return;try{let l=[...t.values()];for(let d=0;dlA.log).join(` +`)},V=JSON.stringify(L),H=TA.enable?oQ(L,2002,y):V;yield this.uploadLogWithRetry(H,y,H instanceof Uint8Array,V),S.forEach(lA=>lA.uploaded=!0)}}catch{}let a=o.filter(l=>!l.uploaded);a.length>0&&(this._queue=a.concat(this._queue))})}uploadLogWithRetry(t,o,a,l){return Bv({retryFunction:()=>nQ({url:Xf(o,OI.LOG),body:t,timeout:5e3,priority:"low"}).then(d=>{a&&d.data!=="ok"&&(TA.handleUploadFailed(),this.uploadLogWithRetry(l,o,!1,l))}),settings:{retries:3,timeout:2e3},onError:d=>{let{retry:h}=d;h()}})()}getPrefix(t){let o=new Date;return o.setTime(Vf()),"[".concat(Gb(o),"] <").concat($B[t],">")}getLogLevel(){return this._logLevel}setLogLevel(t){ze($B[t])||(this._logLevel!==t&&this.info("setLogLevel",t),this._logLevel=t)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(t){if(Ws(t))return t;try{return t instanceof Error?t.toString():JSON.stringify(t)}catch{return""}}addLogToQueue(t,o){let a=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],l=arguments.length>3?arguments[3]:void 0,d=arguments.length>4?arguments[4]:void 0,h={log:o.reduce((y,S)=>"".concat(y," ").concat(this.logChunkToString(S)).trim(),""),level:t,userId:l,sdkAppId:d,forAllJoinedClients:a};F.emit(rA.LOG,{log:h}),this._isEnableUploadLog&&t>=this._logLevelToUpload&&this._queue.push(h)}log(t,o){let a=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],l=arguments.length>3?arguments[3]:void 0,d=arguments.length>4?arguments[4]:void 0;var h;if(o.unshift(this.getPrefix(t)),this.addLogToQueue(t,o,a,l,d),t{let t=16*Math.random()|0;return(A=="x"?t:3&t|8).toString(16)})},$A=new class{constructor(){Y(this,"_prefix","TRTC"),Y(this,"_queue",new Map)}getRealKey(A){return"".concat(this._prefix,"_").concat(A)}checkStorage(){gQ()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(A=>{if(A.startsWith(this._prefix))try{let t=localStorage.getItem(A);if(!t)return!1;let o=JSON.parse(t);if(o&&o.expiresInlocalStorage.removeItem(A)))}doFlush(){if(gQ())try{for(let[A,t]of this._queue)localStorage.setItem(A,JSON.stringify(t))}catch(A){pA.warn(A)}}getItem(A){if(!gQ())return null;try{let t=localStorage.getItem(this.getRealKey(A));if(!t)return null;let o=JSON.parse(t);return o&&o.expiresIn>=Date.now()?o.value:null}catch(t){pA.warn(t)}}setItem(A,t){if(gQ())try{let o={expiresIn:Date.now()+C0,value:t};this._queue.set(this.getRealKey(A),o)}catch(o){pA.warn(o)}}deleteItem(A){if(!gQ())return!1;try{return A=this.getRealKey(A),this._queue.delete(A),localStorage.removeItem(A),!0}catch(t){return pA.warn(t),!1}}clear(){if(gQ())try{localStorage.clear()}catch(A){pA.warn(A)}}},ge={};Wh(ge,{HTTPS_API:()=>qk,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>A1,IS_GET_CAPABILITIES_SUPPORTED:()=>$2,IS_GET_SETTINGS_SUPPORTED:()=>Dy,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>Xk,IS_INSERTABLE_STREAM_SUPPORTED:()=>$p,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>hQ,IS_RTC_RTP_SENDER_SUPPORTED:()=>xC,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>c_,IS_SEI_SUPPORTED:()=>$k,IS_SPC_SUPPORTED:()=>Yv,basis:()=>t1,capabilityCheck:()=>tL,checkSystemRequirementsInternal:()=>Hk,decodeSupportStatus:()=>Vk,detectH264SupportedByFakeStreaming:()=>Z2,detectVideoCodecCapabilities:()=>Hv,detectVideoDecoderCapabilities:()=>oL,detectVideoEncoderCapabilities:()=>iL,encodeSupportStatus:()=>Fv,getBrowserInfo:()=>Lv,getDisplayResolution:()=>ad,getH264ProfileLevelIds:()=>n1,isAddTransceiverSupported:()=>AC,isBrowserSupported:()=>xk,isCanvasCaptureStreamAPISupported:()=>Pv,isCanvasSmallStreamSupported:()=>g_,isGetReceiversSupported:()=>yy,isGetSendersSupported:()=>xI,isGetTransceiversSupported:()=>CQ,isGetUserMediaSupported:()=>Kk,isMediaDevicesSupported:()=>Yk,isMediaSessionSupported:()=>e1,isMediaStreamTrackGeneratorSupported:()=>$K,isMediaStreamTrackProcessorSupported:()=>Uv,isReplaceTrackSupported:()=>X2,isRequestVideoFrameCallbackSupported:()=>Am,isSIMDSupported:()=>Vv,isScaleResolutionDownBySupported:()=>Wk,isScreenCaptureApiAvailable:()=>Xp,isSelectedCandidatePair:()=>Ov,isSetParametersSupported:()=>Zk,isSetSinkIdSupported:()=>ej,isSmallStreamSupported:()=>xv,isStopTransceiverSupported:()=>sa,isTRTCSupported:()=>Aj,isUnifiedPlanDefault:()=>zk,isUsedInHttpProtocol:()=>Qu,isWebAudioSupported:()=>jk,isWebCodecSupported:()=>l_,isWebCodecsSupported:()=>a_,isWebRTCSupported:()=>Sy,isWebTransportSupported:()=>vy});var Oe={};Wh(Oe,{AUDIO_LEVEL_SCALE:()=>sd,AlphaStitchingType:()=>Qy,AudioCodecPipelineType:()=>dQ,AudioDecoderDowngradeState:()=>Gv,AudioPlayerMode:()=>o_,AudioType:()=>J2,BASIC_TYPE:()=>Lk,BannedReason:()=>yg,CONNECTION_CLOSED_REASON:()=>zt,CheckPermissionType:()=>pr,ClientEvent:()=>nt,CodecType:()=>bv,ConnectionEvent:()=>Ko,ConnectionState:()=>dy,DECODE_FAILED_ERROR_CODE:()=>kv,DenoiserMode:()=>Wp,DeviceType:()=>Uk,FacingMode:()=>Gk,FrameWorkType:()=>co,LeaveReason:()=>bk,LocalTrackEvent:()=>No,MULTI_VIDEO_DATA_TYPE:()=>By,MediaType:()=>t_,MediaTypeLabel:()=>ZK,MonitorEventId:()=>ml,MutedFlag:()=>or,NetworkQualityValue:()=>dE,PlayerState:()=>Qo,ReceiveMode:()=>eI,RemoteStreamType:()=>hy,RemoteTrackEvent:()=>Ds,RoomEvent:()=>Bo,SMALL_MODE:()=>Zp,SceneNumber:()=>Za,StreamEvent:()=>wi,StreamType:()=>EQ,SubscribeMediaType:()=>kk,TIMER_TYPE:()=>s_,TRACK_ACTION:()=>Nk,TRACK_KIND:()=>IQ,TrackEvent:()=>jo,UserRole:()=>Jc,UserRoleNumber:()=>ln,VideoCodec:()=>fl,VideoCodecPipelineType:()=>zp,VideoContentHint:()=>n_,VideoDecoderDowngradeState:()=>Cy,VideoPlayerMode:()=>i_,VideoType:()=>uQ});var ke,me,Qt,Ii,at,$e,dA,vt,st,Xi,Ei,co=(A=>(A[A.WEBRTC=30]="WEBRTC",A[A.WASM=37]="WASM",A))(co||{}),Ko=((Ei=Ko||{}).TRACK_ADDED="track-added",Ei.TRACK_UPDATED="track-updated",Ei.TRACK_SUBSCRIBED="track-subscribed",Ei.STREAM_ADDED="stream-added",Ei.STREAM_REMOVED="stream-removed",Ei.STREAM_UPDATED="stream-updated",Ei.STREAM_PUBLISHED="stream-published",Ei.STREAM_SUBSCRIBED="stream-subscribed",Ei.STREAM_UNSUBSCRIBED="stream-unsubscribed",Ei.STATE_CHANGED="state-changed",Ei.ERROR="error",Ei.CONNECTION_STATE_CHANGED="connection-state-changed",Ei.FIREWALL_RESTRICTION="firewall-restriction",Ei.SEI_MESSAGE="sei-message",Ei.CLOSED="closed",Ei),zt=(A=>(A.REMOTE_LEAVE="remote user exitRoom",A.REMOTE_UNPUBLISH="remote user unpublished",A.LOCAL_LEAVE="you exitRoom",A.LOCAL_UNPUBLISH="you unpublished",A.LOCAL_UNSUBSCRIBE="you unsubscribed",A.SWITCH_ROLE="you switch role to audience",A))(zt||{}),nt=((Xi=nt||{}).STREAM_ADDED="stream-added",Xi.STREAM_REMOVED="stream-removed",Xi.STREAM_UPDATED="stream-updated",Xi.STREAM_SUBSCRIBED="stream-subscribed",Xi.CONNECTION_STATE_CHANGED="connection-state-changed",Xi.PEER_JOIN="peer-join",Xi.PEER_LEAVE="peer-leave",Xi.MUTE_AUDIO="mute-audio",Xi.MUTE_VIDEO="mute-video",Xi.UNMUTE_AUDIO="unmute-audio",Xi.UNMUTE_VIDEO="unmute-video",Xi.CLIENT_BANNED="client-banned",Xi.NETWORK_QUALITY="network-quality",Xi.AUDIO_VOLUME="audio-volume",Xi.SEI_MESSAGE="sei-message",Xi.ERROR="error",Xi),wi=((st=wi||{}).PLAYER_STATE_CHANGED="player-state-changed",st.SCREEN_SHARING_STOPPED="screen-sharing-stopped",st.CONNECTION_STATE_CHANGED="connection-state-changed",st.DEVICE_AUTO_RECOVERED="device-auto-recovered",st.ERROR="error",st),No=((vt=No||{}).DEVICE_AUTO_RECOVERED="1",vt.DEVICE_RECOVER_FAILED="5",vt.DEVICE_CHANGED="2",vt.ERROR="3",vt.PUBLISH_STATE_CHANGED="4",vt.ENCODE_FAILED="6",vt.TRACK_ENDED="7",vt.RENDER="render",vt),Qo=(A=>(A.PAUSED="PAUSED",A.PLAYING="PLAYING",A.STOPPED="STOPPED",A))(Qo||{}),Bo=((dA=Bo||{}).PEER_JOIN="peer-join",dA.PEER_LEAVE="peer-leave",dA.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",dA.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",dA.BANNED="banned",dA.NETWORK_QUALITY="network-quality",dA.AUDIO_VOLUME="audio-volume",dA.SEI_MESSAGE="sei-message",dA.ERROR="error",dA.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",dA.REMOTE_PUBLISHED="remote-published",dA.REMOTE_UNPUBLISHED="remote-unpublished",dA.FIREWALL_RESTRICTION="firewall-restriction",dA.HEARTBEAT_REPORT="heartbeat-report",dA.CUSTOM_MESSAGE="custom-message",dA.LAYER_DATA="layerData",dA.FIRST_VIDEO_FRAME="first-video-frame",dA.FIRST_FRAME_RENDER="first-frame-render",dA.DUMP="dump",dA.AUDIO_FRAME="audio-frame",dA.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",dA.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",dA.NTP_TIME_UPDATED="ntp-time-updated",dA.DATA_CHANNEL_MESSAGE="data-channel-message",dA.ASR_ROBOT_PEER_JOIN="asr-robot-peer-join",dA.ASR_ROBOT_PEER_LEAVE="asr-robot-peer-leave",dA),jo=(($e=jo||{}).PLAYER_STATE_CHANGED="player-state-changed",$e.MUTE="mute",$e.UNMUTE="unmute",$e.ERROR="error",$e.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",$e.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",$e.FIRST_VIDEO_FRAME="first-video-frame",$e.FIRST_FRAME_RENDER="first-frame-render",$e.VIDEO_SIZE_CHANGED="video-size-changed",$e),Ds=(A=>(A.DECODE_FAILED="decode-failed",A.DECODE_FAILED_DURING_CALL="decode-failed-during-call",A.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",A.REMOTE_PUBLISH_CHANGED="remote-publish-changed",A.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",A))(Ds||{}),or=((at=or||{})[at.VIDEO=1]="VIDEO",at[at.SMALL=2]="SMALL",at[at.AUX=4]="AUX",at[at.AUDIO=8]="AUDIO",at[at.VIDEO_MUTE=16]="VIDEO_MUTE",at[at.AUX_MUTE=32]="AUX_MUTE",at[at.AUDIO_MUTE=64]="AUDIO_MUTE",at),Za=(A=>(A[A.RTC=1]="RTC",A[A.LIVE=2]="LIVE",A))(Za||{}),ln=(A=>(A[A.ANCHOR=20]="ANCHOR",A[A.AUDIENCE=21]="AUDIENCE",A))(ln||{}),Jc=(A=>(A.ANCHOR="anchor",A.AUDIENCE="audience",A))(Jc||{}),dy=(A=>(A.CONNECTED="CONNECTED",A.DISCONNECTED="DISCONNECTED",A.CONNECTING="CONNECTING",A.RECONNECTED="RECONNECTED",A.RECONNECTING="RECONNECTING",A))(dy||{}),Gv=((Ii=Gv||{}).INITIALIZED="INITIALIZED",Ii.STARTING="STARTING",Ii.STARTED="STARTED",Ii.FAILED="FAILED",Ii),Cy=(A=>(A.INITIALIZED="INITIALIZED",A.STARTING="STARTING",A.STARTED="STARTED",A.FAILED="FAILED",A))(Cy||{}),IQ=(A=>(A.AUDIO="audio",A.VIDEO="video",A.AUXILIARY="auxVideo",A))(IQ||{}),Nk=(A=>(A.ADD="add",A.REMOVE="remove",A))(Nk||{}),t_=(A=>(A[A.NULL=0]="NULL",A[A.AUDIO=1]="AUDIO",A[A.AUX_VIDEO=2]="AUX_VIDEO",A[A.BIG_VIDEO=4]="BIG_VIDEO",A[A.SMALL_VIDEO=8]="SMALL_VIDEO",A))(t_||{}),ZK={1:"audio",2:"auxVideo",4:"video"},J2=((Qt=J2||{})[Qt.opus=111]="opus",Qt),uQ=(A=>(A[A.h264=100]="h264",A[A.vp8=101]="vp8",A))(uQ||{}),EQ=(A=>(A.Big="big",A.Small="small",A))(EQ||{}),hy=(A=>(A.Main="main",A.Aux="auxiliary",A))(hy||{}),By=(A=>(A[A.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",A[A.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",A[A.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",A[A.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",A[A.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",A))(By||{}),ml=((me=ml||{})[me.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",me[me.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",me[me.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",me[me.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",me[me.MUTE_AUDIO=32772]="MUTE_AUDIO",me[me.MUTE_VIDEO=32773]="MUTE_VIDEO",me[me.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",me[me.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",me[me.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",me[me.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",me[me.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",me[me.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",me[me.SWITCH_CAMERA=32780]="SWITCH_CAMERA",me[me.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",me[me.REPLACE_VIDEO=32782]="REPLACE_VIDEO",me[me.REPLACE_AUDIO=32783]="REPLACE_AUDIO",me[me.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",me[me.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",me[me.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",me[me.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",me[me.JOIN=32788]="JOIN",me[me.LEAVE=32789]="LEAVE",me[me.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",me[me.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",me[me.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",me[me.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",me[me.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",me[me.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",me[me.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",me[me.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",me[me.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",me[me.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",me[me.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",me[me.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",me[me.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",me[me.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",me[me.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",me[me.PUBLISH_AUX=32805]="PUBLISH_AUX",me[me.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",me[me.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",me[me.VIDEO_ENCODER=4004]="VIDEO_ENCODER",me[me.VIDEO_DECODER=4005]="VIDEO_DECODER",me),dE=(A=>(A[A.UNKNOWN=0]="UNKNOWN",A[A.EXCELLENT=1]="EXCELLENT",A[A.GOOD=2]="GOOD",A[A.POOR=3]="POOR",A[A.BAD=4]="BAD",A[A.VERY_BAD=5]="VERY_BAD",A[A.DISCONNECTED=6]="DISCONNECTED",A))(dE||{}),eI=(A=>(A[A.MANUAL=0]="MANUAL",A[A.AUTO_AUDIO=1]="AUTO_AUDIO",A[A.AUTO_VIDEO=2]="AUTO_VIDEO",A[A.AUTO_ALL=3]="AUTO_ALL",A))(eI||{}),Gk=(A=>(A.user="user",A.environment="environment",A))(Gk||{}),i_=(A=>(A[A.ELEMENT=0]="ELEMENT",A[A.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",A[A.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",A))(i_||{}),o_=(A=>(A[A.ELEMENT=0]="ELEMENT",A[A.CONTEXT=1]="CONTEXT",A))(o_||{}),yg=(A=>(A.BANNED="banned",A.KICK="kick",A.USER_TIME_OUT="user_time_out",A.ROOM_DISBAND="room_disband",A))(yg||{}),bk=(A=>(A[A.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",A[A.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",A[A.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",A[A.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",A[A.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",A[A.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",A[A.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",A[A.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",A[A.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",A))(bk||{}),sd=1e8,Wp=(A=>(A[A.NORMAL=0]="NORMAL",A[A.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",A))(Wp||{}),kk=class{constructor(){Y(this,"mediaType",0)}set audio(A){A?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(1&this.mediaType)}set video(A){A?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(4&this.mediaType)}set auxiliary(A){A?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(2&this.mediaType)}set smallVideo(A){A?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(8&this.mediaType)}},Lk=(A=>(A.String="string",A.Number="number",A.Boolean="boolean",A.Array="array",A.Object="object",A))(Lk||{}),fl=(A=>(A.H264="h264",A.H265="h265",A.VP8="vp8",A.VP9="vp9",A.AV1="av1",A))(fl||{}),zp=(A=>(A[A.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",A[A.DUMP=1]="DUMP",A[A.SEI=2]="SEI",A[A.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",A))(zp||{}),dQ=(A=>(A[A.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",A[A.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",A[A.DUMP=2]="DUMP",A[A.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",A))(dQ||{}),bv=(A=>(A.WebRTC="webrtc",A.WebCodecs="webcodecs",A.WebAssembly="webassembly",A))(bv||{}),kv=((ke=kv||{})[ke.SUCCESS=0]="SUCCESS",ke[ke.FAILED=1]="FAILED",ke[ke.WEBCODEC_INIT=2]="WEBCODEC_INIT",ke[ke.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",ke[ke.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",ke[ke.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",ke[ke.WASM_INIT=6]="WASM_INIT",ke[ke.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",ke[ke.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",ke[ke.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",ke[ke.TEST=10]="TEST",ke[ke.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",ke),n_=(A=>(A.NONE="",A.DETAIL="detail",A.MOTION="motion",A.TEXT="text",A))(n_||{}),s_=(A=>(A.INTERVAL="interval",A.TIMEOUT="timeout",A.RAF="raf",A.RIC="ric",A.INTERVAL_IN_WORKER="intervalInWorker",A))(s_||{}),Zp=(A=>(A.CANVAS="canvas",A.API="api",A))(Zp||{}),pr=(A=>(A[A.NONE=0]="NONE",A[A.MICROPHONE=1]="MICROPHONE",A[A.CAMERA=2]="CAMERA",A[A.BOTH=3]="BOTH",A))(pr||{}),Uk=(A=>(A.CAMERA="camera",A.MICROPHONE="microphone",A))(Uk||{}),Qy=(A=>(A[A.none=0]="none",A[A.horizontal=1]="horizontal",A[A.vertical=2]="vertical",A))(Qy||{}),Go={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX",SWITCH_PLAYBACK_QUALITY_TIMEOUT:"SWITCH_PLAYBACK_QUALITY_TIMEOUT"},Cc={AVOID_REPEATED_CALL:A=>"previous ".concat(A.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(A){let{key:t,rule:o,fnName:a,value:l}=A;return"'".concat(t||o.name,"' is a required param when calling ").concat(a,"(), received: ").concat(l,".")},INVALID_PARAMETER_TYPE(A){let{key:t,rule:o,fnName:a,value:l}=A,d="".concat(t||o.name),h="";return h=Array.isArray(o.type)?o.type.join("|"):o.type,"'".concat(d,"' must be type of ").concat(h," when calling ").concat(a,"(), received type: ").concat(pg(l),".")},INVALID_PARAMETER_EMPTY(A){let{key:t,rule:o,fnName:a,value:l}=A;return"'".concat(t||o.name,"' cannot be '").concat(l,"' when calling ").concat(a,"().")},INVALID_PARAMETER_INSTANCE(A){let{key:t,rule:o,fnName:a,value:l}=A,d="".concat(t||o.name),h="".concat(o.instanceOf.name||o.instanceOf);return"'".concat(d,"' must be instanceof ").concat(h," when calling ").concat(a,"(), received type: ").concat(pg(l),".")},INVALID_PARAMETER_RANGE(A){let{key:t,rule:o,fnName:a,value:l}=A;return"'".concat(t||o.name,"' must be one of ").concat(o.values.join("|")," when calling ").concat(a,"(), received: ").concat(l,".")},INVALID_PARAMETER_MIN(A){let{key:t,rule:o,fnName:a,value:l}=A;return"the min value of ".concat(t||o.name," is ").concat(o.min,", received: ").concat(l,".")},INVALID_PARAMETER_MAX(A){let{key:t,rule:o,fnName:a,value:l}=A;return"the max value of ".concat(t||o.name," is ").concat(o.max,", received: ").concat(l,".")},API_CALL_TIMEOUT:A=>"".concat(A.commandDesc||A.command," timeout observed."),SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:A=>"SignalChannel setup failure: (errorCode: ".concat(A.errorCode,", errorMsg: ").concat(A.errorMsg," })."),ERROR_MESSAGE(A){let t="".concat(A.type," failed");return A.message&&(t="".concat(t,": ").concat(A.message,".")),t},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:A=>"exchange sdp failed ".concat(A.errMsg,"."),UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:A=>"'".concat(A,"' must be validate string when useStringRoomId is true."),INVALID_ROOMID_INTEGER:A=>"'".concat(A,"' must be an integer between [1, 4294967294] when useStringRoomId is false."),INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED(A){let{error:t,code:o}=A;return"Failed to join room - ".concat(t," code: ").concat(o)},REJOIN_ROOM_FAILED:A=>"reJoin room: ".concat(A.roomId," failed, please check your network."),INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:A=>"duplicate ".concat(A," stream publishing, please unpublish your prev ").concat(A," stream and then re-publish."),INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED(A){let{message:t,userId:o,streamType:a}=A;return"failed to subscribe ".concat(o," ").concat(a," stream, reason: ").concat(t,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:A=>"switchRole failed, errCode: ".concat(A.code," errMsg: ").concat(A.message,"."),CLIENT_BANNED:A=>"client was banned because of ".concat(A.message,"."),INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:A=>"startPublishCDNStream failed, errMsg: ".concat(A.message,"."),STOP_PUBLISH_CDN_FAILED:A=>"stopPublishCDNStream failed, errMsg: ".concat(A.message,"."),INVALID_STREAM_ID:A=>"'".concat(A,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores."),START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:A=>"cannot replace ".concat(A.kind," track because stream has not ").concat(A.kind," track"),NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:A=>"startMixTranscode failed, errMsg: ".concat(A.message,"."),STOP_MIX_TRANSCODE_FAILED:A=>"stopMixTranscode failed, errMsg: ".concat(A.message,"."),MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO(A){let{key:t,rule:o,fnName:a,value:l}=A;return"'".concat(t||o.name,"' cannot be less than 0 when calling ").concat(a,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:A=>"'".concat(A,"' is required and must be between 1 and 15."),MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:A=>{let{key:t,fnName:o}=A;return"'".concat(t,"' is not found in the document object when calling ").concat(o,"().")},INVALID_ELEMENT_ID_TYPE:A=>{let{key:t,fnName:o,type:a}=A;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(o,"(), received: ").concat(a,".")},PLAY_FAILED:A=>"".concat(A.media," play failed, browser exception: ").concat(A.error.toString()),INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:A=>"".concat(A,"Track is not supported on your browser."),NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:A=>"".concat(A.signalResponse," failed, response code is ").concat(A.code," , errMsg: ").concat(A.message,"."),CATCH_HANDLER_ERROR(A){let{name:t,event:o}=A;return"an error was caught in ".concat(t,".on('").concat(o,"', handler), please check your code in 'handler'.")},API_NOT_EXIST(A){let{name:t}=A;return"experimental api ".concat(t," does not exist.")},REPEAT_JOIN:A=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED(A){let{funName:t}=A;return"failed to call ".concat(t,"() because client was destroyed.")},SEI_NOT_SUPPORT:A=>"not support to sendSEIMessage".concat(A===!1?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:A=>{let{isSize:t,name:o,timesInSecond:a,maxSizeInSecond:l}=A;return"api ".concat(o," call ").concat(t?"size":"times"," is over ").concat(t?"".concat(l," bytes"):a," in a second.")},CONNECTION_ABORTED:A=>"connection aborted due to: ".concat(A),API_CALL_ABORTED(A){let t;return t=A.message.includes("REMOTE_STREAM_NOT_EXIST")?"Subscribe ".concat(A.userId," ").concat(A.streamType," stream aborted, reason: remote user ").concat(A.userId," unpublished stream."):"API aborted, reason: ".concat(A.message),t},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:A=>"'streamType' is required when 'userId' is not '*', calling ".concat(A,"()"),SWITCH_PLAYBACK_QUALITY_TIMEOUT:A=>"switchPlaybackQuality timeout: waiting for first frame of user ".concat(A.userId,".")},q2=(A,t)=>t?"".concat(zh,"/").concat(A,"/").concat(t):"".concat(zh,"/").concat(A,"/index.html"),Fk=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let A=localStorage==null?void 0:localStorage.getItem($S);if(A){A=JSON.parse(A);let t=document.createElement("script");t.type="text/javascript",t.text=A.message,document.body.appendChild(t);let o=window.TRTC_ERROR_INFO,a=window.TRTC_ERROR_LINK;return document.body.removeChild(t),{TRTC_ERROR_INFO:o,TRTC_ERROR_LINK:a}}return{}};function sn(A){let{key:t,data:o,link:a,addDocLink:l=!0}=A,d="",h="",y="";ba(Cc[t])?d=Cc[t](o):Ws(Cc[t])&&(d=Cc[t]);let{TRTC_ERROR_INFO:S,TRTC_ERROR_LINK:L}=Fk();a?y="".concat(a.className,".html#").concat(a.fnName):L&&L[t]&&(ba(L[t])?y=L[t](o):Ws(L[t])&&(y=L[t]));let V=d;return Zd()&&(S&&S[t]&&(ba(S[t])?h=S[t](o):Ws(S[t])&&(h=S[t])),h&&(V=l?"".concat(h,` 请查看文档: `).concat(q2("zh-cn",y),` `):"".concat(h,` `),V+=d)),l&&(V+=` Refer to: `.concat(q2("en",y),` -`)),V}var vn,Ss,Ok=dc(wK(),1),Pk=class{constructor(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];Y(this,"countMap",new Map),Y(this,"distributionMap",new Map),Y(this,"version"),Y(this,"log",pA.createLogger({id:"kv"})),A&&(F.on("102",t=>{let{track:o,cost:a}=t;this.addSuccessEvent({key:o.kind===JA.AUDIO?501700:511700,cost:a})}),F.on("103",t=>{let{track:o,error:a}=t;this.addFailedEvent({key:o.kind===JA.AUDIO?501700:511700,error:a})}),F.on("266",t=>{let{enable:o}=t;this.log.info("".concat(o?"enable":"disable"," sso")),o?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(A,t){let o={msg_sdk_basic_info:{uint32_sdk_version:ok(this.version||Wd),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(a=>{let[l,d]=a;return{uint32_key:l,uint32_count:d}}),stats_distribution:[...this.distributionMap.entries()].map(a=>{let[l,d]=a;return{uint32_key:l,distribution_items:[...d.entries()].map(h=>{let[y,S]=h;return{uint32_item_key:y,uint32_item_value:S}})}}),str_user_sig:A,bytes_report_token:t};return this.countMap.clear(),this.distributionMap.clear(),o}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(A){let t=+String(A).slice(-3);return t>=700&&t<799}isErrorCodeKey(A){let t=+String(A).slice(-3);return t>=600&&t<699}isCountKey(A){let t=+String(A).slice(-3);return t>=0&&t<599}isNumberKey(A){let t=+String(A).slice(-3);return t>=800&&t<899}addCount(A){let{key:t,useUV:o=!1}=A;this.isCountKey(t)?o&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug("".concat(t," is not count key, last 3 number should be 0~599"))}addEnum(A){let{key:t,value:o,useUV:a=!0}=A;var l;if(!this.isEnumKey(t))return this.log.debug("".concat(t," is not enum key, last 3 number should be 700~799"));if(a&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let d=((l=this.distributionMap)==null?void 0:l.get(t))||new Map;d.set(o,(d.get(o)||0)+1),this.distributionMap.set(t,d)}addNumber(A){let{key:t,value:o,split:a=100,useUV:l=!1,max:d=5e3}=A;var h;if(!this.isNumberKey(t))return this.log.debug("".concat(t," is not number key, last 3 number should be 800~899"));if(l&&this.countMap.has(t))return;o>d&&(o=d),this.countMap.set(t,(this.countMap.get(t)||0)+1);let y=((h=this.distributionMap)==null?void 0:h.get(t))||new Map,S=0;if(Ys(a))S=Math.floor(o/a);else for(let L=a.length-1;L>0;L--)if(o>a[L]){S=L;break}y.set(S,(y.get(S)||0)+1),this.distributionMap.set(t,y)}addSuccessEvent(A){let{key:t,cost:o,timeKey:a,split:l}=A;if(t&&(this.addEnum({key:t,value:1,useUV:!1}),o)){let d=+String(t).slice(-3);d<800&&d>=700?this.addNumber({key:a||t+100,value:o,split:l}):a||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(A){let{key:t,error:o}=A;if(!t)return;let a=mt.UNKNOWN;o&&(Ys(o)?a=o:(!ze(o.extraCode)||!ze(o.code))&&(a=o.extraCode||o.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:Math.abs(a),useUV:!1})}},K2=((vn=K2||{})[vn.enterRoom=500700]="enterRoom",vn[vn.exitRoom=500701]="exitRoom",vn[vn.switchRole=500702]="switchRole",vn[vn.destroy=500703]="destroy",vn[vn.startLocalAudio=500704]="startLocalAudio",vn[vn.updateLocalAudio=500705]="updateLocalAudio",vn[vn.stopLocalAudio=500706]="stopLocalAudio",vn[vn.startLocalVideo=500707]="startLocalVideo",vn[vn.updateLocalVideo=500708]="updateLocalVideo",vn[vn.stopLocalVideo=500709]="stopLocalVideo",vn[vn.startScreenShare=500710]="startScreenShare",vn[vn.updateScreenShare=500711]="updateScreenShare",vn[vn.stopScreenShare=500712]="stopScreenShare",vn[vn.startRemoteVideo=500713]="startRemoteVideo",vn[vn.updateRemoteVideo=500714]="updateRemoteVideo",vn[vn.stopRemoteVideo=500715]="stopRemoteVideo",vn[vn.muteRemoteAudio=500716]="muteRemoteAudio",vn[vn.setRemoteAudioVolume=500717]="setRemoteAudioVolume",vn[vn.use=500718]="use",vn[vn.switchRoom=500719]="switchRoom",vn[vn.getPermissions=500720]="getPermissions",vn[vn.sendSEIMessage=5e5]="sendSEIMessage",vn[vn.sendCustomMessage=500001]="sendCustomMessage",vn),j2=(A=>(A[A.AudioMixer=550700]="AudioMixer",A[A.AIDenoiser=551700]="AIDenoiser",A[A.VirtualBackground=570700]="VirtualBackground",A[A.Beauty=571700]="Beauty",A[A.Watermark=572700]="Watermark",A[A.BasicBeauty=574700]="BasicBeauty",A[A.FaceDetector=575700]="FaceDetector",A[A.CDNStreaming=590700]="CDNStreaming",A[A.DeviceDetector=591700]="DeviceDetector",A[A.Debug=592700]="Debug",A[A.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",A[A.VideoMixer=594700]="VideoMixer",A[A.AudioProcessor=595700]="AudioProcessor",A[A.LEBPlayer=596700]="LEBPlayer",A[A.RealtimeTranscriber=597700]="RealtimeTranscriber",A))(j2||{}),py=(A=>(A[A.AudioMixer=550701]="AudioMixer",A[A.AIDenoiser=551701]="AIDenoiser",A[A.VirtualBackground=570701]="VirtualBackground",A[A.Beauty=571701]="Beauty",A[A.Watermark=572701]="Watermark",A[A.BasicBeauty=574701]="BasicBeauty",A[A.FaceDetector=575701]="FaceDetector",A[A.CDNStreaming=590701]="CDNStreaming",A[A.DeviceDetector=591701]="DeviceDetector",A[A.Debug=592701]="Debug",A[A.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",A[A.VideoMixer=594701]="VideoMixer",A[A.AudioProcessor=595701]="AudioProcessor",A[A.LEBPlayer=596701]="LEBPlayer",A[A.RealtimeTranscriber=597701]="RealtimeTranscriber",A))(py||{}),r_=(A=>(A[A.AudioMixer=550702]="AudioMixer",A[A.AIDenoiser=551702]="AIDenoiser",A[A.VirtualBackground=570702]="VirtualBackground",A[A.Beauty=571702]="Beauty",A[A.Watermark=572702]="Watermark",A[A.BasicBeauty=574702]="BasicBeauty",A[A.FaceDetector=575702]="FaceDetector",A[A.CDNStreaming=590702]="CDNStreaming",A[A.DeviceDetector=591702]="DeviceDetector",A[A.Debug=592702]="Debug",A[A.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",A[A.VideoMixer=594702]="VideoMixer",A[A.AudioProcessor=595702]="AudioProcessor",A[A.LEBPlayer=596702]="LEBPlayer",A[A.RealtimeTranscriber=597702]="RealtimeTranscriber",A))(r_||{}),fy=((Ss=fy||{})[Ss.DECODER_TYPE=514700]="DECODER_TYPE",Ss[Ss.DECODER_HW_SW=514701]="DECODER_HW_SW",Ss[Ss.DECODE_RESULT=514702]="DECODE_RESULT",Ss[Ss.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",Ss[Ss.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",Ss[Ss.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",Ss[Ss.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",Ss[Ss.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",Ss[Ss.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",Ss[Ss.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",Ss[Ss.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",Ss[Ss.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",Ss[Ss.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",Ss[Ss.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",Ss[Ss.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",Ss[Ss.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",Ss[Ss.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",Ss[Ss.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",Ss[Ss.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",Ss),XK=new Pk(!0),eB=new Pk(!1),ri=XK,Mn={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},W2=new Map([[gr,["Firefox",pv]],[ry,["Edg",Ek]],[$0,["Chrome",A_]],[mg,["Safari",aQ]],[od,["TBS",Ck]],[xp,["XWEB",hk]],[sQ&&Pp,["WeChat",Bk]],[W0,["QQ(Win)",Qk]],[fv,["QQ(Mobile)",ay]],[Yp,["QQ(Mobile X5)",ay]],[yv,["QQ(Mac)",pk]],[z0,["QQ(iPad)",Dv]],[Z0,["MI",Vp]],[AB,["HW",Sk]],[Sv,["Samsung",vk]],[vv,["OPPO",Mk]],[Mv,["VIVO",Rv]],[sy,["EDGE",uk]],[mv,["SogouMobile",K0]],[j0,["Sogou",dk]]]);function Lv(){let A=W2.get(!0);return{browserName:A?A[0]:"unknown",browserVersion:A?A[1]:"unknown"}}var xk=function(){return!(fk||sy||ry&&q0<80||gr&&J0<56)},a_=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(A=>A in window)},Yk=function(){if(!navigator.mediaDevices)return Qu()||pA.error(Cc.NOT_SUPPORTED_MEDIA),!1;let A=["getUserMedia","enumerateDevices"];return A.filter(t=>t in navigator.mediaDevices).length===A.length},z2=!1;function Qu(){return location.protocol==="http:"&&!Jp&&(z2||pA.error(sn({key:Go.NOT_SUPPORTED_HTTP})),z2=!0,!0)}var Uv=function(){return window?.OffscreenCanvas&&window?.MediaStreamTrackProcessor&&window?.MediaStreamTrackGenerator},$K=function(){return!(window==null||!window.MediaStreamTrackGenerator)},Fv=function(){return XA(this,null,function*(){var A,t,o;if(Mn.detail.isH264EncodeSupported&&Mn.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Mn.detail.isH264EncodeSupported,isVp8EncodeSupported:Mn.detail.isVp8EncodeSupported,isH265EncodeSupported:Mn.detail.isH265EncodeSupported};let a,l=!1,d=!1,h=!1;try{let y=new RTCPeerConnection,S=document.createElement(JA.CANVAS);S.getContext("2d");let L=S.captureStream(0);return y.addTrack(L.getVideoTracks()[0],L),a=yield y.createOffer(),l=((A=a.sdp)==null?void 0:A.toLowerCase().indexOf("h264"))!==-1,d=((t=a.sdp)==null?void 0:t.toLowerCase().indexOf("vp8"))!==-1,h=((o=a.sdp)==null?void 0:o.toLowerCase().indexOf("h265"))!==-1,y.close(),{isH264EncodeSupported:l,isVp8EncodeSupported:d,isH265EncodeSupported:h}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},Vk=function(){return XA(this,null,function*(){var A;if(Mn.detail.isH264DecodeSupported&&Mn.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Mn.detail.isH264DecodeSupported,isVp8DecodeSupported:Mn.detail.isVp8DecodeSupported,isH265DecodeSupported:Mn.detail.isH265DecodeSupported};let t,o=!1,a=!1;try{let l=new RTCPeerConnection;AC()?(l.addTransceiver(JA.VIDEO,{direction:"recvonly"}),t=yield l.createOffer()):t=yield l.createOffer({offerToReceiveVideo:!0}),t.sdp.toLowerCase().indexOf("h264")!==-1&&(o=!0),t.sdp.toLowerCase().indexOf("vp8")!==-1&&(a=!0);let d=((A=t.sdp)==null?void 0:A.toLowerCase().indexOf("h265"))!==-1;return l.close(),{isH264DecodeSupported:o,isVp8DecodeSupported:a,isH265DecodeSupported:d}}catch{return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})},Hk=nk(A=>XA(null,null,function*(){let t=Date.now(),o=Sy(),a=Yk(),l=a_();if(Mn.detail.isWebRTCSupported=o,Mn.detail.isMediaDevicesSupported=a,Mn.detail.isWebCodecsSupported=l,Mn.detail.isScreenShareSupported=Xp(),Mn.detail.isSmallStreamSupported=xv(),A===37)return Object.assign(Mn.detail,yield function(){return XA(this,null,function*(){return rd||(rd=new Promise(MA=>XA(null,null,function*(){let oe={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!a_())return void MA(oe);let fe=null,je=null,_e=null,vi=()=>{_e&&clearTimeout(_e),fe=null,je=null};try{fe=document.createElement("canvas"),je=fe.getContext("2d"),fe.width=320,fe.height=240;let Fe=0,Dt=()=>{!je||!fe||(je.fillStyle="hsl(".concat(Fe%360,", 50%, 50%)"),je.fillRect(0,0,fe.width,fe.height),je.fillStyle="white",je.font="20px Arial",je.fillText("Frame ".concat(Fe),10,30),Fe++)};_e=setTimeout(()=>{vi(),MA(oe)},5e3);let pi=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(pi.map(Mi=>XA(null,null,function*(){let Wo,zo={type:Mi.type,encodeSupported:!1,decodeSupported:!1};try{Wo=yield new Promise((vs,Zo)=>XA(null,null,function*(){try{let Vn=new VideoEncoder({output:wa=>{vs(wa),zo.encodeSupported=!0},error:Zo});Vn.configure(Mi.encodeConfig),Dt();let yg=new VideoFrame(fe,{timestamp:0});Vn.encode(yg,{keyFrame:!0}),yg.close(),yield Vn.flush(),Vn.close()}catch(Vn){Zo(Vn)}}))}catch(vs){return pA.warn("".concat(Mi.type," encoder error:"),vs),zo}try{yield new Promise((vs,Zo)=>XA(null,null,function*(){try{let Vn=new VideoDecoder({output:yg=>{zo.decodeSupported=!0,vs(0),yg.close()},error:Zo});Vn.configure(Mi.decodeConfig),Vn.decode(Wo),yield Vn.flush(),Vn.close()}catch(Vn){Zo(Vn)}}))}catch(vs){pA.warn("".concat(Mi.type," decoder error:"),vs)}return zo})))).forEach(Mi=>{Mi.type==="h264"?(oe.isH264EncodeSupported=Mi.encodeSupported,oe.isH264DecodeSupported=Mi.decodeSupported):Mi.type==="vp8"&&(oe.isVp8EncodeSupported=Mi.encodeSupported,oe.isVp8DecodeSupported=Mi.decodeSupported)}),vi(),MA(oe)}catch(Fe){vi(),pA.warn("detectWebCodecsSupported failed:",Fe),MA(oe)}})),rd)})}()),Mn.detail.isBrowserSupported=l,Mn.result=a&&l,Mn.result||pA.error("".concat(navigator.userAgent," ").concat(k0(Mn.detail,!1))),eL(A),ri.addNumber({key:523800,value:Date.now()-t}),Mn;if(Mn.result&&Mn.detail.isH264EncodeSupported&&Mn.detail.isVp8EncodeSupported&&Mn.detail.isH265EncodeSupported&&Mn.detail.isH264DecodeSupported&&Mn.detail.isVp8DecodeSupported&&Mn.detail.isH265DecodeSupported)return Mn;let d=xk(),{encode:h,decode:y}=yield function(){return XA(this,null,function*(){let[MA,oe]=yield Promise.all([Fv(),Vk()]);return{encode:{h264:MA.isH264EncodeSupported,vp8:MA.isVp8EncodeSupported,h265:MA.isH265EncodeSupported},decode:{h264:oe.isH264DecodeSupported,vp8:oe.isVp8DecodeSupported,h265:oe.isH265DecodeSupported}}})}(),{h264:S,vp8:L}=h,{h264:V}=y,{h265:H}=h,{vp8:lA,h265:hA}=y;if(!S||!L){let MA=yield Fv();pA.warn("detect encode again h264:".concat(S," vp8:").concat(L," result: ").concat(JSON.stringify(MA))),S=MA.isH264EncodeSupported,L=MA.isVp8EncodeSupported}if(S&&V&&za&&EE&&!xp&&!od&&(!vv||nd!==115)){let{encode:MA,decode:oe}=yield Z2();S=MA,V=oe}return Mn.result=d&&o&&a&&(S||L)&&(V||lA),Mn.detail.isBrowserSupported=d,Mn.detail.isWebRTCSupported=o,Mn.detail.isH264EncodeSupported=S,Mn.detail.isVp8EncodeSupported=L,Mn.detail.isH265EncodeSupported=H,Mn.detail.isH264DecodeSupported=V,Mn.detail.isVp8DecodeSupported=lA,Mn.detail.isH265DecodeSupported=hA,Mn.result||pA.error("".concat(navigator.userAgent," ").concat(k0(Mn.detail,!1))),eL(),ri.addNumber({key:523800,value:Date.now()-t}),Mn})),Aj=function(){return Mn.result},Xp=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},ej=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype,Jk=null;function Z2(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;return XA(this,null,function*(){return Jk||(Jk=new Promise(t=>XA(null,null,function*(){let o={encode:!1,decode:!1},a=()=>{};try{let l=document.createElement("canvas"),d=l.getContext("2d");l.width=640,l.height=480;let h=setInterval(()=>{d.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))},66),y=-1,S=-1;a=()=>{clearInterval(y),clearInterval(h),clearTimeout(S),V.close(),H.close(),L.getTracks().forEach(fe=>fe.stop())},S=setTimeout(()=>{a(),t(o)},A);let L=l.captureStream(),V=new RTCPeerConnection({}),H=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});V.addEventListener("icecandidate",fe=>H.addIceCandidate(fe.candidate)),H.addEventListener("icecandidate",fe=>V.addIceCandidate(fe.candidate)),V.addTrack(L.getVideoTracks()[0],L);let lA=yield V.createOffer();yield V.setLocalDescription(lA),yield H.setRemoteDescription(lA);let hA=yield H.createAnswer(),MA=Ok.default.parse(hA.sdp),oe=MA.media[0].rtp.findIndex(fe=>fe.codec==="H264");MA.media[0].rtp=[MA.media[0].rtp[oe]],MA.media[0].fmtp=MA.media[0].fmtp.filter(fe=>fe.payload===MA.media[0].rtp[0].payload),MA.media[0].rtcpFb&&(MA.media[0].rtcpFb=MA.media[0].rtcpFb.filter(fe=>fe.payload===MA.media[0].rtp[0].payload)),hA.sdp=Ok.default.write(MA),yield H.setLocalDescription(hA),yield V.setRemoteDescription(hA),y=setInterval(()=>XA(null,null,function*(){o.encode&&o.decode&&(a(),t(o));let[fe,je]=yield Promise.all([V.getSenders()[0].getStats(),H.getReceivers()[0].getStats()]);o.encode||fe.forEach(_e=>{_e.type==="outbound-rtp"&&(_e.mediaType===JA.VIDEO||_e.kind===JA.VIDEO)&&_e.bytesSent>0&&(o.encode=!0)}),o.decode||je.forEach(_e=>{_e.type==="inbound-rtp"&&(_e.mediaType===JA.VIDEO||_e.kind===JA.VIDEO)&&_e.bytesReceived>0&&(o.decode=!0)})}),100)}catch(l){a(),pA.warn("detectH264Supported failed",l),t({encode:!0,decode:!0})}})).then(t=>(t.encode||(t.decode=!0),(!t.encode||!t.decode)&&pA.warn("detectH264Supported encode: ".concat(t.encode," decode: ").concat(t.decode," ").concat(PC)),t)),Jk)})}var rd=null,qk=(A,t,o)=>{location.protocol==="http:"&&!Jp&&(A[t]=()=>{throw new li({code:mt.INVALID_OPERATION,message:Cc.NOT_SUPPORTED_HTTP})})},Ov=function(A){return!(A.type!=="candidate-pair"||!A.nominated||A.state!=="in-progress"&&A.state!=="succeeded")&&!(br(A.selected)&&!A.selected)};function ad(){let A="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",o=screen.height?screen.height*window.devicePixelRatio:"";A+="".concat(t," * ").concat(o)}return A}function Kk(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function jk(){let A={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let o=0;o=86,c_="RTCRtpScriptTransform"in window,$k=xC&&($p||c_),Sy=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(A=>A in window).length>0};function l_(){let A={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return ze(window.AudioDecoder)||(A.AudioDecoder=!0),ze(window.AudioEncoder)||(A.AudioEncoder=!0),ze(window.VideoDecoder)||(A.VideoDecoder=!0),ze(window.VideoEncoder)||(A.VideoEncoder=!0),ze(window.ImageDecoder)||(A.ImageDecoder=!0),A}function e1(){return"mediaSession"in navigator&&!ze(navigator.mediaSession.setActionHandler)}function vy(){return!ze(window.WebTransport)}function Vv(){return typeof WebAssembly<"u"&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function t1(){let A={browser:"".concat(cQ.name,"/").concat(cQ.version),os:pl(),displayResolution:ad(),isScreenShareSupported:Xp(),isWebRTCSupported:Sy(),isGetUserMediaSupported:Kk(),isWebAudioSupported:jk(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:l_(),isMediaSessionSupported:e1(),isWebTransportSupported:vy()};return navigator.userAgent.includes("miniProgram")&&(A.browser="mini/".concat(A.browser)),A}var AL="checkResult";function eL(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30;$A.setItem(AL+A,{ua:navigator.userAgent,checkResult:Mn})}function tL(A){Qu();let t=$A.getItem(AL+A);t&&t.ua===navigator.userAgent&&t.checkResult&&function(o,a){return!!ed(o)&&Object.keys(a).every(l=>l in o)}(t.checkResult.detail,Mn.detail)&&(Mn=t.checkResult),Hk(A)}function Am(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var hQ="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function i1(A){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[A]}var o1=!1;function Hv(){return XA(this,null,function*(){var A;try{if(o1||(A=navigator?.mediaCapabilities)==null||!A.encodingInfo)return;let t=Kp(),o=$l();if(t===0||o===0)return;o1=!0;let a=["H264","VP8","VP9","AV1","H265"],[l,d]=yield Promise.all([iL(a),oL(a)]);l&&Object.keys(l).forEach(S=>{let L=i1(S.toLowerCase());ri.addEnum({key:513707,value:+"".concat(L).concat(+l[S].supported).concat(+l[S].powerEfficient).concat(t).concat(o),useUV:!1})}),d&&Object.keys(d).forEach(S=>{let L=i1(S.toLowerCase());ri.addEnum({key:514713,value:+"".concat(L).concat(+d[S].supported).concat(+d[S].powerEfficient).concat(t).concat(o),useUV:!1})});let{sender:h,receiver:y}=n1();ri.addEnum({key:513708,value:+"".concat(t).concat(o).concat(+h.high),useUV:!1}),ri.addEnum({key:513709,value:+"".concat(t).concat(o).concat(+h.main),useUV:!1}),ri.addEnum({key:514714,value:+"".concat(t).concat(o).concat(+y.high),useUV:!1}),ri.addEnum({key:514715,value:+"".concat(t).concat(o).concat(+y.main),useUV:!1})}catch(t){pA.info("detectVideoCodecCapabilities failed",t)}})}function iL(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1920,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1080,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:30,l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:3e3;return XA(this,null,function*(){let d={};try{for(let h of A){let y=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:"video/".concat(h),width:t,height:o,bitrate:l,framerate:a}});d[h]=y}}catch{}return d})}function oL(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1920,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1080,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:30,l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:3e3;return XA(this,null,function*(){let d={};try{for(let h of A){let y=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:"video/".concat(h),width:t,height:o,bitrate:l,framerate:a}});d[h]=y}}catch{}return d})}function n1(){let A={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){let t=RTCRtpSender.getCapabilities("video");t&&t.codecs&&t.codecs.filter(o=>o.mimeType.toLowerCase()==="video/h264").forEach(o=>{if(o.sdpFmtpLine){let a=o.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(a&&a[1])switch(a[1].slice(0,2)){case"42":A.sender.base=!0;break;case"4d":A.sender.main=!0;break;case"64":A.sender.high=!0}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){let t=RTCRtpReceiver.getCapabilities("video");t&&t.codecs&&t.codecs.filter(o=>o.mimeType.toLowerCase()==="video/h264").forEach(o=>{if(o.sdpFmtpLine){let a=o.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(a&&a[1])switch(a[1].slice(0,2)){case"42":A.receiver.base=!0;break;case"4d":A.receiver.main=!0;break;case"64":A.receiver.high=!0}}})}}catch(t){pA.warn("get H264 profile levelId failed",t)}return A}var tj=dc(Xl(),1),Jv=Symbol("instance"),qv=Symbol("cacheResult"),YC=class{constructor(A,t,o){this.oldState=A,this.newState=t,this.action=o,this.aborted=!1}abort(A){this.aborted=!0,em.call(A,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},I_=class extends Error{constructor(A,t,o){super(t),this.state=A,this.message=t,this.cause=o}},Kv=new Map;function hc(A,t){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(a,l,d)=>{let h=o.action||l;if(!o.context){let S=Kv.get(a)||[];Kv.has(a)||Kv.set(a,S),S.push({from:A,to:t,action:h})}let y=d.value;d.value=function(){let S=this;for(var L=arguments.length,V=new Array(L),H=0;H{if(o.fail&&o.fail.call(this,_e),o.sync){if(o.ignoreError)return _e;throw _e}return o.ignoreError?Promise.resolve(_e):Promise.reject(_e)};if(lA)return hA(lA);let MA=S.state,oe=new YC(MA,t,h);em.call(S,oe);let fe=_e=>{var vi;return S[qv]=_e,oe.aborted||(em.call(S,t),(vi=o.success)===null||vi===void 0||vi.call(this,S[qv])),_e},je=_e=>(em.call(S,MA,_e),hA(_e));try{let _e=y.apply(this,V);return function(vi){return typeof vi=="object"&&vi&&"then"in vi}(_e)?_e.then(fe).catch(je):o.sync?fe(_e):Promise.resolve(fe(_e))}catch(_e){return je(new I_(S._state,"".concat(S.name," ").concat(h," from ").concat(A," to ").concat(t," failed: ").concat(_e),_e instanceof Error?_e:new Error(String(_e))))}}}}var u_=typeof window<"u"&&window.__AFSM__?(A,t)=>{window.dispatchEvent(new CustomEvent(A,{detail:t}))}:typeof importScripts<"u"?(A,t)=>{postMessage({type:A,payload:t})}:()=>{};function em(A,t){let o=this._state;this._state=A;let a=A.toString();A&&this.emit(a,o),this.emit(gs.STATECHANGED,A,o,t),this.updateDevTools({value:A,old:o,err:t instanceof Error?t.message:String(t)})}var gs=class zC extends tj.default{constructor(t,o,a){super(),this.name=t,this.groupName=o,this._state=zC.INIT,t||(t=Date.now().toString(36)),a?Object.setPrototypeOf(this,a):a=Object.getPrototypeOf(this),o||(this.groupName=this.constructor.name);let l=a[Jv];l?this.name=l.name+"-"+l.count++:a[Jv]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),o=Kv.get(t)||[],a=new Set,l=[],d=[],h=new Set,y=Object.getPrototypeOf(t);Kv.has(y)&&(y.stateDiagram.forEach(L=>a.add(L)),y.allStates.forEach(L=>h.add(L))),o.forEach(L=>{let{from:V,to:H,action:lA}=L;typeof V=="string"?l.push({from:V,to:H,action:lA}):V.length?V.forEach(hA=>{l.push({from:hA,to:H,action:lA})}):d.push({to:H,action:lA})}),l.forEach(L=>{let{from:V,to:H,action:lA}=L;h.add(V),h.add(H),h.add(lA+"ing"),a.add("".concat(V," --> ").concat(lA,"ing : ").concat(lA)),a.add("".concat(lA,"ing --> ").concat(H," : ").concat(lA," 🟢")),a.add("".concat(lA,"ing --> ").concat(V," : ").concat(lA," 🔴"))}),d.forEach(L=>{let{to:V,action:H}=L;a.add("".concat(H,"ing --> ").concat(V," : ").concat(H," 🟢")),h.forEach(lA=>{lA!==V&&a.add("".concat(lA," --> ").concat(H,"ing : ").concat(H))})});let S=[...a];return Object.defineProperties(t,{stateDiagram:{value:S},allStates:{value:h}}),S}static get(t){let o;return typeof t=="string"?(o=zC.instances.get(t),o||zC.instances.set(t,o=new zC(t,void 0,Object.create(zC.prototype)))):(o=zC.instances2.get(t),o||zC.instances2.set(t,o=new zC(t.constructor.name,void 0,Object.create(zC.prototype)))),o}static getState(t){var o;return(o=zC.get(t))===null||o===void 0?void 0:o.state}updateDevTools(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};u_(zC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){em.call(this,t)}};gs.STATECHANGED="stateChanged",gs.UPDATEAFSM="updateAFSM",gs.INIT="[*]",gs.ON="on",gs.OFF="off",gs.instances=new Map,gs.instances2=new WeakMap;var E_=typeof window<"u",nL=E_&&window.requestIdleCallback||function(A){let t=Date.now();return setTimeout(()=>{A({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})},1e3)},yl=E_&&window.cancelIdleCallback||function(A){clearTimeout(A)},tm=E_&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),My=class BE{static generateTaskID(){return this.currentTaskID++}static run(t,o,a){a!=null&&a.fps&&(a.delay=a.delay||Number((1e3/a.fps).toFixed(2))),a=Di(t==="interval"?{delay:2e3,count:0,backgroundTask:!0}:t==="ric"?{delay:1e4,count:0}:t==="raf"?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},a);let l=So(Di({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:t,callback:o},a),{delay:a.delay});return this.taskMap.set(l.taskID,l),this[t](l),l.taskID}static interval(t){return t.intervalID=setInterval(()=>{t.callback(),t.loopCount+=1,BE.isBreakLoop(t)},t.delay)}static intervalInWorker(t){BE.sharedWorker||(BE.sharedWorker=new Worker(URL.createObjectURL(new Blob([` +`)),V}var vn,Ss,Ok=dc(wK(),1),Pk=class{constructor(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];Y(this,"countMap",new Map),Y(this,"distributionMap",new Map),Y(this,"version"),Y(this,"log",pA.createLogger({id:"kv"})),A&&(F.on("102",t=>{let{track:o,cost:a}=t;this.addSuccessEvent({key:o.kind===JA.AUDIO?501700:511700,cost:a})}),F.on("103",t=>{let{track:o,error:a}=t;this.addFailedEvent({key:o.kind===JA.AUDIO?501700:511700,error:a})}),F.on("266",t=>{let{enable:o}=t;this.log.info("".concat(o?"enable":"disable"," sso")),o?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(A,t){let o={msg_sdk_basic_info:{uint32_sdk_version:ok(this.version||Wd),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(a=>{let[l,d]=a;return{uint32_key:l,uint32_count:d}}),stats_distribution:[...this.distributionMap.entries()].map(a=>{let[l,d]=a;return{uint32_key:l,distribution_items:[...d.entries()].map(h=>{let[y,S]=h;return{uint32_item_key:y,uint32_item_value:S}})}}),str_user_sig:A,bytes_report_token:t};return this.countMap.clear(),this.distributionMap.clear(),o}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(A){let t=+String(A).slice(-3);return t>=700&&t<799}isErrorCodeKey(A){let t=+String(A).slice(-3);return t>=600&&t<699}isCountKey(A){let t=+String(A).slice(-3);return t>=0&&t<599}isNumberKey(A){let t=+String(A).slice(-3);return t>=800&&t<899}addCount(A){let{key:t,useUV:o=!1}=A;this.isCountKey(t)?o&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug("".concat(t," is not count key, last 3 number should be 0~599"))}addEnum(A){let{key:t,value:o,useUV:a=!0}=A;var l;if(!this.isEnumKey(t))return this.log.debug("".concat(t," is not enum key, last 3 number should be 700~799"));if(a&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);let d=((l=this.distributionMap)==null?void 0:l.get(t))||new Map;d.set(o,(d.get(o)||0)+1),this.distributionMap.set(t,d)}addNumber(A){let{key:t,value:o,split:a=100,useUV:l=!1,max:d=5e3}=A;var h;if(!this.isNumberKey(t))return this.log.debug("".concat(t," is not number key, last 3 number should be 800~899"));if(l&&this.countMap.has(t))return;o>d&&(o=d),this.countMap.set(t,(this.countMap.get(t)||0)+1);let y=((h=this.distributionMap)==null?void 0:h.get(t))||new Map,S=0;if(Ys(a))S=Math.floor(o/a);else for(let L=a.length-1;L>0;L--)if(o>a[L]){S=L;break}y.set(S,(y.get(S)||0)+1),this.distributionMap.set(t,y)}addSuccessEvent(A){let{key:t,cost:o,timeKey:a,split:l}=A;if(t&&(this.addEnum({key:t,value:1,useUV:!1}),o)){let d=+String(t).slice(-3);d<800&&d>=700?this.addNumber({key:a||t+100,value:o,split:l}):a||this.log.debug("time stat ignored, ".concat(t))}}addFailedEvent(A){let{key:t,error:o}=A;if(!t)return;let a=mt.UNKNOWN;o&&(Ys(o)?a=o:(!ze(o.extraCode)||!ze(o.code))&&(a=o.extraCode||o.code)),this.addEnum({key:t,value:0,useUV:!1}),this.addEnum({key:t,value:Math.abs(a),useUV:!1})}},K2=((vn=K2||{})[vn.enterRoom=500700]="enterRoom",vn[vn.exitRoom=500701]="exitRoom",vn[vn.switchRole=500702]="switchRole",vn[vn.destroy=500703]="destroy",vn[vn.startLocalAudio=500704]="startLocalAudio",vn[vn.updateLocalAudio=500705]="updateLocalAudio",vn[vn.stopLocalAudio=500706]="stopLocalAudio",vn[vn.startLocalVideo=500707]="startLocalVideo",vn[vn.updateLocalVideo=500708]="updateLocalVideo",vn[vn.stopLocalVideo=500709]="stopLocalVideo",vn[vn.startScreenShare=500710]="startScreenShare",vn[vn.updateScreenShare=500711]="updateScreenShare",vn[vn.stopScreenShare=500712]="stopScreenShare",vn[vn.startRemoteVideo=500713]="startRemoteVideo",vn[vn.updateRemoteVideo=500714]="updateRemoteVideo",vn[vn.stopRemoteVideo=500715]="stopRemoteVideo",vn[vn.muteRemoteAudio=500716]="muteRemoteAudio",vn[vn.setRemoteAudioVolume=500717]="setRemoteAudioVolume",vn[vn.use=500718]="use",vn[vn.switchRoom=500719]="switchRoom",vn[vn.getPermissions=500720]="getPermissions",vn[vn.sendSEIMessage=5e5]="sendSEIMessage",vn[vn.sendCustomMessage=500001]="sendCustomMessage",vn),j2=(A=>(A[A.AudioMixer=550700]="AudioMixer",A[A.AIDenoiser=551700]="AIDenoiser",A[A.VirtualBackground=570700]="VirtualBackground",A[A.Beauty=571700]="Beauty",A[A.Watermark=572700]="Watermark",A[A.BasicBeauty=574700]="BasicBeauty",A[A.FaceDetector=575700]="FaceDetector",A[A.CDNStreaming=590700]="CDNStreaming",A[A.DeviceDetector=591700]="DeviceDetector",A[A.Debug=592700]="Debug",A[A.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",A[A.VideoMixer=594700]="VideoMixer",A[A.AudioProcessor=595700]="AudioProcessor",A[A.LEBPlayer=596700]="LEBPlayer",A[A.RealtimeTranscriber=597700]="RealtimeTranscriber",A))(j2||{}),py=(A=>(A[A.AudioMixer=550701]="AudioMixer",A[A.AIDenoiser=551701]="AIDenoiser",A[A.VirtualBackground=570701]="VirtualBackground",A[A.Beauty=571701]="Beauty",A[A.Watermark=572701]="Watermark",A[A.BasicBeauty=574701]="BasicBeauty",A[A.FaceDetector=575701]="FaceDetector",A[A.CDNStreaming=590701]="CDNStreaming",A[A.DeviceDetector=591701]="DeviceDetector",A[A.Debug=592701]="Debug",A[A.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",A[A.VideoMixer=594701]="VideoMixer",A[A.AudioProcessor=595701]="AudioProcessor",A[A.LEBPlayer=596701]="LEBPlayer",A[A.RealtimeTranscriber=597701]="RealtimeTranscriber",A))(py||{}),r_=(A=>(A[A.AudioMixer=550702]="AudioMixer",A[A.AIDenoiser=551702]="AIDenoiser",A[A.VirtualBackground=570702]="VirtualBackground",A[A.Beauty=571702]="Beauty",A[A.Watermark=572702]="Watermark",A[A.BasicBeauty=574702]="BasicBeauty",A[A.FaceDetector=575702]="FaceDetector",A[A.CDNStreaming=590702]="CDNStreaming",A[A.DeviceDetector=591702]="DeviceDetector",A[A.Debug=592702]="Debug",A[A.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",A[A.VideoMixer=594702]="VideoMixer",A[A.AudioProcessor=595702]="AudioProcessor",A[A.LEBPlayer=596702]="LEBPlayer",A[A.RealtimeTranscriber=597702]="RealtimeTranscriber",A))(r_||{}),fy=((Ss=fy||{})[Ss.DECODER_TYPE=514700]="DECODER_TYPE",Ss[Ss.DECODER_HW_SW=514701]="DECODER_HW_SW",Ss[Ss.DECODE_RESULT=514702]="DECODE_RESULT",Ss[Ss.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",Ss[Ss.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",Ss[Ss.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",Ss[Ss.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",Ss[Ss.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",Ss[Ss.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",Ss[Ss.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",Ss[Ss.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",Ss[Ss.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",Ss[Ss.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",Ss[Ss.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",Ss[Ss.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",Ss[Ss.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",Ss[Ss.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",Ss[Ss.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",Ss[Ss.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",Ss),XK=new Pk(!0),eB=new Pk(!1),ri=XK,Mn={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},W2=new Map([[gr,["Firefox",pv]],[ry,["Edg",Ek]],[$0,["Chrome",A_]],[fg,["Safari",aQ]],[od,["TBS",Ck]],[xp,["XWEB",hk]],[sQ&&Pp,["WeChat",Bk]],[W0,["QQ(Win)",Qk]],[fv,["QQ(Mobile)",ay]],[Yp,["QQ(Mobile X5)",ay]],[yv,["QQ(Mac)",pk]],[z0,["QQ(iPad)",Dv]],[Z0,["MI",Vp]],[AB,["HW",Sk]],[Sv,["Samsung",vk]],[vv,["OPPO",Mk]],[Mv,["VIVO",Rv]],[sy,["EDGE",uk]],[mv,["SogouMobile",K0]],[j0,["Sogou",dk]]]);function Lv(){let A=W2.get(!0);return{browserName:A?A[0]:"unknown",browserVersion:A?A[1]:"unknown"}}var xk=function(){return!(fk||sy||ry&&q0<80||gr&&J0<56)},a_=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(A=>A in window)},Yk=function(){if(!navigator.mediaDevices)return Qu()||pA.error(Cc.NOT_SUPPORTED_MEDIA),!1;let A=["getUserMedia","enumerateDevices"];return A.filter(t=>t in navigator.mediaDevices).length===A.length},z2=!1;function Qu(){return location.protocol==="http:"&&!Jp&&(z2||pA.error(sn({key:Go.NOT_SUPPORTED_HTTP})),z2=!0,!0)}var Uv=function(){return window?.OffscreenCanvas&&window?.MediaStreamTrackProcessor&&window?.MediaStreamTrackGenerator},$K=function(){return!(window==null||!window.MediaStreamTrackGenerator)},Fv=function(){return XA(this,null,function*(){var A,t,o;if(Mn.detail.isH264EncodeSupported&&Mn.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Mn.detail.isH264EncodeSupported,isVp8EncodeSupported:Mn.detail.isVp8EncodeSupported,isH265EncodeSupported:Mn.detail.isH265EncodeSupported};let a,l=!1,d=!1,h=!1;try{let y=new RTCPeerConnection,S=document.createElement(JA.CANVAS);S.getContext("2d");let L=S.captureStream(0);return y.addTrack(L.getVideoTracks()[0],L),a=yield y.createOffer(),l=((A=a.sdp)==null?void 0:A.toLowerCase().indexOf("h264"))!==-1,d=((t=a.sdp)==null?void 0:t.toLowerCase().indexOf("vp8"))!==-1,h=((o=a.sdp)==null?void 0:o.toLowerCase().indexOf("h265"))!==-1,y.close(),{isH264EncodeSupported:l,isVp8EncodeSupported:d,isH265EncodeSupported:h}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},Vk=function(){return XA(this,null,function*(){var A;if(Mn.detail.isH264DecodeSupported&&Mn.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Mn.detail.isH264DecodeSupported,isVp8DecodeSupported:Mn.detail.isVp8DecodeSupported,isH265DecodeSupported:Mn.detail.isH265DecodeSupported};let t,o=!1,a=!1;try{let l=new RTCPeerConnection;AC()?(l.addTransceiver(JA.VIDEO,{direction:"recvonly"}),t=yield l.createOffer()):t=yield l.createOffer({offerToReceiveVideo:!0}),t.sdp.toLowerCase().indexOf("h264")!==-1&&(o=!0),t.sdp.toLowerCase().indexOf("vp8")!==-1&&(a=!0);let d=((A=t.sdp)==null?void 0:A.toLowerCase().indexOf("h265"))!==-1;return l.close(),{isH264DecodeSupported:o,isVp8DecodeSupported:a,isH265DecodeSupported:d}}catch{return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})},Hk=nk(A=>XA(null,null,function*(){let t=Date.now(),o=Sy(),a=Yk(),l=a_();if(Mn.detail.isWebRTCSupported=o,Mn.detail.isMediaDevicesSupported=a,Mn.detail.isWebCodecsSupported=l,Mn.detail.isScreenShareSupported=Xp(),Mn.detail.isSmallStreamSupported=xv(),A===37)return Object.assign(Mn.detail,yield function(){return XA(this,null,function*(){return rd||(rd=new Promise(MA=>XA(null,null,function*(){let oe={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!a_())return void MA(oe);let fe=null,je=null,_e=null,vi=()=>{_e&&clearTimeout(_e),fe=null,je=null};try{fe=document.createElement("canvas"),je=fe.getContext("2d"),fe.width=320,fe.height=240;let Fe=0,Dt=()=>{!je||!fe||(je.fillStyle="hsl(".concat(Fe%360,", 50%, 50%)"),je.fillRect(0,0,fe.width,fe.height),je.fillStyle="white",je.font="20px Arial",je.fillText("Frame ".concat(Fe),10,30),Fe++)};_e=setTimeout(()=>{vi(),MA(oe)},5e3);let pi=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(pi.map(Mi=>XA(null,null,function*(){let Wo,zo={type:Mi.type,encodeSupported:!1,decodeSupported:!1};try{Wo=yield new Promise((vs,Zo)=>XA(null,null,function*(){try{let Vn=new VideoEncoder({output:wa=>{vs(wa),zo.encodeSupported=!0},error:Zo});Vn.configure(Mi.encodeConfig),Dt();let Dg=new VideoFrame(fe,{timestamp:0});Vn.encode(Dg,{keyFrame:!0}),Dg.close(),yield Vn.flush(),Vn.close()}catch(Vn){Zo(Vn)}}))}catch(vs){return pA.warn("".concat(Mi.type," encoder error:"),vs),zo}try{yield new Promise((vs,Zo)=>XA(null,null,function*(){try{let Vn=new VideoDecoder({output:Dg=>{zo.decodeSupported=!0,vs(0),Dg.close()},error:Zo});Vn.configure(Mi.decodeConfig),Vn.decode(Wo),yield Vn.flush(),Vn.close()}catch(Vn){Zo(Vn)}}))}catch(vs){pA.warn("".concat(Mi.type," decoder error:"),vs)}return zo})))).forEach(Mi=>{Mi.type==="h264"?(oe.isH264EncodeSupported=Mi.encodeSupported,oe.isH264DecodeSupported=Mi.decodeSupported):Mi.type==="vp8"&&(oe.isVp8EncodeSupported=Mi.encodeSupported,oe.isVp8DecodeSupported=Mi.decodeSupported)}),vi(),MA(oe)}catch(Fe){vi(),pA.warn("detectWebCodecsSupported failed:",Fe),MA(oe)}})),rd)})}()),Mn.detail.isBrowserSupported=l,Mn.result=a&&l,Mn.result||pA.error("".concat(navigator.userAgent," ").concat(k0(Mn.detail,!1))),eL(A),ri.addNumber({key:523800,value:Date.now()-t}),Mn;if(Mn.result&&Mn.detail.isH264EncodeSupported&&Mn.detail.isVp8EncodeSupported&&Mn.detail.isH265EncodeSupported&&Mn.detail.isH264DecodeSupported&&Mn.detail.isVp8DecodeSupported&&Mn.detail.isH265DecodeSupported)return Mn;let d=xk(),{encode:h,decode:y}=yield function(){return XA(this,null,function*(){let[MA,oe]=yield Promise.all([Fv(),Vk()]);return{encode:{h264:MA.isH264EncodeSupported,vp8:MA.isVp8EncodeSupported,h265:MA.isH265EncodeSupported},decode:{h264:oe.isH264DecodeSupported,vp8:oe.isVp8DecodeSupported,h265:oe.isH265DecodeSupported}}})}(),{h264:S,vp8:L}=h,{h264:V}=y,{h265:H}=h,{vp8:lA,h265:hA}=y;if(!S||!L){let MA=yield Fv();pA.warn("detect encode again h264:".concat(S," vp8:").concat(L," result: ").concat(JSON.stringify(MA))),S=MA.isH264EncodeSupported,L=MA.isVp8EncodeSupported}if(S&&V&&za&&EE&&!xp&&!od&&(!vv||nd!==115)){let{encode:MA,decode:oe}=yield Z2();S=MA,V=oe}return Mn.result=d&&o&&a&&(S||L)&&(V||lA),Mn.detail.isBrowserSupported=d,Mn.detail.isWebRTCSupported=o,Mn.detail.isH264EncodeSupported=S,Mn.detail.isVp8EncodeSupported=L,Mn.detail.isH265EncodeSupported=H,Mn.detail.isH264DecodeSupported=V,Mn.detail.isVp8DecodeSupported=lA,Mn.detail.isH265DecodeSupported=hA,Mn.result||pA.error("".concat(navigator.userAgent," ").concat(k0(Mn.detail,!1))),eL(),ri.addNumber({key:523800,value:Date.now()-t}),Mn})),Aj=function(){return Mn.result},Xp=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},ej=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype,Jk=null;function Z2(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;return XA(this,null,function*(){return Jk||(Jk=new Promise(t=>XA(null,null,function*(){let o={encode:!1,decode:!1},a=()=>{};try{let l=document.createElement("canvas"),d=l.getContext("2d");l.width=640,l.height=480;let h=setInterval(()=>{d.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))},66),y=-1,S=-1;a=()=>{clearInterval(y),clearInterval(h),clearTimeout(S),V.close(),H.close(),L.getTracks().forEach(fe=>fe.stop())},S=setTimeout(()=>{a(),t(o)},A);let L=l.captureStream(),V=new RTCPeerConnection({}),H=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});V.addEventListener("icecandidate",fe=>H.addIceCandidate(fe.candidate)),H.addEventListener("icecandidate",fe=>V.addIceCandidate(fe.candidate)),V.addTrack(L.getVideoTracks()[0],L);let lA=yield V.createOffer();yield V.setLocalDescription(lA),yield H.setRemoteDescription(lA);let hA=yield H.createAnswer(),MA=Ok.default.parse(hA.sdp),oe=MA.media[0].rtp.findIndex(fe=>fe.codec==="H264");MA.media[0].rtp=[MA.media[0].rtp[oe]],MA.media[0].fmtp=MA.media[0].fmtp.filter(fe=>fe.payload===MA.media[0].rtp[0].payload),MA.media[0].rtcpFb&&(MA.media[0].rtcpFb=MA.media[0].rtcpFb.filter(fe=>fe.payload===MA.media[0].rtp[0].payload)),hA.sdp=Ok.default.write(MA),yield H.setLocalDescription(hA),yield V.setRemoteDescription(hA),y=setInterval(()=>XA(null,null,function*(){o.encode&&o.decode&&(a(),t(o));let[fe,je]=yield Promise.all([V.getSenders()[0].getStats(),H.getReceivers()[0].getStats()]);o.encode||fe.forEach(_e=>{_e.type==="outbound-rtp"&&(_e.mediaType===JA.VIDEO||_e.kind===JA.VIDEO)&&_e.bytesSent>0&&(o.encode=!0)}),o.decode||je.forEach(_e=>{_e.type==="inbound-rtp"&&(_e.mediaType===JA.VIDEO||_e.kind===JA.VIDEO)&&_e.bytesReceived>0&&(o.decode=!0)})}),100)}catch(l){a(),pA.warn("detectH264Supported failed",l),t({encode:!0,decode:!0})}})).then(t=>(t.encode||(t.decode=!0),(!t.encode||!t.decode)&&pA.warn("detectH264Supported encode: ".concat(t.encode," decode: ").concat(t.decode," ").concat(PC)),t)),Jk)})}var rd=null,qk=(A,t,o)=>{location.protocol==="http:"&&!Jp&&(A[t]=()=>{throw new li({code:mt.INVALID_OPERATION,message:Cc.NOT_SUPPORTED_HTTP})})},Ov=function(A){return!(A.type!=="candidate-pair"||!A.nominated||A.state!=="in-progress"&&A.state!=="succeeded")&&!(br(A.selected)&&!A.selected)};function ad(){let A="";if(screen.width){let t=screen.width?screen.width*window.devicePixelRatio:"",o=screen.height?screen.height*window.devicePixelRatio:"";A+="".concat(t," * ").concat(o)}return A}function Kk(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function jk(){let A={isSupported:!1},t=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let o=0;o=86,c_="RTCRtpScriptTransform"in window,$k=xC&&($p||c_),Sy=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(A=>A in window).length>0};function l_(){let A={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return ze(window.AudioDecoder)||(A.AudioDecoder=!0),ze(window.AudioEncoder)||(A.AudioEncoder=!0),ze(window.VideoDecoder)||(A.VideoDecoder=!0),ze(window.VideoEncoder)||(A.VideoEncoder=!0),ze(window.ImageDecoder)||(A.ImageDecoder=!0),A}function e1(){return"mediaSession"in navigator&&!ze(navigator.mediaSession.setActionHandler)}function vy(){return!ze(window.WebTransport)}function Vv(){return typeof WebAssembly<"u"&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function t1(){let A={browser:"".concat(cQ.name,"/").concat(cQ.version),os:pl(),displayResolution:ad(),isScreenShareSupported:Xp(),isWebRTCSupported:Sy(),isGetUserMediaSupported:Kk(),isWebAudioSupported:jk(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:l_(),isMediaSessionSupported:e1(),isWebTransportSupported:vy()};return navigator.userAgent.includes("miniProgram")&&(A.browser="mini/".concat(A.browser)),A}var AL="checkResult";function eL(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30;$A.setItem(AL+A,{ua:navigator.userAgent,checkResult:Mn})}function tL(A){Qu();let t=$A.getItem(AL+A);t&&t.ua===navigator.userAgent&&t.checkResult&&function(o,a){return!!ed(o)&&Object.keys(a).every(l=>l in o)}(t.checkResult.detail,Mn.detail)&&(Mn=t.checkResult),Hk(A)}function Am(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var hQ="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function i1(A){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[A]}var o1=!1;function Hv(){return XA(this,null,function*(){var A;try{if(o1||(A=navigator?.mediaCapabilities)==null||!A.encodingInfo)return;let t=Kp(),o=AI();if(t===0||o===0)return;o1=!0;let a=["H264","VP8","VP9","AV1","H265"],[l,d]=yield Promise.all([iL(a),oL(a)]);l&&Object.keys(l).forEach(S=>{let L=i1(S.toLowerCase());ri.addEnum({key:513707,value:+"".concat(L).concat(+l[S].supported).concat(+l[S].powerEfficient).concat(t).concat(o),useUV:!1})}),d&&Object.keys(d).forEach(S=>{let L=i1(S.toLowerCase());ri.addEnum({key:514713,value:+"".concat(L).concat(+d[S].supported).concat(+d[S].powerEfficient).concat(t).concat(o),useUV:!1})});let{sender:h,receiver:y}=n1();ri.addEnum({key:513708,value:+"".concat(t).concat(o).concat(+h.high),useUV:!1}),ri.addEnum({key:513709,value:+"".concat(t).concat(o).concat(+h.main),useUV:!1}),ri.addEnum({key:514714,value:+"".concat(t).concat(o).concat(+y.high),useUV:!1}),ri.addEnum({key:514715,value:+"".concat(t).concat(o).concat(+y.main),useUV:!1})}catch(t){pA.info("detectVideoCodecCapabilities failed",t)}})}function iL(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1920,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1080,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:30,l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:3e3;return XA(this,null,function*(){let d={};try{for(let h of A){let y=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:"video/".concat(h),width:t,height:o,bitrate:l,framerate:a}});d[h]=y}}catch{}return d})}function oL(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1920,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1080,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:30,l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:3e3;return XA(this,null,function*(){let d={};try{for(let h of A){let y=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:"video/".concat(h),width:t,height:o,bitrate:l,framerate:a}});d[h]=y}}catch{}return d})}function n1(){let A={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){let t=RTCRtpSender.getCapabilities("video");t&&t.codecs&&t.codecs.filter(o=>o.mimeType.toLowerCase()==="video/h264").forEach(o=>{if(o.sdpFmtpLine){let a=o.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(a&&a[1])switch(a[1].slice(0,2)){case"42":A.sender.base=!0;break;case"4d":A.sender.main=!0;break;case"64":A.sender.high=!0}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){let t=RTCRtpReceiver.getCapabilities("video");t&&t.codecs&&t.codecs.filter(o=>o.mimeType.toLowerCase()==="video/h264").forEach(o=>{if(o.sdpFmtpLine){let a=o.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(a&&a[1])switch(a[1].slice(0,2)){case"42":A.receiver.base=!0;break;case"4d":A.receiver.main=!0;break;case"64":A.receiver.high=!0}}})}}catch(t){pA.warn("get H264 profile levelId failed",t)}return A}var tj=dc($l(),1),Jv=Symbol("instance"),qv=Symbol("cacheResult"),YC=class{constructor(A,t,o){this.oldState=A,this.newState=t,this.action=o,this.aborted=!1}abort(A){this.aborted=!0,em.call(A,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},I_=class extends Error{constructor(A,t,o){super(t),this.state=A,this.message=t,this.cause=o}},Kv=new Map;function hc(A,t){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(a,l,d)=>{let h=o.action||l;if(!o.context){let S=Kv.get(a)||[];Kv.has(a)||Kv.set(a,S),S.push({from:A,to:t,action:h})}let y=d.value;d.value=function(){let S=this;for(var L=arguments.length,V=new Array(L),H=0;H{if(o.fail&&o.fail.call(this,_e),o.sync){if(o.ignoreError)return _e;throw _e}return o.ignoreError?Promise.resolve(_e):Promise.reject(_e)};if(lA)return hA(lA);let MA=S.state,oe=new YC(MA,t,h);em.call(S,oe);let fe=_e=>{var vi;return S[qv]=_e,oe.aborted||(em.call(S,t),(vi=o.success)===null||vi===void 0||vi.call(this,S[qv])),_e},je=_e=>(em.call(S,MA,_e),hA(_e));try{let _e=y.apply(this,V);return function(vi){return typeof vi=="object"&&vi&&"then"in vi}(_e)?_e.then(fe).catch(je):o.sync?fe(_e):Promise.resolve(fe(_e))}catch(_e){return je(new I_(S._state,"".concat(S.name," ").concat(h," from ").concat(A," to ").concat(t," failed: ").concat(_e),_e instanceof Error?_e:new Error(String(_e))))}}}}var u_=typeof window<"u"&&window.__AFSM__?(A,t)=>{window.dispatchEvent(new CustomEvent(A,{detail:t}))}:typeof importScripts<"u"?(A,t)=>{postMessage({type:A,payload:t})}:()=>{};function em(A,t){let o=this._state;this._state=A;let a=A.toString();A&&this.emit(a,o),this.emit(gs.STATECHANGED,A,o,t),this.updateDevTools({value:A,old:o,err:t instanceof Error?t.message:String(t)})}var gs=class zC extends tj.default{constructor(t,o,a){super(),this.name=t,this.groupName=o,this._state=zC.INIT,t||(t=Date.now().toString(36)),a?Object.setPrototypeOf(this,a):a=Object.getPrototypeOf(this),o||(this.groupName=this.constructor.name);let l=a[Jv];l?this.name=l.name+"-"+l.count++:a[Jv]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let t=Object.getPrototypeOf(this),o=Kv.get(t)||[],a=new Set,l=[],d=[],h=new Set,y=Object.getPrototypeOf(t);Kv.has(y)&&(y.stateDiagram.forEach(L=>a.add(L)),y.allStates.forEach(L=>h.add(L))),o.forEach(L=>{let{from:V,to:H,action:lA}=L;typeof V=="string"?l.push({from:V,to:H,action:lA}):V.length?V.forEach(hA=>{l.push({from:hA,to:H,action:lA})}):d.push({to:H,action:lA})}),l.forEach(L=>{let{from:V,to:H,action:lA}=L;h.add(V),h.add(H),h.add(lA+"ing"),a.add("".concat(V," --> ").concat(lA,"ing : ").concat(lA)),a.add("".concat(lA,"ing --> ").concat(H," : ").concat(lA," 🟢")),a.add("".concat(lA,"ing --> ").concat(V," : ").concat(lA," 🔴"))}),d.forEach(L=>{let{to:V,action:H}=L;a.add("".concat(H,"ing --> ").concat(V," : ").concat(H," 🟢")),h.forEach(lA=>{lA!==V&&a.add("".concat(lA," --> ").concat(H,"ing : ").concat(H))})});let S=[...a];return Object.defineProperties(t,{stateDiagram:{value:S},allStates:{value:h}}),S}static get(t){let o;return typeof t=="string"?(o=zC.instances.get(t),o||zC.instances.set(t,o=new zC(t,void 0,Object.create(zC.prototype)))):(o=zC.instances2.get(t),o||zC.instances2.set(t,o=new zC(t.constructor.name,void 0,Object.create(zC.prototype)))),o}static getState(t){var o;return(o=zC.get(t))===null||o===void 0?void 0:o.state}updateDevTools(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};u_(zC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},t))}get state(){return this._state}set state(t){em.call(this,t)}};gs.STATECHANGED="stateChanged",gs.UPDATEAFSM="updateAFSM",gs.INIT="[*]",gs.ON="on",gs.OFF="off",gs.instances=new Map,gs.instances2=new WeakMap;var E_=typeof window<"u",nL=E_&&window.requestIdleCallback||function(A){let t=Date.now();return setTimeout(()=>{A({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-t))})},1e3)},yl=E_&&window.cancelIdleCallback||function(A){clearTimeout(A)},tm=E_&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),My=class BE{static generateTaskID(){return this.currentTaskID++}static run(t,o,a){a!=null&&a.fps&&(a.delay=a.delay||Number((1e3/a.fps).toFixed(2))),a=Di(t==="interval"?{delay:2e3,count:0,backgroundTask:!0}:t==="ric"?{delay:1e4,count:0}:t==="raf"?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},a);let l=So(Di({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:t,callback:o},a),{delay:a.delay});return this.taskMap.set(l.taskID,l),this[t](l),l.taskID}static interval(t){return t.intervalID=setInterval(()=>{t.callback(),t.loopCount+=1,BE.isBreakLoop(t)},t.delay)}static intervalInWorker(t){BE.sharedWorker||(BE.sharedWorker=new Worker(URL.createObjectURL(new Blob([` const timers = new Map(); self.onmessage = function(e) { const { taskId, delay, type } = e.data; @@ -281,7 +281,7 @@ Refer to: `.concat(q2("en",y),` - `,o.onclick=this.onQuestionClick.bind(this);let a=document.createElement("div");a.className=Z,a.innerText="".concat(Zd()?"详情 >":"Detail >"),a.onclick=this.onCollapseClick.bind(this);let l=A.content.firstChild,d=l.querySelector(".".concat(C_));return d.appendChild(a),d.appendChild(o),d.appendChild(t),l}addDiaLog(){Si()||(Ot=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(jv)).onclick=A=>A.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",pA.info("show autoplay dialog"),ds.uploadEvent({log:Te}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Ot=!1),qc=null}onConfirm(){pA.warn("confirm clicked, try resume stream"),F.emit(rA.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let A=this._dialogNode.querySelector(".".concat(bA));A.style.visibility="".concat(this._showDetail?"hidden":"visible"),A.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||ds.uploadEvent({log:xe}),this._isCollapseClicked=!0}onQuestionClick(){window.open(bi,"_blank"),this._isQuestionClicked||ds.uploadEvent({log:It}),this._isQuestionClicked=!0}},qc=null;function JC(){qc||(qc=new ra)}var Bi,bo=class QX extends HC{constructor(t){super(t,JA.VIDEO),Y(this,"stat",{}),Y(this,"_calculateTimeout",-1),Y(this,"viewMirror",!1),Y(this,"objectFit","cover"),Y(this,"container"),Y(this,"canvas"),Y(this,"shouldRenderAlpha",!1),Y(this,"_preSize",{width:0,height:0}),Y(this,"posterImg"),Y(this,"pipWindow"),Y(this,"enterPIPPromise"),Y(this,"_originContainerPosition"),Y(this,"_isResettingSrcObject",!1),Y(this,"_wrapper",null),Y(this,"_useWrapper",!1),Y(this,"_isFirstFrameRenderEmitted",!1),this.mode=t.canvas?1:0,this.container=t.container,this.canvas=t.canvas,ze(t.viewMirror)||(this.viewMirror=t.viewMirror),ze(t.objectFit)||(this.objectFit=t.objectFit),this.initializeElement()}get isPlaying(){var t;return!(this._state!=="PLAYING"||this.element&&this.element.paused)&&((t=this.track)==null?void 0:t.readyState)==="live"&&!this.track.muted}initializeElement(){let t=document.createElement(JA.VIDEO);this.track&&this.mode!==2&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,za&&(t.poster="data:,"),this._appendToWrapper(),this.bindElementEvents(),this.calculateStat(),this._bindFirstFrameRenderEvent(t)}_bindFirstFrameRenderEvent(t){let o=()=>{if(this._isFirstFrameRenderEmitted)return;this._isFirstFrameRenderEmitted=!0;let a=t.videoWidth||0,l=t.videoHeight||0;this._log.info("first frame render: ".concat(a,"x").concat(l)),this.emit(Mo.FIRST_FRAME_RENDER,{width:a,height:l})};typeof t.requestVideoFrameCallback=="function"?t.requestVideoFrameCallback(o):t.addEventListener("loadeddata",o,{once:!0})}get styleAttribute(){let t=this._useWrapper?"grid-area:1/1;width:100%;height:100%;object-fit:".concat(this.objectFit,";").concat(this.shouldRenderAlpha?"":"background-color:black",";"):"width:100%;height:100%;object-fit:".concat(this.objectFit,";").concat(this.shouldRenderAlpha?"":"background-color:black",";");return this.viewMirror&&(t+="transform:scaleX(-1);"),t}setLiveMode(t){if(this._useWrapper!==t&&(this._useWrapper=t,this.elementToRender&&this.elementToRender.setAttribute("style",this.styleAttribute),this.container&&this.elementToRender))if(t){let o=this._getOrCreateWrapper();o.insertBefore(this.elementToRender,o.firstChild)}else this.container.appendChild(this.elementToRender),this._cleanupWrapper()}setContainer(t){if(this.container===t)return;let o=this._wrapper,a=this.container;this.container=t,this._pausedRetryCount=Gp,this.track&&this.elementToRender&&this._appendToWrapper(),o&&a&&a!==this.container&&o.isConnected&&o.children.length===0&&o.remove()}_getOrCreateWrapper(){if(!this.container)throw new Error("[VideoPlayer] container is required");let t=this.container.querySelector("[data-trtc-video-wrapper]");return t||(t=document.createElement("div"),t.setAttribute("data-trtc-video-wrapper","true"),t.style.cssText="display:grid;width:100%;height:100%;",this.container.appendChild(t)),this._wrapper=t,t}_appendToWrapper(t){let o=t??this.elementToRender;if(this.container&&o)if(this._useWrapper){let a=this._getOrCreateWrapper();a.insertBefore(o,a.firstChild)}else this.container.appendChild(o)}bindElementEvents(){let t=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),this.handleFullscreenChange=this.handleFullscreenChange.bind(this),this.handleVolumeChange=this.handleVolumeChange.bind(this),t&&t.add(JA.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(JA.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(JA.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener(JA.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.addEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.addEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.addEventListener("volumechange",this.handleVolumeChange))}handleTrackEvent(t){var o;return t.type===JA.MUTE&&((o=this.stat)!=null&&o.fps&&(this.stat.fps=0),this.isFullscreen()&&this.resetSrcObjectToReplay()),super.handleTrackEvent(t)}handleFullscreenChange(){this.isFullscreen()?(this._log.info("enter fullscreen"),this.emit(Mo.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(Mo.LEAVE_FULL_SCREEN))}handleVolumeChange(){var t;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(Mo.VOLUME_CHANGE,{muted:(t=this.element)==null?void 0:t.muted})}handleElementEvent(t){var o,a,l,d,h,y;if(this.mode===2)return;super.handleElementEvent(t);let S=t.type,L=this.isPictureInPicture(),V=this.isFullscreen(),H=t.isTrusted&&(L&&mg||V);if(S===JA.PLAYING&&H&&!this._isResettingSrcObject&&(this._log.warn("user resume in ".concat(V?"fullscreen":"pip")),this.emit(Mo.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),S===JA.PAUSE&&(H&&(this._log.warn("user pause in ".concat(V?"fullscreen":"pip")),this.emit(Mo.USER_PAUSE_IN_PIP_OR_FULL_SCREEN)),this.container&&!this.container.isConnected&&(this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(this.container.id)),OC(500).then(()=>{var lA;(lA=this.container)!=null&&lA.isConnected&&(this._pausedRetryCount=Gp,this._log.info("view container ".concat(this.container.id," is in dom, reset pausedRetryCount")))})),this._pausedRetryCount>0&&!Si()&&!this.isPausedByUserCall&&!H&&(this._log.info("[".concat(Gp-this._pausedRetryCount+1,"/").concat(Gp,"] ").concat(this.kind," player auto resume when paused")),this.doResume(),this._pausedRetryCount--),ng&&!H&&(this._interval=kr.run("timeout",()=>{this.element&&this._state==="PAUSED"&&!this.isPausedByUserCall&&this.doResume()},{delay:3e3})),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let lA=this.element.style.transform;S===JA.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=lA.replace("scaleX(-1)",""):S===JA.LEAVE_PICTURE_IN_PICTURE&&!lA.includes("scaleX")&&(this.element.style.transform="".concat(lA," scaleX(-1)"))}S===JA.RESIZE&&(this._preSize.height!==((o=this.element)==null?void 0:o.videoHeight)||this._preSize.width!==((a=this.element)==null?void 0:a.videoWidth))&&(this._log.info("video size changed to ".concat((l=this.element)==null?void 0:l.videoWidth,"x").concat((d=this.element)==null?void 0:d.videoHeight)),this._preSize.height=((h=this.element)==null?void 0:h.videoHeight)||0,this._preSize.width=((y=this.element)==null?void 0:y.videoWidth)||0,this.emit(Mo.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height})),S===JA.LEAVE_PICTURE_IN_PICTURE&&(this._log.warn("exit pip"),this.isPaused&&!this.isPausedByUserCall&&(this._log.warn("resume after exit pip"),this.doResume()),this.resetSrcObjectToReplay(),this.emit(Mo.LEAVE_PICTURE_IN_PICTURE)),S===JA.ENTER_PICTURE_IN_PICTURE&&this.emit(Mo.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){za&&Iy&&this.isPlayCalled&&this.element&&this.track&&!this.isPausedByUserCall&&(this._log.warn("reset srcObject to replay for android chromium"),this._isResettingSrcObject=!0,this.element.srcObject=new MediaStream([this.track]),this.element.play().catch(t=>{this._log.warn("play failed after reset srcObject",t)}).finally(()=>{this._isResettingSrcObject=!1}))}setCanvas(t){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;var a,l;this.canvas!==t&&((a=this.canvas)==null||a.remove(),t?.setAttribute("style",this.styleAttribute),this.canvas=t,this.mode=t?o:0,this.mode===2&&this.setTrack(t.captureStream().getVideoTracks()[0]),t?((l=this.element)==null||l.remove(),this._appendToWrapper(t)):this.element&&this._appendToWrapper(this.element))}setAttr(t){let o=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},t);o.style=Object.assign({width:"100%",height:"100%"},o.style),super.setAttr(o)}get mirror(){return this.viewMirror}setRect(t,o){this.elementToRender&&(this.elementToRender.style.width="".concat(t,"px"),this.elementToRender.style.height="".concat(o,"px"))}setViewMirror(t){this.elementToRender&&(this.elementToRender.style.transform=t?"scaleX(-1)":""),this.viewMirror=t}setObjectFit(t){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(t)),this.objectFit=t}setPoster(t){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return new Promise(a=>{if(!this.element||(this._log.info("setPoster",t.slice(0,10)),t===""?this.element.removeAttribute("poster"):this.element.poster=t,!o||!mg&&!gr))return a();if(t==="")return this.removePosterImg(),a();if(this.posterImg)return a();let l=document.createElement("img");l.src=t;let d=window.getComputedStyle(this.element),h=d.objectFit||this.objectFit,y=1;if(this._useWrapper){let S=parseInt(d.zIndex,10);isNaN(S)||(y=S+1)}l.style.cssText=this._useWrapper?"grid-area:1/1;z-index:".concat(y,";width:100%;height:100%;object-fit:").concat(h,";"):"position:absolute;top:0;left:0;width:100%;height:100%;object-fit:".concat(h,";"),l.onload=()=>XA(this,null,function*(){try{l.decode&&(yield l.decode()),this.container&&!this._useWrapper&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=l;let S=this._useWrapper?this._wrapper:this.container;S?.appendChild(l),Qv()&&$d<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(S){this._log.warn("decode poster image error",S)}return a()}),l.onerror=()=>(this._log.warn("load poster image error"),a())})}removePosterImg(){this.posterImg&&(Qv()&&$d<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),!this._useWrapper&&this.container&&!ze(this._originContainerPosition)&&this.container.style.position==="relative"&&(this.container.style.position=this._originContainerPosition),delete this.posterImg)}get hasPoster(){var t;return!!this.posterImg||!((t=this.element)==null||!t.getAttribute("poster"))}pause(){let t=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return XA(this,null,function*(){UI(QX.prototype,this,"pause").call(this),!this.isPictureInPicture()&&!this.hasPoster&&(Iy||t&&(gr||mg))&&(yield this.setPoster(this.getVideoFrame(),!0))})}resume(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return super.resume(t).then(()=>{var o;(this.posterImg||(o=this.element)!=null&&o.poster)&&this.setPoster("",!0)})}doResume(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this.isPaused&&t&&this.element&&this.track&&Iy&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;var o;this.isPictureInPicture()&&this.exitPictureInPicture().catch(a=>{}),this.isFullscreen()&&this.exitFullscreen().catch(a=>{}),this.element&&(this.element.removeEventListener(JA.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.removeEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.removeEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.removeEventListener("volumechange",this.handleVolumeChange)),this._isFirstFrameRenderEmitted=!1,super.stop(t),(o=this.canvas)==null||o.remove(),this.removePosterImg(),this._useWrapper&&this._cleanupWrapper()}_cleanupWrapper(){this._wrapper&&this._wrapper.children.length===0&&this._wrapper.remove(),this._wrapper=null}play(t){if(ze(t?.isLiveStream)||this.setLiveMode(t.isLiveStream),this.element){if(this.elementToRender&&this.container)if(this._useWrapper){let o=this._getOrCreateWrapper();this.elementToRender.parentElement!==o&&o.insertBefore(this.elementToRender,o.firstChild)}else this.elementToRender.parentElement!==this.container&&this.container.append(this.elementToRender)}else this.initializeElement();return this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(t){t!==this.track&&(this.unbindTrackEvents(),this.track=t,this.emit(Mo.MEDIA_TRACK_CHANGED,t),t!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([t]),this.element.remove()),this._appendToWrapper()))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let t=document.createElement("canvas");return t.width=this.element.videoWidth,t.height=this.element.videoHeight,t.getContext("2d").drawImage(this.element,0,0),t.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Am()&&this.element&&this._calculateTimeout<0){let t=0,o=null,a=(l,d)=>{this.stat.width=d.width,this.stat.height=d.height,o&&(this.stat.fps=Math.round((d.presentedFrames-o.presentedFrames)/(l-t)*1e3)),t=l,o=d,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var h;return(h=this.element)==null?void 0:h.requestVideoFrameCallback(a)},2e3))};this.element.requestVideoFrameCallback(a)}}catch(t){this._log.warn("init stat failed",t)}}enterFullscreen(){return XA(this,null,function*(){let t=this.elementToRender;if(!t)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");if(ng&&this.isPictureInPicture()){this._log.info("exit pip before entering fullscreen");try{yield this.exitPictureInPicture()}catch(o){this._log.warn("exit pip failed before fullscreen:",o)}}try{if(t.requestFullscreen)yield t.requestFullscreen();else if(t.webkitRequestFullscreen)yield t.webkitRequestFullscreen();else if(t.webkitEnterFullscreen)yield t.webkitEnterFullscreen();else if(t.mozRequestFullScreen)yield t.mozRequestFullScreen();else{if(!t.msRequestFullscreen)throw new Error("Fullscreen API not supported");yield t.msRequestFullscreen()}this._log.info("entered fullscreen mode")}catch(o){throw this._log.error("failed to enter fullscreen:",o),o}})}exitFullscreen(){return XA(this,null,function*(){try{if(!this.isFullscreen())return;if(document.exitFullscreen)yield document.exitFullscreen();else if(document.webkitExitFullscreen)yield document.webkitExitFullscreen();else if(document.mozCancelFullScreen)yield document.mozCancelFullScreen();else{if(!document.msExitFullscreen)throw new Error("Exit fullscreen API not supported");yield document.msExitFullscreen()}this._log.info("exited fullscreen mode")}catch(t){throw this._log.error("failed to exit fullscreen:",t),t}})}isFullscreen(){let t=this.elementToRender;return!!t&&(this.element&&this.element.webkitDisplayingFullscreen?!this.isPictureInPicture():(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===t)}toggleFullscreen(){return XA(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return XA(this,null,function*(){this.enterPIPPromise=this._enterPictureInPicture();try{return yield this.enterPIPPromise}finally{delete this.enterPIPPromise}})}_enterPictureInPicture(){return XA(this,null,function*(){try{if(!this.element)throw new Error("No video element available for pip");if(this.canvas&&this.mode!==1)throw new Error("pip is not supported for canvas-only mode");let{element:t}=this;if(t.requestPictureInPicture){this._log.info("requestPictureInPicture");let o=yield t.requestPictureInPicture();return this.pipWindow=o,this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),this._appendToWrapper(this.element)),o}if(t.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield t.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered pip mode (webkit)"),{};throw new Error("pip API not supported")}catch(t){throw this._log.error("failed to enter pip:",t.name,t.message),t}})}exitPictureInPicture(){return XA(this,null,function*(){var t;try{if(!this.isPictureInPicture())return;if(delete this.pipWindow,document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this.elementToRender===this.canvas&&((t=this.element)==null||t.remove(),this._pausedRetryCount=Gp,this._appendToWrapper(this.canvas)),this._log.info("exited pip mode");else{if(!this.element||!this.element.webkitSetPresentationMode)throw new Error("Exit pip API not supported or not in PiP mode");yield this.element.webkitSetPresentationMode("inline"),this._log.info("exited pip mode (webkit)")}}catch(o){throw this._log.error("failed to exit pip:",o),o}})}isPictureInPicture(){if(!this.element)return!1;let{element:t}=this;return document.pictureInPictureElement?document.pictureInPictureElement===t:!!t.webkitPresentationMode&&t.webkitPresentationMode==="picture-in-picture"}togglePictureInPicture(){return XA(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function qg(A,t){return XA(this,null,function*(){if(!A.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield A.audioWorklet.addModule(t),pA.info("worklet addModule success")}catch(o){throw pA.info("worklet addModule catch error. ".concat(o.message)),o}})}typeof AudioContext<"u"?Bi=AudioContext:typeof webkitAudioContext<"u"?Bi=webkitAudioContext:typeof mozAudioContext<"u"&&(Bi=mozAudioContext);var Hs,pu=1500,eC=-1,im=0,cd=-1,YI=!1,s1=0,h_=-1,aL=-1;(function A(){try{if(Hs)return;(Hs=new Bi({sampleRate:48e3})).onstatechange=()=>{pA.info("context state: ".concat(Hs.state).concat(Hs.state!=="running"?" visibilityState: ".concat(document.visibilityState):"")),B_()},clearTimeout(eC)}catch(t){pA.error("initAudioContext failed: ".concat(t," typeof AudioContextClass: ").concat(typeof Bi)),eC=setTimeout(A,1e3)}})();var B_=()=>{Hs.state==="suspended"?(im=Oo(),cd===-1&&(cd=setTimeout(()=>{Hs.state==="suspended"&&(YI=!0,F.emit("155",{isSuspended:!0}))},pu)),gL(),document.addEventListener("click",B_)):Hs.state==="interrupted"?gL():(im&&(ri.addNumber({key:507800,value:Oo()-im,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),im=0),cd!==-1&&(clearTimeout(cd),cd=-1,YI&&(YI=!1,F.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",B_),document.removeEventListener("click",B_))},ij=0,oj=-1;function gL(){return new Promise((A,t)=>{if(Hs.state==="running")return A();Date.now()-ij<1e3?(clearTimeout(oj),oj=setTimeout(()=>{ij=Date.now(),Hs.resume().then(A,t)},1e3)):(clearTimeout(oj),ij=Date.now(),Hs.resume().then(A,t))}).catch(A=>{pA.warn("context resume failed: ".concat(A)),document.addEventListener("visibilitychange",B_)})}document.addEventListener("click",B_);var VI=A=>Hs,HI=class{constructor(A){this.name=A,Y(this,"node"),Y(this,"node2"),Y(this,"pre",new Set),Y(this,"next",new Set),Y(this,"context"),Y(this,"connectedNodes",new Set),Y(this,"nextInputChannelMap",new Map),Y(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(A){this._channelCount=A,this.setChannelCount(this.node,A),this.setChannelCount(this.node2,A),this.next.forEach(t=>t.channelCount=A)}setChannelCount(A,t){!A||A instanceof ScriptProcessorNode||(A.channelCountMode="explicit",A.channelCount=t||this.channelCount||1)}setContext(A){this.context=A,this.node&&A.addMixWeight()}removeContext(){var A;this.node&&((A=this.context)==null||A.reduceMixWeight()),delete this.context}replaceNode(A){var t;if(A!==this.node)try{this.node?this._disconnect():(t=this.context)==null||t.addMixWeight(),this.node=A,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(o){pA.error(o)}}setNode(A,t){var o;if(!this.node)try{(o=this.context)==null||o.addMixWeight(),this.node=A,this.setChannelCount(this.node),t&&(this.node2=t,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),ri.addSuccessEvent({key:502701})}catch(a){pA.error(a),ri.addFailedEvent({key:502701,error:a})}}deleteNode(){var A;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(A=this.context)==null||A.reduceMixWeight(),this.preNodeReconnect(),ri.addSuccessEvent({key:502702})}catch(t){pA.error(t),ri.addFailedEvent({key:502702,error:t})}}preNodeReconnect(){this.pre.forEach(A=>{A.node?A.reconnect():A.preNodeReconnect()})}connectNext(A){this.next.forEach(t=>{let o=this.nextInputChannelMap.get(t);A._connect(t.node,o)||t.connectNext(A)})}_connect(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return!(!this.node||!A)&&((this.node2||this.node).connect(A,0,t),this.connectedNodes.add(A),!0)}_disconnect(){this.connectedNodes.forEach(A=>{var t;return(t=this.node2||this.node)==null?void 0:t.disconnect(A)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return this.next.add(A),A.pre.add(this),this.nextInputChannelMap.set(A,t),A}},dtA=class extends HI{constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:256;super(),this.fftSize=A,Y(this,"dataArray",new Uint8Array(0))}setNode(A){A.fftSize=this.fftSize,this.dataArray=new Uint8Array(A.frequencyBinCount),super.setNode(A)}getByteTimeDomainData(){var A;return(A=this.node)==null||A.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var A;return(A=this.node)==null||A.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let A=this.getByteTimeDomainData(),t=0,o=0,a="M".concat(t,",").concat(o);for(let l=0;l0&&arguments[0]!==void 0?arguments[0]:1;this.mixWeight+=A,this.mixWeight-1==A+1>>1&&this.mixOnChange()}reduceMixWeight(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.addMixWeight(-A)}close(){this.inputs.forEach(A=>A.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},b5=new WeakMap;function r1(A){try{let t=b5.get(A);if(t)return t;let o=VI();if(A instanceof HTMLAudioElement)t=o.createMediaElementSource(A);else{if(!(A instanceof MediaStreamTrack))return A;t=o.createMediaStreamSource(new MediaStream([A]))}return b5.set(A,t),t}catch(t){if(!(gr&&t instanceof Error&&t.name==="NotSupportedError"))throw t;pA.warn(t)}}var a1=class lm{constructor(t){Y(this,"_volume",0),Y(this,"_volumeDb",0),Y(this,"_log"),Y(this,"_scriptProcessorNode",null),Y(this,"_audioWorkletNode",null),Y(this,"_interval",200),Y(this,"ready",this.preload());let{log:o}=t;this._log=o,F.on(rA.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-lm.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!lm.workletReady){let t='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(it+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';lm.workletReady=qg(lm.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return lm.workletReady.then(()=>this.initAudioWorklet()).catch(t=>(this._log.error("volumeMeter preload error: ".concat(t)),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(lm.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=o=>{lm.lastMessageTime=Date.now(),this._volume=o.data.volume||0,this._volumeDb=o.data.volumeDb||0,!t&&o.data.cacheLen&&o.data.outputLen&&(this._log.warn("worklet play success"),t=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(t){this._log.error("volumeMeter init audio worklet error: ".concat(t)),ds.logFailedEvent({userId:this._log.userId,eventType:Wa.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=VI().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{lm.lastMessageTime=Date.now();let o=t.inputBuffer.getChannelData(0),a=0;for(let l=0;l>2);A.copyTo(o,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:o},[o.buffer]),A.close()}}},g1=k5,htA=dc(Xl(),1),U5=A=>t=>t.deviceId===A,nj=class{constructor(A,t){Y(this,"kind"),Y(this,"type"),Y(this,"devices",[]),this.kind=A,this.type=t}update(A,t){let o=A.filter(a=>a.kind==="".concat(this.kind).concat(this.type.toLocaleLowerCase()));this.devices.length===1&&cL(this.devices[0])||t&&(o.forEach(a=>{if(a.deviceId&&!this.devices.find(U5(a.deviceId))){let l="".concat(this.kind).concat(this.type,"Added");pA.warn("".concat(l,": ").concat(JSON.stringify(a))),t.emit(l,a)}}),this.devices.forEach(a=>{if(a.deviceId&&!o.find(U5(a.deviceId))){let l="".concat(this.kind).concat(this.type,"Removed");pA.warn("".concat(l,": ").concat(JSON.stringify(a))),t.emit(l,a)}})),this.devices=o}hasDevice(A){return!!this.devices.find(t=>t.deviceId===A)}},BtA=class extends htA.EventEmitter{constructor(){super(),Y(this,"audioInputs",new nj(JA.AUDIO,"Input")),Y(this,"videoInputs",new nj(JA.VIDEO,"Input")),Y(this,"audioOutputs",new nj(JA.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||kr.run("interval",()=>{this.update()},{delay:1e4}))}init(){c1().then(A=>{this.audioInputs.update(A),this.videoInputs.update(A),this.audioOutputs.update(A)})}update(){return XA(this,arguments,function(){var A=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function*(){let o=yield c1(t);return A.audioInputs.update(o,A),A.videoInputs.update(o,A),A.audioOutputs.update(o,A),A}()})}hasBlueTooth(){var A;if(1e3*((A=VI())==null?void 0:A.outputLatency)>150)return!0;let t=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(o=>t.some(a=>o.label.toLowerCase().includes(a)))||this.audioInputs.devices.some(o=>t.some(a=>o.label.toLowerCase().includes(a)))}},Kc=u0||I0?null:new BtA;function cL(A){return A.deviceId===A.groupId&&A.groupId===""}function c1(){return XA(this,arguments,function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function*(){if(Qu()||!Yk())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(A!==0){let o={audio:!1,video:!1};if(t.forEach(a=>{cL(a)&&(a.kind===JA.AUDIO_INPUT?o.audio=!0:a.kind===JA.VIDEO_INPUT&&(o.video=!0))}),A===2&&(o.audio=!1),A===1&&(o.video=!1),o.audio||o.video){let a;try{a=yield navigator.mediaDevices.getUserMedia(o),o.audio&&gL()}catch(l){pA.debug("capture before getDevices failed: ",l)}t=yield navigator.mediaDevices.enumerateDevices(),a?.getTracks().forEach(l=>l.stop())}}return t.map((o,a)=>{let l={kind:o.kind,deviceId:o.deviceId,groupId:o.groupId,label:o.label||"".concat(o.kind,"_").concat(a)};return o.deviceId.length>0&&sj.add("".concat(o.deviceId,"_").concat(o.kind)),o.getCapabilities&&(l.getCapabilities=()=>o.getCapabilities()),l})}()})}function om(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return Kc.update(A?1:0).then(t=>t.audioInputs.devices)}function nm(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return Kc.update(A?2:0).then(t=>t.videoInputs.devices)}var F5=!1;function Zv(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return XA(this,null,function*(){return(ng||mg)&&(A=!1),Kc.update(A?1:0).then(t=>t.audioOutputs.devices)})}var sj=new Set;function O5(A,t){return XA(this,null,function*(){let o=(yield om()).find(a=>a.deviceId===sv);return!t&&o?.groupId===A||o?.groupId===A&&o.label===t})}var l1,QtA=class extends N5{constructor(A){super(),this.log=A,Y(this,"volumeMeter"),Y(this,"volumeMeterAfter3A"),Y(this,"volumeDestination"),Y(this,"analyser",new dtA),this.volumeMeter=new L5({log:this.log}),this.volumeMeterAfter3A=new L5({log:this.log}),this.volumeDestination=new HI,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},rj=class pX extends HC{constructor(t){super(t,JA.AUDIO),Y(this,"_outputDeviceId"),Y(this,"_floatVolume",1),Y(this,"_destination"),Y(this,"pipeline"),Y(this,"volumeMeterMode","worklet"),Y(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=t.enableVolumeControlInIOS,this.mode=0,t.url&&(this.url=t.url),this.pipeline=new QtA(this._log)}setTrack(t){}get duration(){var t;return Math.floor(1e3*(((t=this.element)==null?void 0:t.duration)||0))}get currentTime(){var t;return Math.floor(1e3*(((t=this.element)==null?void 0:t.currentTime)||0))}set currentTime(t){this.element&&(this.element.currentTime=t/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(t){if((PI==="15.2"||PI==="15.3"||PI==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");this._log.info("audio player initializeElement");let o=l1||new Audio;o.setAttribute("autoplay","autoplay"),o.srcObject=this.getMediaStream(),o.muted=this.muted,this.url&&(o.crossOrigin="anonymous",o.src=this.url),this.element=o,this.setVolume(Ys(t)?t/100:this._floatVolume),o===l1&&(l1=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(Mo.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(t){return XA(this,null,function*(){if(this.track||this.url){try{!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(t?.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(VI().createAnalyser()),function(){XA(this,null,function*(){try{F5||(F5=!0,pA.info("speakers:".concat((yield Zv()).map(o=>" ".concat(o.deviceId.slice(0,8),": ").concat(o.label)))))}catch{}})}()}catch(o){throw this._log.warn("audio play error: ".concat(o)),uy(PI,"18.7",!0)&&this.bindAutoPlayEvent(),o}return UI(pX.prototype,this,"play").call(this)}})}stop(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.pipeline.destroy(),super.stop(t)}setVolume(t){this._floatVolume=t,this.element&&(this.element.volume=t)}setSinkId(t){return XA(this,null,function*(){var o,a;this._outputDeviceId!==t&&(this._outputDeviceId=t),this.element&&this.element.sinkId!==t&&(yield(a=(o=this.element).setSinkId)==null?void 0:a.call(o,t))})}get useDestination(){return!!this.pipeline.stream}setLoop(t){this.element&&(this.element.loop=t)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},ptA=class extends rj{setTrack(A){this.track!==A&&(this.unbindTrackEvents(),this.track=A,this.emit(Mo.MEDIA_TRACK_CHANGED,A),A&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([A]))))}},P5=class extends rj{constructor(A){super(A),Y(this,"_sourceElement"),Y(this,"_output",new HI),this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(VI().destination)}write(A){this.pipeline.volumeMeter.write(A)}setTrack(A){var t,o,a;((o=(t=this.element)==null?void 0:t.error)==null?void 0:o.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==A&&(this.unbindTrackEvents(),this.track=A,this.emit(Mo.MEDIA_TRACK_CHANGED,A),A?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([A]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([A])),this.pipeline.source.channelCount=((a=A.getSettings())==null?void 0:a.channelCount)||1,this.pipeline.replaceSource(A)):this.pipeline.source.deleteNode())}setVolume(A){var t;let o=A<=1&&!Qv();if(this._floatVolume!==A||!(o&&((t=this.element)==null?void 0:t.volume)===A||!o&&this.pipeline.volume===A))if(this._floatVolume=A,this.useDestination)this.pipeline.setVolume(A),this._log.info("set pipeline volume: ".concat(A));else if(o)this.element?(this._log.info("set element volume: ".concat(A)),this.element.volume=A):this._log.info("set element volume: no element");else{if(Qv()){if(!this.enableVolumeControlInIOS)return;(function(){if(!ng||aL!==-1)return;let a=()=>{Oo()-s1<500||(Hs&&Hs.state==="running"&&Hs.currentTime===h_&&(pA.warn("context is fake running, auto resume"),Hs.suspend().catch(l=>{pA.warn("context suspend failed: ".concat(l))})),h_=Hs.currentTime,s1=Oo())};aL=setInterval(()=>{a()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&a()})})()}if(gr&&!this.pipeline.source.node)return void this._log.warn("set pipeline volume failed: no source node");this._log.info("start set pipeline volume: ".concat(A)),this.pipeline.setVolume(A),this.element&&!this._sourceElement&&(this._destination||(this._destination=VI().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),Vs(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(a=>{this.emit(Mo.AUTOPLAY_FAILED,a)}))}}stop(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Hp&&(l1=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(A)}},aj=class extends gs{constructor(A){let{userId:t,sdkAppId:o,mediaType:a,room:l,PlayerClass:d=a===1?P5:bo}=A;var h;super(),Y(this,"id",YA()),Y(this,"userId",""),Y(this,"isRemote"),Y(this,"mediaType"),Y(this,"room"),Y(this,"user"),Y(this,"_log"),Y(this,"_inputTrack"),Y(this,"_outputTrack"),Y(this,"isPlayCalled"),Y(this,"container",null),Y(this,"player"),Y(this,"subVideoPlayerMap"),Y(this,"muted",!1),Y(this,"abortCtrl"),Y(this,"objectFit","cover"),Y(this,"mirror"),Y(this,"rotation"),Y(this,"isScreen",!1),Y(this,"manager"),Y(this,"trackSettings"),Y(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=a,this._log=pA.createLogger({parent:l?.getLogger(),id:"".concat(this.kind[0],"t"),userId:(h=l||this.room)==null?void 0:h.userId,remoteUserId:this instanceof hL?void 0:this.userId,sdkAppId:o,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof hL}),this.player=new d({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:l?.enableVolumeControlInIOS}),this.player.on(Mo.PLAYER_STATE_CHANGED,y=>{if(F.emit(rA.PLAYER_STATE_CHANGED,Di({track:this},y)),this.emit("player-state-changed",y),y.state==="PLAYING"&&this.room){let S=!0;for(let{remoteAudioTrack:L,remoteVideoTrack:V,remoteAuxiliaryTrack:H}of[...this.room.remotePublishedUserMap.values()])if(L.isAvailable&&!L.player.isPlaying||V.isAvailable&&!V.player.isPlaying||H.isAvailable&&!H.player.isPlaying){S=!1;break}S&&Si()&&qc&&qc.deleteDialog()}}),this.kind===JA.VIDEO&&(this.player.on(Mo.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(Mo.LOADED_DATA),F.emit(rA.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Mo.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(Mo.LOADED_META_DATA)}),this.player.on(Mo.MEDIA_TRACK_CHANGED,y=>{var S;(S=this.subVideoPlayerMap)==null||S.forEach(L=>L.setTrack(y))}),this.player.on(Mo.RESIZE,y=>{this.emitFirstVideoFrameEvent(Mo.RESIZE),this.emit("video-size-changed",Di({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},y))}),this.player.on(Mo.FIRST_FRAME_RENDER,y=>{this.emit("first-frame-render",So(Di({},y),{streamType:this.streamType,userId:this.isRemote?this.userId:""}))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(Mo.ERROR,this.onPlayerError.bind(this)),this.player.on(Mo.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||pA}get kind(){return this.mediaType===1?JA.AUDIO:JA.VIDEO}get isAudio(){return this.kind===JA.AUDIO}get strMediaType(){return this.mediaType===4?JA.VIDEO:this.mediaType===2?JA.SCREEN:JA.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}play(A,t){return XA(this,null,function*(){let o=ka(A)?A[0]:A;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!ze(t.muted)&&this.setPlayerMute(t.muted),t&&!ze(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof bo&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(ka(A)&&A.length>=1&&this.container&&A.includes(this.container)&&this.container.contains(this.player.elementToRender)?(A.splice(A.indexOf(this.container),1),A.unshift(this.container)):(this.container=o,this.player.setContainer(o))),ka(A)&&A.length>=1&&(yield this.playSubContainer(A.slice(1),t))));if(t&&!ze(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===JA.VIDEO)&&this.setPlayerMute(!0),t&&!ze(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof bo&&(ze(t?.isLiveStream)||this.player.setLiveMode(t.isLiveStream),this.player.setObjectFit(this.objectFit),t&&!ze(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof bo&&this.player.setContainer(o)),F.emit(rA.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info("play with options: ".concat(JSON.stringify(t)));try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),ka(A)&&A.length>1&&(yield this.playSubContainer(A.slice(1),t))}catch(a){throw this.handleAutoPlayFailed(a),a}}else this.log.info("play has not mediaTrack, abort")})}setMirror(A,t){if(this.isScreen||this.kind!==JA.VIDEO||ze(A)||A===this.mirror)return;this.mirror=A;let o=this.player;t&&(o=t);let a=this.manager;if(br(this.mirror))return o.setViewMirror(this.mirror),void(!this.isRemote&&a&&(a.mirror=!1));switch(this.mirror){case"view":a&&(a.mirror=!1),o.setViewMirror(!0);break;case"publish":a&&(a.mirror=!0),o.setViewMirror(!0);break;case"both":a&&(a.mirror=!0),o.setViewMirror(!1)}}playSubContainer(A,t){return XA(this,null,function*(){if(!this._outputTrack||this.kind===JA.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((a,l)=>{var d;A.find(h=>l===h)||(a.stop(),(d=this.subVideoPlayerMap)==null||d.delete(l))});for(let[a,l]of A.entries()){let d=this.subVideoPlayerMap.get(l);d?t&&(ze(t.objectFit)||d.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(l,new bo({id:this.userId||this.id,track:this.playerMediaTrack,container:l,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(a+1)})}))}let o=[...this.subVideoPlayerMap.values()];for(let a of o)a.setViewMirror(this.player.mirror),yield a.play()})}setAudioOutput(A){return this.player.setSinkId(A)}setAudioVolume(A){this.player.setVolume(A)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var A;return((A=this.player)==null?void 0:A.getInternalAudioLevel())||0}stop(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(ck(this)&&!A?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return XA(this,null,function*(){var A;this.isPlayCalled&&(yield(A=this.player)==null?void 0:A.resume())})}close(){this._toInitState(),this.log.info("close"),this.isPlayCalled&&this.stop(!0)}_toInitState(){}setMute(A){this.muted=A,this._inputTrack&&(this._inputTrack.enabled=!A),this._outputTrack&&(this._outputTrack.enabled=!A),this.emit(A?"mute":"unmute",this),F.emit(A?rA.TRACK_MUTED:rA.TRACK_UNMUTED,{track:this})}setPlayerMute(A){this.player.setMuted(A)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(A){gd(A,A).add(JA.MUTE,this.onTrackMuted).add(JA.UNMUTE,this.onTrackUnmuted).add(JA.ENDED,this.onTrackEnded),A.muted&&this.onTrackMuted(),A.readyState===JA.ENDED&&this.onTrackEnded()}uninstallTrackEvent(A){Vs(A)}setInputMediaStreamTrack(A){var t;let o=this._inputTrack;if(A!==o)return this._inputTrack=A,this.trackSettings=(t=A.getSettings)==null?void 0:t.call(A),A.enabled=!this.muted,o&&this.uninstallTrackEvent(o),this.installTrackEvent(A),this.emit("input-media-track-changed",A||null,o||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(A)}setOutputMediaStreamTrack(A){var t;let o=this._outputTrack;this instanceof QQ&&Lp(o)||A!==o&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",A.label):this.log.info("setOutputMediaStreamTrack",(t=A.getSettings)==null?void 0:t.call(A).deviceId,A.label),this._outputTrack=A,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!A),this.emit("output-media-track-changed",A))}setMediaType(A){this.mediaType=A}updatePlayingState(A){var t,o;if(this.isPlayCalled){if(A){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch(a=>this.handleAutoPlayFailed(a)),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return ck(this)&&this.isAudio&&(t=this.user)!=null&&t.muteState.hasAudio&&(o=this.user)!=null&&o.muteState.audioMuted?void 0:(this.player.stop(ck(this)?this.jitterBufferDelay:0),void this.log.info("playing state updated, stop ".concat(this.kind)))}this.log.debug("updatePlayingState abort ".concat(this.isPlayCalled," ").concat(A," ").concat(this.player.isStopped))}handleAutoPlayFailed(A){return XA(this,null,function*(){var t;this.log.warn("handleAutoPlayFailed",A);let o=()=>{this.resume().then(()=>{document.removeEventListener("click",o,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((xp||sQ)&&(yield OC(100),(t=this.player)!=null&&t.isPlaying))return;JC()}else document.addEventListener("click",o,!0);F.once(rA.LOCAL_TRACK_CAPTURE_SUCCESS,a=>{let{track:l}=a;l.kind==="audio"&&Si()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&o()}),this.emit("error",A)})}getVideoFrame(){return this.player instanceof bo?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(A){var t,o,a;if(this.isFirstVideoFrameEmitted)return;let l=(t=this.mediaTrack)==null?void 0:t.getSettings(),d=l?.width||((o=this.player.element)==null?void 0:o.videoWidth)||0,h=l?.height||((a=this.player.element)==null?void 0:a.videoHeight)||0;A===Mo.RESIZE&&!d&&!h||A===Mo.LOADED_META_DATA&&!d&&!h||(A===Mo.LOADED_DATA&&!d&&!h&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,iQ(this.rotation)&&([d,h]=[h,d]),this.emit("first-video-frame",{width:d,height:h,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn("".concat(this.kind," track is unable to provide media output"))}onTrackUnmuted(){this._log.info("".concat(this.kind," track is able to provide media output"))}onTrackEnded(){this._log.warn("".concat(this.kind," track ended"))}};Qi([hc([],gs.INIT,{sync:!0})],aj.prototype,"_toInitState");var mtA=Object.prototype.hasOwnProperty,sm=function(A){if(A==null)return!0;if(typeof A=="boolean")return!1;if(typeof A=="number")return A===0;if(typeof A=="string"||typeof A=="function"||Array.isArray(A))return A.length===0;if(A instanceof Error)return A.message==="";if(uE(A))switch(Object.prototype.toString.call(A)){case"[object File]":case"[object Map]":case"[object Set]":return A.size===0;case"[object Object]":for(let t in A)if(mtA.call(A,t))return!1;return!0}return!1},ftA=Bv({retryFunction:function(A){return XA(this,null,function*(){let t=function(d){return{audio:ytA(d),video:DtA(d)}}(A);pA.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let o=[],a=[],l=["label","deviceId","groupId"];if(t.audio&&(o=yield om(),pA.info("microphones: ".concat(Xd(o.map(d=>So(Di({},d),{groupId:d.groupId.substring(0,8)})),{keysToInclude:l})))),t.video&&(a=yield nm(),pA.info("cameras: ".concat(Xd(a,{keysToInclude:l}))),!br(t.video)&&t.video.facingMode==="user"&&!t.video.deviceId)){let d=a.filter(h=>!h.label.includes("infrared")).find(h=>h.label.includes("facing front"));d&&(t.video.deviceId=d.deviceId,pA.info("exclude infrared camera: ".concat(JSON.stringify(t))))}try{let d=yield navigator.mediaDevices.getUserMedia(t);return $2&&d.getTracks().forEach(h=>{var y;let S=h.getCapabilities();pA.info("".concat(h.kind," capabilities: ").concat(Xd(S,{keysToInclude:Jb}))),!ze(A.echoCancellation)&&((y=S.echoCancellation)==null?void 0:y.indexOf(A.echoCancellation))===-1&&pA.warn("Invalid argument for 'echoCancellation'. Expected one of [".concat(JSON.stringify(S.echoCancellation),"], but received '").concat(A.echoCancellation,"'"))}),t.audio&&gL(),d}catch(d){let{message:h}=d;throw d.name==="NotFoundError"&&(A.video&&a&&a.length===0&&(h=sn({key:Go.CAMERA_NOT_FOUND})),A.audio&&o&&o.length===0&&(h=sn({key:Go.MICROPHONE_NOT_FOUND}))),new li({code:mt.INITIALIZE_FAILED,name:d.name,message:h,constraint:d.constraint})}})},settings:{retries:3,timeout:500},onError:A=>{let{error:t,retry:o,reject:a,retryFuncArgs:l,retriedCount:d}=A,h=d+1;t.name==="NotReadableError"||t.name==="OverconstrainedError"||t.name==="AbortError"?(h===1?(l[0].video&&(l[0].maxResolution=!1,(!mg||l[0].width*l[0].height<=2073600)&&l[0].frameRate&&(l[0].frameRate=l[0].frameRate>10?10:5)),l[0].retryWhenExactFailed&&l[0].useExactDeviceId&&(l[0].useExactDeviceId=!1)):h===2?l[0].useDeviceIdOnly=!0:h===3&&!l[0].useExactDeviceId&&(l[0].useTrueAsConstraint=!0),o()):a(t),l[0].microphoneId&&x5(l[0].microphoneId,!1),l[0].cameraId&&x5(l[0].cameraId,!0)},onRetrying:A=>{pA.warn("getUserMedia NotReadableError observed, retrying [".concat(A,"/3]"))},onRetryFailed:A=>{ds.logFailedEvent({eventType:Wa.GET_USER_MEDIA_RETRY,error:A})},onRetrySuccess:A=>{ds.logSuccessEvent({eventType:Wa.GET_USER_MEDIA_RETRY}),ds.uploadEvent({log:"stat-".concat(Wa.GET_USER_MEDIA_RETRY,"-success-").concat(A)})}});function x5(A,t){return XA(this,null,function*(){let o=(t?yield nm():yield om()).find(a=>a.deviceId===A);o&&ba(o.getCapabilities)&&pA.warn(Xd(o.getCapabilities(),{keysToInclude:Jb}))})}function ytA(A){if(!A.audio)return!1;if(A.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:A.sampleRate};return!sm(A.microphoneId)&&(t.deviceId=A.useExactDeviceId?{exact:A.microphoneId}:A.microphoneId,A.useDeviceIdOnly)?t:(Ys(A.channelCount)&&(t.channelCount=A.channelCount),(br(A.echoCancellation)||A.echoCancellation==="remote-only"||A.echoCancellation==="all")&&(t.echoCancellation=A.echoCancellation),br(A.noiseSuppression)&&!A.noiseSuppression&&(t.noiseSuppression=!1),br(A.autoGainControl)&&!A.autoGainControl&&(t.autoGainControl=!1),!!sm(t)||t)}function DtA(A){if(!A.video)return!1;if(A.useTrueAsConstraint)return!0;let{maxResolution:t=!0}=A,o={};return A.cameraId?o.deviceId=A.useExactDeviceId?{exact:A.cameraId}:A.cameraId:A.facingMode&&(o.facingMode=A.facingMode),A.useDeviceIdOnly&&!sm(o)?o:(A.width&&(o.width={ideal:A.width},t&&!gr&&(o.width.max=A.width)),A.height&&(o.height={ideal:A.height},t&&!gr&&(o.height.max=A.height)),gr&&rQ&&A.width&&A.height&&A.width*A.height<101376&&(o.width=A.width,o.height=A.height),A.frameRate&&(o.frameRate=A.frameRate),!!sm(o)||o)}var StA=ftA;function Y5(A){return Xr((t,o)=>function(){for(var a=arguments.length,l=new Array(a),d=0;dfunction(){for(var a=arguments.length,l=new Array(a),d=0;dfunction(){for(var a=arguments.length,l=new Array(a),d=0;d{let A=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&pA.info("visibility change: ".concat(document.visibilityState)),!A&&(document.addEventListener("visibilitychange",()=>{pA.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState}),A=!0)}})(),MtA=0,H5=class{constructor(A){Y(this,"log"),Y(this,"isRunning",!1),Y(this,"queue",[]);let t="fq".concat(++MtA);A&&(t+="|".concat(A)),this.log=pA.createLogger({id:t})}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(A){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var o,a;let l=Di({},A),d=new Promise((h,y)=>{l.resolve=h,l.reject=y});return l.promise=d,t?this.length<=1?this.queue.push(l):(a=(o=this.lastQueueItem)==null?void 0:o.promise)==null||a.then(l.resolve,l.reject):this.queue.push(l),this.log.debug("push ".concat(this.length),A.funcName,A.args),this.isRunning||this.callNext(),d}shift(){let A=this.queue.shift();return this.log.debug("shift ".concat(this.length),A?.funcName,A?.args),A}callNext(){if(this.isRunning||this.length===0)return;let{fn:A,args:t,context:o,resolve:a,reject:l,funcName:d}=this.queue[0];this.log.debug("callNext",this.length,d,t),this.isRunning=!0,A.apply(o,t).then(a,l).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},I1=new WeakMap,u1=new WeakMap;function lL(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return function(t,o,a){let l=a.value;return a.value=function(){let d=I1.get(this)||new H5;for(var h=arguments.length,y=new Array(h),S=0;SS.push(lA)),(y=u1.get(this))==null||y.forEach(lA=>lA?.queue.forEach(hA=>S.push(hA))),S.forEach(lA=>{lA.reject(new li({code:mt.API_CALL_ABORTED,message:A}))}),I1.delete(this),u1.delete(this),l.apply(this,V)},a}}function Ry(A,t){return function(o,a,l){let d=l.value,h=y=>A(...y);return l.value=function(){for(var y=arguments.length,S=new Array(y),L=0;Lfunction(){let l=A;try{for(var d=arguments.length,h=new Array(d),y=0;y(t?ri.addSuccessEvent({key:l,cost:Oo()-L}):ri.addSuccessEvent({key:l}),V)).catch(V=>{throw ri.addFailedEvent({key:l,error:V}),V}):(ri.addSuccessEvent({key:l}),S)}catch(S){throw ri.addFailedEvent({key:l,error:S}),S}})}var q5={};function sg(){}Wh(q5,{Events:()=>Bc,Inspect:()=>_y,LastSink:()=>E1,Sink:()=>Zn,Subscribe:()=>d1,TimeoutError:()=>W5,audit:()=>IiA,bindCallback:()=>WtA,bindNodeCallback:()=>ztA,buffer:()=>UtA,bufferCount:()=>LtA,bufferTime:()=>kiA,call:()=>K5,catchError:()=>Ez,combineLatest:()=>X5,concat:()=>TtA,concatMap:()=>SiA,concatMapTo:()=>viA,count:()=>$tA,create:()=>pr,debounce:()=>EiA,debounceTime:()=>diA,defer:()=>$5,delay:()=>LiA,deliver:()=>Xn,dispose:()=>gj,elementAt:()=>CiA,empty:()=>Ej,every:()=>miA,exhaustMap:()=>TiA,exhaustMapTo:()=>NiA,expand:()=>FiA,filter:()=>$v,find:()=>hiA,findIndex:()=>BiA,first:()=>QiA,fromAnimationFrame:()=>KtA,fromArray:()=>xtA,fromEvent:()=>Ea,fromEventPattern:()=>YtA,fromFetch:()=>VtA,fromIterable:()=>HtA,fromPromise:()=>iz,fromReadableStream:()=>qtA,fromReader:()=>JtA,groupBy:()=>GiA,identity:()=>RtA,ignoreElements:()=>iiA,iif:()=>GtA,inspect:()=>j5,interval:()=>tz,last:()=>piA,map:()=>Cj,mapTo:()=>yiA,max:()=>AiA,merge:()=>cj,mergeMap:()=>RiA,mergeMapTo:()=>wiA,min:()=>eiA,never:()=>ZtA,nothing:()=>sg,of:()=>PtA,pairwise:()=>fiA,pipe:()=>Ma,race:()=>Z5,range:()=>jtA,reduce:()=>oz,retry:()=>YiA,scan:()=>rz,setAsapScheduler:()=>OtA,share:()=>IL,shareReplay:()=>NtA,skip:()=>siA,skipUntil:()=>riA,skipWhile:()=>dj,startWith:()=>lj,subject:()=>BQ,subscribe:()=>Dl,sum:()=>tiA,switchMap:()=>h1,switchMapTo:()=>Q1,take:()=>p_,takeLast:()=>niA,takeUntil:()=>CE,takeWhile:()=>oiA,tap:()=>hj,throttle:()=>ciA,throwError:()=>XtA,timeInterval:()=>biA,timeout:()=>xiA,timer:()=>uj,toPromise:()=>OiA,toReadableStream:()=>PiA,withLatestFrom:()=>ktA,zip:()=>btA});var K5=A=>A(),RtA=A=>A;function gj(){this.dispose()}var j5=()=>typeof __FASTRX_DEVTOOLS__<"u",wtA=1,_y=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(A){let t=new _tA(A,this,this.streamId++);return Bc.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},E1=class{constructor(){this.defers=new Set,this.disposed=!1}next(A){}complete(){this.dispose()}error(A){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=sg,this.error=sg,this.next=sg,this.dispose=sg,this.subscribe=sg,this.doDefer()}subscribe(A){return A instanceof _y?A.subscribe(this):A(this),this}get bindSubscribe(){return A=>this.subscribe(A)}doDefer(){this.defers.forEach(K5),this.defers.clear()}defer(A){this.defers.add(A)}removeDefer(A){this.defers.delete(A)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},Zn=class extends E1{constructor(A){super(),this.sink=A,A.defer(this.bindDispose)}next(A){this.sink.next(A)}complete(){this.sink.complete()}error(A){this.sink.error(A)}},d1=class extends E1{constructor(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:sg,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:sg,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:sg;if(super(),this._next=t,this._error=o,this._complete=a,this.then=sg,A instanceof _y){let l={toString:()=>"subscribe",id:0,source:A};this.defer(()=>{Bc.defer(l,0)}),Bc.create(l),Bc.pipe(l),this.sourceId=l.id,this.subscribe(A),Bc.subscribe({id:l.id,end:!0}),t==sg?this._next=d=>Bc.next(l,0,d):this.next=d=>{Bc.next(l,0,d),t(d)},a==sg?this._complete=()=>Bc.complete(l,0):this.complete=()=>{this.dispose(),Bc.complete(l,0),a()},o==sg?this._error=d=>Bc.complete(l,0,d):this.error=d=>{this.dispose(),Bc.complete(l,0,d),o(d)}}else this.subscribe(A)}next(A){this._next(A)}complete(){this.dispose(),this._complete()}error(A){this.dispose(),this._error(A)}};function Ma(A){for(var t=arguments.length,o=new Array(t>1?t-1:0),a=1;ad(l),A)}function pr(A,t,o){if(j5()){let a=Object.defineProperties(Object.setPrototypeOf(A,_y.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:o,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Bc.create(a);for(let l=0;l{if(d instanceof _y){let h=pr(y=>{let S=new A(y,...a);S.sourceId=h.id,S.subscribe(d)},t,arguments);return h.source=d,Bc.pipe(h),h}return h=>d(new A(h,...a))}}}function Ty(A,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:A,payload:t}})}var _tA=class extends Zn{constructor(A,t,o){super(A),this.source=t,this.id=o,this.sourceId=A.sourceId,this.defer(()=>{Bc.defer(this.source,this.id)})}next(A){Bc.next(this.source,this.id,A),this.sink.next(A)}complete(){Bc.complete(this.source,this.id),this.sink.complete()}error(A){Bc.complete(this.source,this.id,A),this.sink.error(A)}},Bc={addSource(A,t){Ty("addSource",{id:A.id,name:A.toString(),source:{id:t.id,name:t.toString()}})},next(A,t,o){Ty("next",{id:A.id,streamId:t,data:o&&o.toString()})},subscribe(A,t){let{id:o,end:a}=A;Ty("subscribe",{id:o,end:a,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(A,t,o){Ty("complete",{id:A.id,streamId:t,err:o?o.toString():null})},defer(A,t){Ty("defer",{id:A.id,streamId:t})},pipe(A){Ty("pipe",{name:A.toString(),id:A.id,source:{id:A.source.id,name:A.source.toString()}})},update(A){Ty("update",{id:A.id,name:A.toString()})},create(A){A.id||(A.id=wtA++),Ty("create",{name:A.toString(),id:A.id})}},W5=class extends Error{constructor(A){super("timeout after ".concat(A,"ms")),this.timeout=A}},z5=class extends E1{constructor(A){super(),this.source=A,this.sinks=new Set}add(A){A.defer(()=>this.remove(A)),this.sinks.add(A).size===1&&(this.reset(),this.subscribe(this.source))}remove(A){this.sinks.delete(A),this.sinks.size===0&&this.dispose()}next(A){this.sinks.forEach(t=>t.next(A))}complete(){this.sinks.forEach(A=>A.complete()),this.sinks.clear()}error(A){this.sinks.forEach(t=>t.error(A)),this.sinks.clear()}};function IL(){return A=>{let t=new z5(A);if(A instanceof _y){let o=pr(a=>{t.add(a)},"share",arguments);return t.sourceId=o.id,o.source=A,Bc.pipe(o),o}return pr(t.add.bind(t),"share",arguments)}}function cj(){for(var A=arguments.length,t=new Array(A),o=0;o{let l=new Zn(a),d=t.length;l.complete=()=>{--d===0&&a.complete()},t.forEach(l.bindSubscribe)},"merge",arguments)}function Z5(){for(var A=arguments.length,t=new Array(A),o=0;o{let l=new Map;t.forEach(d=>{let h=new Zn(a);l.set(d,h),h.complete=()=>{l.delete(d),l.size===0?a.complete():h.dispose()},h.next=y=>{l.delete(d),l.forEach(S=>S.dispose()),h.resetNext(),h.resetComplete(),h.next(y)}}),t.forEach(d=>l.get(d).subscribe(d))},"race",arguments)}function TtA(){for(var A=arguments.length,t=new Array(A),o=0;o{let l=0,d=t.length,h=new Zn(a);h.complete=()=>{l{let o=new z5(t),a=[];return o.next=function(l){a.push(l),a.length>A&&a.shift(),this.sinks.forEach(d=>d.next(l))},pr(l=>{l.defer(()=>o.remove(l)),a.forEach(d=>l.next(d)),o.add(l)},"shareReplay",arguments)}}function GtA(A,t,o){return pr(a=>A()?t(a):o(a),"iif",arguments)}function X5(){for(var A=arguments.length,t=new Array(A),o=0;o{let l=t.length,d=l,h=l,y=new Array(l),S=()=>{--h===0&&a.complete()};t.forEach((L,V)=>{let H=new Zn(a);H.next=lA=>{d--,H.next=hA=>{y[V]=hA,d===0&&a.next(y)},H.next(lA)},H.complete=S,H.subscribe(L)})},"combineLatest",arguments)}function btA(){for(var A=arguments.length,t=new Array(A),o=0;o{let l=t.length,d=l,h=new Array(l),y=()=>{--d===0&&a.complete()};t.forEach((S,L)=>{let V=new Zn(a),H=[];h[L]=H,V.next=lA=>{H.push(lA),h.every(hA=>hA.length)&&a.next(h.map(hA=>hA.shift()))},V.complete=y,V.subscribe(S)})},"zip",arguments)}function lj(){for(var A=arguments.length,t=new Array(A),o=0;opr(function(l){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,h=arguments.length>2&&arguments[2]!==void 0?arguments[2]:t.length;for(;d1?o-1:0),l=1;lthis.buffer=d,t.complete=sg,t.subscribe(X5(...a))}next(A){this.buffer&&this.sink.next([A,...this.buffer])}},"withLatestFrom"),LtA=Xn(class extends Zn{constructor(A,t,o){super(A),this.bufferSize=t,this.startBufferEvery=o,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(A){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(t=>{t.push(A)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(A),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(A=>this.sink.next(A)),super.complete()}},"bufferCount"),UtA=Xn(class extends Zn{constructor(A,t){super(A),this.buffer=[];let o=new Zn(A);o.next=a=>{A.next(this.buffer),this.buffer=[]},o.complete=sg,o.subscribe(t)}next(A){this.buffer.push(A)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),FtA=function(A,t,o,a){return new(o||(o=Promise))(function(l,d){function h(L){try{S(a.next(L))}catch(V){d(V)}}function y(L){try{S(a.throw(L))}catch(V){d(V)}}function S(L){L.done?l(L.value):function(V){return V instanceof o?V:new o(function(H){H(V)})}(L.value).then(h,y)}S((a=a.apply(A,[])).next())})};function BQ(A){let t=arguments,o=IL()(pr(a=>{o.next=l=>a.next(l),o.complete=()=>a.complete(),o.error=l=>a.error(l),A&&a.subscribe(A)},"subject",t));return o.next=sg,o.complete=sg,o.error=sg,o}function $5(A){return pr(t=>t.subscribe(A()),"defer",arguments)}var Q_={promise:A=>{Promise.resolve().then(A)},setImmediate:typeof setImmediate<"u"?A=>setImmediate(A):null,setTimeout:A=>setTimeout(A,0)},Ij=typeof Promise<"u"?Q_.promise:Q_.setImmediate?Q_.setImmediate:Q_.setTimeout,Az=A=>t=>{Ij(()=>A(t))},OtA=A=>{typeof A=="function"?Ij=A:Q_[A]&&(Ij=Q_[A])},ez=A=>Az(t=>{for(let o=0;!t.disposed&&o{let o=0,a=setInterval(()=>t.next(o++),A);return t.defer(()=>{clearInterval(a)}),"interval"},"interval",arguments)}function uj(A,t){return pr(o=>{let a=0,l=setTimeout(()=>{if(o.removeDefer(d),o.next(a++),t){let h=setInterval(()=>o.next(a++),t);o.defer(()=>{clearInterval(h)})}else o.complete()},A),d=()=>clearTimeout(l);o.defer(d)},"timer",arguments)}function C1(A,t){return o=>{let a=l=>o.next(l);o.defer(()=>t(a)),A(a)}}function YtA(A,t){return pr(C1(A,t),"fromEventPattern",arguments)}function Ea(A,t){if("on"in A&&"off"in A)return pr(C1(o=>A.on(t,o),o=>A.off(t,o)),"fromEvent",arguments);if("addListener"in A&&"removeListener"in A)return pr(C1(o=>A.addListener(t,o),o=>A.removeListener(t,o)),"fromEvent",arguments);if("addEventListener"in A)return pr(C1(o=>A.addEventListener(t,o),o=>A.removeEventListener(t,o)),"fromEvent",arguments);throw"target is not a EventDispachter"}function iz(A){return pr(t=>{A.then(o=>{t.next(o),t.complete()},t.error.bind(t))},"fromPromise",arguments)}function VtA(A,t){return pr($5(()=>iz(fetch(A,t))),"fromFetch",arguments)}function HtA(A){return pr(Az(t=>{try{for(let o of A){if(t.disposed)return;t.next(o)}t.complete()}catch(o){t.error(o)}}),"fromIterable",arguments)}function JtA(A){let t=o=>FtA(this,void 0,void 0,function*(){try{if(o.disposed)return;let{done:a,value:l}=yield A.read();if(a)return void o.complete();o.next(l),t(o)}catch(a){o.error(a)}});return pr(o=>{t(o)},"fromReader",arguments)}function qtA(A){return pr(t=>{let o=new AbortController,a=o.signal;t.defer(()=>o.abort("cancelled")),A.pipeTo(new WritableStream({write(l){t.next(l)},close(){t.complete()},abort(l){t.error(l)}}),{signal:a}).then(()=>t.complete(),l=>t.error(l))},"fromReadableStream",arguments)}function KtA(){return pr(A=>{let t=requestAnimationFrame(function o(a){A.disposed||(A.next(a),t=requestAnimationFrame(o))});A.defer(()=>cancelAnimationFrame(t))},"fromAnimationFrame",arguments)}function jtA(A,t){return pr(function(o){let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:A,l=arguments.length>2&&arguments[2]!==void 0?arguments[2]:t+A;for(;a2?o-2:0),l=2;l{let h=a.concat(y=>(d.next(y),d.complete()));A.apply(t,h)},"bindCallback",arguments)}function ztA(A,t){for(var o=arguments.length,a=new Array(o>2?o-2:0),l=2;l{let h=a.concat((y,S)=>y?d.error(y):(d.next(S),d.complete()));A.apply(t,h)},"bindNodeCallback",arguments)}function ZtA(){return pr(()=>{},"never",arguments)}function XtA(A){return pr(t=>t.error(A),"throwError",arguments)}function Ej(){return pr(A=>A.complete(),"empty",arguments)}var uL=class extends Zn{constructor(A,t,o){super(A),this.f=t;let a=()=>{this.sink.next(this.acc),this.sink.complete()};o===void 0?this.next=l=>{this.acc=l,this.complete=a,this.resetNext()}:(this.acc=o,this.complete=a)}next(A){this.acc=this.f(this.acc,A)}},oz=Xn(uL,"reduce"),$tA=A=>Xn(uL,"count")((t,o)=>A(o)?t+1:t,0),AiA=()=>Xn(uL,"max")(Math.max),eiA=()=>Xn(uL,"min")(Math.min),tiA=()=>Xn(uL,"sum")((A,t)=>A+t,0),$v=Xn(class extends Zn{constructor(A,t,o){super(A),this.filter=t,this.thisArg=o}next(A){this.filter.call(this.thisArg,A)&&this.sink.next(A)}},"filter"),iiA=Xn(class extends Zn{next(A){}},"ignoreElements"),p_=Xn(class extends Zn{constructor(A,t){super(A),this.count=t}next(A){this.sink.next(A),--this.count===0&&(this.doDefer(),this.complete())}},"take"),CE=Xn(class extends Zn{constructor(A,t){super(A);let o=new Zn(A);o.next=()=>{o.doDefer(),A.complete()},o.complete=gj,o.subscribe(t)}},"takeUntil"),oiA=Xn(class extends Zn{constructor(A,t){super(A),this.f=t}next(A){this.f(A)?this.sink.next(A):(this.doDefer(),this.complete())}},"takeWhile"),niA=A=>oz((t,o)=>(t.push(o),t.length>A&&t.shift(),t),[]),siA=Xn(class extends Zn{constructor(A,t){super(A),this.count=t}next(A){--this.count===0&&(this.next=super.next)}},"skip"),riA=Xn(class extends Zn{constructor(A,t){super(A),A.next=sg;let o=new Zn(A);o.next=()=>{o.doDefer(),A.resetNext()},o.complete=gj,o.subscribe(t)}},"skipUntil"),dj=Xn(class extends Zn{constructor(A,t){super(A),this.f=t}next(A){this.f(A)||(this.next=super.next,this.next(A))}},"skipWhile"),aiA={leading:!0,trailing:!1},giA=class extends Zn{constructor(A,t,o){super(A),this.durationSelector=t,this.trailing=o}cacheValue(A){this.last=A,this.disposed&&this.throttle(A)}send(A){this.sink.next(A),this.throttle(A)}throttle(A){this.reset(),this.subscribe(this.durationSelector(A))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},nz=class extends Zn{constructor(A,t){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:aiA;super(A),this.durationSelector=t,this.config=o,this._throttle=new giA(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(A){this._throttle.disposed&&this.config.leading?this._throttle.send(A):this._throttle.cacheValue(A)}complete(){this._throttle.throttle=sg,this._throttle.complete(),super.complete()}},ciA=Xn(nz,"throttle"),liA={leading:!1,trailing:!0},IiA=A=>Xn(nz,"audit")(A,liA),uiA=class extends Zn{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},sz=class extends Zn{constructor(A,t){super(A),this.durationSelector=t,this._debounce=new uiA(this.sink),this._debounce.dispose()}next(A){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=A,this._debounce.subscribe(this.durationSelector(A))}complete(){this._debounce.complete(),super.complete()}},EiA=Xn(sz,"debounce"),diA=A=>Xn(sz,"debounceTime")(t=>uj(A)),CiA=Xn(class extends Zn{constructor(A,t,o){super(A),this.count=t,this.defaultValue=o}next(A){this.count--===0&&(this.defaultValue=A,this.doDefer(),this.complete())}complete(){this.defaultValue!==void 0?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("not enough elements in sequence"))}},"elementAt"),hiA=A=>t=>p_(1)(dj(o=>!A(o))(t)),BiA=Xn(class extends Zn{constructor(A,t){super(A),this.f=t,this.i=0}next(A){this.f(A)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},"findIndex"),QiA=Xn(class extends Zn{constructor(A,t,o){super(A),this.f=t,this.defaultValue=o,this.index=0}next(A){(!this.f||this.f(A,this.index++))&&(this.defaultValue=A,this.doDefer(),this.complete())}complete(){this.defaultValue!==void 0?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"first"),piA=Xn(class extends Zn{constructor(A,t,o){super(A),this.f=t,this.defaultValue=o,this.index=0}next(A){(!this.f||this.f(A,this.index++))&&(this.defaultValue=A)}complete(){this.defaultValue!==void 0?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"last"),miA=Xn(class extends Zn{constructor(A,t){super(A),this.predicate=t,this.index=0}next(A){this.predicate(A,this.index++)?this.result=!0:(this.result=!1,this.doDefer(),this.complete())}complete(){this.result!==void 0?(this.sink.next(this.result),super.complete()):this.error(new Error("no elements in sequence"))}},"every"),rz=Xn(class extends Zn{constructor(A,t,o){super(A),this.f=t,o===void 0?this.next=a=>{this.acc=a,this.resetNext(),this.sink.next(this.acc)}:this.acc=o}next(A){this.sink.next(this.acc=this.f(this.acc,A))}},"scan"),fiA=Xn(class extends Zn{constructor(){super(...arguments),this.hasLast=!1}next(A){this.hasLast?this.sink.next([this.last,A]):this.hasLast=!0,this.last=A}},"pairwise"),az=class extends Zn{constructor(A,t,o){super(A),this.mapper=t,this.thisArg=o}next(A){super.next(this.mapper.call(this.thisArg,A))}},Cj=Xn(az,"map"),yiA=A=>Xn(az,"mapTo")(t=>A),EL=class extends Zn{constructor(A,t,o){super(A),this.data=t,this.context=o}next(A){let t=this.context.combineResults;t?this.sink.next(t(this.data,A)):this.sink.next(A)}tryComplete(){this.context.resetComplete(),this.dispose()}},dL=class mX extends Zn{constructor(t,o,a){super(t),this.makeSource=o,this.combineResults=a,this.index=0}subInner(t,o){let a=this.currentSink=new o(this.sink,t,this);this.complete===mX.prototype.complete&&(this.complete=this.tryComplete),a.complete=a.tryComplete,a.subscribe(this.makeSource(t,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},gz=class extends EL{},cz=class extends dL{next(A){this.subInner(A,gz),this.next=t=>{this.currentSink.dispose(),this.subInner(t,gz)}}},h1=Xn(cz,"switchMap");function B1(A){return(t,o)=>A(()=>t,o)}var Q1=B1(Xn(cz,"switchMapTo")),DiA=class extends EL{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},lz=class extends dL{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(A){this.next2(A),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),DiA),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},SiA=Xn(lz,"concatMap"),viA=B1(Xn(lz,"concatMapTo")),MiA=class extends EL{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Iz=class extends dL{constructor(){super(...arguments),this.inners=new Set}next(A){this.subInner(A,MiA),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(A=>A.resetComplete()):this.dispose()}},RiA=Xn(Iz,"mergeMap"),wiA=B1(Xn(Iz,"mergeMapTo")),_iA=class extends EL{dispose(){this.context.resetNext(),super.dispose()}},uz=class extends dL{next(A){this.next=sg,this.subInner(A,_iA)}},TiA=Xn(uz,"exhaustMap"),NiA=B1(Xn(uz,"exhaustMapTo")),GiA=Xn(class extends Zn{constructor(A,t){super(A),this.f=t,this.groups=new Map}next(A){let t=this.f(A),o=this.groups.get(t);o===void 0&&(o=BQ(),o.key=t,this.groups.set(t,o),super.next(o)),o.next(A)}complete(){this.groups.forEach(A=>A.complete()),super.complete()}error(A){this.groups.forEach(t=>t.error(A)),super.error(A)}},"groupBy"),biA=Xn(class extends Zn{constructor(){super(...arguments),this.start=new Date}next(A){this.sink.next({value:A,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},"timeInterval"),kiA=Xn(class extends Zn{constructor(A,t){super(A),this.miniseconds=t,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(A){this.buffer.push(A)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},"bufferTime"),LiA=Xn(class extends Zn{constructor(A,t){super(A),this.buffer=[],this.delayTime=t}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(A){this.timeoutId=setTimeout(()=>{let t=this.buffer.shift();if(t){let{time:o,data:a}=t;super.next(a),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(o))}},A)}next(A){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:A})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},"delay"),Ez=Xn(class extends Zn{constructor(A,t){super(A),this.selector=t}error(A){this.dispose(),this.selector(A)(this.sink)}},"catchError"),UiA=class extends EL{tryComplete(){let A=this.context.inners.delete(this);super.dispose(),A&&this.context.checkComplete()}next(A){this.sink.next(A),this.context.expandValue(A)}},FiA=Xn(class extends dL{constructor(A,t){super(A,t),this.project=t,this.inners=new Set,this.sourceCompleted=!1}next(A){this.sink.next(A),this.expandValue(A)}expandValue(A){let t=new UiA(this.sink,A,this);this.currentSink=t,this.complete=this.tryComplete,t.complete=t.tryComplete,this.inners.add(t),t.subscribe(this.makeSource(A,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},"expand"),OiA=()=>A=>new Promise((t,o)=>{let a;new d1(A,l=>a=l,o,()=>t(a))}),PiA=()=>A=>{let t;return new ReadableStream({start(o){t=new d1(A,o.enqueue.bind(o),o.error.bind(o),o.close.bind(o))},cancel(){t.dispose()}})},Dl=function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:sg,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:sg,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:sg;return a=>new d1(a,A,t,o)},hj=Xn(class extends Zn{constructor(A,t){super(A),t instanceof Function?this.next=o=>{t(o),A.next(o)}:(t.next&&(this.next=o=>{t.next(o),A.next(o)}),t.complete&&(this.complete=()=>{t.complete(),A.complete()}),t.error&&(this.error=o=>{t.error(o),A.error(o)}))}},"tap"),xiA=Xn(class extends Zn{constructor(A,t){super(A),this.timeout=t,this.id=setTimeout(()=>this.error(new W5(this.timeout)),this.timeout)}next(A){super.next(A),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),YiA=function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1/0;return t=>{if(t instanceof _y){let o=pr(a=>{let l=A,d=new Zn(a);d.error=h=>{l-- >0?d.subscribe(t):a.error(h)},d.sourceId=o.id,d.subscribe(t)},"retry",[A]);return o.source=t,Bc.pipe(o),o}return o=>{let a=A,l=new Zn(o);l.error=d=>{a-- >0?t(l):o.error(d)},t(l)}}},Bj=(A=>(A[A.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",A[A.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",A))(Bj||{}),CL=class fX extends aj{constructor(t,o){super({mediaType:t,PlayerClass:o}),Y(this,"isRemote",!1),Y(this,"deviceId"),Y(this,"groupId",""),Y(this,"label",""),Y(this,"sourceTrack"),Y(this,"enableAutoSwitchWhenRecapturing",!0),Y(this,"_isRecapturing",!1),Y(this,"_lastRecaptureTime",0),Y(this,"_onMuteTimeoutId",-1),Y(this,"_encodeCheckTimeoutId",-1),Y(this,"recaptureMode",0),Y(this,"profile"),Y(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return!(!this.mediaTrack||this.sourceTrack===this.mediaTrack)}encodeFrame(t,o){throw new Error("Method not implemented.")}installTrackEvent(t){t.addEventListener(JA.MUTE,this.onTrackMuted),t.addEventListener(JA.UNMUTE,this.onTrackUnmuted),t.addEventListener(JA.ENDED,this.onTrackEnded),t.muted&&this.onTrackMuted(),t.readyState===JA.ENDED&&this.onTrackEnded()}uninstallTrackEvent(t){t.removeEventListener(JA.MUTE,this.onTrackMuted),t.removeEventListener(JA.UNMUTE,this.onTrackUnmuted),t.removeEventListener(JA.ENDED,this.onTrackEnded)}setStateToReady(){}capture(t){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return XA(this,null,function*(){var a,l;let d=this.sourceTrack;try{let h,y=Oo();F.emit(rA.LOCAL_TRACK_CAPTURE_START,{track:this}),t.customSource?(h=new MediaStream,h.addTrack(t.customSource)):(o||(a=this.sourceTrack)==null||a.stop(),h=yield StA(t));let S=h.getTracks()[0];return yield this.setInputMediaStreamTrack(S),t.customSource||(this.sourceTrack=S,this.updateDeviceIdInUse(),this.listenDeviceChange()),F.emit(rA.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Oo()-y,profile:this.profile,room:(l=this.manager)==null?void 0:l.room}),h}catch(h){throw F.emit(rA.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:h}),this.log.error("getUserMedia error observed ".concat(h)),h}finally{o&&d?.stop()}})}setOutputMediaStreamTrack(t){var o;if(super.setOutputMediaStreamTrack(t),this.setStateToReady(),this.isPublishing||this.isPublished)return(o=this.room)==null?void 0:o.replaceTrack(this)}get hasFlag(){var t,o;let a=kp(((t=this.room)==null?void 0:t.localPublishFlag)||0,((o=this.room)==null?void 0:o.userId)||"");return this.mediaType===4&&a.hasVideo||this.mediaType===1&&a.hasAudio||this.mediaType===2&&a.hasAuxiliary}publish(t,o){return XA(this,null,function*(){return this.room=t,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=t.userId,this._log.bindParent(t.getLogger()),yield o,this._checkPublishFlag(t)})}_checkPublishFlag(t){return new Promise((o,a)=>XA(this,null,function*(){var l,d,h,y,S;let L=()=>a(new li({code:mt.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?o():((this.state===gs.INIT||this.state==="ready")&&L(),Ma(Ea(t,"local-publish-flag-changed"),$v(()=>this.hasFlag),CE(cj(Ea(this,gs.INIT),Ea(this,"ready"))),Dl(o,a,L))),(h=(d=(l=this.room)==null?void 0:l.networkQuality)==null?void 0:d.hadRecentBadUplink)!=null&&h.call(d,2))return o();let V=t.heartbeatCount,H=((S=(y=this.mediaTrack)==null?void 0:y.stats)==null?void 0:S.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>XA(this,null,function*(){var lA,hA,MA,oe,fe,je,_e,vi;if((MA=(hA=(lA=this.room)==null?void 0:lA.networkQuality)==null?void 0:hA.hadRecentBadUplink)!=null&&MA.call(hA,2)||t.heartbeatCount-V<3)return o();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((oe=this.mediaTrack)!=null&&oe.stats){let pi=this.mediaTrack.stats.totalFrames||0;pi-H===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",pi)}let Fe=this.kind===JA.AUDIO,Dt=this.stat.bytesSent>0;if(ri[Dt?"addSuccessEvent":"addFailedEvent"]({key:Fe?503700:513702}),!Fe){let pi={H264:513704,H265:513705,VP8:513706}[((je=(fe=this.room)==null?void 0:fe.videoCodec)==null?void 0:je.toUpperCase())||"H264"];pi&&ri[Dt?"addSuccessEvent":"addFailedEvent"]({key:pi})}if(!Dt){if(ri.addEnum({key:Fe?503701:513703,value:Kp()}),ds.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(lQ()||jp()),userId:this.userId}),this.log.warn(Fe?"encode failed":"".concat((vi=(_e=this.room)==null?void 0:_e.videoCodec)==null?void 0:vi.toUpperCase()," encode failed")),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield OC(5e3),this.stat.bytesSent>0||this.hasFlag)))return o();this.emit("6",this),a(new li({message:"".concat(this.strMediaType," encode failed"),code:Fe?mt.AUDIO_ENCODE_FAILED:mt.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),F.emit(rA.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return XA(this,null,function*(){if(this.sourceTrack&&Dy){let{deviceId:t,groupId:o}=this.sourceTrack.getSettings(),{label:a}=this.sourceTrack;(yield function(l){return XA(this,arguments,function(d){let{newDeviceId:h,oldDeviceId:y,oldGroupId:S,oldLabel:L,kind:V}=d;return function*(){return h===y&&(V!==JA.AUDIO||h!==sv||(yield O5(S,L)))}()})}({newDeviceId:t,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=t,this.label=a,o&&(this.groupId=o),c1().then(l=>{let d=l.find(h=>{let y=h.deviceId===t;return o&&(y=y&&h.groupId===o),y});d&&this.emit("2",d)}))}})}setProfile(t){this.log.info("setProfile",t),Object.assign(this.profile,t)}isNeedToRecapture(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return!(!this.deviceId||!this.sourceTrack||this.kind===JA.AUDIO&&!function(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let a=o.label.toLocaleLowerCase();if(a.includes("mic")||a.includes("麦克风"))return!0;let l="".concat((o?.getSettings()||{}).deviceId,"_").concat(JA.AUDIO_INPUT);return!!sj.has(l)}(this.sourceTrack)||this.kind===JA.VIDEO&&!function(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let a=o.label.toLocaleLowerCase();if(a.includes("camera")||a.includes("webcam"))return!0;let l="".concat((o?.getSettings()||{}).deviceId,"_").concat(JA.VIDEO_INPUT);return!!sj.has(l)}(this.sourceTrack)||this._isRecapturing||t&&rQ&&mg)}onTrackMuted(){if(super.onTrackMuted(),vtA(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTimethis.onTrackMuted(),av);this._onMuteTimeoutId=setTimeout(()=>XA(this,null,function*(){var t;if((t=this.sourceTrack)!=null&&t.muted){if((ng||za)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return XA(this,null,function*(){if(UI(fX.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTimethis.onTrackEnded(),av);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(t){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return XA(this,null,function*(){var a;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let l=this.sourceTrack;o||(a=this.sourceTrack)==null||a.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let d={useExactDeviceId:!0};if(t==="user"||t==="environment")d.facingMode=t;else{let h;(this.kind==="audio"?yield om():yield nm()).find(y=>y.deviceId===t)&&(h=t),d.deviceId=h}return this.capture(d,o).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),F.emit(rA.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(h=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(h.message)),this.emit("5",h),F.emit(rA.LOCAL_TRACK_RECAPTURE,{track:this,error:h})}).finally(()=>{o&&l?.stop()})})}getRecoverCaptureDeviceId(){return XA(this,null,function*(){let t=this instanceof QQ;if(t&&this.facingMode)return this.facingMode;let{deviceId:o}=this;if(o){let a=(BL.get(o)||0)+1;if(BL.set(o,a),a>=3&&this.enableAutoSwitchWhenRecapturing){let l=t?(yield nm()).find(d=>!BL.has(d.deviceId)):(yield om()).find(d=>!BL.has(d.deviceId));l&&(this.log.warn("".concat(o," capture fail ").concat(a," times, change new ").concat(l.deviceId)),o=l.deviceId)}}return o})}stopCapture(){var t;this.sourceTrack&&(this.sourceTrack.stop(),F.emit(rA.LOCAL_TRACK_STOPPED,{track:this}),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(t=this.manager)==null||t.removeInput(this),this._onMuteTimeoutId&&clearTimeout(this._onMuteTimeoutId)}close(){super.close(),this.stopCapture()}};Qi([hc(gs.INIT,"ready",{ignoreError:!0,sync:!0})],CL.prototype,"setStateToReady"),Qi([lL()],CL.prototype,"capture"),Qi([hc("ready","publish",{ignoreError:!0,success(){F.emit(rA.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(A){var t;(t=this.room)==null||t.localTracks.delete(this);let o="error",a=A instanceof li?A:A.cause instanceof li?A.cause:A,l=!1;a instanceof li&&(a.message.includes("timeout")?o="timeout":a.code===mt.API_CALL_ABORTED&&(l=!0,o="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:o,error:a}),this.log[l?"info":"error"]("publish failed",a)}}),wy(521714,!1)],CL.prototype,"publish"),Qi([Xr(A=>function(){return XA(this,null,function*(){let t=this.state==="publish"?"started":"starting";A.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),hc([],"ready",{sync:!0})],CL.prototype,"unpublish");var hL=CL,BL=new Map;F.on(rA.SWITCH_DEVICE_SUCCESS,A=>{A.track.deviceId&&BL.delete(A.track.deviceId)});var AM=class VL extends hL{constructor(t){super(1,ptA),Y(this,"mediaType",1),Y(this,"volume",0),Y(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),Y(this,"playerMuted",!0),Y(this,"pipeline"),Y(this,"earMonitorGainNode",new HI),Y(this,"_output",new HI),Y(this,"codecPipeline",[]),Y(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),Y(this,"mixedAudioReferenceMap",new Map),Y(this,"isAudioContextLongSuspended",!1),Y(this,"after3aSilenceStartTime",0),Y(this,"_micMuted",!1),Y(this,"_volumeDetectionTrack",null),Y(this,"_volumeDetectionSource",new HI),this.manager=t,this.pipeline=new G5(t),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this._volumeDetectionSource.pipeTo(this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),F.on(rA.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return g1.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let t=(this.volume||super.getAudioLevel())*this.captureVolume;return t>1?1:t}getInternalAudioLevelAfter3A(){if(this.pipeline.isProcessEnabled)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(t){ze(t)||(t!==0||this.after3aSilenceStartTime?t>0&&(this.after3aSilenceStartTime=0):this.after3aSilenceStartTime=Oo())}setInputMediaStreamTrack(t){return XA(this,null,function*(){let o=this.trackSettings||{};ri.addEnum({key:501701,value:o.channelCount||0,useUV:!1}),ri.addEnum({key:501702,value:o.sampleRate||0,useUV:!1}),ri.addEnum({key:502700,value:0});let{sampleRate:a,channelCount:l}=o;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:a,channelCount:l}))),this.pipeline.source.channelCount=l||1,this.pipeline.replaceSource(t),yield UI(VL.prototype,this,"setInputMediaStreamTrack").call(this,t),this.updatePlayingState(!!t)})}capture(t){return XA(this,arguments,function(o){var a=this;let{deviceId:l,customSource:d,useExactDeviceId:h=!0,retryWhenExactFailed:y}=o,S=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return function*(){let L=yield UI(VL.prototype,a,"capture").call(a,{video:!1,audio:!0,microphoneId:l,echoCancellation:a.profile.echoCancellation,autoGainControl:a.profile.autoGainControl,noiseSuppression:a.profile.noiseSuppression,sampleRate:a.profile.sampleRate,channelCount:a.profile.channelCount,useExactDeviceId:h,retryWhenExactFailed:y,customSource:d},S);return gL(),L}()})}switchDevice(t){return XA(this,null,function*(){if(this.mediaTrack){if(this.deviceId===t&&!this.isUseCustomSource&&(t!==sv||(yield O5(this.groupId,this.label))))return;try{this.log.info("switchDevice audio to: ".concat(t)),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:t,useExactDeviceId:!0,retryWhenExactFailed:!1}),F.emit(rA.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(o){throw this.log.error("switch microphone failed ".concat(o)),this.deviceId&&this.recapture(this.deviceId),o}}})}listenDeviceChange(){Kc&&!Kc.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Kc.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(t){return XA(this,null,function*(){if(t.deviceId===this.deviceId){let o=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(Bj[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(t))),this.recaptureMode===0){Kg(this.userId,{eventId:2003,param1:6,streamType:1});let a=yield om();a[0]?this.recapture(a[0].deviceId):o=!0}o&&Kc.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(t){this.recaptureMode===1&&t.deviceId!==this.deviceId||(Kc.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(t))),this.recapture(t.deviceId))}update3A(t){return XA(this,arguments,function(o){var a=this;let{echoCancellation:l,noiseSuppression:d,autoGainControl:h}=o;return function*(){let y=a.sourceTrack||a.mediaTrack;if(!y)return;let S=y.getConstraints(),L=!1;!ze(l)&&l!==a.profile.echoCancellation&&(a.profile.echoCancellation=l,S.echoCancellation=l,L=!0),!ze(d)&&d!==a.profile.noiseSuppression&&(a.profile.noiseSuppression=d,S.noiseSuppression=d,L=!0),!ze(h)&&h!==a.profile.autoGainControl&&(a.profile.autoGainControl=h,S.autoGainControl=h,L=!0),L&&(gr||mg?yield y.applyConstraints(S).catch(V=>a._log.warn("update3A failed: ",V)):a.deviceId&&(yield a.recapture(a.deviceId,!0)))}()})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(t){this.pipeline.setVolume(t/100),this.pipeline.gain.node&&ri.addEnum({key:502700,value:2})}setMute(t,o){var a;this._cleanupVolumeDetectionTrack(),t==="microphone"?(this._micMuted=!0,this.sourceTrack&&(this.sourceTrack.enabled=!1),o&&this._setupVolumeDetectionTrack(),((a=this.manager)==null?void 0:a.mixWeight)<=1?(this.muted=!0,this._inputTrack&&(this._inputTrack.enabled=!1),this._outputTrack&&(this._outputTrack.enabled=!1),this.emit("mute",this),F.emit(rA.TRACK_MUTED,{track:this})):this._outputTrack&&(this._outputTrack.enabled=!0)):t===!0?(this._micMuted=!1,this.muted=!0,this.sourceTrack&&(this.sourceTrack.enabled=!1),this._inputTrack&&(this._inputTrack.enabled=!1),this._outputTrack&&(this._outputTrack.enabled=!1),o&&this._setupVolumeDetectionTrack(),this.emit("mute",this),F.emit(rA.TRACK_MUTED,{track:this})):(this._micMuted=!1,this.muted=!1,this.sourceTrack&&(this.sourceTrack.enabled=!0),this._inputTrack&&(this._inputTrack.enabled=!0),this._outputTrack&&(this._outputTrack.enabled=!0),this.emit("unmute",this),F.emit(rA.TRACK_UNMUTED,{track:this}))}_setupVolumeDetectionTrack(){let t=this.sourceTrack||this.mediaTrack;if(!t)return;this._volumeDetectionTrack=t.clone(),this._volumeDetectionTrack.enabled=!0;let o=r1(this._volumeDetectionTrack);o&&this._volumeDetectionSource.setNode(o)}_cleanupVolumeDetectionTrack(){this._volumeDetectionTrack&&(this._volumeDetectionTrack.stop(),this._volumeDetectionTrack=null),this._volumeDetectionSource.deleteNode()}get isMicMuted(){return this._micMuted}setAudioVolume(t){super.setAudioVolume(0),ng&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(VI().createGain()),this._output.setNode(VI().destination)),this.earMonitorGainNode.node.gain.value=t}enableTrackANS(t){return this.update3A({noiseSuppression:t})}enableTrackAEC(t){if(this.sourceTrack&&!mg&&!ng)return this.update3A({echoCancellation:t})}addDenoiser(t){var o;nd<=92&&((o=this.trackSettings)==null?void 0:o.sampleRate)!==48e3?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(ri.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(t),this.enableTrackANS(!1))}mixAudioReference(t,o){if(this.mixedAudioReferenceMap.has(o))return;this.log.info("mixAudioReference() => ".concat(o));let a=r1(t);if(!a)return;let l=new HI,d=VI().createGain();d.gain.value=1;let h=new HI;l.pipeTo(h).pipeTo(this.pipeline.mixNode),l.setNode(a),h.setNode(d),this.mixedAudioReferenceMap.set(o,[l,h])}unMixAudioReference(t){let[o,a]=this.mixedAudioReferenceMap.get(t)||[];o&&(this.log.info("unMixAudioReference() => ".concat(t)),o.deleteNode(),a?.deleteNode(),this.mixedAudioReferenceMap.delete(t))}setAudioReferenceVolume(t,o){let[a,l]=this.mixedAudioReferenceMap.get(t)||[];l!=null&&l.node&&(l.node.gain.value=o/100,this.log.info("setAudioReferenceVolume() => ".concat(t," ").concat(l.node.gain.value)))}addAudioProcessor(t,o,a){this.pipeline.silentNode.setNode(a),this.pipeline.mixNode.setNode(o),this.pipeline.aec.setNode(t)}removeDenoiser(t){if(this.pipeline.denoiser.node===t)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(t){this.pipeline.aec.node===t&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this._cleanupVolumeDetectionTrack(),this.mixedAudioReferenceMap.forEach(t=>{let[o,a]=t;o.deleteNode(),a.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),Kc.off("audioInputAdded",this.handleMicrophoneAdded,this),Kc.off("audioInputRemoved",this.handleMicrophoneRemoved,this),F.off(rA.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(t){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return XA(this,null,function*(){try{yield UI(VL.prototype,this,"recapture").call(this,t,o)}catch(a){let l=(yield om()).find(d=>d.deviceId!==t);if(!l)throw a;yield UI(VL.prototype,this,"recapture").call(this,l.deviceId)}})}encodeFrame(t){return this.manager?this.manager.encodePipeline.reduceRight((o,a)=>a?a({frame:o,ntp:Vf()}):o,t):t}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(t=>t)}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended(t){let{isSuspended:o}=t;if(this.pipeline.isProcessEnabled)if(o){this.isAudioContextLongSuspended=!0,this.log.warn("context has suspended for ".concat(1.5," seconds, change to source audio").concat(Hp?"":", non-Safari"));let a=this.sourceTrack||this.mediaTrack;a&&this.setOutputMediaStreamTrack(a)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(t){if(this.isAudioContextLongSuspended){let o=this.sourceTrack||this.mediaTrack;o&&(t=o)}super.setOutputMediaStreamTrack(t)}};function p1(A,t){return t+4<=A.byteLength&&A.getUint8(t)===0&&A.getUint8(t+1)===0&&A.getUint8(t+2)===0&&A.getUint8(t+3)===1?4:t+3<=A.byteLength&&A.getUint8(t)===0&&A.getUint8(t+1)===0&&A.getUint8(t+2)===1?3:0}function dz(A){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],o=new DataView(A),a=[],l=0;for(;l0){h=H;break}let y=h===-1?o.byteLength:h,S=y-l,L=new ArrayBuffer(S),V=new DataView(L);for(let H=0;H1&&arguments[1]!==void 0&&arguments[1];this.dataView=A,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let{seiPayloadStartIndex:A}=this,t=this.dataView.byteLength-2,o=[],a=0;for(let d=A;d<=t;d++){let h=this.dataView.getInt8(d);switch(h){case 0:case 1:case 2:case 3:a===2&&(o.push(3),a=0),h===0?a+=1:a=0,o.push(h);break;default:a=0,o.push(h)}}o.push(this.dataView.getInt8(this.dataView.byteLength-1));let l=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,A),...o]).buffer);this.dataView=l}removePreventionByte(){let{seiPayloadStartIndex:A}=this,t=this.dataView.byteLength-1,o=[],a=0;for(let d=A;d<=t;d++)switch(this.dataView.getInt8(d)){case 0:a++,o.push(this.dataView.getInt8(d));break;case 3:a!==2&&o.push(this.dataView.getInt8(d)),a=0;break;default:o.push(this.dataView.getInt8(d)),a=0}let l=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,A),...o]).buffer);this.dataView=l}get seiPayloadStartIndex(){let A=6;for(let t=6;t=this.dataView.byteLength?0:31&this.dataView.getUint8(A)}getStartCodeLength(){return this.dataView.byteLength>=4&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===0&&this.dataView.getUint8(3)===1?4:this.dataView.byteLength>=3&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===1?3:0}get isIDR(){return this.naluType===5}get isSPS(){return this.naluType===7}get isPPS(){return this.naluType===8}get isSEI(){return this.naluType===6}},ViA=class{constructor(){Y(this,"_seiMessageList",[]),Y(this,"_smallSeiMessageList",[]),Y(this,"_seiPayloadType",243)}encodeSEINalu(A){let t=A.byteLength,o=parseInt(String(t/255),10),a=t%255,l=[];l.push(0,0,0,1,6,this._seiPayloadType);for(let h=0;h0&&A.data.byteLength>0){let a=9-this.getNaluCount(A.data);if(a<=0)return 0;let l=o.splice(0,a).reverse().map(this.encodeSEINalu.bind(this)),d=l.reduce((V,H)=>V+H.dataView.byteLength,0),h=new ArrayBuffer(d+A.data.byteLength),y=new DataView(h),S=new DataView(A.data),L=0;for(let V=0;V1&&arguments[1]!==void 0?arguments[1]:4,bo),Y(this,"profile",Di({},Av)),Y(this,"avoidCropping",!1),Y(this,"_scaleResolutionDownBy"),Y(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0}),Y(this,"small"),Y(this,"isNeedToSetBandwidth"),Y(this,"muteImage"),Y(this,"manager"),Y(this,"_seiCodec",new ViA),this.manager=t;let o=()=>{var a;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let l=zd(((a=this.room)==null?void 0:a.sdkAppId)||0)?Lb:E0;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(l)),this.setProfile(So(Di({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",o),this.on("publish",o),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(Dy&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var t;return((t=this._inputTrack)==null?void 0:t.contentHint)||""}get isQosClearFirst(){var t;return((t=this._inputTrack)==null?void 0:t.contentHint)==="detail"}get hasSmall(){var t;return!((t=this.manager)==null||!t.hasSmall)}setMute(t){return XA(this,null,function*(){var o,a,l;if(Ws(t)){if(this.muteImage===t)return;yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),yield(a=this.manager)==null?void 0:a.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:t,fillVideo:!0}),this.muteImage=t,UI(F_.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(l=this.manager)==null?void 0:l.deleteWatermark("mute"),this.muteImage=void 0),UI(F_.prototype,this,"setMute").call(this,t)})}capture(t){return XA(this,arguments,function(o){var a=this;let{deviceId:l,facingMode:d,useExactDeviceId:h=!0,customSource:y,retryWhenExactFailed:S=!0}=o;return function*(){let L={audio:!1,video:!0,facingMode:d||a.facingMode,cameraId:l,width:a.profile.width,height:a.profile.height,frameRate:a.profile.frameRate,useExactDeviceId:h,retryWhenExactFailed:S,customSource:y};if(L.facingMode==="environment"){let V=yield a.getDeviceIdWhenUsingBackCamera();V&&(L.cameraId=V)}return UI(F_.prototype,a,"capture").call(a,L)}()})}setProfile(t){var o;let a=this.fallbackProfile(t);if(a.bitrate&&(this.isNeedToSetBandwidth=a.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(a);else{let l=zd(((o=this.room)==null?void 0:o.sdkAppId)||0)?Lb:E0;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(l)),super.setProfile(So(Di({},this.profile),{width:1920,height:1080}))}}applyProfile(){return XA(this,null,function*(){var t,o;if(!this.mediaTrack)return;let{width:a=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),d=a*l,h=this.settings,y=h.height!==this.profile.height||h.width!==this.profile.width||h.frameRate!==this.profile.frameRate;if(y&&($d===16&&this.deviceId?yield this.recapture(this.deviceId):(Lp(this.outMediaTrack)?yield(t=this.outMediaTrack)==null?void 0:t.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}):yield(o=this.sourceTrack||this.mediaTrack)==null?void 0:o.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:S=0,height:L=0}=(this.sourceTrack||this.mediaTrack).getSettings(),V=S*L;return y&&V&&d&&V===d?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:JA.VIDEO,videoType:JA.BIG})}})}get settings(){let t={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},o=this.sourceTrack||this.mediaTrack;return Dy&&o&&Object.assign(t,o.getSettings()),t}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:F0(this.settings,this.profile)}isAllowed2k4k(t){var o;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(t.height*t.width<3686400))||((o=this.room.scheduleResult.trtcAutoConf)==null?void 0:o["2k4k"])===1}isNeedToSwitchDevice(t){return!(!this.mediaTrack||this.deviceId===t||this.facingMode===t)}switchDevice(t){return XA(this,null,function*(){try{if(!this.isNeedToSwitchDevice(t)&&!this.isUseCustomSource)return;let o={useExactDeviceId:!0,retryWhenExactFailed:!1};t==="user"||t==="environment"?o.facingMode=t:o.deviceId=t,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(o),F.emit(rA.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(o){throw this.log.error("switch camera failed ".concat(o)),this.deviceId&&this.recapture(this.deviceId),o}})}getDeviceIdWhenUsingBackCamera(){return XA(this,null,function*(){let t;try{if(yk&&!ly&&A1){let o=(yield nm(!0)).map(l=>{var d;return So(Di({},l),{capabilities:(d=l.getCapabilities)==null?void 0:d.call(l)})}).filter(l=>{var d,h;return(h=(d=l.capabilities)==null?void 0:d.facingMode)==null?void 0:h.includes("environment")}),a=o[0];o.forEach(l=>{var d,h,y,S;let{capabilities:L}=l;((d=L.width)!=null&&d.max&&(h=L.height)!=null&&h.max?L.width.max*L.height.max:0)>((y=a.capabilities.width)!=null&&y.max&&(S=a.capabilities.height)!=null&&S.max?a.capabilities.width.max*a.capabilities.height.max:0)&&(a=l)}),a!=null&&a.capabilities&&(this._log.info("use max resolution back camera",a),t=a.deviceId)}}catch(o){this._log.warn("get max res camera failed",o)}return t})}updateSmallConfig(t){return XA(this,null,function*(){var o,a;this._log.info("update small stream config: ".concat(JSON.stringify(t)));let l=!this.small;this.small=this.fallbackProfile(t,!0),yield(o=this.manager)==null?void 0:o.update(),l&&(yield(a=this.room)==null?void 0:a.enableSmall(!0)),this.log.info("update small stream config success")})}fallbackProfile(t){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1],a=t.width>t.height,l=Di({},t);return t.width*t.height<=19200&&za&&EE&&(this.log.warn("".concat(o?"small ":"","resolution is ").concat(t.width,"*").concat(t.height,", fallback to 240*180 for android chrome")),l.width=a?240:180,l.height=a?180:240,l.bitrate=Math.max(t.bitrate,150)),t.width*t.height>921600&&x2&&(l.width=a?1280:720,l.height=a?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),wk(PI,"14.3")&&uy(PI,"14.0",!0)&&this.on("7",()=>{let d=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=d?640:480,this.profile.height=d?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>230400&&(this.profile.width=d?640:360,this.profile.height=d?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!o&&this.avoidCropping&&(EE||gr)&&!e_()&&t.width*t.height<=230400&&t.width/t.height===16/9&&(this._scaleResolutionDownBy=1280/t.width,l.width=1280,l.height=720,this.log.warn("capture 720p, scale: ".concat(this._scaleResolutionDownBy))),l}stopSmall(){var t,o;this.small&&(delete this.small,(t=this.manager)==null||t.update(),(o=this.room)==null||o.enableSmall(!1))}listenDeviceChange(){Kc&&!Kc.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Kc.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(t){return XA(this,null,function*(){if(t.deviceId===this.deviceId){let o=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(Bj[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(t))),this.recaptureMode===0){Kg(this.userId,{eventId:2003,param1:7,streamType:2});let a=yield nm();a[0]?this.recapture(a[0].deviceId):o=!0}o&&Kc.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(t){return XA(this,null,function*(){this.recaptureMode===1&&t.deviceId!==this.deviceId||(Kc.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn("camera added: ".concat(JSON.stringify(t))),this.recapture(t.deviceId))})}encodeFrame(t,o){if(!this.manager)return t;let a=o?8:this.mediaType;return this.manager.encodePipeline.reduceRight((l,d)=>d?d({frame:l,mediaType:a}):l,t)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(t=>t)}play(t,o){return ze(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(t,o)}close(){Kc.off("videoInputAdded",this.handleCameraAdded,this),Kc.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(t){return XA(this,null,function*(){try{yield UI(F_.prototype,this,"recapture").call(this,t)}catch(o){let a=(yield nm()).find(l=>l.deviceId!==t);if(!a)throw o;yield UI(F_.prototype,this,"recapture").call(this,a.deviceId)}})}setContentHint(t){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==t&&(this.log.info("setContentHint ".concat(t)),this.mediaTrack.contentHint=t),this.outMediaTrack&&this.outMediaTrack.contentHint!==t&&(this.outMediaTrack.contentHint=t))}setRotation(t){this.manager&&(this.isScreen||ze(t)||t!==this.rotation&&(this.rotation=t,this.manager.rotation=t))}};Qi([Xv(function(A){this.setContentHint(A.contentHint||"motion")})],Cz.prototype,"capture");var QQ=Cz,hz={};Wh(hz,{REPORT_TYPE:()=>O0,buildSSOPackage:()=>oQ,bytes2ms:()=>N0,calculateScaleResolutionDownNumber:()=>F0,concatArrayBuffers:()=>hv,convertObjectNumberToInt:()=>U0,copyProperties:()=>B2,deepClone:()=>iy,deepCloneBasic:()=>oy,deepMerge:()=>$h,delay:()=>OC,fibonacci:()=>Ay,formatedTime:()=>v2,getConstructorName:()=>Iv,getContainerFromElement:()=>tk,getEnv:()=>d2,getFirst16Bits:()=>R2,getInternalVersion:()=>D2,getLast16Bits:()=>P0,getLoggerUrl:()=>Xf,getMediaStreamTrackInfo:()=>rk,getMuteStateFromFlag:()=>kp,getNetworkType:()=>_0,getNumNetworkType:()=>$f,getReconnectionTimeout:()=>bp,getStringByteLength:()=>L0,getTestSignalDomain:()=>C2,getTurnServer:()=>S2,getUint32Version:()=>ok,getValueType:()=>Qg,getViewListFromView:()=>dv,glog:()=>p2,ipv4ToUint32:()=>Ev,isArray:()=>ka,isAudioWorkletSupported:()=>m2,isBoolean:()=>br,isConstructor:()=>ty,isEmpty:()=>b0,isFunction:()=>ba,isLangChinese:()=>Zd,isMediaStreamTrack:()=>Ak,isNumber:()=>Ys,isObject:()=>ed,isOverseaSdkAppId:()=>zd,isPlainObject:()=>uE,isPortrait:()=>ik,isPromise:()=>ey,isRemoteTrack:()=>ek,isRotate90Or270:()=>iQ,isSetSinkIdSupported:()=>f2,isString:()=>Ws,isUndefined:()=>ze,isVideoMixerOutputTrack:()=>Lp,loadImage:()=>Cv,loadVideo:()=>M2,ms2bytes:()=>Q2,ms2samples:()=>G0,normalizeUrl:()=>sk,performanceNow:()=>Oo,promiseAny:()=>uv,samples2ms:()=>$b,setNetworkTypeFromWebRTC:()=>T0,stringify:()=>Xd,stringifyIncludeValue:()=>k0,throttlePromise:()=>nk});var HiA=[-1,-1,1,-1,-1,1,1,1],JiA=[0,0,1,0,0,1,1,1],QL=class lW extends gs{constructor(t,o){if(super(),this.context=t,Y(this,"name"),Y(this,"input"),Y(this,"output"),Y(this,"texture"),Y(this,"ctx2d",null),Y(this,"fbo"),Y(this,"width",0),Y(this,"height",0),Y(this,"x",0),Y(this,"y",0),Y(this,"program"),Y(this,"vertexShader"),Y(this,"fragmentShader"),Y(this,"totalFrames",0),Y(this,"dropFrames",0),Y(this,"matchInputSize",!0),Y(this,"texCoordBuffer"),Y(this,"positionBuffer"),Y(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),Y(this,"cost",0),Y(this,"_canvas",null),Y(this,"_image"),Y(this,"log"),this.context.on("disconnect",this.close,this),this.name=o.name,this.log=o.logger,this.matchInputSize=o.matchInputSize!==!1,this.width=o.width||t.width,this.height=o.height||t.height,this._image=o.image,t instanceof pQ)t.ctx&&o.create2d&&(typeof OffscreenCanvas=="function"&&$d!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);else try{let a=t.ctx;this.texCoordBuffer=this.createBuffer(JiA),this.positionBuffer=this.createBuffer(HiA),o.createTexture!==!1&&(this.texture=a.createTexture(),this.useTexture(),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.pixelStorei(a.UNPACK_ALIGNMENT,1)),o.useFbo&&(this.fbo=a.createFramebuffer(),this.useBufferFrame(),this.useTexture(),a.texImage2D(a.TEXTURE_2D,0,a.RGBA,this.width,this.height,0,a.RGBA,a.UNSIGNED_BYTE,null),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,this.texture,0)),o.useDefaultProgram?this.program=t.defaultProgam:(o.vertexShaderSource||o.fragmentShaderSource)&&(this.vertexShader=o.vertexShaderSource?t.createShader(a.VERTEX_SHADER,o.vertexShaderSource):t.defaultVShader,this.fragmentShader=o.fragmentShaderSource?t.createShader(a.FRAGMENT_SHADER,o.fragmentShaderSource):t.defaultFShader,this.program=t.createProgram(this.vertexShader,this.fragmentShader))}catch(a){this.context.destroy(new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(a.message||a)}))}}get image(){return this._image}set image(t){this._image=t}createFramebuffer(t){let o=this.context.ctx,a=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,a),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,t,0),a}connect(t){for(var o=arguments.length,a=new Array(o>1?o-1:0),l=1;l0&&arguments[0]!==void 0?arguments[0]:0;var o;(o=this.output)==null||o.update(t)}disconnect(){for(var t,o=arguments.length,a=new Array(o),l=0;l{d&&(t.activeTexture(t.TEXTURE0+h),t.bindTexture(t.TEXTURE_2D,d))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let t=this.context.ctx;t.bindFramebuffer(t.FRAMEBUFFER,this.fbo||null)}createBuffer(t){let o=this.context.ctx,a=o.createBuffer();return o.bindBuffer(o.ARRAY_BUFFER,a),o.bufferData(o.ARRAY_BUFFER,new Float32Array(t),o.STATIC_DRAW),a}setTexBuffer(t){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,this.texCoordBuffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array(t),o.STATIC_DRAW)}setPosBuffer(t){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,this.positionBuffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array(t),o.STATIC_DRAW)}changeBufferData(t,o){let a=this.context.ctx;a.bindBuffer(a.ARRAY_BUFFER,t),a.bufferData(a.ARRAY_BUFFER,new Float32Array(o),a.STATIC_DRAW)}setAttributes(){let t=this.context.ctx;for(var o=arguments.length,a=new Array(o),l=0;l{t.enableVertexAttribArray(h),t.bindBuffer(t.ARRAY_BUFFER,d),t.vertexAttribPointer(h,2,t.FLOAT,!1,0,0)})}getVertexPoint(t,o){return[t/this.width*2-1,o/this.height*2-1]}layout2texCoords(t){return[...this.getVertexPoint(t.x,t.y),...this.getVertexPoint(t.x+t.width,t.y),...this.getVertexPoint(t.x,t.y+t.height),...this.getVertexPoint(t.x+t.width,t.y+t.height)]}resize(t,o){if(this.width!==t||this.height!==o){if(this.width=t,this.height=o,this._canvas&&(this._canvas.width=t,this._canvas.height=o),this.texture&&this.fbo){this.useTexture();let a=this.context.ctx;a.texImage2D(a.TEXTURE_2D,0,a.RGBA,t,o,0,a.RGBA,a.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(t,o)}}draw(t,o){this.setAttributes(t||this.positionBuffer,o||this.texCoordBuffer);let a=this.context.ctx;a.drawArrays(a.TRIANGLE_STRIP,0,4)}draw2d(t,o,a,l,d,h,y,S,L){let V=!(ze(h)||ze(y)||ze(S)||ze(L));return!(!this.ctx2d||!t)&&(t instanceof ImageData?(V?this.ctx2d.putImageData(t,o,a,h,y,S,L):this.ctx2d.putImageData(t,o,a),this.emit(lW.RENDER,this.ctx2d.canvas)):(V?this.ctx2d.drawImage(t,h,y,S,L,o,a,l,d):this.ctx2d.drawImage(t,o,a,l,d),this.emit(lW.RENDER,t)),typeof VideoFrame<"u"&&t instanceof VideoFrame&&t.close(),!0)}drawBackGround2d(t){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=t,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var t;let{totalFrames:o,x:a,y:l,width:d,height:h,name:y,cost:S}=this,L=Date.now(),V=(o-this.lastInfo.totalFrames)/((L-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:o,x:a,y:l,width:d,height:h,timestamp:L,fps:V,name:y,cost:S},Di({parent:(t=this.input)==null?void 0:t.getInfo()},this.lastInfo)}createTexture(t){let o=this.context.ctx,a=o.createTexture();return this.useTextures(a),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.pixelStorei(o.UNPACK_ALIGNMENT,1),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,t),a}};Y(QL,"RENDER","render"),Qi([hc(gs.INIT,"connected",{sync:!0})],QL.prototype,"connect"),Qi([hc("connected",gs.INIT,{ignoreError:!0,sync:!0})],QL.prototype,"disconnect"),Qi([hc([],"closed",{sync:!0})],QL.prototype,"close");var tC=QL,qiA=Ma(tz(250),Cj(()=>performance.now()),IL()),KiA=[0,1,1,1,0,0,1,0],Qj=class extends tC{constructor(A,t){super(A,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),Y(this,"_intervalId",0),Y(this,"_sequence",0),Y(this,"checkGLError",!1),Y(this,"checkVisibilityChange"),A instanceof pQ?this.ctx2d=A.ctx||null:A.available&&t!=null&&t.mirrorUpAndDown&&this.setTexBuffer(KiA)}start(A){this.log.info("".concat(this.name," start render ").concat(A," fps")),kr.clearTask(this._intervalId),this._intervalId=kr.run("intervalInWorker",()=>{if(A!==this.context.frameRate&&(kr.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof qC){let t=this.context.ctx.getError();t&&this.context.destroy(new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:5,message:"".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(t)}))}},{fps:this.context.frameRate})}render(A){var t;return!((t=this.input)==null||!t.requestFrame(A))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(tC.RENDER,this.context._canvas),!0)}addInput(A){for(var t=arguments.length,o=new Array(t>1?t-1:0),a=1;a0&&arguments[0]!==void 0?arguments[0]:0;this.state!=="closed"&&(this._intervalId&&(kr.clearTask(this._intervalId),this._intervalId=0,A===1&&(this.log.info("".concat(this.name," use requestVideoFrameCallback")),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info("".concat(this.name," use timer")),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(A){super.removeInput(A),kr.clearTask(this._intervalId)}resize(A,t){super.resize(A,t),this.context.setSize(A,t)}close(){super.close(),kr.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},pj=class extends Qj{constructor(A,t){super(A,t),Y(this,"_videoTrack"),Y(this,"_muteOb"),Y(this,"_closedOb",Ea(this,"closed")),Y(this,"_subscription"),Y(this,"_canvasContainer"),Number(aQ)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=A.canvas.captureStream().getVideoTracks(),this._muteOb=Ea(this._videoTrack,"mute"),Ma(Ea(this._videoTrack,"ended"),CE(this._closedOb),Dl(()=>{this.context.destroy(new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){var A;this._subscription=Ma(this._muteOb,CE(this._closedOb),Q1((A=5e3,t=>{let o=performance.now();Ma(qiA,dj(a=>a-o{var t;return!((t=this._videoTrack)==null||!t.muted||document.hidden)}),Dl(()=>{this.context.destroy(new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var A;(A=this._subscription)==null||A.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info("".concat(this.name," put canvas to body")),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(A){return this.putCanvasIntoDom(),super.render(A)}render2d(A){return this.putCanvasIntoDom(),super.render2d(A)}close(){var A,t;super.close(),(A=this._videoTrack)==null||A.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},jiA=class extends pj{render(A){var t;let o=!((t=this.input)==null||!t.requestFrame(A));if(this.context._canvas2d){let a=this.context._canvas2d.getContext("2d");a.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),a.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height),this.emit(tC.RENDER,this.context._canvas2d)}else this.emit(tC.RENDER,this.context._canvas);return o}},WiA=class extends pj{constructor(A,t,o){super(A,{name:"smallDestination",logger:o}),this.resolution=t}resize(A,t){let o,a=A*t,l=this.resolution.width*this.resolution.height;this.log.info("big res: ".concat(A,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),a>l?o=a/l:(this.log.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(A," * ").concat(t," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),o=a/19200),super.resize(A/Math.sqrt(o),t/Math.sqrt(o))}},Bz=class extends tC{constructor(A,t){super(A,Di({name:"imageSource"},t)),Y(this,"_lastImage"),Y(this,"_totalFrames",0),Y(this,"_autoResize",!1),Y(this,"_canvasRendered"),Y(this,"videoCallbackId",0),Y(this,"waitingFirstFrame",!0),Y(this,"shouldUpdate",!0),this._autoResize=t?.autoResize!==!1,$d===16&&(this._canvasRendered=BQ(),Ma(this._canvasRendered,lj(this._image),h1(o=>o instanceof HTMLCanvasElement?Ea(o,"rendered"):Ej()),CE(Ea(this,"closed")),Dl(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let A=this.image;this.videoCallbackId&&A.cancelVideoFrameCallback(this.videoCallbackId),Am()&&!document.hidden&&(this.videoCallbackId=A.requestVideoFrameCallback((t,o)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=o.presentedFrames,this.update(1))}))}_render(A,t){var o;let{width:a,height:l}=this,{image:d}=this;if(d instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:a,videoHeight:l}=d,!a||!l)return!1;d.width=a,d.height=l}else if(d instanceof HTMLImageElement||d instanceof ImageData||d instanceof ImageBitmap){if({width:a,height:l}=d,d!==this._lastImage)this._lastImage=d;else if(a===this.width&&l===this.height)return!0}else d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?({width:a,height:l}=d,this._lastImage=d):typeof VideoFrame<"u"&&d instanceof VideoFrame&&({displayWidth:a,displayHeight:l}=d,(o=this._lastImage)==null||o.close(),this._lastImage=d);if(!this._autoResize)return!0;if(this.width===a&&this.height===l&&this.totalFrames){if(t){this.useTexture();let h=this.context.ctx;h.texSubImage2D(h.TEXTURE_2D,0,0,0,h.RGBA,h.UNSIGNED_BYTE,d)}}else{if(t){this.useTexture();let h=this.context.ctx;h.texImage2D(h.TEXTURE_2D,0,h.RGBA,h.RGBA,h.UNSIGNED_BYTE,d)}this.resize(a,l)}return!0}get image(){return this._image}set image(A){var t;(t=this._canvasRendered)==null||t.next(A),this._image=A}render(A){return this._render(A,!0)}render2d(A){return this._render(A,!1)}},Qz=class extends Bz{constructor(A,t,o){super(A,o),this._player=t,this.name="videoPlayerSource",Ma(Ea(this._player,Mo.PLAYER_STATE_CHANGED),CE(Ea(this,"closed")),$v(a=>{let{state:l}=a;return l==="PLAYING"}),Dl(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},m_=class extends Qz{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(A,t,o){super(A,new bo({id:o.name,track:t,muted:!0,container:null,objectFit:"contain",log:o.logger}),o),this.name="videoTrackSource",this._player.play()}replaceTrack(A){this.waitingFirstFrame=!0,this._player.setTrack(A),this._player.play()}close(){super.close(),this._player.stop()}},ziA=class extends tC{constructor(A,t,o){super(A,So(Di({name:"textSource"},o),{create2d:!0})),Y(this,"hasChange",!0),Y(this,"content",""),this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(A){this.ctx2d&&(this.ctx2d.font=A,this.hasChange=!0)}get font(){var A;return((A=this.ctx2d)==null?void 0:A.font)||""}set color(A){this.ctx2d&&(this.ctx2d.fillStyle=A,this.hasChange=!0)}get color(){var A;return((A=this.ctx2d)==null?void 0:A.fillStyle)||""}render2d(A){return!(!this.ctx2d||!this.hasChange)&&(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0)}render(A){return!1}resize(A,t){if(!this.ctx2d)return;let{color:o,font:a}=this;super.resize(A,t),this.color=o,this.font=a}drawMultilineText(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1.2;if(!this.ctx2d)return;let a=this.ctx2d.measureText(this.content);t+=a.fontBoundingBoxAscent||a.actualBoundingBoxAscent||0;let l=this.font.match(/(\d+)px/),d=(l?parseInt(l[1],10):16)*o,h=this.content.split(` + `,o.onclick=this.onQuestionClick.bind(this);let a=document.createElement("div");a.className=Z,a.innerText="".concat(Zd()?"详情 >":"Detail >"),a.onclick=this.onCollapseClick.bind(this);let l=A.content.firstChild,d=l.querySelector(".".concat(C_));return d.appendChild(a),d.appendChild(o),d.appendChild(t),l}addDiaLog(){Si()||(Ot=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(jv)).onclick=A=>A.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",pA.info("show autoplay dialog"),ds.uploadEvent({log:Te}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Ot=!1),qc=null}onConfirm(){pA.warn("confirm clicked, try resume stream"),F.emit(rA.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let A=this._dialogNode.querySelector(".".concat(bA));A.style.visibility="".concat(this._showDetail?"hidden":"visible"),A.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||ds.uploadEvent({log:xe}),this._isCollapseClicked=!0}onQuestionClick(){window.open(bi,"_blank"),this._isQuestionClicked||ds.uploadEvent({log:It}),this._isQuestionClicked=!0}},qc=null;function JC(){qc||(qc=new ra)}var Bi,bo=class QX extends HC{constructor(t){super(t,JA.VIDEO),Y(this,"stat",{}),Y(this,"_calculateTimeout",-1),Y(this,"viewMirror",!1),Y(this,"objectFit","cover"),Y(this,"container"),Y(this,"canvas"),Y(this,"shouldRenderAlpha",!1),Y(this,"_preSize",{width:0,height:0}),Y(this,"posterImg"),Y(this,"pipWindow"),Y(this,"enterPIPPromise"),Y(this,"_originContainerPosition"),Y(this,"_isResettingSrcObject",!1),Y(this,"_wrapper",null),Y(this,"_useWrapper",!1),Y(this,"_isFirstFrameRenderEmitted",!1),this.mode=t.canvas?1:0,this.container=t.container,this.canvas=t.canvas,ze(t.viewMirror)||(this.viewMirror=t.viewMirror),ze(t.objectFit)||(this.objectFit=t.objectFit),this.initializeElement()}get isPlaying(){var t;return!(this._state!=="PLAYING"||this.element&&this.element.paused)&&((t=this.track)==null?void 0:t.readyState)==="live"&&!this.track.muted}initializeElement(){let t=document.createElement(JA.VIDEO);this.track&&this.mode!==2&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id","video_".concat(this.id)),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,za&&(t.poster="data:,"),this._appendToWrapper(),this.bindElementEvents(),this.calculateStat(),this._bindFirstFrameRenderEvent(t)}_bindFirstFrameRenderEvent(t){let o=()=>{if(this._isFirstFrameRenderEmitted)return;this._isFirstFrameRenderEmitted=!0;let a=t.videoWidth||0,l=t.videoHeight||0;this._log.info("first frame render: ".concat(a,"x").concat(l)),this.emit(Mo.FIRST_FRAME_RENDER,{width:a,height:l})};typeof t.requestVideoFrameCallback=="function"?t.requestVideoFrameCallback(o):t.addEventListener("loadeddata",o,{once:!0})}get styleAttribute(){let t=this._useWrapper?"grid-area:1/1;width:100%;height:100%;object-fit:".concat(this.objectFit,";").concat(this.shouldRenderAlpha?"":"background-color:black",";"):"width:100%;height:100%;object-fit:".concat(this.objectFit,";").concat(this.shouldRenderAlpha?"":"background-color:black",";");return this.viewMirror&&(t+="transform:scaleX(-1);"),t}setLiveMode(t){if(this._useWrapper!==t&&(this._useWrapper=t,this.elementToRender&&this.elementToRender.setAttribute("style",this.styleAttribute),this.container&&this.elementToRender))if(t){let o=this._getOrCreateWrapper();o.insertBefore(this.elementToRender,o.firstChild)}else this.container.appendChild(this.elementToRender),this._cleanupWrapper()}setContainer(t){if(this.container===t)return;let o=this._wrapper,a=this.container;this.container=t,this._pausedRetryCount=Gp,this.track&&this.elementToRender&&this._appendToWrapper(),o&&a&&a!==this.container&&o.isConnected&&o.children.length===0&&o.remove()}_getOrCreateWrapper(){if(!this.container)throw new Error("[VideoPlayer] container is required");let t=this.container.querySelector("[data-trtc-video-wrapper]");return t||(t=document.createElement("div"),t.setAttribute("data-trtc-video-wrapper","true"),t.style.cssText="display:grid;width:100%;height:100%;",this.container.appendChild(t)),this._wrapper=t,t}_appendToWrapper(t){let o=t??this.elementToRender;if(this.container&&o)if(this._useWrapper){let a=this._getOrCreateWrapper();a.insertBefore(o,a.firstChild)}else this.container.appendChild(o)}bindElementEvents(){let t=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),this.handleFullscreenChange=this.handleFullscreenChange.bind(this),this.handleVolumeChange=this.handleVolumeChange.bind(this),t&&t.add(JA.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(JA.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(JA.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener(JA.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.addEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.addEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.addEventListener("volumechange",this.handleVolumeChange))}handleTrackEvent(t){var o;return t.type===JA.MUTE&&((o=this.stat)!=null&&o.fps&&(this.stat.fps=0),this.isFullscreen()&&this.resetSrcObjectToReplay()),super.handleTrackEvent(t)}handleFullscreenChange(){this.isFullscreen()?(this._log.info("enter fullscreen"),this.emit(Mo.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(Mo.LEAVE_FULL_SCREEN))}handleVolumeChange(){var t;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(Mo.VOLUME_CHANGE,{muted:(t=this.element)==null?void 0:t.muted})}handleElementEvent(t){var o,a,l,d,h,y;if(this.mode===2)return;super.handleElementEvent(t);let S=t.type,L=this.isPictureInPicture(),V=this.isFullscreen(),H=t.isTrusted&&(L&&fg||V);if(S===JA.PLAYING&&H&&!this._isResettingSrcObject&&(this._log.warn("user resume in ".concat(V?"fullscreen":"pip")),this.emit(Mo.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),S===JA.PAUSE&&(H&&(this._log.warn("user pause in ".concat(V?"fullscreen":"pip")),this.emit(Mo.USER_PAUSE_IN_PIP_OR_FULL_SCREEN)),this.container&&!this.container.isConnected&&(this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(this.container.id)),OC(500).then(()=>{var lA;(lA=this.container)!=null&&lA.isConnected&&(this._pausedRetryCount=Gp,this._log.info("view container ".concat(this.container.id," is in dom, reset pausedRetryCount")))})),this._pausedRetryCount>0&&!Si()&&!this.isPausedByUserCall&&!H&&(this._log.info("[".concat(Gp-this._pausedRetryCount+1,"/").concat(Gp,"] ").concat(this.kind," player auto resume when paused")),this.doResume(),this._pausedRetryCount--),ng&&!H&&(this._interval=kr.run("timeout",()=>{this.element&&this._state==="PAUSED"&&!this.isPausedByUserCall&&this.doResume()},{delay:3e3})),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let lA=this.element.style.transform;S===JA.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=lA.replace("scaleX(-1)",""):S===JA.LEAVE_PICTURE_IN_PICTURE&&!lA.includes("scaleX")&&(this.element.style.transform="".concat(lA," scaleX(-1)"))}S===JA.RESIZE&&(this._preSize.height!==((o=this.element)==null?void 0:o.videoHeight)||this._preSize.width!==((a=this.element)==null?void 0:a.videoWidth))&&(this._log.info("video size changed to ".concat((l=this.element)==null?void 0:l.videoWidth,"x").concat((d=this.element)==null?void 0:d.videoHeight)),this._preSize.height=((h=this.element)==null?void 0:h.videoHeight)||0,this._preSize.width=((y=this.element)==null?void 0:y.videoWidth)||0,this.emit(Mo.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height})),S===JA.LEAVE_PICTURE_IN_PICTURE&&(this._log.warn("exit pip"),this.isPaused&&!this.isPausedByUserCall&&(this._log.warn("resume after exit pip"),this.doResume()),this.resetSrcObjectToReplay(),this.emit(Mo.LEAVE_PICTURE_IN_PICTURE)),S===JA.ENTER_PICTURE_IN_PICTURE&&this.emit(Mo.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){za&&Iy&&this.isPlayCalled&&this.element&&this.track&&!this.isPausedByUserCall&&(this._log.warn("reset srcObject to replay for android chromium"),this._isResettingSrcObject=!0,this.element.srcObject=new MediaStream([this.track]),this.element.play().catch(t=>{this._log.warn("play failed after reset srcObject",t)}).finally(()=>{this._isResettingSrcObject=!1}))}setCanvas(t){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;var a,l;this.canvas!==t&&((a=this.canvas)==null||a.remove(),t?.setAttribute("style",this.styleAttribute),this.canvas=t,this.mode=t?o:0,this.mode===2&&this.setTrack(t.captureStream().getVideoTracks()[0]),t?((l=this.element)==null||l.remove(),this._appendToWrapper(t)):this.element&&this._appendToWrapper(this.element))}setAttr(t){let o=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},t);o.style=Object.assign({width:"100%",height:"100%"},o.style),super.setAttr(o)}get mirror(){return this.viewMirror}setRect(t,o){this.elementToRender&&(this.elementToRender.style.width="".concat(t,"px"),this.elementToRender.style.height="".concat(o,"px"))}setViewMirror(t){this.elementToRender&&(this.elementToRender.style.transform=t?"scaleX(-1)":""),this.viewMirror=t}setObjectFit(t){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(t)),this.objectFit=t}setPoster(t){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return new Promise(a=>{if(!this.element||(this._log.info("setPoster",t.slice(0,10)),t===""?this.element.removeAttribute("poster"):this.element.poster=t,!o||!fg&&!gr))return a();if(t==="")return this.removePosterImg(),a();if(this.posterImg)return a();let l=document.createElement("img");l.src=t;let d=window.getComputedStyle(this.element),h=d.objectFit||this.objectFit,y=1;if(this._useWrapper){let S=parseInt(d.zIndex,10);isNaN(S)||(y=S+1)}l.style.cssText=this._useWrapper?"grid-area:1/1;z-index:".concat(y,";width:100%;height:100%;object-fit:").concat(h,";"):"position:absolute;top:0;left:0;width:100%;height:100%;object-fit:".concat(h,";"),l.onload=()=>XA(this,null,function*(){try{l.decode&&(yield l.decode()),this.container&&!this._useWrapper&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=l;let S=this._useWrapper?this._wrapper:this.container;S?.appendChild(l),Qv()&&$d<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(S){this._log.warn("decode poster image error",S)}return a()}),l.onerror=()=>(this._log.warn("load poster image error"),a())})}removePosterImg(){this.posterImg&&(Qv()&&$d<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),!this._useWrapper&&this.container&&!ze(this._originContainerPosition)&&this.container.style.position==="relative"&&(this.container.style.position=this._originContainerPosition),delete this.posterImg)}get hasPoster(){var t;return!!this.posterImg||!((t=this.element)==null||!t.getAttribute("poster"))}pause(){let t=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return XA(this,null,function*(){UI(QX.prototype,this,"pause").call(this),!this.isPictureInPicture()&&!this.hasPoster&&(Iy||t&&(gr||fg))&&(yield this.setPoster(this.getVideoFrame(),!0))})}resume(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return super.resume(t).then(()=>{var o;(this.posterImg||(o=this.element)!=null&&o.poster)&&this.setPoster("",!0)})}doResume(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this.isPaused&&t&&this.element&&this.track&&Iy&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;var o;this.isPictureInPicture()&&this.exitPictureInPicture().catch(a=>{}),this.isFullscreen()&&this.exitFullscreen().catch(a=>{}),this.element&&(this.element.removeEventListener(JA.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.removeEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.removeEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.removeEventListener("volumechange",this.handleVolumeChange)),this._isFirstFrameRenderEmitted=!1,super.stop(t),(o=this.canvas)==null||o.remove(),this.removePosterImg(),this._useWrapper&&this._cleanupWrapper()}_cleanupWrapper(){this._wrapper&&this._wrapper.children.length===0&&this._wrapper.remove(),this._wrapper=null}play(t){if(ze(t?.isLiveStream)||this.setLiveMode(t.isLiveStream),this.element){if(this.elementToRender&&this.container)if(this._useWrapper){let o=this._getOrCreateWrapper();this.elementToRender.parentElement!==o&&o.insertBefore(this.elementToRender,o.firstChild)}else this.elementToRender.parentElement!==this.container&&this.container.append(this.elementToRender)}else this.initializeElement();return this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(t){t!==this.track&&(this.unbindTrackEvents(),this.track=t,this.emit(Mo.MEDIA_TRACK_CHANGED,t),t!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([t]),this.element.remove()),this._appendToWrapper()))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let t=document.createElement("canvas");return t.width=this.element.videoWidth,t.height=this.element.videoHeight,t.getContext("2d").drawImage(this.element,0,0),t.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Am()&&this.element&&this._calculateTimeout<0){let t=0,o=null,a=(l,d)=>{this.stat.width=d.width,this.stat.height=d.height,o&&(this.stat.fps=Math.round((d.presentedFrames-o.presentedFrames)/(l-t)*1e3)),t=l,o=d,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var h;return(h=this.element)==null?void 0:h.requestVideoFrameCallback(a)},2e3))};this.element.requestVideoFrameCallback(a)}}catch(t){this._log.warn("init stat failed",t)}}enterFullscreen(){return XA(this,null,function*(){let t=this.elementToRender;if(!t)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");if(ng&&this.isPictureInPicture()){this._log.info("exit pip before entering fullscreen");try{yield this.exitPictureInPicture()}catch(o){this._log.warn("exit pip failed before fullscreen:",o)}}try{if(t.requestFullscreen)yield t.requestFullscreen();else if(t.webkitRequestFullscreen)yield t.webkitRequestFullscreen();else if(t.webkitEnterFullscreen)yield t.webkitEnterFullscreen();else if(t.mozRequestFullScreen)yield t.mozRequestFullScreen();else{if(!t.msRequestFullscreen)throw new Error("Fullscreen API not supported");yield t.msRequestFullscreen()}this._log.info("entered fullscreen mode")}catch(o){throw this._log.error("failed to enter fullscreen:",o),o}})}exitFullscreen(){return XA(this,null,function*(){try{if(!this.isFullscreen())return;if(document.exitFullscreen)yield document.exitFullscreen();else if(document.webkitExitFullscreen)yield document.webkitExitFullscreen();else if(document.mozCancelFullScreen)yield document.mozCancelFullScreen();else{if(!document.msExitFullscreen)throw new Error("Exit fullscreen API not supported");yield document.msExitFullscreen()}this._log.info("exited fullscreen mode")}catch(t){throw this._log.error("failed to exit fullscreen:",t),t}})}isFullscreen(){let t=this.elementToRender;return!!t&&(this.element&&this.element.webkitDisplayingFullscreen?!this.isPictureInPicture():(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===t)}toggleFullscreen(){return XA(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return XA(this,null,function*(){this.enterPIPPromise=this._enterPictureInPicture();try{return yield this.enterPIPPromise}finally{delete this.enterPIPPromise}})}_enterPictureInPicture(){return XA(this,null,function*(){try{if(!this.element)throw new Error("No video element available for pip");if(this.canvas&&this.mode!==1)throw new Error("pip is not supported for canvas-only mode");let{element:t}=this;if(t.requestPictureInPicture){this._log.info("requestPictureInPicture");let o=yield t.requestPictureInPicture();return this.pipWindow=o,this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),this._appendToWrapper(this.element)),o}if(t.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield t.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered pip mode (webkit)"),{};throw new Error("pip API not supported")}catch(t){throw this._log.error("failed to enter pip:",t.name,t.message),t}})}exitPictureInPicture(){return XA(this,null,function*(){var t;try{if(!this.isPictureInPicture())return;if(delete this.pipWindow,document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this.elementToRender===this.canvas&&((t=this.element)==null||t.remove(),this._pausedRetryCount=Gp,this._appendToWrapper(this.canvas)),this._log.info("exited pip mode");else{if(!this.element||!this.element.webkitSetPresentationMode)throw new Error("Exit pip API not supported or not in PiP mode");yield this.element.webkitSetPresentationMode("inline"),this._log.info("exited pip mode (webkit)")}}catch(o){throw this._log.error("failed to exit pip:",o),o}})}isPictureInPicture(){if(!this.element)return!1;let{element:t}=this;return document.pictureInPictureElement?document.pictureInPictureElement===t:!!t.webkitPresentationMode&&t.webkitPresentationMode==="picture-in-picture"}togglePictureInPicture(){return XA(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function Kg(A,t){return XA(this,null,function*(){if(!A.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield A.audioWorklet.addModule(t),pA.info("worklet addModule success")}catch(o){throw pA.info("worklet addModule catch error. ".concat(o.message)),o}})}typeof AudioContext<"u"?Bi=AudioContext:typeof webkitAudioContext<"u"?Bi=webkitAudioContext:typeof mozAudioContext<"u"&&(Bi=mozAudioContext);var Hs,pu=1500,eC=-1,im=0,cd=-1,YI=!1,s1=0,h_=-1,aL=-1;(function A(){try{if(Hs)return;(Hs=new Bi({sampleRate:48e3})).onstatechange=()=>{pA.info("context state: ".concat(Hs.state).concat(Hs.state!=="running"?" visibilityState: ".concat(document.visibilityState):"")),B_()},clearTimeout(eC)}catch(t){pA.error("initAudioContext failed: ".concat(t," typeof AudioContextClass: ").concat(typeof Bi)),eC=setTimeout(A,1e3)}})();var B_=()=>{Hs.state==="suspended"?(im=Oo(),cd===-1&&(cd=setTimeout(()=>{Hs.state==="suspended"&&(YI=!0,F.emit("155",{isSuspended:!0}))},pu)),gL(),document.addEventListener("click",B_)):Hs.state==="interrupted"?gL():(im&&(ri.addNumber({key:507800,value:Oo()-im,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),im=0),cd!==-1&&(clearTimeout(cd),cd=-1,YI&&(YI=!1,F.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",B_),document.removeEventListener("click",B_))},ij=0,oj=-1;function gL(){return new Promise((A,t)=>{if(Hs.state==="running")return A();Date.now()-ij<1e3?(clearTimeout(oj),oj=setTimeout(()=>{ij=Date.now(),Hs.resume().then(A,t)},1e3)):(clearTimeout(oj),ij=Date.now(),Hs.resume().then(A,t))}).catch(A=>{pA.warn("context resume failed: ".concat(A)),document.addEventListener("visibilitychange",B_)})}document.addEventListener("click",B_);var VI=A=>Hs,HI=class{constructor(A){this.name=A,Y(this,"node"),Y(this,"node2"),Y(this,"pre",new Set),Y(this,"next",new Set),Y(this,"context"),Y(this,"connectedNodes",new Set),Y(this,"nextInputChannelMap",new Map),Y(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(A){this._channelCount=A,this.setChannelCount(this.node,A),this.setChannelCount(this.node2,A),this.next.forEach(t=>t.channelCount=A)}setChannelCount(A,t){!A||A instanceof ScriptProcessorNode||(A.channelCountMode="explicit",A.channelCount=t||this.channelCount||1)}setContext(A){this.context=A,this.node&&A.addMixWeight()}removeContext(){var A;this.node&&((A=this.context)==null||A.reduceMixWeight()),delete this.context}replaceNode(A){var t;if(A!==this.node)try{this.node?this._disconnect():(t=this.context)==null||t.addMixWeight(),this.node=A,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(o){pA.error(o)}}setNode(A,t){var o;if(!this.node)try{(o=this.context)==null||o.addMixWeight(),this.node=A,this.setChannelCount(this.node),t&&(this.node2=t,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),ri.addSuccessEvent({key:502701})}catch(a){pA.error(a),ri.addFailedEvent({key:502701,error:a})}}deleteNode(){var A;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(A=this.context)==null||A.reduceMixWeight(),this.preNodeReconnect(),ri.addSuccessEvent({key:502702})}catch(t){pA.error(t),ri.addFailedEvent({key:502702,error:t})}}preNodeReconnect(){this.pre.forEach(A=>{A.node?A.reconnect():A.preNodeReconnect()})}connectNext(A){this.next.forEach(t=>{let o=this.nextInputChannelMap.get(t);A._connect(t.node,o)||t.connectNext(A)})}_connect(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return!(!this.node||!A)&&((this.node2||this.node).connect(A,0,t),this.connectedNodes.add(A),!0)}_disconnect(){this.connectedNodes.forEach(A=>{var t;return(t=this.node2||this.node)==null?void 0:t.disconnect(A)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return this.next.add(A),A.pre.add(this),this.nextInputChannelMap.set(A,t),A}},dtA=class extends HI{constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:256;super(),this.fftSize=A,Y(this,"dataArray",new Uint8Array(0))}setNode(A){A.fftSize=this.fftSize,this.dataArray=new Uint8Array(A.frequencyBinCount),super.setNode(A)}getByteTimeDomainData(){var A;return(A=this.node)==null||A.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var A;return(A=this.node)==null||A.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let A=this.getByteTimeDomainData(),t=0,o=0,a="M".concat(t,",").concat(o);for(let l=0;l0&&arguments[0]!==void 0?arguments[0]:1;this.mixWeight+=A,this.mixWeight-1==A+1>>1&&this.mixOnChange()}reduceMixWeight(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.addMixWeight(-A)}close(){this.inputs.forEach(A=>A.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},b5=new WeakMap;function r1(A){try{let t=b5.get(A);if(t)return t;let o=VI();if(A instanceof HTMLAudioElement)t=o.createMediaElementSource(A);else{if(!(A instanceof MediaStreamTrack))return A;t=o.createMediaStreamSource(new MediaStream([A]))}return b5.set(A,t),t}catch(t){if(!(gr&&t instanceof Error&&t.name==="NotSupportedError"))throw t;pA.warn(t)}}var a1=class lm{constructor(t){Y(this,"_volume",0),Y(this,"_volumeDb",0),Y(this,"_log"),Y(this,"_scriptProcessorNode",null),Y(this,"_audioWorkletNode",null),Y(this,"_interval",200),Y(this,"ready",this.preload());let{log:o}=t;this._log=o,F.on(rA.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-lm.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!lm.workletReady){let t='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(it+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';lm.workletReady=Kg(lm.audioContext,URL.createObjectURL(new Blob([t],{type:"application/javascript"})))}return lm.workletReady.then(()=>this.initAudioWorklet()).catch(t=>(this._log.error("volumeMeter preload error: ".concat(t)),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(lm.audioContext,"volume-meter");let t=!1;this._audioWorkletNode.port.onmessage=o=>{lm.lastMessageTime=Date.now(),this._volume=o.data.volume||0,this._volumeDb=o.data.volumeDb||0,!t&&o.data.cacheLen&&o.data.outputLen&&(this._log.warn("worklet play success"),t=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(t){this._log.error("volumeMeter init audio worklet error: ".concat(t)),ds.logFailedEvent({userId:this._log.userId,eventType:Wa.LOAD_WORKLET,error:t}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=VI().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=t=>{lm.lastMessageTime=Date.now();let o=t.inputBuffer.getChannelData(0),a=0;for(let l=0;l>2);A.copyTo(o,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:o},[o.buffer]),A.close()}}},g1=k5,htA=dc($l(),1),U5=A=>t=>t.deviceId===A,nj=class{constructor(A,t){Y(this,"kind"),Y(this,"type"),Y(this,"devices",[]),this.kind=A,this.type=t}update(A,t){let o=A.filter(a=>a.kind==="".concat(this.kind).concat(this.type.toLocaleLowerCase()));this.devices.length===1&&cL(this.devices[0])||t&&(o.forEach(a=>{if(a.deviceId&&!this.devices.find(U5(a.deviceId))){let l="".concat(this.kind).concat(this.type,"Added");pA.warn("".concat(l,": ").concat(JSON.stringify(a))),t.emit(l,a)}}),this.devices.forEach(a=>{if(a.deviceId&&!o.find(U5(a.deviceId))){let l="".concat(this.kind).concat(this.type,"Removed");pA.warn("".concat(l,": ").concat(JSON.stringify(a))),t.emit(l,a)}})),this.devices=o}hasDevice(A){return!!this.devices.find(t=>t.deviceId===A)}},BtA=class extends htA.EventEmitter{constructor(){super(),Y(this,"audioInputs",new nj(JA.AUDIO,"Input")),Y(this,"videoInputs",new nj(JA.VIDEO,"Input")),Y(this,"audioOutputs",new nj(JA.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||kr.run("interval",()=>{this.update()},{delay:1e4}))}init(){c1().then(A=>{this.audioInputs.update(A),this.videoInputs.update(A),this.audioOutputs.update(A)})}update(){return XA(this,arguments,function(){var A=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function*(){let o=yield c1(t);return A.audioInputs.update(o,A),A.videoInputs.update(o,A),A.audioOutputs.update(o,A),A}()})}hasBlueTooth(){var A;if(1e3*((A=VI())==null?void 0:A.outputLatency)>150)return!0;let t=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(o=>t.some(a=>o.label.toLowerCase().includes(a)))||this.audioInputs.devices.some(o=>t.some(a=>o.label.toLowerCase().includes(a)))}},Kc=u0||I0?null:new BtA;function cL(A){return A.deviceId===A.groupId&&A.groupId===""}function c1(){return XA(this,arguments,function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function*(){if(Qu()||!Yk())return[];let t=yield navigator.mediaDevices.enumerateDevices();if(A!==0){let o={audio:!1,video:!1};if(t.forEach(a=>{cL(a)&&(a.kind===JA.AUDIO_INPUT?o.audio=!0:a.kind===JA.VIDEO_INPUT&&(o.video=!0))}),A===2&&(o.audio=!1),A===1&&(o.video=!1),o.audio||o.video){let a;try{a=yield navigator.mediaDevices.getUserMedia(o),o.audio&&gL()}catch(l){pA.debug("capture before getDevices failed: ",l)}t=yield navigator.mediaDevices.enumerateDevices(),a?.getTracks().forEach(l=>l.stop())}}return t.map((o,a)=>{let l={kind:o.kind,deviceId:o.deviceId,groupId:o.groupId,label:o.label||"".concat(o.kind,"_").concat(a)};return o.deviceId.length>0&&sj.add("".concat(o.deviceId,"_").concat(o.kind)),o.getCapabilities&&(l.getCapabilities=()=>o.getCapabilities()),l})}()})}function om(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return Kc.update(A?1:0).then(t=>t.audioInputs.devices)}function nm(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return Kc.update(A?2:0).then(t=>t.videoInputs.devices)}var F5=!1;function Zv(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return XA(this,null,function*(){return(ng||fg)&&(A=!1),Kc.update(A?1:0).then(t=>t.audioOutputs.devices)})}var sj=new Set;function O5(A,t){return XA(this,null,function*(){let o=(yield om()).find(a=>a.deviceId===sv);return!t&&o?.groupId===A||o?.groupId===A&&o.label===t})}var l1,QtA=class extends N5{constructor(A){super(),this.log=A,Y(this,"volumeMeter"),Y(this,"volumeMeterAfter3A"),Y(this,"volumeDestination"),Y(this,"analyser",new dtA),this.volumeMeter=new L5({log:this.log}),this.volumeMeterAfter3A=new L5({log:this.log}),this.volumeDestination=new HI,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},rj=class pX extends HC{constructor(t){super(t,JA.AUDIO),Y(this,"_outputDeviceId"),Y(this,"_floatVolume",1),Y(this,"_destination"),Y(this,"pipeline"),Y(this,"volumeMeterMode","worklet"),Y(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=t.enableVolumeControlInIOS,this.mode=0,t.url&&(this.url=t.url),this.pipeline=new QtA(this._log)}setTrack(t){}get duration(){var t;return Math.floor(1e3*(((t=this.element)==null?void 0:t.duration)||0))}get currentTime(){var t;return Math.floor(1e3*(((t=this.element)==null?void 0:t.currentTime)||0))}set currentTime(t){this.element&&(this.element.currentTime=t/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(t){if((PI==="15.2"||PI==="15.3"||PI==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");this._log.info("audio player initializeElement");let o=l1||new Audio;o.setAttribute("autoplay","autoplay"),o.srcObject=this.getMediaStream(),o.muted=this.muted,this.url&&(o.crossOrigin="anonymous",o.src=this.url),this.element=o,this.setVolume(Ys(t)?t/100:this._floatVolume),o===l1&&(l1=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(Mo.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(t){return XA(this,null,function*(){if(this.track||this.url){try{!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(t?.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(VI().createAnalyser()),function(){XA(this,null,function*(){try{F5||(F5=!0,pA.info("speakers:".concat((yield Zv()).map(o=>" ".concat(o.deviceId.slice(0,8),": ").concat(o.label)))))}catch{}})}()}catch(o){throw this._log.warn("audio play error: ".concat(o)),uy(PI,"18.7",!0)&&this.bindAutoPlayEvent(),o}return UI(pX.prototype,this,"play").call(this)}})}stop(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.pipeline.destroy(),super.stop(t)}setVolume(t){this._floatVolume=t,this.element&&(this.element.volume=t)}setSinkId(t){return XA(this,null,function*(){var o,a;this._outputDeviceId!==t&&(this._outputDeviceId=t),this.element&&this.element.sinkId!==t&&(yield(a=(o=this.element).setSinkId)==null?void 0:a.call(o,t))})}get useDestination(){return!!this.pipeline.stream}setLoop(t){this.element&&(this.element.loop=t)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},ptA=class extends rj{setTrack(A){this.track!==A&&(this.unbindTrackEvents(),this.track=A,this.emit(Mo.MEDIA_TRACK_CHANGED,A),A&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([A]))))}},P5=class extends rj{constructor(A){super(A),Y(this,"_sourceElement"),Y(this,"_output",new HI),this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(VI().destination)}write(A){this.pipeline.volumeMeter.write(A)}setTrack(A){var t,o,a;((o=(t=this.element)==null?void 0:t.error)==null?void 0:o.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==A&&(this.unbindTrackEvents(),this.track=A,this.emit(Mo.MEDIA_TRACK_CHANGED,A),A?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([A]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([A])),this.pipeline.source.channelCount=((a=A.getSettings())==null?void 0:a.channelCount)||1,this.pipeline.replaceSource(A)):this.pipeline.source.deleteNode())}setVolume(A){var t;let o=A<=1&&!Qv();if(this._floatVolume!==A||!(o&&((t=this.element)==null?void 0:t.volume)===A||!o&&this.pipeline.volume===A))if(this._floatVolume=A,this.useDestination)this.pipeline.setVolume(A),this._log.info("set pipeline volume: ".concat(A));else if(o)this.element?(this._log.info("set element volume: ".concat(A)),this.element.volume=A):this._log.info("set element volume: no element");else{if(Qv()){if(!this.enableVolumeControlInIOS)return;(function(){if(!ng||aL!==-1)return;let a=()=>{Oo()-s1<500||(Hs&&Hs.state==="running"&&Hs.currentTime===h_&&(pA.warn("context is fake running, auto resume"),Hs.suspend().catch(l=>{pA.warn("context suspend failed: ".concat(l))})),h_=Hs.currentTime,s1=Oo())};aL=setInterval(()=>{a()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&a()})})()}if(gr&&!this.pipeline.source.node)return void this._log.warn("set pipeline volume failed: no source node");this._log.info("start set pipeline volume: ".concat(A)),this.pipeline.setVolume(A),this.element&&!this._sourceElement&&(this._destination||(this._destination=VI().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),Vs(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(a=>{this.emit(Mo.AUTOPLAY_FAILED,a)}))}}stop(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.pipeline.destroy();let t=this._sourceElement||this.element;t&&Hp&&(l1=t),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(A)}},aj=class extends gs{constructor(A){let{userId:t,sdkAppId:o,mediaType:a,room:l,PlayerClass:d=a===1?P5:bo}=A;var h;super(),Y(this,"id",YA()),Y(this,"userId",""),Y(this,"isRemote"),Y(this,"mediaType"),Y(this,"room"),Y(this,"user"),Y(this,"_log"),Y(this,"_inputTrack"),Y(this,"_outputTrack"),Y(this,"isPlayCalled"),Y(this,"container",null),Y(this,"player"),Y(this,"subVideoPlayerMap"),Y(this,"muted",!1),Y(this,"abortCtrl"),Y(this,"objectFit","cover"),Y(this,"mirror"),Y(this,"rotation"),Y(this,"isScreen",!1),Y(this,"manager"),Y(this,"trackSettings"),Y(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=a,this._log=pA.createLogger({parent:l?.getLogger(),id:"".concat(this.kind[0],"t"),userId:(h=l||this.room)==null?void 0:h.userId,remoteUserId:this instanceof hL?void 0:this.userId,sdkAppId:o,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof hL}),this.player=new d({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:l?.enableVolumeControlInIOS}),this.player.on(Mo.PLAYER_STATE_CHANGED,y=>{if(F.emit(rA.PLAYER_STATE_CHANGED,Di({track:this},y)),this.emit("player-state-changed",y),y.state==="PLAYING"&&this.room){let S=!0;for(let{remoteAudioTrack:L,remoteVideoTrack:V,remoteAuxiliaryTrack:H}of[...this.room.remotePublishedUserMap.values()])if(L.isAvailable&&!L.player.isPlaying||V.isAvailable&&!V.player.isPlaying||H.isAvailable&&!H.player.isPlaying){S=!1;break}S&&Si()&&qc&&qc.deleteDialog()}}),this.kind===JA.VIDEO&&(this.player.on(Mo.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(Mo.LOADED_DATA),F.emit(rA.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Mo.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(Mo.LOADED_META_DATA)}),this.player.on(Mo.MEDIA_TRACK_CHANGED,y=>{var S;(S=this.subVideoPlayerMap)==null||S.forEach(L=>L.setTrack(y))}),this.player.on(Mo.RESIZE,y=>{this.emitFirstVideoFrameEvent(Mo.RESIZE),this.emit("video-size-changed",Di({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},y))}),this.player.on(Mo.FIRST_FRAME_RENDER,y=>{this.emit("first-frame-render",So(Di({},y),{streamType:this.streamType,userId:this.isRemote?this.userId:""}))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(Mo.ERROR,this.onPlayerError.bind(this)),this.player.on(Mo.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||pA}get kind(){return this.mediaType===1?JA.AUDIO:JA.VIDEO}get isAudio(){return this.kind===JA.AUDIO}get strMediaType(){return this.mediaType===4?JA.VIDEO:this.mediaType===2?JA.SCREEN:JA.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}play(A,t){return XA(this,null,function*(){let o=ka(A)?A[0]:A;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(t))),t&&!ze(t.muted)&&this.setPlayerMute(t.muted),t&&!ze(t.objectFit)&&(this.objectFit=t.objectFit),void(this.player instanceof bo&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(ka(A)&&A.length>=1&&this.container&&A.includes(this.container)&&this.container.contains(this.player.elementToRender)?(A.splice(A.indexOf(this.container),1),A.unshift(this.container)):(this.container=o,this.player.setContainer(o))),ka(A)&&A.length>=1&&(yield this.playSubContainer(A.slice(1),t))));if(t&&!ze(t.muted)?this.setPlayerMute(t.muted):(!this.isRemote||this.kind===JA.VIDEO)&&this.setPlayerMute(!0),t&&!ze(t.objectFit)&&(this.objectFit=t.objectFit),this.player instanceof bo&&(ze(t?.isLiveStream)||this.player.setLiveMode(t.isLiveStream),this.player.setObjectFit(this.objectFit),t&&!ze(t.poster)&&this.player.setPoster(t.poster)),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof bo&&this.player.setContainer(o)),F.emit(rA.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info("play with options: ".concat(JSON.stringify(t)));try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(t),ka(A)&&A.length>1&&(yield this.playSubContainer(A.slice(1),t))}catch(a){throw this.handleAutoPlayFailed(a),a}}else this.log.info("play has not mediaTrack, abort")})}setMirror(A,t){if(this.isScreen||this.kind!==JA.VIDEO||ze(A)||A===this.mirror)return;this.mirror=A;let o=this.player;t&&(o=t);let a=this.manager;if(br(this.mirror))return o.setViewMirror(this.mirror),void(!this.isRemote&&a&&(a.mirror=!1));switch(this.mirror){case"view":a&&(a.mirror=!1),o.setViewMirror(!0);break;case"publish":a&&(a.mirror=!0),o.setViewMirror(!0);break;case"both":a&&(a.mirror=!0),o.setViewMirror(!1)}}playSubContainer(A,t){return XA(this,null,function*(){if(!this._outputTrack||this.kind===JA.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((a,l)=>{var d;A.find(h=>l===h)||(a.stop(),(d=this.subVideoPlayerMap)==null||d.delete(l))});for(let[a,l]of A.entries()){let d=this.subVideoPlayerMap.get(l);d?t&&(ze(t.objectFit)||d.setObjectFit(t.objectFit)):this.subVideoPlayerMap.set(l,new bo({id:this.userId||this.id,track:this.playerMediaTrack,container:l,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(a+1)})}))}let o=[...this.subVideoPlayerMap.values()];for(let a of o)a.setViewMirror(this.player.mirror),yield a.play()})}setAudioOutput(A){return this.player.setSinkId(A)}setAudioVolume(A){this.player.setVolume(A)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var A;return((A=this.player)==null?void 0:A.getInternalAudioLevel())||0}stop(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(ck(this)&&!A?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(t=>{t.stop()}),this.container=null)}resume(){return XA(this,null,function*(){var A;this.isPlayCalled&&(yield(A=this.player)==null?void 0:A.resume())})}close(){this._toInitState(),this.log.info("close"),this.isPlayCalled&&this.stop(!0)}_toInitState(){}setMute(A){this.muted=A,this._inputTrack&&(this._inputTrack.enabled=!A),this._outputTrack&&(this._outputTrack.enabled=!A),this.emit(A?"mute":"unmute",this),F.emit(A?rA.TRACK_MUTED:rA.TRACK_UNMUTED,{track:this})}setPlayerMute(A){this.player.setMuted(A)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(A){gd(A,A).add(JA.MUTE,this.onTrackMuted).add(JA.UNMUTE,this.onTrackUnmuted).add(JA.ENDED,this.onTrackEnded),A.muted&&this.onTrackMuted(),A.readyState===JA.ENDED&&this.onTrackEnded()}uninstallTrackEvent(A){Vs(A)}setInputMediaStreamTrack(A){var t;let o=this._inputTrack;if(A!==o)return this._inputTrack=A,this.trackSettings=(t=A.getSettings)==null?void 0:t.call(A),A.enabled=!this.muted,o&&this.uninstallTrackEvent(o),this.installTrackEvent(A),this.emit("input-media-track-changed",A||null,o||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(A)}setOutputMediaStreamTrack(A){var t;let o=this._outputTrack;this instanceof QQ&&Lp(o)||A!==o&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",A.label):this.log.info("setOutputMediaStreamTrack",(t=A.getSettings)==null?void 0:t.call(A).deviceId,A.label),this._outputTrack=A,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!A),this.emit("output-media-track-changed",A))}setMediaType(A){this.mediaType=A}updatePlayingState(A){var t,o;if(this.isPlayCalled){if(A){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch(a=>this.handleAutoPlayFailed(a)),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return ck(this)&&this.isAudio&&(t=this.user)!=null&&t.muteState.hasAudio&&(o=this.user)!=null&&o.muteState.audioMuted?void 0:(this.player.stop(ck(this)?this.jitterBufferDelay:0),void this.log.info("playing state updated, stop ".concat(this.kind)))}this.log.debug("updatePlayingState abort ".concat(this.isPlayCalled," ").concat(A," ").concat(this.player.isStopped))}handleAutoPlayFailed(A){return XA(this,null,function*(){var t;this.log.warn("handleAutoPlayFailed",A);let o=()=>{this.resume().then(()=>{document.removeEventListener("click",o,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((xp||sQ)&&(yield OC(100),(t=this.player)!=null&&t.isPlaying))return;JC()}else document.addEventListener("click",o,!0);F.once(rA.LOCAL_TRACK_CAPTURE_SUCCESS,a=>{let{track:l}=a;l.kind==="audio"&&Si()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&o()}),this.emit("error",A)})}getVideoFrame(){return this.player instanceof bo?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(A){var t,o,a;if(this.isFirstVideoFrameEmitted)return;let l=(t=this.mediaTrack)==null?void 0:t.getSettings(),d=l?.width||((o=this.player.element)==null?void 0:o.videoWidth)||0,h=l?.height||((a=this.player.element)==null?void 0:a.videoHeight)||0;A===Mo.RESIZE&&!d&&!h||A===Mo.LOADED_META_DATA&&!d&&!h||(A===Mo.LOADED_DATA&&!d&&!h&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,iQ(this.rotation)&&([d,h]=[h,d]),this.emit("first-video-frame",{width:d,height:h,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn("".concat(this.kind," track is unable to provide media output"))}onTrackUnmuted(){this._log.info("".concat(this.kind," track is able to provide media output"))}onTrackEnded(){this._log.warn("".concat(this.kind," track ended"))}};Qi([hc([],gs.INIT,{sync:!0})],aj.prototype,"_toInitState");var mtA=Object.prototype.hasOwnProperty,sm=function(A){if(A==null)return!0;if(typeof A=="boolean")return!1;if(typeof A=="number")return A===0;if(typeof A=="string"||typeof A=="function"||Array.isArray(A))return A.length===0;if(A instanceof Error)return A.message==="";if(uE(A))switch(Object.prototype.toString.call(A)){case"[object File]":case"[object Map]":case"[object Set]":return A.size===0;case"[object Object]":for(let t in A)if(mtA.call(A,t))return!1;return!0}return!1},ftA=Bv({retryFunction:function(A){return XA(this,null,function*(){let t=function(d){return{audio:ytA(d),video:DtA(d)}}(A);pA.info("getUserMedia with constraints: ".concat(JSON.stringify(t)));let o=[],a=[],l=["label","deviceId","groupId"];if(t.audio&&(o=yield om(),pA.info("microphones: ".concat(Xd(o.map(d=>So(Di({},d),{groupId:d.groupId.substring(0,8)})),{keysToInclude:l})))),t.video&&(a=yield nm(),pA.info("cameras: ".concat(Xd(a,{keysToInclude:l}))),!br(t.video)&&t.video.facingMode==="user"&&!t.video.deviceId)){let d=a.filter(h=>!h.label.includes("infrared")).find(h=>h.label.includes("facing front"));d&&(t.video.deviceId=d.deviceId,pA.info("exclude infrared camera: ".concat(JSON.stringify(t))))}try{let d=yield navigator.mediaDevices.getUserMedia(t);return $2&&d.getTracks().forEach(h=>{var y;let S=h.getCapabilities();pA.info("".concat(h.kind," capabilities: ").concat(Xd(S,{keysToInclude:Jb}))),!ze(A.echoCancellation)&&((y=S.echoCancellation)==null?void 0:y.indexOf(A.echoCancellation))===-1&&pA.warn("Invalid argument for 'echoCancellation'. Expected one of [".concat(JSON.stringify(S.echoCancellation),"], but received '").concat(A.echoCancellation,"'"))}),t.audio&&gL(),d}catch(d){let{message:h}=d;throw d.name==="NotFoundError"&&(A.video&&a&&a.length===0&&(h=sn({key:Go.CAMERA_NOT_FOUND})),A.audio&&o&&o.length===0&&(h=sn({key:Go.MICROPHONE_NOT_FOUND}))),new li({code:mt.INITIALIZE_FAILED,name:d.name,message:h,constraint:d.constraint})}})},settings:{retries:3,timeout:500},onError:A=>{let{error:t,retry:o,reject:a,retryFuncArgs:l,retriedCount:d}=A,h=d+1;t.name==="NotReadableError"||t.name==="OverconstrainedError"||t.name==="AbortError"?(h===1?(l[0].video&&(l[0].maxResolution=!1,(!fg||l[0].width*l[0].height<=2073600)&&l[0].frameRate&&(l[0].frameRate=l[0].frameRate>10?10:5)),l[0].retryWhenExactFailed&&l[0].useExactDeviceId&&(l[0].useExactDeviceId=!1)):h===2?l[0].useDeviceIdOnly=!0:h===3&&!l[0].useExactDeviceId&&(l[0].useTrueAsConstraint=!0),o()):a(t),l[0].microphoneId&&x5(l[0].microphoneId,!1),l[0].cameraId&&x5(l[0].cameraId,!0)},onRetrying:A=>{pA.warn("getUserMedia NotReadableError observed, retrying [".concat(A,"/3]"))},onRetryFailed:A=>{ds.logFailedEvent({eventType:Wa.GET_USER_MEDIA_RETRY,error:A})},onRetrySuccess:A=>{ds.logSuccessEvent({eventType:Wa.GET_USER_MEDIA_RETRY}),ds.uploadEvent({log:"stat-".concat(Wa.GET_USER_MEDIA_RETRY,"-success-").concat(A)})}});function x5(A,t){return XA(this,null,function*(){let o=(t?yield nm():yield om()).find(a=>a.deviceId===A);o&&ba(o.getCapabilities)&&pA.warn(Xd(o.getCapabilities(),{keysToInclude:Jb}))})}function ytA(A){if(!A.audio)return!1;if(A.useTrueAsConstraint)return!0;let t={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:A.sampleRate};return!sm(A.microphoneId)&&(t.deviceId=A.useExactDeviceId?{exact:A.microphoneId}:A.microphoneId,A.useDeviceIdOnly)?t:(Ys(A.channelCount)&&(t.channelCount=A.channelCount),(br(A.echoCancellation)||A.echoCancellation==="remote-only"||A.echoCancellation==="all")&&(t.echoCancellation=A.echoCancellation),br(A.noiseSuppression)&&!A.noiseSuppression&&(t.noiseSuppression=!1),br(A.autoGainControl)&&!A.autoGainControl&&(t.autoGainControl=!1),!!sm(t)||t)}function DtA(A){if(!A.video)return!1;if(A.useTrueAsConstraint)return!0;let{maxResolution:t=!0}=A,o={};return A.cameraId?o.deviceId=A.useExactDeviceId?{exact:A.cameraId}:A.cameraId:A.facingMode&&(o.facingMode=A.facingMode),A.useDeviceIdOnly&&!sm(o)?o:(A.width&&(o.width={ideal:A.width},t&&!gr&&(o.width.max=A.width)),A.height&&(o.height={ideal:A.height},t&&!gr&&(o.height.max=A.height)),gr&&rQ&&A.width&&A.height&&A.width*A.height<101376&&(o.width=A.width,o.height=A.height),A.frameRate&&(o.frameRate=A.frameRate),!!sm(o)||o)}var StA=ftA;function Y5(A){return Xr((t,o)=>function(){for(var a=arguments.length,l=new Array(a),d=0;dfunction(){for(var a=arguments.length,l=new Array(a),d=0;dfunction(){for(var a=arguments.length,l=new Array(a),d=0;d{let A=!1,t=document.visibilityState;return()=>{document.visibilityState!==t&&pA.info("visibility change: ".concat(document.visibilityState)),!A&&(document.addEventListener("visibilitychange",()=>{pA.info("visibility change: ".concat(document.visibilityState)),t=document.visibilityState}),A=!0)}})(),MtA=0,H5=class{constructor(A){Y(this,"log"),Y(this,"isRunning",!1),Y(this,"queue",[]);let t="fq".concat(++MtA);A&&(t+="|".concat(A)),this.log=pA.createLogger({id:t})}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(A){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var o,a;let l=Di({},A),d=new Promise((h,y)=>{l.resolve=h,l.reject=y});return l.promise=d,t?this.length<=1?this.queue.push(l):(a=(o=this.lastQueueItem)==null?void 0:o.promise)==null||a.then(l.resolve,l.reject):this.queue.push(l),this.log.debug("push ".concat(this.length),A.funcName,A.args),this.isRunning||this.callNext(),d}shift(){let A=this.queue.shift();return this.log.debug("shift ".concat(this.length),A?.funcName,A?.args),A}callNext(){if(this.isRunning||this.length===0)return;let{fn:A,args:t,context:o,resolve:a,reject:l,funcName:d}=this.queue[0];this.log.debug("callNext",this.length,d,t),this.isRunning=!0,A.apply(o,t).then(a,l).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},I1=new WeakMap,u1=new WeakMap;function lL(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return function(t,o,a){let l=a.value;return a.value=function(){let d=I1.get(this)||new H5;for(var h=arguments.length,y=new Array(h),S=0;SS.push(lA)),(y=u1.get(this))==null||y.forEach(lA=>lA?.queue.forEach(hA=>S.push(hA))),S.forEach(lA=>{lA.reject(new li({code:mt.API_CALL_ABORTED,message:A}))}),I1.delete(this),u1.delete(this),l.apply(this,V)},a}}function Ry(A,t){return function(o,a,l){let d=l.value,h=y=>A(...y);return l.value=function(){for(var y=arguments.length,S=new Array(y),L=0;Lfunction(){let l=A;try{for(var d=arguments.length,h=new Array(d),y=0;y(t?ri.addSuccessEvent({key:l,cost:Oo()-L}):ri.addSuccessEvent({key:l}),V)).catch(V=>{throw ri.addFailedEvent({key:l,error:V}),V}):(ri.addSuccessEvent({key:l}),S)}catch(S){throw ri.addFailedEvent({key:l,error:S}),S}})}var q5={};function sg(){}Wh(q5,{Events:()=>Bc,Inspect:()=>_y,LastSink:()=>E1,Sink:()=>Zn,Subscribe:()=>d1,TimeoutError:()=>W5,audit:()=>IiA,bindCallback:()=>WtA,bindNodeCallback:()=>ztA,buffer:()=>UtA,bufferCount:()=>LtA,bufferTime:()=>kiA,call:()=>K5,catchError:()=>Ez,combineLatest:()=>X5,concat:()=>TtA,concatMap:()=>SiA,concatMapTo:()=>viA,count:()=>$tA,create:()=>mr,debounce:()=>EiA,debounceTime:()=>diA,defer:()=>$5,delay:()=>LiA,deliver:()=>Xn,dispose:()=>gj,elementAt:()=>CiA,empty:()=>Ej,every:()=>miA,exhaustMap:()=>TiA,exhaustMapTo:()=>NiA,expand:()=>FiA,filter:()=>$v,find:()=>hiA,findIndex:()=>BiA,first:()=>QiA,fromAnimationFrame:()=>KtA,fromArray:()=>xtA,fromEvent:()=>Ea,fromEventPattern:()=>YtA,fromFetch:()=>VtA,fromIterable:()=>HtA,fromPromise:()=>iz,fromReadableStream:()=>qtA,fromReader:()=>JtA,groupBy:()=>GiA,identity:()=>RtA,ignoreElements:()=>iiA,iif:()=>GtA,inspect:()=>j5,interval:()=>tz,last:()=>piA,map:()=>Cj,mapTo:()=>yiA,max:()=>AiA,merge:()=>cj,mergeMap:()=>RiA,mergeMapTo:()=>wiA,min:()=>eiA,never:()=>ZtA,nothing:()=>sg,of:()=>PtA,pairwise:()=>fiA,pipe:()=>Ma,race:()=>Z5,range:()=>jtA,reduce:()=>oz,retry:()=>YiA,scan:()=>rz,setAsapScheduler:()=>OtA,share:()=>IL,shareReplay:()=>NtA,skip:()=>siA,skipUntil:()=>riA,skipWhile:()=>dj,startWith:()=>lj,subject:()=>BQ,subscribe:()=>Dl,sum:()=>tiA,switchMap:()=>h1,switchMapTo:()=>Q1,take:()=>p_,takeLast:()=>niA,takeUntil:()=>CE,takeWhile:()=>oiA,tap:()=>hj,throttle:()=>ciA,throwError:()=>XtA,timeInterval:()=>biA,timeout:()=>xiA,timer:()=>uj,toPromise:()=>OiA,toReadableStream:()=>PiA,withLatestFrom:()=>ktA,zip:()=>btA});var K5=A=>A(),RtA=A=>A;function gj(){this.dispose()}var j5=()=>typeof __FASTRX_DEVTOOLS__<"u",wtA=1,_y=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(A){let t=new _tA(A,this,this.streamId++);return Bc.subscribe({id:this.id,end:!1},{nodeId:t.sourceId,streamId:t.id}),this(t),t}},E1=class{constructor(){this.defers=new Set,this.disposed=!1}next(A){}complete(){this.dispose()}error(A){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=sg,this.error=sg,this.next=sg,this.dispose=sg,this.subscribe=sg,this.doDefer()}subscribe(A){return A instanceof _y?A.subscribe(this):A(this),this}get bindSubscribe(){return A=>this.subscribe(A)}doDefer(){this.defers.forEach(K5),this.defers.clear()}defer(A){this.defers.add(A)}removeDefer(A){this.defers.delete(A)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},Zn=class extends E1{constructor(A){super(),this.sink=A,A.defer(this.bindDispose)}next(A){this.sink.next(A)}complete(){this.sink.complete()}error(A){this.sink.error(A)}},d1=class extends E1{constructor(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:sg,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:sg,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:sg;if(super(),this._next=t,this._error=o,this._complete=a,this.then=sg,A instanceof _y){let l={toString:()=>"subscribe",id:0,source:A};this.defer(()=>{Bc.defer(l,0)}),Bc.create(l),Bc.pipe(l),this.sourceId=l.id,this.subscribe(A),Bc.subscribe({id:l.id,end:!0}),t==sg?this._next=d=>Bc.next(l,0,d):this.next=d=>{Bc.next(l,0,d),t(d)},a==sg?this._complete=()=>Bc.complete(l,0):this.complete=()=>{this.dispose(),Bc.complete(l,0),a()},o==sg?this._error=d=>Bc.complete(l,0,d):this.error=d=>{this.dispose(),Bc.complete(l,0,d),o(d)}}else this.subscribe(A)}next(A){this._next(A)}complete(){this.dispose(),this._complete()}error(A){this.dispose(),this._error(A)}};function Ma(A){for(var t=arguments.length,o=new Array(t>1?t-1:0),a=1;ad(l),A)}function mr(A,t,o){if(j5()){let a=Object.defineProperties(Object.setPrototypeOf(A,_y.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:t,writable:!0,configurable:!0},args:{value:o,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Bc.create(a);for(let l=0;l{if(d instanceof _y){let h=mr(y=>{let S=new A(y,...a);S.sourceId=h.id,S.subscribe(d)},t,arguments);return h.source=d,Bc.pipe(h),h}return h=>d(new A(h,...a))}}}function Ty(A,t){window.postMessage({source:"fastrx-devtools-backend",payload:{event:A,payload:t}})}var _tA=class extends Zn{constructor(A,t,o){super(A),this.source=t,this.id=o,this.sourceId=A.sourceId,this.defer(()=>{Bc.defer(this.source,this.id)})}next(A){Bc.next(this.source,this.id,A),this.sink.next(A)}complete(){Bc.complete(this.source,this.id),this.sink.complete()}error(A){Bc.complete(this.source,this.id,A),this.sink.error(A)}},Bc={addSource(A,t){Ty("addSource",{id:A.id,name:A.toString(),source:{id:t.id,name:t.toString()}})},next(A,t,o){Ty("next",{id:A.id,streamId:t,data:o&&o.toString()})},subscribe(A,t){let{id:o,end:a}=A;Ty("subscribe",{id:o,end:a,sink:{nodeId:t&&t.nodeId,streamId:t&&t.streamId}})},complete(A,t,o){Ty("complete",{id:A.id,streamId:t,err:o?o.toString():null})},defer(A,t){Ty("defer",{id:A.id,streamId:t})},pipe(A){Ty("pipe",{name:A.toString(),id:A.id,source:{id:A.source.id,name:A.source.toString()}})},update(A){Ty("update",{id:A.id,name:A.toString()})},create(A){A.id||(A.id=wtA++),Ty("create",{name:A.toString(),id:A.id})}},W5=class extends Error{constructor(A){super("timeout after ".concat(A,"ms")),this.timeout=A}},z5=class extends E1{constructor(A){super(),this.source=A,this.sinks=new Set}add(A){A.defer(()=>this.remove(A)),this.sinks.add(A).size===1&&(this.reset(),this.subscribe(this.source))}remove(A){this.sinks.delete(A),this.sinks.size===0&&this.dispose()}next(A){this.sinks.forEach(t=>t.next(A))}complete(){this.sinks.forEach(A=>A.complete()),this.sinks.clear()}error(A){this.sinks.forEach(t=>t.error(A)),this.sinks.clear()}};function IL(){return A=>{let t=new z5(A);if(A instanceof _y){let o=mr(a=>{t.add(a)},"share",arguments);return t.sourceId=o.id,o.source=A,Bc.pipe(o),o}return mr(t.add.bind(t),"share",arguments)}}function cj(){for(var A=arguments.length,t=new Array(A),o=0;o{let l=new Zn(a),d=t.length;l.complete=()=>{--d===0&&a.complete()},t.forEach(l.bindSubscribe)},"merge",arguments)}function Z5(){for(var A=arguments.length,t=new Array(A),o=0;o{let l=new Map;t.forEach(d=>{let h=new Zn(a);l.set(d,h),h.complete=()=>{l.delete(d),l.size===0?a.complete():h.dispose()},h.next=y=>{l.delete(d),l.forEach(S=>S.dispose()),h.resetNext(),h.resetComplete(),h.next(y)}}),t.forEach(d=>l.get(d).subscribe(d))},"race",arguments)}function TtA(){for(var A=arguments.length,t=new Array(A),o=0;o{let l=0,d=t.length,h=new Zn(a);h.complete=()=>{l{let o=new z5(t),a=[];return o.next=function(l){a.push(l),a.length>A&&a.shift(),this.sinks.forEach(d=>d.next(l))},mr(l=>{l.defer(()=>o.remove(l)),a.forEach(d=>l.next(d)),o.add(l)},"shareReplay",arguments)}}function GtA(A,t,o){return mr(a=>A()?t(a):o(a),"iif",arguments)}function X5(){for(var A=arguments.length,t=new Array(A),o=0;o{let l=t.length,d=l,h=l,y=new Array(l),S=()=>{--h===0&&a.complete()};t.forEach((L,V)=>{let H=new Zn(a);H.next=lA=>{d--,H.next=hA=>{y[V]=hA,d===0&&a.next(y)},H.next(lA)},H.complete=S,H.subscribe(L)})},"combineLatest",arguments)}function btA(){for(var A=arguments.length,t=new Array(A),o=0;o{let l=t.length,d=l,h=new Array(l),y=()=>{--d===0&&a.complete()};t.forEach((S,L)=>{let V=new Zn(a),H=[];h[L]=H,V.next=lA=>{H.push(lA),h.every(hA=>hA.length)&&a.next(h.map(hA=>hA.shift()))},V.complete=y,V.subscribe(S)})},"zip",arguments)}function lj(){for(var A=arguments.length,t=new Array(A),o=0;omr(function(l){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,h=arguments.length>2&&arguments[2]!==void 0?arguments[2]:t.length;for(;d1?o-1:0),l=1;lthis.buffer=d,t.complete=sg,t.subscribe(X5(...a))}next(A){this.buffer&&this.sink.next([A,...this.buffer])}},"withLatestFrom"),LtA=Xn(class extends Zn{constructor(A,t,o){super(A),this.bufferSize=t,this.startBufferEvery=o,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(A){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(t=>{t.push(A)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(A),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(A=>this.sink.next(A)),super.complete()}},"bufferCount"),UtA=Xn(class extends Zn{constructor(A,t){super(A),this.buffer=[];let o=new Zn(A);o.next=a=>{A.next(this.buffer),this.buffer=[]},o.complete=sg,o.subscribe(t)}next(A){this.buffer.push(A)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),FtA=function(A,t,o,a){return new(o||(o=Promise))(function(l,d){function h(L){try{S(a.next(L))}catch(V){d(V)}}function y(L){try{S(a.throw(L))}catch(V){d(V)}}function S(L){L.done?l(L.value):function(V){return V instanceof o?V:new o(function(H){H(V)})}(L.value).then(h,y)}S((a=a.apply(A,[])).next())})};function BQ(A){let t=arguments,o=IL()(mr(a=>{o.next=l=>a.next(l),o.complete=()=>a.complete(),o.error=l=>a.error(l),A&&a.subscribe(A)},"subject",t));return o.next=sg,o.complete=sg,o.error=sg,o}function $5(A){return mr(t=>t.subscribe(A()),"defer",arguments)}var Q_={promise:A=>{Promise.resolve().then(A)},setImmediate:typeof setImmediate<"u"?A=>setImmediate(A):null,setTimeout:A=>setTimeout(A,0)},Ij=typeof Promise<"u"?Q_.promise:Q_.setImmediate?Q_.setImmediate:Q_.setTimeout,Az=A=>t=>{Ij(()=>A(t))},OtA=A=>{typeof A=="function"?Ij=A:Q_[A]&&(Ij=Q_[A])},ez=A=>Az(t=>{for(let o=0;!t.disposed&&o{let o=0,a=setInterval(()=>t.next(o++),A);return t.defer(()=>{clearInterval(a)}),"interval"},"interval",arguments)}function uj(A,t){return mr(o=>{let a=0,l=setTimeout(()=>{if(o.removeDefer(d),o.next(a++),t){let h=setInterval(()=>o.next(a++),t);o.defer(()=>{clearInterval(h)})}else o.complete()},A),d=()=>clearTimeout(l);o.defer(d)},"timer",arguments)}function C1(A,t){return o=>{let a=l=>o.next(l);o.defer(()=>t(a)),A(a)}}function YtA(A,t){return mr(C1(A,t),"fromEventPattern",arguments)}function Ea(A,t){if("on"in A&&"off"in A)return mr(C1(o=>A.on(t,o),o=>A.off(t,o)),"fromEvent",arguments);if("addListener"in A&&"removeListener"in A)return mr(C1(o=>A.addListener(t,o),o=>A.removeListener(t,o)),"fromEvent",arguments);if("addEventListener"in A)return mr(C1(o=>A.addEventListener(t,o),o=>A.removeEventListener(t,o)),"fromEvent",arguments);throw"target is not a EventDispachter"}function iz(A){return mr(t=>{A.then(o=>{t.next(o),t.complete()},t.error.bind(t))},"fromPromise",arguments)}function VtA(A,t){return mr($5(()=>iz(fetch(A,t))),"fromFetch",arguments)}function HtA(A){return mr(Az(t=>{try{for(let o of A){if(t.disposed)return;t.next(o)}t.complete()}catch(o){t.error(o)}}),"fromIterable",arguments)}function JtA(A){let t=o=>FtA(this,void 0,void 0,function*(){try{if(o.disposed)return;let{done:a,value:l}=yield A.read();if(a)return void o.complete();o.next(l),t(o)}catch(a){o.error(a)}});return mr(o=>{t(o)},"fromReader",arguments)}function qtA(A){return mr(t=>{let o=new AbortController,a=o.signal;t.defer(()=>o.abort("cancelled")),A.pipeTo(new WritableStream({write(l){t.next(l)},close(){t.complete()},abort(l){t.error(l)}}),{signal:a}).then(()=>t.complete(),l=>t.error(l))},"fromReadableStream",arguments)}function KtA(){return mr(A=>{let t=requestAnimationFrame(function o(a){A.disposed||(A.next(a),t=requestAnimationFrame(o))});A.defer(()=>cancelAnimationFrame(t))},"fromAnimationFrame",arguments)}function jtA(A,t){return mr(function(o){let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:A,l=arguments.length>2&&arguments[2]!==void 0?arguments[2]:t+A;for(;a2?o-2:0),l=2;l{let h=a.concat(y=>(d.next(y),d.complete()));A.apply(t,h)},"bindCallback",arguments)}function ztA(A,t){for(var o=arguments.length,a=new Array(o>2?o-2:0),l=2;l{let h=a.concat((y,S)=>y?d.error(y):(d.next(S),d.complete()));A.apply(t,h)},"bindNodeCallback",arguments)}function ZtA(){return mr(()=>{},"never",arguments)}function XtA(A){return mr(t=>t.error(A),"throwError",arguments)}function Ej(){return mr(A=>A.complete(),"empty",arguments)}var uL=class extends Zn{constructor(A,t,o){super(A),this.f=t;let a=()=>{this.sink.next(this.acc),this.sink.complete()};o===void 0?this.next=l=>{this.acc=l,this.complete=a,this.resetNext()}:(this.acc=o,this.complete=a)}next(A){this.acc=this.f(this.acc,A)}},oz=Xn(uL,"reduce"),$tA=A=>Xn(uL,"count")((t,o)=>A(o)?t+1:t,0),AiA=()=>Xn(uL,"max")(Math.max),eiA=()=>Xn(uL,"min")(Math.min),tiA=()=>Xn(uL,"sum")((A,t)=>A+t,0),$v=Xn(class extends Zn{constructor(A,t,o){super(A),this.filter=t,this.thisArg=o}next(A){this.filter.call(this.thisArg,A)&&this.sink.next(A)}},"filter"),iiA=Xn(class extends Zn{next(A){}},"ignoreElements"),p_=Xn(class extends Zn{constructor(A,t){super(A),this.count=t}next(A){this.sink.next(A),--this.count===0&&(this.doDefer(),this.complete())}},"take"),CE=Xn(class extends Zn{constructor(A,t){super(A);let o=new Zn(A);o.next=()=>{o.doDefer(),A.complete()},o.complete=gj,o.subscribe(t)}},"takeUntil"),oiA=Xn(class extends Zn{constructor(A,t){super(A),this.f=t}next(A){this.f(A)?this.sink.next(A):(this.doDefer(),this.complete())}},"takeWhile"),niA=A=>oz((t,o)=>(t.push(o),t.length>A&&t.shift(),t),[]),siA=Xn(class extends Zn{constructor(A,t){super(A),this.count=t}next(A){--this.count===0&&(this.next=super.next)}},"skip"),riA=Xn(class extends Zn{constructor(A,t){super(A),A.next=sg;let o=new Zn(A);o.next=()=>{o.doDefer(),A.resetNext()},o.complete=gj,o.subscribe(t)}},"skipUntil"),dj=Xn(class extends Zn{constructor(A,t){super(A),this.f=t}next(A){this.f(A)||(this.next=super.next,this.next(A))}},"skipWhile"),aiA={leading:!0,trailing:!1},giA=class extends Zn{constructor(A,t,o){super(A),this.durationSelector=t,this.trailing=o}cacheValue(A){this.last=A,this.disposed&&this.throttle(A)}send(A){this.sink.next(A),this.throttle(A)}throttle(A){this.reset(),this.subscribe(this.durationSelector(A))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},nz=class extends Zn{constructor(A,t){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:aiA;super(A),this.durationSelector=t,this.config=o,this._throttle=new giA(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(A){this._throttle.disposed&&this.config.leading?this._throttle.send(A):this._throttle.cacheValue(A)}complete(){this._throttle.throttle=sg,this._throttle.complete(),super.complete()}},ciA=Xn(nz,"throttle"),liA={leading:!1,trailing:!0},IiA=A=>Xn(nz,"audit")(A,liA),uiA=class extends Zn{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},sz=class extends Zn{constructor(A,t){super(A),this.durationSelector=t,this._debounce=new uiA(this.sink),this._debounce.dispose()}next(A){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=A,this._debounce.subscribe(this.durationSelector(A))}complete(){this._debounce.complete(),super.complete()}},EiA=Xn(sz,"debounce"),diA=A=>Xn(sz,"debounceTime")(t=>uj(A)),CiA=Xn(class extends Zn{constructor(A,t,o){super(A),this.count=t,this.defaultValue=o}next(A){this.count--===0&&(this.defaultValue=A,this.doDefer(),this.complete())}complete(){this.defaultValue!==void 0?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("not enough elements in sequence"))}},"elementAt"),hiA=A=>t=>p_(1)(dj(o=>!A(o))(t)),BiA=Xn(class extends Zn{constructor(A,t){super(A),this.f=t,this.i=0}next(A){this.f(A)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},"findIndex"),QiA=Xn(class extends Zn{constructor(A,t,o){super(A),this.f=t,this.defaultValue=o,this.index=0}next(A){(!this.f||this.f(A,this.index++))&&(this.defaultValue=A,this.doDefer(),this.complete())}complete(){this.defaultValue!==void 0?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"first"),piA=Xn(class extends Zn{constructor(A,t,o){super(A),this.f=t,this.defaultValue=o,this.index=0}next(A){(!this.f||this.f(A,this.index++))&&(this.defaultValue=A)}complete(){this.defaultValue!==void 0?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"last"),miA=Xn(class extends Zn{constructor(A,t){super(A),this.predicate=t,this.index=0}next(A){this.predicate(A,this.index++)?this.result=!0:(this.result=!1,this.doDefer(),this.complete())}complete(){this.result!==void 0?(this.sink.next(this.result),super.complete()):this.error(new Error("no elements in sequence"))}},"every"),rz=Xn(class extends Zn{constructor(A,t,o){super(A),this.f=t,o===void 0?this.next=a=>{this.acc=a,this.resetNext(),this.sink.next(this.acc)}:this.acc=o}next(A){this.sink.next(this.acc=this.f(this.acc,A))}},"scan"),fiA=Xn(class extends Zn{constructor(){super(...arguments),this.hasLast=!1}next(A){this.hasLast?this.sink.next([this.last,A]):this.hasLast=!0,this.last=A}},"pairwise"),az=class extends Zn{constructor(A,t,o){super(A),this.mapper=t,this.thisArg=o}next(A){super.next(this.mapper.call(this.thisArg,A))}},Cj=Xn(az,"map"),yiA=A=>Xn(az,"mapTo")(t=>A),EL=class extends Zn{constructor(A,t,o){super(A),this.data=t,this.context=o}next(A){let t=this.context.combineResults;t?this.sink.next(t(this.data,A)):this.sink.next(A)}tryComplete(){this.context.resetComplete(),this.dispose()}},dL=class mX extends Zn{constructor(t,o,a){super(t),this.makeSource=o,this.combineResults=a,this.index=0}subInner(t,o){let a=this.currentSink=new o(this.sink,t,this);this.complete===mX.prototype.complete&&(this.complete=this.tryComplete),a.complete=a.tryComplete,a.subscribe(this.makeSource(t,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},gz=class extends EL{},cz=class extends dL{next(A){this.subInner(A,gz),this.next=t=>{this.currentSink.dispose(),this.subInner(t,gz)}}},h1=Xn(cz,"switchMap");function B1(A){return(t,o)=>A(()=>t,o)}var Q1=B1(Xn(cz,"switchMapTo")),DiA=class extends EL{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},lz=class extends dL{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(A){this.next2(A),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),DiA),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},SiA=Xn(lz,"concatMap"),viA=B1(Xn(lz,"concatMapTo")),MiA=class extends EL{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Iz=class extends dL{constructor(){super(...arguments),this.inners=new Set}next(A){this.subInner(A,MiA),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(A=>A.resetComplete()):this.dispose()}},RiA=Xn(Iz,"mergeMap"),wiA=B1(Xn(Iz,"mergeMapTo")),_iA=class extends EL{dispose(){this.context.resetNext(),super.dispose()}},uz=class extends dL{next(A){this.next=sg,this.subInner(A,_iA)}},TiA=Xn(uz,"exhaustMap"),NiA=B1(Xn(uz,"exhaustMapTo")),GiA=Xn(class extends Zn{constructor(A,t){super(A),this.f=t,this.groups=new Map}next(A){let t=this.f(A),o=this.groups.get(t);o===void 0&&(o=BQ(),o.key=t,this.groups.set(t,o),super.next(o)),o.next(A)}complete(){this.groups.forEach(A=>A.complete()),super.complete()}error(A){this.groups.forEach(t=>t.error(A)),super.error(A)}},"groupBy"),biA=Xn(class extends Zn{constructor(){super(...arguments),this.start=new Date}next(A){this.sink.next({value:A,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},"timeInterval"),kiA=Xn(class extends Zn{constructor(A,t){super(A),this.miniseconds=t,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(A){this.buffer.push(A)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},"bufferTime"),LiA=Xn(class extends Zn{constructor(A,t){super(A),this.buffer=[],this.delayTime=t}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(A){this.timeoutId=setTimeout(()=>{let t=this.buffer.shift();if(t){let{time:o,data:a}=t;super.next(a),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(o))}},A)}next(A){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:A})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},"delay"),Ez=Xn(class extends Zn{constructor(A,t){super(A),this.selector=t}error(A){this.dispose(),this.selector(A)(this.sink)}},"catchError"),UiA=class extends EL{tryComplete(){let A=this.context.inners.delete(this);super.dispose(),A&&this.context.checkComplete()}next(A){this.sink.next(A),this.context.expandValue(A)}},FiA=Xn(class extends dL{constructor(A,t){super(A,t),this.project=t,this.inners=new Set,this.sourceCompleted=!1}next(A){this.sink.next(A),this.expandValue(A)}expandValue(A){let t=new UiA(this.sink,A,this);this.currentSink=t,this.complete=this.tryComplete,t.complete=t.tryComplete,this.inners.add(t),t.subscribe(this.makeSource(A,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},"expand"),OiA=()=>A=>new Promise((t,o)=>{let a;new d1(A,l=>a=l,o,()=>t(a))}),PiA=()=>A=>{let t;return new ReadableStream({start(o){t=new d1(A,o.enqueue.bind(o),o.error.bind(o),o.close.bind(o))},cancel(){t.dispose()}})},Dl=function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:sg,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:sg,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:sg;return a=>new d1(a,A,t,o)},hj=Xn(class extends Zn{constructor(A,t){super(A),t instanceof Function?this.next=o=>{t(o),A.next(o)}:(t.next&&(this.next=o=>{t.next(o),A.next(o)}),t.complete&&(this.complete=()=>{t.complete(),A.complete()}),t.error&&(this.error=o=>{t.error(o),A.error(o)}))}},"tap"),xiA=Xn(class extends Zn{constructor(A,t){super(A),this.timeout=t,this.id=setTimeout(()=>this.error(new W5(this.timeout)),this.timeout)}next(A){super.next(A),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),YiA=function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1/0;return t=>{if(t instanceof _y){let o=mr(a=>{let l=A,d=new Zn(a);d.error=h=>{l-- >0?d.subscribe(t):a.error(h)},d.sourceId=o.id,d.subscribe(t)},"retry",[A]);return o.source=t,Bc.pipe(o),o}return o=>{let a=A,l=new Zn(o);l.error=d=>{a-- >0?t(l):o.error(d)},t(l)}}},Bj=(A=>(A[A.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",A[A.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",A))(Bj||{}),CL=class fX extends aj{constructor(t,o){super({mediaType:t,PlayerClass:o}),Y(this,"isRemote",!1),Y(this,"deviceId"),Y(this,"groupId",""),Y(this,"label",""),Y(this,"sourceTrack"),Y(this,"enableAutoSwitchWhenRecapturing",!0),Y(this,"_isRecapturing",!1),Y(this,"_lastRecaptureTime",0),Y(this,"_onMuteTimeoutId",-1),Y(this,"_encodeCheckTimeoutId",-1),Y(this,"recaptureMode",0),Y(this,"profile"),Y(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return!(!this.mediaTrack||this.sourceTrack===this.mediaTrack)}encodeFrame(t,o){throw new Error("Method not implemented.")}installTrackEvent(t){t.addEventListener(JA.MUTE,this.onTrackMuted),t.addEventListener(JA.UNMUTE,this.onTrackUnmuted),t.addEventListener(JA.ENDED,this.onTrackEnded),t.muted&&this.onTrackMuted(),t.readyState===JA.ENDED&&this.onTrackEnded()}uninstallTrackEvent(t){t.removeEventListener(JA.MUTE,this.onTrackMuted),t.removeEventListener(JA.UNMUTE,this.onTrackUnmuted),t.removeEventListener(JA.ENDED,this.onTrackEnded)}setStateToReady(){}capture(t){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return XA(this,null,function*(){var a,l;let d=this.sourceTrack;try{let h,y=Oo();F.emit(rA.LOCAL_TRACK_CAPTURE_START,{track:this}),t.customSource?(h=new MediaStream,h.addTrack(t.customSource)):(o||(a=this.sourceTrack)==null||a.stop(),h=yield StA(t));let S=h.getTracks()[0];return yield this.setInputMediaStreamTrack(S),t.customSource||(this.sourceTrack=S,this.updateDeviceIdInUse(),this.listenDeviceChange()),F.emit(rA.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Oo()-y,profile:this.profile,room:(l=this.manager)==null?void 0:l.room}),h}catch(h){throw F.emit(rA.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:h}),this.log.error("getUserMedia error observed ".concat(h)),h}finally{o&&d?.stop()}})}setOutputMediaStreamTrack(t){var o;if(super.setOutputMediaStreamTrack(t),this.setStateToReady(),this.isPublishing||this.isPublished)return(o=this.room)==null?void 0:o.replaceTrack(this)}get hasFlag(){var t,o;let a=kp(((t=this.room)==null?void 0:t.localPublishFlag)||0,((o=this.room)==null?void 0:o.userId)||"");return this.mediaType===4&&a.hasVideo||this.mediaType===1&&a.hasAudio||this.mediaType===2&&a.hasAuxiliary}publish(t,o){return XA(this,null,function*(){return this.room=t,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=t.userId,this._log.bindParent(t.getLogger()),yield o,this._checkPublishFlag(t)})}_checkPublishFlag(t){return new Promise((o,a)=>XA(this,null,function*(){var l,d,h,y,S;let L=()=>a(new li({code:mt.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?o():((this.state===gs.INIT||this.state==="ready")&&L(),Ma(Ea(t,"local-publish-flag-changed"),$v(()=>this.hasFlag),CE(cj(Ea(this,gs.INIT),Ea(this,"ready"))),Dl(o,a,L))),(h=(d=(l=this.room)==null?void 0:l.networkQuality)==null?void 0:d.hadRecentBadUplink)!=null&&h.call(d,2))return o();let V=t.heartbeatCount,H=((S=(y=this.mediaTrack)==null?void 0:y.stats)==null?void 0:S.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>XA(this,null,function*(){var lA,hA,MA,oe,fe,je,_e,vi;if((MA=(hA=(lA=this.room)==null?void 0:lA.networkQuality)==null?void 0:hA.hadRecentBadUplink)!=null&&MA.call(hA,2)||t.heartbeatCount-V<3)return o();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((oe=this.mediaTrack)!=null&&oe.stats){let pi=this.mediaTrack.stats.totalFrames||0;pi-H===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",pi)}let Fe=this.kind===JA.AUDIO,Dt=this.stat.bytesSent>0;if(ri[Dt?"addSuccessEvent":"addFailedEvent"]({key:Fe?503700:513702}),!Fe){let pi={H264:513704,H265:513705,VP8:513706}[((je=(fe=this.room)==null?void 0:fe.videoCodec)==null?void 0:je.toUpperCase())||"H264"];pi&&ri[Dt?"addSuccessEvent":"addFailedEvent"]({key:pi})}if(!Dt){if(ri.addEnum({key:Fe?503701:513703,value:Kp()}),ds.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(lQ()||jp()),userId:this.userId}),this.log.warn(Fe?"encode failed":"".concat((vi=(_e=this.room)==null?void 0:_e.videoCodec)==null?void 0:vi.toUpperCase()," encode failed")),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield OC(5e3),this.stat.bytesSent>0||this.hasFlag)))return o();this.emit("6",this),a(new li({message:"".concat(this.strMediaType," encode failed"),code:Fe?mt.AUDIO_ENCODE_FAILED:mt.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),F.emit(rA.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return XA(this,null,function*(){if(this.sourceTrack&&Dy){let{deviceId:t,groupId:o}=this.sourceTrack.getSettings(),{label:a}=this.sourceTrack;(yield function(l){return XA(this,arguments,function(d){let{newDeviceId:h,oldDeviceId:y,oldGroupId:S,oldLabel:L,kind:V}=d;return function*(){return h===y&&(V!==JA.AUDIO||h!==sv||(yield O5(S,L)))}()})}({newDeviceId:t,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=t,this.label=a,o&&(this.groupId=o),c1().then(l=>{let d=l.find(h=>{let y=h.deviceId===t;return o&&(y=y&&h.groupId===o),y});d&&this.emit("2",d)}))}})}setProfile(t){this.log.info("setProfile",t),Object.assign(this.profile,t)}isNeedToRecapture(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return!(!this.deviceId||!this.sourceTrack||this.kind===JA.AUDIO&&!function(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let a=o.label.toLocaleLowerCase();if(a.includes("mic")||a.includes("麦克风"))return!0;let l="".concat((o?.getSettings()||{}).deviceId,"_").concat(JA.AUDIO_INPUT);return!!sj.has(l)}(this.sourceTrack)||this.kind===JA.VIDEO&&!function(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let a=o.label.toLocaleLowerCase();if(a.includes("camera")||a.includes("webcam"))return!0;let l="".concat((o?.getSettings()||{}).deviceId,"_").concat(JA.VIDEO_INPUT);return!!sj.has(l)}(this.sourceTrack)||this._isRecapturing||t&&rQ&&fg)}onTrackMuted(){if(super.onTrackMuted(),vtA(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTimethis.onTrackMuted(),av);this._onMuteTimeoutId=setTimeout(()=>XA(this,null,function*(){var t;if((t=this.sourceTrack)!=null&&t.muted){if((ng||za)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return XA(this,null,function*(){if(UI(fX.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTimethis.onTrackEnded(),av);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(t){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return XA(this,null,function*(){var a;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let l=this.sourceTrack;o||(a=this.sourceTrack)==null||a.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let d={useExactDeviceId:!0};if(t==="user"||t==="environment")d.facingMode=t;else{let h;(this.kind==="audio"?yield om():yield nm()).find(y=>y.deviceId===t)&&(h=t),d.deviceId=h}return this.capture(d,o).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),F.emit(rA.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(h=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(h.message)),this.emit("5",h),F.emit(rA.LOCAL_TRACK_RECAPTURE,{track:this,error:h})}).finally(()=>{o&&l?.stop()})})}getRecoverCaptureDeviceId(){return XA(this,null,function*(){let t=this instanceof QQ;if(t&&this.facingMode)return this.facingMode;let{deviceId:o}=this;if(o){let a=(BL.get(o)||0)+1;if(BL.set(o,a),a>=3&&this.enableAutoSwitchWhenRecapturing){let l=t?(yield nm()).find(d=>!BL.has(d.deviceId)):(yield om()).find(d=>!BL.has(d.deviceId));l&&(this.log.warn("".concat(o," capture fail ").concat(a," times, change new ").concat(l.deviceId)),o=l.deviceId)}}return o})}stopCapture(){var t;this.sourceTrack&&(this.sourceTrack.stop(),F.emit(rA.LOCAL_TRACK_STOPPED,{track:this}),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(t=this.manager)==null||t.removeInput(this),this._onMuteTimeoutId&&clearTimeout(this._onMuteTimeoutId)}close(){super.close(),this.stopCapture()}};Qi([hc(gs.INIT,"ready",{ignoreError:!0,sync:!0})],CL.prototype,"setStateToReady"),Qi([lL()],CL.prototype,"capture"),Qi([hc("ready","publish",{ignoreError:!0,success(){F.emit(rA.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(A){var t;(t=this.room)==null||t.localTracks.delete(this);let o="error",a=A instanceof li?A:A.cause instanceof li?A.cause:A,l=!1;a instanceof li&&(a.message.includes("timeout")?o="timeout":a.code===mt.API_CALL_ABORTED&&(l=!0,o="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:o,error:a}),this.log[l?"info":"error"]("publish failed",a)}}),wy(521714,!1)],CL.prototype,"publish"),Qi([Xr(A=>function(){return XA(this,null,function*(){let t=this.state==="publish"?"started":"starting";A.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:t,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),hc([],"ready",{sync:!0})],CL.prototype,"unpublish");var hL=CL,BL=new Map;F.on(rA.SWITCH_DEVICE_SUCCESS,A=>{A.track.deviceId&&BL.delete(A.track.deviceId)});var AM=class VL extends hL{constructor(t){super(1,ptA),Y(this,"mediaType",1),Y(this,"volume",0),Y(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),Y(this,"playerMuted",!0),Y(this,"pipeline"),Y(this,"earMonitorGainNode",new HI),Y(this,"_output",new HI),Y(this,"codecPipeline",[]),Y(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),Y(this,"mixedAudioReferenceMap",new Map),Y(this,"isAudioContextLongSuspended",!1),Y(this,"after3aSilenceStartTime",0),Y(this,"_micMuted",!1),Y(this,"_volumeDetectionTrack",null),Y(this,"_volumeDetectionSource",new HI),this.manager=t,this.pipeline=new G5(t),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this._volumeDetectionSource.pipeTo(this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),F.on(rA.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return g1.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let t=(this.volume||super.getAudioLevel())*this.captureVolume;return t>1?1:t}getInternalAudioLevelAfter3A(){if(this.pipeline.isProcessEnabled)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(t){ze(t)||(t!==0||this.after3aSilenceStartTime?t>0&&(this.after3aSilenceStartTime=0):this.after3aSilenceStartTime=Oo())}setInputMediaStreamTrack(t){return XA(this,null,function*(){let o=this.trackSettings||{};ri.addEnum({key:501701,value:o.channelCount||0,useUV:!1}),ri.addEnum({key:501702,value:o.sampleRate||0,useUV:!1}),ri.addEnum({key:502700,value:0});let{sampleRate:a,channelCount:l}=o;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:a,channelCount:l}))),this.pipeline.source.channelCount=l||1,this.pipeline.replaceSource(t),yield UI(VL.prototype,this,"setInputMediaStreamTrack").call(this,t),this.updatePlayingState(!!t)})}capture(t){return XA(this,arguments,function(o){var a=this;let{deviceId:l,customSource:d,useExactDeviceId:h=!0,retryWhenExactFailed:y}=o,S=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return function*(){let L=yield UI(VL.prototype,a,"capture").call(a,{video:!1,audio:!0,microphoneId:l,echoCancellation:a.profile.echoCancellation,autoGainControl:a.profile.autoGainControl,noiseSuppression:a.profile.noiseSuppression,sampleRate:a.profile.sampleRate,channelCount:a.profile.channelCount,useExactDeviceId:h,retryWhenExactFailed:y,customSource:d},S);return gL(),L}()})}switchDevice(t){return XA(this,null,function*(){if(this.mediaTrack){if(this.deviceId===t&&!this.isUseCustomSource&&(t!==sv||(yield O5(this.groupId,this.label))))return;try{this.log.info("switchDevice audio to: ".concat(t)),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:t,useExactDeviceId:!0,retryWhenExactFailed:!1}),F.emit(rA.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(o){throw this.log.error("switch microphone failed ".concat(o)),this.deviceId&&this.recapture(this.deviceId),o}}})}listenDeviceChange(){Kc&&!Kc.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Kc.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(t){return XA(this,null,function*(){if(t.deviceId===this.deviceId){let o=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(Bj[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(t))),this.recaptureMode===0){jg(this.userId,{eventId:2003,param1:6,streamType:1});let a=yield om();a[0]?this.recapture(a[0].deviceId):o=!0}o&&Kc.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(t){this.recaptureMode===1&&t.deviceId!==this.deviceId||(Kc.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(t))),this.recapture(t.deviceId))}update3A(t){return XA(this,arguments,function(o){var a=this;let{echoCancellation:l,noiseSuppression:d,autoGainControl:h}=o;return function*(){let y=a.sourceTrack||a.mediaTrack;if(!y)return;let S=y.getConstraints(),L=!1;!ze(l)&&l!==a.profile.echoCancellation&&(a.profile.echoCancellation=l,S.echoCancellation=l,L=!0),!ze(d)&&d!==a.profile.noiseSuppression&&(a.profile.noiseSuppression=d,S.noiseSuppression=d,L=!0),!ze(h)&&h!==a.profile.autoGainControl&&(a.profile.autoGainControl=h,S.autoGainControl=h,L=!0),L&&(gr||fg?yield y.applyConstraints(S).catch(V=>a._log.warn("update3A failed: ",V)):a.deviceId&&(yield a.recapture(a.deviceId,!0)))}()})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(t){this.pipeline.setVolume(t/100),this.pipeline.gain.node&&ri.addEnum({key:502700,value:2})}setMute(t,o){var a;this._cleanupVolumeDetectionTrack(),t==="microphone"?(this._micMuted=!0,this.sourceTrack&&(this.sourceTrack.enabled=!1),o&&this._setupVolumeDetectionTrack(),((a=this.manager)==null?void 0:a.mixWeight)<=1?(this.muted=!0,this._inputTrack&&(this._inputTrack.enabled=!1),this._outputTrack&&(this._outputTrack.enabled=!1),this.emit("mute",this),F.emit(rA.TRACK_MUTED,{track:this})):this._outputTrack&&(this._outputTrack.enabled=!0)):t===!0?(this._micMuted=!1,this.muted=!0,this.sourceTrack&&(this.sourceTrack.enabled=!1),this._inputTrack&&(this._inputTrack.enabled=!1),this._outputTrack&&(this._outputTrack.enabled=!1),o&&this._setupVolumeDetectionTrack(),this.emit("mute",this),F.emit(rA.TRACK_MUTED,{track:this})):(this._micMuted=!1,this.muted=!1,this.sourceTrack&&(this.sourceTrack.enabled=!0),this._inputTrack&&(this._inputTrack.enabled=!0),this._outputTrack&&(this._outputTrack.enabled=!0),this.emit("unmute",this),F.emit(rA.TRACK_UNMUTED,{track:this}))}_setupVolumeDetectionTrack(){let t=this.sourceTrack||this.mediaTrack;if(!t)return;this._volumeDetectionTrack=t.clone(),this._volumeDetectionTrack.enabled=!0;let o=r1(this._volumeDetectionTrack);o&&this._volumeDetectionSource.setNode(o)}_cleanupVolumeDetectionTrack(){this._volumeDetectionTrack&&(this._volumeDetectionTrack.stop(),this._volumeDetectionTrack=null),this._volumeDetectionSource.deleteNode()}get isMicMuted(){return this._micMuted}setAudioVolume(t){super.setAudioVolume(0),ng&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(VI().createGain()),this._output.setNode(VI().destination)),this.earMonitorGainNode.node.gain.value=t}enableTrackANS(t){return this.update3A({noiseSuppression:t})}enableTrackAEC(t){if(this.sourceTrack&&!fg&&!ng)return this.update3A({echoCancellation:t})}addDenoiser(t){var o;nd<=92&&((o=this.trackSettings)==null?void 0:o.sampleRate)!==48e3?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(ri.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(t),this.enableTrackANS(!1))}mixAudioReference(t,o){if(this.mixedAudioReferenceMap.has(o))return;this.log.info("mixAudioReference() => ".concat(o));let a=r1(t);if(!a)return;let l=new HI,d=VI().createGain();d.gain.value=1;let h=new HI;l.pipeTo(h).pipeTo(this.pipeline.mixNode),l.setNode(a),h.setNode(d),this.mixedAudioReferenceMap.set(o,[l,h])}unMixAudioReference(t){let[o,a]=this.mixedAudioReferenceMap.get(t)||[];o&&(this.log.info("unMixAudioReference() => ".concat(t)),o.deleteNode(),a?.deleteNode(),this.mixedAudioReferenceMap.delete(t))}setAudioReferenceVolume(t,o){let[a,l]=this.mixedAudioReferenceMap.get(t)||[];l!=null&&l.node&&(l.node.gain.value=o/100,this.log.info("setAudioReferenceVolume() => ".concat(t," ").concat(l.node.gain.value)))}addAudioProcessor(t,o,a){this.pipeline.silentNode.setNode(a),this.pipeline.mixNode.setNode(o),this.pipeline.aec.setNode(t)}removeDenoiser(t){if(this.pipeline.denoiser.node===t)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(t){this.pipeline.aec.node===t&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this._cleanupVolumeDetectionTrack(),this.mixedAudioReferenceMap.forEach(t=>{let[o,a]=t;o.deleteNode(),a.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),Kc.off("audioInputAdded",this.handleMicrophoneAdded,this),Kc.off("audioInputRemoved",this.handleMicrophoneRemoved,this),F.off(rA.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(t){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return XA(this,null,function*(){try{yield UI(VL.prototype,this,"recapture").call(this,t,o)}catch(a){let l=(yield om()).find(d=>d.deviceId!==t);if(!l)throw a;yield UI(VL.prototype,this,"recapture").call(this,l.deviceId)}})}encodeFrame(t){return this.manager?this.manager.encodePipeline.reduceRight((o,a)=>a?a({frame:o,ntp:Vf()}):o,t):t}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(t=>t)}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended(t){let{isSuspended:o}=t;if(this.pipeline.isProcessEnabled)if(o){this.isAudioContextLongSuspended=!0,this.log.warn("context has suspended for ".concat(1.5," seconds, change to source audio").concat(Hp?"":", non-Safari"));let a=this.sourceTrack||this.mediaTrack;a&&this.setOutputMediaStreamTrack(a)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(t){if(this.isAudioContextLongSuspended){let o=this.sourceTrack||this.mediaTrack;o&&(t=o)}super.setOutputMediaStreamTrack(t)}};function p1(A,t){return t+4<=A.byteLength&&A.getUint8(t)===0&&A.getUint8(t+1)===0&&A.getUint8(t+2)===0&&A.getUint8(t+3)===1?4:t+3<=A.byteLength&&A.getUint8(t)===0&&A.getUint8(t+1)===0&&A.getUint8(t+2)===1?3:0}function dz(A){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1],o=new DataView(A),a=[],l=0;for(;l0){h=H;break}let y=h===-1?o.byteLength:h,S=y-l,L=new ArrayBuffer(S),V=new DataView(L);for(let H=0;H1&&arguments[1]!==void 0&&arguments[1];this.dataView=A,this.isSEI&&(t?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let{seiPayloadStartIndex:A}=this,t=this.dataView.byteLength-2,o=[],a=0;for(let d=A;d<=t;d++){let h=this.dataView.getInt8(d);switch(h){case 0:case 1:case 2:case 3:a===2&&(o.push(3),a=0),h===0?a+=1:a=0,o.push(h);break;default:a=0,o.push(h)}}o.push(this.dataView.getInt8(this.dataView.byteLength-1));let l=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,A),...o]).buffer);this.dataView=l}removePreventionByte(){let{seiPayloadStartIndex:A}=this,t=this.dataView.byteLength-1,o=[],a=0;for(let d=A;d<=t;d++)switch(this.dataView.getInt8(d)){case 0:a++,o.push(this.dataView.getInt8(d));break;case 3:a!==2&&o.push(this.dataView.getInt8(d)),a=0;break;default:o.push(this.dataView.getInt8(d)),a=0}let l=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,A),...o]).buffer);this.dataView=l}get seiPayloadStartIndex(){let A=6;for(let t=6;t=this.dataView.byteLength?0:31&this.dataView.getUint8(A)}getStartCodeLength(){return this.dataView.byteLength>=4&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===0&&this.dataView.getUint8(3)===1?4:this.dataView.byteLength>=3&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===1?3:0}get isIDR(){return this.naluType===5}get isSPS(){return this.naluType===7}get isPPS(){return this.naluType===8}get isSEI(){return this.naluType===6}},ViA=class{constructor(){Y(this,"_seiMessageList",[]),Y(this,"_smallSeiMessageList",[]),Y(this,"_seiPayloadType",243)}encodeSEINalu(A){let t=A.byteLength,o=parseInt(String(t/255),10),a=t%255,l=[];l.push(0,0,0,1,6,this._seiPayloadType);for(let h=0;h0&&A.data.byteLength>0){let a=9-this.getNaluCount(A.data);if(a<=0)return 0;let l=o.splice(0,a).reverse().map(this.encodeSEINalu.bind(this)),d=l.reduce((V,H)=>V+H.dataView.byteLength,0),h=new ArrayBuffer(d+A.data.byteLength),y=new DataView(h),S=new DataView(A.data),L=0;for(let V=0;V1&&arguments[1]!==void 0?arguments[1]:4,bo),Y(this,"profile",Di({},Av)),Y(this,"avoidCropping",!1),Y(this,"_scaleResolutionDownBy"),Y(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0}),Y(this,"small"),Y(this,"isNeedToSetBandwidth"),Y(this,"muteImage"),Y(this,"manager"),Y(this,"_seiCodec",new ViA),this.manager=t;let o=()=>{var a;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let l=zd(((a=this.room)==null?void 0:a.sdkAppId)||0)?Lb:E0;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(l)),this.setProfile(So(Di({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",o),this.on("publish",o),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(Dy&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var t;return((t=this._inputTrack)==null?void 0:t.contentHint)||""}get isQosClearFirst(){var t;return((t=this._inputTrack)==null?void 0:t.contentHint)==="detail"}get hasSmall(){var t;return!((t=this.manager)==null||!t.hasSmall)}setMute(t){return XA(this,null,function*(){var o,a,l;if(Ws(t)){if(this.muteImage===t)return;yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),yield(a=this.manager)==null?void 0:a.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:t,fillVideo:!0}),this.muteImage=t,UI(F_.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(l=this.manager)==null?void 0:l.deleteWatermark("mute"),this.muteImage=void 0),UI(F_.prototype,this,"setMute").call(this,t)})}capture(t){return XA(this,arguments,function(o){var a=this;let{deviceId:l,facingMode:d,useExactDeviceId:h=!0,customSource:y,retryWhenExactFailed:S=!0}=o;return function*(){let L={audio:!1,video:!0,facingMode:d||a.facingMode,cameraId:l,width:a.profile.width,height:a.profile.height,frameRate:a.profile.frameRate,useExactDeviceId:h,retryWhenExactFailed:S,customSource:y};if(L.facingMode==="environment"){let V=yield a.getDeviceIdWhenUsingBackCamera();V&&(L.cameraId=V)}return UI(F_.prototype,a,"capture").call(a,L)}()})}setProfile(t){var o;let a=this.fallbackProfile(t);if(a.bitrate&&(this.isNeedToSetBandwidth=a.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(a);else{let l=zd(((o=this.room)==null?void 0:o.sdkAppId)||0)?Lb:E0;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(l)),super.setProfile(So(Di({},this.profile),{width:1920,height:1080}))}}applyProfile(){return XA(this,null,function*(){var t,o;if(!this.mediaTrack)return;let{width:a=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),d=a*l,h=this.settings,y=h.height!==this.profile.height||h.width!==this.profile.width||h.frameRate!==this.profile.frameRate;if(y&&($d===16&&this.deviceId?yield this.recapture(this.deviceId):(Lp(this.outMediaTrack)?yield(t=this.outMediaTrack)==null?void 0:t.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}):yield(o=this.sourceTrack||this.mediaTrack)==null?void 0:o.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:S=0,height:L=0}=(this.sourceTrack||this.mediaTrack).getSettings(),V=S*L;return y&&V&&d&&V===d?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:JA.VIDEO,videoType:JA.BIG})}})}get settings(){let t={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},o=this.sourceTrack||this.mediaTrack;return Dy&&o&&Object.assign(t,o.getSettings()),t}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:F0(this.settings,this.profile)}isAllowed2k4k(t){var o;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(t.height*t.width<3686400))||((o=this.room.scheduleResult.trtcAutoConf)==null?void 0:o["2k4k"])===1}isNeedToSwitchDevice(t){return!(!this.mediaTrack||this.deviceId===t||this.facingMode===t)}switchDevice(t){return XA(this,null,function*(){try{if(!this.isNeedToSwitchDevice(t)&&!this.isUseCustomSource)return;let o={useExactDeviceId:!0,retryWhenExactFailed:!1};t==="user"||t==="environment"?o.facingMode=t:o.deviceId=t,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(o),F.emit(rA.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(o){throw this.log.error("switch camera failed ".concat(o)),this.deviceId&&this.recapture(this.deviceId),o}})}getDeviceIdWhenUsingBackCamera(){return XA(this,null,function*(){let t;try{if(yk&&!ly&&A1){let o=(yield nm(!0)).map(l=>{var d;return So(Di({},l),{capabilities:(d=l.getCapabilities)==null?void 0:d.call(l)})}).filter(l=>{var d,h;return(h=(d=l.capabilities)==null?void 0:d.facingMode)==null?void 0:h.includes("environment")}),a=o[0];o.forEach(l=>{var d,h,y,S;let{capabilities:L}=l;((d=L.width)!=null&&d.max&&(h=L.height)!=null&&h.max?L.width.max*L.height.max:0)>((y=a.capabilities.width)!=null&&y.max&&(S=a.capabilities.height)!=null&&S.max?a.capabilities.width.max*a.capabilities.height.max:0)&&(a=l)}),a!=null&&a.capabilities&&(this._log.info("use max resolution back camera",a),t=a.deviceId)}}catch(o){this._log.warn("get max res camera failed",o)}return t})}updateSmallConfig(t){return XA(this,null,function*(){var o,a;this._log.info("update small stream config: ".concat(JSON.stringify(t)));let l=!this.small;this.small=this.fallbackProfile(t,!0),yield(o=this.manager)==null?void 0:o.update(),l&&(yield(a=this.room)==null?void 0:a.enableSmall(!0)),this.log.info("update small stream config success")})}fallbackProfile(t){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1],a=t.width>t.height,l=Di({},t);return t.width*t.height<=19200&&za&&EE&&(this.log.warn("".concat(o?"small ":"","resolution is ").concat(t.width,"*").concat(t.height,", fallback to 240*180 for android chrome")),l.width=a?240:180,l.height=a?180:240,l.bitrate=Math.max(t.bitrate,150)),t.width*t.height>921600&&x2&&(l.width=a?1280:720,l.height=a?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),wk(PI,"14.3")&&uy(PI,"14.0",!0)&&this.on("7",()=>{let d=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=d?640:480,this.profile.height=d?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>230400&&(this.profile.width=d?640:360,this.profile.height=d?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!o&&this.avoidCropping&&(EE||gr)&&!e_()&&t.width*t.height<=230400&&t.width/t.height===16/9&&(this._scaleResolutionDownBy=1280/t.width,l.width=1280,l.height=720,this.log.warn("capture 720p, scale: ".concat(this._scaleResolutionDownBy))),l}stopSmall(){var t,o;this.small&&(delete this.small,(t=this.manager)==null||t.update(),(o=this.room)==null||o.enableSmall(!1))}listenDeviceChange(){Kc&&!Kc.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Kc.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(t){return XA(this,null,function*(){if(t.deviceId===this.deviceId){let o=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(Bj[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(t))),this.recaptureMode===0){jg(this.userId,{eventId:2003,param1:7,streamType:2});let a=yield nm();a[0]?this.recapture(a[0].deviceId):o=!0}o&&Kc.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(t){return XA(this,null,function*(){this.recaptureMode===1&&t.deviceId!==this.deviceId||(Kc.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn("camera added: ".concat(JSON.stringify(t))),this.recapture(t.deviceId))})}encodeFrame(t,o){if(!this.manager)return t;let a=o?8:this.mediaType;return this.manager.encodePipeline.reduceRight((l,d)=>d?d({frame:l,mediaType:a}):l,t)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(t=>t)}play(t,o){return ze(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(t,o)}close(){Kc.off("videoInputAdded",this.handleCameraAdded,this),Kc.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(t){return XA(this,null,function*(){try{yield UI(F_.prototype,this,"recapture").call(this,t)}catch(o){let a=(yield nm()).find(l=>l.deviceId!==t);if(!a)throw o;yield UI(F_.prototype,this,"recapture").call(this,a.deviceId)}})}setContentHint(t){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==t&&(this.log.info("setContentHint ".concat(t)),this.mediaTrack.contentHint=t),this.outMediaTrack&&this.outMediaTrack.contentHint!==t&&(this.outMediaTrack.contentHint=t))}setRotation(t){this.manager&&(this.isScreen||ze(t)||t!==this.rotation&&(this.rotation=t,this.manager.rotation=t))}};Qi([Xv(function(A){this.setContentHint(A.contentHint||"motion")})],Cz.prototype,"capture");var QQ=Cz,hz={};Wh(hz,{REPORT_TYPE:()=>O0,buildSSOPackage:()=>oQ,bytes2ms:()=>N0,calculateScaleResolutionDownNumber:()=>F0,concatArrayBuffers:()=>hv,convertObjectNumberToInt:()=>U0,copyProperties:()=>B2,deepClone:()=>iy,deepCloneBasic:()=>oy,deepMerge:()=>$h,delay:()=>OC,fibonacci:()=>Ay,formatedTime:()=>v2,getConstructorName:()=>Iv,getContainerFromElement:()=>tk,getEnv:()=>d2,getFirst16Bits:()=>R2,getInternalVersion:()=>D2,getLast16Bits:()=>P0,getLoggerUrl:()=>Xf,getMediaStreamTrackInfo:()=>rk,getMuteStateFromFlag:()=>kp,getNetworkType:()=>_0,getNumNetworkType:()=>$f,getReconnectionTimeout:()=>bp,getStringByteLength:()=>L0,getTestSignalDomain:()=>C2,getTurnServer:()=>S2,getUint32Version:()=>ok,getValueType:()=>pg,getViewListFromView:()=>dv,glog:()=>p2,ipv4ToUint32:()=>Ev,isArray:()=>ka,isAudioWorkletSupported:()=>m2,isBoolean:()=>br,isConstructor:()=>ty,isEmpty:()=>b0,isFunction:()=>ba,isLangChinese:()=>Zd,isMediaStreamTrack:()=>Ak,isNumber:()=>Ys,isObject:()=>ed,isOverseaSdkAppId:()=>zd,isPlainObject:()=>uE,isPortrait:()=>ik,isPromise:()=>ey,isRemoteTrack:()=>ek,isRotate90Or270:()=>iQ,isSetSinkIdSupported:()=>f2,isString:()=>Ws,isUndefined:()=>ze,isVideoMixerOutputTrack:()=>Lp,loadImage:()=>Cv,loadVideo:()=>M2,ms2bytes:()=>Q2,ms2samples:()=>G0,normalizeUrl:()=>sk,performanceNow:()=>Oo,promiseAny:()=>uv,samples2ms:()=>$b,setNetworkTypeFromWebRTC:()=>T0,stringify:()=>Xd,stringifyIncludeValue:()=>k0,throttlePromise:()=>nk});var HiA=[-1,-1,1,-1,-1,1,1,1],JiA=[0,0,1,0,0,1,1,1],QL=class lW extends gs{constructor(t,o){if(super(),this.context=t,Y(this,"name"),Y(this,"input"),Y(this,"output"),Y(this,"texture"),Y(this,"ctx2d",null),Y(this,"fbo"),Y(this,"width",0),Y(this,"height",0),Y(this,"x",0),Y(this,"y",0),Y(this,"program"),Y(this,"vertexShader"),Y(this,"fragmentShader"),Y(this,"totalFrames",0),Y(this,"dropFrames",0),Y(this,"matchInputSize",!0),Y(this,"texCoordBuffer"),Y(this,"positionBuffer"),Y(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),Y(this,"cost",0),Y(this,"_canvas",null),Y(this,"_image"),Y(this,"log"),this.context.on("disconnect",this.close,this),this.name=o.name,this.log=o.logger,this.matchInputSize=o.matchInputSize!==!1,this.width=o.width||t.width,this.height=o.height||t.height,this._image=o.image,t instanceof pQ)t.ctx&&o.create2d&&(typeof OffscreenCanvas=="function"&&$d!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);else try{let a=t.ctx;this.texCoordBuffer=this.createBuffer(JiA),this.positionBuffer=this.createBuffer(HiA),o.createTexture!==!1&&(this.texture=a.createTexture(),this.useTexture(),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.pixelStorei(a.UNPACK_ALIGNMENT,1)),o.useFbo&&(this.fbo=a.createFramebuffer(),this.useBufferFrame(),this.useTexture(),a.texImage2D(a.TEXTURE_2D,0,a.RGBA,this.width,this.height,0,a.RGBA,a.UNSIGNED_BYTE,null),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,this.texture,0)),o.useDefaultProgram?this.program=t.defaultProgam:(o.vertexShaderSource||o.fragmentShaderSource)&&(this.vertexShader=o.vertexShaderSource?t.createShader(a.VERTEX_SHADER,o.vertexShaderSource):t.defaultVShader,this.fragmentShader=o.fragmentShaderSource?t.createShader(a.FRAGMENT_SHADER,o.fragmentShaderSource):t.defaultFShader,this.program=t.createProgram(this.vertexShader,this.fragmentShader))}catch(a){this.context.destroy(new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(a.message||a)}))}}get image(){return this._image}set image(t){this._image=t}createFramebuffer(t){let o=this.context.ctx,a=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,a),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,t,0),a}connect(t){for(var o=arguments.length,a=new Array(o>1?o-1:0),l=1;l0&&arguments[0]!==void 0?arguments[0]:0;var o;(o=this.output)==null||o.update(t)}disconnect(){for(var t,o=arguments.length,a=new Array(o),l=0;l{d&&(t.activeTexture(t.TEXTURE0+h),t.bindTexture(t.TEXTURE_2D,d))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let t=this.context.ctx;t.bindFramebuffer(t.FRAMEBUFFER,this.fbo||null)}createBuffer(t){let o=this.context.ctx,a=o.createBuffer();return o.bindBuffer(o.ARRAY_BUFFER,a),o.bufferData(o.ARRAY_BUFFER,new Float32Array(t),o.STATIC_DRAW),a}setTexBuffer(t){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,this.texCoordBuffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array(t),o.STATIC_DRAW)}setPosBuffer(t){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,this.positionBuffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array(t),o.STATIC_DRAW)}changeBufferData(t,o){let a=this.context.ctx;a.bindBuffer(a.ARRAY_BUFFER,t),a.bufferData(a.ARRAY_BUFFER,new Float32Array(o),a.STATIC_DRAW)}setAttributes(){let t=this.context.ctx;for(var o=arguments.length,a=new Array(o),l=0;l{t.enableVertexAttribArray(h),t.bindBuffer(t.ARRAY_BUFFER,d),t.vertexAttribPointer(h,2,t.FLOAT,!1,0,0)})}getVertexPoint(t,o){return[t/this.width*2-1,o/this.height*2-1]}layout2texCoords(t){return[...this.getVertexPoint(t.x,t.y),...this.getVertexPoint(t.x+t.width,t.y),...this.getVertexPoint(t.x,t.y+t.height),...this.getVertexPoint(t.x+t.width,t.y+t.height)]}resize(t,o){if(this.width!==t||this.height!==o){if(this.width=t,this.height=o,this._canvas&&(this._canvas.width=t,this._canvas.height=o),this.texture&&this.fbo){this.useTexture();let a=this.context.ctx;a.texImage2D(a.TEXTURE_2D,0,a.RGBA,t,o,0,a.RGBA,a.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(t,o)}}draw(t,o){this.setAttributes(t||this.positionBuffer,o||this.texCoordBuffer);let a=this.context.ctx;a.drawArrays(a.TRIANGLE_STRIP,0,4)}draw2d(t,o,a,l,d,h,y,S,L){let V=!(ze(h)||ze(y)||ze(S)||ze(L));return!(!this.ctx2d||!t)&&(t instanceof ImageData?(V?this.ctx2d.putImageData(t,o,a,h,y,S,L):this.ctx2d.putImageData(t,o,a),this.emit(lW.RENDER,this.ctx2d.canvas)):(V?this.ctx2d.drawImage(t,h,y,S,L,o,a,l,d):this.ctx2d.drawImage(t,o,a,l,d),this.emit(lW.RENDER,t)),typeof VideoFrame<"u"&&t instanceof VideoFrame&&t.close(),!0)}drawBackGround2d(t){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=t,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var t;let{totalFrames:o,x:a,y:l,width:d,height:h,name:y,cost:S}=this,L=Date.now(),V=(o-this.lastInfo.totalFrames)/((L-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:o,x:a,y:l,width:d,height:h,timestamp:L,fps:V,name:y,cost:S},Di({parent:(t=this.input)==null?void 0:t.getInfo()},this.lastInfo)}createTexture(t){let o=this.context.ctx,a=o.createTexture();return this.useTextures(a),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.pixelStorei(o.UNPACK_ALIGNMENT,1),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,t),a}};Y(QL,"RENDER","render"),Qi([hc(gs.INIT,"connected",{sync:!0})],QL.prototype,"connect"),Qi([hc("connected",gs.INIT,{ignoreError:!0,sync:!0})],QL.prototype,"disconnect"),Qi([hc([],"closed",{sync:!0})],QL.prototype,"close");var tC=QL,qiA=Ma(tz(250),Cj(()=>performance.now()),IL()),KiA=[0,1,1,1,0,0,1,0],Qj=class extends tC{constructor(A,t){super(A,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},t)),Y(this,"_intervalId",0),Y(this,"_sequence",0),Y(this,"checkGLError",!1),Y(this,"checkVisibilityChange"),A instanceof pQ?this.ctx2d=A.ctx||null:A.available&&t!=null&&t.mirrorUpAndDown&&this.setTexBuffer(KiA)}start(A){this.log.info("".concat(this.name," start render ").concat(A," fps")),kr.clearTask(this._intervalId),this._intervalId=kr.run("intervalInWorker",()=>{if(A!==this.context.frameRate&&(kr.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof qC){let t=this.context.ctx.getError();t&&this.context.destroy(new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:5,message:"".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(t)}))}},{fps:this.context.frameRate})}render(A){var t;return!((t=this.input)==null||!t.requestFrame(A))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(tC.RENDER,this.context._canvas),!0)}addInput(A){for(var t=arguments.length,o=new Array(t>1?t-1:0),a=1;a0&&arguments[0]!==void 0?arguments[0]:0;this.state!=="closed"&&(this._intervalId&&(kr.clearTask(this._intervalId),this._intervalId=0,A===1&&(this.log.info("".concat(this.name," use requestVideoFrameCallback")),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info("".concat(this.name," use timer")),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(A){super.removeInput(A),kr.clearTask(this._intervalId)}resize(A,t){super.resize(A,t),this.context.setSize(A,t)}close(){super.close(),kr.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},pj=class extends Qj{constructor(A,t){super(A,t),Y(this,"_videoTrack"),Y(this,"_muteOb"),Y(this,"_closedOb",Ea(this,"closed")),Y(this,"_subscription"),Y(this,"_canvasContainer"),Number(aQ)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=A.canvas.captureStream().getVideoTracks(),this._muteOb=Ea(this._videoTrack,"mute"),Ma(Ea(this._videoTrack,"ended"),CE(this._closedOb),Dl(()=>{this.context.destroy(new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){var A;this._subscription=Ma(this._muteOb,CE(this._closedOb),Q1((A=5e3,t=>{let o=performance.now();Ma(qiA,dj(a=>a-o{var t;return!((t=this._videoTrack)==null||!t.muted||document.hidden)}),Dl(()=>{this.context.destroy(new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var A;(A=this._subscription)==null||A.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info("".concat(this.name," put canvas to body")),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(A){return this.putCanvasIntoDom(),super.render(A)}render2d(A){return this.putCanvasIntoDom(),super.render2d(A)}close(){var A,t;super.close(),(A=this._videoTrack)==null||A.stop(),delete this._videoTrack,(t=this._canvasContainer)==null||t.remove()}},jiA=class extends pj{render(A){var t;let o=!((t=this.input)==null||!t.requestFrame(A));if(this.context._canvas2d){let a=this.context._canvas2d.getContext("2d");a.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),a.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height),this.emit(tC.RENDER,this.context._canvas2d)}else this.emit(tC.RENDER,this.context._canvas);return o}},WiA=class extends pj{constructor(A,t,o){super(A,{name:"smallDestination",logger:o}),this.resolution=t}resize(A,t){let o,a=A*t,l=this.resolution.width*this.resolution.height;this.log.info("big res: ".concat(A,"*").concat(t," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),a>l?o=a/l:(this.log.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(A," * ").concat(t," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),o=a/19200),super.resize(A/Math.sqrt(o),t/Math.sqrt(o))}},Bz=class extends tC{constructor(A,t){super(A,Di({name:"imageSource"},t)),Y(this,"_lastImage"),Y(this,"_totalFrames",0),Y(this,"_autoResize",!1),Y(this,"_canvasRendered"),Y(this,"videoCallbackId",0),Y(this,"waitingFirstFrame",!0),Y(this,"shouldUpdate",!0),this._autoResize=t?.autoResize!==!1,$d===16&&(this._canvasRendered=BQ(),Ma(this._canvasRendered,lj(this._image),h1(o=>o instanceof HTMLCanvasElement?Ea(o,"rendered"):Ej()),CE(Ea(this,"closed")),Dl(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let A=this.image;this.videoCallbackId&&A.cancelVideoFrameCallback(this.videoCallbackId),Am()&&!document.hidden&&(this.videoCallbackId=A.requestVideoFrameCallback((t,o)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=o.presentedFrames,this.update(1))}))}_render(A,t){var o;let{width:a,height:l}=this,{image:d}=this;if(d instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:a,videoHeight:l}=d,!a||!l)return!1;d.width=a,d.height=l}else if(d instanceof HTMLImageElement||d instanceof ImageData||d instanceof ImageBitmap){if({width:a,height:l}=d,d!==this._lastImage)this._lastImage=d;else if(a===this.width&&l===this.height)return!0}else d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?({width:a,height:l}=d,this._lastImage=d):typeof VideoFrame<"u"&&d instanceof VideoFrame&&({displayWidth:a,displayHeight:l}=d,(o=this._lastImage)==null||o.close(),this._lastImage=d);if(!this._autoResize)return!0;if(this.width===a&&this.height===l&&this.totalFrames){if(t){this.useTexture();let h=this.context.ctx;h.texSubImage2D(h.TEXTURE_2D,0,0,0,h.RGBA,h.UNSIGNED_BYTE,d)}}else{if(t){this.useTexture();let h=this.context.ctx;h.texImage2D(h.TEXTURE_2D,0,h.RGBA,h.RGBA,h.UNSIGNED_BYTE,d)}this.resize(a,l)}return!0}get image(){return this._image}set image(A){var t;(t=this._canvasRendered)==null||t.next(A),this._image=A}render(A){return this._render(A,!0)}render2d(A){return this._render(A,!1)}},Qz=class extends Bz{constructor(A,t,o){super(A,o),this._player=t,this.name="videoPlayerSource",Ma(Ea(this._player,Mo.PLAYER_STATE_CHANGED),CE(Ea(this,"closed")),$v(a=>{let{state:l}=a;return l==="PLAYING"}),Dl(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},m_=class extends Qz{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(A,t,o){super(A,new bo({id:o.name,track:t,muted:!0,container:null,objectFit:"contain",log:o.logger}),o),this.name="videoTrackSource",this._player.play()}replaceTrack(A){this.waitingFirstFrame=!0,this._player.setTrack(A),this._player.play()}close(){super.close(),this._player.stop()}},ziA=class extends tC{constructor(A,t,o){super(A,So(Di({name:"textSource"},o),{create2d:!0})),Y(this,"hasChange",!0),Y(this,"content",""),this.ctx2d.textBaseline="top",this.content=t.content||"",t.font&&(this.font=t.font),t.color&&(this.color=t.color)}set font(A){this.ctx2d&&(this.ctx2d.font=A,this.hasChange=!0)}get font(){var A;return((A=this.ctx2d)==null?void 0:A.font)||""}set color(A){this.ctx2d&&(this.ctx2d.fillStyle=A,this.hasChange=!0)}get color(){var A;return((A=this.ctx2d)==null?void 0:A.fillStyle)||""}render2d(A){return!(!this.ctx2d||!this.hasChange)&&(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0)}render(A){return!1}resize(A,t){if(!this.ctx2d)return;let{color:o,font:a}=this;super.resize(A,t),this.color=o,this.font=a}drawMultilineText(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1.2;if(!this.ctx2d)return;let a=this.ctx2d.measureText(this.content);t+=a.fontBoundingBoxAscent||a.actualBoundingBoxAscent||0;let l=this.font.match(/(\d+)px/),d=(l?parseInt(l[1],10):16)*o,h=this.content.split(` `);for(let y=0;y0&&arguments[0]!==void 0&&arguments[0];if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(pL._ids++)),A&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",qb),!this.ctx)throw new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,` // 顶点着色器 attribute vec4 a_position; @@ -300,19 +300,19 @@ uniform sampler2D u_texture; void main() { gl_FragColor = texture2D(u_texture, v_texCoord); -} `),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(A){let t="";return A&&(t=A.message,this.error=A,ri.addFailedEvent({key:512702,error:A})),this.disconnect(),this.log.info("video context destroy".concat(t)?": ".concat(t):""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),A}set width(A){var t;(t=this.ctx)==null||t.viewport(0,0,A,this.height),super.width=A,this._canvas2d&&(this._canvas2d.width=A)}set height(A){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,A),super.height=A,this._canvas2d&&(this._canvas2d.height=A)}setSize(A,t){var o;(o=this.ctx)==null||o.viewport(0,0,A,t),super.setSize(A,t),this._canvas2d&&(this._canvas2d.width=A,this._canvas2d.height=t)}createShader(A,t){let o=this.ctx,a=o.createShader(A);return o.shaderSource(a,t),o.compileShader(a),a}createProgram(A,t){let o=this.ctx,a=o.createProgram();return o.attachShader(a,A),o.attachShader(a,t),o.linkProgram(a),o.getProgramParameter(a,o.LINK_STATUS)||this.log.error(o.getProgramInfoLog(a)),a}};Y(mL,"UNAVAILABLE","unavailable"),Qi([hc(gs.INIT,"created",{sync:!0,fail(A){this.log.error("video gl context create failed",A.cause),ri.addFailedEvent({key:512700,error:A.cause||A})},success(){this.log.info("video context created use webgl"),ri.addSuccessEvent({key:512700})}})],mL.prototype,"create"),Qi([hc("created",gs.INIT,{ignoreError:!0,sync:!0,success(A){A&&this.emit(mL.UNAVAILABLE,A),this.removeAllListeners()}})],mL.prototype,"destroy");var qC=mL,pQ=class extends pL{constructor(){super(...arguments),Y(this,"ctx")}create(A){if(this.hasAlpha=A.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(pL._ids++),this.ctx=this._canvas.getContext("2d",{alpha:A.alpha,willReadFrequently:A.willReadFrequently}),!this.ctx)throw new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(A){let t="";A&&(t=A.message,this.error=A,ri.addFailedEvent({key:512703,error:A})),this.disconnect(),this.log.info("video context destroy ".concat(t?": ".concat(t):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),ri.addSuccessEvent({key:512703})}};function ZiA(A,t,o,a,l){arguments.length>5&&arguments[5]!==void 0&&arguments[5]&&([o,a]=[a,o]);let d={sWidth:A,sHeight:t,dWidth:o,dHeight:a,sx:0,sy:0,dx:0,dy:0};if(A===0||t===0)return d;switch(l){case void 0:case"fill":break;case"contain":{let h=Math.min(o/A,a/t);d.dWidth=A*h,d.dHeight=t*h,d.dx=(o-d.dWidth)/2,d.dy=(a-d.dHeight)/2;break}case"cover":{let h=Math.max(o/A,a/t),y=o/h,S=a/h;d.sx=(A-y)/2,d.sy=(t-S)/2,d.sWidth=y,d.sHeight=S;break}}return d}Qi([hc(gs.INIT,"created",{sync:!0,fail(A){this.log.error("video 2d context create failed",A.cause),ri.addFailedEvent({key:512701,error:A.cause||A})},success(){this.log.info("video context created use 2d"),ri.addSuccessEvent({key:512701})}})],pQ.prototype,"create"),Qi([hc("created",gs.INIT,{ignoreError:!0,sync:!0})],pQ.prototype,"destroy");var XiA=class{constructor(A,t){this.node=A,this.layout=t,Y(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},pz=class extends tC{constructor(A,t){super(A,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),Y(this,"inputs",[]),Y(this,"backgroundColor","black")}addInput(A,t){let o=0,a=this.inputs.length;for(;ot.zIndex))throw new Error("input already exists at zIndex ".concat(t.zIndex));a=d}}let l=new XiA(A,t);this.inputs.splice(o,0,l)}changeInputLayout(A,t){let o=this.inputs.findIndex(lA=>lA.node===A);if(o<0)return;let{x:a,y:l,width:d,height:h,zIndex:y,fillMode:S,rotation:L,hidden:V}=t;if(!ze(y)&&this.inputs.some(lA=>lA.layout.zIndex===y&&lA.node!==A))throw new Error("input already exists at zIndex ".concat(t.zIndex));let H=this.inputs[o];ze(a)||(H.layout.x=a),ze(l)||(H.layout.y=l),ze(d)||(H.layout.width=d),ze(h)||(H.layout.height=h),ze(L)||(H.layout.rotation=L),ze(V)||(H.layout.hidden=V),S&&(H.layout.fillMode=S),!ze(y)&&y!==H.layout.zIndex&&(H.layout.zIndex=y,this.inputs.sort((lA,hA)=>lA.layout.zIndex-hA.layout.zIndex))}hasInput(A){return this.inputs.some(t=>t.node===A)}hasNoInput(){return this.inputs.length===0}resize(A,t){if(!this.matchInputSize)return void super.resize(A,t);let o=this.inputs.reduce((a,l)=>l?Object.assign(a,{width:Math.max(a.width,l.right),height:Math.max(a.height,l.bottom)}):a,{width:0,height:0});super.resize(o.width,o.height),this.context instanceof qC&&this.inputs.forEach(a=>{if(a){let l=this.layout2texCoords(a);a.positionBuffer?this.changeBufferData(a.positionBuffer,l):a.positionBuffer=this.createBuffer(l)}})}connect(A){for(var t=arguments.length,o=new Array(t>1?t-1:0),a=1;at.node!==A),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(A){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((o,a)=>a.node.requestFrame(A)||o,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;ot.node.requestFrame(A)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t4&&arguments[4]!==void 0&&arguments[4];this.ctx2d&&(l&&([o,a]=[a,o]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(A,t,o,a),this.ctx2d.restore())}getInfo(){let{totalFrames:A,x:t,y:o,width:a,height:l,name:d}=this,h=Date.now(),y=(A-this.lastInfo.totalFrames)/((h-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:A,x:t,y:o,width:a,height:l,timestamp:h,fps:y,name:d},Di({parent:this.inputs.filter(S=>S).map(S=>S.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(A=>{var t;if(A.node.disconnect(),A.positionBuffer&&this.context instanceof qC)try{(t=this.context.ctx)==null||t.deleteBuffer(A.positionBuffer)}catch{}})}close(){super.close(),this.removeAllInputs()}},$iA=[1,0,0,0,1,1,0,1],Ny=class extends tC{constructor(A,t,o,a){if(super(A,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t}),Y(this,"mirror",!1),Y(this,"rotation",0),o&&(this.mirror=o),a&&(this.rotation=a),A instanceof qC)try{this.setTexBuffer($iA)}catch(l){A.destroy(new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(l.message||l)}))}}draw2d(A,t,o,a,l){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(a,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(l/a,a/l)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,l),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(l/a,a/l));let d=super.draw2d(A,t,o,a,l);return this.ctx2d.restore(),d}return!1}render(A){var t;return!((t=this.input)==null||!t.requestFrame(A))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}resize(A,t){iQ(this.rotation)&&([A,t]=[t,A]),super.resize(A,t)}},mj=class extends hL{constructor(A){super(arguments.length>1&&arguments[1]!==void 0?arguments[1]:4,bo),Y(this,"inputLocalVideoTracks",new Map),Y(this,"inputLocalScreenTracks",new Map),Y(this,"cameraNodeMap",new Map),Y(this,"screenNodeMap",new Map),Y(this,"textNodeMap",new Map),Y(this,"imageNodeMap",new Map),Y(this,"videoNodeMap",new Map),Y(this,"endedIds",new Set),Y(this,"videoContext"),Y(this,"mixNode"),Y(this,"destination"),Y(this,"manager"),Y(this,"stat"),Y(this,"_checkId",0),Y(this,"autoSetFps",!0),this.manager=A,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(tC.RENDER,t=>{this.emit("render",t)}),this.mixNode=new pz(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;this._checkId=kr.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:A})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new pQ({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(A){this.autoSetFps=!1,this.videoContext.frameRate=A;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var A;if(!this.autoSetFps)return;for(let l of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])l.shouldUpdate=!1;let t=null,o=0,a=!0;for(let[l,d]of this.inputLocalVideoTracks)if(d.profile.frameRate>o){if(this.endedIds.has(l)){let h=this.cameraNodeMap.get(l);h&&h.image.cancelVideoFrameCallback(h.videoCallbackId);continue}o=d.profile.frameRate,t=l}for(let[l,d]of this.inputLocalScreenTracks)if(d.profile.frameRate>o){if(this.endedIds.has(l)){let h=this.screenNodeMap.get(l);h&&h.image.cancelVideoFrameCallback(h.videoCallbackId);continue}o=d.profile.frameRate,t=l,a=!1}if(t!==null){let l=a?this.cameraNodeMap.get(t):this.screenNodeMap.get(t);l&&(l.shouldUpdate=!0,l.tryVideoFrameCallback()),this.log.info("set mix fps: ",o)}else(A=this.destination)==null||A.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(A){this.mixNode&&(this.mixNode.backgroundColor=A)}resizeMixCanvas(A,t){var o;(o=this.mixNode)==null||o.resize(A,t)}startMix(){return XA(this,null,function*(){var A;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Hp&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(A=this.manager)==null||A.changeInput(this)})}addCameraSource(A,t,o){if(this.inputLocalVideoTracks.has(A)||this.cameraNodeMap.has(A))throw new Error("There is already a cameraSource with the same ID: ".concat(A));let a,{mediaTrack:l}=t;if(!l)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,gd(this,Kc).add("videoInputRemoved",d=>{d.deviceId===t.deviceId&&(this.endedIds.add(A),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(A),this.updateCameraSource(A,o,t.mediaTrack)}),a=$d===16&&l instanceof CanvasCaptureMediaStreamTrack?this.videoContext.createVideoImageSource(l.canvas,{name:"cameraCanvasSource",logger:this.log}):this.videoContext.createVideoTrackSource(l,"cameraNodeSource"),a.resize(t.settings.width,t.settings.height),a.shouldUpdate=!1,this._connectMix(a,o,"cover"),this.inputLocalVideoTracks.set(A,t),this.cameraNodeMap.set(A,a),this.setFpsAuto()}addScreenSource(A,t,o){if(this.inputLocalScreenTracks.has(A)||this.screenNodeMap.has(A))throw new Error("There is already a screenSource with the same ID: ".concat(A));let{mediaTrack:a}=t;if(!a)throw new Error("no mediaTrack, add screenSource failed");t.on("output-media-track-changed",()=>{this.updateScreenSource(A,o,t.mediaTrack)});let l=this.videoContext.createVideoTrackSource(a,"screenNodeSource");l.resize(t.settings.width,t.settings.height),l.shouldUpdate=!1,this._connectMix(l,o),this.inputLocalScreenTracks.set(A,t),this.screenNodeMap.set(A,l),this.setFpsAuto()}addTextSource(A){let{id:t,content:o="",font:a,color:l,layout:d}=A;if(this.textNodeMap.has(t))throw new Error("There is already a textSource with the same ID: ".concat(t));let h=this.videoContext.createTextSource({content:o,font:a,color:l});h.resize(d.width,d.height),this._connectMix(h,d),this.textNodeMap.set(t,h)}addImageSource(A,t,o){if(this.imageNodeMap.has(A))throw new Error("There is already a imageSource with the same ID: ".concat(A));let a=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});a.resize(t.width,t.height),this._connectMix(a,o),this.imageNodeMap.set(A,a)}addVideoSource(A,t,o){if(this.videoNodeMap.has(A))throw new Error("There is already a videoSource with the same ID: ".concat(A));let a=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});a.resize(t.videoWidth,t.videoHeight),a.shouldUpdate=!1,this._connectMix(a,o),this.videoNodeMap.set(A,a)}updateCameraSource(A,t){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,a=arguments.length>3?arguments[3]:void 0,l=this.inputLocalVideoTracks.get(A);l&&o&&o!==l.mediaTrack&&(this.log.debug("updateCameraSource mixerLocalVideoTrack newTrack:",o,"oldTrack:",l.mediaTrack),l.setInputMediaStreamTrack(o));let d=this.cameraNodeMap.get(A);if(d){if(o){if($d===16&&o instanceof CanvasCaptureMediaStreamTrack)if(d instanceof m_){let S=d.output;d.close(),d=this.videoContext.createVideoImageSource(o.canvas,{name:"cameraCanvasSource",logger:this.log}),d.connect(S),this.cameraNodeMap.set(A,d)}else d.image=o.canvas;else if(d instanceof m_)d.replaceTrack(o);else{let S=d.output;d.close(),d=this.videoContext.createVideoTrackSource(o,"cameraNodeSource"),d.connect(S),this.cameraNodeMap.set(A,d)}let{width:h,height:y}=o.getSettings();h&&y&&d.resize(h,y)}a&&d.resize(a.width,a.height),(a||o)&&this.setFpsAuto(),this._changeMixLayout(d,t)}}updateScreenSource(A,t){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,a=this.inputLocalScreenTracks.get(A);this.log.debug("updateScreenSource mixerLocalScreenTrack",a,o),a&&o&&o!==a.mediaTrack&&a.setInputMediaStreamTrack(o);let l=this.screenNodeMap.get(A);l&&(o&&l.replaceTrack(o),this._changeMixLayout(l,t))}updateTextSource(A){let{id:t,content:o,font:a,color:l,layout:d}=A,h=this.textNodeMap.get(t);h&&(ze(o)||(h.content=o),ze(a)||(h.font=a),ze(l)||(h.color=l),h.resize(d.width,d.height),this._changeMixLayout(h,d))}updateImageSource(A,t,o){let a=this.imageNodeMap.get(A);a&&(o&&(a.image=o,a.resize(o.width,o.height)),this._changeMixLayout(a,t))}updateVideoSource(A,t,o){let a=this.videoNodeMap.get(A);if(a){if(o){let l=a.image;l instanceof HTMLVideoElement&&this.stopVideoElement(l),a.image=o,a.resize(o.videoWidth,o.videoHeight)}this._changeMixLayout(a,t)}}_connectMix(A,t){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"contain";if(!this.mixNode)return;let{mirror:a,rotation:l}=t;A.disconnect();let d=new Ny(this.videoContext,this.log,a,l);d=A.connect(d),t.fillMode||(t.fillMode=o),d.connect(this.mixNode,t)}_changeMixLayout(A,t){if(!this.mixNode)return;let{mirror:o,rotation:a}=t,l=A.output||A;l instanceof Ny&&(ze(o)||(l.mirror=o),ze(a)||(l.rotation=a),l.resize(A.width,A.height)),this.mixNode.changeInputLayout(l,t)}removeCameraSource(A){let t=this.inputLocalVideoTracks.get(A);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(A);let o=this.cameraNodeMap.get(A);o&&(o.output instanceof Ny&&o.output.close(),o.close(),this.cameraNodeMap.delete(A)),this.checkAfterRemove(!0)}removeScreenSource(A){let t=this.inputLocalScreenTracks.get(A);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(A);let o=this.screenNodeMap.get(A);o&&(o.output instanceof Ny&&o.output.close(),o.close(),this.screenNodeMap.delete(A)),this.checkAfterRemove(!0)}removeTextSource(A){let t=this.textNodeMap.get(A);t&&(t.output instanceof Ny&&t.output.close(),t.close(),this.textNodeMap.delete(A)),this.checkAfterRemove()}removeImageSource(A){let t=this.imageNodeMap.get(A);t&&(t.output instanceof Ny&&t.output.close(),t.close(),this.imageNodeMap.delete(A)),this.checkAfterRemove()}removeVideoSource(A){let t=this.videoNodeMap.get(A);t&&(t.output instanceof Ny&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(A)),this.checkAfterRemove()}checkAfterRemove(){arguments.length>0&&arguments[0]!==void 0&&arguments[0]&&this.setFpsAuto()}stopVideoElement(A){A.pause(),A.src="",A.srcObject=null,A.remove()}close(){var A;super.close(),kr.clearTask(this._checkId),(A=this.videoContext)==null||A.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),Vs(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}},fj=YA();if(typeof navigator<"u"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:fj,exposeOrigin:!0,permittedOrigins:["*"]})}catch{}var AoA=function(A){return XA(this,null,function*(){let t=null,o=function(d){let h={preferCurrentTab:d.preferDisplaySurface==="current-tab"||!!d.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},y={width:mg?{max:d.width}:{ideal:d.width,max:d.width},height:mg?{max:d.height}:{ideal:d.height,max:d.height},frameRate:d.frameRate,displaySurface:d.preferDisplaySurface||"monitor"};if(h.video=y,d.systemAudio){let{echoCancellation:S=!0,noiseSuppression:L=!1,autoGainControl:V=!1}=d;h.audio={echoCancellation:S,noiseSuppression:L,autoGainControl:V,sampleRate:48e3}}return h}(A);pA.info("getDisplayMedia with constraints: ".concat(JSON.stringify(o)));let a=yield navigator.mediaDevices.getDisplayMedia(o);A.systemAudio&&a.getAudioTracks().length===0&&($0&&nd<74||mg||gr)&&pA.warn("Your browser not support capture system audio");let l=a.getVideoTracks()[0];if(l){if(A.frameRate)try{yield l.applyConstraints({frameRate:{min:A.frameRate,ideal:A.frameRate},width:A.width,height:A.height})}catch(d){pA.warn("screen applyConstraints failed: ".concat(d))}A.captureElement&&(yield function(d,h){return XA(this,null,function*(){var y;if("CropTarget"in window&&"fromElement"in CropTarget&&ba(d.cropTo))try{if(((y=d.getCaptureHandle())==null?void 0:y.handle)!==fj)return;let S=yield CropTarget.fromElement(h);yield d.cropTo(S)}catch(S){pA.warn("cropTo target failed ".concat(S))}})}(l,A.captureElement))}if(A.audio){let d=function(h){let y={echoCancellation:h.echoCancellation,autoGainControl:h.autoGainControl,noiseSuppression:h.noiseSuppression,sampleRate:h.sampleRate,channelCount:h.channelCount};return ze(h.microphoneId)||(y.deviceId=h.microphoneId),{audio:y,video:!1}}(A);pA.info("getUserMedia with constraints: ".concat(JSON.stringify(d))),t=yield navigator.mediaDevices.getUserMedia(d),a.addTrack(t.getAudioTracks()[0])}return a})},eM=class extends QQ{constructor(A){super(A,2),Y(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),Y(this,"objectFit","contain"),Y(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}get isShareCurrentTab(){var A,t;try{return fj===((t=(A=this.mediaTrack)==null?void 0:A.getCaptureHandle())==null?void 0:t.handle)}catch{return}}capture(A){return XA(this,arguments,function(t){var o=this;let{systemAudio:a=!1,autoGainControl:l,echoCancellation:d,noiseSuppression:h,audioTrack:y,videoTrack:S,captureElement:L,preferDisplaySurface:V}=t;return function*(){var H;try{let lA,hA=Oo();return S||y?(lA=new MediaStream,S&&lA.addTrack(S),y&&lA.addTrack(y)):(lA=yield AoA({audio:!1,systemAudio:a,width:o.profile.width,height:o.profile.height,frameRate:o.profile.frameRate,autoGainControl:l,echoCancellation:d,noiseSuppression:h,captureElement:L,preferDisplaySurface:V}),o.sourceTrack=lA.getVideoTracks()[0]),yield o.setInputMediaStreamTrack(lA.getVideoTracks()[0]),F.emit(rA.LOCAL_TRACK_CAPTURE_SUCCESS,{track:o,cost:Oo()-hA,profile:o.profile,room:(H=o.manager)==null?void 0:H.room}),lA}catch(lA){throw o.log.error("getDisplayMedia error observed ".concat(lA)),lA instanceof li?lA:new li({code:mt.INITIALIZE_FAILED,name:lA.name,message:lA.message})}}()})}switchDevice(A){return XA(this,null,function*(){throw new Error("Method not implemented.")})}};Qi([Xv(function(A){this.setContentHint(A.contentHint||"detail")})],eM.prototype,"capture");var yj,Dj=class extends AM{constructor(A){super(A),this._log.id="s-".concat(this._log.id),this.isScreen=!0}addAudioProcessor(A,t,o){this.pipeline.silentNode.setNode(o),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(A),this.enableTrackAEC(!1)}removeAudioProcessor(A){this.pipeline.aec.node===A&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};function Sj(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,a=arguments.length>3?arguments[3]:void 0;return XA(this,null,function*(){let l=VI();yj||(yj=qg(l,URL.createObjectURL(new Blob(['registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;ty.connect(h,0,S)),new ReadableStream({start(y){h.port.onmessage=S=>{y.enqueue(S.data)}},cancel(){A.forEach(y=>y.disconnect(h)),h.port.close()}})})}var eoA=class extends CtA{constructor(A){super(),this.room=A,Y(this,"_localAudioTrack"),Y(this,"_localScreenAudioTrack"),Y(this,"log"),Y(this,"denoiser"),Y(this,"voiceChanger"),Y(this,"mixChangedDebounce"),Y(this,"audioProcessor"),Y(this,"encodePipeline",[]),Y(this,"decodePipeline",[]),Y(this,"getPCMAbortCtrlMap",new Map),Y(this,"audioFrameEventConfigMap",new Map),Y(this,"audioReferenceMap",new Map),Y(this,"isLocalAudioNeedAudioProcess",!1),Y(this,"isScreenAudioNeedAudioProcess",!1),this.log=pA.createLogger({parent:A?.getLogger(),id:"am",userId:A?.userId,sdkAppId:A?.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var A;return(A=this._localAudioTrack)==null?void 0:A.pipeline}get _localScreenAudioPipeline(){var A;return(A=this._localScreenAudioTrack)==null?void 0:A.pipeline}dump(A){var t,o;if(!this._localAudioTrack)return;let a=[],l=[];(t=this._localAudioPipline)!=null&&t.source.node&&(a.push(this._localAudioPipline.source.node),l.push("mic")),(o=this._localAudioPipline)!=null&&o.denoiser.node&&(a.push(this._localAudioPipline.denoiser.node),l.push("mic-processed")),this.mixWeight>1&&(a.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),l.push("mix")),this.log.info("dump audio track ".concat(l,", duration: ").concat(A));let d=new AbortController,h=[],y=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),d.abort("timeout")},1e3*A),S=()=>{for(let V=0;VV.pipeTo(new WritableStream({write(H){H.forEach((lA,hA)=>h[hA]=h[hA]?h[hA].concat(lA[0]):[lA[0]])}}),d).catch(H=>S));return{then:L.then.bind(L),download:S}}getPCM(A,t){var o,a,l;if(typeof WritableStream>"u")return void this.log.warn("getPCM failed: browser not support WritableStream");let{enable:d,sampleRate:h=48e3,channelCount:y=1,port:S}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!d)return;this.log.info("getPCM ".concat(t||"local"));let L,V,H=Math.floor(.04*h),lA=new Float32Array(H),hA=new Float32Array(H),MA=0,oe=new AbortController,fe=t===""?(o=this._localAudioTrack)==null?void 0:o.mediaTrack:(l=(a=this.room)==null?void 0:a.remotePublishedUserMap.get(t))==null?void 0:l.remoteAudioTrack.mediaTrack;if(fe)return Sj([VI().createMediaStreamSource(new MediaStream([fe]))],h,y,S).then(je=>je.pipeTo(new WritableStream({write(_e){_e[0][0]&&(MA+_e[0][0].length>H?(lA.set(_e[0][0].subarray(0,H-MA),MA),L=_e[0][0].subarray(H-MA),_e[0][1]&&(hA.set(_e[0][1].subarray(0,H-MA),MA),V=_e[0][1].subarray(H-MA)),MA+=H-MA):(L&&(lA.set(L,MA),MA+=L.length,L=void 0),V&&(hA.set(V,MA),V=void 0),lA.set(_e[0][0],MA),_e[0][1]&&hA.set(_e[0][1],MA),MA+=_e[0][0].length),MA>=H&&(MA=0,A({userId:t,sampleRate:h,channelCount:y,data:y===1?lA:[lA,hA]}),lA=new Float32Array(H),hA=new Float32Array(H)))}}),oe).catch(_e=>this.log.warn("stop getPCM reason:".concat(_e)))),oe;this.log.info("getPCM failed: ".concat(t||"local"," has no audio track"))}get hasScreenAudioTrack(){return!ze(this._localScreenAudioTrack)}get hasAudioTrack(){return!ze(this._localAudioTrack)}changeInput(A){var t,o;return A instanceof Dj?(this._localScreenAudioTrack=A,this.isScreenAudioNeedAudioProcess&&(t=this.audioProcessor)!=null&&t.screenAudioWorkletNode&&(A.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((a,l)=>{A.mixAudioReference(a,l)})),A.pipeline.connect(),this.mixOnChange()):A instanceof AM?(this._localAudioTrack=A,this.denoiser&&A.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&(o=this.audioProcessor)!=null&&o.localAudioWorkletNode&&(A.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((a,l)=>{A.mixAudioReference(a,l)})),A.pipeline.connect(),this.mixOnChange()):A instanceof y1?A.setOutputMediaStreamTrack(A.mediaTrack):void 0}mixAudioReference(A,t){var o;(o=this._localAudioTrack)==null||o.mixAudioReference(A,t)}unMixAudioReference(A){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(A)}setAudioReferenceVolume(A,t){var o;(o=this._localAudioTrack)==null||o.setAudioReferenceVolume(A,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var A,t;return delete this.mixChangedDebounce,Promise.all([(A=this._localAudioTrack)==null?void 0:A.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(A){A instanceof Dj?delete this._localScreenAudioTrack:A instanceof AM&&delete this._localAudioTrack}addDenoiser(A){var t;this.denoiser=A,(t=this._localAudioTrack)==null||t.addDenoiser(A)}addAudioProcessor(A,t,o,a){var l;this.audioProcessor={localAudioWorkletNode:o,mixNode:A,silentNode:t,screenAudioWorkletNode:a},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&o&&(this._localAudioTrack.addAudioProcessor(o,A,t),this.audioReferenceMap.forEach((d,h)=>{var y;(y=this._localAudioTrack)==null||y.mixAudioReference(d,h)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&a&&((l=this._localScreenAudioTrack)==null||l.addAudioProcessor(a,A,t),this.audioReferenceMap.forEach((d,h)=>{var y;(y=this._localScreenAudioTrack)==null||y.mixAudioReference(d,h)}))}removeDenoiser(A){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0:t.removeDenoiser(A)}addVoiceChanger(A,t){var o;this.voiceChanger=[A,t],(o=this._localAudioTrack)==null||o.pipeline.voiceChanger.setNode(A,t)}removeVoiceChanger(){var A;delete this.voiceChanger,(A=this._localAudioTrack)==null||A.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(A,t){var o,a;delete this.audioProcessor,(o=this._localAudioTrack)==null||o.removeAudioProcessor(A),(a=this._localScreenAudioTrack)==null||a.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(A=>A?.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor(A){let{processor:t,type:o}=A;var a;this.encodePipeline.includes(t)||(this.encodePipeline[o]=t,(a=this.room)==null||a.enableInsertableStreams())}addDecodeProcessor(A){let{processor:t,type:o}=A;var a;this.decodePipeline.includes(t)||(this.decodePipeline[o]=t,(a=this.room)==null||a.enableInsertableStreams())}removeEncodeProcessor(A){let{type:t}=A;this.encodePipeline[t]=void 0}removeDecodeProcessor(A){let{type:t}=A;this.decodePipeline[t]=void 0}handleLocalTrackStarted(A){let{room:t,userId:o}=A;var a;if(t!==this.room||this.getPCMAbortCtrlMap.get(o))return;let l=this.getPCM(d=>{var h;(h=this.room)==null||h.emit("audio-frame",d)},"");this.getPCMAbortCtrlMap.set(o,l),this.getPCMAbortCtrlMap.get(o)&&((a=this._localAudioTrack)==null||a.on("input-media-track-changed",()=>{let d=this.getPCMAbortCtrlMap.get(o);d&&(d.abort("inputMediaTrackChanged"),d=this.getPCM(h=>{var y;(y=this.room)==null||y.emit("audio-frame",h)},""),this.getPCMAbortCtrlMap.set(o,d))}))}handleLocalTrackStopped(A){let{room:t,userId:o}=A;if(t!==this.room)return;let a=this.getPCMAbortCtrlMap.get(o);a&&(a.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(o))}handleRemoteTrackStarted(A){let{room:t,userId:o}=A;if(t===this.room&&!this.getPCMAbortCtrlMap.get(o)){let a=this.room.audioManager.getPCM(l=>{var d;(d=this.room)==null||d.emit("audio-frame",l)},o);this.getPCMAbortCtrlMap.set(o,a)}}handleRemoteTrackStopped(A){let{room:t,userId:o}=A;if(t!==this.room)return;let a=this.getPCMAbortCtrlMap.get(o);a&&(a.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(o))}installEvent(){F.on("113",this.handleLocalTrackStarted,this),F.on("114",this.handleLocalTrackStopped,this),F.on("115",this.handleRemoteTrackStarted,this),F.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){F.off("113",this.handleLocalTrackStarted),F.off("114",this.handleLocalTrackStopped),F.off("115",this.handleRemoteTrackStarted),F.off("116",this.handleRemoteTrackStopped)}updateAudioReference(A){let{type:t,audioReference:o,refId:a,volume:l}=A;if(t==="add"){if(this.audioReferenceMap.get(a)||!o||(this.audioReferenceMap.set(a,o),!this.audioProcessor))return;this.mixAudioReference(o,a)}else if(t==="remove")this.audioReferenceMap.get(a)&&(this.audioReferenceMap.delete(a),this.unMixAudioReference(a));else if(t==="updateVolume"){if(!this.audioProcessor||ze(l))return;this.setAudioReferenceVolume(a,l)}}};function f1(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return Xr((o,a)=>function(){for(var l=arguments.length,d=new Array(l),h=0;h{let L=setTimeout(()=>{let V=new li({code:mt.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(a,"() timeout ").concat(A,"s")});(this.log||this._log||pA).warn(V),t===2?S(V):t===1&&y()},1e3*A);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(L),o.apply(this,d).then(y,S).finally(()=>{clearTimeout(L),this._checkPendingPromiseSet&&L&&this._checkPendingPromiseSet.delete(L)})})})}var tM=class IW extends aj{constructor(t,o,a){super({userId:o.userId,sdkAppId:t.sdkAppId,mediaType:a,room:t}),this.room=t,this.user=o,Y(this,"tinyId"),Y(this,"isRemote",!0),Y(this,"jitterBufferDelay",0),Y(this,"availableState"),Y(this,"remotePublishState"),Y(this,"_triggerCheckDecodeSubject",BQ(Ea(this,IW.STATE_SUBSCRIBE))),Y(this,"ignoreUpdatePlayingState"),this.tinyId=o.tinyId,this.availableState=new gs("".concat(o.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new gs("".concat(o.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),Ma(cj(Ea(this,gs.STATECHANGED),Ea(this.remotePublishState,gs.STATECHANGED)),Cj(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Dl(y=>{this.availableState.state!==(y?gs.ON:gs.OFF)&&(this.availableState.state=y?gs.ON:gs.OFF),(!this.isRemotePublished||!this.ignoreUpdatePlayingState)&&this.updatePlayingState(y)}));let l=Ma(Ea(this.player,Mo.ERROR),$v(y=>y.code===MediaError.MEDIA_ERR_DECODE)),d=Ma(uj(5e3),$v(()=>!!(!this.ignoreDecodeError&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived&&this.isRemotePublished)&&(!this.player.isPlaying&&!(this.kind===JA.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1)))),h=Ma(Z5(l,d),CE(Ea(this,gs.INIT)));Ma(this._triggerCheckDecodeSubject,$v(()=>!this.ignoreDecodeError),Q1(h),Dl(y=>{this.reportDecodeResult(!1,y)}))}setMute(t){this.isRemotePublished&&super.setMute(t)}setInputMediaStreamTrack(t){super.setInputMediaStreamTrack(t),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(t=>{this.mediaTrack?t():this.once("input-media-track-changed",t)})}get ignoreDecodeError(){var t,o,a,l;return(l=(a=(o=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:o.hadRecentBadDownlink)==null?void 0:a.call(o,2))!=null&&l||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===IW.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===gs.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(t){return t}unsubscribe(){this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(t,o){var a,l;let d=this.kind===JA.AUDIO;if(ri[t?"addSuccessEvent":"addFailedEvent"]({key:d?504700:514702}),!d){let h=((a=this.room)==null?void 0:a.downlinkVideoCodec.toUpperCase())||"H264";ri[t?"addSuccessEvent":"addFailedEvent"]({key:fy["DECODE_".concat(h,"_RESULT")]}),t||this.log.warn("".concat((l=this.room)==null?void 0:l.downlinkVideoCodec," decode failed"))}t||(ri.addEnum({key:d?504701:514703,value:Kp()}),ds.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(lQ()||jp()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===JA.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:o}))}updatePlayingState(t){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===t){if(t&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed: ".concat(this.isSubscribed," isAvailable: ").concat(this.isRemotePublished," hasTrack: ").concat(!!this.outMediaTrack," "));super.updatePlayingState(t)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?gs.ON:gs.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};Y(tM,"STATE_SUBSCRIBE","subscribe"),Qi([f1(5,1)],tM.prototype,"waitHasMediaTrack"),Qi([hc(gs.INIT,tM.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),F.emit(rA.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),wy(521716,!1)],tM.prototype,"subscribe"),Qi([hc(tM.STATE_SUBSCRIBE,gs.INIT,{sync:!0,success(){this.log.info("unsubscribed"),F.emit(rA.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],tM.prototype,"unsubscribe");var mz=tM,y1=class extends mz{constructor(A,t){super(A,t,1),Y(this,"volume",0),Y(this,"mediaType",1),Y(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=A.audioManager}get dbVolume(){return g1.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(A){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var A,t;return!!this.manager&&(this.manager.decodePipeline.some(o=>o)||((t=(A=this.player.element)==null?void 0:A.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&l_().AudioDecoder&&$p)}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(A){if(!this.manager)return A;let t=A;for(let[o,a]of this.manager.decodePipeline.entries()){if(!a)continue;let l={frame:A,track:this};if(o===1&&this.isAvailable&&this.room.role==="audience"&&(l.onAudioFrameNTPTime=d=>{let{ntp:h,frame:y,hasLeavingTag:S}=d;this.emit("audio-frame-with-ntp",{ntp:h,frame:y,hasLeavingTag:S})}),t=a(l),!t)return}return t}getAudioLevel(){if(!this.isAvailable)return 0;let A=this.volume||super.getAudioLevel();return A>1?1:A}getInternalAudioLevel(){return this.isAvailable?super.getInternalAudioLevel():0}get isRemotePublished(){return this.user.muteState.audioAvailable}},toA=class extends tC{constructor(A,t,o,a,l){super(A,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t}),this.setContainer=a,Y(this,"initStat",{alphaStitchingType:1}),Y(this,"end",BQ()),Y(this,"minSize",320),Y(this,"maxSize",1280),Y(this,"draggable",!1),Y(this,"startDragX",0),Y(this,"startDragY",0),Y(this,"left",0),Y(this,"top",0),Y(this,"baseWidth",320),Y(this,"baseRatio"),Y(this,"container"),this.initStat=l,this.draggable=o,this.bindDragEvents(),ri.addEnum({key:515700,value:1}),this.draggable&&ri.addEnum({key:515700,value:11})}bindDragEvents(){let A=this.context._canvas;if(A)if(this.draggable){let t=CE(this.end);Ma(Ea(A,"mousedown"),hj(this.startDrag.bind(this)),h1(()=>Ma(Ea(window,"mousemove"),CE(Ea(window,"mouseup")))),t,Dl(this.doDrag.bind(this))),Ma(Ea(A,"dblclick"),t,Dl(this.resetPosition.bind(this))),Ma(Ea(A,"wheel"),t,Dl(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(A){var t;return!((t=this.input)==null||!t.requestFrame(A))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}startDrag(A){A.preventDefault(),A.button===0&&(this.startDragX=A.clientX-this.left,this.startDragY=A.clientY-this.top)}renderCanvas(){let{container:A}=this;A||this.setContainer(),A&&this.baseRatio&&this.draggable&&(A.style.setProperty("width","".concat(this.baseWidth,"px")),A.style.setProperty("height","".concat(this.baseWidth/this.baseRatio,"px")),A.style.setProperty("position","fixed"),A.style.setProperty("left","".concat(this.left,"px")),A.style.setProperty("top","".concat(this.top,"px")))}doDrag(A){A.preventDefault(),this.left=A.clientX-this.startDragX,this.top=A.clientY-this.startDragY,this.renderCanvas()}handleZoom(A){A.preventDefault();let t=A.deltaY,o=this.context._canvas;o&&(this.baseWidth||(this.baseWidth=o.offsetWidth),this.baseWidth=t<0?Math.min(1.1*this.baseWidth,this.maxSize):Math.max(.9*this.baseWidth,this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(A,t,o,a,l){var d;let{ctx2d:h}=this,y=this.context._canvas;if(!h||!y)return!1;let S=super.draw2d(A,t,o,a,l),L=h.getImageData(0,0,a,l),{data:V}=L,H=!1;if(this.initStat.alphaStitchingType===1){let lA=Math.floor(a/2);for(let hA=0;hA=100;V[oe+3]=_e?255:0}H=super.draw2d(L,0,0,0,0,lA,l),y.width=lA}else if(this.initStat.alphaStitchingType===2){let lA=Math.floor(l/2);for(let hA=0;hA=100;V[oe+3]=_e?255:0}H=super.draw2d(L,0,0,0,0,a,lA),y.height=lA}return(d=this.context.ctx)==null||d.clearRect(0,0,a,l),S&&H}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}},fL=class extends mz{constructor(A,t){super(A,t,arguments.length>2&&arguments[2]!==void 0?arguments[2]:4),Y(this,"mediaType",4),Y(this,"source"),Y(this,"shouldRenderAlpha",!1),Y(this,"alphaNode"),Y(this,"shouldBeDraggable",!0),Y(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0,keyFramesDecoded:0}),Y(this,"_keyFrameCountLogged",!1),Y(this,"_keyFrameStartTimestamp",0),Y(this,"_keyFrameStartCount",0),Y(this,"_keyFrameIntervals",[]),Y(this,"_prevKeyFrameTimestamp",0),this.manager=A.videoManager,this.on("first-video-frame",o=>{this.room.emit("first-video-frame",o)}),this.on("first-frame-render",o=>{this.room.emit("first-frame-render",o)})}isAlphaSei(A){if(this.userId!==A.userId||A.seiPayloadType!==50)return!1;let t=new Uint8Array(A.data);return t.length%3==0&&t[0]===0&&t[1]===1&&t}play(A,t){return t!=null&&t.canvasRender&&!this.source&&this.useCanvasPlayer(),super.play(A,t).then(()=>{this.player.calculateStat(),F.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(A){let t=this.isAlphaSei(A);if(t)if(this.alphaNode){let o=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===o)return;this.alphaNode.initStat={alphaStitchingType:o};let a=this.player.getElement();if(a){let l=a.videoWidth/a.videoHeight;l&&(this.alphaNode.baseRatio=l*(o===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(o))}else this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2])}generateAlphaCanvasName(A){let t=Qy[A];return"".concat("alpha","_").concat(t,"_").concat(this.userId)}useCanvasPlayer(A){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let t=new pQ({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&A?this.generateAlphaCanvasName(A):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let o=new Qj(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&A){let a=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},l=new toA(t,this.log,this.shouldBeDraggable,a,{alphaStitchingType:A});this.source.connect(l),l.connect(o),this.alphaNode=l}else this.source.connect(o);Am()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(A){let t=this.decodeFPS,o=(a=t,[15,30,45,60].reduce((l,d)=>Math.abs(d-a)l.msg_user_info.str_identifier===this.userId))||{},o=this.mediaType===2?7:this.isSmall?3:2;if(!t||t.length===0)return 0;let a=t.find(l=>l.uint32_video_stream_type===o);return a?.uint32_video_dec_fps||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),F.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(A){if(!this.manager)return A;for(let t of this.manager.decodePipeline)if(t&&!(A=t({frame:A,track:this})))return;return A}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(A){this.room.changeType(A,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(A){A==="publish"||A==="both"||super.setMirror(A)}setDraggable(A){this.shouldBeDraggable=A,this.alphaNode&&(this.alphaNode.draggable=A,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(A){this.emit("decode-downgrade-state-changed",A)}updateKeyFramesDecoded(A){let t=this.stat.keyFramesDecoded||0;if(this.stat.keyFramesDecoded=A,this._keyFrameCountLogged)return;let o=Date.now();if(!this._keyFrameStartTimestamp)return this._keyFrameStartTimestamp=o,this._keyFrameStartCount=A,void(this._prevKeyFrameTimestamp=o);if(this._prevKeyFrameTimestamp&&A>t){let l=A-t,d=(o-this._prevKeyFrameTimestamp)/1e3/l;this._keyFrameIntervals.push(d)}this._prevKeyFrameTimestamp=o;let a=o-this._keyFrameStartTimestamp;if(a>=16e3){let l=A-this._keyFrameStartCount,d=l>0?a/1e3/l:0,h="".concat(l," keyframes in 16s ").concat(d," [").concat(this._keyFrameIntervals.map(S=>S.toFixed(1)).join(","),"] keyFramesDecoded ").concat(A),y=d<=2.5?"debug":"info";this.log[y](h),this._keyFrameCountLogged=!0}}},fz=class extends fL{constructor(A,t){super(A,t,2),Y(this,"mediaType",2),Y(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},f_=new Map;function Kg(A,t){let o=So(Di({},t),{timestamp:Vf()});f_.has(A)?f_.get(A).push(o):f_.set(A,[o])}function yz(){for(var A=arguments.length,t=new Array(A),o=0;ofunction(){for(var d=arguments.length,h=new Array(d),y=0;yty(L)?Iv(L):Ws(L)?L:Qg(L))},fnName:l,value:o},link:{className:d,fnName:l}})})}else if(!ze(t.type)&&Qg(o)!==t.type)throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_PARAMETER_TYPE,data:{key:a,rule:t,fnName:l,value:o},link:{className:d,fnName:l}})});if(t.allowEmpty===!1){let S=Ys(o)&&(o===0||Number.isNaN(o)),L=Ws(o)&&o.trim()==="";if(S||L)throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_PARAMETER_EMPTY,data:{key:a,rule:t,fnName:l,value:o},link:{className:d,fnName:l}})})}if(t.notLessThanZero&&Ys(o)&&o<0)throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.CANNOT_LESS_THAN_ZERO,data:{key:a,rule:t,fnName:l,value:o},link:{className:d,fnName:l}})});if(!ze(t.min)&&Ys(o)&&ot.max)throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_PARAMETER_MAX,data:{key:a,rule:t,fnName:l,value:o},link:{className:d,fnName:l}})});if(Ws(t.instanceOf)){if(!o||o._name!==t.instanceOf)throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_PARAMETER_INSTANCE,data:{key:a,rule:t,fnName:l,value:o},link:{className:d,fnName:l}})})}else if(ba(t.instanceOf)&&!(o instanceof t.instanceOf))throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_PARAMETER_INSTANCE,data:{key:a,rule:t,fnName:l,value:o},link:{className:d,fnName:l}})});if(t.values&&!t.values.includes(o))throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_PARAMETER_RANGE,data:{key:a,rule:t,fnName:l,value:o},link:{className:d,fnName:l}})});let{properties:h}=t;uE(h)&&ed(o)&&Object.keys(h).forEach(S=>{D1.call(this,{rule:h[S],value:o&&o[S],key:"".concat(a,".").concat(S),fnName:l,className:d})});let{arrayItem:y}=t;uE(y)&&ka(o)&&o.forEach((S,L)=>{D1.call(this,{rule:y,value:S,key:"".concat(a,"[").concat(L,"]"),fnName:l,className:d})}),ba(t.validate)&&t.validate.call(this,o,a,l,d,this)}F.on(rA.JOIN_SUCCESS,A=>{let{room:t}=A;Kg(t.userId,{eventId:32788})}),F.on(rA.LEAVE_START,A=>{let{room:t}=A;Kg(t.userId,{eventId:32789})}),F.on(rA.LOCAL_TRACK_PUBLISHED,A=>{let{track:t}=A;if(t.room){let o=32769;t.mediaType===4?o=32768:t.mediaType===2&&(o=32805),Kg(t.room.userId,{eventId:o})}}),F.on(rA.LOCAL_TRACK_UNPUBLISHED,A=>{let{track:t}=A;if(t.room){let o=32771;t.mediaType===4?o=32770:t.mediaType===2&&(o=32806),Kg(t.room.userId,{eventId:o})}}),F.on(rA.TRACK_MUTED,A=>{let{track:t}=A;t.room&&(t.kind===JA.AUDIO?Kg(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):Kg(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))}),F.on(rA.TRACK_UNMUTED,A=>{let{track:t}=A;t.room&&(t.kind===JA.AUDIO?Kg(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):Kg(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))}),F.on(rA.REMOTE_TRACK_SUBSCRIBED,A=>{let{track:t}=A;t.room&&(t.mediaType===1&&Kg(t.room.userId,{eventId:32777,remoteUserId:t.userId}),t.mediaType===4&&Kg(t.room.userId,{eventId:32776,remoteUserId:t.userId}),t.mediaType===8&&Kg(t.room.userId,{eventId:32803,remoteUserId:t.userId}))}),F.on(rA.REMOTE_TRACK_UNSUBSCRIBED,A=>{let{track:t}=A;t.room&&(t.mediaType===1&&Kg(t.room.userId,{eventId:32779,remoteUserId:t.userId}),t.mediaType===4&&Kg(t.room.userId,{eventId:32778,remoteUserId:t.userId}),t.mediaType===8&&Kg(t.room.userId,{eventId:32804,remoteUserId:t.userId}))}),F.on(rA.SWITCH_DEVICE_SUCCESS,A=>{let{track:t}=A;t.room&&Kg(t.room.userId,{eventId:t.kind===JA.VIDEO?32780:32781})}),F.on(rA.LOCAL_TRACK_REPLACED,A=>{let{track:t}=A;t.room&&Kg(t.room.userId,{eventId:t.kind===JA.VIDEO?32782:32783})}),F.on(rA.SIGNAL_CONNECTION_STATE_CHANGED,A=>{let t,{room:o,prevState:a,state:l}=A;switch(l){case"CONNECTED":t=a==="RECONNECTING"?32795:32791;break;case"DISCONNECTED":t=a==="RECONNECTING"?32796:32790;break;case"RECONNECTING":t=32794}t&&Kg(o.userId,{eventId:t})}),F.on(rA.PEER_CONNECTION_STATE_CHANGED,A=>{let t,{room:o,prevState:a,state:l,remoteUserId:d}=A,h=!!d;switch(l){case"CONNECTED":t=a==="RECONNECTING"?h?32801:32798:h?32793:32792;break;case"DISCONNECTED":a==="RECONNECTING"&&(t=h?32802:32799);break;case"RECONNECTING":t=h?32800:32797}t&&Kg(o.userId,{eventId:t,remoteUserId:d})}),F.on(rA.VIDEO_CODEC_IMPLEMENTATION_CHANGED,A=>{let{implementation:t,userId:o,remoteUserId:a,codec:l,isHWCodec:d,prevImplementation:h,streamType:y}=A,S=d?1:0;h||(S=d?3:2);let L={H264:0,H265:1,VP8:2}[l.toUpperCase()],V={eventId:4004,param1:S,param2:L,streamType:y||2};a&&(V.remoteUserId=a,V.eventId=4005),Kg(o,V),ri.addEnum({key:a?514701:513701,value:S}),ri.addEnum({key:a?514700:513700,value:L})}),F.on(rA.LOCAL_TRACK_RECAPTURE,A=>{let{track:t,error:o}=A;if(t.userId){let a={eventId:2003,param1:0};t.kind===JA.AUDIO?(a.streamType=1,o&&(a.param1=2)):(a.streamType=t.streamType==="auxiliary"?7:2,o&&(a.param1=8)),Kg(t.userId,a)}});var ooA=dc(Xl(),1),noA=class extends ooA.EventEmitter{constructor(A,t){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"userId";super(),this.mySelfId=A,this._log=t,this.key=o,Y(this,"userMap",new Map),Y(this,"remotePublishedUserMap",new Map),Y(this,"asrRobotUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(A=>A.isRobot)}getPublishedUser(A){return this.remotePublishedUserMap.get(A)}addUser(A){let t=A[this.key],{userId:o,tinyId:a,role:l,fromType:d}=A;if(d===D0)return void this.addAsrRobotUser(A);if(this.userMap.has(t))return;let h={userId:o,tinyId:a,role:l===20?"anchor":"audience"};this.userMap.set(t,h),this.emit("1",h)}addAsrRobotUser(A){let t=A[this.key],{userId:o,tinyId:a,role:l}=A;if(this.asrRobotUserMap.has(t))return;let d={userId:o,tinyId:a,role:l===20?"anchor":"audience"};this.asrRobotUserMap.set(t,d),this.emit("8",d)}deleteUser(A,t){let o=this.userMap.get(A);if(!o)return;if(this.asrRobotUserMap.has(A))return void this.deleteAsrRobotUser(A);let a="peer leave [".concat(A,"]");ze(t)||(a+=":".concat(l2[t])),this._log.info(a);let l=this.remotePublishedUserMap.get(A);if(l){let d=l.muteState;l.flag=0,this.emit("5",l.userId),this.deleteRemotePublishedUser(A),this.emit("6",{prevMuteState:d,muteState:l.muteState,flag:0})}this.userMap.delete(A),this.emit("2",{userId:o.userId,reason:t})}deleteAsrRobotUser(A){if(!this.asrRobotUserMap.has(A))return;let t=this.asrRobotUserMap.get(A);t&&(this.asrRobotUserMap.delete(A),this.emit("9",t))}setUserList(A){this.userMap.forEach(t=>{A.findIndex(o=>o[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),A.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(A){this.remotePublishedUserMap.has(A[this.key])||this.remotePublishedUserMap.set(A[this.key],A)}deleteRemotePublishedUser(A){this.remotePublishedUserMap.has(A)&&this.remotePublishedUserMap.delete(A)}setRemotePublishedUserList(A){this.remotePublishedUserMap.forEach(t=>{let o=t[this.key];if(A.findIndex(a=>a[this.key]===t[this.key])<0){this._log.info("remote [".concat(o,"] unpublish"));let a=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(o),this.emit("6",{prevMuteState:a,muteState:t.muteState,flag:0})}}),A.forEach(t=>{var o;let a=t[this.key];if(a===this.mySelfId)return void this.emit("7",t);let{flag:l,userId:d,tinyId:h,fromType:y}=t,S=kp(l,d),L=(o=this.remotePublishedUserMap.get(a))==null?void 0:o.muteState;if(L){let V=this.remotePublishedUserMap.get(a);V&&V.flag!==l&&(V.flag=l,this._log.info("remote publish updated: ".concat(JSON.stringify(V.muteState))),this.emit("6",{prevMuteState:L,muteState:S,flag:l}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(S))),this.addUser({userId:d,tinyId:h,role:20,fromType:y}),this.emit("3",t),this.emit("6",{prevMuteState:kp(0,d),muteState:S,flag:l})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}},soA=dc(Xl(),1),roA=class extends soA.default{constructor(){super(...arguments),Y(this,"_connectionTimeoutCount",0),Y(this,"_isFirewallRestrictionEventEmitted",!1)}increaseTimeoutCount(){this._connectionTimeoutCount+=1,this.checkAndEmitFirewallRestriction()}resetTimeoutCount(){this._connectionTimeoutCount=0}checkAndEmitFirewallRestriction(){this._connectionTimeoutCount>=3&&!this._isFirewallRestrictionEventEmitted&&(this._isFirewallRestrictionEventEmitted=!0,this.emit("firewall-restriction"))}destroy(){this._connectionTimeoutCount=0,this._isFirewallRestrictionEventEmitted=!1,this.removeAllListeners()}};function Dz(A){let{timesInSecond:t,maxSizeInSecond:o,getSize:a}=A;return Xr((l,d)=>{let h=new WeakMap;return F.on(rA.ROOM_DESTROY,y=>{let{room:S}=y;return h.delete(S)}),function(){let y=h.get(this);for(var S=arguments.length,L=new Array(S),V=0;V1e3&&(y.timestamp=Date.now(),y.callCountInSecond=0,y.totalSizeInSecond=0),a&&(y.totalSizeInSecond+=a(...L)),y.timestamp!==0&&Date.now()-y.timestamp<1e3&&(y.callCountInSecond>=t||y.totalSizeInSecond>o))throw new li({code:mt.INVALID_OPERATION,message:sn({key:Go.CALL_FREQUENCY_LIMIT,data:{isTimes:y.callCountInSecond>=t,isSize:y.totalSizeInSecond>o,name:d,timesInSecond:t,maxSizeInSecond:o}})});y.callCountInSecond++,l.call(this,...L)}})}var wt,Sz=!0,yL={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"},ko={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},S1=((wt=S1||{})[wt.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",wt[wt.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",wt[wt.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",wt[wt.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",wt[wt.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",wt[wt.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",wt[wt.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",wt[wt.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",wt[wt.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",wt[wt.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",wt[wt.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",wt[wt.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",wt[wt.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",wt[wt.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",wt[wt.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",wt[wt.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",wt[wt.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",wt[wt.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",wt[wt.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",wt[wt.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",wt[wt.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",wt[wt.INVALID_OPERATION=5100]="INVALID_OPERATION",wt[wt.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",wt[wt.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",wt[wt.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",wt[wt.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",wt[wt.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",wt[wt.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",wt[wt.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",wt[wt.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",wt[wt.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",wt[wt.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",wt[wt.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",wt[wt.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",wt[wt.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",wt[wt.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",wt[wt.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",wt[wt.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",wt[wt.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",wt[wt.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",wt[wt.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",wt[wt.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",wt[wt.DEVICE_ERROR=5300]="DEVICE_ERROR",wt[wt.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",wt[wt.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",wt[wt.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",wt[wt.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",wt[wt.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",wt[wt.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",wt[wt.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",wt[wt.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",wt[wt.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",wt[wt.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",wt[wt.SERVER_ERROR=5400]="SERVER_ERROR",wt[wt.NEED_TO_BUY=5401]="NEED_TO_BUY",wt[wt.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",wt[wt.OPERATION_FAILED=5500]="OPERATION_FAILED",wt[wt.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",wt[wt.REJOIN_FAILED=5502]="REJOIN_FAILED",wt[wt.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",wt[wt.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",wt[wt.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",wt[wt.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",wt[wt.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",wt[wt.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",wt[wt.OPERATION_ABORT=5998]="OPERATION_ABORT",wt[wt.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",wt),vz=So(Di({},Cc),{INVALID_PARAMETER(A){let{fnName:t}=A;return"the parameters of the '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(A){let{key:t,rule:o,fnName:a,value:l}=A;return"'".concat(t||o.name,"' is a required param when calling ").concat(a,"(), received: ").concat(l,".")},INVALID_PARAMETER_TYPE(A){let{key:t,rule:o,fnName:a,value:l}=A,d="".concat(t||o.name),h="";return h=Array.isArray(o.type)?o.type.join("|"):o.type,"'".concat(d,"' must be type of ").concat(h," when calling ").concat(a,"(), received type: ").concat(Qg(l),".")},INVALID_PARAMETER_EMPTY(A){let{key:t,rule:o,fnName:a,value:l}=A;return"'".concat(t||o.name,"' cannot be '").concat(l,"' when calling ").concat(a,"().")},INVALID_PARAMETER_INSTANCE(A){let{key:t,rule:o,fnName:a,value:l}=A,d="".concat(t||o.name),h="".concat(o.instanceOf.name||o.instanceOf);return"'".concat(d,"' must be instanceof ").concat(h," when calling ").concat(a,"(), received type: ").concat(Qg(l),".")},INVALID_PARAMETER_RANGE(A){let{key:t,rule:o,fnName:a,value:l}=A;return"'".concat(t||o.name,"' must be one of ").concat(o.values.join("|")," when calling ").concat(a,"(), received: ").concat(l,".")},INVALID_PARAMETER_LESS_THAN_ZERO(A){let{key:t,rule:o,fnName:a}=A;return"'".concat(t||o.name,"' cannot be less than 0 when calling ").concat(a,"().")},INVALID_PARAMETER_MIN(A){let{key:t,rule:o,value:a}=A;return"the min value of ".concat(t||o.name," is ").concat(o.min,", received: ").concat(a,".")},INVALID_PARAMETER_MAX(A){let{key:t,rule:o,value:a}=A;return"the max value of ".concat(t||o.name," is ").concat(o.max,", received: ").concat(a,".")},INVALID_ELEMENT_ID(A){let{key:t,fnName:o}=A;return"'".concat(t,"' is not found in the document object when calling ").concat(o,"().")},INVALID_ELEMENT_ID_TYPE(A){let{key:t,fnName:o,type:a}=A;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(o,"(), received: ").concat(a,".")},INVALID_STREAM_ID(A){let{key:t}=A;return"'".concat(t,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING(A){let{key:t}=A;return"'".concat(t,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(A){let{key:t}=A;return"'".concat(t,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(A){let{key:t}=A;return"'".concat(t,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIRED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_ROOM_ID_TYPE_MISMATCH(A){let{key:t}=A;return"The type of target roomId must match the current roomId. Current room is using '".concat(t,"', but received '").concat(t==="strRoomId"?"roomId":"strRoomId","'.")},INVALID_ROOM_ID_DUPLICATE(A){let{key:t}=A;return"the target '".concat(t,"' must not be the same as the current '").concat(t,"'.")},INVALID_STREAM_TYPE:A=>{let{fnName:t}=A;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(A){let{fnName:t}=A;return"the API '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(A){let{fnName:t}=A;return"cannot ".concat(t," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(A){let{fnName:t,value:o}=A;return"cannot ".concat(t," because remote user(userId: ").concat(o.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(A){let{fnName:t,value:o}=A;return"cannot ".concat(t," because remote user(userId: ").concat(o.userId,") does not publishing ").concat(o.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(A){let{fnName:t}=A;return"you are already ".concat(t,"(), cannot repeated call '").concat(t,"'.")},INVALID_OPERATION_NEED_VIDEO(A){let{fnName:t}=A;return"cannot call '".concat(t,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(A){let{fnName:t}=A;return"cannot call '".concat(t,"' because the microphone or screen share is not turned on.")},INVALID_BUFFER_EMPTY:A=>{let{key:t}=A;return"the buffer size of paramerter '".concat(t,"' cannot be empty")},INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:A=>{let{fnName:t}=A;return"you need to call ".concat(t,"() after publish stream.")},ENV_NOT_SUPPORTED(A){let{fnName:t}=A;return"the current browser does not support the capability of the function '".concat(t,"' you are calling, please check the API documentation.")},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION(A){let{fnName:t}=A;return"cannot call ".concat(t," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(A){let{fnName:t,error:o}=A;return"'".concat(t,"' got device exception").concat(o?", error: ".concat(o.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(A){let{fnName:t,deviceType:o=iM(t),error:a}=A;return"NotFoundError, no ".concat(o," detected, please check your device and the configuration on '").concat(t,"'").concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(A){let{fnName:t,deviceType:o=iM(t),error:a}=A;return"NotAllowedError, you have disabled ".concat(o," access, please allow the current application to use the ").concat(o).concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(A){let{fnName:t,deviceType:o=iM(t),error:a}=A;return"NotReadableError, the ".concat(o," maybe in use by another APP, please check if the device is pre-occupied by another APP.")},DEVICE_OVERCONSTRAINED_ERROR(A){let{fnName:t,deviceType:o=iM(t),error:a}=A;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(A){let{fnName:t,deviceType:o=iM(t),error:a}=A;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(o).concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_SECURITY_ERROR(A){let{fnName:t,deviceType:o=iM(t),error:a}=A;return"SecurityError, check whether the system security policy restricts the use of the ".concat(o,", and it is recommended to turn on the ").concat(o," after the user interacts with the page").concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_ABORT_ERROR(A){let{fnName:t,deviceType:o=iM(t),error:a}=A;return"AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal".concat(a?" error: ".concat(a.toString(),"."):".")},CAMERA_RECOVER_FAILED(A){let{error:t}=A;return"camera recover capture failed ".concat(t?.name||"",": ").concat(t?.originMessage||t?.message)},MICROPHONE_RECOVER_FAILED(A){let{error:t}=A;return"microphone recover capture failed ".concat(t?.name||"",": ").concat(t?.originMessage||t?.message)},OPERATION_FAILED(A){let{fnName:t,error:o}=A;return"'".concat(t,"' failed, reason: ").concat(o?.toString())},FIREWALL_RESTRICTION:()=>"media connection failure due to firewall restrictions, please try to change your network.",EVENT_HANDLER_ERROR(A){let{eventName:t}=A;return"an error was caught on trtc.on('".concat(t,"', handler), please check your code on 'handler'.")},VIDEO_CONTEXT_ERROR(A){let{reason:t,error:o}=A;return"video context error ".concat(t," ").concat(o?.name||""," ").concat(o?.message||"")},SERVER_ERROR(A){let{fnName:t,error:o}=A;return"'".concat(t,"' got server error: ").concat(o?.toString(),", please check the SDK documentation.")},NEED_TO_BUY(A){let{value:t,url:o}=A;return"You need to buy packages for ".concat(t,". Refer to: ").concat(o)},ACCOUNT_NO_MONEY:A=>{let{fnParams:t}=A;return"your TRTC account run out of credit, please recharge.".concat(t.sdkAppId?" SDKAppId: ".concat(t.sdkAppId):"")},OPERATION_ABORT(A){let{fnName:t}=A;return"'".concat(t,"' abort")},UNKNOWN_ERROR(A){let{fnName:t,error:o}=A;return"'".concat(t,"' throw unknown exception").concat(o?", error: ".concat(o.toString(),"."):".")}});function iM(A){if(!A)return"camera";let t=A.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var aoA=class SY extends Error{constructor(t){let{code:o,extraCode:a,message:l="",messageParams:d,fnName:h="",originError:y,data:S}=t;var L;let V;V=l||function(H){let lA,{code:hA,params:MA,enableDocLink:oe=!1}=H,fe="",je=S1[hA];try{lA=vz[je]}catch{lA=vz.UNKNOWN_ERROR}return ba(lA)?fe=lA(MA):Ws(lA)&&(fe=lA),MA.fnName&&!fe.includes(MA.fnName)&&(fe[fe.length-1]!=="."&&(fe+="."),fe+=" thrown from ".concat(MA.fnName,"()")),oe&&(fe+=" doc:"),fe}({code:o===ko.SERVER_ERROR?o:a||o,params:Di({fnName:h,error:y},d)}),super(V),Y(this,"name","RtcError"),Y(this,"code"),Y(this,"extraCode"),Y(this,"functionName"),Y(this,"message"),Y(this,"data"),Y(this,"handler"),Y(this,"originError"),this.name=S1[o],this.code=o,this.extraCode=a,this.functionName=h,this.originError=y,this.message=V,this.data=S,this.extraCode===5302&&(L=this.originError)!=null&&L.message.includes("system")&&(this.handler=()=>{let H=document.createElement("a");gy?H.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):rQ&&(H.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),H.href.length>0&&H.click()})}static convertFrom(t,o,a){let l=t;if(t instanceof li){let{stack:d}=t,h={code:ko.UNKNOWN_ERROR,fnName:o,originError:t};switch(t.getCode()){case mt.INVALID_PARAMETER:h.code=ko.INVALID_PARAMETER,h.message=t.message;break;case mt.INVALID_OPERATION:h.code=ko.INVALID_OPERATION,h.message=t.message;break;case mt.NOT_SUPPORTED:case mt.NOT_SUPPORTED_H264:h.code=ko.ENV_NOT_SUPPORTED,t.getCode()===mt.NOT_SUPPORTED_H264&&(h.extraCode=t.message.includes(Cc.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case mt.JOIN_ROOM_FAILED:h.messageParams={fnParams:a};case mt.SERVER_TIMEOUT:case mt.SWITCH_ROLE_FAILED:case mt.SWITCH_ROOM_FAILED:h.code=ko.SERVER_ERROR,h.extraCode=t.getExtraCode();break;case mt.API_CALL_ABORTED:h.code=ko.OPERATION_ABORT;break;case mt.DEVICE_NOT_FOUND:case mt.DEVICE_AUTO_RECOVER_FAILED:case mt.INITIALIZE_FAILED:h.code=5300,t.name&&(h.extraCode=function(y){let S;switch(y){case"NotFoundError":S=5301;break;case"NotAllowedError":S=5302;break;case"NotReadableError":S=5303;break;case"OverconstrainedError":S=5304;break;case"InvalidStateError":S=5305;break;case"SecurityError":S=5306;break;case"AbortError":S=5307;break;default:S=5300}return S}(t.name));break;case mt.VIDEO_ENCODE_FAILED:h.extraCode=5505;case mt.AUDIO_ENCODE_FAILED:h.extraCode=5506,h.code=ko.OPERATION_FAILED;break;case mt.UNKNOWN:break;default:h.code=ko.OPERATION_FAILED}l=new SY(h),d&&(l.stack+=d.substr(d.indexOf(` -`)))}else{if(t instanceof SY)return t;l=new SY({code:ko.UNKNOWN_ERROR,fnName:o,originError:t})}return l}},Lo=aoA;function iC(A){return A==="sub"?"auxiliary":A==="auxiliary"?"sub":"main"}function v1(A){return A===yL.QOS_PREFERENCE_CLEAR?"detail":A===yL.QOS_PREFERENCE_SMOOTH?"motion":""}function M1(A,t){let o=t?A2:Av;return T2(A)?Di(Di({},o),A):FC[A]?FC[A]:o}var Mz={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},Rz={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},y_={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(A,t,o){if(Ws(A)&&!document.getElementById(A))throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5009,fnName:o,messageParams:{key:t}})}},wz={name:"userId",required:!0,type:"string"},_z={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function D_(A,t){if(!A)throw new Lo({code:ko.INVALID_OPERATION,extraCode:5101,fnName:t})}function Tz(A,t,o){if(!A)throw new Lo({code:ko.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:o}})}function Nz(A,t,o){if(!(/^[1-9]\d*$/.test(String(A))&&A<4294967295))throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:o}})}function Gz(A,t,o){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(A))throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:o}})}function bz(A){var t;if((t=A?.option)==null||!t.small)return;if(!xv())return pA.warn("small stream is not supported"),void delete A.option.small;let o=M1(A.option.profile),a=M1(A.option.small,!0);return((l,d)=>l.width*l.height>=d.width*d.height&&l.frameRate>=d.frameRate&&l.bitrate>=d.bitrate)(o,a)?void 0:(pA.warn("small stream profile must be less than big stream profile. Big: ".concat(JSON.stringify(o),", Small: ").concat(JSON.stringify(a))),void delete A.option.small)}var goA={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(A,t,o){if(this._room.isJoined)throw new Lo({code:ko.INVALID_OPERATION,extraCode:5104,fnName:o});if(A.roomId){if(Ws(A.roomId))throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5016,fnName:o,messageParams:{key:t}});Nz(A.roomId,o,t)}else{if(!A.strRoomId)throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5015,fnName:o});Gz(A.strRoomId,o,t)}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:y_,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:Mz},validate(A){var t,o;if(((t=A?.option)==null||!t.videoTrack)&&Qu())throw new Lo({code:ko.ENV_NOT_SUPPORTED,extraCode:5201});(o=A?.option)!=null&&o.small&&bz(A)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:So(Di({},y_),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:Mz},validate(A){var t;(t=A?.option)!=null&&t.small&&bz(A)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:_z},validate(A){var t;if(((t=A?.option)==null||!t.audioTrack)&&Qu())throw new Lo({code:ko.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:_z}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:y_,publish:{type:"boolean"},option:Rz},validate(A,t,o,a,l){var d;if((d=A?.option)==null||!d.videoTrack){if(Qu())throw new Lo({code:ko.ENV_NOT_SUPPORTED,extraCode:5201});if(!Xp())throw new Lo({code:ko.ENV_NOT_SUPPORTED,fnName:o,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:y_,publish:{type:"boolean"},option:Rz}},muteRemoteAudio:[wz,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[wz,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:y_,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(A,t,o){D_(this._room.isJoined,o);let a=this._room.remotePublishedUserMap.get(A.userId);if(Tz(!!a,o,A),a&&(A.streamType==="main"&&!a.muteState.videoAvailable||A.streamType==="sub"&&!a.muteState.hasAuxiliary))throw new Lo({code:ko.INVALID_OPERATION,extraCode:5103,fnName:o,messageParams:{value:A}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:So(Di({},y_),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(A,t,o){D_(this._room.isJoined,o);let a=this._room.remotePublishedUserMap.get(A.userId);if(Tz(!!a,o,A),a){if(A.streamType==="main"&&!a.muteState.videoAvailable||A.streamType==="sub"&&!a.muteState.hasAuxiliary)throw new Lo({code:ko.INVALID_OPERATION,extraCode:5103,fnName:o,messageParams:{value:A}});if(A.option){let l=A.streamType==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack;if((A.option.pictureInPicture||A.option.fullScreen||A.option.fullScreen)&&(!l.isSubscribed||!l.player.isPlaying))throw new Lo({code:ko.INVALID_OPERATION,message:"cannot set pictureInPicture or fullScreen when remote video is not playing"})}}}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(A,t,o){if(A.userId!=="*"&&ze(A.streamType))throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5014,fnName:o})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(A,t,o){D_(this._room.isJoining||this._room.isJoined,o)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(A,t,o,a){if(!$k)throw new Lo({code:ko.ENV_NOT_SUPPORTED,fnName:o,extraCode:5207});if(!this._room.enableSEI)throw new Lo({code:ko.INVALID_OPERATION,fnName:o,extraCode:5108});if(A.byteLength>1e3)throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5018,fnName:o});if(A.byteLength===0)throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:o});D_(this._room.isJoined,o)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(A,t,o){if(!A&&!this._room.isMainStreamPublished||A&&!this._room.isAuxStreamPublished)throw new Lo({code:ko.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:o})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(A,t,o,a){if(A.byteLength>1e3)throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5018,fnName:o});if(A.byteLength===0)throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5017,fnName:o,messageParams:{key:t}})}}},validate(A,t,o){if(D_(this._room.isJoined,o),this._room.scene==="live"&&this._room.role==="audience")throw new Lo({code:ko.INVALID_OPERATION,extraCode:5107,fnName:o,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(A,t,o){if(D_(this._room.isJoined,o),this._room.useStringRoomId&&A.strRoomId===this._room.roomId||!this._room.useStringRoomId&&A.roomId===Number(this._room.roomId))throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5020,fnName:o,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(A.roomId&&this._room.useStringRoomId||!A.roomId&&A.strRoomId&&!this._room.useStringRoomId)throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5019,fnName:o,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(A.roomId)Nz(A.roomId,o,t);else{if(!A.strRoomId)throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5015,fnName:o});Gz(A.strRoomId,o,t)}},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},eI={TRTC:goA},oC=class extends Error{};function coA(A,t){let o=iy(A);for(let a=0;a!0),Y(this,"mergeUpdate",coA);let a=O_.instances.get(t);a?a.set(o,this):O_.instances.set(t,new Map([[o,this]]))}static get(t,o){if(!o)return;let a=O_.instances.get(t);return a&&a.get(o)||new O_(t,o)}static gets(t,o){let a=O_.instances.get(t),l=[];return a&&a.forEach((d,h)=>{o.test(h)&&l.push(d)}),l}action(t,o,a){let l=y=>{var S;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(S=this.currentOp)==null||S.action(),y},d=y=>{var S,L;throw this.ops.shift(),t===0&&((S=this.currentOp)==null?void 0:S.type)===2&&this.ops.shift().reject(new oC("start failed")),(L=this.currentOp)==null||L.action(),y},h={type:t,action:()=>o(...h.args).then(l,d),args:a,resolve:loA,reject:IoA};try{switch(this.state){case 1:if(t===0)throw new oC("already started");break;case 4:if(t===2)throw new oC("not started");break;default:return this.cacheOp(h)}}catch(y){return Promise.reject(y)}return this.ops.push(h),h.promise=o(...h.args).then(l,d)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new oC("already start");break;case 3:switch(t.type){case 2:throw new oC("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new oC("unknown state")}else switch(t.type){case 3:if(this.lastOpType===3)return this.lastOp.promise;{let a=new oC("keep stop");if(this.ops.slice(1).forEach(l=>l.reject(a)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,t.args),this.lastOp.promise;case 3:throw new oC("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new oC("start not allowed after update");case 0:throw new oC("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new oC("keep start")),new oC("already start")}}t.promise=new Promise((a,l)=>{t._resolve?t._resolve.then(a):t.resolve=a,t._reject?t._reject.catch(l):t.reject=l});let{action:o}=t;return t.action=()=>o().then(t.resolve,t.reject),this.ops.push(t),t.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};Y(kz,"instances",new WeakMap);var DL=kz,R1=new WeakMap,w1=(A,t)=>{if(t instanceof oC){let{stack:o}=t;t=new Lo({code:ko.OPERATION_ABORT,message:"".concat(A," abort: ").concat(t.message),fnName:A}),o&&(t.stack+=o.substr(o.indexOf(` -`)))}throw t};function oM(A,t){return Xr((o,a)=>function(){for(var l=arguments.length,d=new Array(l),h=0;hfunction(){for(var h=arguments.length,y=new Array(h),S=0;S{var MA,oe;let fe=(MA=R1.get(this))==null?void 0:MA.get(H(...y));if(fe){let{timeoutId:_e,resolve:vi}=fe;clearTimeout(_e),vi()}let je=setTimeout(()=>{if(L.state===3||L.state===4)return lA();L.action(2,l.bind(this),y).catch(w1.bind(null,d)).then(lA,hA)},V);R1.has(this)?(oe=R1.get(this))==null||oe.set(H(...y),{timeoutId:je,resolve:lA}):R1.set(this,new Map([[H(...y),{timeoutId:je,resolve:lA}]]))})}return L.action(2,l.bind(this),y).catch(w1.bind(null,d))})}function nM(A){return Xr((t,o)=>function(){for(var a=arguments.length,l=new Array(a),d=0;dS.action(3,()=>Promise.resolve(),l))).then(()=>t.call(this,...l));let y=DL.get(this,h);return y?y.action(3,t.bind(this),l).catch(w1.bind(null,o)):t.apply(this,l)})}function sM(){return function(A,t,o){return A.prototype[t]=function(){let a=this._log||console,l='"'.concat(t,'" is a static method. Use TRTC.').concat(t,"() instead. See: ").concat(zh,"/en/TRTC.html#.").concat(t);a.warn(l)},o}}var Ao={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed",REALTIME_TRANSCRIBER_MESSAGE:"realtime-transcriber-message",REALTIME_TRANSCRIBER_STATE_CHANGED:"realtime-transcriber-state-changed",PICTURE_IN_PICTURE_STATE_CHANGED:"picture-in-picture-state-changed",FULL_SCREEN_STATE_CHANGED:"full-screen-state-changed"},uoA=new Set([Ao.AUDIO_VOLUME,Ao.AUDIO_FRAME,Ao.NETWORK_QUALITY,Ao.STATISTICS,Ao.SEI_MESSAGE,Ao.CUSTOM_MESSAGE,Ao.LAYER_DATA]),Lz={};Wh(Lz,{ScheduleRequestType:()=>Oz,getAbilityConfig:()=>EoA,getScheduleDomain:()=>Mj,isNeedToSchedule:()=>SL,scheduleProxy:()=>rm,sendScheduleRequest:()=>Fz,setIsNeedToSchedule:()=>mQ,setScheduleProxy:()=>vj});var _1=null,T1=0,Uz=72e5,N1="trtc_schedule_cache",SL=!0;function mQ(A){br(A)&&A!==SL&&(SL=A,pA.info("setIsNeedToSchedule ".concat(A)),A?function(){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.removeItem(N1)}catch(t){pA.error("clearScheduleCache error",t)}}():T1=Date.now()+Uz)}function Fz(A){return XA(this,arguments,function(t){let{userId:o,sdkAppId:a,useStringRoomId:l,roomId:d,userSig:h,version:y,frameWorkType:S,role:L,latencyLevel:V}=t;return function*(){var H;if(!SL&&_1&&T1>Date.now())return{isCached:!0,result:_1};let lA={delta:0,count:[1,1],msg:[],detail:[]};try{let hA=new FormData;hA.append("userId",String(o)),hA.append("sdkAppId",String(a)),hA.append("isStrGroupId",String(l)),hA.append("groupId",String(d)),hA.append("sdkVersion",y),hA.append("userSig",String(h));let MA=((H=yield Tv())==null?void 0:H.model)||Tk();MA&&hA.append("model",MA);let oe=jp();oe&&hA.append("osString",oe);let fe=qp();fe&&hA.append("gpu",fe),L&&hA.append("role",String(L)),V&&hA.append("latencyLevel",String(V)),S&&hA.append("frameWorkType",String(S));let je=Oo(),_e=yield function(Fe,Dt,pi){return new Promise((Mi,Wo)=>{let zo=null;uv([Pz(vs=>Dt.count[0]=vs+1,vs=>{let{error:Zo,retry:Vn,retriedCount:yg,retryFuncArgs:wa}=vs;Dt.msg[0]=Zo.message,zo||(yg>=1&&(wa[0]=Gy(pi,"config",JA.MAIN,!0)),Vn())})(Gy(pi,"config",JA.MAIN),Fe,{get timeout(){return 1e3*Ay(2+Dt.count[0])}}),Pz(vs=>Dt.count[1]=vs+1,vs=>{let{error:Zo,retry:Vn,retriedCount:yg,retryFuncArgs:wa}=vs;Dt.msg[1]=Zo.message,zo||(yg>=2&&(wa[0]=Gy(pi,"config",JA.BACKUP,!0)),Vn())})(Gy(pi,"config",JA.BACKUP),Fe,{get timeout(){return 1e3*Ay(2+Dt.count[1])}})]).then(vs=>{zo=vs,Mi(zo)}).catch(Wo)})}(hA,lA,a);_e.config&&(_e.config.loggerDomain&&XS(_e.config.loggerDomain),br(_e.config.scheduleCache)&&mQ(!_e.config.scheduleCache)),lA.delta=Oo()-je;let vi=function(Fe,Dt,pi){let Mi={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let Wo=performance.getEntriesByType("resource"),zo=Gy(Fe,"config",JA.MAIN),vs=Gy(Fe,"config",JA.BACKUP);for(let Zo of Wo)if(Zo.startTime>=pi&&(Zo.name===zo||Zo.name===vs)&&Zo.transferSize>0){let Vn=Zo.name===zo?JA.MAIN:JA.BACKUP,yg=Math.round(Zo.duration),wa=Math.round(Zo.domainLookupStart-Zo.startTime),fu=Zo.redirectStart>0?Math.round(Zo.redirectEnd-Zo.redirectStart):0,_L=Zo.fetchStart>0?Math.round(Zo.domainLookupStart-Zo.fetchStart):0,__=Math.round(Zo.domainLookupEnd-Zo.domainLookupStart),O8=Math.round(Zo.requestStart-Zo.secureConnectionStart),P8=Math.round(Zo.secureConnectionStart-Zo.connectStart),x8=Math.round(Zo.responseStart-Zo.requestStart),Y8=Math.round(Zo.responseEnd-Zo.responseStart),xnA=[__,O8,P8,x8,Y8];ds.uploadEvent({log:"stat-schedule-net:".concat(yg,"(").concat(wa,"(").concat(fu,"->").concat(_L,")->").concat(xnA.join("->"),") ").concat(Vn),userId:Dt}),Mi=So(Di({},Mi),{totalCost:yg,local:wa,dns:__,tcp:P8,tls:O8,request:x8,response:Y8});break}}catch(Wo){pA.error("getScheduleDetailCost error",Wo)}return Mi}(Number(a),o,je);return _1=_e,function(Fe){if(typeof window<"u"&&typeof localStorage<"u")try{let Dt=Date.now()+Uz;localStorage.setItem(N1,JSON.stringify({result:Fe,expireIn:Dt})),T1=Dt}catch(Dt){pA.error("saveScheduleToLocalStorage error",Dt)}}(_e),{isCached:!1,result:_e,detailCost:vi}}catch(hA){let MA=ka(hA)?hA[0]:hA,oe=Ys(MA.code)?MA.code:0,fe="schedule failed".concat(MA.message?": ".concat(MA.message):""),je=new li({code:mt.SCHEDULE_FAILED,extraCode:oe,message:sn({key:Go.JOIN_ROOM_FAILED,data:{error:fe,code:oe}})});throw pA.error(fe,oe),je}}()})}typeof document<"u"&&document.head.insertAdjacentHTML("beforeend",Object.values(tQ).map(A=>'')).join(`\r +} `),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(A){let t="";return A&&(t=A.message,this.error=A,ri.addFailedEvent({key:512702,error:A})),this.disconnect(),this.log.info("video context destroy".concat(t)?": ".concat(t):""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),A}set width(A){var t;(t=this.ctx)==null||t.viewport(0,0,A,this.height),super.width=A,this._canvas2d&&(this._canvas2d.width=A)}set height(A){var t;(t=this.ctx)==null||t.viewport(0,0,this.width,A),super.height=A,this._canvas2d&&(this._canvas2d.height=A)}setSize(A,t){var o;(o=this.ctx)==null||o.viewport(0,0,A,t),super.setSize(A,t),this._canvas2d&&(this._canvas2d.width=A,this._canvas2d.height=t)}createShader(A,t){let o=this.ctx,a=o.createShader(A);return o.shaderSource(a,t),o.compileShader(a),a}createProgram(A,t){let o=this.ctx,a=o.createProgram();return o.attachShader(a,A),o.attachShader(a,t),o.linkProgram(a),o.getProgramParameter(a,o.LINK_STATUS)||this.log.error(o.getProgramInfoLog(a)),a}};Y(mL,"UNAVAILABLE","unavailable"),Qi([hc(gs.INIT,"created",{sync:!0,fail(A){this.log.error("video gl context create failed",A.cause),ri.addFailedEvent({key:512700,error:A.cause||A})},success(){this.log.info("video context created use webgl"),ri.addSuccessEvent({key:512700})}})],mL.prototype,"create"),Qi([hc("created",gs.INIT,{ignoreError:!0,sync:!0,success(A){A&&this.emit(mL.UNAVAILABLE,A),this.removeAllListeners()}})],mL.prototype,"destroy");var qC=mL,pQ=class extends pL{constructor(){super(...arguments),Y(this,"ctx")}create(A){if(this.hasAlpha=A.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(pL._ids++),this.ctx=this._canvas.getContext("2d",{alpha:A.alpha,willReadFrequently:A.willReadFrequently}),!this.ctx)throw new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(A){let t="";A&&(t=A.message,this.error=A,ri.addFailedEvent({key:512703,error:A})),this.disconnect(),this.log.info("video context destroy ".concat(t?": ".concat(t):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),ri.addSuccessEvent({key:512703})}};function ZiA(A,t,o,a,l){arguments.length>5&&arguments[5]!==void 0&&arguments[5]&&([o,a]=[a,o]);let d={sWidth:A,sHeight:t,dWidth:o,dHeight:a,sx:0,sy:0,dx:0,dy:0};if(A===0||t===0)return d;switch(l){case void 0:case"fill":break;case"contain":{let h=Math.min(o/A,a/t);d.dWidth=A*h,d.dHeight=t*h,d.dx=(o-d.dWidth)/2,d.dy=(a-d.dHeight)/2;break}case"cover":{let h=Math.max(o/A,a/t),y=o/h,S=a/h;d.sx=(A-y)/2,d.sy=(t-S)/2,d.sWidth=y,d.sHeight=S;break}}return d}Qi([hc(gs.INIT,"created",{sync:!0,fail(A){this.log.error("video 2d context create failed",A.cause),ri.addFailedEvent({key:512701,error:A.cause||A})},success(){this.log.info("video context created use 2d"),ri.addSuccessEvent({key:512701})}})],pQ.prototype,"create"),Qi([hc("created",gs.INIT,{ignoreError:!0,sync:!0})],pQ.prototype,"destroy");var XiA=class{constructor(A,t){this.node=A,this.layout=t,Y(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},pz=class extends tC{constructor(A,t){super(A,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:t}),Y(this,"inputs",[]),Y(this,"backgroundColor","black")}addInput(A,t){let o=0,a=this.inputs.length;for(;ot.zIndex))throw new Error("input already exists at zIndex ".concat(t.zIndex));a=d}}let l=new XiA(A,t);this.inputs.splice(o,0,l)}changeInputLayout(A,t){let o=this.inputs.findIndex(lA=>lA.node===A);if(o<0)return;let{x:a,y:l,width:d,height:h,zIndex:y,fillMode:S,rotation:L,hidden:V}=t;if(!ze(y)&&this.inputs.some(lA=>lA.layout.zIndex===y&&lA.node!==A))throw new Error("input already exists at zIndex ".concat(t.zIndex));let H=this.inputs[o];ze(a)||(H.layout.x=a),ze(l)||(H.layout.y=l),ze(d)||(H.layout.width=d),ze(h)||(H.layout.height=h),ze(L)||(H.layout.rotation=L),ze(V)||(H.layout.hidden=V),S&&(H.layout.fillMode=S),!ze(y)&&y!==H.layout.zIndex&&(H.layout.zIndex=y,this.inputs.sort((lA,hA)=>lA.layout.zIndex-hA.layout.zIndex))}hasInput(A){return this.inputs.some(t=>t.node===A)}hasNoInput(){return this.inputs.length===0}resize(A,t){if(!this.matchInputSize)return void super.resize(A,t);let o=this.inputs.reduce((a,l)=>l?Object.assign(a,{width:Math.max(a.width,l.right),height:Math.max(a.height,l.bottom)}):a,{width:0,height:0});super.resize(o.width,o.height),this.context instanceof qC&&this.inputs.forEach(a=>{if(a){let l=this.layout2texCoords(a);a.positionBuffer?this.changeBufferData(a.positionBuffer,l):a.positionBuffer=this.createBuffer(l)}})}connect(A){for(var t=arguments.length,o=new Array(t>1?t-1:0),a=1;at.node!==A),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(A){let t=this.context.ctx;if(t.clearColor(0,0,0,0),this.inputs.reduce((o,a)=>a.node.requestFrame(A)||o,!1)&&t){this.useProgram(),t.enable(t.BLEND),t.blendFunc(t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;ot.node.requestFrame(A)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let t=0;t4&&arguments[4]!==void 0&&arguments[4];this.ctx2d&&(l&&([o,a]=[a,o]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(A,t,o,a),this.ctx2d.restore())}getInfo(){let{totalFrames:A,x:t,y:o,width:a,height:l,name:d}=this,h=Date.now(),y=(A-this.lastInfo.totalFrames)/((h-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:A,x:t,y:o,width:a,height:l,timestamp:h,fps:y,name:d},Di({parent:this.inputs.filter(S=>S).map(S=>S.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(A=>{var t;if(A.node.disconnect(),A.positionBuffer&&this.context instanceof qC)try{(t=this.context.ctx)==null||t.deleteBuffer(A.positionBuffer)}catch{}})}close(){super.close(),this.removeAllInputs()}},$iA=[1,0,0,0,1,1,0,1],Ny=class extends tC{constructor(A,t,o,a){if(super(A,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:t}),Y(this,"mirror",!1),Y(this,"rotation",0),o&&(this.mirror=o),a&&(this.rotation=a),A instanceof qC)try{this.setTexBuffer($iA)}catch(l){A.destroy(new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(l.message||l)}))}}draw2d(A,t,o,a,l){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(a,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(l/a,a/l)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,l),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(l/a,a/l));let d=super.draw2d(A,t,o,a,l);return this.ctx2d.restore(),d}return!1}render(A){var t;return!((t=this.input)==null||!t.requestFrame(A))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}resize(A,t){iQ(this.rotation)&&([A,t]=[t,A]),super.resize(A,t)}},mj=class extends hL{constructor(A){super(arguments.length>1&&arguments[1]!==void 0?arguments[1]:4,bo),Y(this,"inputLocalVideoTracks",new Map),Y(this,"inputLocalScreenTracks",new Map),Y(this,"cameraNodeMap",new Map),Y(this,"screenNodeMap",new Map),Y(this,"textNodeMap",new Map),Y(this,"imageNodeMap",new Map),Y(this,"videoNodeMap",new Map),Y(this,"endedIds",new Set),Y(this,"videoContext"),Y(this,"mixNode"),Y(this,"destination"),Y(this,"manager"),Y(this,"stat"),Y(this,"_checkId",0),Y(this,"autoSetFps",!0),this.manager=A,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(tC.RENDER,t=>{this.emit("render",t)}),this.mixNode=new pz(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;this._checkId=kr.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:A})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new pQ({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(A){this.autoSetFps=!1,this.videoContext.frameRate=A;for(let t of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])t.shouldUpdate=!1;setTimeout(()=>{var t;return(t=this.destination)==null?void 0:t.start(this.videoContext.frameRate)},500)}setFpsAuto(){var A;if(!this.autoSetFps)return;for(let l of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])l.shouldUpdate=!1;let t=null,o=0,a=!0;for(let[l,d]of this.inputLocalVideoTracks)if(d.profile.frameRate>o){if(this.endedIds.has(l)){let h=this.cameraNodeMap.get(l);h&&h.image.cancelVideoFrameCallback(h.videoCallbackId);continue}o=d.profile.frameRate,t=l}for(let[l,d]of this.inputLocalScreenTracks)if(d.profile.frameRate>o){if(this.endedIds.has(l)){let h=this.screenNodeMap.get(l);h&&h.image.cancelVideoFrameCallback(h.videoCallbackId);continue}o=d.profile.frameRate,t=l,a=!1}if(t!==null){let l=a?this.cameraNodeMap.get(t):this.screenNodeMap.get(t);l&&(l.shouldUpdate=!0,l.tryVideoFrameCallback()),this.log.info("set mix fps: ",o)}else(A=this.destination)==null||A.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(A){this.mixNode&&(this.mixNode.backgroundColor=A)}resizeMixCanvas(A,t){var o;(o=this.mixNode)==null||o.resize(A,t)}startMix(){return XA(this,null,function*(){var A;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Hp&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(A=this.manager)==null||A.changeInput(this)})}addCameraSource(A,t,o){if(this.inputLocalVideoTracks.has(A)||this.cameraNodeMap.has(A))throw new Error("There is already a cameraSource with the same ID: ".concat(A));let a,{mediaTrack:l}=t;if(!l)throw new Error("no mediaTrack, add cameraSource failed");t.recaptureMode=1,gd(this,Kc).add("videoInputRemoved",d=>{d.deviceId===t.deviceId&&(this.endedIds.add(A),this.setFpsAuto())}),t.on("output-media-track-changed",()=>{this.endedIds.delete(A),this.updateCameraSource(A,o,t.mediaTrack)}),a=$d===16&&l instanceof CanvasCaptureMediaStreamTrack?this.videoContext.createVideoImageSource(l.canvas,{name:"cameraCanvasSource",logger:this.log}):this.videoContext.createVideoTrackSource(l,"cameraNodeSource"),a.resize(t.settings.width,t.settings.height),a.shouldUpdate=!1,this._connectMix(a,o,"cover"),this.inputLocalVideoTracks.set(A,t),this.cameraNodeMap.set(A,a),this.setFpsAuto()}addScreenSource(A,t,o){if(this.inputLocalScreenTracks.has(A)||this.screenNodeMap.has(A))throw new Error("There is already a screenSource with the same ID: ".concat(A));let{mediaTrack:a}=t;if(!a)throw new Error("no mediaTrack, add screenSource failed");t.on("output-media-track-changed",()=>{this.updateScreenSource(A,o,t.mediaTrack)});let l=this.videoContext.createVideoTrackSource(a,"screenNodeSource");l.resize(t.settings.width,t.settings.height),l.shouldUpdate=!1,this._connectMix(l,o),this.inputLocalScreenTracks.set(A,t),this.screenNodeMap.set(A,l),this.setFpsAuto()}addTextSource(A){let{id:t,content:o="",font:a,color:l,layout:d}=A;if(this.textNodeMap.has(t))throw new Error("There is already a textSource with the same ID: ".concat(t));let h=this.videoContext.createTextSource({content:o,font:a,color:l});h.resize(d.width,d.height),this._connectMix(h,d),this.textNodeMap.set(t,h)}addImageSource(A,t,o){if(this.imageNodeMap.has(A))throw new Error("There is already a imageSource with the same ID: ".concat(A));let a=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});a.resize(t.width,t.height),this._connectMix(a,o),this.imageNodeMap.set(A,a)}addVideoSource(A,t,o){if(this.videoNodeMap.has(A))throw new Error("There is already a videoSource with the same ID: ".concat(A));let a=this.videoContext.createVideoImageSource(t,{autoResize:!1,logger:this.log});a.resize(t.videoWidth,t.videoHeight),a.shouldUpdate=!1,this._connectMix(a,o),this.videoNodeMap.set(A,a)}updateCameraSource(A,t){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,a=arguments.length>3?arguments[3]:void 0,l=this.inputLocalVideoTracks.get(A);l&&o&&o!==l.mediaTrack&&(this.log.debug("updateCameraSource mixerLocalVideoTrack newTrack:",o,"oldTrack:",l.mediaTrack),l.setInputMediaStreamTrack(o));let d=this.cameraNodeMap.get(A);if(d){if(o){if($d===16&&o instanceof CanvasCaptureMediaStreamTrack)if(d instanceof m_){let S=d.output;d.close(),d=this.videoContext.createVideoImageSource(o.canvas,{name:"cameraCanvasSource",logger:this.log}),d.connect(S),this.cameraNodeMap.set(A,d)}else d.image=o.canvas;else if(d instanceof m_)d.replaceTrack(o);else{let S=d.output;d.close(),d=this.videoContext.createVideoTrackSource(o,"cameraNodeSource"),d.connect(S),this.cameraNodeMap.set(A,d)}let{width:h,height:y}=o.getSettings();h&&y&&d.resize(h,y)}a&&d.resize(a.width,a.height),(a||o)&&this.setFpsAuto(),this._changeMixLayout(d,t)}}updateScreenSource(A,t){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,a=this.inputLocalScreenTracks.get(A);this.log.debug("updateScreenSource mixerLocalScreenTrack",a,o),a&&o&&o!==a.mediaTrack&&a.setInputMediaStreamTrack(o);let l=this.screenNodeMap.get(A);l&&(o&&l.replaceTrack(o),this._changeMixLayout(l,t))}updateTextSource(A){let{id:t,content:o,font:a,color:l,layout:d}=A,h=this.textNodeMap.get(t);h&&(ze(o)||(h.content=o),ze(a)||(h.font=a),ze(l)||(h.color=l),h.resize(d.width,d.height),this._changeMixLayout(h,d))}updateImageSource(A,t,o){let a=this.imageNodeMap.get(A);a&&(o&&(a.image=o,a.resize(o.width,o.height)),this._changeMixLayout(a,t))}updateVideoSource(A,t,o){let a=this.videoNodeMap.get(A);if(a){if(o){let l=a.image;l instanceof HTMLVideoElement&&this.stopVideoElement(l),a.image=o,a.resize(o.videoWidth,o.videoHeight)}this._changeMixLayout(a,t)}}_connectMix(A,t){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"contain";if(!this.mixNode)return;let{mirror:a,rotation:l}=t;A.disconnect();let d=new Ny(this.videoContext,this.log,a,l);d=A.connect(d),t.fillMode||(t.fillMode=o),d.connect(this.mixNode,t)}_changeMixLayout(A,t){if(!this.mixNode)return;let{mirror:o,rotation:a}=t,l=A.output||A;l instanceof Ny&&(ze(o)||(l.mirror=o),ze(a)||(l.rotation=a),l.resize(A.width,A.height)),this.mixNode.changeInputLayout(l,t)}removeCameraSource(A){let t=this.inputLocalVideoTracks.get(A);if(!t)return;t.close(),this.inputLocalVideoTracks.delete(A);let o=this.cameraNodeMap.get(A);o&&(o.output instanceof Ny&&o.output.close(),o.close(),this.cameraNodeMap.delete(A)),this.checkAfterRemove(!0)}removeScreenSource(A){let t=this.inputLocalScreenTracks.get(A);if(!t)return;t.close(),this.inputLocalScreenTracks.delete(A);let o=this.screenNodeMap.get(A);o&&(o.output instanceof Ny&&o.output.close(),o.close(),this.screenNodeMap.delete(A)),this.checkAfterRemove(!0)}removeTextSource(A){let t=this.textNodeMap.get(A);t&&(t.output instanceof Ny&&t.output.close(),t.close(),this.textNodeMap.delete(A)),this.checkAfterRemove()}removeImageSource(A){let t=this.imageNodeMap.get(A);t&&(t.output instanceof Ny&&t.output.close(),t.close(),this.imageNodeMap.delete(A)),this.checkAfterRemove()}removeVideoSource(A){let t=this.videoNodeMap.get(A);t&&(t.output instanceof Ny&&t.output.close(),t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image),t.close(),this.videoNodeMap.delete(A)),this.checkAfterRemove()}checkAfterRemove(){arguments.length>0&&arguments[0]!==void 0&&arguments[0]&&this.setFpsAuto()}stopVideoElement(A){A.pause(),A.src="",A.srcObject=null,A.remove()}close(){var A;super.close(),kr.clearTask(this._checkId),(A=this.videoContext)==null||A.destroy(),delete this.mixNode,delete this.destination;for(let t of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])t.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),Vs(this);for(let t of this.videoNodeMap.values())t.image instanceof HTMLVideoElement&&this.stopVideoElement(t.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}},fj=YA();if(typeof navigator<"u"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:fj,exposeOrigin:!0,permittedOrigins:["*"]})}catch{}var AoA=function(A){return XA(this,null,function*(){let t=null,o=function(d){let h={preferCurrentTab:d.preferDisplaySurface==="current-tab"||!!d.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},y={width:fg?{max:d.width}:{ideal:d.width,max:d.width},height:fg?{max:d.height}:{ideal:d.height,max:d.height},frameRate:d.frameRate,displaySurface:d.preferDisplaySurface||"monitor"};if(h.video=y,d.systemAudio){let{echoCancellation:S=!0,noiseSuppression:L=!1,autoGainControl:V=!1}=d;h.audio={echoCancellation:S,noiseSuppression:L,autoGainControl:V,sampleRate:48e3}}return h}(A);pA.info("getDisplayMedia with constraints: ".concat(JSON.stringify(o)));let a=yield navigator.mediaDevices.getDisplayMedia(o);A.systemAudio&&a.getAudioTracks().length===0&&($0&&nd<74||fg||gr)&&pA.warn("Your browser not support capture system audio");let l=a.getVideoTracks()[0];if(l){if(A.frameRate)try{yield l.applyConstraints({frameRate:{min:A.frameRate,ideal:A.frameRate},width:A.width,height:A.height})}catch(d){pA.warn("screen applyConstraints failed: ".concat(d))}A.captureElement&&(yield function(d,h){return XA(this,null,function*(){var y;if("CropTarget"in window&&"fromElement"in CropTarget&&ba(d.cropTo))try{if(((y=d.getCaptureHandle())==null?void 0:y.handle)!==fj)return;let S=yield CropTarget.fromElement(h);yield d.cropTo(S)}catch(S){pA.warn("cropTo target failed ".concat(S))}})}(l,A.captureElement))}if(A.audio){let d=function(h){let y={echoCancellation:h.echoCancellation,autoGainControl:h.autoGainControl,noiseSuppression:h.noiseSuppression,sampleRate:h.sampleRate,channelCount:h.channelCount};return ze(h.microphoneId)||(y.deviceId=h.microphoneId),{audio:y,video:!1}}(A);pA.info("getUserMedia with constraints: ".concat(JSON.stringify(d))),t=yield navigator.mediaDevices.getUserMedia(d),a.addTrack(t.getAudioTracks()[0])}return a})},eM=class extends QQ{constructor(A){super(A,2),Y(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),Y(this,"objectFit","contain"),Y(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}get isShareCurrentTab(){var A,t;try{return fj===((t=(A=this.mediaTrack)==null?void 0:A.getCaptureHandle())==null?void 0:t.handle)}catch{return}}capture(A){return XA(this,arguments,function(t){var o=this;let{systemAudio:a=!1,autoGainControl:l,echoCancellation:d,noiseSuppression:h,audioTrack:y,videoTrack:S,captureElement:L,preferDisplaySurface:V}=t;return function*(){var H;try{let lA,hA=Oo();return S||y?(lA=new MediaStream,S&&lA.addTrack(S),y&&lA.addTrack(y)):(lA=yield AoA({audio:!1,systemAudio:a,width:o.profile.width,height:o.profile.height,frameRate:o.profile.frameRate,autoGainControl:l,echoCancellation:d,noiseSuppression:h,captureElement:L,preferDisplaySurface:V}),o.sourceTrack=lA.getVideoTracks()[0]),yield o.setInputMediaStreamTrack(lA.getVideoTracks()[0]),F.emit(rA.LOCAL_TRACK_CAPTURE_SUCCESS,{track:o,cost:Oo()-hA,profile:o.profile,room:(H=o.manager)==null?void 0:H.room}),lA}catch(lA){throw o.log.error("getDisplayMedia error observed ".concat(lA)),lA instanceof li?lA:new li({code:mt.INITIALIZE_FAILED,name:lA.name,message:lA.message})}}()})}switchDevice(A){return XA(this,null,function*(){throw new Error("Method not implemented.")})}};Qi([Xv(function(A){this.setContentHint(A.contentHint||"detail")})],eM.prototype,"capture");var yj,Dj=class extends AM{constructor(A){super(A),this._log.id="s-".concat(this._log.id),this.isScreen=!0}addAudioProcessor(A,t,o){this.pipeline.silentNode.setNode(o),this.pipeline.mixNode.setNode(t),this.pipeline.aec.setNode(A),this.enableTrackAEC(!1)}removeAudioProcessor(A){this.pipeline.aec.node===A&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};function Sj(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,a=arguments.length>3?arguments[3]:void 0;return XA(this,null,function*(){let l=VI();yj||(yj=Kg(l,URL.createObjectURL(new Blob(['registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;ty.connect(h,0,S)),new ReadableStream({start(y){h.port.onmessage=S=>{y.enqueue(S.data)}},cancel(){A.forEach(y=>y.disconnect(h)),h.port.close()}})})}var eoA=class extends CtA{constructor(A){super(),this.room=A,Y(this,"_localAudioTrack"),Y(this,"_localScreenAudioTrack"),Y(this,"log"),Y(this,"denoiser"),Y(this,"voiceChanger"),Y(this,"mixChangedDebounce"),Y(this,"audioProcessor"),Y(this,"encodePipeline",[]),Y(this,"decodePipeline",[]),Y(this,"getPCMAbortCtrlMap",new Map),Y(this,"audioFrameEventConfigMap",new Map),Y(this,"audioReferenceMap",new Map),Y(this,"isLocalAudioNeedAudioProcess",!1),Y(this,"isScreenAudioNeedAudioProcess",!1),this.log=pA.createLogger({parent:A?.getLogger(),id:"am",userId:A?.userId,sdkAppId:A?.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var A;return(A=this._localAudioTrack)==null?void 0:A.pipeline}get _localScreenAudioPipeline(){var A;return(A=this._localScreenAudioTrack)==null?void 0:A.pipeline}dump(A){var t,o;if(!this._localAudioTrack)return;let a=[],l=[];(t=this._localAudioPipline)!=null&&t.source.node&&(a.push(this._localAudioPipline.source.node),l.push("mic")),(o=this._localAudioPipline)!=null&&o.denoiser.node&&(a.push(this._localAudioPipline.denoiser.node),l.push("mic-processed")),this.mixWeight>1&&(a.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),l.push("mix")),this.log.info("dump audio track ".concat(l,", duration: ").concat(A));let d=new AbortController,h=[],y=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),d.abort("timeout")},1e3*A),S=()=>{for(let V=0;VV.pipeTo(new WritableStream({write(H){H.forEach((lA,hA)=>h[hA]=h[hA]?h[hA].concat(lA[0]):[lA[0]])}}),d).catch(H=>S));return{then:L.then.bind(L),download:S}}getPCM(A,t){var o,a,l;if(typeof WritableStream>"u")return void this.log.warn("getPCM failed: browser not support WritableStream");let{enable:d,sampleRate:h=48e3,channelCount:y=1,port:S}=(t===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(t)||this.audioFrameEventConfigMap.get("*"))||{};if(!d)return;this.log.info("getPCM ".concat(t||"local"));let L,V,H=Math.floor(.04*h),lA=new Float32Array(H),hA=new Float32Array(H),MA=0,oe=new AbortController,fe=t===""?(o=this._localAudioTrack)==null?void 0:o.mediaTrack:(l=(a=this.room)==null?void 0:a.remotePublishedUserMap.get(t))==null?void 0:l.remoteAudioTrack.mediaTrack;if(fe)return Sj([VI().createMediaStreamSource(new MediaStream([fe]))],h,y,S).then(je=>je.pipeTo(new WritableStream({write(_e){_e[0][0]&&(MA+_e[0][0].length>H?(lA.set(_e[0][0].subarray(0,H-MA),MA),L=_e[0][0].subarray(H-MA),_e[0][1]&&(hA.set(_e[0][1].subarray(0,H-MA),MA),V=_e[0][1].subarray(H-MA)),MA+=H-MA):(L&&(lA.set(L,MA),MA+=L.length,L=void 0),V&&(hA.set(V,MA),V=void 0),lA.set(_e[0][0],MA),_e[0][1]&&hA.set(_e[0][1],MA),MA+=_e[0][0].length),MA>=H&&(MA=0,A({userId:t,sampleRate:h,channelCount:y,data:y===1?lA:[lA,hA]}),lA=new Float32Array(H),hA=new Float32Array(H)))}}),oe).catch(_e=>this.log.warn("stop getPCM reason:".concat(_e)))),oe;this.log.info("getPCM failed: ".concat(t||"local"," has no audio track"))}get hasScreenAudioTrack(){return!ze(this._localScreenAudioTrack)}get hasAudioTrack(){return!ze(this._localAudioTrack)}changeInput(A){var t,o;return A instanceof Dj?(this._localScreenAudioTrack=A,this.isScreenAudioNeedAudioProcess&&(t=this.audioProcessor)!=null&&t.screenAudioWorkletNode&&(A.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((a,l)=>{A.mixAudioReference(a,l)})),A.pipeline.connect(),this.mixOnChange()):A instanceof AM?(this._localAudioTrack=A,this.denoiser&&A.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&(o=this.audioProcessor)!=null&&o.localAudioWorkletNode&&(A.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((a,l)=>{A.mixAudioReference(a,l)})),A.pipeline.connect(),this.mixOnChange()):A instanceof y1?A.setOutputMediaStreamTrack(A.mediaTrack):void 0}mixAudioReference(A,t){var o;(o=this._localAudioTrack)==null||o.mixAudioReference(A,t)}unMixAudioReference(A){var t;(t=this._localAudioTrack)==null||t.unMixAudioReference(A)}setAudioReferenceVolume(A,t){var o;(o=this._localAudioTrack)==null||o.setAudioReferenceVolume(A,t)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var A,t;return delete this.mixChangedDebounce,Promise.all([(A=this._localAudioTrack)==null?void 0:A.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(t=this._localScreenAudioTrack)==null?void 0:t.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(A){A instanceof Dj?delete this._localScreenAudioTrack:A instanceof AM&&delete this._localAudioTrack}addDenoiser(A){var t;this.denoiser=A,(t=this._localAudioTrack)==null||t.addDenoiser(A)}addAudioProcessor(A,t,o,a){var l;this.audioProcessor={localAudioWorkletNode:o,mixNode:A,silentNode:t,screenAudioWorkletNode:a},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&o&&(this._localAudioTrack.addAudioProcessor(o,A,t),this.audioReferenceMap.forEach((d,h)=>{var y;(y=this._localAudioTrack)==null||y.mixAudioReference(d,h)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&a&&((l=this._localScreenAudioTrack)==null||l.addAudioProcessor(a,A,t),this.audioReferenceMap.forEach((d,h)=>{var y;(y=this._localScreenAudioTrack)==null||y.mixAudioReference(d,h)}))}removeDenoiser(A){var t;return delete this.denoiser,(t=this._localAudioTrack)==null?void 0:t.removeDenoiser(A)}addVoiceChanger(A,t){var o;this.voiceChanger=[A,t],(o=this._localAudioTrack)==null||o.pipeline.voiceChanger.setNode(A,t)}removeVoiceChanger(){var A;delete this.voiceChanger,(A=this._localAudioTrack)==null||A.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(A,t){var o,a;delete this.audioProcessor,(o=this._localAudioTrack)==null||o.removeAudioProcessor(A),(a=this._localScreenAudioTrack)==null||a.removeAudioProcessor(t)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(A=>A?.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor(A){let{processor:t,type:o}=A;var a;this.encodePipeline.includes(t)||(this.encodePipeline[o]=t,(a=this.room)==null||a.enableInsertableStreams())}addDecodeProcessor(A){let{processor:t,type:o}=A;var a;this.decodePipeline.includes(t)||(this.decodePipeline[o]=t,(a=this.room)==null||a.enableInsertableStreams())}removeEncodeProcessor(A){let{type:t}=A;this.encodePipeline[t]=void 0}removeDecodeProcessor(A){let{type:t}=A;this.decodePipeline[t]=void 0}handleLocalTrackStarted(A){let{room:t,userId:o}=A;var a;if(t!==this.room||this.getPCMAbortCtrlMap.get(o))return;let l=this.getPCM(d=>{var h;(h=this.room)==null||h.emit("audio-frame",d)},"");this.getPCMAbortCtrlMap.set(o,l),this.getPCMAbortCtrlMap.get(o)&&((a=this._localAudioTrack)==null||a.on("input-media-track-changed",()=>{let d=this.getPCMAbortCtrlMap.get(o);d&&(d.abort("inputMediaTrackChanged"),d=this.getPCM(h=>{var y;(y=this.room)==null||y.emit("audio-frame",h)},""),this.getPCMAbortCtrlMap.set(o,d))}))}handleLocalTrackStopped(A){let{room:t,userId:o}=A;if(t!==this.room)return;let a=this.getPCMAbortCtrlMap.get(o);a&&(a.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(o))}handleRemoteTrackStarted(A){let{room:t,userId:o}=A;if(t===this.room&&!this.getPCMAbortCtrlMap.get(o)){let a=this.room.audioManager.getPCM(l=>{var d;(d=this.room)==null||d.emit("audio-frame",l)},o);this.getPCMAbortCtrlMap.set(o,a)}}handleRemoteTrackStopped(A){let{room:t,userId:o}=A;if(t!==this.room)return;let a=this.getPCMAbortCtrlMap.get(o);a&&(a.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(o))}installEvent(){F.on("113",this.handleLocalTrackStarted,this),F.on("114",this.handleLocalTrackStopped,this),F.on("115",this.handleRemoteTrackStarted,this),F.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){F.off("113",this.handleLocalTrackStarted),F.off("114",this.handleLocalTrackStopped),F.off("115",this.handleRemoteTrackStarted),F.off("116",this.handleRemoteTrackStopped)}updateAudioReference(A){let{type:t,audioReference:o,refId:a,volume:l}=A;if(t==="add"){if(this.audioReferenceMap.get(a)||!o||(this.audioReferenceMap.set(a,o),!this.audioProcessor))return;this.mixAudioReference(o,a)}else if(t==="remove")this.audioReferenceMap.get(a)&&(this.audioReferenceMap.delete(a),this.unMixAudioReference(a));else if(t==="updateVolume"){if(!this.audioProcessor||ze(l))return;this.setAudioReferenceVolume(a,l)}}};function f1(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return Xr((o,a)=>function(){for(var l=arguments.length,d=new Array(l),h=0;h{let L=setTimeout(()=>{let V=new li({code:mt.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(a,"() timeout ").concat(A,"s")});(this.log||this._log||pA).warn(V),t===2?S(V):t===1&&y()},1e3*A);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(L),o.apply(this,d).then(y,S).finally(()=>{clearTimeout(L),this._checkPendingPromiseSet&&L&&this._checkPendingPromiseSet.delete(L)})})})}var tM=class IW extends aj{constructor(t,o,a){super({userId:o.userId,sdkAppId:t.sdkAppId,mediaType:a,room:t}),this.room=t,this.user=o,Y(this,"tinyId"),Y(this,"isRemote",!0),Y(this,"jitterBufferDelay",0),Y(this,"availableState"),Y(this,"remotePublishState"),Y(this,"_triggerCheckDecodeSubject",BQ(Ea(this,IW.STATE_SUBSCRIBE))),Y(this,"ignoreUpdatePlayingState"),this.tinyId=o.tinyId,this.availableState=new gs("".concat(o.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new gs("".concat(o.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),Ma(cj(Ea(this,gs.STATECHANGED),Ea(this.remotePublishState,gs.STATECHANGED)),Cj(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Dl(y=>{this.availableState.state!==(y?gs.ON:gs.OFF)&&(this.availableState.state=y?gs.ON:gs.OFF),(!this.isRemotePublished||!this.ignoreUpdatePlayingState)&&this.updatePlayingState(y)}));let l=Ma(Ea(this.player,Mo.ERROR),$v(y=>y.code===MediaError.MEDIA_ERR_DECODE)),d=Ma(uj(5e3),$v(()=>!!(!this.ignoreDecodeError&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived&&this.isRemotePublished)&&(!this.player.isPlaying&&!(this.kind===JA.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1)))),h=Ma(Z5(l,d),CE(Ea(this,gs.INIT)));Ma(this._triggerCheckDecodeSubject,$v(()=>!this.ignoreDecodeError),Q1(h),Dl(y=>{this.reportDecodeResult(!1,y)}))}setMute(t){this.isRemotePublished&&super.setMute(t)}setInputMediaStreamTrack(t){super.setInputMediaStreamTrack(t),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(t=>{this.mediaTrack?t():this.once("input-media-track-changed",t)})}get ignoreDecodeError(){var t,o,a,l;return(l=(a=(o=(t=this.room)==null?void 0:t.networkQuality)==null?void 0:o.hadRecentBadDownlink)==null?void 0:a.call(o,2))!=null&&l||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===IW.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===gs.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(t){return t}unsubscribe(){this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(t,o){var a,l;let d=this.kind===JA.AUDIO;if(ri[t?"addSuccessEvent":"addFailedEvent"]({key:d?504700:514702}),!d){let h=((a=this.room)==null?void 0:a.downlinkVideoCodec.toUpperCase())||"H264";ri[t?"addSuccessEvent":"addFailedEvent"]({key:fy["DECODE_".concat(h,"_RESULT")]}),t||this.log.warn("".concat((l=this.room)==null?void 0:l.downlinkVideoCodec," decode failed"))}t||(ri.addEnum({key:d?504701:514703,value:Kp()}),ds.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(lQ()||jp()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===JA.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:o}))}updatePlayingState(t){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===t){if(t&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed: ".concat(this.isSubscribed," isAvailable: ").concat(this.isRemotePublished," hasTrack: ").concat(!!this.outMediaTrack," "));super.updatePlayingState(t)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?gs.ON:gs.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};Y(tM,"STATE_SUBSCRIBE","subscribe"),Qi([f1(5,1)],tM.prototype,"waitHasMediaTrack"),Qi([hc(gs.INIT,tM.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),F.emit(rA.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),wy(521716,!1)],tM.prototype,"subscribe"),Qi([hc(tM.STATE_SUBSCRIBE,gs.INIT,{sync:!0,success(){this.log.info("unsubscribed"),F.emit(rA.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],tM.prototype,"unsubscribe");var mz=tM,y1=class extends mz{constructor(A,t){super(A,t,1),Y(this,"volume",0),Y(this,"mediaType",1),Y(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=A.audioManager}get dbVolume(){return g1.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(A){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var A,t;return!!this.manager&&(this.manager.decodePipeline.some(o=>o)||((t=(A=this.player.element)==null?void 0:A.error)==null?void 0:t.code)===MediaError.MEDIA_ERR_DECODE&&l_().AudioDecoder&&$p)}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(A){if(!this.manager)return A;let t=A;for(let[o,a]of this.manager.decodePipeline.entries()){if(!a)continue;let l={frame:A,track:this};if(o===1&&this.isAvailable&&this.room.role==="audience"&&(l.onAudioFrameNTPTime=d=>{let{ntp:h,frame:y,hasLeavingTag:S}=d;this.emit("audio-frame-with-ntp",{ntp:h,frame:y,hasLeavingTag:S})}),t=a(l),!t)return}return t}getAudioLevel(){if(!this.isAvailable)return 0;let A=this.volume||super.getAudioLevel();return A>1?1:A}getInternalAudioLevel(){return this.isAvailable?super.getInternalAudioLevel():0}get isRemotePublished(){return this.user.muteState.audioAvailable}},toA=class extends tC{constructor(A,t,o,a,l){super(A,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:t}),this.setContainer=a,Y(this,"initStat",{alphaStitchingType:1}),Y(this,"end",BQ()),Y(this,"minSize",320),Y(this,"maxSize",1280),Y(this,"draggable",!1),Y(this,"startDragX",0),Y(this,"startDragY",0),Y(this,"left",0),Y(this,"top",0),Y(this,"baseWidth",320),Y(this,"baseRatio"),Y(this,"container"),this.initStat=l,this.draggable=o,this.bindDragEvents(),ri.addEnum({key:515700,value:1}),this.draggable&&ri.addEnum({key:515700,value:11})}bindDragEvents(){let A=this.context._canvas;if(A)if(this.draggable){let t=CE(this.end);Ma(Ea(A,"mousedown"),hj(this.startDrag.bind(this)),h1(()=>Ma(Ea(window,"mousemove"),CE(Ea(window,"mouseup")))),t,Dl(this.doDrag.bind(this))),Ma(Ea(A,"dblclick"),t,Dl(this.resetPosition.bind(this))),Ma(Ea(A,"wheel"),t,Dl(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(A){var t;return!((t=this.input)==null||!t.requestFrame(A))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}startDrag(A){A.preventDefault(),A.button===0&&(this.startDragX=A.clientX-this.left,this.startDragY=A.clientY-this.top)}renderCanvas(){let{container:A}=this;A||this.setContainer(),A&&this.baseRatio&&this.draggable&&(A.style.setProperty("width","".concat(this.baseWidth,"px")),A.style.setProperty("height","".concat(this.baseWidth/this.baseRatio,"px")),A.style.setProperty("position","fixed"),A.style.setProperty("left","".concat(this.left,"px")),A.style.setProperty("top","".concat(this.top,"px")))}doDrag(A){A.preventDefault(),this.left=A.clientX-this.startDragX,this.top=A.clientY-this.startDragY,this.renderCanvas()}handleZoom(A){A.preventDefault();let t=A.deltaY,o=this.context._canvas;o&&(this.baseWidth||(this.baseWidth=o.offsetWidth),this.baseWidth=t<0?Math.min(1.1*this.baseWidth,this.maxSize):Math.max(.9*this.baseWidth,this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(A,t,o,a,l){var d;let{ctx2d:h}=this,y=this.context._canvas;if(!h||!y)return!1;let S=super.draw2d(A,t,o,a,l),L=h.getImageData(0,0,a,l),{data:V}=L,H=!1;if(this.initStat.alphaStitchingType===1){let lA=Math.floor(a/2);for(let hA=0;hA=100;V[oe+3]=_e?255:0}H=super.draw2d(L,0,0,0,0,lA,l),y.width=lA}else if(this.initStat.alphaStitchingType===2){let lA=Math.floor(l/2);for(let hA=0;hA=100;V[oe+3]=_e?255:0}H=super.draw2d(L,0,0,0,0,a,lA),y.height=lA}return(d=this.context.ctx)==null||d.clearRect(0,0,a,l),S&&H}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}},fL=class extends mz{constructor(A,t){super(A,t,arguments.length>2&&arguments[2]!==void 0?arguments[2]:4),Y(this,"mediaType",4),Y(this,"source"),Y(this,"shouldRenderAlpha",!1),Y(this,"alphaNode"),Y(this,"shouldBeDraggable",!0),Y(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0,keyFramesDecoded:0}),Y(this,"_keyFrameCountLogged",!1),Y(this,"_keyFrameStartTimestamp",0),Y(this,"_keyFrameStartCount",0),Y(this,"_keyFrameIntervals",[]),Y(this,"_prevKeyFrameTimestamp",0),this.manager=A.videoManager,this.on("first-video-frame",o=>{this.room.emit("first-video-frame",o)}),this.on("first-frame-render",o=>{this.room.emit("first-frame-render",o)})}isAlphaSei(A){if(this.userId!==A.userId||A.seiPayloadType!==50)return!1;let t=new Uint8Array(A.data);return t.length%3==0&&t[0]===0&&t[1]===1&&t}play(A,t){return t!=null&&t.canvasRender&&!this.source&&this.useCanvasPlayer(),super.play(A,t).then(()=>{this.player.calculateStat(),F.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(A){let t=this.isAlphaSei(A);if(t)if(this.alphaNode){let o=t[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===o)return;this.alphaNode.initStat={alphaStitchingType:o};let a=this.player.getElement();if(a){let l=a.videoWidth/a.videoHeight;l&&(this.alphaNode.baseRatio=l*(o===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(o))}else this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(t[2])}generateAlphaCanvasName(A){let t=Qy[A];return"".concat("alpha","_").concat(t,"_").concat(this.userId)}useCanvasPlayer(A){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let t=new pQ({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&A?this.generateAlphaCanvasName(A):this.userId});t.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let o=new Qj(t,{name:"remotePlayer",logger:this.log});if(this.source=t.createVideoPlayerSource(this.player),this.player.setCanvas(t._canvas),this.shouldRenderAlpha&&A){let a=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},l=new toA(t,this.log,this.shouldBeDraggable,a,{alphaStitchingType:A});this.source.connect(l),l.connect(o),this.alphaNode=l}else this.source.connect(o);Am()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,t),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(A){let t=this.decodeFPS,o=(a=t,[15,30,45,60].reduce((l,d)=>Math.abs(d-a)l.msg_user_info.str_identifier===this.userId))||{},o=this.mediaType===2?7:this.isSmall?3:2;if(!t||t.length===0)return 0;let a=t.find(l=>l.uint32_video_stream_type===o);return a?.uint32_video_dec_fps||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),F.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(A){if(!this.manager)return A;for(let t of this.manager.decodePipeline)if(t&&!(A=t({frame:A,track:this})))return;return A}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(A){this.room.changeType(A,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(A){A==="publish"||A==="both"||super.setMirror(A)}setDraggable(A){this.shouldBeDraggable=A,this.alphaNode&&(this.alphaNode.draggable=A,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(A){this.emit("decode-downgrade-state-changed",A)}updateKeyFramesDecoded(A){let t=this.stat.keyFramesDecoded||0;if(this.stat.keyFramesDecoded=A,this._keyFrameCountLogged)return;let o=Date.now();if(!this._keyFrameStartTimestamp)return this._keyFrameStartTimestamp=o,this._keyFrameStartCount=A,void(this._prevKeyFrameTimestamp=o);if(this._prevKeyFrameTimestamp&&A>t){let l=A-t,d=(o-this._prevKeyFrameTimestamp)/1e3/l;this._keyFrameIntervals.push(d)}this._prevKeyFrameTimestamp=o;let a=o-this._keyFrameStartTimestamp;if(a>=16e3){let l=A-this._keyFrameStartCount,d=l>0?a/1e3/l:0,h="".concat(l," keyframes in 16s ").concat(d," [").concat(this._keyFrameIntervals.map(S=>S.toFixed(1)).join(","),"] keyFramesDecoded ").concat(A),y=d<=2.5?"debug":"info";this.log[y](h),this._keyFrameCountLogged=!0}}},fz=class extends fL{constructor(A,t){super(A,t,2),Y(this,"mediaType",2),Y(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},f_=new Map;function jg(A,t){let o=So(Di({},t),{timestamp:Vf()});f_.has(A)?f_.get(A).push(o):f_.set(A,[o])}function yz(){for(var A=arguments.length,t=new Array(A),o=0;ofunction(){for(var d=arguments.length,h=new Array(d),y=0;yty(L)?Iv(L):Ws(L)?L:pg(L))},fnName:l,value:o},link:{className:d,fnName:l}})})}else if(!ze(t.type)&&pg(o)!==t.type)throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_PARAMETER_TYPE,data:{key:a,rule:t,fnName:l,value:o},link:{className:d,fnName:l}})});if(t.allowEmpty===!1){let S=Ys(o)&&(o===0||Number.isNaN(o)),L=Ws(o)&&o.trim()==="";if(S||L)throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_PARAMETER_EMPTY,data:{key:a,rule:t,fnName:l,value:o},link:{className:d,fnName:l}})})}if(t.notLessThanZero&&Ys(o)&&o<0)throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.CANNOT_LESS_THAN_ZERO,data:{key:a,rule:t,fnName:l,value:o},link:{className:d,fnName:l}})});if(!ze(t.min)&&Ys(o)&&ot.max)throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_PARAMETER_MAX,data:{key:a,rule:t,fnName:l,value:o},link:{className:d,fnName:l}})});if(Ws(t.instanceOf)){if(!o||o._name!==t.instanceOf)throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_PARAMETER_INSTANCE,data:{key:a,rule:t,fnName:l,value:o},link:{className:d,fnName:l}})})}else if(ba(t.instanceOf)&&!(o instanceof t.instanceOf))throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_PARAMETER_INSTANCE,data:{key:a,rule:t,fnName:l,value:o},link:{className:d,fnName:l}})});if(t.values&&!t.values.includes(o))throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_PARAMETER_RANGE,data:{key:a,rule:t,fnName:l,value:o},link:{className:d,fnName:l}})});let{properties:h}=t;uE(h)&&ed(o)&&Object.keys(h).forEach(S=>{D1.call(this,{rule:h[S],value:o&&o[S],key:"".concat(a,".").concat(S),fnName:l,className:d})});let{arrayItem:y}=t;uE(y)&&ka(o)&&o.forEach((S,L)=>{D1.call(this,{rule:y,value:S,key:"".concat(a,"[").concat(L,"]"),fnName:l,className:d})}),ba(t.validate)&&t.validate.call(this,o,a,l,d,this)}F.on(rA.JOIN_SUCCESS,A=>{let{room:t}=A;jg(t.userId,{eventId:32788})}),F.on(rA.LEAVE_START,A=>{let{room:t}=A;jg(t.userId,{eventId:32789})}),F.on(rA.LOCAL_TRACK_PUBLISHED,A=>{let{track:t}=A;if(t.room){let o=32769;t.mediaType===4?o=32768:t.mediaType===2&&(o=32805),jg(t.room.userId,{eventId:o})}}),F.on(rA.LOCAL_TRACK_UNPUBLISHED,A=>{let{track:t}=A;if(t.room){let o=32771;t.mediaType===4?o=32770:t.mediaType===2&&(o=32806),jg(t.room.userId,{eventId:o})}}),F.on(rA.TRACK_MUTED,A=>{let{track:t}=A;t.room&&(t.kind===JA.AUDIO?jg(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):jg(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))}),F.on(rA.TRACK_UNMUTED,A=>{let{track:t}=A;t.room&&(t.kind===JA.AUDIO?jg(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):jg(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))}),F.on(rA.REMOTE_TRACK_SUBSCRIBED,A=>{let{track:t}=A;t.room&&(t.mediaType===1&&jg(t.room.userId,{eventId:32777,remoteUserId:t.userId}),t.mediaType===4&&jg(t.room.userId,{eventId:32776,remoteUserId:t.userId}),t.mediaType===8&&jg(t.room.userId,{eventId:32803,remoteUserId:t.userId}))}),F.on(rA.REMOTE_TRACK_UNSUBSCRIBED,A=>{let{track:t}=A;t.room&&(t.mediaType===1&&jg(t.room.userId,{eventId:32779,remoteUserId:t.userId}),t.mediaType===4&&jg(t.room.userId,{eventId:32778,remoteUserId:t.userId}),t.mediaType===8&&jg(t.room.userId,{eventId:32804,remoteUserId:t.userId}))}),F.on(rA.SWITCH_DEVICE_SUCCESS,A=>{let{track:t}=A;t.room&&jg(t.room.userId,{eventId:t.kind===JA.VIDEO?32780:32781})}),F.on(rA.LOCAL_TRACK_REPLACED,A=>{let{track:t}=A;t.room&&jg(t.room.userId,{eventId:t.kind===JA.VIDEO?32782:32783})}),F.on(rA.SIGNAL_CONNECTION_STATE_CHANGED,A=>{let t,{room:o,prevState:a,state:l}=A;switch(l){case"CONNECTED":t=a==="RECONNECTING"?32795:32791;break;case"DISCONNECTED":t=a==="RECONNECTING"?32796:32790;break;case"RECONNECTING":t=32794}t&&jg(o.userId,{eventId:t})}),F.on(rA.PEER_CONNECTION_STATE_CHANGED,A=>{let t,{room:o,prevState:a,state:l,remoteUserId:d}=A,h=!!d;switch(l){case"CONNECTED":t=a==="RECONNECTING"?h?32801:32798:h?32793:32792;break;case"DISCONNECTED":a==="RECONNECTING"&&(t=h?32802:32799);break;case"RECONNECTING":t=h?32800:32797}t&&jg(o.userId,{eventId:t,remoteUserId:d})}),F.on(rA.VIDEO_CODEC_IMPLEMENTATION_CHANGED,A=>{let{implementation:t,userId:o,remoteUserId:a,codec:l,isHWCodec:d,prevImplementation:h,streamType:y}=A,S=d?1:0;h||(S=d?3:2);let L={H264:0,H265:1,VP8:2}[l.toUpperCase()],V={eventId:4004,param1:S,param2:L,streamType:y||2};a&&(V.remoteUserId=a,V.eventId=4005),jg(o,V),ri.addEnum({key:a?514701:513701,value:S}),ri.addEnum({key:a?514700:513700,value:L})}),F.on(rA.LOCAL_TRACK_RECAPTURE,A=>{let{track:t,error:o}=A;if(t.userId){let a={eventId:2003,param1:0};t.kind===JA.AUDIO?(a.streamType=1,o&&(a.param1=2)):(a.streamType=t.streamType==="auxiliary"?7:2,o&&(a.param1=8)),jg(t.userId,a)}});var ooA=dc($l(),1),noA=class extends ooA.EventEmitter{constructor(A,t){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"userId";super(),this.mySelfId=A,this._log=t,this.key=o,Y(this,"userMap",new Map),Y(this,"remotePublishedUserMap",new Map),Y(this,"asrRobotUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(A=>A.isRobot)}getPublishedUser(A){return this.remotePublishedUserMap.get(A)}addUser(A){let t=A[this.key],{userId:o,tinyId:a,role:l,fromType:d}=A;if(d===D0)return void this.addAsrRobotUser(A);if(this.userMap.has(t))return;let h={userId:o,tinyId:a,role:l===20?"anchor":"audience"};this.userMap.set(t,h),this.emit("1",h)}addAsrRobotUser(A){let t=A[this.key],{userId:o,tinyId:a,role:l}=A;if(this.asrRobotUserMap.has(t))return;let d={userId:o,tinyId:a,role:l===20?"anchor":"audience"};this.asrRobotUserMap.set(t,d),this.emit("8",d)}deleteUser(A,t){let o=this.userMap.get(A);if(!o)return;if(this.asrRobotUserMap.has(A))return void this.deleteAsrRobotUser(A);let a="peer leave [".concat(A,"]");ze(t)||(a+=":".concat(l2[t])),this._log.info(a);let l=this.remotePublishedUserMap.get(A);if(l){let d=l.muteState;l.flag=0,this.emit("5",l.userId),this.deleteRemotePublishedUser(A),this.emit("6",{prevMuteState:d,muteState:l.muteState,flag:0})}this.userMap.delete(A),this.emit("2",{userId:o.userId,reason:t})}deleteAsrRobotUser(A){if(!this.asrRobotUserMap.has(A))return;let t=this.asrRobotUserMap.get(A);t&&(this.asrRobotUserMap.delete(A),this.emit("9",t))}setUserList(A){this.userMap.forEach(t=>{A.findIndex(o=>o[this.key]===t[this.key])<0&&this.deleteUser(t[this.key],0)}),A.forEach(t=>{!this.userMap.has(t[this.key])&&t[this.key]!==this.mySelfId&&this.addUser(t)})}addRemotePublishedUser(A){this.remotePublishedUserMap.has(A[this.key])||this.remotePublishedUserMap.set(A[this.key],A)}deleteRemotePublishedUser(A){this.remotePublishedUserMap.has(A)&&this.remotePublishedUserMap.delete(A)}setRemotePublishedUserList(A){this.remotePublishedUserMap.forEach(t=>{let o=t[this.key];if(A.findIndex(a=>a[this.key]===t[this.key])<0){this._log.info("remote [".concat(o,"] unpublish"));let a=t.muteState;t.flag=0,this.emit("5",t.userId),this.deleteRemotePublishedUser(o),this.emit("6",{prevMuteState:a,muteState:t.muteState,flag:0})}}),A.forEach(t=>{var o;let a=t[this.key];if(a===this.mySelfId)return void this.emit("7",t);let{flag:l,userId:d,tinyId:h,fromType:y}=t,S=kp(l,d),L=(o=this.remotePublishedUserMap.get(a))==null?void 0:o.muteState;if(L){let V=this.remotePublishedUserMap.get(a);V&&V.flag!==l&&(V.flag=l,this._log.info("remote publish updated: ".concat(JSON.stringify(V.muteState))),this.emit("6",{prevMuteState:L,muteState:S,flag:l}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(S))),this.addUser({userId:d,tinyId:h,role:20,fromType:y}),this.emit("3",t),this.emit("6",{prevMuteState:kp(0,d),muteState:S,flag:l})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}},soA=dc($l(),1),roA=class extends soA.default{constructor(){super(...arguments),Y(this,"_connectionTimeoutCount",0),Y(this,"_isFirewallRestrictionEventEmitted",!1)}increaseTimeoutCount(){this._connectionTimeoutCount+=1,this.checkAndEmitFirewallRestriction()}resetTimeoutCount(){this._connectionTimeoutCount=0}checkAndEmitFirewallRestriction(){this._connectionTimeoutCount>=3&&!this._isFirewallRestrictionEventEmitted&&(this._isFirewallRestrictionEventEmitted=!0,this.emit("firewall-restriction"))}destroy(){this._connectionTimeoutCount=0,this._isFirewallRestrictionEventEmitted=!1,this.removeAllListeners()}};function Dz(A){let{timesInSecond:t,maxSizeInSecond:o,getSize:a}=A;return Xr((l,d)=>{let h=new WeakMap;return F.on(rA.ROOM_DESTROY,y=>{let{room:S}=y;return h.delete(S)}),function(){let y=h.get(this);for(var S=arguments.length,L=new Array(S),V=0;V1e3&&(y.timestamp=Date.now(),y.callCountInSecond=0,y.totalSizeInSecond=0),a&&(y.totalSizeInSecond+=a(...L)),y.timestamp!==0&&Date.now()-y.timestamp<1e3&&(y.callCountInSecond>=t||y.totalSizeInSecond>o))throw new li({code:mt.INVALID_OPERATION,message:sn({key:Go.CALL_FREQUENCY_LIMIT,data:{isTimes:y.callCountInSecond>=t,isSize:y.totalSizeInSecond>o,name:d,timesInSecond:t,maxSizeInSecond:o}})});y.callCountInSecond++,l.call(this,...L)}})}var wt,Sz=!0,yL={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"},ko={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},S1=((wt=S1||{})[wt.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",wt[wt.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",wt[wt.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",wt[wt.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",wt[wt.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",wt[wt.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",wt[wt.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",wt[wt.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",wt[wt.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",wt[wt.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",wt[wt.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",wt[wt.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",wt[wt.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",wt[wt.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",wt[wt.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",wt[wt.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",wt[wt.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",wt[wt.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",wt[wt.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",wt[wt.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",wt[wt.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",wt[wt.INVALID_OPERATION=5100]="INVALID_OPERATION",wt[wt.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",wt[wt.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",wt[wt.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",wt[wt.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",wt[wt.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",wt[wt.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",wt[wt.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",wt[wt.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",wt[wt.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",wt[wt.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",wt[wt.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",wt[wt.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",wt[wt.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",wt[wt.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",wt[wt.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",wt[wt.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",wt[wt.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",wt[wt.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",wt[wt.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",wt[wt.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",wt[wt.DEVICE_ERROR=5300]="DEVICE_ERROR",wt[wt.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",wt[wt.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",wt[wt.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",wt[wt.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",wt[wt.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",wt[wt.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",wt[wt.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",wt[wt.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",wt[wt.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",wt[wt.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",wt[wt.SERVER_ERROR=5400]="SERVER_ERROR",wt[wt.NEED_TO_BUY=5401]="NEED_TO_BUY",wt[wt.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",wt[wt.OPERATION_FAILED=5500]="OPERATION_FAILED",wt[wt.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",wt[wt.REJOIN_FAILED=5502]="REJOIN_FAILED",wt[wt.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",wt[wt.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",wt[wt.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",wt[wt.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",wt[wt.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",wt[wt.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",wt[wt.OPERATION_ABORT=5998]="OPERATION_ABORT",wt[wt.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",wt),vz=So(Di({},Cc),{INVALID_PARAMETER(A){let{fnName:t}=A;return"the parameters of the '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(A){let{key:t,rule:o,fnName:a,value:l}=A;return"'".concat(t||o.name,"' is a required param when calling ").concat(a,"(), received: ").concat(l,".")},INVALID_PARAMETER_TYPE(A){let{key:t,rule:o,fnName:a,value:l}=A,d="".concat(t||o.name),h="";return h=Array.isArray(o.type)?o.type.join("|"):o.type,"'".concat(d,"' must be type of ").concat(h," when calling ").concat(a,"(), received type: ").concat(pg(l),".")},INVALID_PARAMETER_EMPTY(A){let{key:t,rule:o,fnName:a,value:l}=A;return"'".concat(t||o.name,"' cannot be '").concat(l,"' when calling ").concat(a,"().")},INVALID_PARAMETER_INSTANCE(A){let{key:t,rule:o,fnName:a,value:l}=A,d="".concat(t||o.name),h="".concat(o.instanceOf.name||o.instanceOf);return"'".concat(d,"' must be instanceof ").concat(h," when calling ").concat(a,"(), received type: ").concat(pg(l),".")},INVALID_PARAMETER_RANGE(A){let{key:t,rule:o,fnName:a,value:l}=A;return"'".concat(t||o.name,"' must be one of ").concat(o.values.join("|")," when calling ").concat(a,"(), received: ").concat(l,".")},INVALID_PARAMETER_LESS_THAN_ZERO(A){let{key:t,rule:o,fnName:a}=A;return"'".concat(t||o.name,"' cannot be less than 0 when calling ").concat(a,"().")},INVALID_PARAMETER_MIN(A){let{key:t,rule:o,value:a}=A;return"the min value of ".concat(t||o.name," is ").concat(o.min,", received: ").concat(a,".")},INVALID_PARAMETER_MAX(A){let{key:t,rule:o,value:a}=A;return"the max value of ".concat(t||o.name," is ").concat(o.max,", received: ").concat(a,".")},INVALID_ELEMENT_ID(A){let{key:t,fnName:o}=A;return"'".concat(t,"' is not found in the document object when calling ").concat(o,"().")},INVALID_ELEMENT_ID_TYPE(A){let{key:t,fnName:o,type:a}=A;return"the element corresponding to '".concat(t,"' must be instanceof HTMLElement when calling ").concat(o,"(), received: ").concat(a,".")},INVALID_STREAM_ID(A){let{key:t}=A;return"'".concat(t,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING(A){let{key:t}=A;return"'".concat(t,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(A){let{key:t}=A;return"'".concat(t,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(A){let{key:t}=A;return"'".concat(t,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIRED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_ROOM_ID_TYPE_MISMATCH(A){let{key:t}=A;return"The type of target roomId must match the current roomId. Current room is using '".concat(t,"', but received '").concat(t==="strRoomId"?"roomId":"strRoomId","'.")},INVALID_ROOM_ID_DUPLICATE(A){let{key:t}=A;return"the target '".concat(t,"' must not be the same as the current '").concat(t,"'.")},INVALID_STREAM_TYPE:A=>{let{fnName:t}=A;return"'streamType' is required when 'userId' is not '*', calling ".concat(t,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(A){let{fnName:t}=A;return"the API '".concat(t,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(A){let{fnName:t}=A;return"cannot ".concat(t," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(A){let{fnName:t,value:o}=A;return"cannot ".concat(t," because remote user(userId: ").concat(o.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(A){let{fnName:t,value:o}=A;return"cannot ".concat(t," because remote user(userId: ").concat(o.userId,") does not publishing ").concat(o.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(A){let{fnName:t}=A;return"you are already ".concat(t,"(), cannot repeated call '").concat(t,"'.")},INVALID_OPERATION_NEED_VIDEO(A){let{fnName:t}=A;return"cannot call '".concat(t,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(A){let{fnName:t}=A;return"cannot call '".concat(t,"' because the microphone or screen share is not turned on.")},INVALID_BUFFER_EMPTY:A=>{let{key:t}=A;return"the buffer size of paramerter '".concat(t,"' cannot be empty")},INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:A=>{let{fnName:t}=A;return"you need to call ".concat(t,"() after publish stream.")},ENV_NOT_SUPPORTED(A){let{fnName:t}=A;return"the current browser does not support the capability of the function '".concat(t,"' you are calling, please check the API documentation.")},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION(A){let{fnName:t}=A;return"cannot call ".concat(t," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(A){let{fnName:t,error:o}=A;return"'".concat(t,"' got device exception").concat(o?", error: ".concat(o.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(A){let{fnName:t,deviceType:o=iM(t),error:a}=A;return"NotFoundError, no ".concat(o," detected, please check your device and the configuration on '").concat(t,"'").concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(A){let{fnName:t,deviceType:o=iM(t),error:a}=A;return"NotAllowedError, you have disabled ".concat(o," access, please allow the current application to use the ").concat(o).concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(A){let{fnName:t,deviceType:o=iM(t),error:a}=A;return"NotReadableError, the ".concat(o," maybe in use by another APP, please check if the device is pre-occupied by another APP.")},DEVICE_OVERCONSTRAINED_ERROR(A){let{fnName:t,deviceType:o=iM(t),error:a}=A;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(A){let{fnName:t,deviceType:o=iM(t),error:a}=A;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(o).concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_SECURITY_ERROR(A){let{fnName:t,deviceType:o=iM(t),error:a}=A;return"SecurityError, check whether the system security policy restricts the use of the ".concat(o,", and it is recommended to turn on the ").concat(o," after the user interacts with the page").concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_ABORT_ERROR(A){let{fnName:t,deviceType:o=iM(t),error:a}=A;return"AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal".concat(a?" error: ".concat(a.toString(),"."):".")},CAMERA_RECOVER_FAILED(A){let{error:t}=A;return"camera recover capture failed ".concat(t?.name||"",": ").concat(t?.originMessage||t?.message)},MICROPHONE_RECOVER_FAILED(A){let{error:t}=A;return"microphone recover capture failed ".concat(t?.name||"",": ").concat(t?.originMessage||t?.message)},OPERATION_FAILED(A){let{fnName:t,error:o}=A;return"'".concat(t,"' failed, reason: ").concat(o?.toString())},FIREWALL_RESTRICTION:()=>"media connection failure due to firewall restrictions, please try to change your network.",EVENT_HANDLER_ERROR(A){let{eventName:t}=A;return"an error was caught on trtc.on('".concat(t,"', handler), please check your code on 'handler'.")},VIDEO_CONTEXT_ERROR(A){let{reason:t,error:o}=A;return"video context error ".concat(t," ").concat(o?.name||""," ").concat(o?.message||"")},SERVER_ERROR(A){let{fnName:t,error:o}=A;return"'".concat(t,"' got server error: ").concat(o?.toString(),", please check the SDK documentation.")},NEED_TO_BUY(A){let{value:t,url:o}=A;return"You need to buy packages for ".concat(t,". Refer to: ").concat(o)},ACCOUNT_NO_MONEY:A=>{let{fnParams:t}=A;return"your TRTC account run out of credit, please recharge.".concat(t.sdkAppId?" SDKAppId: ".concat(t.sdkAppId):"")},OPERATION_ABORT(A){let{fnName:t}=A;return"'".concat(t,"' abort")},UNKNOWN_ERROR(A){let{fnName:t,error:o}=A;return"'".concat(t,"' throw unknown exception").concat(o?", error: ".concat(o.toString(),"."):".")}});function iM(A){if(!A)return"camera";let t=A.toLowerCase();return t.includes("screen")?"screen share":t.includes("audio")?"microphone":"camera"}var aoA=class SY extends Error{constructor(t){let{code:o,extraCode:a,message:l="",messageParams:d,fnName:h="",originError:y,data:S}=t;var L;let V;V=l||function(H){let lA,{code:hA,params:MA,enableDocLink:oe=!1}=H,fe="",je=S1[hA];try{lA=vz[je]}catch{lA=vz.UNKNOWN_ERROR}return ba(lA)?fe=lA(MA):Ws(lA)&&(fe=lA),MA.fnName&&!fe.includes(MA.fnName)&&(fe[fe.length-1]!=="."&&(fe+="."),fe+=" thrown from ".concat(MA.fnName,"()")),oe&&(fe+=" doc:"),fe}({code:o===ko.SERVER_ERROR?o:a||o,params:Di({fnName:h,error:y},d)}),super(V),Y(this,"name","RtcError"),Y(this,"code"),Y(this,"extraCode"),Y(this,"functionName"),Y(this,"message"),Y(this,"data"),Y(this,"handler"),Y(this,"originError"),this.name=S1[o],this.code=o,this.extraCode=a,this.functionName=h,this.originError=y,this.message=V,this.data=S,this.extraCode===5302&&(L=this.originError)!=null&&L.message.includes("system")&&(this.handler=()=>{let H=document.createElement("a");gy?H.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):rQ&&(H.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),H.href.length>0&&H.click()})}static convertFrom(t,o,a){let l=t;if(t instanceof li){let{stack:d}=t,h={code:ko.UNKNOWN_ERROR,fnName:o,originError:t};switch(t.getCode()){case mt.INVALID_PARAMETER:h.code=ko.INVALID_PARAMETER,h.message=t.message;break;case mt.INVALID_OPERATION:h.code=ko.INVALID_OPERATION,h.message=t.message;break;case mt.NOT_SUPPORTED:case mt.NOT_SUPPORTED_H264:h.code=ko.ENV_NOT_SUPPORTED,t.getCode()===mt.NOT_SUPPORTED_H264&&(h.extraCode=t.message.includes(Cc.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case mt.JOIN_ROOM_FAILED:h.messageParams={fnParams:a};case mt.SERVER_TIMEOUT:case mt.SWITCH_ROLE_FAILED:case mt.SWITCH_ROOM_FAILED:h.code=ko.SERVER_ERROR,h.extraCode=t.getExtraCode();break;case mt.API_CALL_ABORTED:h.code=ko.OPERATION_ABORT;break;case mt.DEVICE_NOT_FOUND:case mt.DEVICE_AUTO_RECOVER_FAILED:case mt.INITIALIZE_FAILED:h.code=5300,t.name&&(h.extraCode=function(y){let S;switch(y){case"NotFoundError":S=5301;break;case"NotAllowedError":S=5302;break;case"NotReadableError":S=5303;break;case"OverconstrainedError":S=5304;break;case"InvalidStateError":S=5305;break;case"SecurityError":S=5306;break;case"AbortError":S=5307;break;default:S=5300}return S}(t.name));break;case mt.VIDEO_ENCODE_FAILED:h.extraCode=5505;case mt.AUDIO_ENCODE_FAILED:h.extraCode=5506,h.code=ko.OPERATION_FAILED;break;case mt.UNKNOWN:break;default:h.code=ko.OPERATION_FAILED}l=new SY(h),d&&(l.stack+=d.substr(d.indexOf(` +`)))}else{if(t instanceof SY)return t;l=new SY({code:ko.UNKNOWN_ERROR,fnName:o,originError:t})}return l}},Lo=aoA;function iC(A){return A==="sub"?"auxiliary":A==="auxiliary"?"sub":"main"}function v1(A){return A===yL.QOS_PREFERENCE_CLEAR?"detail":A===yL.QOS_PREFERENCE_SMOOTH?"motion":""}function M1(A,t){let o=t?A2:Av;return T2(A)?Di(Di({},o),A):FC[A]?FC[A]:o}var Mz={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},Rz={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},y_={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(A,t,o){if(Ws(A)&&!document.getElementById(A))throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5009,fnName:o,messageParams:{key:t}})}},wz={name:"userId",required:!0,type:"string"},_z={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function D_(A,t){if(!A)throw new Lo({code:ko.INVALID_OPERATION,extraCode:5101,fnName:t})}function Tz(A,t,o){if(!A)throw new Lo({code:ko.INVALID_OPERATION,extraCode:5102,fnName:t,messageParams:{value:o}})}function Nz(A,t,o){if(!(/^[1-9]\d*$/.test(String(A))&&A<4294967295))throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5013,fnName:t,messageParams:{key:o}})}function Gz(A,t,o){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(A))throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5012,fnName:t,messageParams:{key:o}})}function bz(A){var t;if((t=A?.option)==null||!t.small)return;if(!xv())return pA.warn("small stream is not supported"),void delete A.option.small;let o=M1(A.option.profile),a=M1(A.option.small,!0);return((l,d)=>l.width*l.height>=d.width*d.height&&l.frameRate>=d.frameRate&&l.bitrate>=d.bitrate)(o,a)?void 0:(pA.warn("small stream profile must be less than big stream profile. Big: ".concat(JSON.stringify(o),", Small: ").concat(JSON.stringify(a))),void delete A.option.small)}var goA={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(A,t,o){if(this._room.isJoined)throw new Lo({code:ko.INVALID_OPERATION,extraCode:5104,fnName:o});if(A.roomId){if(Ws(A.roomId))throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5016,fnName:o,messageParams:{key:t}});Nz(A.roomId,o,t)}else{if(!A.strRoomId)throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5015,fnName:o});Gz(A.strRoomId,o,t)}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:y_,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:Mz},validate(A){var t,o;if(((t=A?.option)==null||!t.videoTrack)&&Qu())throw new Lo({code:ko.ENV_NOT_SUPPORTED,extraCode:5201});(o=A?.option)!=null&&o.small&&bz(A)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:So(Di({},y_),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:Mz},validate(A){var t;(t=A?.option)!=null&&t.small&&bz(A)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:_z},validate(A){var t;if(((t=A?.option)==null||!t.audioTrack)&&Qu())throw new Lo({code:ko.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:_z}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:y_,publish:{type:"boolean"},option:Rz},validate(A,t,o,a,l){var d;if((d=A?.option)==null||!d.videoTrack){if(Qu())throw new Lo({code:ko.ENV_NOT_SUPPORTED,extraCode:5201});if(!Xp())throw new Lo({code:ko.ENV_NOT_SUPPORTED,fnName:o,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:y_,publish:{type:"boolean"},option:Rz}},muteRemoteAudio:[wz,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[wz,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:y_,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(A,t,o){D_(this._room.isJoined,o);let a=this._room.remotePublishedUserMap.get(A.userId);if(Tz(!!a,o,A),a&&(A.streamType==="main"&&!a.muteState.videoAvailable||A.streamType==="sub"&&!a.muteState.hasAuxiliary))throw new Lo({code:ko.INVALID_OPERATION,extraCode:5103,fnName:o,messageParams:{value:A}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:So(Di({},y_),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(A,t,o){D_(this._room.isJoined,o);let a=this._room.remotePublishedUserMap.get(A.userId);if(Tz(!!a,o,A),a){if(A.streamType==="main"&&!a.muteState.videoAvailable||A.streamType==="sub"&&!a.muteState.hasAuxiliary)throw new Lo({code:ko.INVALID_OPERATION,extraCode:5103,fnName:o,messageParams:{value:A}});if(A.option){let l=A.streamType==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack;if((A.option.pictureInPicture||A.option.fullScreen||A.option.fullScreen)&&(!l.isSubscribed||!l.player.isPlaying))throw new Lo({code:ko.INVALID_OPERATION,message:"cannot set pictureInPicture or fullScreen when remote video is not playing"})}}}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(A,t,o){if(A.userId!=="*"&&ze(A.streamType))throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5014,fnName:o})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(A,t,o){D_(this._room.isJoining||this._room.isJoined,o)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(A,t,o,a){if(!$k)throw new Lo({code:ko.ENV_NOT_SUPPORTED,fnName:o,extraCode:5207});if(!this._room.enableSEI)throw new Lo({code:ko.INVALID_OPERATION,fnName:o,extraCode:5108});if(A.byteLength>1e3)throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5018,fnName:o});if(A.byteLength===0)throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5017,messageParams:{key:t},fnName:o});D_(this._room.isJoined,o)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(A,t,o){if(!A&&!this._room.isMainStreamPublished||A&&!this._room.isAuxStreamPublished)throw new Lo({code:ko.INVALID_OPERATION,extraCode:5109,messageParams:{key:t},fnName:o})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(A,t,o,a){if(A.byteLength>1e3)throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5018,fnName:o});if(A.byteLength===0)throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5017,fnName:o,messageParams:{key:t}})}}},validate(A,t,o){if(D_(this._room.isJoined,o),this._room.scene==="live"&&this._room.role==="audience")throw new Lo({code:ko.INVALID_OPERATION,extraCode:5107,fnName:o,messageParams:{key:t}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(A,t,o){if(D_(this._room.isJoined,o),this._room.useStringRoomId&&A.strRoomId===this._room.roomId||!this._room.useStringRoomId&&A.roomId===Number(this._room.roomId))throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5020,fnName:o,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(A.roomId&&this._room.useStringRoomId||!A.roomId&&A.strRoomId&&!this._room.useStringRoomId)throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5019,fnName:o,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(A.roomId)Nz(A.roomId,o,t);else{if(!A.strRoomId)throw new Lo({code:ko.INVALID_PARAMETER,extraCode:5015,fnName:o});Gz(A.strRoomId,o,t)}},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},tI={TRTC:goA},oC=class extends Error{};function coA(A,t){let o=iy(A);for(let a=0;a!0),Y(this,"mergeUpdate",coA);let a=O_.instances.get(t);a?a.set(o,this):O_.instances.set(t,new Map([[o,this]]))}static get(t,o){if(!o)return;let a=O_.instances.get(t);return a&&a.get(o)||new O_(t,o)}static gets(t,o){let a=O_.instances.get(t),l=[];return a&&a.forEach((d,h)=>{o.test(h)&&l.push(d)}),l}action(t,o,a){let l=y=>{var S;return t===0?this.started=!0:t===3&&(this.started=!1),this.ops.shift(),(S=this.currentOp)==null||S.action(),y},d=y=>{var S,L;throw this.ops.shift(),t===0&&((S=this.currentOp)==null?void 0:S.type)===2&&this.ops.shift().reject(new oC("start failed")),(L=this.currentOp)==null||L.action(),y},h={type:t,action:()=>o(...h.args).then(l,d),args:a,resolve:loA,reject:IoA};try{switch(this.state){case 1:if(t===0)throw new oC("already started");break;case 4:if(t===2)throw new oC("not started");break;default:return this.cacheOp(h)}}catch(y){return Promise.reject(y)}return this.ops.push(h),h.promise=o(...h.args).then(l,d)}cacheOp(t){if(this.ops.length===1)switch(this.state){case 0:case 2:if(t.type===0)throw new oC("already start");break;case 3:switch(t.type){case 2:throw new oC("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new oC("unknown state")}else switch(t.type){case 3:if(this.lastOpType===3)return this.lastOp.promise;{let a=new oC("keep stop");if(this.ops.slice(1).forEach(l=>l.reject(a)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,t.args),this.lastOp.promise;case 3:throw new oC("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new oC("start not allowed after update");case 0:throw new oC("duplicate start");case 3:if(this.startSame(this.currentOp.args,t.args))throw this.ops.pop().reject(new oC("keep start")),new oC("already start")}}t.promise=new Promise((a,l)=>{t._resolve?t._resolve.then(a):t.resolve=a,t._reject?t._reject.catch(l):t.reject=l});let{action:o}=t;return t.action=()=>o().then(t.resolve,t.reject),this.ops.push(t),t.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};Y(kz,"instances",new WeakMap);var DL=kz,R1=new WeakMap,w1=(A,t)=>{if(t instanceof oC){let{stack:o}=t;t=new Lo({code:ko.OPERATION_ABORT,message:"".concat(A," abort: ").concat(t.message),fnName:A}),o&&(t.stack+=o.substr(o.indexOf(` +`)))}throw t};function oM(A,t){return Xr((o,a)=>function(){for(var l=arguments.length,d=new Array(l),h=0;hfunction(){for(var h=arguments.length,y=new Array(h),S=0;S{var MA,oe;let fe=(MA=R1.get(this))==null?void 0:MA.get(H(...y));if(fe){let{timeoutId:_e,resolve:vi}=fe;clearTimeout(_e),vi()}let je=setTimeout(()=>{if(L.state===3||L.state===4)return lA();L.action(2,l.bind(this),y).catch(w1.bind(null,d)).then(lA,hA)},V);R1.has(this)?(oe=R1.get(this))==null||oe.set(H(...y),{timeoutId:je,resolve:lA}):R1.set(this,new Map([[H(...y),{timeoutId:je,resolve:lA}]]))})}return L.action(2,l.bind(this),y).catch(w1.bind(null,d))})}function nM(A){return Xr((t,o)=>function(){for(var a=arguments.length,l=new Array(a),d=0;dS.action(3,()=>Promise.resolve(),l))).then(()=>t.call(this,...l));let y=DL.get(this,h);return y?y.action(3,t.bind(this),l).catch(w1.bind(null,o)):t.apply(this,l)})}function sM(){return function(A,t,o){return A.prototype[t]=function(){let a=this._log||console,l='"'.concat(t,'" is a static method. Use TRTC.').concat(t,"() instead. See: ").concat(zh,"/en/TRTC.html#.").concat(t);a.warn(l)},o}}var Ao={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed",REALTIME_TRANSCRIBER_MESSAGE:"realtime-transcriber-message",REALTIME_TRANSCRIBER_STATE_CHANGED:"realtime-transcriber-state-changed",PICTURE_IN_PICTURE_STATE_CHANGED:"picture-in-picture-state-changed",FULL_SCREEN_STATE_CHANGED:"full-screen-state-changed"},uoA=new Set([Ao.AUDIO_VOLUME,Ao.AUDIO_FRAME,Ao.NETWORK_QUALITY,Ao.STATISTICS,Ao.SEI_MESSAGE,Ao.CUSTOM_MESSAGE,Ao.LAYER_DATA]),Lz={};Wh(Lz,{ScheduleRequestType:()=>Oz,getAbilityConfig:()=>EoA,getScheduleDomain:()=>Mj,isNeedToSchedule:()=>SL,scheduleProxy:()=>rm,sendScheduleRequest:()=>Fz,setIsNeedToSchedule:()=>mQ,setScheduleProxy:()=>vj});var _1=null,T1=0,Uz=72e5,N1="trtc_schedule_cache",SL=!0;function mQ(A){br(A)&&A!==SL&&(SL=A,pA.info("setIsNeedToSchedule ".concat(A)),A?function(){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.removeItem(N1)}catch(t){pA.error("clearScheduleCache error",t)}}():T1=Date.now()+Uz)}function Fz(A){return XA(this,arguments,function(t){let{userId:o,sdkAppId:a,useStringRoomId:l,roomId:d,userSig:h,version:y,frameWorkType:S,role:L,latencyLevel:V}=t;return function*(){var H;if(!SL&&_1&&T1>Date.now())return{isCached:!0,result:_1};let lA={delta:0,count:[1,1],msg:[],detail:[]};try{let hA=new FormData;hA.append("userId",String(o)),hA.append("sdkAppId",String(a)),hA.append("isStrGroupId",String(l)),hA.append("groupId",String(d)),hA.append("sdkVersion",y),hA.append("userSig",String(h));let MA=((H=yield Tv())==null?void 0:H.model)||Tk();MA&&hA.append("model",MA);let oe=jp();oe&&hA.append("osString",oe);let fe=qp();fe&&hA.append("gpu",fe),L&&hA.append("role",String(L)),V&&hA.append("latencyLevel",String(V)),S&&hA.append("frameWorkType",String(S));let je=Oo(),_e=yield function(Fe,Dt,pi){return new Promise((Mi,Wo)=>{let zo=null;uv([Pz(vs=>Dt.count[0]=vs+1,vs=>{let{error:Zo,retry:Vn,retriedCount:Dg,retryFuncArgs:wa}=vs;Dt.msg[0]=Zo.message,zo||(Dg>=1&&(wa[0]=Gy(pi,"config",JA.MAIN,!0)),Vn())})(Gy(pi,"config",JA.MAIN),Fe,{get timeout(){return 1e3*Ay(2+Dt.count[0])}}),Pz(vs=>Dt.count[1]=vs+1,vs=>{let{error:Zo,retry:Vn,retriedCount:Dg,retryFuncArgs:wa}=vs;Dt.msg[1]=Zo.message,zo||(Dg>=2&&(wa[0]=Gy(pi,"config",JA.BACKUP,!0)),Vn())})(Gy(pi,"config",JA.BACKUP),Fe,{get timeout(){return 1e3*Ay(2+Dt.count[1])}})]).then(vs=>{zo=vs,Mi(zo)}).catch(Wo)})}(hA,lA,a);_e.config&&(_e.config.loggerDomain&&XS(_e.config.loggerDomain),br(_e.config.scheduleCache)&&mQ(!_e.config.scheduleCache)),lA.delta=Oo()-je;let vi=function(Fe,Dt,pi){let Mi={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let Wo=performance.getEntriesByType("resource"),zo=Gy(Fe,"config",JA.MAIN),vs=Gy(Fe,"config",JA.BACKUP);for(let Zo of Wo)if(Zo.startTime>=pi&&(Zo.name===zo||Zo.name===vs)&&Zo.transferSize>0){let Vn=Zo.name===zo?JA.MAIN:JA.BACKUP,Dg=Math.round(Zo.duration),wa=Math.round(Zo.domainLookupStart-Zo.startTime),fu=Zo.redirectStart>0?Math.round(Zo.redirectEnd-Zo.redirectStart):0,_L=Zo.fetchStart>0?Math.round(Zo.domainLookupStart-Zo.fetchStart):0,__=Math.round(Zo.domainLookupEnd-Zo.domainLookupStart),O8=Math.round(Zo.requestStart-Zo.secureConnectionStart),P8=Math.round(Zo.secureConnectionStart-Zo.connectStart),x8=Math.round(Zo.responseStart-Zo.requestStart),Y8=Math.round(Zo.responseEnd-Zo.responseStart),xnA=[__,O8,P8,x8,Y8];ds.uploadEvent({log:"stat-schedule-net:".concat(Dg,"(").concat(wa,"(").concat(fu,"->").concat(_L,")->").concat(xnA.join("->"),") ").concat(Vn),userId:Dt}),Mi=So(Di({},Mi),{totalCost:Dg,local:wa,dns:__,tcp:P8,tls:O8,request:x8,response:Y8});break}}catch(Wo){pA.error("getScheduleDetailCost error",Wo)}return Mi}(Number(a),o,je);return _1=_e,function(Fe){if(typeof window<"u"&&typeof localStorage<"u")try{let Dt=Date.now()+Uz;localStorage.setItem(N1,JSON.stringify({result:Fe,expireIn:Dt})),T1=Dt}catch(Dt){pA.error("saveScheduleToLocalStorage error",Dt)}}(_e),{isCached:!1,result:_e,detailCost:vi}}catch(hA){let MA=ka(hA)?hA[0]:hA,oe=Ys(MA.code)?MA.code:0,fe="schedule failed".concat(MA.message?": ".concat(MA.message):""),je=new li({code:mt.SCHEDULE_FAILED,extraCode:oe,message:sn({key:Go.JOIN_ROOM_FAILED,data:{error:fe,code:oe}})});throw pA.error(fe,oe),je}}()})}typeof document<"u"&&document.head.insertAdjacentHTML("beforeend",Object.values(tQ).map(A=>'')).join(`\r `)),function(){if(typeof window<"u"&&typeof localStorage<"u")try{let A=localStorage.getItem(N1);if(A){let{result:t,expireIn:o}=JSON.parse(A);o>Date.now()?(_1=t,T1=o,SL=!1):localStorage.removeItem(N1)}}catch(A){pA.error("loadScheduleFromLocalStorage error",A)}}(),F.on("28",()=>mQ(!0)),F.on("63",()=>mQ(!0)),F.on("84",()=>mQ(!0)),F.on("201",A=>{A.state==="RECONNECTING"&&mQ(!0)}),F.on("202",A=>{A.state==="RECONNECTING"&&mQ(!0)});var rm={main:"",backup:""};function vj(A){ka(A)?(rm.main=A[0],rm.backup=A[1]):(rm.main=A,rm.backup=A)}var Oz=(A=>(A.CONFIG="config",A.TRTC_AUTO_CONF="trtcAutoConf",A.AUDIO_AI_AUTH="audioAiAuth",A))(Oz||{});function Gy(A,t){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:JA.MAIN,a=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return"https://".concat(rm[o]||Mj(A,o,a),"/api/v1/").concat(t)}function EoA(A,t,o){let a=Gy(A,t),l=Gy(A,t,JA.BACKUP),d=new URLSearchParams(o).toString(),h=fetch("".concat(a,"?").concat(d)).then(S=>S.json()),y=fetch("".concat(l,"?").concat(d)).then(S=>S.json());return uv([h,y])}function Mj(A){let t,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:JA.MAIN,a=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return t=zd(A)?a?o===JA.MAIN?tQ.MAIN_OVERSEA_BACKUP:tQ.BACKUP_OVERSEA:o===JA.MAIN?tQ.MAIN_OVERSEA:tQ.BACKUP_OVERSEA:o===JA.MAIN?tQ.MAIN:tQ.BACKUP,t}function doA(A,t,o){return new Promise((a,l)=>{nQ({url:A,body:t,timeout:o.timeout,priority:"high"}).then(d=>{d.data.code===0?a(d.data.data):l({code:d.data.code,message:d.data.msg})}).catch(l)})}var Pz=(A,t)=>Bv({retryFunction:doA,settings:{retries:3,timeout:0},onError:t,onRetrying:A}),Rj=class{constructor(){Y(this,"_log"),this._log=pA.createLogger({id:"fd"})}download(A,t){return XA(this,null,function*(){let{type:o="blob"}=t||{};A=sk(A);try{let a,l=Oo();if(a=ba(fetch)?yield this.downloadWithFetch(A,o):yield this.downloadWithXHR(A,o),!a||!a.data)throw new Error("data is empty");let d=Oo()-l;return this._log.info("downloaded: ".concat(A,", return type: ").concat(o,", cost: ").concat(d,"ms")),ri.addSuccessEvent({key:522700,cost:Oo()-l}),a.data}catch(a){throw this._log.error("failed to download: ".concat(A,", error: ").concat(a)),ri.addFailedEvent({key:522700,error:a}),a}})}downloadWithFetch(A,t){return XA(this,null,function*(){this._log.info("download with fetch: ".concat(A,", return type: ").concat(t));try{let o,a=yield fetch(A);if(!a.ok){let l=new Error("network response was not ok: ".concat(a.status));throw l.status=a.status,l}return o=t==="arraybuffer"?yield a.arrayBuffer():yield a.blob(),{data:o}}catch(o){throw o}})}downloadWithXHR(A,t){return this._log.info("download with xhr: ".concat(A,", return type: ").concat(t)),new Promise((o,a)=>{let l=new XMLHttpRequest;l.open("GET",A,!0),l.responseType=t,l.onload=()=>{if(l.status===200||l.status===0&&l.response)o({data:l.response});else{let d=new Error("XHR failed, status: ".concat(l.status));d.status=l.status,a(d)}},l.onerror=a,l.send(null)})}loadWasm(A,t){return XA(this,null,function*(){this._log.info("loadWasm ".concat(A,", importObject: ").concat(JSON.stringify(t)));let o=Oo(),a=null,l=null;if(ba(WebAssembly.instantiateStreaming)&&!A.startsWith("data:application/octet-stream;base64,")&&!(d=>d.startsWith("file://"))(A)&&ba(fetch))try{let d=fetch(A);a=(yield WebAssembly.instantiateStreaming(d,t)).instance}catch(d){l=d}if(!a)try{let d=yield this.download(A,{type:"arraybuffer"});a=(yield WebAssembly.instantiate(d,t)).instance}catch(d){l=d}if(a){let d=Oo()-o;return this._log.info("loadedWasm ".concat(A,", cost: ").concat(d,"ms")),ri.addSuccessEvent({key:522701,cost:d}),a}throw this._log.error("failed to loadWasm ".concat(A,", error: ").concat(l)),ri.addFailedEvent({key:522701,error:l}),l})}loadScript(A){this._log.info("loadScript ".concat(A));let t=Oo();return new Promise((o,a)=>{let l=document.createElement("script");l.type="text/javascript",l.onload=()=>{this._log.info("loadedScript ".concat(A,", cost: ").concat(Oo()-t,"ms")),ri.addSuccessEvent({key:522702,cost:Oo()-t,split:1e3}),o(l)},l.onerror=d=>{this._log.error("failed to loadScript ".concat(A,", error: ").concat(d?.message||JSON.stringify(d))),ri.addFailedEvent({key:522702}),a(d)},l.crossOrigin="anonymous",l.src=A,document.head.append?document.head.append(l):document.getElementsByTagName("head")[0].appendChild(l)})}};Qi([iB({settings:{timeout:0,retries:3},onError(A,t,o){var a;A?.status===404||(a=A?.message)!=null&&a.includes("404")?(this._log.warn("download 404, stop retry"),o(A)):t()},onRetrying(A){this._log.warn("download retrying: ".concat(A))}})],Rj.prototype,"download"),Qi([iB({settings:{timeout:3e3,retries:3},onRetrying(A){this._log.warn("loadScript retrying: ".concat(A))}})],Rj.prototype,"loadScript");var wj=new Rj;function xz(A){let[t,o]=A,a=o.byteLength,l=parseInt(String(a/255),10),d=a%255,h=[];h.push(0,0,0,1,6,t);for(let S=0;SV+H.dataView.byteLength,0),h=new ArrayBuffer(d+t.data.byteLength),y=new DataView(h),S=new DataView(t.data),L=0;for(let V=0;Vl.isSEI);o?.(a.reverse())}catch{}return t}function Kz(A){let{seiMessageList:t,isAudio:o,getNtpTime:a,isMain:l}=A;return new TransformStream({transform(d,h){let y=d;o?audioEncodePipeline.forEach(S=>{y=S({frame:y,ntp:a(),onDump:()=>{self.postMessage({type:"dump",isAudio:o,data:y.data,userId:""})}})}):videoEncodePipeline.forEach(S=>{y=S({frame:y,seiMessageList:t,onDump:()=>{self.postMessage({type:"dump",isAudio:o,data:y.data,userId:"",streamType:l?"main":"auxiliary"})}})}),h.enqueue(y)}})}function jz(A){let{userId:t,streamType:o,isAudio:a}=A;return new TransformStream({transform(l,d){let h=l;a?(audioDecodePipeline.forEach(y=>{h=y({frame:h,onAudioFrameNTPTime:S=>{self.postMessage({type:"audio-ntp",data:S,userId:t,streamType:o})},onDump:()=>{self.postMessage({type:"dump",isAudio:a,data:h.data,userId:t})}})}),d.enqueue(h)):videoDecodePipeline.forEach(y=>{h=y({frame:h,onSEI:S=>{S.forEach(L=>{self.postMessage({type:"sei",seiPayloadType:L.seiPayloadType,data:L.seiPayload.buffer,userId:t,streamType:o})})},onDump:()=>{self.postMessage({type:"dump",isAudio:a,data:h.data,userId:t,streamType:o})}})}),d.enqueue(h)}})}function Wz(A){let t=[m1],o=[Hz,Yz,dz,Vz,xz,Kz,jz,P0,hv,p1],a="const videoEncodePipeline=[".concat(A.videoEncodePipeline.toString(),`]; const videoDecodePipeline=[`).concat(A.videoDecodePipeline.toString(),`]; const audioEncodePipeline = [`).concat(A.audioEncodePipeline.toString(),`]; const audioDecodePipeline = [`).concat(A.audioDecodePipeline.toString(),"];"),l="(()=>{".concat(t.map(S=>"const ".concat(S.name,"=(()=>").concat(S.toString(),")()")).join(` `),` `).concat(o.map(S=>S.toString()).join(` -`),";(").concat(()=>{let S=[],L=[],V=[],H=0;self.onmessage=lA=>{switch(lA.data.type){case"sei":lA.data.isMain?(S.push(lA.data.data),lA.data.small&&V.push(lA.data.data)):L.push(lA.data.data);break;case"ntp-offset":H=lA.data.data}},self.onrtctransform=lA=>{let{options:hA}=lA.transformer,MA=hA.isReceiver?jz({userId:hA.userId,streamType:hA.streamType,isAudio:hA.isAudio}):Kz({getNtpTime:()=>Date.now()+H,isAudio:hA.isAudio,isMain:hA.isMain,seiMessageList:hA.isMain?hA.small?V:S:L});lA.transformer.readable.pipeThrough(MA).pipeTo(lA.transformer.writable)}},")();").concat(a,"})()"),d=new Blob([l],{type:"text/javascript"}),h=URL.createObjectURL(d),y=new Worker(h);return URL.revokeObjectURL(h),y}var zz,_j=class{constructor(A){Y(this,"audioPlayer"),Y(this,"videoPlayer"),Y(this,"log"),this.audioPlayer=A.audioPlayer,this.videoPlayer=A.videoPlayer,this.log=A.log.createChild({id:"pip"}),this.videoPlayer.on(Mo.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.on(Mo.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.on(Mo.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(Mo.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(Mo.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.on(Mo.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.on(Mo.VOLUME_CHANGE,this.handleVolumeChange,this)}handleUserResumeInPIPOrFullScreen(){this.audioPlayer.isPaused&&(this.log.warn("resume audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doResume()),za&&Iy&&this.videoPlayer.resetSrcObjectToReplay()}handleUserPauseInPIPOrFullScreen(){this.audioPlayer.isPaused||(this.log.warn("pause audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doPause())}handleEnterPIPOrFullScreen(){this.videoPlayer.element&&this.audioPlayer.muted!==this.videoPlayer.element.muted&&(this.log.warn("sync video muted to ".concat(this.audioPlayer.muted," when enter ").concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.videoPlayer.element.muted=this.audioPlayer.muted)}handleLeavePIP(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume after leave pip"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave pip"),this.videoPlayer.doResume())}handleLeaveFullScreen(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume audio after leave fullscreen"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave fullscreen"),za&&Iy?this.videoPlayer.resetSrcObjectToReplay():this.videoPlayer.doResume())}handleVolumeChange(A){A.muted!==void 0&&this.audioPlayer.muted!==A.muted&&(this.log.warn("sync audio muted to ".concat(A.muted," in ").concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.setMuted(A.muted))}destroy(){this.videoPlayer.off(Mo.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.off(Mo.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.off(Mo.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(Mo.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(Mo.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.off(Mo.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.off(Mo.VOLUME_CHANGE,this.handleVolumeChange,this)}},Zz=!1;function CoA(A){var t=this;let{TRTC:o,room:a,errorModule:l,assetsPath:d}=A;return{TRTC:o,LocalMixVideoTrack:mj,LocalVideoTrack:QQ,LocalScreenTrack:eM,room:a,assetsPath:d,fileDownloader:wj,innerEmitter:F,INNER_EVENT:rA,constants:Wx,environment:N2,utils:hz,eventLogger:ds,log:this.room.getLogger(),loggerManager:pA,errorModule:l,kvStatManager:ri,rtcDectection:ge,trtc:this,rx:q5,enums:Oe,schedule:Lz,getDevices:c1,initVisionTaskRegistry:function(h,y){let S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"/mediapipe/vision.js";return XA(t,null,function*(){!window.VisionTaskRegistry&&!Zz&&(Zz=!0,zz=wj.loadScript("".concat(h,"/").concat(S).replace(/([^:]\/)\/+/g,"$1"))),yield zz,yield(yield window.VisionTaskRegistry.getInstance(h)).preloadModels(y)})},audioContext:VI(),deviceDetector:Kc,AudioPlayer:rj,RemoteAudioPlayer:P5,VideoPlayer:bo,showAutoPlayDialog:JC,Timer:kr,clearStarted:(h,y)=>{let S=h.getAlias(),L=DL.instances.get(this);if(L)if(y){let V=L.get(S+y);if(!V)return;V.started=!1}else L.forEach((V,H)=>{H.startsWith(S)&&(V.started=!1)})},startGetPCM:Sj,createAudioNode:r1,getNetworkTimeOffset:Kx,validateSourceNode:()=>{var h;if(gr&&((h=this.room.audioManager._localAudioPipline)==null||!h.source.node))throw new Lo({code:ko.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})},createScriptTransformWorker:Wz,AVPlayerStateSyncManager:_j,PlayerEvent:Mo}}var v_=new WeakMap,Xz="5.15.3-beta.12";function mu(){for(var A=arguments.length,t=new Array(A),o=0;ofunction(){for(var d=arguments.length,h=new Array(d),y=0;yfunction(){for(var d=arguments.length,h=new Array(d),y=0;yty(V)?Iv(V):Ws(V)?V:Qg(V))},value:o}})}else if(!ze(t.type)&&Qg(o)!==t.type)throw new Lo(h(5002));if(t.allowEmpty===!1){let L=Ys(o)&&(o===0||Number.isNaN(o)),V=Ws(o)&&o.trim()==="";if(L||V)throw new Lo(h(5003))}if(t.notLessThanZero&&Ys(o)&&o<0)throw new Lo(h(5006));if(!ze(t.min)&&Ys(o)&&ot.max)throw new Lo(h(5008));if(Ws(t.instanceOf)){if(!o||o._name!==t.instanceOf)throw new Lo(h(5004))}else if(ba(t.instanceOf)&&!(o instanceof t.instanceOf))throw new Lo(h(5004));if(Array.isArray(t.values)&&!t.values.includes(o))throw new Lo(h(5005));let{properties:y}=t;uE(y)&&ed(o)&&Object.keys(y).forEach(L=>{G1.call(this,{rule:y[L],value:o&&o[L],key:"".concat(L),fnName:l,className:d})});let{arrayItem:S}=t;uE(S)&&ka(o)&&o.forEach((L,V)=>{G1.call(this,{rule:S,value:L,key:"".concat(a,"[").concat(V,"]"),fnName:l,className:d})}),ba(t.validate)&&t.validate.call(this,o,a,l,d,this)}var hoA=0;function Ra(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:o,getKVReportKey:a,ignoreLog:l,ignoreErrorLog:d}=A;return Xr((h,y)=>function(){for(var S=arguments.length,L=new Array(S),V=0;V0?oe.info("".concat(y,"() ").concat(fe," ").concat(JSON.stringify(L,(vi,Fe)=>MA(vi,Fe,["userSig","privateMapKey"])))):oe.info("".concat(y,"() ").concat(fe));let je=a?a(...L):K2[y],_e=d?.(...L)||!1;try{let vi=h.apply(this,L),Fe=Oo();if(ey(vi)){let Dt="".concat(y.includes("Plugin")?"".concat(((lA=(H=L[0]).getName)==null?void 0:lA.call(H))||""," "):" ");return vi.then(pi=>(oe.info("".concat(y,"() success ").concat(fe," ").concat(Dt).concat(t.call(this,...L))),ri.addSuccessEvent({key:je,cost:Oo()-Fe}),pi)).catch(pi=>{var Mi;let Wo=(pi=Lo.convertFrom.call(this,pi,y,L.length===1?L[0]:L)).extraCode||pi.code,zo=(Mi=pi.message)!=null&&Mi.includes(Wo)?"":" code:".concat(Wo),vs=pi?.code===ko.OPERATION_ABORT;throw _e||oe[vs?"warn":"error"]("".concat(y,"() failed ").concat(fe," ").concat(Dt).concat(t.call(this,...L)," ").concat(pi).concat(zo," params: ").concat(JSON.stringify(L,MA))),ri.addFailedEvent({key:je,error:pi}),pi})}return ri.addSuccessEvent({key:je}),vi}catch(vi){let Fe=(vi=Lo.convertFrom.call(this,vi,y)).extraCode||vi.code,Dt=(hA=vi.message)!=null&&hA.includes(Fe)?"":" code:".concat(Fe),pi=vi?.code===ko.OPERATION_ABORT;throw _e||oe[pi?"warn":"error"]("".concat(y,"() failed ").concat(fe," ").concat(vi).concat(Dt," params: ").concat(JSON.stringify(L,MA))),ri.addFailedEvent({key:je,error:vi}),vi}})}var Nj,Gj=A=>Xr((t,o)=>function(a,l){return XA(this,null,function*(){let d=this._plugins.get(a);if(!d)throw this._log.error("plugin ".concat(String(a)," is not found")),new Lo({code:ko.OPERATION_ABORT,message:"plugin ".concat(String(a)," is not found"),fnName:o});if(ba(d.constructor.isSupported)&&!d.constructor.isSupported())throw this._log.error("plugin ".concat(String(a)," is not supported")),new Lo({code:ko.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(a)," is not supported"),extraCode:5210,fnName:o});return Tj.call(this,d.getValidateRule(A),[l],o,"TRTC"),t.call(this,d,l)})}),bj=0,b1=class HL{constructor(t){this.core=t,Y(this,"log"),Y(this,"customAudioReferenceMap",new Map),Y(this,"audioRefId",0),Y(this,"audioContext",VI()),Y(this,"localAudioWorkletNode"),Y(this,"screenAudioWorkletNode"),Y(this,"mixNode"),Y(this,"silentNode"),bj+=1,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(bj)}),this.log.info("created id=".concat(this.getAlias()).concat(bj)),this.installEvent()}static getStartValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(o,a,l,d){if(!t.room.audioManager.hasAudioTrack&&!t.room.audioManager.hasScreenAudioTrack)throw new Lo({code:ko.INVALID_OPERATION,extraCode:5106,fnName:l})}}}preload(t){return Nj||(Nj=this.doPreload(t)),Nj}doPreload(t){return XA(this,null,function*(){let o=yield this.core.fileDownloader.download(t,{type:"blob"}),a=URL.createObjectURL(o);try{yield qg(this.audioContext,a)}catch(l){this.log.error("preload audioProcessor failed. ".concat(l))}finally{URL.revokeObjectURL(a)}})}getName(){return HL.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return HL.getStartValidateRule(this.core);case"update":return HL.updateValidateRule;case"stop":return HL.stopValidateRule}}start(t){return XA(this,null,function*(){var o,a,l,d;let{room:h}=this.core,{sdkAppId:y,userId:S,userSig:L,assetsPath:V=this.core.assetsPath,audioReference:H,processLevel:lA,enableDump:hA,isLocalAudioNeedAudioProcess:MA=!0,isScreenAudioNeedAudioProcess:oe=!1}=t;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=MA,this.core.room.audioManager.isScreenAudioNeedAudioProcess=oe,!V)throw new Lo({code:ko.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(V,"/audioProcessor-wasm.js")),MA&&!this.localAudioWorkletNode){let{sign:fe,status:je,timestamp:_e}=yield this.getAuthData(y,S,L);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",y,S,_e,fe,je,h)}if(oe&&!this.screenAudioWorkletNode){let{sign:fe,status:je,timestamp:_e}=yield this.getAuthData(y,S,L);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",y,S,_e,fe,je,h)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(o=this.localAudioWorkletNode)==null||o.port.postMessage({type:"enable"}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"enable"}),h.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),ze(H)||H.forEach(fe=>{this.customAudioReferenceMap.set(fe,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:fe,refId:"o-".concat(this.audioRefId++)})}),ze(lA)||(l=this.localAudioWorkletNode)==null||l.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:lA}}),ze(hA)||(d=this.localAudioWorkletNode)==null||d.port.postMessage({type:"dump",data:{enable:hA}})})}update(t){return XA(this,null,function*(){var o,a,l;let{audioReference:d,enableDump:h,processLevel:y}=t;ze(d)||(this.customAudioReferenceMap.forEach((S,L)=>{this.customAudioReferenceMap.delete(L),this.core.room.audioManager.updateAudioReference({type:"remove",refId:S})}),d.forEach(S=>{this.customAudioReferenceMap.set(S,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:S,refId:"o-".concat(this.audioRefId++)})})),ze(y)||(o=this.localAudioWorkletNode)==null||o.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:y}}),ze(h)||((a=this.localAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:h}}),(l=this.screenAudioWorkletNode)==null||l.port.postMessage({type:"dump",data:{enable:h}}))})}stop(){return XA(this,null,function*(){var t,o;let{room:a}=this.core;(t=this.localAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),(o=this.screenAudioWorkletNode)==null||o.port.postMessage({type:"disable"}),yield a.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(t,o,a){return XA(this,null,function*(){let l=String(Date.now()).slice(0,-3),{auth:d,sign:h,status:y,message:S}=yield function(L){return XA(this,arguments,function(V){let{sdkAppId:H,userId:lA,userSig:hA,timestamp:MA}=V;return function*(){let oe="".concat(function(Wo){let zo=arguments.length>1&&arguments[1]!==void 0?arguments[1]:JA.MAIN;return"https://".concat(rm[zo]||Mj(Wo,zo),"/api/v1/audioAiAuth")}(H),"?sdkAppId=").concat(H,"&userId=").concat(lA,"&userSig=").concat(hA,"×tamp=").concat(MA),fe=yield fetch(oe),{data:{errCode:je,errMsg:_e,sign:vi,status:Fe}}=yield fe.json();if(Fe==="1")return{auth:!0,sign:vi,status:Fe,message:_e};let Dt=zd(H)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",pi="Init RTCAudioProcessor failed.",Mi="";switch(je){case 1:Mi="Please check your params.";break;case 2:Mi="You need to buy packages. Refer to: ".concat(Dt);break;case 3:Mi="Server is invalid. Please contact our engineer. ";break;case 4:Mi="Your packages is not active. Refer to: ".concat(Dt);break;case 5:Mi="Your packages is expired. Refer to: ".concat(Dt);break;case 6:Mi="Your version is not supported."}return{auth:!1,status:Fe,message:_e?"".concat(pi," Reason: ").concat(_e,". ").concat(Mi):"".concat(pi,", ").concat(Mi)}}()})}({sdkAppId:t,userSig:a,userId:o,timestamp:l});if(!d)throw this.log.info("audioProcessor: ".concat(o," auth result: ").concat(d,". Message: ").concat(S)),new Lo({code:ko.INVALID_PARAMETER,message:S});return{sign:h,status:y,timestamp:l}})}initWorkletNode(t,o,a,l,d,h,y,S){t.port.postMessage({type:"init",data:{sdkAppId:String(a),userId:l,timestamp:d,sign:h,status:y}}),t.port.onmessage=L=>{var V;let{data:H}=L;switch(H.type){case"cost":let lA=H?.value>10?"info":"debug";return void this.log[lA]("".concat(o==="localAudio"?"":"[".concat(o,"] "),"avg cost: ").concat(H.value," max: ").concat(H?.max,"(").concat(Gb(new Date(H?.maxCostTimestamp)),") hist: ").concat((V=H?.hist)==null?void 0:V.join(" ")));case"log":return void this.log[H.logLevel]("".concat(o==="localAudio"?"":"[".concat(o,"] ")).concat(H.value));case"dump":return void F.emit("265",{room:S,data:H.value,type:o==="localAudio"?"dump":"dump-screen-audio"});case"detectEcho":return void this.log.warn("".concat(o==="localAudio"?"":"[".concat(o,"] "),"detect echo: ").concat(e_()?lQ():jp()))}}}handleLocalAudioStarted(t){return XA(this,null,function*(){var o;if(this.hitTest(t.room)&&((o=this.core.room.scheduleResult.config)==null?void 0:o.audioProcessor)===!0)try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(a){this.log.warn("audio processor auto start failed, error: ".concat(a))}})}handleLocalAudioStopped(t){return XA(this,null,function*(){var o;!this.hitTest(t.room)||((o=this.core.room.scheduleResult.config)==null?void 0:o.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(t){return t===this.core.room}};Y(b1,"updateValidateRule",{type:"object"}),Y(b1,"stopValidateRule",{type:"object"}),Y(b1,"Name","AudioProcessor");var BoA=b1,kj=0,QoA=class{constructor(A,t){Y(this,"audioObjectURL"),Y(this,"player"),Y(this,"publisher"),Y(this,"mixInput"),this.mixInput=new G5(t),A.url?(this.player=new Audio(A.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(A.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(A.track),this.mixInput.connect()}updateSettings(A){this.player&&(ze(A.volume)||(this.volume=A.volume),ze(A.loop)||(this.loop=A.loop),ze(A.playbackRate)||(this.playbackRate=A.playbackRate))}updateListener(A){if(this.player){if(A.onDurationChange){let{onDurationChange:t}=A;this.player.ondurationchange=o=>{t(o.target.duration)}}if(A.onTimeUpdate){let t=A.onTimeUpdate,{player:o}=this;o.ontimeupdate=()=>{t(o.currentTime,o.duration)}}A.onEnded&&(this.player.onended=A.onEnded)}}reload(A){return XA(this,null,function*(){if(A.url){let t=yield wj.download(A.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(t),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(A),this.updateSettings(A))}else this.mixInput.replaceSource(A.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(A){this.player&&(A<0&&A>this.player.duration||(this.player.currentTime=A,this.publisher.currentTime=A))}play(){var A,t;return Promise.all([(A=this.player)==null?void 0:A.play(),(t=this.publisher)==null?void 0:t.play()])}pause(){var A,t;(A=this.player)==null||A.pause(),(t=this.publisher)==null||t.pause()}stop(){var A;(A=this.player)==null||A.pause(),this.mixInput.disconnect()}setOperation(A){A==="pause"&&this.pause(),A==="resume"&&(this.pause(),this.play()),A==="stop"&&(this.pause(),this.seek(0))}set volume(A){!this.player||!this.publisher||(this.player.volume=A,this.publisher.volume=A)}set loop(A){!this.player||!this.publisher||(this.player.loop=A,this.publisher.loop=A)}set playbackRate(A){!this.player||!this.publisher||(this.player.playbackRate=A,this.publisher.playbackRate=A)}};function M_(A,t){if(t&&typeof t!="function")throw new Lo({code:ko.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(A," should be a function.")})}var vL=class JL{constructor(t){this.core=t,Y(this,"log"),Y(this,"mixedMusicMap",new Map),Y(this,"cacheMusicMap",new Map),kj+=1,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(kj)}),this.log.info("created id=".concat(this.getAlias()).concat(kj))}getName(){return JL.Name}getAlias(){return"ax"}getGroup(t){return t?.id}getValidateRule(t){switch(t){case"start":return JL.startValidateRule;case"update":return JL.updateValidateRule;case"stop":return JL.stopValidateRule}}start(t){return XA(this,null,function*(){let{room:o}=this.core;this.core.validateSourceNode(),this.log.info("add music source, id: ".concat(t.id," url: ").concat(t.url,", track: ").concat(t.track));let{id:a,url:l}=t;if(this.mixedMusicMap.has(a))return;let d=this.cacheMusicMap.get(a);d?t.url?d.reset():(d.mixInput.replaceSource(t.track),d.mixInput.connect()):(d=new QoA(t,o.audioManager),this.cacheMusicMap.set(a,d)),d.updateListener(t),d.updateSettings(t);try{yield d.play()}catch(h){yield this.handleAutoPlayFailed(d,t,h)}this.mixedMusicMap.set(a,d),d.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:d.mixInput.source.node,refId:"ax-".concat(a)}),this.log.info("start mix audio track ".concat(a," success.")),ri.addEnum({key:502700,value:3}),this.kvUpload(t)})}handleAutoPlayFailed(t,o,a){return XA(this,null,function*(){if(a.name==="NotSupportedError")this.log.error("play failed, try to reload source. error: ".concat(a)),yield t.reload(o),yield t.play();else{if(a.name!=="NotAllowedError")throw a;if(this.core.room.enableAutoPlayDialog){let l=()=>{var d;(d=t.play())==null||d.finally(()=>{F.off("154",l,this)})};F.on("154",l,this),JC()}else this.core.trtc.emit(Ao.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>XA(this,null,function*(){return t.play()})})}})}update(t){return XA(this,null,function*(){let{id:o,operation:a,seekFrom:l,playbackRate:d}=t;this.log.info("update music source, ".concat(JSON.stringify(t)));let h=this.mixedMusicMap.get(o);h?(h.updateSettings(t),h.updateListener(t),ze(a)||h.setOperation(a),ze(l)||h.seek(l),this.kvUpload(t)):this.log.warn("update music source failed, music id: ".concat(o," not found."))})}stop(t){return XA(this,arguments,function(o){var a=this;let{id:l}=o;return function*(){if(a.mixedMusicMap.has(l)){a.log.info("remove music source, music id: ".concat(l));let d=a.mixedMusicMap.get(l);d!=null&&d.mixInput.source.node&&a.core.room.audioManager.updateAudioReference({type:"remove",audioReference:d.mixInput.source.node,refId:"ax-".concat(l)}),d?.stop(),a.mixedMusicMap.delete(l)}l==="*"&&a.destroyAllMusic()}()})}kvUpload(t){let{track:o,loop:a,volume:l,playbackRate:d,operation:h,seekFrom:y,onTimeUpdate:S,onDurationChange:L,onEnded:V}=t;o&&ri.addCount({key:502009}),a&&ri.addCount({key:502001}),l&&ri.addCount({key:502002}),d&&ri.addCount({key:502003}),h&&ri.addCount({key:502004}),y&&ri.addCount({key:502005}),typeof S!="function"&&ri.addCount({key:502007}),typeof V!="function"&&ri.addCount({key:502008}),typeof L!="function"&&ri.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,o)=>{t!=null&&t.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.track,refId:o}),this.stop({id:o})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};Y(vL,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(A,t,o){if(A.url&&A.url!=="*"){let a=A.url.split("?")[0],l=["mp3","ogg","wav","flac"],d=a.split(".").pop(),h=l.indexOf(d)>=0,y=a.startsWith("blob"),S=a.startsWith("data");if(!(h||y||S))throw new Lo({code:ko.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:o})}if(!A.url&&!A.track)throw new Lo({code:ko.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:o});M_("onTimeUpdate",A.onTimeUpdate),M_("onEnded",A.onEnded),M_("onDurationChange",A.onDurationChange)}}),Y(vL,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(A,t,o){M_("onTimeUpdate",A.onTimeUpdate),M_("onEnded",A.onEnded),M_("onDurationChange",A.onDurationChange)}}),Y(vL,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),Y(vL,"Name","AudioMixer");var Lj,poA=vL,Uj=0,k1=class qL{constructor(t){this.core=t,Y(this,"log"),Y(this,"audioContext",VI()),Y(this,"workletNode"),Y(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5}),Uj+=1,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(Uj)}),this.log.info("created id=".concat(this.getAlias()).concat(Uj))}static startValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(o,a,l,d){if(!t.room.audioManager.hasAudioTrack)throw new Lo({code:ko.INVALID_OPERATION,extraCode:5106,fnName:l})}}}preload(t){return Lj||(Lj=this.doPreload(t)),Lj}doPreload(t){return XA(this,null,function*(){let o=yield this.core.fileDownloader.download(t,{type:"blob"}),a=URL.createObjectURL(o);try{yield qg(this.audioContext,a)}catch(l){throw this.log.error("load worklet failed",l),l}finally{URL.revokeObjectURL(a)}})}getName(){return qL.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return qL.startValidateRule(this.core);case"update":return qL.updateValidateRule;case"stop":return qL.stopValidateRule}}start(t){return XA(this,null,function*(){let{room:o,schedule:a}=this.core,{assetsPath:l=this.core.assetsPath}=t;if(!l)throw new Lo({code:ko.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(l,"/denoiser-wasm").concat(Vv()?"":"-nosimd",".js")),!this.workletNode){let d=String(Date.now()).slice(0,-3),{auth:h,sign:y,status:S,message:L}=yield function(V,H){return XA(this,arguments,function(lA,hA){let{sdkAppId:MA,userId:oe,userSig:fe,timestamp:je}=hA;return function*(){try{let{data:{errCode:_e,errMsg:vi,sign:Fe,status:Dt}}=yield lA.getAbilityConfig(MA,lA.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:MA,userId:oe,userSig:fe,timestamp:je});if(Dt==="1")return{auth:!0,sign:Fe,status:Dt,message:vi};let pi=zd(MA)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",Mi="Init RTCAIDenoiser failed.",Wo="";switch(_e){case 1:Wo="Please check your params.";break;case 2:Wo="You need to buy packages. Refer to: ".concat(pi);break;case 3:Wo="Server is invalid. Please contact our engineer. ";break;case 4:Wo="Your packages is not active. Refer to: ".concat(pi);break;case 5:Wo="Your packages is expired. Refer to: ".concat(pi);break;case 6:Wo="Your version is not supported."}return{auth:!1,status:Dt,message:vi?"".concat(Mi," Reason: ").concat(vi,". ").concat(Wo):"".concat(Mi,", ").concat(Wo)}}catch(_e){return{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(_e)}}}()})}(a,So(Di({},t),{timestamp:d}));if(!h)throw this.log.info("RTCAIDenoiser: ".concat(t.userId," auth result: ").concat(h,". Message: ").concat(L)),new Lo({code:ko.INVALID_PARAMETER,message:L});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(t.sdkAppId),userId:t.userId,timestamp:d,sign:y,status:S}}),this.workletNode.port.onmessage=V=>{var H;let{data:lA}=V;if(lA.type==="cost"){let hA=lA?.max>20?"warn":lA?.max>10?"info":"debug";this.log[hA]("avg cost: ".concat(lA.value," max: ").concat(lA?.max,"(").concat(Gb(new Date(lA?.maxCostTimestamp)),") hist: ").concat((H=lA?.hist)==null?void 0:H.join(" ")))}else lA.type==="log"&&this.log[lA.logLevel]("".concat(lA.value))}}this.updateConfig(t),this.workletNode.port.postMessage({type:"enable"}),o.audioManager.addDenoiser(this.workletNode),o.sendAbilityStatus({ai_denoise:1})})}update(t){return XA(this,null,function*(){this.updateConfig(t)})}stop(){return XA(this,null,function*(){if(!this.workletNode)return;let{room:t}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeDenoiser(this.workletNode)})}updateConfig(t){if(!this.workletNode)return;let o=!1;ze(t.mode)||(t.mode===0?this.config.enableFarFieldReduce=!1:t.mode===1&&(this.config.enableFarFieldReduce=!0),o=!0),ze(t.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=t.farFieldReduceThreshold,o=!0),o&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};Y(k1,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),Y(k1,"stopValidateRule",{type:"object"}),Y(k1,"Name","AIDenoiser");var moA=k1,foA=dc(Xl(),1),yoA=class extends foA.EventEmitter{constructor(){super(),Y(this,"observer"),Y(this,"state","nominal"),this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return XA(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!za&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(A){ds.uploadEvent({log:"stat-pressure-detector-start-failed",error:A})}})}onPressureChange(A){let t=this.stateNum,o=A[A.length-1];this.state=o.state,(this.stateNum>3||t>3)&&pA.info("".concat(o.source,": ").concat(o.state)),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var A;try{(A=this.observer)==null||A.disconnect(),this.observer=null}catch(t){ds.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},A8=new yoA,Fj=0,Oj=class yX{constructor(t){this.core=t,Y(this,"log"),Y(this,"_seiMessageList",[]),Y(this,"_smallSeiMessageList",[]),Y(this,"_subStreamSeiMessageList",[]),Fj++,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(Fj)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(Fj)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(t){let{frame:o,mediaType:a}=t;try{return Jz({frame:o,seiMessageList:a===8?this._smallSeiMessageList:a===2?this._subStreamSeiMessageList:this._seiMessageList})}catch(l){this.log.warn(l)}return o}decode(t){let{frame:o,track:a}=t;return qz({frame:o,onSEI:l=>{l.forEach(d=>{a!=null&&a.userId?this.core.trtc.emit(Ao.SEI_MESSAGE,{seiPayloadType:d.seiPayloadType,data:d.seiPayload.buffer,userId:a.userId,streamType:a.mediaType===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:d})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(t){switch(t){case"start":case"update":case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:$p?this.encode:Jz,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:$p?this.decode:qz,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update(t){let{buffer:o,options:a}=t;var l;let d=[a.seiPayloadType,o],h=!!a.small;a.toSubStream?this._subStreamSeiMessageList.push(d):(this._seiMessageList.push(d),h&&this._smallSeiMessageList.push(d)),(l=this.core.room.scriptTransformWorker)==null||l.postMessage({type:"sei",data:d,isMain:!a.toSubStream,small:h})}getName(){return yX.Name}getAlias(){return"sei"}getGroup(){return"sei"}};Y(Oj,"autoStart",!0),Y(Oj,"Name","SEI");var L1,DoA=Oj,SoA=0,Pj=class DX{constructor(t){this.core=t,Y(this,"_core"),Y(this,"log"),Y(this,"dialog"),this._core=t,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(++SoA)}),this.log.info("created")}getName(){return DX.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(t){switch(t){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return XA(this,null,function*(){var t;!new URLSearchParams(location.search).has("trtcDebug")&&((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog())})}update(t){return XA(this,arguments,function(o){var a=this;let{visible:l}=o;return function*(){l?yield a.openDebugDiaLog():a.closeDebugDiaLog()}()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return XA(this,null,function*(){var t;if(!this.dialog)try{if(L1)yield L1;else{let o=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||"https://unpkg.com/".concat("trtc-sdk-v5","@").concat(Wd,"/assets/debug-dialog.js");L1=this._core.fileDownloader.loadScript(o),yield L1}this.dialog=new TRTCDebugDialog(this._core,this.log),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(o){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(o))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}};Y(Pj,"Name","Debug"),Y(Pj,"autoStart",!0);var voA=Pj,e8=A=>{switch(A){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},t8=class{constructor(A,t,o){Y(this,"trackDoneOB"),Y(this,"startOB"),Y(this,"stopOB"),Y(this,"inputFrameCount",0),Y(this,"decodedFrameCount",0),Y(this,"type","auto"),Y(this,"config"),Y(this,"decoder"),Y(this,"_decodeSink");let{kvStatManager:a,trtc:l}=A;this.config=o.config,this.trackDoneOB=Ea(t,gs.INIT),this.stopOB=BQ(),this.startOB=BQ(),o.type==="auto"?this.type="webCodecs":this.type=o.type;let d=BQ();Ma(this.startOB,lj(0),h1(h=>{let y=this.pipe(t);return d.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),Ma(y,CE(this.stopOB),Dl(()=>{},S=>{t.log.error(S),a.addFailedEvent({key:e8(this.type),error:S}),h>4?this.startOB.error(S):this.startOB.next(h+1)})),Ma(y,p_(1),Ez(Ej))}),CE(this.stopOB),Dl(()=>{t.player.setOutput(),d.next("STARTED")},h=>{d.next("FAILED")},()=>{a.addSuccessEvent({key:e8(this.type)}),a.addSuccessEvent({key:504702})}))}mock(A){this._decodeSink?this._decodeSink.error(A):this.startOB.next(0)}close(A){this.stopOB.next(A)}pipe(A){return IL()(t=>XA(this,null,function*(){this._decodeSink=t,t.defer(()=>{var a;(a=this.decoder)==null||a.close()});let{type:o}=this;try{o==="webCodecs"&&(this.decoder=new AudioDecoder({error:a=>{A.log.error(a),t.error(4)},output:a=>{this.decodedFrameCount++,t.next(a),A.player.write(a)}})),this.decoder.configure(this.config)}catch(a){A.log.error(a),t.error(o==="webCodecs"?2:6)}}))}decodeFrame(A){var t;this.inputFrameCount++,((t=this.decoder)==null?void 0:t.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:A.data,timestamp:A.timestamp,type:"key"}))}},MoA={type:"object"},i8=class uW{constructor(t){this.core=t,Y(this,"log"),Y(this,"contextMap",new Map),Y(this,"decodeProcessorMap",new WeakMap),this.log=t.log.createChild({id:"".concat(this.getAlias())})}getAlias(){return uW.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return uW.Name}getValidateRule(t){return MoA}start(t){let{track:o}=t;this.decodeProcessorMap.set(o,this.decode(t)),this.core.room.audioManager.addDecodeProcessor({processor:a=>{let{frame:l,track:d}=a;return this.decodeProcessorMap.has(d)?this.decodeProcessorMap.get(d)({frame:l,track:d}):l},type:3})}decode(t){return o=>{let{frame:a,track:l}=o;if(l!==t.track)return a;if(this.contextMap.has(l))return this.contextMap.get(l).decodeFrame(a);let d=new t8(this.core,l,t);return Ma(d.trackDoneOB,p_(1),Dl(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:l})})),this.contextMap.set(l,d),d.decodeFrame(a)}}stop(t){let{track:o}=t,a=this.contextMap.get(o);a&&(a.close("stop"),this.contextMap.delete(o),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(t){let o=this.contextMap.get(t.track);if(o){if(t.type==="mock")return void o.mock(10);o.close("update"),this.contextMap.set(t.track,new t8(this.core,t.track,t))}}};Y(i8,"Name","TRTCAudioDecoder");var o8=i8,RoA={rttPoorLimit:150,lossPoorLimit:20,rttGoodLimit:100,lossGoodLimit:10,fpsPoorLimit:5,cooldownTime:1e4,poorCount:3,goodCount:5,maxUpgradeFailCount:3},woA=class{constructor(){Y(this,"log"),Y(this,"autoMode",{enabled:!1,instance:null,config:RoA,sortedStreamList:[],currentQualityIndex:0}),Y(this,"switchControl",{isInternal:!1,isSwitching:!1,lastSwitchTime:0,boundOnStatistics:null}),Y(this,"networkMetrics",{frameRate:0,rtt:0,loss:0}),Y(this,"counters",{rttUnder:0,lossUnder:0,downgradeCondition:0,upgradeFail:0}),Y(this,"onStatistics",A=>{var t,o;if(!this.autoMode.instance)return;let{config:a}=this.autoMode;if(this.networkMetrics.rtt=A.rtt,this.networkMetrics.loss=A.downLoss,this.counters.rttUnder=A.rttV.userId===d);if((o=y?.video)==null||!o.length)return;let S=h==="sub"?"sub":"big",L=y.video.find(V=>V.videoType===S);L?(this.networkMetrics.frameRate=L.frameRate||0,this.checkAndSwitchQuality()):this.log.warn("onStatistics: videoStat not found for userId=".concat(d,", streamType=").concat(h))}),this.log=pA.createLogger({id:"pqs"})}getCurrentPlayingStream(A){var t,o;let a=A,l=a._playbackQualityList;if(!l||l.length===0)return this.log.warn("getCurrentPlayingStream: streamList is empty"),null;for(let d of l){let h=A.room.remotePublishedUserMap.get(d.userId);if(!h)continue;let y=(t=d.streamType)!=null?t:"main";if((y==="sub"?h.remoteAuxiliaryTrack:h.remoteVideoTrack).isPlayCalled){let S=(o=a._remoteVideoConfigMap.get("".concat(d.userId,"_").concat(y)))==null?void 0:o.config;if(S)return{userId:d.userId,streamType:y,config:S}}}return null}switchPlaybackQuality(A){return XA(this,null,function*(){var t;let{trtcInstance:o,streamList:a,quality:l}=A;this.log.info("switchPlaybackQuality quality: ".concat(l,", streamList: ").concat(JSON.stringify(a)));let d=o;if(a&&a.length>0&&(d._playbackQualityList=a.map(MA=>{var oe;return So(Di({},MA),{streamType:(oe=MA.streamType)!=null?oe:"main"})})),l==="auto")return void(yield this.startAutoMode(o));if(this.autoMode.enabled&&l&&!this.switchControl.isInternal&&this.stopAutoMode(),!l)return;if(!d._playbackQualityList||d._playbackQualityList.length<=0)return void this.log.warn("switchPlaybackQuality: streamList is empty, please call with streamList first");let h=d._playbackQualityList.find(MA=>MA.name===l);if(!h)return void this.log.warn('switchPlaybackQuality: quality "'.concat(l,'" not found in streamList'));let y=this.getCurrentPlayingStream(o);if(this.log.info("currentPlaying userId: ".concat(y?.userId,", streamType: ").concat(y?.streamType)),!y)return;let S=(t=h.streamType)!=null?t:"main";if(y.userId===h.userId&&y.streamType===S)return void this.log.info("switchPlaybackQuality: already playing target stream");let L=Di({},y.config);L.streamType==="main"&&S==="main"&&(yield o.muteRemoteAudio(L.userId,!0));let V,H=new Promise(MA=>{V=MA}),lA=MA=>{MA.userId===h.userId&&MA.streamType===S&&MA.state==="PLAYING"&&MA.reason==="playing"&&V("success")};o.on(Ao.VIDEO_PLAY_STATE_CHANGED,lA);let hA=new Promise(MA=>setTimeout(()=>MA("timeout"),1e4));try{if(yield o.startRemoteVideo(So(Di({},y.config),{userId:h.userId,streamType:S,option:So(Di({},y.config.option),{isLiveStream:!0})})),(yield Promise.race([H,hA]))==="timeout"){this.log.error("switchPlaybackQuality: VIDEO_PLAY_STATE_CHANGED timeout, rollback");try{yield o.stopRemoteVideo({userId:h.userId,streamType:S})}catch(oe){this.log.warn("switchPlaybackQuality: rollback stopRemoteVideo failed",oe)}throw L.streamType==="main"&&S==="main"&&(yield o.muteRemoteAudio(L.userId,!1).catch(oe=>{this.log.warn("switchPlaybackQuality: rollback muteRemoteAudio failed",oe)})),new li({code:mt.SUBSCRIPTION_TIMEOUT,message:sn({key:Go.SWITCH_PLAYBACK_QUALITY_TIMEOUT,data:{userId:h.userId}})})}let MA=o.stopRemoteVideo(L);L.streamType==="main"&&S==="main"?yield Promise.all([o.muteRemoteAudio(h.userId,!1).catch(oe=>{this.log.warn("muteRemoteAudio(new, false) failed",oe)}),MA]):yield MA,d._currentLiveUserId=h.userId,d._currentLiveStreamType=S}finally{o.off(Ao.VIDEO_PLAY_STATE_CHANGED,lA)}})}startAutoMode(A){return XA(this,null,function*(){if(this.autoMode.enabled)return void this.log.info("auto mode already enabled");let t=A;if(!t._playbackQualityList||t._playbackQualityList.length<=1)return void this.log.warn("startAutoMode: need at least 2 streams in streamList for auto mode");this.autoMode.enabled=!0,this.autoMode.instance=A,this.counters.rttUnder=0,this.counters.lossUnder=0,this.counters.downgradeCondition=0,this.counters.upgradeFail=0,this.switchControl.lastSwitchTime=0;let o=t._playbackQualityList||[];this.autoMode.sortedStreamList=[...o].sort((l,d)=>d.bitrate-l.bitrate),this.log.info("auto mode streams: ".concat(this.autoMode.sortedStreamList.map(l=>"".concat(l.name,"(").concat(l.bitrate,"kbps)")).join(" > ")));let a=this.getCurrentPlayingStream(A);if(a){let{userId:l,streamType:d}=a,h=this.autoMode.sortedStreamList.findIndex(y=>{var S;return y.userId===l&&((S=y.streamType)!=null?S:"main")===d});this.autoMode.currentQualityIndex=h>=0?h:0}else this.autoMode.currentQualityIndex=0;this.switchControl.boundOnStatistics=this.onStatistics,A.on(Ao.STATISTICS,this.switchControl.boundOnStatistics),this.log.info("auto mode started")})}stopAutoMode(){this.autoMode.enabled&&(this.autoMode.instance&&this.switchControl.boundOnStatistics&&this.autoMode.instance.off(Ao.STATISTICS,this.switchControl.boundOnStatistics),this.switchControl.boundOnStatistics=null,this.autoMode.enabled=!1,this.autoMode.instance=null,this.autoMode.sortedStreamList=[],this.autoMode.currentQualityIndex=0,this.counters.rttUnder=0,this.counters.lossUnder=0,this.counters.downgradeCondition=0,this.counters.upgradeFail=0,this.networkMetrics.frameRate=0,this.networkMetrics.rtt=0,this.networkMetrics.loss=0,this.switchControl.isSwitching=!1,this.log.info("auto mode stopped"))}checkAndSwitchQuality(){var A;if(!this.autoMode.enabled||!this.autoMode.instance||this.switchControl.isSwitching)return;let{config:t}=this.autoMode,o=Date.now()-this.switchControl.lastSwitchTime0,h=this.networkMetrics.frameRate<=t.fpsPoorLimit,y=this.networkMetrics.loss>=t.lossPoorLimit||this.networkMetrics.rtt>=t.rttPoorLimit,S=h&&y;this.counters.downgradeCondition=S?this.counters.downgradeCondition+1:0;let L=this.counters.rttUnder>=t.goodCount&&this.counters.lossUnder>=t.goodCount,V=this.counters.upgradeFail{if(V.remoteAudioTrack.isAvailable){if(S.get(V.userId))return;let H=y.getPCM(lA=>{t.emit(Ao.AUDIO_FRAME,lA)},V.userId);S.set(V.userId,H)}});else{if(S.get(a))return;let V=y.getPCM(H=>{t.emit(Ao.AUDIO_FRAME,H)},a);S.set(a,V)}else if(a==="*")t.room.remotePublishedUserMap.forEach(V=>{if(V.remoteAudioTrack.isSubscribed){let{userId:H}=V,lA=S.get(H);lA?.abort("disable"),S.delete(H)}});else{let V=S.get(a);V?.abort("disable"),S.delete(a)}})}resumeRemotePlayer(A){return XA(this,null,function*(){if(A.userId==="*"){let o=[];return A.trtcInstance.room.remotePublishedUserMap.forEach(a=>{let{remoteAudioTrack:l,remoteVideoTrack:d,remoteAuxiliaryTrack:h}=a;A.streamType?A.streamType==="main"?(l.isAvailable&&o.push(l.player.resume()),d.isAvailable&&o.push(d.player.resume())):h.isAvailable&&o.push(h.player.resume()):(l.isAvailable&&o.push(l.player.resume()),d.isAvailable&&o.push(d.player.resume()),h.isAvailable&&o.push(h.player.resume()))}),Promise.all(o)}let t=A.trtcInstance.room.remotePublishedUserMap.get(A.userId);if(t)return A.streamType==="main"?Promise.all([t.remoteAudioTrack.player.resume(),t.remoteVideoTrack.player.resume()]):t.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(A){if(A.userId==="*")A.trtcInstance.room.remotePublishedUserMap.forEach(t=>{let{remoteAudioTrack:o,remoteVideoTrack:a,remoteAuxiliaryTrack:l}=t;A.streamType?A.streamType==="main"?(o.isAvailable&&o.player.pause(),a.isAvailable&&a.player.pause(!1)):l.isAvailable&&l.player.pause(!1):(o.isAvailable&&o.player.pause(),a.isAvailable&&a.player.pause(!1),l.isAvailable&&l.player.pause(!1))});else{let t=A.trtcInstance.room.remotePublishedUserMap.get(A.userId);t&&(A.streamType==="main"?(t.remoteAudioTrack.player.pause(),t.remoteVideoTrack.player.pause(!1)):t.remoteAuxiliaryTrack.player.pause(!1))}}requestPictureInPicture(A){let t=[...A.trtcInstance.room.remotePublishedUserMap.values()].find(o=>o.remoteVideoTrack.isAvailable);return t?A.enable?t.remoteVideoTrack.player.enterPictureInPicture():t.remoteVideoTrack.player.exitPictureInPicture():Promise.reject(new li({code:mt.INVALID_OPERATION,message:"no available remote video"}))}requestFullScreen(A){let t=[...A.trtcInstance.room.remotePublishedUserMap.values()].find(o=>o.remoteVideoTrack.isAvailable);return t?A.enable?t.remoteVideoTrack.player.enterFullscreen():t.remoteVideoTrack.player.exitFullscreen():Promise.reject(new li({code:mt.INVALID_OPERATION,message:"no available remote video"}))}switchPlaybackQuality(A){return XA(this,null,function*(){let t=A.trtcInstance;return t._playbackQualitySwitcher||(t._playbackQualitySwitcher=new woA),t._playbackQualitySwitcher.switchPlaybackQuality(A)})}prelink(A){return XA(this,null,function*(){let{trtcInstance:t}=A;return A.enable?t.room.prelink(A.sdkAppId,A.userId,A.userSig,RL.frameWorkType,A.roomId,A.strRoomId):t.room.closePrelink()})}};Qi([yz({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],xj.prototype,"enableAudioFrameEvent"),Qi([yz({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!1,type:"string"},sdkAppId:{required:!1,type:"number"},userSig:{required:!1,type:"string"},roomId:{required:!1,type:"number"},strRoomId:{required:!1,type:"string"}}})],xj.prototype,"prelink");var _oA=new xj,ToA=dc(Xl(),1),NoA=class extends ToA.EventEmitter{constructor(){super(),Y(this,"states",{}),Y(this,"permissionChangeHandler"),Y(this,"log"),this.log=pA.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var A,t;this.emit("permission-state-change",{camera:(A=this.states.camera)==null?void 0:A.state,microphone:(t=this.states.microphone)==null?void 0:t.state})}}request(A){return XA(this,null,function*(){if(this.log.info("request ".concat(A.join(", "))),A.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:A.includes("camera"),audio:A.includes("microphone")})).getTracks().forEach(t=>t.stop())})}get(A){return XA(this,null,function*(){try{return this.states[A]||(this.states[A]=yield navigator.permissions.query({name:A}),this.states[A].addEventListener("change",this.permissionChangeHandler)),this.log.info("get ".concat(A," permission state: ").concat(this.states[A].state)),this.states[A].state}catch(t){return this.log.error("get ".concat(A," permission failed, error: ").concat(t instanceof Error?t.message:t)),null}})}destroy(){Object.values(this.states).forEach(A=>{A?.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},U1=new NoA,n8=0,ML=new Set,tI=null;zx(Xz),$A.checkStorage();var bn=class Im extends _K.EventEmitter{constructor(t,o){super(),Y(this,"_room"),Y(this,"_eventListened",new Set),Y(this,"_localVideoTrack",null),Y(this,"_localAudioTrack",null),Y(this,"_localScreenTrack",null),Y(this,"_localScreenAudioTrack",null),Y(this,"_localVideoConfig",null),Y(this,"_localScreenConfig",null),Y(this,"_localAudioConfig",null),Y(this,"_remoteVideoConfigMap",new Map),Y(this,"_remoteAudioConfigMap",new Map),Y(this,"_remoteAudioVolumeMap",new Map),Y(this,"_remoteAudioMuteMap",new Map),Y(this,"_mediaTrackMap",new WeakMap),Y(this,"_log",pA.createLogger({id:"t".concat(++n8)})),Y(this,"_plugins",new Map),Y(this,"_networkQuality",null),Y(this,"_speakerId"),Y(this,"enterRoomParams"),Y(this,"_enableAutoSwitchWhenRecapturing",!0),Y(this,"_autoSubscribeDataChannel",!1),Y(this,"_playbackQualityList",[]),this._room=new t(Di({logger:this._log,frameWorkType:Im.frameWorkType},o)),this._room.videoDecodeFallbackType=o.videoDecodeFallback,br(o.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=o.enableAutoSwitchWhenRecapturing),this._log.info("create() ".concat(JSON.stringify(o,(a,l)=>a==="plugins"?l.map(d=>d.Name):l))),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(a){return this._room.audioManager.dump(a)}}}),o.plugins&&o.plugins.forEach(a=>{this._use(a,o.assetsPath)}),this._use(poA,o.assetsPath),this._use(BoA,o.assetsPath),this._use(moA,o.assetsPath),this._use(o8,o.assetsPath),this._use(voA),o.enableSEI&&$k&&this._use(DoA),this._room.on("audio-volume",a=>{var l,d;!a.find(h=>h.userId==="")&&this._localAudioTrack&&a.push({userId:"",volume:Math.floor(100*((l=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?l:this._localAudioTrack.getAudioLevel())),floatVolume:(d=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?d:this._localAudioTrack.getInternalAudioLevel()}),o.volumeType===1&&a.forEach(h=>{var y;let S=h.userId===""?this._localAudioTrack:(y=this.room.remotePublishedUserMap.get(h.userId))==null?void 0:y.remoteAudioTrack;S&&(h.volume=S.dbVolume)}),o.enableDbVolume&&a.forEach(h=>{var y;let S=h.userId===""?this._localAudioTrack:(y=this.room.remotePublishedUserMap.get(h.userId))==null?void 0:y.remoteAudioTrack;S&&(h.volume=S.dbVolume)}),this.emit(Ao.AUDIO_VOLUME,{result:a.sort((h,y)=>y.volume-h.volume)})}),this._room.videoManager.on("error",a=>{this._log.error(new Lo({code:ko.OPERATION_FAILED,extraCode:5504,message:a.message,originError:a}))}),this._listenEvents(),this._initActiveSpeaker(),((a,l)=>{let{emit:d}=a;a.emit=function(){for(var h=arguments.length,y=new Array(h),S=0;S{let S=[],L=[],V=[],H=0;self.onmessage=lA=>{switch(lA.data.type){case"sei":lA.data.isMain?(S.push(lA.data.data),lA.data.small&&V.push(lA.data.data)):L.push(lA.data.data);break;case"ntp-offset":H=lA.data.data}},self.onrtctransform=lA=>{let{options:hA}=lA.transformer,MA=hA.isReceiver?jz({userId:hA.userId,streamType:hA.streamType,isAudio:hA.isAudio}):Kz({getNtpTime:()=>Date.now()+H,isAudio:hA.isAudio,isMain:hA.isMain,seiMessageList:hA.isMain?hA.small?V:S:L});lA.transformer.readable.pipeThrough(MA).pipeTo(lA.transformer.writable)}},")();").concat(a,"})()"),d=new Blob([l],{type:"text/javascript"}),h=URL.createObjectURL(d),y=new Worker(h);return URL.revokeObjectURL(h),y}var zz,_j=class{constructor(A){Y(this,"audioPlayer"),Y(this,"videoPlayer"),Y(this,"log"),this.audioPlayer=A.audioPlayer,this.videoPlayer=A.videoPlayer,this.log=A.log.createChild({id:"pip"}),this.videoPlayer.on(Mo.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.on(Mo.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.on(Mo.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(Mo.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(Mo.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.on(Mo.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.on(Mo.VOLUME_CHANGE,this.handleVolumeChange,this)}handleUserResumeInPIPOrFullScreen(){this.audioPlayer.isPaused&&(this.log.warn("resume audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doResume()),za&&Iy&&this.videoPlayer.resetSrcObjectToReplay()}handleUserPauseInPIPOrFullScreen(){this.audioPlayer.isPaused||(this.log.warn("pause audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doPause())}handleEnterPIPOrFullScreen(){this.videoPlayer.element&&this.audioPlayer.muted!==this.videoPlayer.element.muted&&(this.log.warn("sync video muted to ".concat(this.audioPlayer.muted," when enter ").concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.videoPlayer.element.muted=this.audioPlayer.muted)}handleLeavePIP(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume after leave pip"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave pip"),this.videoPlayer.doResume())}handleLeaveFullScreen(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume audio after leave fullscreen"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave fullscreen"),za&&Iy?this.videoPlayer.resetSrcObjectToReplay():this.videoPlayer.doResume())}handleVolumeChange(A){A.muted!==void 0&&this.audioPlayer.muted!==A.muted&&(this.log.warn("sync audio muted to ".concat(A.muted," in ").concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.setMuted(A.muted))}destroy(){this.videoPlayer.off(Mo.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.off(Mo.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.off(Mo.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(Mo.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(Mo.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.off(Mo.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.off(Mo.VOLUME_CHANGE,this.handleVolumeChange,this)}},Zz=!1;function CoA(A){var t=this;let{TRTC:o,room:a,errorModule:l,assetsPath:d}=A;return{TRTC:o,LocalMixVideoTrack:mj,LocalVideoTrack:QQ,LocalScreenTrack:eM,room:a,assetsPath:d,fileDownloader:wj,innerEmitter:F,INNER_EVENT:rA,constants:Wx,environment:N2,utils:hz,eventLogger:ds,log:this.room.getLogger(),loggerManager:pA,errorModule:l,kvStatManager:ri,rtcDectection:ge,trtc:this,rx:q5,enums:Oe,schedule:Lz,getDevices:c1,initVisionTaskRegistry:function(h,y){let S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"/mediapipe/vision.js";return XA(t,null,function*(){!window.VisionTaskRegistry&&!Zz&&(Zz=!0,zz=wj.loadScript("".concat(h,"/").concat(S).replace(/([^:]\/)\/+/g,"$1"))),yield zz,yield(yield window.VisionTaskRegistry.getInstance(h)).preloadModels(y)})},audioContext:VI(),deviceDetector:Kc,AudioPlayer:rj,RemoteAudioPlayer:P5,VideoPlayer:bo,showAutoPlayDialog:JC,Timer:kr,clearStarted:(h,y)=>{let S=h.getAlias(),L=DL.instances.get(this);if(L)if(y){let V=L.get(S+y);if(!V)return;V.started=!1}else L.forEach((V,H)=>{H.startsWith(S)&&(V.started=!1)})},startGetPCM:Sj,createAudioNode:r1,getNetworkTimeOffset:Kx,validateSourceNode:()=>{var h;if(gr&&((h=this.room.audioManager._localAudioPipline)==null||!h.source.node))throw new Lo({code:ko.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})},createScriptTransformWorker:Wz,AVPlayerStateSyncManager:_j,PlayerEvent:Mo}}var v_=new WeakMap,Xz="5.15.3-beta.12";function mu(){for(var A=arguments.length,t=new Array(A),o=0;ofunction(){for(var d=arguments.length,h=new Array(d),y=0;yfunction(){for(var d=arguments.length,h=new Array(d),y=0;yty(V)?Iv(V):Ws(V)?V:pg(V))},value:o}})}else if(!ze(t.type)&&pg(o)!==t.type)throw new Lo(h(5002));if(t.allowEmpty===!1){let L=Ys(o)&&(o===0||Number.isNaN(o)),V=Ws(o)&&o.trim()==="";if(L||V)throw new Lo(h(5003))}if(t.notLessThanZero&&Ys(o)&&o<0)throw new Lo(h(5006));if(!ze(t.min)&&Ys(o)&&ot.max)throw new Lo(h(5008));if(Ws(t.instanceOf)){if(!o||o._name!==t.instanceOf)throw new Lo(h(5004))}else if(ba(t.instanceOf)&&!(o instanceof t.instanceOf))throw new Lo(h(5004));if(Array.isArray(t.values)&&!t.values.includes(o))throw new Lo(h(5005));let{properties:y}=t;uE(y)&&ed(o)&&Object.keys(y).forEach(L=>{G1.call(this,{rule:y[L],value:o&&o[L],key:"".concat(L),fnName:l,className:d})});let{arrayItem:S}=t;uE(S)&&ka(o)&&o.forEach((L,V)=>{G1.call(this,{rule:S,value:L,key:"".concat(a,"[").concat(V,"]"),fnName:l,className:d})}),ba(t.validate)&&t.validate.call(this,o,a,l,d,this)}var hoA=0;function Ra(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{getRemoteId:t=()=>"",replaceArg:o,getKVReportKey:a,ignoreLog:l,ignoreErrorLog:d}=A;return Xr((h,y)=>function(){for(var S=arguments.length,L=new Array(S),V=0;V0?oe.info("".concat(y,"() ").concat(fe," ").concat(JSON.stringify(L,(vi,Fe)=>MA(vi,Fe,["userSig","privateMapKey"])))):oe.info("".concat(y,"() ").concat(fe));let je=a?a(...L):K2[y],_e=d?.(...L)||!1;try{let vi=h.apply(this,L),Fe=Oo();if(ey(vi)){let Dt="".concat(y.includes("Plugin")?"".concat(((lA=(H=L[0]).getName)==null?void 0:lA.call(H))||""," "):" ");return vi.then(pi=>(oe.info("".concat(y,"() success ").concat(fe," ").concat(Dt).concat(t.call(this,...L))),ri.addSuccessEvent({key:je,cost:Oo()-Fe}),pi)).catch(pi=>{var Mi;let Wo=(pi=Lo.convertFrom.call(this,pi,y,L.length===1?L[0]:L)).extraCode||pi.code,zo=(Mi=pi.message)!=null&&Mi.includes(Wo)?"":" code:".concat(Wo),vs=pi?.code===ko.OPERATION_ABORT;throw _e||oe[vs?"warn":"error"]("".concat(y,"() failed ").concat(fe," ").concat(Dt).concat(t.call(this,...L)," ").concat(pi).concat(zo," params: ").concat(JSON.stringify(L,MA))),ri.addFailedEvent({key:je,error:pi}),pi})}return ri.addSuccessEvent({key:je}),vi}catch(vi){let Fe=(vi=Lo.convertFrom.call(this,vi,y)).extraCode||vi.code,Dt=(hA=vi.message)!=null&&hA.includes(Fe)?"":" code:".concat(Fe),pi=vi?.code===ko.OPERATION_ABORT;throw _e||oe[pi?"warn":"error"]("".concat(y,"() failed ").concat(fe," ").concat(vi).concat(Dt," params: ").concat(JSON.stringify(L,MA))),ri.addFailedEvent({key:je,error:vi}),vi}})}var Nj,Gj=A=>Xr((t,o)=>function(a,l){return XA(this,null,function*(){let d=this._plugins.get(a);if(!d)throw this._log.error("plugin ".concat(String(a)," is not found")),new Lo({code:ko.OPERATION_ABORT,message:"plugin ".concat(String(a)," is not found"),fnName:o});if(ba(d.constructor.isSupported)&&!d.constructor.isSupported())throw this._log.error("plugin ".concat(String(a)," is not supported")),new Lo({code:ko.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(a)," is not supported"),extraCode:5210,fnName:o});return Tj.call(this,d.getValidateRule(A),[l],o,"TRTC"),t.call(this,d,l)})}),bj=0,b1=class HL{constructor(t){this.core=t,Y(this,"log"),Y(this,"customAudioReferenceMap",new Map),Y(this,"audioRefId",0),Y(this,"audioContext",VI()),Y(this,"localAudioWorkletNode"),Y(this,"screenAudioWorkletNode"),Y(this,"mixNode"),Y(this,"silentNode"),bj+=1,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(bj)}),this.log.info("created id=".concat(this.getAlias()).concat(bj)),this.installEvent()}static getStartValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(o,a,l,d){if(!t.room.audioManager.hasAudioTrack&&!t.room.audioManager.hasScreenAudioTrack)throw new Lo({code:ko.INVALID_OPERATION,extraCode:5106,fnName:l})}}}preload(t){return Nj||(Nj=this.doPreload(t)),Nj}doPreload(t){return XA(this,null,function*(){let o=yield this.core.fileDownloader.download(t,{type:"blob"}),a=URL.createObjectURL(o);try{yield Kg(this.audioContext,a)}catch(l){this.log.error("preload audioProcessor failed. ".concat(l))}finally{URL.revokeObjectURL(a)}})}getName(){return HL.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(t){switch(t){case"start":return HL.getStartValidateRule(this.core);case"update":return HL.updateValidateRule;case"stop":return HL.stopValidateRule}}start(t){return XA(this,null,function*(){var o,a,l,d;let{room:h}=this.core,{sdkAppId:y,userId:S,userSig:L,assetsPath:V=this.core.assetsPath,audioReference:H,processLevel:lA,enableDump:hA,isLocalAudioNeedAudioProcess:MA=!0,isScreenAudioNeedAudioProcess:oe=!1}=t;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=MA,this.core.room.audioManager.isScreenAudioNeedAudioProcess=oe,!V)throw new Lo({code:ko.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(V,"/audioProcessor-wasm.js")),MA&&!this.localAudioWorkletNode){let{sign:fe,status:je,timestamp:_e}=yield this.getAuthData(y,S,L);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",y,S,_e,fe,je,h)}if(oe&&!this.screenAudioWorkletNode){let{sign:fe,status:je,timestamp:_e}=yield this.getAuthData(y,S,L);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",y,S,_e,fe,je,h)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(o=this.localAudioWorkletNode)==null||o.port.postMessage({type:"enable"}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"enable"}),h.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),ze(H)||H.forEach(fe=>{this.customAudioReferenceMap.set(fe,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:fe,refId:"o-".concat(this.audioRefId++)})}),ze(lA)||(l=this.localAudioWorkletNode)==null||l.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:lA}}),ze(hA)||(d=this.localAudioWorkletNode)==null||d.port.postMessage({type:"dump",data:{enable:hA}})})}update(t){return XA(this,null,function*(){var o,a,l;let{audioReference:d,enableDump:h,processLevel:y}=t;ze(d)||(this.customAudioReferenceMap.forEach((S,L)=>{this.customAudioReferenceMap.delete(L),this.core.room.audioManager.updateAudioReference({type:"remove",refId:S})}),d.forEach(S=>{this.customAudioReferenceMap.set(S,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:S,refId:"o-".concat(this.audioRefId++)})})),ze(y)||(o=this.localAudioWorkletNode)==null||o.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:y}}),ze(h)||((a=this.localAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:h}}),(l=this.screenAudioWorkletNode)==null||l.port.postMessage({type:"dump",data:{enable:h}}))})}stop(){return XA(this,null,function*(){var t,o;let{room:a}=this.core;(t=this.localAudioWorkletNode)==null||t.port.postMessage({type:"disable"}),(o=this.screenAudioWorkletNode)==null||o.port.postMessage({type:"disable"}),yield a.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(t,o,a){return XA(this,null,function*(){let l=String(Date.now()).slice(0,-3),{auth:d,sign:h,status:y,message:S}=yield function(L){return XA(this,arguments,function(V){let{sdkAppId:H,userId:lA,userSig:hA,timestamp:MA}=V;return function*(){let oe="".concat(function(Wo){let zo=arguments.length>1&&arguments[1]!==void 0?arguments[1]:JA.MAIN;return"https://".concat(rm[zo]||Mj(Wo,zo),"/api/v1/audioAiAuth")}(H),"?sdkAppId=").concat(H,"&userId=").concat(lA,"&userSig=").concat(hA,"×tamp=").concat(MA),fe=yield fetch(oe),{data:{errCode:je,errMsg:_e,sign:vi,status:Fe}}=yield fe.json();if(Fe==="1")return{auth:!0,sign:vi,status:Fe,message:_e};let Dt=zd(H)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",pi="Init RTCAudioProcessor failed.",Mi="";switch(je){case 1:Mi="Please check your params.";break;case 2:Mi="You need to buy packages. Refer to: ".concat(Dt);break;case 3:Mi="Server is invalid. Please contact our engineer. ";break;case 4:Mi="Your packages is not active. Refer to: ".concat(Dt);break;case 5:Mi="Your packages is expired. Refer to: ".concat(Dt);break;case 6:Mi="Your version is not supported."}return{auth:!1,status:Fe,message:_e?"".concat(pi," Reason: ").concat(_e,". ").concat(Mi):"".concat(pi,", ").concat(Mi)}}()})}({sdkAppId:t,userSig:a,userId:o,timestamp:l});if(!d)throw this.log.info("audioProcessor: ".concat(o," auth result: ").concat(d,". Message: ").concat(S)),new Lo({code:ko.INVALID_PARAMETER,message:S});return{sign:h,status:y,timestamp:l}})}initWorkletNode(t,o,a,l,d,h,y,S){t.port.postMessage({type:"init",data:{sdkAppId:String(a),userId:l,timestamp:d,sign:h,status:y}}),t.port.onmessage=L=>{var V;let{data:H}=L;switch(H.type){case"cost":let lA=H?.value>10?"info":"debug";return void this.log[lA]("".concat(o==="localAudio"?"":"[".concat(o,"] "),"avg cost: ").concat(H.value," max: ").concat(H?.max,"(").concat(Gb(new Date(H?.maxCostTimestamp)),") hist: ").concat((V=H?.hist)==null?void 0:V.join(" ")));case"log":return void this.log[H.logLevel]("".concat(o==="localAudio"?"":"[".concat(o,"] ")).concat(H.value));case"dump":return void F.emit("265",{room:S,data:H.value,type:o==="localAudio"?"dump":"dump-screen-audio"});case"detectEcho":return void this.log.warn("".concat(o==="localAudio"?"":"[".concat(o,"] "),"detect echo: ").concat(e_()?lQ():jp()))}}}handleLocalAudioStarted(t){return XA(this,null,function*(){var o;if(this.hitTest(t.room)&&((o=this.core.room.scheduleResult.config)==null?void 0:o.audioProcessor)===!0)try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(a){this.log.warn("audio processor auto start failed, error: ".concat(a))}})}handleLocalAudioStopped(t){return XA(this,null,function*(){var o;!this.hitTest(t.room)||((o=this.core.room.scheduleResult.config)==null?void 0:o.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(t){return t===this.core.room}};Y(b1,"updateValidateRule",{type:"object"}),Y(b1,"stopValidateRule",{type:"object"}),Y(b1,"Name","AudioProcessor");var BoA=b1,kj=0,QoA=class{constructor(A,t){Y(this,"audioObjectURL"),Y(this,"player"),Y(this,"publisher"),Y(this,"mixInput"),this.mixInput=new G5(t),A.url?(this.player=new Audio(A.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(A.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(A.track),this.mixInput.connect()}updateSettings(A){this.player&&(ze(A.volume)||(this.volume=A.volume),ze(A.loop)||(this.loop=A.loop),ze(A.playbackRate)||(this.playbackRate=A.playbackRate))}updateListener(A){if(this.player){if(A.onDurationChange){let{onDurationChange:t}=A;this.player.ondurationchange=o=>{t(o.target.duration)}}if(A.onTimeUpdate){let t=A.onTimeUpdate,{player:o}=this;o.ontimeupdate=()=>{t(o.currentTime,o.duration)}}A.onEnded&&(this.player.onended=A.onEnded)}}reload(A){return XA(this,null,function*(){if(A.url){let t=yield wj.download(A.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(t),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(A),this.updateSettings(A))}else this.mixInput.replaceSource(A.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(A){this.player&&(A<0&&A>this.player.duration||(this.player.currentTime=A,this.publisher.currentTime=A))}play(){var A,t;return Promise.all([(A=this.player)==null?void 0:A.play(),(t=this.publisher)==null?void 0:t.play()])}pause(){var A,t;(A=this.player)==null||A.pause(),(t=this.publisher)==null||t.pause()}stop(){var A;(A=this.player)==null||A.pause(),this.mixInput.disconnect()}setOperation(A){A==="pause"&&this.pause(),A==="resume"&&(this.pause(),this.play()),A==="stop"&&(this.pause(),this.seek(0))}set volume(A){!this.player||!this.publisher||(this.player.volume=A,this.publisher.volume=A)}set loop(A){!this.player||!this.publisher||(this.player.loop=A,this.publisher.loop=A)}set playbackRate(A){!this.player||!this.publisher||(this.player.playbackRate=A,this.publisher.playbackRate=A)}};function M_(A,t){if(t&&typeof t!="function")throw new Lo({code:ko.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(A," should be a function.")})}var vL=class JL{constructor(t){this.core=t,Y(this,"log"),Y(this,"mixedMusicMap",new Map),Y(this,"cacheMusicMap",new Map),kj+=1,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(kj)}),this.log.info("created id=".concat(this.getAlias()).concat(kj))}getName(){return JL.Name}getAlias(){return"ax"}getGroup(t){return t?.id}getValidateRule(t){switch(t){case"start":return JL.startValidateRule;case"update":return JL.updateValidateRule;case"stop":return JL.stopValidateRule}}start(t){return XA(this,null,function*(){let{room:o}=this.core;this.core.validateSourceNode(),this.log.info("add music source, id: ".concat(t.id," url: ").concat(t.url,", track: ").concat(t.track));let{id:a,url:l}=t;if(this.mixedMusicMap.has(a))return;let d=this.cacheMusicMap.get(a);d?t.url?d.reset():(d.mixInput.replaceSource(t.track),d.mixInput.connect()):(d=new QoA(t,o.audioManager),this.cacheMusicMap.set(a,d)),d.updateListener(t),d.updateSettings(t);try{yield d.play()}catch(h){yield this.handleAutoPlayFailed(d,t,h)}this.mixedMusicMap.set(a,d),d.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:d.mixInput.source.node,refId:"ax-".concat(a)}),this.log.info("start mix audio track ".concat(a," success.")),ri.addEnum({key:502700,value:3}),this.kvUpload(t)})}handleAutoPlayFailed(t,o,a){return XA(this,null,function*(){if(a.name==="NotSupportedError")this.log.error("play failed, try to reload source. error: ".concat(a)),yield t.reload(o),yield t.play();else{if(a.name!=="NotAllowedError")throw a;if(this.core.room.enableAutoPlayDialog){let l=()=>{var d;(d=t.play())==null||d.finally(()=>{F.off("154",l,this)})};F.on("154",l,this),JC()}else this.core.trtc.emit(Ao.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>XA(this,null,function*(){return t.play()})})}})}update(t){return XA(this,null,function*(){let{id:o,operation:a,seekFrom:l,playbackRate:d}=t;this.log.info("update music source, ".concat(JSON.stringify(t)));let h=this.mixedMusicMap.get(o);h?(h.updateSettings(t),h.updateListener(t),ze(a)||h.setOperation(a),ze(l)||h.seek(l),this.kvUpload(t)):this.log.warn("update music source failed, music id: ".concat(o," not found."))})}stop(t){return XA(this,arguments,function(o){var a=this;let{id:l}=o;return function*(){if(a.mixedMusicMap.has(l)){a.log.info("remove music source, music id: ".concat(l));let d=a.mixedMusicMap.get(l);d!=null&&d.mixInput.source.node&&a.core.room.audioManager.updateAudioReference({type:"remove",audioReference:d.mixInput.source.node,refId:"ax-".concat(l)}),d?.stop(),a.mixedMusicMap.delete(l)}l==="*"&&a.destroyAllMusic()}()})}kvUpload(t){let{track:o,loop:a,volume:l,playbackRate:d,operation:h,seekFrom:y,onTimeUpdate:S,onDurationChange:L,onEnded:V}=t;o&&ri.addCount({key:502009}),a&&ri.addCount({key:502001}),l&&ri.addCount({key:502002}),d&&ri.addCount({key:502003}),h&&ri.addCount({key:502004}),y&&ri.addCount({key:502005}),typeof S!="function"&&ri.addCount({key:502007}),typeof V!="function"&&ri.addCount({key:502008}),typeof L!="function"&&ri.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((t,o)=>{t!=null&&t.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:t.mixInput.track,refId:o}),this.stop({id:o})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};Y(vL,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(A,t,o){if(A.url&&A.url!=="*"){let a=A.url.split("?")[0],l=["mp3","ogg","wav","flac"],d=a.split(".").pop(),h=l.indexOf(d)>=0,y=a.startsWith("blob"),S=a.startsWith("data");if(!(h||y||S))throw new Lo({code:ko.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:o})}if(!A.url&&!A.track)throw new Lo({code:ko.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:o});M_("onTimeUpdate",A.onTimeUpdate),M_("onEnded",A.onEnded),M_("onDurationChange",A.onDurationChange)}}),Y(vL,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(A,t,o){M_("onTimeUpdate",A.onTimeUpdate),M_("onEnded",A.onEnded),M_("onDurationChange",A.onDurationChange)}}),Y(vL,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),Y(vL,"Name","AudioMixer");var Lj,poA=vL,Uj=0,k1=class qL{constructor(t){this.core=t,Y(this,"log"),Y(this,"audioContext",VI()),Y(this,"workletNode"),Y(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5}),Uj+=1,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(Uj)}),this.log.info("created id=".concat(this.getAlias()).concat(Uj))}static startValidateRule(t){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(o,a,l,d){if(!t.room.audioManager.hasAudioTrack)throw new Lo({code:ko.INVALID_OPERATION,extraCode:5106,fnName:l})}}}preload(t){return Lj||(Lj=this.doPreload(t)),Lj}doPreload(t){return XA(this,null,function*(){let o=yield this.core.fileDownloader.download(t,{type:"blob"}),a=URL.createObjectURL(o);try{yield Kg(this.audioContext,a)}catch(l){throw this.log.error("load worklet failed",l),l}finally{URL.revokeObjectURL(a)}})}getName(){return qL.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(t){switch(t){case"start":return qL.startValidateRule(this.core);case"update":return qL.updateValidateRule;case"stop":return qL.stopValidateRule}}start(t){return XA(this,null,function*(){let{room:o,schedule:a}=this.core,{assetsPath:l=this.core.assetsPath}=t;if(!l)throw new Lo({code:ko.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(l,"/denoiser-wasm").concat(Vv()?"":"-nosimd",".js")),!this.workletNode){let d=String(Date.now()).slice(0,-3),{auth:h,sign:y,status:S,message:L}=yield function(V,H){return XA(this,arguments,function(lA,hA){let{sdkAppId:MA,userId:oe,userSig:fe,timestamp:je}=hA;return function*(){try{let{data:{errCode:_e,errMsg:vi,sign:Fe,status:Dt}}=yield lA.getAbilityConfig(MA,lA.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:MA,userId:oe,userSig:fe,timestamp:je});if(Dt==="1")return{auth:!0,sign:Fe,status:Dt,message:vi};let pi=zd(MA)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",Mi="Init RTCAIDenoiser failed.",Wo="";switch(_e){case 1:Wo="Please check your params.";break;case 2:Wo="You need to buy packages. Refer to: ".concat(pi);break;case 3:Wo="Server is invalid. Please contact our engineer. ";break;case 4:Wo="Your packages is not active. Refer to: ".concat(pi);break;case 5:Wo="Your packages is expired. Refer to: ".concat(pi);break;case 6:Wo="Your version is not supported."}return{auth:!1,status:Dt,message:vi?"".concat(Mi," Reason: ").concat(vi,". ").concat(Wo):"".concat(Mi,", ").concat(Wo)}}catch(_e){return{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(_e)}}}()})}(a,So(Di({},t),{timestamp:d}));if(!h)throw this.log.info("RTCAIDenoiser: ".concat(t.userId," auth result: ").concat(h,". Message: ").concat(L)),new Lo({code:ko.INVALID_PARAMETER,message:L});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(t.sdkAppId),userId:t.userId,timestamp:d,sign:y,status:S}}),this.workletNode.port.onmessage=V=>{var H;let{data:lA}=V;if(lA.type==="cost"){let hA=lA?.max>20?"warn":lA?.max>10?"info":"debug";this.log[hA]("avg cost: ".concat(lA.value," max: ").concat(lA?.max,"(").concat(Gb(new Date(lA?.maxCostTimestamp)),") hist: ").concat((H=lA?.hist)==null?void 0:H.join(" ")))}else lA.type==="log"&&this.log[lA.logLevel]("".concat(lA.value))}}this.updateConfig(t),this.workletNode.port.postMessage({type:"enable"}),o.audioManager.addDenoiser(this.workletNode),o.sendAbilityStatus({ai_denoise:1})})}update(t){return XA(this,null,function*(){this.updateConfig(t)})}stop(){return XA(this,null,function*(){if(!this.workletNode)return;let{room:t}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield t.audioManager.removeDenoiser(this.workletNode)})}updateConfig(t){if(!this.workletNode)return;let o=!1;ze(t.mode)||(t.mode===0?this.config.enableFarFieldReduce=!1:t.mode===1&&(this.config.enableFarFieldReduce=!0),o=!0),ze(t.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=t.farFieldReduceThreshold,o=!0),o&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};Y(k1,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),Y(k1,"stopValidateRule",{type:"object"}),Y(k1,"Name","AIDenoiser");var moA=k1,foA=dc($l(),1),yoA=class extends foA.EventEmitter{constructor(){super(),Y(this,"observer"),Y(this,"state","nominal"),this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return XA(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!za&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(A){ds.uploadEvent({log:"stat-pressure-detector-start-failed",error:A})}})}onPressureChange(A){let t=this.stateNum,o=A[A.length-1];this.state=o.state,(this.stateNum>3||t>3)&&pA.info("".concat(o.source,": ").concat(o.state)),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var A;try{(A=this.observer)==null||A.disconnect(),this.observer=null}catch(t){ds.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:t})}}},A8=new yoA,Fj=0,Oj=class yX{constructor(t){this.core=t,Y(this,"log"),Y(this,"_seiMessageList",[]),Y(this,"_smallSeiMessageList",[]),Y(this,"_subStreamSeiMessageList",[]),Fj++,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(Fj)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(Fj)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(t){let{frame:o,mediaType:a}=t;try{return Jz({frame:o,seiMessageList:a===8?this._smallSeiMessageList:a===2?this._subStreamSeiMessageList:this._seiMessageList})}catch(l){this.log.warn(l)}return o}decode(t){let{frame:o,track:a}=t;return qz({frame:o,onSEI:l=>{l.forEach(d=>{a!=null&&a.userId?this.core.trtc.emit(Ao.SEI_MESSAGE,{seiPayloadType:d.seiPayloadType,data:d.seiPayload.buffer,userId:a.userId,streamType:a.mediaType===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:d})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(t){switch(t){case"start":case"update":case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:$p?this.encode:Jz,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:$p?this.decode:qz,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update(t){let{buffer:o,options:a}=t;var l;let d=[a.seiPayloadType,o],h=!!a.small;a.toSubStream?this._subStreamSeiMessageList.push(d):(this._seiMessageList.push(d),h&&this._smallSeiMessageList.push(d)),(l=this.core.room.scriptTransformWorker)==null||l.postMessage({type:"sei",data:d,isMain:!a.toSubStream,small:h})}getName(){return yX.Name}getAlias(){return"sei"}getGroup(){return"sei"}};Y(Oj,"autoStart",!0),Y(Oj,"Name","SEI");var L1,DoA=Oj,SoA=0,Pj=class DX{constructor(t){this.core=t,Y(this,"_core"),Y(this,"log"),Y(this,"dialog"),this._core=t,this.log=t.log.createChild({id:"".concat(this.getAlias()).concat(++SoA)}),this.log.info("created")}getName(){return DX.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(t){switch(t){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return XA(this,null,function*(){var t;!new URLSearchParams(location.search).has("trtcDebug")&&((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog())})}update(t){return XA(this,arguments,function(o){var a=this;let{visible:l}=o;return function*(){l?yield a.openDebugDiaLog():a.closeDebugDiaLog()}()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return XA(this,null,function*(){var t;if(!this.dialog)try{if(L1)yield L1;else{let o=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((t=window.sessionStorage)==null?void 0:t.getItem("TRTC_DEBUG_DIALOG_PATH"))||"https://unpkg.com/".concat("trtc-sdk-v5","@").concat(Wd,"/assets/debug-dialog.js");L1=this._core.fileDownloader.loadScript(o),yield L1}this.dialog=new TRTCDebugDialog(this._core,this.log),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(o){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(o))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}};Y(Pj,"Name","Debug"),Y(Pj,"autoStart",!0);var voA=Pj,e8=A=>{switch(A){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},t8=class{constructor(A,t,o){Y(this,"trackDoneOB"),Y(this,"startOB"),Y(this,"stopOB"),Y(this,"inputFrameCount",0),Y(this,"decodedFrameCount",0),Y(this,"type","auto"),Y(this,"config"),Y(this,"decoder"),Y(this,"_decodeSink");let{kvStatManager:a,trtc:l}=A;this.config=o.config,this.trackDoneOB=Ea(t,gs.INIT),this.stopOB=BQ(),this.startOB=BQ(),o.type==="auto"?this.type="webCodecs":this.type=o.type;let d=BQ();Ma(this.startOB,lj(0),h1(h=>{let y=this.pipe(t);return d.next("STARTING"),t.log.info("decoder type: ".concat(this.type)),Ma(y,CE(this.stopOB),Dl(()=>{},S=>{t.log.error(S),a.addFailedEvent({key:e8(this.type),error:S}),h>4?this.startOB.error(S):this.startOB.next(h+1)})),Ma(y,p_(1),Ez(Ej))}),CE(this.stopOB),Dl(()=>{t.player.setOutput(),d.next("STARTED")},h=>{d.next("FAILED")},()=>{a.addSuccessEvent({key:e8(this.type)}),a.addSuccessEvent({key:504702})}))}mock(A){this._decodeSink?this._decodeSink.error(A):this.startOB.next(0)}close(A){this.stopOB.next(A)}pipe(A){return IL()(t=>XA(this,null,function*(){this._decodeSink=t,t.defer(()=>{var a;(a=this.decoder)==null||a.close()});let{type:o}=this;try{o==="webCodecs"&&(this.decoder=new AudioDecoder({error:a=>{A.log.error(a),t.error(4)},output:a=>{this.decodedFrameCount++,t.next(a),A.player.write(a)}})),this.decoder.configure(this.config)}catch(a){A.log.error(a),t.error(o==="webCodecs"?2:6)}}))}decodeFrame(A){var t;this.inputFrameCount++,((t=this.decoder)==null?void 0:t.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:A.data,timestamp:A.timestamp,type:"key"}))}},MoA={type:"object"},i8=class uW{constructor(t){this.core=t,Y(this,"log"),Y(this,"contextMap",new Map),Y(this,"decodeProcessorMap",new WeakMap),this.log=t.log.createChild({id:"".concat(this.getAlias())})}getAlias(){return uW.Name}getGroup(t){return t.track.userId+t.track.streamType}getName(){return uW.Name}getValidateRule(t){return MoA}start(t){let{track:o}=t;this.decodeProcessorMap.set(o,this.decode(t)),this.core.room.audioManager.addDecodeProcessor({processor:a=>{let{frame:l,track:d}=a;return this.decodeProcessorMap.has(d)?this.decodeProcessorMap.get(d)({frame:l,track:d}):l},type:3})}decode(t){return o=>{let{frame:a,track:l}=o;if(l!==t.track)return a;if(this.contextMap.has(l))return this.contextMap.get(l).decodeFrame(a);let d=new t8(this.core,l,t);return Ma(d.trackDoneOB,p_(1),Dl(()=>{this.core.clearStarted(this,this.getGroup(t)),this.stop({track:l})})),this.contextMap.set(l,d),d.decodeFrame(a)}}stop(t){let{track:o}=t,a=this.contextMap.get(o);a&&(a.close("stop"),this.contextMap.delete(o),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(t){let o=this.contextMap.get(t.track);if(o){if(t.type==="mock")return void o.mock(10);o.close("update"),this.contextMap.set(t.track,new t8(this.core,t.track,t))}}};Y(i8,"Name","TRTCAudioDecoder");var o8=i8,RoA={rttPoorLimit:150,lossPoorLimit:20,rttGoodLimit:100,lossGoodLimit:10,fpsPoorLimit:5,cooldownTime:1e4,poorCount:3,goodCount:5,maxUpgradeFailCount:3},woA=class{constructor(){Y(this,"log"),Y(this,"autoMode",{enabled:!1,instance:null,config:RoA,sortedStreamList:[],currentQualityIndex:0}),Y(this,"switchControl",{isInternal:!1,isSwitching:!1,lastSwitchTime:0,boundOnStatistics:null}),Y(this,"networkMetrics",{frameRate:0,rtt:0,loss:0}),Y(this,"counters",{rttUnder:0,lossUnder:0,downgradeCondition:0,upgradeFail:0}),Y(this,"onStatistics",A=>{var t,o;if(!this.autoMode.instance)return;let{config:a}=this.autoMode;if(this.networkMetrics.rtt=A.rtt,this.networkMetrics.loss=A.downLoss,this.counters.rttUnder=A.rttV.userId===d);if((o=y?.video)==null||!o.length)return;let S=h==="sub"?"sub":"big",L=y.video.find(V=>V.videoType===S);L?(this.networkMetrics.frameRate=L.frameRate||0,this.checkAndSwitchQuality()):this.log.warn("onStatistics: videoStat not found for userId=".concat(d,", streamType=").concat(h))}),this.log=pA.createLogger({id:"pqs"})}getCurrentPlayingStream(A){var t,o;let a=A,l=a._playbackQualityList;if(!l||l.length===0)return this.log.warn("getCurrentPlayingStream: streamList is empty"),null;for(let d of l){let h=A.room.remotePublishedUserMap.get(d.userId);if(!h)continue;let y=(t=d.streamType)!=null?t:"main";if((y==="sub"?h.remoteAuxiliaryTrack:h.remoteVideoTrack).isPlayCalled){let S=(o=a._remoteVideoConfigMap.get("".concat(d.userId,"_").concat(y)))==null?void 0:o.config;if(S)return{userId:d.userId,streamType:y,config:S}}}return null}switchPlaybackQuality(A){return XA(this,null,function*(){var t;let{trtcInstance:o,streamList:a,quality:l}=A;this.log.info("switchPlaybackQuality quality: ".concat(l,", streamList: ").concat(JSON.stringify(a)));let d=o;if(a&&a.length>0&&(d._playbackQualityList=a.map(MA=>{var oe;return So(Di({},MA),{streamType:(oe=MA.streamType)!=null?oe:"main"})})),l==="auto")return void(yield this.startAutoMode(o));if(this.autoMode.enabled&&l&&!this.switchControl.isInternal&&this.stopAutoMode(),!l)return;if(!d._playbackQualityList||d._playbackQualityList.length<=0)return void this.log.warn("switchPlaybackQuality: streamList is empty, please call with streamList first");let h=d._playbackQualityList.find(MA=>MA.name===l);if(!h)return void this.log.warn('switchPlaybackQuality: quality "'.concat(l,'" not found in streamList'));let y=this.getCurrentPlayingStream(o);if(this.log.info("currentPlaying userId: ".concat(y?.userId,", streamType: ").concat(y?.streamType)),!y)return;let S=(t=h.streamType)!=null?t:"main";if(y.userId===h.userId&&y.streamType===S)return void this.log.info("switchPlaybackQuality: already playing target stream");let L=Di({},y.config);L.streamType==="main"&&S==="main"&&(yield o.muteRemoteAudio(L.userId,!0));let V,H=new Promise(MA=>{V=MA}),lA=MA=>{MA.userId===h.userId&&MA.streamType===S&&MA.state==="PLAYING"&&MA.reason==="playing"&&V("success")};o.on(Ao.VIDEO_PLAY_STATE_CHANGED,lA);let hA=new Promise(MA=>setTimeout(()=>MA("timeout"),1e4));try{if(yield o.startRemoteVideo(So(Di({},y.config),{userId:h.userId,streamType:S,option:So(Di({},y.config.option),{isLiveStream:!0})})),(yield Promise.race([H,hA]))==="timeout"){this.log.error("switchPlaybackQuality: VIDEO_PLAY_STATE_CHANGED timeout, rollback");try{yield o.stopRemoteVideo({userId:h.userId,streamType:S})}catch(oe){this.log.warn("switchPlaybackQuality: rollback stopRemoteVideo failed",oe)}throw L.streamType==="main"&&S==="main"&&(yield o.muteRemoteAudio(L.userId,!1).catch(oe=>{this.log.warn("switchPlaybackQuality: rollback muteRemoteAudio failed",oe)})),new li({code:mt.SUBSCRIPTION_TIMEOUT,message:sn({key:Go.SWITCH_PLAYBACK_QUALITY_TIMEOUT,data:{userId:h.userId}})})}let MA=o.stopRemoteVideo(L);L.streamType==="main"&&S==="main"?yield Promise.all([o.muteRemoteAudio(h.userId,!1).catch(oe=>{this.log.warn("muteRemoteAudio(new, false) failed",oe)}),MA]):yield MA,d._currentLiveUserId=h.userId,d._currentLiveStreamType=S}finally{o.off(Ao.VIDEO_PLAY_STATE_CHANGED,lA)}})}startAutoMode(A){return XA(this,null,function*(){if(this.autoMode.enabled)return void this.log.info("auto mode already enabled");let t=A;if(!t._playbackQualityList||t._playbackQualityList.length<=1)return void this.log.warn("startAutoMode: need at least 2 streams in streamList for auto mode");this.autoMode.enabled=!0,this.autoMode.instance=A,this.counters.rttUnder=0,this.counters.lossUnder=0,this.counters.downgradeCondition=0,this.counters.upgradeFail=0,this.switchControl.lastSwitchTime=0;let o=t._playbackQualityList||[];this.autoMode.sortedStreamList=[...o].sort((l,d)=>d.bitrate-l.bitrate),this.log.info("auto mode streams: ".concat(this.autoMode.sortedStreamList.map(l=>"".concat(l.name,"(").concat(l.bitrate,"kbps)")).join(" > ")));let a=this.getCurrentPlayingStream(A);if(a){let{userId:l,streamType:d}=a,h=this.autoMode.sortedStreamList.findIndex(y=>{var S;return y.userId===l&&((S=y.streamType)!=null?S:"main")===d});this.autoMode.currentQualityIndex=h>=0?h:0}else this.autoMode.currentQualityIndex=0;this.switchControl.boundOnStatistics=this.onStatistics,A.on(Ao.STATISTICS,this.switchControl.boundOnStatistics),this.log.info("auto mode started")})}stopAutoMode(){this.autoMode.enabled&&(this.autoMode.instance&&this.switchControl.boundOnStatistics&&this.autoMode.instance.off(Ao.STATISTICS,this.switchControl.boundOnStatistics),this.switchControl.boundOnStatistics=null,this.autoMode.enabled=!1,this.autoMode.instance=null,this.autoMode.sortedStreamList=[],this.autoMode.currentQualityIndex=0,this.counters.rttUnder=0,this.counters.lossUnder=0,this.counters.downgradeCondition=0,this.counters.upgradeFail=0,this.networkMetrics.frameRate=0,this.networkMetrics.rtt=0,this.networkMetrics.loss=0,this.switchControl.isSwitching=!1,this.log.info("auto mode stopped"))}checkAndSwitchQuality(){var A;if(!this.autoMode.enabled||!this.autoMode.instance||this.switchControl.isSwitching)return;let{config:t}=this.autoMode,o=Date.now()-this.switchControl.lastSwitchTime0,h=this.networkMetrics.frameRate<=t.fpsPoorLimit,y=this.networkMetrics.loss>=t.lossPoorLimit||this.networkMetrics.rtt>=t.rttPoorLimit,S=h&&y;this.counters.downgradeCondition=S?this.counters.downgradeCondition+1:0;let L=this.counters.rttUnder>=t.goodCount&&this.counters.lossUnder>=t.goodCount,V=this.counters.upgradeFail{if(V.remoteAudioTrack.isAvailable){if(S.get(V.userId))return;let H=y.getPCM(lA=>{t.emit(Ao.AUDIO_FRAME,lA)},V.userId);S.set(V.userId,H)}});else{if(S.get(a))return;let V=y.getPCM(H=>{t.emit(Ao.AUDIO_FRAME,H)},a);S.set(a,V)}else if(a==="*")t.room.remotePublishedUserMap.forEach(V=>{if(V.remoteAudioTrack.isSubscribed){let{userId:H}=V,lA=S.get(H);lA?.abort("disable"),S.delete(H)}});else{let V=S.get(a);V?.abort("disable"),S.delete(a)}})}resumeRemotePlayer(A){return XA(this,null,function*(){if(A.userId==="*"){let o=[];return A.trtcInstance.room.remotePublishedUserMap.forEach(a=>{let{remoteAudioTrack:l,remoteVideoTrack:d,remoteAuxiliaryTrack:h}=a;A.streamType?A.streamType==="main"?(l.isAvailable&&o.push(l.player.resume()),d.isAvailable&&o.push(d.player.resume())):h.isAvailable&&o.push(h.player.resume()):(l.isAvailable&&o.push(l.player.resume()),d.isAvailable&&o.push(d.player.resume()),h.isAvailable&&o.push(h.player.resume()))}),Promise.all(o)}let t=A.trtcInstance.room.remotePublishedUserMap.get(A.userId);if(t)return A.streamType==="main"?Promise.all([t.remoteAudioTrack.player.resume(),t.remoteVideoTrack.player.resume()]):t.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(A){if(A.userId==="*")A.trtcInstance.room.remotePublishedUserMap.forEach(t=>{let{remoteAudioTrack:o,remoteVideoTrack:a,remoteAuxiliaryTrack:l}=t;A.streamType?A.streamType==="main"?(o.isAvailable&&o.player.pause(),a.isAvailable&&a.player.pause(!1)):l.isAvailable&&l.player.pause(!1):(o.isAvailable&&o.player.pause(),a.isAvailable&&a.player.pause(!1),l.isAvailable&&l.player.pause(!1))});else{let t=A.trtcInstance.room.remotePublishedUserMap.get(A.userId);t&&(A.streamType==="main"?(t.remoteAudioTrack.player.pause(),t.remoteVideoTrack.player.pause(!1)):t.remoteAuxiliaryTrack.player.pause(!1))}}requestPictureInPicture(A){let t=[...A.trtcInstance.room.remotePublishedUserMap.values()].find(o=>o.remoteVideoTrack.isAvailable);return t?A.enable?t.remoteVideoTrack.player.enterPictureInPicture():t.remoteVideoTrack.player.exitPictureInPicture():Promise.reject(new li({code:mt.INVALID_OPERATION,message:"no available remote video"}))}requestFullScreen(A){let t=[...A.trtcInstance.room.remotePublishedUserMap.values()].find(o=>o.remoteVideoTrack.isAvailable);return t?A.enable?t.remoteVideoTrack.player.enterFullscreen():t.remoteVideoTrack.player.exitFullscreen():Promise.reject(new li({code:mt.INVALID_OPERATION,message:"no available remote video"}))}switchPlaybackQuality(A){return XA(this,null,function*(){let t=A.trtcInstance;return t._playbackQualitySwitcher||(t._playbackQualitySwitcher=new woA),t._playbackQualitySwitcher.switchPlaybackQuality(A)})}prelink(A){return XA(this,null,function*(){let{trtcInstance:t}=A;return A.enable?t.room.prelink(A.sdkAppId,A.userId,A.userSig,RL.frameWorkType,A.roomId,A.strRoomId):t.room.closePrelink()})}};Qi([yz({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],xj.prototype,"enableAudioFrameEvent"),Qi([yz({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!1,type:"string"},sdkAppId:{required:!1,type:"number"},userSig:{required:!1,type:"string"},roomId:{required:!1,type:"number"},strRoomId:{required:!1,type:"string"}}})],xj.prototype,"prelink");var _oA=new xj,ToA=dc($l(),1),NoA=class extends ToA.EventEmitter{constructor(){super(),Y(this,"states",{}),Y(this,"permissionChangeHandler"),Y(this,"log"),this.log=pA.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var A,t;this.emit("permission-state-change",{camera:(A=this.states.camera)==null?void 0:A.state,microphone:(t=this.states.microphone)==null?void 0:t.state})}}request(A){return XA(this,null,function*(){if(this.log.info("request ".concat(A.join(", "))),A.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:A.includes("camera"),audio:A.includes("microphone")})).getTracks().forEach(t=>t.stop())})}get(A){return XA(this,null,function*(){try{return this.states[A]||(this.states[A]=yield navigator.permissions.query({name:A}),this.states[A].addEventListener("change",this.permissionChangeHandler)),this.log.info("get ".concat(A," permission state: ").concat(this.states[A].state)),this.states[A].state}catch(t){return this.log.error("get ".concat(A," permission failed, error: ").concat(t instanceof Error?t.message:t)),null}})}destroy(){Object.values(this.states).forEach(A=>{A?.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},U1=new NoA,n8=0,ML=new Set,iI=null;zx(Xz),$A.checkStorage();var bn=class Im extends _K.EventEmitter{constructor(t,o){super(),Y(this,"_room"),Y(this,"_eventListened",new Set),Y(this,"_localVideoTrack",null),Y(this,"_localAudioTrack",null),Y(this,"_localScreenTrack",null),Y(this,"_localScreenAudioTrack",null),Y(this,"_localVideoConfig",null),Y(this,"_localScreenConfig",null),Y(this,"_localAudioConfig",null),Y(this,"_remoteVideoConfigMap",new Map),Y(this,"_remoteAudioConfigMap",new Map),Y(this,"_remoteAudioVolumeMap",new Map),Y(this,"_remoteAudioMuteMap",new Map),Y(this,"_mediaTrackMap",new WeakMap),Y(this,"_log",pA.createLogger({id:"t".concat(++n8)})),Y(this,"_plugins",new Map),Y(this,"_networkQuality",null),Y(this,"_speakerId"),Y(this,"enterRoomParams"),Y(this,"_enableAutoSwitchWhenRecapturing",!0),Y(this,"_autoSubscribeDataChannel",!1),Y(this,"_playbackQualityList",[]),this._room=new t(Di({logger:this._log,frameWorkType:Im.frameWorkType},o)),this._room.videoDecodeFallbackType=o.videoDecodeFallback,br(o.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=o.enableAutoSwitchWhenRecapturing),this._log.info("create() ".concat(JSON.stringify(o,(a,l)=>a==="plugins"?l.map(d=>d.Name):l))),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(a){return this._room.audioManager.dump(a)}}}),o.plugins&&o.plugins.forEach(a=>{this._use(a,o.assetsPath)}),this._use(poA,o.assetsPath),this._use(BoA,o.assetsPath),this._use(moA,o.assetsPath),this._use(o8,o.assetsPath),this._use(voA),o.enableSEI&&$k&&this._use(DoA),this._room.on("audio-volume",a=>{var l,d;!a.find(h=>h.userId==="")&&this._localAudioTrack&&a.push({userId:"",volume:Math.floor(100*((l=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?l:this._localAudioTrack.getAudioLevel())),floatVolume:(d=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?d:this._localAudioTrack.getInternalAudioLevel()}),o.volumeType===1&&a.forEach(h=>{var y;let S=h.userId===""?this._localAudioTrack:(y=this.room.remotePublishedUserMap.get(h.userId))==null?void 0:y.remoteAudioTrack;S&&(h.volume=S.dbVolume)}),o.enableDbVolume&&a.forEach(h=>{var y;let S=h.userId===""?this._localAudioTrack:(y=this.room.remotePublishedUserMap.get(h.userId))==null?void 0:y.remoteAudioTrack;S&&(h.volume=S.dbVolume)}),this.emit(Ao.AUDIO_VOLUME,{result:a.sort((h,y)=>y.volume-h.volume)})}),this._room.videoManager.on("error",a=>{this._log.error(new Lo({code:ko.OPERATION_FAILED,extraCode:5504,message:a.message,originError:a}))}),this._listenEvents(),this._initActiveSpeaker(),((a,l)=>{let{emit:d}=a;a.emit=function(){for(var h=arguments.length,y=new Array(h),S=0;S{y&&pA.info(PC)})}})();let a=new Im(t,o||{});return ML.add(a),a.__v_skip=!0,a}get room(){return this._room}_listenEvents(){gd(this,this._room).add("peer-join",t=>{let{userId:o}=t;this.emit(Ao.REMOTE_USER_ENTER,{userId:o})}).add("peer-leave",t=>{let{userId:o,reason:a}=t;this.emit(Ao.REMOTE_USER_EXIT,{userId:o,reason:a})}).add("banned",t=>{mQ(!0),this._exitRoom().finally(()=>{this.emit(Ao.KICKED_OUT,{reason:t.reason})})}).add("error",t=>{this._exitRoom().finally(()=>{this.emit(Ao.ERROR,Lo.convertFrom(t))})}).add("signal-connection-state-changed",t=>{this.emit(Ao.CONNECTION_STATE_CHANGED,t)}).add("network-quality",t=>{this._networkQuality=t;let o=So(Di({},t),{uplinkRTT:Math.min(t.uplinkRTT,y0),downlinkRTT:Math.min(t.downlinkRTT,y0)});this.emit(Ao.NETWORK_QUALITY,o)}).add("remote-published",t=>{[t.remoteAudioTrack,t.remoteVideoTrack,t.remoteAuxiliaryTrack].forEach(o=>{gd(o,o).add("player-state-changed",a=>{let l=So(Di({},a),{userId:t.userId});o.kind===JA.VIDEO&&(l.streamType=iC(o.streamType)),this.emit(o.kind===JA.AUDIO?Ao.AUDIO_PLAY_STATE_CHANGED:Ao.VIDEO_PLAY_STATE_CHANGED,l)}).add("error",a=>{a.getCode()===mt.PLAY_NOT_ALLOWED&&this.emit(Ao.AUTOPLAY_FAILED,{userId:o.userId,mediaType:o.strMediaType,resume:()=>o.player.resume()})})})}).add("remote-unpublished",t=>{[t.remoteAudioTrack,t.remoteVideoTrack,t.remoteAuxiliaryTrack].forEach(o=>{Vs(o)})}).add("remote-publish-state-changed",t=>{let{prevMuteState:o,muteState:a}=t,{userId:l}=a,d=o.audioAvailable,h=o.videoAvailable,{audioAvailable:y,videoAvailable:S}=a;y||this._remoteAudioConfigMap.delete(l),S||this._removeRemoteVideoConfig(l,"main"),a.hasAuxiliary||this._removeRemoteVideoConfig(l,"sub"),h!==S&&(S?this._onVideoAvailable({userId:l,streamType:"main"}):this._onVideoUnavailable({userId:l,streamType:"main"}),this.emit(S?Ao.REMOTE_VIDEO_AVAILABLE:Ao.REMOTE_VIDEO_UNAVAILABLE,{userId:l,streamType:"main"})),d!==y&&(y?this._onAudioAvailable({userId:l}):this._onAudioUnavailable({userId:l,muteState:a}),this.emit(y?Ao.REMOTE_AUDIO_AVAILABLE:Ao.REMOTE_AUDIO_UNAVAILABLE,{userId:l})),o.hasAuxiliary!==a.hasAuxiliary&&(a.hasAuxiliary?this._onVideoAvailable({userId:l,streamType:"sub"}):this._onVideoUnavailable({userId:l,streamType:"sub"}),this.emit(a.hasAuxiliary?Ao.REMOTE_VIDEO_AVAILABLE:Ao.REMOTE_VIDEO_UNAVAILABLE,{userId:l,streamType:"sub"})),o.hasDatachannel!==a.hasDatachannel&&a.hasDatachannel&&this._onDataChannelAvailable()}).add("sei-message",t=>{this.emit(Ao.SEI_MESSAGE,So(Di({},t),{streamType:iC(t.streamType)}))}).add("firewall-restriction",()=>{this.emit(Ao.ERROR,new Lo({code:ko.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",t=>{var o,a,l,d,h,y,S;let L={2:"big",3:"small",7:"sub"},V={rtt:Math.min(t.msg_up_stream_info.msg_network_status.uint32_rtt||((o=t.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((a=this._networkQuality)==null?void 0:a.uplinkRTT)||((l=this._networkQuality)==null?void 0:l.downlinkRTT)||0,y0),upLoss:((d=this._networkQuality)==null?void 0:d.uplinkLoss)||0,downLoss:((h=this._networkQuality)==null?void 0:h.downlinkLoss)||0,bytesSent:t.bytes_sent||0,bytesReceived:t.bytes_received||0,localStatistics:{audio:{bitrate:(((y=t.msg_up_stream_info.msg_audio_status)==null?void 0:y.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((S=t.msg_up_stream_info.msg_audio_status)==null?void 0:S.uint32_audio_level)||0)/sd},video:t.msg_up_stream_info.msg_video_status.filter(H=>L[H.uint32_video_stream_type]).map(H=>({bitrate:(H.uint32_video_codec_bitrate||0)/1e3,width:H.uint32_video_width,height:H.uint32_video_height,frameRate:H.uint32_video_enc_fps,videoType:L[H.uint32_video_stream_type]}))},remoteStatistics:t.msg_down_stream_info.map(H=>({userId:H.msg_user_info.str_identifier,audio:{bitrate:(H.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(H.msg_audio_status.uint32_audio_level||0)/sd,point2pointDelay:(H.msg_audio_status.uint32_audio_p2p_delay||0)+(H.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:H.msg_audio_status.uint32_audio_cache_ms||0},video:H.msg_video_status.map(lA=>({bitrate:(lA.uint32_video_codec_bitrate||0)/1e3,width:lA.uint32_video_width,height:lA.uint32_video_height,frameRate:lA.uint32_video_dec_fps,videoType:L[lA.uint32_video_stream_type],point2pointDelay:(lA.uint32_video_p2p_delay||0)+(lA.uint32_video_cache_ms||0),jitterBufferDelay:lA.uint32_video_cache_ms||0,codec:lA.uint32_video_codec}))}))};this.emit(Ao.STATISTICS,V)}).add("custom-message",t=>{this.emit(Ao.CUSTOM_MESSAGE,t)}).add("layerData",t=>this.emit(Ao.LAYER_DATA,t)).add("first-video-frame",t=>{this.emit(Ao.FIRST_VIDEO_FRAME,So(Di({},t),{streamType:iC(t.streamType)}))}).add("audio-frame",t=>{this.emit(Ao.AUDIO_FRAME,t)}).add("data-channel-message",t=>{var o,a,l,d,h;let{data:y}=t;if(y.sender==="")return;let S={segmentId:(o=y.payload)==null?void 0:o.roundid,speakerUserId:y.sender,sourceText:(a=y.payload)==null?void 0:a.text,translationTexts:(l=y.payload)==null?void 0:l.translate_msg,timestamp:(d=y.payload)==null?void 0:d.start_utc_ms,isCompleted:(h=y.payload)==null?void 0:h.end,robotId:y.robotid};S.sourceText!==""&&this.emit(Ao.REALTIME_TRANSCRIBER_MESSAGE,S)}).add("asr-robot-peer-join",t=>{this.emit(Ao.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"started",roomId:this.room.roomId,transcriberRobotId:t.userId})}).add("asr-robot-peer-leave",t=>{this.emit(Ao.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"stopped",roomId:this.room.roomId,transcriberRobotId:t.userId})}),gd(this,Kc).add("audioInputAdded",t=>{this.emit(Ao.DEVICE_CHANGED,{type:"microphone",action:"add",device:t})}).add("audioInputRemoved",t=>{this.emit(Ao.DEVICE_CHANGED,{type:"microphone",action:"remove",device:t})}).add("videoInputAdded",t=>{this.emit(Ao.DEVICE_CHANGED,{type:"camera",action:"add",device:t})}).add("videoInputRemoved",t=>{this.emit(Ao.DEVICE_CHANGED,{type:"camera",action:"remove",device:t})}).add("audioOutputAdded",t=>XA(this,null,function*(){if(this.emit(Ao.DEVICE_CHANGED,{type:"speaker",action:"add",device:t}),tI&&tI.deviceId===f0){let o=(yield Zv()).find(a=>a.deviceId===f0);o&&tI.groupId!==o.groupId&&(tI=o,this.emit(Ao.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}))}})).add("audioOutputRemoved",t=>XA(this,null,function*(){this.emit(Ao.DEVICE_CHANGED,{type:"speaker",action:"remove",device:t});let o=(yield Zv())[0];if(!o||!tI||tI.groupId===o.groupId)return;let a=tI.deviceId===t.deviceId,l=tI.deviceId===f0&&tI.deviceId===o.deviceId;(a||l)&&(tI=o,this.emit(Ao.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}))})),gd(this,U1).add("permission-state-change",t=>{this.emit(Ao.PERMISSION_STATE_CHANGE,t)}),this.room.enableSEI&&this.on(Ao.SEI_MESSAGE,t=>{var o;let a=(o=this.room.remotePublishedUserMap.get(t.userId))==null?void 0:o.remoteVideoTrack;a&&a.updateAlphaRenderInfo(t)})}getNetworkTime(){return Vf()}use(t){let o,a;return"plugin"in t?(o=t.plugin,a=t.assetsPath):o=t,o.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(o,a)}_use(t,o){let a=this._plugins.get(t.Name);if(a)return this._log.warn("duplicate install plugin",t.Name),a;let l=new t(CoA.call(this,{TRTC:Im,room:this._room,assetsPath:o,errorModule:{RtcError:Lo,ErrorCode:ko,CoreErrorCode:mt,ErrorCodeDictionary:S1}}));return this._plugins.set(t.Name,l),l.__v_skip=!0,t.autoStart&&this.startPlugin(t.Name),l}enterRoom(t){return XA(this,null,function*(){var o,a;this.enterRoomParams=t;let{scene:l="rtc",enableAutoPlayDialog:d=!0,autoReceiveAudio:h=!0,autoReceiveVideo:y=!1}=t;t.proxy&&(this._room.setProxyServer(t.proxy),!Ws(t.proxy)&&t.proxy.turnServer&&((a=(o=this._room).setTurnServer)==null||a.call(o,t.proxy.turnServer,t.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=d,this._room.autoReceiveAudio=h,this._room.autoReceiveVideo=y,br(t.preferHW)&&(this._room.preferHW=t.preferHW),t.playoutDelay&&(this._room.playoutDelay=t.playoutDelay),t.jitterBufferDelay&&(this._room.jitterBufferDelay=t.jitterBufferDelay);let S={sdkAppId:t.sdkAppId,userId:t.userId,userSig:t.userSig,privateMapKey:t.privateMapKey||null,latencyLevel:t.latencyLevel,role:t.role==="audience"?21:20,roomId:t.roomId||0,strRoomId:t.strRoomId||"",businessInfo:t.businessInfo||null,streamId:null,userDefineRecordId:t.userDefineRecordId||null,enableDataChannel:this._plugins.has("RealtimeTranscriber"),frameWorkType:t.frameWorkType,component:t.component,language:t.language,priority:t.priority,useVp8:t.useVp8,useH265:t.useH265||!1,keepAlive:t.keepAlive};t.strRoomId&&!t.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(S,l,Im.frameWorkType),this._checkTrackToPublish(),A8.start()})}exitRoom(){return XA(this,null,function*(){return yield this._exitRoom()})}switchRoom(t){return XA(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(t)}catch(o){if(!(o instanceof Jx)||o.code!==mt.API_CALL_TIMEOUT&&o.code!==mt.SWITCH_ROOM_FAILED)throw o;this._log.warn("switchRoom ".concat(o.code===mt.API_CALL_TIMEOUT?"timeout":"failed",", fallback to exitRoom() and enterRoom()")),yield this._rejoinRoom(t)}else yield this._rejoinRoom(t)})}_rejoinRoom(t){return XA(this,null,function*(){yield this.exitRoom();let o=Di(Di({},this.enterRoomParams),t);yield this.enterRoom(o)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(t=>{this._stopRemoteAudio({userId:t}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(t=>{let o=t.includes("main")?"main":"sub",a=t.split("_".concat(o))[0];a&&this._stopRemoteVideo({userId:a,streamType:o}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),function(t){let o=v_.get(t);o&&(o.forEach(a=>clearTimeout(a)),v_.delete(t))}(this),this._room.remotePublishedUserMap.forEach(t=>{Vs(t.remoteAudioTrack),Vs(t.remoteVideoTrack),Vs(t.remoteAuxiliaryTrack)})}switchRole(t,o){return XA(this,null,function*(){o!=null&&o.privateMapKey&&(this._room.privateMapKey=o.privateMapKey),o!=null&&o.latencyLevel&&(this._room.latencyLevel=o.latencyLevel),yield this._room.switchRole(t),t==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(t=>{var o;return(o=t.destroy)==null?void 0:o.call(t)}),this._plugins.clear(),Vs(this),this.removeAllListeners(),this._room.destroy(),ML.delete(this),ML.size===0&&A8.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),F.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return XA(this,arguments,function(){var t=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0};return function*(){if(t._localAudioTrack)return void t._log.warn("local audio is already started");let{publish:a=!0,mute:l,muteKeepVolumeDetection:d,option:h}=o,y=new AM(t._room.audioManager),S={},L={muted:!0};h&&(ze(h.microphoneId)?ze(h.audioTrack)||(S.customSource=h.audioTrack):S.deviceId=h.microphoneId,h&&Ys(h.captureVolume)&&y.setCaptureVolume(h.captureVolume),ze(h.profile)||(Ws(h.profile)?Tp[h.profile]&&y.setProfile(Tp[h.profile]):y.setProfile(h.profile)),Ys(h.earMonitorVolume)&&(L.muted=!(h.earMonitorVolume>0),L.volume=h.earMonitorVolume),ze(h.echoCancellation)||(y.profile.echoCancellation=h.echoCancellation),ze(h.noiseSuppression)||(y.profile.noiseSuppression=h.noiseSuppression),ze(h.autoGainControl)||(y.profile.autoGainControl=h.autoGainControl),br(t._enableAutoSwitchWhenRecapturing)&&(y.enableAutoSwitchWhenRecapturing=t._enableAutoSwitchWhenRecapturing)),y.on("5",V=>{t.emit(Ao.ERROR,new Lo({code:ko.DEVICE_ERROR,extraCode:5309,messageParams:{error:V}}))}),y.on("2",V=>{t.emit(Ao.DEVICE_CHANGED,{type:"microphone",action:"active",device:V})}),y.on("4",V=>{let H;V.error&&(H=Lo.convertFrom(V.error)),t.emit(Ao.PUBLISH_STATE_CHANGED,So(Di({},V),{error:H}))}),y.on("6",()=>{}),t._listenOutputTrackChanged(y),t._speakerId&&y.setAudioOutput(t._speakerId),yield y.capture(S),ze(l)||y.setMute(l,d),gd(y,y).add("player-state-changed",V=>{t.emit(Ao.AUDIO_PLAY_STATE_CHANGED,So(Di({},V),{userId:""}))}),a&&t._room.isJoined&&t._room.publish(y).catch(()=>{}),t._localAudioTrack=y,t._room.capturedLocalMainAudioTrack=y,t._localAudioConfig=So(Di({},o),{publish:a}),yield t._updateAudioPlayOption({playOption:L,track:y}),F.emit("113",{userId:"",room:t.room})}()})}updateLocalAudio(t){return XA(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:o,mute:a,muteKeepVolumeDetection:l,option:d}=t,h={};d&&(d.microphoneId?yield this._localAudioTrack.switchDevice(d.microphoneId):ze(d.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(d.audioTrack)),ze(d.captureVolume)||this._localAudioTrack.setCaptureVolume(d.captureVolume),ze(d.earMonitorVolume)||(h.muted=!(d.earMonitorVolume>0),h.volume=d.earMonitorVolume),yield this._localAudioTrack.update3A(d)),this._room.isJoined&&!ze(o)&&(o&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!o&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),ze(a)||this._localAudioTrack.setMute(a,l),yield this._updateAudioPlayOption({playOption:h,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),$h(this._localAudioConfig,t)})}stopLocalAudio(){return XA(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),F.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),Vs(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,delete this._room.capturedLocalMainAudioTrack)})}startLocalVideo(){return XA(this,arguments,function(){var t=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0,view:null,capture:!0};return function*(){var a,l,d;if(t._localVideoTrack)return void t._log.warn("local video is already started");let{view:h,publish:y=!0,capture:S=!0,mute:L,option:V,forcePublish:H=!1}=o,lA=y||H,hA=S,MA=new QQ(t._room.videoManager),oe={},fe={};if(V&&(br(V.avoidCropping)&&(MA.avoidCropping=V.avoidCropping),V.cameraId?oe.deviceId=V.cameraId:ze(V.useFrontCamera)?ze(V.videoTrack)||(oe.customSource=V.videoTrack):oe.facingMode=V.useFrontCamera?JA.FACING_MODE_USER:JA.FACING_MODE_ENVIRONMENT,ze(V.retryWhenExactFailed)||(oe.retryWhenExactFailed=V.retryWhenExactFailed),V.qosPreference&&(oe.contentHint=v1(V.qosPreference)),ze(V.profile)||(Ws(V.profile)?FC[V.profile]&&MA.setProfile(FC[V.profile]):MA.setProfile(V.profile)),ze(V.fillMode)||(fe.objectFit=V.fillMode),ze(V.mirror)||(fe.mirror=V.mirror),ze(V.small)||(ze(V.smallMode)||(t._room.smallMode=V.smallMode),br(V.small)&&V.small===!1?MA.stopSmall():MA.updateSmallConfig(M1(V.small,!0))),ze(V.rotation)||MA.setRotation(V.rotation),br(t._enableAutoSwitchWhenRecapturing)&&(MA.enableAutoSwitchWhenRecapturing=t._enableAutoSwitchWhenRecapturing)),MA.once("first-video-frame",je=>{t.emit(Ao.FIRST_VIDEO_FRAME,So(Di({},je),{streamType:iC(je.streamType)}))}),MA.on("5",je=>{t.emit(Ao.ERROR,new Lo({code:ko.DEVICE_ERROR,extraCode:5308,messageParams:{error:je}}))}),MA.on("2",je=>{t.emit(Ao.DEVICE_CHANGED,{type:"camera",action:"active",device:je})}),MA.on("4",je=>{let _e;je.error&&(_e=Lo.convertFrom(je.error)),t.emit(Ao.PUBLISH_STATE_CHANGED,So(Di({},je),{error:_e}))}),MA.on("6",()=>{}),t._listenOutputTrackChanged(MA),oe.customSource&&Lp(oe.customSource)?(MA.setOutputMediaStreamTrack(oe.customSource),hA=!1):hA?yield MA.capture(oe):(a=MA.manager)==null||a.changeInput(MA),ze(L)||(yield MA.setMute(L)),gd(MA,MA).add("player-state-changed",je=>{t.emit(Ao.VIDEO_PLAY_STATE_CHANGED,So(Di({},je),{userId:"",streamType:"main"}))}).add("video-size-changed",je=>{t.emit(Ao.VIDEO_SIZE_CHANGED,So(Di({},je),{streamType:iC(je.streamType)}))}),lA){let je=t._localScreenTrack&&((l=t._localScreenConfig)==null?void 0:l.publish)&&t._localScreenConfig.streamType==="main";t._room.isJoined?!je||H?(t._room.publish(MA).catch(()=>{}),((d=t._localScreenConfig)==null?void 0:d.streamType)==="main"&&t._localScreenConfig&&(t._localScreenConfig.publish=!1)):(lA=!1,t._log.warn("main stream is already published, local video track will not publish")):je&&(lA=!1)}t._localVideoTrack=MA,t._room.capturedLocalMainVideoTrack=MA,t._localVideoConfig=So(Di({},o),{view:h,publish:lA,capture:hA}),yield t._updateVideoPlayOption({view:h,playOption:fe,track:MA})}()})}updateLocalVideo(t){return XA(this,null,function*(){var o,a,l,d,h,y,S;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:L,publish:V=!0,mute:H,capture:lA,option:hA,forcePublish:MA=!1}=t,oe=V||MA,fe=lA,je={};if(!this._localVideoConfig.capture&&Lp((o=this.localVideoTrack)==null?void 0:o.outMediaTrack)&&(hA!=null&&hA.cameraId||hA!=null&&hA.videoTrack)&&this._localVideoTrack.outMediaTrack!==hA?.videoTrack&&(fe=!0),this._localVideoConfig.capture)fe!==!1?hA!=null&&hA.cameraId?yield this._localVideoTrack.switchDevice(hA?.cameraId):ze(hA?.useFrontCamera)?ze(hA?.videoTrack)||(Lp(hA?.videoTrack)?hA?.videoTrack!==((a=this.localVideoTrack)==null?void 0:a.outMediaTrack)&&(yield this._localVideoTrack.setOutputMediaStreamTrack(hA?.videoTrack)):yield this._localVideoTrack.setInputMediaStreamTrack(hA?.videoTrack)):yield this._localVideoTrack.switchDevice(hA!=null&&hA.useFrontCamera?JA.FACING_MODE_USER:JA.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(fe){let _e={};_e.deviceId=hA?.cameraId||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),_e.facingMode=hA!=null&&hA.useFrontCamera||(d=this._localVideoConfig.option)!=null&&d.useFrontCamera?JA.FACING_MODE_USER:JA.FACING_MODE_ENVIRONMENT,_e.customSource=hA!=null&&hA.videoTrack||!_e.deviceId?(h=this._localVideoConfig.option)==null?void 0:h.videoTrack:void 0,yield this._localVideoTrack.capture(_e)}hA&&(ze(hA.profile)||(Ws(hA.profile)?FC[hA.profile]&&this._localVideoTrack.setProfile(FC[hA.profile]):this._localVideoTrack.setProfile(hA.profile),(!hA.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(hA.cameraId||hA.useFrontCamera?JA.FACING_MODE_USER:JA.FACING_MODE_ENVIRONMENT))&&(yield this._localVideoTrack.applyProfile())),ze(hA.fillMode)||(je.objectFit=hA.fillMode),ze(hA.mirror)||(je.mirror=hA.mirror),ze(hA.rotation)||this._localVideoTrack.setRotation(hA.rotation),hA.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(v1(hA.qosPreference)),ze(hA.small)||(br(hA.small)&&!hA.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(M1(hA.small,!0)))),this._room.isJoined&&ze(oe)&&this._localVideoConfig.publish&&fe&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((oe??this._localVideoConfig.publish)||MA?this._localScreenTrack&&((y=this._localScreenConfig)!=null&&y.publish)&&this._localScreenConfig.streamType==="main"&&!MA?(oe=!1,this._log.warn("main stream is already published, local video track will not publish")):(this._room.publish(this._localVideoTrack).catch(()=>{}),((S=this._localScreenConfig)==null?void 0:S.streamType)==="main"&&this._localScreenConfig&&(this._localScreenConfig.publish=!1)):this._room.unpublish(this._localVideoTrack).catch(()=>{})),ze(H)||(yield this._localVideoTrack.setMute(H)),yield this._updateVideoPlayOption({view:L,playOption:je,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),$h(this._localVideoConfig,So(Di({},t),{publish:oe,capture:fe}))})}stopLocalVideo(){return XA(this,null,function*(){var t;this._localVideoTrack&&(this._room.isJoined&&(t=this._localVideoConfig)!=null&&t.publish&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),Vs(this._localVideoTrack),this._localVideoTrack=null,delete this._room.capturedLocalMainVideoTrack,this._localVideoConfig=null)})}startScreenShare(){return XA(this,arguments,function(){var t=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0,view:null};return function*(){var a,l,d;if(t._localScreenTrack)return void t._log.warn("screen share is already started");let{view:h=null,publish:y=!0,muteSystemAudio:S,option:L}=o,V=y,H=new eM(t._room.videoManager);H.on("4",fe=>{let je;fe.error&&(je=Lo.convertFrom(fe.error)),t.emit(Ao.PUBLISH_STATE_CHANGED,So(Di({},fe),{error:je}))}),H.once("first-video-frame",fe=>{t.emit(Ao.FIRST_VIDEO_FRAME,So(Di({},fe),{streamType:iC(fe.streamType)}))}),t._listenOutputTrackChanged(H),o.streamType==="main"&&(H.mediaType=4);let lA=null,hA={},MA={};L&&(ze(L.profile)||(Ws(L.profile)?Ub[L.profile]&&H.setProfile(Ub[L.profile]):H.setProfile(L.profile)),L.systemAudio&&(hA.systemAudio=!0,hA.echoCancellation=L.echoCancellation,hA.noiseSuppression=L.noiseSuppression,hA.autoGainControl=L.autoGainControl),ze(L.fillMode)||(MA.objectFit=L.fillMode),L.videoTrack&&(hA.videoTrack=L.videoTrack),L.audioTrack&&(hA.audioTrack=L.audioTrack),L.captureElement&&(hA.captureElement=L.captureElement),L.preferDisplaySurface&&(hA.preferDisplaySurface=L.preferDisplaySurface),L.qosPreference&&(hA.contentHint=v1(L.qosPreference)));let oe=yield H.capture(hA);if(H.mediaTrack.addEventListener(JA.ENDED,()=>{t._stopScreenShare(),t.emit(Ao.SCREEN_SHARE_STOPPED)}),oe.getAudioTracks()[0]){lA=new Dj(t._room.audioManager);let fe=oe.getAudioTracks()[0];(a=o.option)!=null&&a.systemAudio&&!((l=o.option)!=null&&l.audioTrack)&&(lA.sourceTrack=fe),yield lA.setInputMediaStreamTrack(fe),br(S)&&lA.mediaTrack&&(lA.mediaTrack.enabled=!S),t._speakerId&&lA.setAudioOutput(t._speakerId)}if(gd(H,H).add("player-state-changed",fe=>{t.emit(Ao.VIDEO_PLAY_STATE_CHANGED,So(Di({},fe),{userId:"",streamType:"sub"}))}),V){let fe=t._localVideoTrack&&((d=t._localVideoConfig)==null?void 0:d.publish),je=!(o.streamType==="main"&&fe);t._room.isJoined?(je?t._room.publish(H).catch(()=>{}):(V=!1,t._log.warn("main stream is already published, screen share main will not publish")),lA&&(t._checkScreenAudioEchoCancellation(H,lA),t._room.publish(lA).catch(()=>{}))):je||(V=!1)}t._localScreenTrack=H,t._room.capturedLocalAuxVideoTrack=H,t._localScreenAudioTrack=lA,t._localScreenConfig=So(Di({},o),{view:h,publish:V}),yield t._updateVideoPlayOption({view:h,playOption:MA,track:H})}()})}updateScreenShare(t){return XA(this,null,function*(){var o,a;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:l,publish:d,muteSystemAudio:h,option:y}=t,S=d,L={};if(y){if(ze(y.fillMode)||(L.objectFit=y.fillMode),y.qosPreference){let V=v1(y.qosPreference);this._localScreenTrack.setContentHint(V)}y.videoTrack&&this._localScreenTrack.setInputMediaStreamTrack(y.videoTrack),y.audioTrack&&this._localScreenAudioTrack&&this._localScreenAudioTrack.setInputMediaStreamTrack(y.audioTrack)}if(this._room.isJoined&&!ze(S)){if(S&&!this._localScreenConfig.publish){let V=this._localVideoTrack&&((o=this._localVideoConfig)==null?void 0:o.publish);this._localScreenConfig.streamType==="main"&&V?(S=!1,this._log.warn("main stream is already published, screen share main will not publish")):this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})}if(this._localScreenConfig.publish&&!S){let V=[this._localScreenTrack];this._localScreenAudioTrack&&V.push(this._localScreenAudioTrack),V.forEach(H=>this._room.unpublish(H).catch(()=>{}))}}(a=this._localScreenAudioTrack)!=null&&a.mediaTrack&&br(h)&&(this._localScreenAudioTrack.mediaTrack.enabled=!h),yield this._updateVideoPlayOption({view:l,playOption:L,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),$h(this._localScreenConfig,So(Di({},t),{publish:S}))})}stopScreenShare(){return XA(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(t){return XA(this,null,function*(){let{view:o,userId:a,streamType:l,option:d}=t,h="".concat(a,"_").concat(l);if(this._remoteVideoConfigMap.has(h))return void this._log.warn("remote video has already started. userId:".concat(a,", streamType:").concat(l));let y=this._room.remotePublishedUserMap.get(a);if(!y)return;let S={},L=l==="main"?y.remoteVideoTrack:y.remoteAuxiliaryTrack,V=this._bindRemoteVideoTrackEvents(L);this._listenOutputTrackChanged(L),d&&(ze(d.fillMode)||(S.objectFit=d.fillMode),ze(d.mirror)||(S.mirror=d.mirror),ze(d.poster)||(S.poster=d.poster),S.canvasRender=d.canvasRender,l==="main"&&!ze(d.small)&&(!y.remoteVideoTrack.isSubscribing&&!y.remoteVideoTrack.isSubscribed&&y.remoteVideoTrack.setMediaType(d.small?8:4),this._room.changeType(d.small,L.user)),ze(d.draggable)||L.setDraggable(d.draggable)),S.isLiveStream=!!this._playbackQualityList.find(H=>H.userId===a&&H.streamType===l),yield this._room.subscribe(L),yield this._enableVideoDecodeFallback(L,l),yield this._updateVideoPlayOption({view:o,playOption:S,track:L}),this._emitTrackEvent(L),this._remoteVideoConfigMap.set(h,{config:t,handlers:V}),d&&!ze(d.receiveWhenViewVisible)&&this._observeView({remoteTrack:L,view:o,receiveWhenViewVisible:d.receiveWhenViewVisible,viewRoot:d?.viewRoot})})}updateRemoteVideo(t){return XA(this,null,function*(){var o,a;let{view:l,userId:d,streamType:h,option:y,mute:S}=t,L="".concat(d,"_").concat(h),V=this._remoteVideoConfigMap.get(L);if(!V||!this._room.remotePublishedUserMap.has(d))return;let H={};y&&(ze(y.fillMode)||(H.objectFit=y.fillMode),ze(y.mirror)||(H.mirror=y.mirror));let lA=null,hA=this._room.remotePublishedUserMap.get(d);if(h==="main"&&hA!=null&&hA.muteState.hasVideo&&(lA=hA.remoteVideoTrack),h==="sub"&&hA!=null&&hA.muteState.hasAuxiliary&&(lA=hA.remoteAuxiliaryTrack),!lA)return;let{config:MA}=V;h==="main"&&y&&!ze(y.small)&&this._room.changeType(y.small,lA.user),y&&!ze(y.draggable)&&lA.setDraggable(y.draggable),y&&(br(y.pictureInPicture)&&(y.pictureInPicture?yield lA.player.enterPictureInPicture():yield lA.player.exitPictureInPicture()),br(y.fullScreen)&&(y.fullScreen?yield lA.player.enterFullscreen():yield lA.player.exitFullscreen())),br(S)&&(lA.ignoreUpdatePlayingState=!0,S?(yield lA.player.pause(),yield this.room.unsubscribe(lA)):(yield this.room.subscribe(lA),yield lA.player.resume(!0))),yield this._updateVideoPlayOption({view:l,playOption:H,track:lA,prevConfig:MA}),$h(MA,t);let oe=ze(y?.receiveWhenViewVisible)?(o=MA.option)==null?void 0:o.receiveWhenViewVisible:y.receiveWhenViewVisible,fe=ze(l)?MA.view:l,je=ze(y?.viewRoot)?(a=MA.option)==null?void 0:a.viewRoot:y.viewRoot;this._observeView({remoteTrack:lA,view:fe,receiveWhenViewVisible:oe,viewRoot:je})})}stopRemoteVideo(t){return XA(this,null,function*(){return this._stopRemoteVideo(t)})}_stopRemoteVideo(t){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return XA(this,null,function*(){let a=[],l=this._room.remotePublishedUserMap.get(t.userId);if(l){let{muteState:d,remoteVideoTrack:h,remoteAuxiliaryTrack:y}=l;t.streamType==="main"&&(h.stop(),d.hasVideo&&a.push(h)),t.streamType==="sub"&&(y.stop(),d.hasAuxiliary&&a.push(y))}for(let d of a)o&&(delete d.ignoreUpdatePlayingState,yield this._room.unsubscribe(d),this._mediaTrackMap.delete(d.outMediaTrack));this._removeRemoteVideoConfig(t.userId,t.streamType)})}_removeRemoteVideoConfig(t,o){let a="".concat(t,"_").concat(o),l=this._remoteVideoConfigMap.get(a);if(l&&(l.observer&&l.observer.disconnect(),l.handlers)){let d=this._room.remotePublishedUserMap.get(t);if(d){let h=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack;this._unbindRemoteVideoTrackEvents(h,l.handlers)}}this._remoteVideoConfigMap.delete(a)}_bindRemoteVideoTrackEvents(t){let o={onEnterPIP:()=>XA(this,null,function*(){yield t.player.enterPIPPromise,this.emit(Ao.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:iC(t.streamType),userId:t.userId,isPictureInPicture:!0,pictureInPictureWindow:t.player.pipWindow})}),onLeavePIP:()=>{this.emit(Ao.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:iC(t.streamType),userId:t.userId,isPictureInPicture:!1})},onEnterFullScreen:()=>{this.emit(Ao.FULL_SCREEN_STATE_CHANGED,{streamType:iC(t.streamType),userId:t.userId,isFullScreen:!0})},onLeaveFullScreen:()=>{this.emit(Ao.FULL_SCREEN_STATE_CHANGED,{streamType:iC(t.streamType),userId:t.userId,isFullScreen:!1})},onDecodeFailed:()=>{this.emit(Ao.ERROR,new Lo({code:ko.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))},onVideoSizeChanged:a=>{this.emit(Ao.VIDEO_SIZE_CHANGED,So(Di({},a),{streamType:iC(a.streamType)}))}};return t.player.on(Mo.ENTER_PICTURE_IN_PICTURE,o.onEnterPIP),t.player.on(Mo.LEAVE_PICTURE_IN_PICTURE,o.onLeavePIP),t.player.on(Mo.ENTER_FULL_SCREEN,o.onEnterFullScreen),t.player.on(Mo.LEAVE_FULL_SCREEN,o.onLeaveFullScreen),t.on("decode-failed",o.onDecodeFailed),t.on("video-size-changed",o.onVideoSizeChanged),o}_unbindRemoteVideoTrackEvents(t,o){t.player.off(Mo.ENTER_PICTURE_IN_PICTURE,o.onEnterPIP),t.player.off(Mo.LEAVE_PICTURE_IN_PICTURE,o.onLeavePIP),t.player.off(Mo.ENTER_FULL_SCREEN,o.onEnterFullScreen),t.player.off(Mo.LEAVE_FULL_SCREEN,o.onLeaveFullScreen),t.off("decode-failed",o.onDecodeFailed),t.off("video-size-changed",o.onVideoSizeChanged)}muteRemoteAudio(t,o){return XA(this,null,function*(){this._remoteAudioMuteMap.set(t,o);try{if(t==="*")if(o)yield this._stopRemoteAudio({userId:t});else{let a=[...this._room.remotePublishedUserMap.values()];for(let l of a)l.muteState.hasAudio&&!this._remoteAudioConfigMap.has(l.userId)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:l.userId}))}else o?yield this._stopRemoteAudio({userId:t}):!this._remoteAudioConfigMap.has(t)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:t}))}catch(a){throw a.code!==ko.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(t),a}})}setRemoteAudioVolume(t,o){if(t==="*"){this._remoteAudioVolumeMap.set("*",o),this._remoteAudioVolumeMap.forEach((l,d)=>this._remoteAudioVolumeMap.set(d,o));let a=[...this._room.remotePublishedUserMap.values()];for(let l of a)this._remoteAudioVolumeMap.set(l.userId,o),l.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:o},track:l.remoteAudioTrack})}else if(t){let a=this._room.remotePublishedUserMap.get(t);this._remoteAudioVolumeMap.set(t,o),a&&a.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:o},track:a.remoteAudioTrack})}}startPlugin(t,o){return XA(this,null,function*(){return t.start(o)})}updatePlugin(t,o){return XA(this,null,function*(){return t.update(o)})}stopPlugin(t,o){return XA(this,null,function*(){return t.stop(o)})}enableAudioVolumeEvaluation(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3,o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this._room.enableAudioVolumeEvaluation(t,o)}on(t,o,a){if(this.listeners(t).includes(o))return this;if(this._log.debug("on",t),super.on(t,o,a),this._eventListened.add(t),this.listeners(Ao.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:l}=this.room.audioManager;l.get("")||l.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return t==="realtime-transcriber-message"&&this._room.subscribeDataChannel(),this}emit(t){for(var o=arguments.length,a=new Array(o>1?o-1:0),l=1;l{d?.abort("off")}),l.clear()}return this}getAudioTrack(){let t,o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userId:"",streamType:"main"},a=null,l="main",d=!1;if(Ws(o)?t=o:(t=o.userId,d=o.processed===!0,o.streamType&&(l=o.streamType)),t){let h=this._room.remotePublishedUserMap.get(t);h&&(a=h.remoteAudioTrack)}else a=l==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return a?d&&a.outMediaTrack&&a.outMediaTrack!==a.mediaTrack?a.outMediaTrack.clone():a.mediaTrack:null}getVideoTrack(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userId:"",streamType:"main"},{userId:o="",streamType:a="main",processed:l=!1}=t,d=null;if(o==="")a==="main"&&this._localVideoTrack&&(d=this._localVideoTrack),a==="sub"&&this._localScreenTrack&&(d=this._localScreenTrack);else{let h=this._room.remotePublishedUserMap.get(o);h&&(d=a==="main"?h.remoteVideoTrack:h.remoteAuxiliaryTrack)}return d?l&&d.outMediaTrack&&d.outMediaTrack!==d.mediaTrack?d.outMediaTrack.clone():d.mediaTrack:null}getVideoSnapshot(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{userId:o,streamType:a="main"}=t;if(o){let l=this._room.remotePublishedUserMap.get(o);if(a==="main"&&l!=null&&l.muteState.hasVideo)return l.remoteVideoTrack.getVideoFrame();if(a==="sub"&&l!=null&&l.muteState.hasAuxiliary)return l.remoteAuxiliaryTrack.getVideoFrame()}else{if(a==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(a==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(t){var o,a;this._speakerId=t,(o=this._localAudioTrack)==null||o.setAudioOutput(t),(a=this._localScreenAudioTrack)==null||a.setAudioOutput(t),this._room.remotePublishedUserMap.forEach(l=>l.remoteAudioTrack.setAudioOutput(t))}setCurrentSpeaker(t){return XA(this,null,function*(){(yield Zv()).forEach(o=>{o.deviceId===t&&(this._setCurrentSpeaker(t),this.emit(Ao.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),tI=o)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: '.concat(zh,"/en/TRTC.html#.setCurrentSpeaker"))})}_startRemoteAudio(t){return this._doStartRemoteAudio(t)}_doStartRemoteAudio(t){return XA(this,null,function*(){var o;let{userId:a}=t;if(this._remoteAudioConfigMap.has(a))return void this._log.warn("remote audio has already started. userId:".concat(a));let l=this._room.remotePublishedUserMap.get(a);if(!l)return;let d={},h=l.remoteAudioTrack;h.on("decode-failed",y=>{this.emit(Ao.ERROR,new Lo({code:ko.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(h),this._speakerId&&h.setAudioOutput(this._speakerId);try{let y=(o=this._remoteAudioVolumeMap.get(a))!=null?o:this._remoteAudioVolumeMap.get("*"),S=Ys(y)?y:100;d.volume=S,this._remoteAudioConfigMap.set(a,t),yield this._room.subscribe(h),Ma(Ea(h,"decode-failed"),CE(Ea(h,gs.INIT)),Dl(()=>{this.startPlugin(o8.Name,{track:h,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:d,track:h}),F.emit("115",{userId:a,room:this.room}),h.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:h.outMediaTrack,refId:"ra-".concat(a)})}catch(y){throw this._remoteAudioConfigMap.delete(a),y}this._emitTrackEvent(h)})}_stopRemoteAudio(t){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return XA(this,null,function*(){let a=this._room.remotePublishedUserMap.get(t.userId);a&&(a.remoteAudioTrack.stop(),a.muteState.hasAudio&&o&&(yield this._room.unsubscribe(a.remoteAudioTrack)),this._mediaTrackMap.delete(a.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(t.userId)),F.emit("116",{userId:t.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:"ra-".concat(t.userId)})})}_enableVideoDecodeFallback(t,o){let a,l=this._room.videoDecodeFallbackType;l&&this._plugins.has("TRTCVideoDecoder")&&(t.log.debug("remote video will fall back when decode failed",t.id),Ma(Ea(t,"decode-failed"),CE(Ea(t,gs.INIT)),hj(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:t,config:{codec:"avc1.420028"},fallback:l})}),Q1(Ea(t,"decode-downgrade-state-changed")),Dl(d=>{a=d.state,this.emit(Ao.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,So(Di({},d),{streamType:o,userId:t.userId}))},d=>{t.log.error("fallback",d)},()=>{a==="STARTED"&&t.log.info("fallback complete")})))}_updateVideoPlayOption(t){return XA(this,arguments,function(o){let{view:a,playOption:l,track:d,prevConfig:h}=o;return function*(){if(d.setMirror(l.mirror),ze(a)&&h&&h.view&&!b0(l)){let y=dv(h.view);y.length>0&&(yield d.play(y,l))}if(!ze(a)){let y=dv(a);y.length>0?yield d.play(y,l):d.stop()}}()})}_updateAudioPlayOption(t){return XA(this,arguments,function(o){var a=this;let{playOption:l={},track:d,prevConfig:h}=o;return function*(){if(!d.isPlayCalled)try{yield d.play(null,l)}catch{}if(ze(l.muted)||d.setPlayerMute(l.muted),ze(l.volume)||d.setAudioVolume(l.volume/100),d instanceof AM&&d.mediaTrack){let y=l.muted===!1&&!ze(l.volume)&&l.volume>0?"add":"remove";a.room.audioManager.updateAudioReference({type:y,audioReference:d.mediaTrack,refId:"em"})}else if(d instanceof y1){let y=l.muted?0:l.volume;if(ze(y))return;a.room.audioManager.updateAudioReference({type:"updateVolume",refId:"ra-".concat(d.userId),volume:l.volume})}}()})}_listenOutputTrackChanged(t){t.listeners("output-media-track-changed").length===0&&t.on("output-media-track-changed",()=>this._emitTrackEvent(t,!1))}_emitTrackEvent(t){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],a=t.isRemote?t.userId:"";t.outMediaTrack&&(o&&this._mediaTrackMap.get(t.outMediaTrack)===a||(this._mediaTrackMap.set(t.outMediaTrack,a),this.emit(Ao.TRACK,{userId:a,streamType:iC(t.streamType),track:t.outMediaTrack,sourceTrack:t.mediaTrack})))}_checkTrackToPublish(){var t,o,a;let l=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&l.push(this._localAudioTrack),(o=this._localVideoConfig)!=null&&o.publish&&this._localVideoTrack&&l.push(this._localVideoTrack),(a=this._localScreenConfig)!=null&&a.publish&&(this._localScreenTrack&&l.push(this._localScreenTrack),this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),l.length!==0)return Promise.all(l.map(d=>this._room.publish(d).catch(()=>{})))}_observeView(t){let{remoteTrack:o,view:a,receiveWhenViewVisible:l,viewRoot:d}=t;if(ze(a)||ze(l))return;let h=this._remoteVideoConfigMap.get("".concat(o.userId,"_").concat(iC(o.streamType)));if(!h)return;let y=h.observer||void 0;if(a===null||ka(a)&&a.length===0||!l)return y?.disconnect(),void(o.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",o.userId,o.strMediaType),this._room.subscribe(o).catch(()=>{})));let S=h.visibleViewMap||new Map,L=-1;(!y||y.root!==d)&&(y?.disconnect(),S.clear(),y=new IntersectionObserver(H=>{H.forEach(lA=>{S.set(lA.target,lA.isIntersecting),o.log.info("view ".concat(lA.target.id," is").concat(lA.isIntersecting?"":" not"," visible"))}),clearTimeout(L),L=window.setTimeout(()=>{[...S.values()].find(lA=>lA)?o.isSubscribed||this._room.subscribe(o).catch(()=>{}):o.isSubscribed&&this._room.unsubscribe(o).catch(()=>{})},200)},{root:d}));let V=new Set(dv(a));S.forEach((H,lA)=>{V.has(lA)||(y.unobserve(lA),S.delete(lA))}),V.forEach(H=>{S.set(H,!0),y.observe(H)}),y.takeRecords().forEach(H=>{S.set(H.target,H.isIntersecting)}),h.visibleViewMap=S,h.observer=y}_exitRoom(){return XA(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return XA(this,null,function*(){var t,o;if(this._localScreenTrack){if(this._room.isJoined){let a=[];(t=this._localScreenConfig)!=null&&t.publish&&a.push(this._localScreenTrack),this._localScreenAudioTrack&&a.push(this._localScreenAudioTrack),yield Promise.all(a.map(l=>this._room.unpublish(l).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((o=this._localScreenAudioTrack.trackSettings)==null?void 0:o.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),Vs(this._localScreenTrack),this._localScreenTrack=null,delete this._room.capturedLocalAuxVideoTrack,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(t,o){return XA(this,null,function*(){var a,l;if(!t||!o)return;let d=(a=t.trackSettings)==null?void 0:a.displaySurface;if(((l=o.trackSettings)==null?void 0:l.echoCancellation)===!1&&(d==="monitor"||d==="browser"&&t.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(h){this._log.warn("start audioProcessor plugin failed: ",h)}}})}_onLocalTrackCaptured(t){let{track:o}=t;o.kind==="audio"&&(!tI||cL(tI))&&(this._initActiveSpeaker(),F.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return XA(this,null,function*(){if(tI&&!cL(tI))this.emit(Ao.DEVICE_CHANGED,{type:"speaker",action:"active",device:tI});else{let t=yield Zv();t[0]&&!cL(t[0])?(tI=t[0],this.emit(Ao.DEVICE_CHANGED,{type:"speaker",action:"active",device:t[0]})):F.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable(t){let{userId:o}=t,a=this._remoteAudioMuteMap.has(o)?this._remoteAudioMuteMap.get(o):this._remoteAudioMuteMap.get("*");(a===!1||this._room.autoReceiveAudio&&!a)&&this._doStartRemoteAudio({userId:o}).catch(()=>{})}_onVideoAvailable(t){let{userId:o,streamType:a}=t;if(!this._room.autoReceiveVideo)return;let l=this._room.remotePublishedUserMap.get(o);if(l){let d=a==="main"?l.remoteVideoTrack:l.remoteAuxiliaryTrack,h=[d];this._room.autoReceiveAudio&&l.remoteAudioTrack.isAvailable&&h.push(l.remoteAudioTrack),this._room.subscribe(...h).then(()=>{this._emitTrackEvent(d)}).catch(()=>{})}}_onAudioUnavailable(t){let{userId:o,muteState:a}=t;a.hasAudio&&a.audioMuted||this._stopRemoteAudio({userId:o},!1).catch(()=>{})}_onVideoUnavailable(t){let{userId:o,streamType:a}=t;this._stopRemoteVideo({userId:o,streamType:a},!1).catch(()=>{})}_onDataChannelAvailable(){if(this.listeners("realtime-transcriber-message").length>0)return this._room.subscribeDataChannel()}sendSEIMessage(t,o){var a;let l=this._plugins.get("SEI");l&&(l.update({buffer:t,options:So(Di({seiPayloadType:243},o),{small:!((a=this._localVideoTrack)==null||!a.small)})}),ri.addCount({key:5e5,useUV:!0}))}sendCustomMessage(t){var o,a;(a=(o=this._room).sendCustomMessage)==null||a.call(o,t),ri.addCount({key:500001,useUV:!0})}callExperimentalAPI(t,o){return XA(this,null,function*(){return this._log.info("callExperimentalAPI(".concat(t,", ").concat(JSON.stringify(o),")")),_oA.call(t,Di({trtcInstance:this},o))})}static setLogLevel(t,o){pA.setLogLevel(t),ze(o)||(o?pA.enableUploadLog():pA.disableUploadLog())}static isSupported(){return Hk(Im.frameWorkType)}static getPermissions(t){return XA(this,arguments,function(o){let{request:a=!0,types:l=["camera","microphone"]}=o;return function*(){a&&(yield U1.request(l).catch(y=>{var S;return pA.error("getPermissions request failed, error: ".concat((S=y?.message)!=null?S:y))}));let[d,h]=yield Promise.all([U1.get("camera"),U1.get("microphone")]);return{camera:d,microphone:h}}()})}static getCameraList(){return nm(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getMicrophoneList(){return om(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getSpeakerList(){return Zv(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static setCurrentSpeaker(t){return XA(this,null,function*(){if(za&&(t===yL.SPEAKER||t===yL.HEADSET)){let o=yield Im.getMicrophoneList(),a="";return o.forEach(l=>{l.label===t&&(a=l.deviceId)}),a?void ML.forEach(l=>XA(null,null,function*(){l._localAudioTrack&&(yield l.updateLocalAudio({option:{microphoneId:a}}))})):void 0}(yield Zv()).forEach(o=>{o.deviceId===t&&(ML.forEach(a=>{a._setCurrentSpeaker(t),a.emit(Ao.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),tI=o)})})}static _addKVStat(t){let{type:o,key:a,value:l,base:d,useUV:h,version:y,max:S}=t;switch(y&&(eB.version=y),o){case"count":eB.addCount({key:a,useUV:h});break;case"enum":eB.addEnum({key:a,value:l,useUV:h});break;case"number":eB.addNumber({key:a,value:l,split:d,max:S})}}get localVideoTrack(){return this._localVideoTrack}get localScreenTrack(){return this._localScreenTrack}get localScreenAudioTrack(){return this._localScreenAudioTrack}};Y(bn,"VERSION",Xz),Y(bn,"_loggerManager",pA),Y(bn,"EVENT",Ao),Y(bn,"ERROR_CODE",ko),Y(bn,"TYPE",yL),Y(bn,"frameWorkType",30),Qi([Ra({replaceArg:A=>({argIndex:0,value:{name:"plugin"in A?A.plugin.Name:A.Name,assetsPath:"assetsPath"in A?A?.assetsPath:"default"}})})],bn.prototype,"use"),Qi([mu(eI.TRTC.enterRoom),oM("room",(A,t)=>{let[o]=A,[a]=t;return(o.roomId||o.strRoomId)===(a.roomId||a.strRoomId)&&o.userId===a.userId&&o.sdkAppId===a.sdkAppId}),Xr(A=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),A.call(this,t)}),Ra()],bn.prototype,"enterRoom"),Qi([Ra()],bn.prototype,"exitRoom"),Qi([mu(eI.TRTC.switchRoom),Ra(),lL()],bn.prototype,"switchRoom"),Qi([mu(eI.TRTC.switchRole),S_("room",{merge:(A,t)=>t}),Ra()],bn.prototype,"switchRole"),Qi([Ra()],bn.prototype,"destroy"),Qi([mu(eI.TRTC.startLocalAudio),oM("audio",(A,t)=>{let[o]=A,[a]=t;var l,d;return((l=o?.option)==null?void 0:l.microphoneId)===((d=a?.option)==null?void 0:d.microphoneId)}),Ra()],bn.prototype,"startLocalAudio"),Qi([mu(eI.TRTC.updateLocalAudio),S_("audio",{debounce:{delay:200,getKey:()=>"".concat(n8,"-localAudio"),isNeedToDebounce:A=>{var t;return!ze((t=A.option)==null?void 0:t.captureVolume)}}}),Ra()],bn.prototype,"updateLocalAudio"),Qi([nM("audio"),Ra()],bn.prototype,"stopLocalAudio"),Qi([mu(eI.TRTC.startLocalVideo),oM("video",(A,t)=>{let[o]=A,[a]=t;var l,d;return((l=o?.option)==null?void 0:l.cameraId)===((d=a?.option)==null?void 0:d.cameraId)}),Ra()],bn.prototype,"startLocalVideo"),Qi([mu(eI.TRTC.updateLocalVideo),S_("video"),Ra()],bn.prototype,"updateLocalVideo"),Qi([nM("video"),Ra()],bn.prototype,"stopLocalVideo"),Qi([mu(eI.TRTC.startScreenShare),oM("screen",()=>!0),Ra()],bn.prototype,"startScreenShare"),Qi([mu(eI.TRTC.updateScreenShare),S_("screen"),Ra()],bn.prototype,"updateScreenShare"),Qi([Ra()],bn.prototype,"stopScreenShare"),Qi([mu(eI.TRTC.startRemoteVideo),oM(A=>"v".concat(A.userId).concat(A.streamType),()=>!0),Ra({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],bn.prototype,"startRemoteVideo"),Qi([mu(eI.TRTC.updateRemoteVideo),S_(A=>"v".concat(A.userId).concat(A.streamType)),Ra({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],bn.prototype,"updateRemoteVideo"),Qi([mu(eI.TRTC.stopRemoteVideo),Xr(A=>function(t){return XA(this,null,function*(){if(t.userId==="*"){let o=[];return this._room.remotePublishedUserMap.forEach(a=>{this._remoteVideoConfigMap.has("".concat(a.userId,"_main"))&&o.push(this.stopRemoteVideo({streamType:"main",userId:a.userId}).catch(()=>{})),this._remoteVideoConfigMap.has("".concat(a.userId,"_sub"))&&o.push(this.stopRemoteVideo({streamType:"sub",userId:a.userId}).catch(()=>{}))}),Promise.all(o)}return A.call(this,t)})}),Ra({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],bn.prototype,"stopRemoteVideo"),Qi([nM(A=>"v".concat(A.userId).concat(A.streamType))],bn.prototype,"_stopRemoteVideo"),Qi([mu(...eI.TRTC.muteRemoteAudio),Ra({getRemoteId:A=>A})],bn.prototype,"muteRemoteAudio"),Qi([$z(...eI.TRTC.setRemoteAudioVolume),function(A,t){return Xr((o,a)=>function(){for(var l=arguments.length,d=new Array(l),h=0;h{var H;(H=v_.get(this))==null||H.delete(S)},A);y.set(S,V)}else{clearTimeout(L);let V=window.setTimeout(()=>{var H;o.apply(this,d),(H=v_.get(this))==null||H.delete(S)},A);y.set(S,V)}})}(200,A=>A),Ra({getRemoteId:A=>A})],bn.prototype,"setRemoteAudioVolume"),Qi([Gj("start"),Xv(A=>{var t;return(t=A.afterStart)==null?void 0:t.call(A)}),oM((A,t)=>A.disableRandomCall?null:A.getAlias()+A.getGroup(t)),Ra({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>j2[A.getName()],ignoreLog:A=>A.getName()==="Debug",ignoreErrorLog:A=>A.getName()==="AudioProcessor"})],bn.prototype,"startPlugin"),Qi([Gj("update"),S_((A,t)=>A.disableRandomCall?null:A.getAlias()+A.getGroup(t),{merge:(A,t)=>($h(A[1],t[1]),A)}),Ra({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>py[A.getName()]})],bn.prototype,"updatePlugin"),Qi([Gj("stop"),nM((A,t)=>{if(A.disableRandomCall)return null;let o=A.getGroup(t),a=A.getAlias();return o==="*"?new RegExp("".concat(a,".*")):a+o}),Ra({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>r_[A.getName()]})],bn.prototype,"stopPlugin"),Qi([$z(...eI.TRTC.enableAudioVolumeEvaluation)],bn.prototype,"enableAudioVolumeEvaluation"),Qi([Ra()],bn.prototype,"getVideoSnapshot"),Qi([Ra()],bn.prototype,"_setCurrentSpeaker"),Qi([oM(A=>"a".concat(A.userId),()=>!0)],bn.prototype,"_startRemoteAudio"),Qi([Xr(A=>function(t){return XA(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(So(Di({},t),{userId:o.userId})).catch(()=>{}))):A.call(this,t)})}),nM(A=>"a".concat(A.userId))],bn.prototype,"_stopRemoteAudio"),Qi([nM("room")],bn.prototype,"_exitRoom"),Qi([nM("screen")],bn.prototype,"_stopScreenShare"),Qi([mu(...eI.TRTC.sendSEIMessage),Dz({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var A=arguments.length,t=new Array(A),o=0;oA.data.byteLength})],bn.prototype,"sendCustomMessage"),Qi([Ra()],bn.prototype,"callExperimentalAPI"),Qi([sM()],bn,"create"),Qi([mu(eI.TRTC.create)],bn,"_create"),Qi([sM()],bn,"setLogLevel"),Qi([sM()],bn,"isSupported"),Qi([sM(),Ra()],bn,"getPermissions"),Qi([sM()],bn,"getCameraList"),Qi([sM()],bn,"getMicrophoneList"),Qi([sM()],bn,"getSpeakerList");var RL=bn,GoA=class{constructor(){Y(this,"_set",new Set),F.on(rA.LEAVE_SUCCESS,this.delete,this),F.on(rA.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add(A){let{room:t,roomId:o}=A;if(t.scene==="rtc")return;let a=this.getKey(t.userId,o||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(a)}delete(A){let{room:t,roomId:o}=A;if(t.scene==="rtc")return;let a=this.getKey(t.userId,t.roomId||o,t.sdkAppId,t.useStringRoomId);this._set.delete(a)}getKey(A,t,o,a){return"".concat(o,"_").concat(t,"_").concat(A,"_").concat(a)}isJoined(A){let{userId:t,roomId:o,sdkAppId:a,room:l}=A;return l.scene!=="rtc"&&this._set.has(this.getKey(t,o,a,l.useStringRoomId))}handleSwitchRoomSuccess(A){let{room:t,currentRoomId:o,targetRoomId:a}=A;t.scene!=="rtc"&&(this._set.delete(this.getKey(t.userId,o,t.sdkAppId,t.useStringRoomId)),this._set.add(this.getKey(t.userId,a,t.sdkAppId,t.useStringRoomId)))}};function boA(){return XA(this,null,function*(){let A,t;try{let hA=yield om();A=hA&&hA.length}catch{}try{let hA=yield nm();t=hA&&hA.length}catch{}let o={microphone:A,camera:t},{isH264EncodeSupported:a,isVp8EncodeSupported:l,isH264DecodeSupported:d,isVp8DecodeSupported:h,isH265EncodeSupported:y,isH265DecodeSupported:S}=this.checkSystemResult.detail,L=ge.basis(),V={webRTC:L.isWebRTCSupported,getUserMedia:L.isGetUserMediaSupported,webSocket:L.isWebSocketsSupported,screenShare:L.isScreenShareSupported,webAudio:L.isWebAudioSupported,h264Encode:a,h264Decode:d,vp8Encode:l,vp8Decode:h,h265Encode:y,h265Decode:S},H={browser:L.browser,os:L.os,trtc:V,devices:o},lA={isWebCodecSupported:L.isWebCodecSupported,isMediaSessionSupported:L.isMediaSessionSupported,isWebTransportSupported:L.isWebTransportSupported};ds.uploadEvent({log:"trtcstats-".concat(JSON.stringify(H)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(H))),ds.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(lA)),userId:this.userId}),Hv()})}var koA=dc(Xl()),s8="1",Yj="2",wL="3",LoA="4",F1="5",UoA="6",O1="7",r8="8",nB={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},FoA=[nB.UPDATE_REMOTE_MUTE_STAT,nB.UPLINK_NETWORK_STATS,nB.USER_LIST_RES,nB.MUTE_RESULT,nB.SERVER_FIRST_PACKAGE_RECEIVED,nB.RECEIVE_CUSTOM_MSG,nB.UPDATE_NETWORK_TIME_RESULT],Qn={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},a8="publish_change",OoA="join",PoA="leave",xoA="quality_report",g8="mute_uplink",c8="publish",Vj="publish_state_change",P1="unpublish",l8="subscribe",Hj="unsubscribe",Jj="subscribe_change",YoA="start_publishing",VoA="stop_publishing",HoA="start_push_user_cdn",JoA="stop_push_user_cdn",qoA="start_mcu_mix",KoA="stop_mcu_mix",joA="start_publish_cdn_stream",WoA="update_publish_cdn_stream",zoA="stop_publish_cdn_stream",ZoA="get_user_list",XoA="change_role",qj="update_constraint_config",$oA="rebuild_pc",AnA="join/v2",I8="publish/v2",u8="subscribe/v3",enA="ability_status_report",tnA="reconnect",inA="channel_msg",onA="switch_room",nnA="update_network_time",snA=new Set([c8,a8,Vj,P1,l8,Jj,Hj,I8,u8]),x1=new Set,rnA=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],anA=0,E8=class extends koA.default{constructor(A){var t,o,a;super(),Y(this,"room"),Y(this,"sdkAppId"),Y(this,"userId"),Y(this,"userSig"),Y(this,"url"),Y(this,"backupUrl"),Y(this,"destroyed",!1),Y(this,"_socketInUse"),Y(this,"_socket"),Y(this,"_backupSocket"),Y(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0}),Y(this,"_currentState","DISCONNECTED"),Y(this,"_isReconnecting",!1),Y(this,"_seq",0),Y(this,"_log"),Y(this,"_lastMessageTime",-1),Y(this,"_connectStartTime",-1),Y(this,"_stopConnectRetry"),Y(this,"_isFirstConnect",!0),Y(this,"bytesSent",0),Y(this,"bytesReceived",0),Y(this,"keepAlive",!1),Y(this,"signalDomainWhenUnifiedProxy"),Y(this,"stopKeepAliveTimeout"),Y(this,"stopPrelinkTimeout"),Y(this,"rtt",0),Y(this,"prelink",!1),Y(this,"_prelinkConfig"),this.room=A.room,this.sdkAppId=A.sdkAppId,this.userId=A.userId,this.userSig=A.userSig,this.signalDomainWhenUnifiedProxy=A.signalDomainWhenUnifiedProxy,this.prelink=A.prelink||!1;let l=((o=(t=this.room.scheduleResult)==null?void 0:t.config)==null?void 0:o.keepAliveClient)||0;(a=this.room.joinParams)!=null&&a.keepAlive&&!l&&(l=1),l-x1.size>0&&this.room.enableSPC&&(this.keepAlive=!0,x1.add(this)),this.url=A.url,this.backupUrl=A.backupUrl,this._seq=0,this._log=pA.createLogger({parent:this.room.getLogger(),id:"ws".concat(++anA),userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let A="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));this.signalDomainWhenUnifiedProxy&&(A+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy))),this.prelink&&(A+="&prelink=1");let t=new URLSearchParams(location.search);return rnA.forEach(o=>{let a=t.get("trtc_".concat(o));a&&(A+="&".concat(o,"=").concat(encodeURIComponent(a)))}),this.race?"".concat(A,"&race=1"):A}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12e3}connect(){return XA(this,arguments,function(){var A=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1e4;return function*(){if(A.isConnected)return Promise.resolve();A._log.info("connect to [".concat(A.url,", ").concat(A.backupUrl,"] ").concat(A.race?"race":"").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(A.keepAlive))),A.emitConnectionStateChanged("CONNECTING"),A._connectStartTime=Oo();let o=[A.connectWS({url:A._urlWithParam,isMain:!0,timeout:t})];A.race&&A._backupUrlWithParam!==A._urlWithParam&&o.push(A.connectWS({url:A._backupUrlWithParam,isMain:!1,timeout:t})),A._socketInUse=yield uv(o),A.unbindAndCloseSocket(A._socketInUse===A._socket?JA.BACKUP:JA.MAIN),A._isFirstConnect&&(ri.addSuccessEvent({key:521720}),A._isFirstConnect=!1),A.emitConnectionStateChanged("CONNECTED")}()})}connectWS(A){let{url:t,timeout:o,isMain:a}=A,l=new WebSocket(t);this.bindSocket(l),a?this._socket=l:this._backupSocket=l;let d=-1;return new Promise((h,y)=>{l.onclose=y,l.onerror=y,l.onopen=()=>h(l),o&&(d=setTimeout(()=>{this.unbindAndCloseSocket(a?JA.MAIN:JA.BACKUP),y(new li({code:mt.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},o))}).finally(()=>{l.onclose=null,l.onerror=null,l.onopen=null,clearTimeout(d)})}bindSocket(A){A.addEventListener("close",this.onclose),A.addEventListener("error",this.onerror),A.addEventListener("message",this.onmessage)}unbindSocket(A){A.removeEventListener("close",this.onclose),A.removeEventListener("error",this.onerror),A.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(A){if(A===JA.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch{}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch{}this._backupSocket=null}}onclose(A){A.target===this._socketInUse&&(this._log.warn("".concat(A.target===this._socket?"main":"backup"," is closed code:").concat(A.code," ").concat(A.reason)),this.emitConnectionStateChanged("DISCONNECTED"),(!A.wasClean||A.code!==1e3&&A.code!==4013)&&this.startReconnection(),this.prelink&&A.code===4013&&this.room.clearNetworkQuality(),this.room.isJoining&&this.emit(F1,new li({code:mt.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(A){this._log.error("".concat(A.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),A.target===this._socketInUse&&(this.unbindAndCloseSocket(JA.MAIN),this.unbindAndCloseSocket(JA.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(F1,new li({code:mt.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(A){if(!this.isConnected)return;let{isOnline:t}=this;this._lastMessageTime=Date.now(),t||this.emit(r8),this.bytesReceived+=L0(A.data);let o=JSON.parse(A.data),{cmd:a,data:l}=o,d=Object.values(nB),h=Object.keys(nB)[d.indexOf(a)],y=Qn[h]||a;switch(FoA.includes(a)||(this._log.debug("received ".concat(a," msg: ").concat(A.data)),y&&this._log.info("Received event: [ ".concat(y," ]"))),a){case nB.CHANNEL_SETUP_RESULT:if(o.code===0)this._signalInfo.clientIp=l.clientIp,this._signalInfo.signalIp=l.signalInnerIp,l.svrTime&&ZB(l.svrTime-new Date().getTime()),this._log.info("ChannelSetup Success ".concat(Oo()-this._connectStartTime)),ri.addSuccessEvent({key:521701,cost:Oo()-this._connectStartTime}),this._connectStartTime=-1,this.room.firewallDetector.resetTimeoutCount(),this.emit(s8,{signalInfo:this._signalInfo});else{let S=new li({code:mt.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:o.code,message:sn({key:Go.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:o.code,errorMsg:o.message}})});this._log.error("".concat(o.code,", ").concat(o.message)),this.close(),ri.addFailedEvent({key:521701,error:S}),this.emit(F1,S)}break;case nB.JOIN_ROOM_RESULT:o.code===0&&(this._signalInfo.relayIp=l.relayOuterIp,this._signalInfo.relayInnerIp=l.relayInnerIp,this._signalInfo.bakRelayIps=l.bakRelayIps,this._signalInfo.relayPort=l.relayPort,this._signalInfo.tinyId=o.tinyId,this._signalInfo.endReportExtend=l.endReportExtend,this._signalInfo.reportToken=l.reportToken,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(y,{data:o});break;default:this.emit(String(y),{data:o})}}reGetSignalChannelUrl(){return XA(this,null,function*(){try{if(!this.room.joinParams)return;mQ(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:A,backupUrl:t}=this.room.getSignalChannelUrl();this.url=A,this.backupUrl=t}catch{}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let A=this._socketInUse===this._socket;this.unbindAndCloseSocket(A?JA.MAIN:JA.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return XA(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:A,useStringRoomId:t}=this.room,{relayIp:o,relayInnerIp:a,relayPort:l}=this._signalInfo,{data:d}=yield this.sendWaitForResponse({command:tnA,data:{roomId:A,useStringRoomId:t,relayInnerIp:a,relayOuterIp:o,relayPort:l},responseCommand:Qn.CHANNEL_RECONNECT_RESULT});d.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),ri.addSuccessEvent({key:521702,cost:Oo()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(ri.addFailedEvent({key:521702,error:d.code}),this._log.warn("reconnect failed, ".concat(d.code," ").concat(d.message)),this.room.reJoin())}catch(A){this._log.error(A),this.room.reJoin()}}})}send(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let o={cmd:A,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},a=JSON.stringify(o);return this._socketInUse.send(a),snA.has(A)&&this._log.info("send",A,t),this.bytesSent+=L0(a),o.seq}}sendWaitForResponse(A){let{command:t,data:o,timeout:a=5e3,responseCommand:l,commandDesc:d,enableLog:h=!0,addReceiveTime:y=!1}=A;return new Promise((S,L)=>{let V=()=>{clearTimeout(H),L(new li({code:mt.API_CALL_ABORTED,message:"".concat(t," aborted due to connection closed")}))};this.once(O1,V);let H=setTimeout(()=>{this.off(l,lA),this.off(O1,V);let MA=new li({code:mt.API_CALL_TIMEOUT,message:sn({key:Go.API_CALL_TIMEOUT,data:{commandDesc:d,command:t}})});h&&this._log.warn(MA),L(MA)},a),lA=MA=>{MA.data.seq===hA&&(clearTimeout(H),this.off(l,lA),this.off(O1,V),y&&(MA.data.receiveTime=Date.now()),S(MA))};this.on(l,lA);let hA=this.send(t,o)})}sendWaitForResponseWithRetry(A){let{commandDesc:t,command:o,retries:a=0,retryTimeout:l=0}=A;return Bv({retryFunction:this.sendWaitForResponse,onError:d=>{let{retry:h,reject:y,error:S}=d;!this.room.isJoined||this.destroyed||S.code===mt.API_CALL_ABORTED?y(S):this.isOnline?h():(this._log.warn("retry ".concat(o," when connected")),this.once(r8,h))},onRetrying:d=>{this._log.warn("".concat(t||o," timeout observed, retrying [").concat(d,"/").concat(a,"]"))},settings:{retries:a,timeout:l},context:this})(A)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),clearTimeout(this.stopPrelinkTimeout),x1.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(JA.MAIN),this.unbindAndCloseSocket(JA.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(O1)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var A;let t=(A=this._signalInfo.bakRelayIps)==null?void 0:A.shift();return t&&(t.relayPort=t.relayPort||this._signalInfo.relayPort),t}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(A,"s")),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(A,"s")),this.close(),this.off(Qn.JOIN_ROOM_RESULT,t)},1e3*A);let t=o=>{o.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(Qn.JOIN_ROOM_RESULT,t))};this.on(Qn.JOIN_ROOM_RESULT,t)}}stopPrelinkIn(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:300;if(this.keepAlive)return;this._log.info("stopPrelink in ".concat(A,"s")),this.stopPrelinkTimeout=setTimeout(()=>{this._log.info("close prelink due to not used in ".concat(A,"s")),this.close(),this.room.clearNetworkQuality(),this.off(Qn.JOIN_ROOM_RESULT,t)},1e3*A);let t=o=>{o.data.code===0&&(this._log.info("stopPrelink clear timeout"),clearTimeout(this.stopPrelinkTimeout),this.off(Qn.JOIN_ROOM_RESULT,t))};this.on(Qn.JOIN_ROOM_RESULT,t)}markPrelinkConnected(A){this._prelinkConfig=So(Di({},A),{linkedTime:Date.now()})}isPrelinkValid(A,t,o){return!(!this.prelink||!this._prelinkConfig)&&(A!==this._prelinkConfig.sdkAppId||t!==this._prelinkConfig.userId||o!==this._prelinkConfig.userSig?(this._log.warn("prelink params not match"),!1):!!this.isConnected||(this._log.warn("prelink is not connected"),!1))}consumePrelink(){this.prelink=!1,this._prelinkConfig=void 0}emitConnectionStateChanged(A){if(A===this._currentState)return;this._log.info("".concat(this._currentState," -> ").concat(A));let t={prevState:this._currentState,state:A};A==="CONNECTING"&&(t.isReconnecting=this._isReconnecting),this.emit(Yj,t),this._currentState=A,A==="CONNECTED"?this.emit(wL):A==="DISCONNECTED"&&this.emit(UoA)}};Qi([iB({settings:{retries:1/0,timeout:2e3},onError(A,t){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(ri.addFailedEvent({key:521720,error:A}),this._isFirstConnect=!1),this.room.firewallDetector.increaseTimeoutCount(),t())},onRetrying(A,t){this._log.warn("retrying to connect ".concat(A)),A>=3&&A%3==0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],E8.prototype,"connect");var gnA=dc(Xl()),d8=!1,am=class{constructor(A){Y(this,"userId"),Y(this,"tinyId"),Y(this,"_sdpSemantics"),Y(this,"_isUplink"),Y(this,"_room"),Y(this,"_log"),Y(this,"_signalChannel"),Y(this,"_isErrorObserved",!1),Y(this,"_waitForPeerConnectionConnectedPromise"),Y(this,"_waitForPeerConnectionConnectedPromiseReject",null),Y(this,"_peerConnection",null),Y(this,"_emitter",new gnA.default),Y(this,"_currentState","DISCONNECTED"),Y(this,"_isReconnecting",!1),Y(this,"_reconnectionCount",0),Y(this,"_reconnectionTimer",-1),Y(this,"_isFirstConnection",!0),Y(this,"_prevTime",-1),Y(this,"_localAddress"),Y(this,"_remoteAddress"),Y(this,"isDestoyed",!1),this.userId=A.userId,this.tinyId=A.tinyId,this._room=A.room,this._sdpSemantics=A.room.sdpSemantics,this._isUplink=A.isUplink,this._log=A.room.getLogger().createChild({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=A.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=Oo())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,ri.addSuccessEvent({key:521705,cost:Math.min(Oo()-this._prevTime,3e4)})):this._isReconnecting&&ri.addSuccessEvent({key:521706,cost:Oo()-this._prevTime}),this._prevTime=-1}catch(A){throw this._isFirstConnection?(this._isFirstConnection=!1,ri.addFailedEvent({key:521705,error:A})):this._isReconnecting&&this._reconnectionCount>=3&&ri.addFailedEvent({key:521706,error:A}),A}}initialize(){let A={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(A),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(A){this._log.info("close connection"),this._emitter.emit("closed",A),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection()}destroy(){this.isDestoyed=!0}closePeerConnection(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,A&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new li({code:mt.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Zh;let A=null;if(this._isUplink){if(!xI()||this._peerConnection.getSenders().length===0)return Zh;A=this._peerConnection.getSenders()[0].transport}else{if(!yy()||this._peerConnection.getReceivers().length===0)return Zh;A=this._peerConnection.getReceivers()[0].transport}return A?A.state:Zh}onConnectionStateChange(A){let t=this._peerConnection.iceConnectionState,o=this.getDTLSTransportState();if(this._log.info("connectionState: ".concat(A.target.connectionState,", ICE: ").concat(t,", DTLS: ").concat(o)),A.target.connectionState===mo.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),A.target.connectionState===mo.FAILED||A.target.connectionState===mo.CLOSED){let a="connection ".concat(A.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(o),l=new li({message:a,code:mt.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",l)}(A.target.connectionState===mo.CONNECTED||A.target.connectionState===mo.COMPLETED)&&(this.logSelectedCandidate(),ds.logSuccessEvent({userId:this._room.userId,eventType:Wa.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(A){return A!==this._currentState&&(A==="CONNECTED"&&(this._room.firewallDetector.resetTimeoutCount(),d8=!0),F.emit(rA.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:A,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:A}),this._currentState=A,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return XA(this,null,function*(){if(!this._peerConnection)return;let A=yield this._peerConnection.getStats();for(let[,t]of A)if(Ov(t)){let o=A.get(t.localCandidateId),a=A.get(t.remoteCandidateId);o&&(this._log.info("local candidate: ".concat(o.candidateType," ").concat(o.protocol,":").concat(o.ip||o.address,":").concat(o.port," ").concat(o.networkType||""," ").concat(o.candidateType==="relay"?"relayProtocol:".concat(o.relayProtocol):"")),this._localAddress="".concat(o.ip||o.address,":").concat(o.port)),a&&(this._log.info("remote candidate: ".concat(a.candidateType," ").concat(a.protocol,":").concat(a.ip||a.address,":").concat(a.port)),this._remoteAddress="".concat(a.protocol,":").concat(a.ip||a.address));break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise((A,t)=>{if(this._currentState==="CONNECTED")return A();this._waitForPeerConnectionConnectedPromiseReject=t;let o=h=>{h.state==="CONNECTED"&&(clearTimeout(d),l(),A())},a=h=>{let{room:y}=h;y===this._room&&(clearTimeout(d),l(),t(new li({code:mt.API_CALL_ABORTED,message:sn({key:Go.CONNECTION_ABORTED,data:"leave room"})})))},l=()=>{F.off(rA.LEAVE_SUCCESS,a,this),this._emitter.off("connection-state-changed",o,this)},d=setTimeout(()=>{l();let h=new li({code:mt.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),t(h)},Hb);F.on(rA.LEAVE_SUCCESS,a,this),this._emitter.on("connection-state-changed",o,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null})),this._waitForPeerConnectionConnectedPromise}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(wL,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=jf()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let A=new li({code:this._isUplink?mt.UPLINK_RECONNECTION_FAILED:mt.DOWNLINK_RECONNECTION_FAILED,message:sn({key:this._isUplink?Go.UPLINK_RECONNECTION_FAILED:Go.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",A),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this._reconnectionCount,"]")),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(wL,this.reconnect,this),-1)}on(A,t,o){this._emitter.on(A,t,o)}off(A,t,o){this._emitter.off(A,t,o)}getIsReconnecting(){return this._isReconnecting}get isH264(){var A,t;return!((t=(A=this._peerConnection)==null?void 0:A.remoteDescription)==null||!t.sdp.includes("H264"))}setOffer(A){var t;return(t=this._peerConnection)==null?void 0:t.setLocalDescription(A)}setAnswer(A){var t;return(t=this._peerConnection)==null?void 0:t.setRemoteDescription(A)}};Qi([wy(521712,!1)],am.prototype,"setOffer"),Qi([wy(521713,!1)],am.prototype,"setAnswer");var C8=dc(Tb()),Qc=function(A){return C8.default.parse(A)},by=function(A){return C8.default.write(A)};function Kj(A){return Object.keys(A).filter(t=>A[t])}var Y1=class SX extends am{constructor(t){super(So(Di({},t),{isUplink:!1})),Y(this,"_flag",0),Y(this,"isRobot",!1),Y(this,"role","anchor"),Y(this,"remoteAudioTrack"),Y(this,"remoteVideoTrack"),Y(this,"remoteAuxiliaryTrack"),Y(this,"avPlayerStateSyncManager"),Y(this,"ssrc",{audio:0,video:0,auxiliary:0}),Y(this,"_isSDPExchanging",!1),Y(this,"_videoCodec"),Y(this,"fromType"),this.flag=t.flag,this.isRobot=t.isRobot||!1,this.remoteAudioTrack=t.remoteAudioTrack||new y1(this._room,this),this.remoteVideoTrack=t.remoteVideoTrack||new fL(this._room,this),this.remoteAuxiliaryTrack=t.remoteAuxiliaryTrack||new fz(this._room,this),this.avPlayerStateSyncManager=new _j({log:this._log,audioPlayer:this.remoteAudioTrack.player,videoPlayer:this.remoteVideoTrack.player})}get videoCodec(){var t,o;let a=(o=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:o.sdp;return a?a.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(t){this._videoCodec=t}get subscribeState(){let t={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?t.smallVideo=!0:t.video=!0),this.remoteAudioTrack.isSubscribed&&(t.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(t.auxiliary=!0),t}get muteState(){return kp(this.flag,this.userId)}get flag(){return this._flag}set flag(t){var o,a,l;t!==this._flag&&(this._flag=t,(o=this.remoteAudioTrack)==null||o.onFlagChanged(),(a=this.remoteVideoTrack)==null||a.onFlagChanged(),(l=this.remoteAuxiliaryTrack)==null||l.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(t){return t===JA.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(t){super.close(t),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.avPlayerStateSyncManager.destroy(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(t){var o,a;let l=this._currentState,d=super.emitConnectionStateChangedEvent(t);return d&&l!==t&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:l,state:t}),(a=this.remoteAuxiliaryTrack)==null||a.emit("connection-state-changed",{prevState:l,state:t})),d}onTrack(t){let o=t.streams[0],{track:a}=t,l=o.id===hu?JA.MAIN:JA.AUXILIARY;this._log.debug("ontrack ".concat(l," ").concat(a.kind));let d=JA.AUDIO;a.kind===JA.VIDEO&&(d=l===JA.MAIN?JA.VIDEO:JA.AUXILIARY);let h=this.remoteAudioTrack;d===JA.VIDEO?h=this.remoteVideoTrack:d===JA.AUXILIARY&&(h=this.remoteAuxiliaryTrack),h.setInputMediaStreamTrack(a)}addRRTRLine(t){let o=t.split(`\r +CPU core: `).concat(navigator.hardwareConcurrency,", GPU: ").concat(qp());if(ng&&window.screen&&(window.screen.width||window.screen.height)){let y="".concat(window.screen.width,"x").concat(window.screen.height,"@").concat(window.devicePixelRatio);d+=", screen: ".concat(y)}let h=navigator.deviceMemory;h&&(d+=", minRAM: ".concat(h,"GB")),pA.info(d),pA.info("URL: ".concat(location.href).concat(((l=self.frameElement)==null?void 0:l.tagName)==="IFRAME"?" in iframe":"")),Tv().then(y=>{y&&pA.info(PC)})}})();let a=new Im(t,o||{});return ML.add(a),a.__v_skip=!0,a}get room(){return this._room}_listenEvents(){gd(this,this._room).add("peer-join",t=>{let{userId:o}=t;this.emit(Ao.REMOTE_USER_ENTER,{userId:o})}).add("peer-leave",t=>{let{userId:o,reason:a}=t;this.emit(Ao.REMOTE_USER_EXIT,{userId:o,reason:a})}).add("banned",t=>{mQ(!0),this._exitRoom().finally(()=>{this.emit(Ao.KICKED_OUT,{reason:t.reason})})}).add("error",t=>{this._exitRoom().finally(()=>{this.emit(Ao.ERROR,Lo.convertFrom(t))})}).add("signal-connection-state-changed",t=>{this.emit(Ao.CONNECTION_STATE_CHANGED,t)}).add("network-quality",t=>{this._networkQuality=t;let o=So(Di({},t),{uplinkRTT:Math.min(t.uplinkRTT,y0),downlinkRTT:Math.min(t.downlinkRTT,y0)});this.emit(Ao.NETWORK_QUALITY,o)}).add("remote-published",t=>{[t.remoteAudioTrack,t.remoteVideoTrack,t.remoteAuxiliaryTrack].forEach(o=>{gd(o,o).add("player-state-changed",a=>{let l=So(Di({},a),{userId:t.userId});o.kind===JA.VIDEO&&(l.streamType=iC(o.streamType)),this.emit(o.kind===JA.AUDIO?Ao.AUDIO_PLAY_STATE_CHANGED:Ao.VIDEO_PLAY_STATE_CHANGED,l)}).add("error",a=>{a.getCode()===mt.PLAY_NOT_ALLOWED&&this.emit(Ao.AUTOPLAY_FAILED,{userId:o.userId,mediaType:o.strMediaType,resume:()=>o.player.resume()})})})}).add("remote-unpublished",t=>{[t.remoteAudioTrack,t.remoteVideoTrack,t.remoteAuxiliaryTrack].forEach(o=>{Vs(o)})}).add("remote-publish-state-changed",t=>{let{prevMuteState:o,muteState:a}=t,{userId:l}=a,d=o.audioAvailable,h=o.videoAvailable,{audioAvailable:y,videoAvailable:S}=a;y||this._remoteAudioConfigMap.delete(l),S||this._removeRemoteVideoConfig(l,"main"),a.hasAuxiliary||this._removeRemoteVideoConfig(l,"sub"),h!==S&&(S?this._onVideoAvailable({userId:l,streamType:"main"}):this._onVideoUnavailable({userId:l,streamType:"main"}),this.emit(S?Ao.REMOTE_VIDEO_AVAILABLE:Ao.REMOTE_VIDEO_UNAVAILABLE,{userId:l,streamType:"main"})),d!==y&&(y?this._onAudioAvailable({userId:l}):this._onAudioUnavailable({userId:l,muteState:a}),this.emit(y?Ao.REMOTE_AUDIO_AVAILABLE:Ao.REMOTE_AUDIO_UNAVAILABLE,{userId:l})),o.hasAuxiliary!==a.hasAuxiliary&&(a.hasAuxiliary?this._onVideoAvailable({userId:l,streamType:"sub"}):this._onVideoUnavailable({userId:l,streamType:"sub"}),this.emit(a.hasAuxiliary?Ao.REMOTE_VIDEO_AVAILABLE:Ao.REMOTE_VIDEO_UNAVAILABLE,{userId:l,streamType:"sub"})),o.hasDatachannel!==a.hasDatachannel&&a.hasDatachannel&&this._onDataChannelAvailable()}).add("sei-message",t=>{this.emit(Ao.SEI_MESSAGE,So(Di({},t),{streamType:iC(t.streamType)}))}).add("firewall-restriction",()=>{this.emit(Ao.ERROR,new Lo({code:ko.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",t=>{var o,a,l,d,h,y,S;let L={2:"big",3:"small",7:"sub"},V={rtt:Math.min(t.msg_up_stream_info.msg_network_status.uint32_rtt||((o=t.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((a=this._networkQuality)==null?void 0:a.uplinkRTT)||((l=this._networkQuality)==null?void 0:l.downlinkRTT)||0,y0),upLoss:((d=this._networkQuality)==null?void 0:d.uplinkLoss)||0,downLoss:((h=this._networkQuality)==null?void 0:h.downlinkLoss)||0,bytesSent:t.bytes_sent||0,bytesReceived:t.bytes_received||0,localStatistics:{audio:{bitrate:(((y=t.msg_up_stream_info.msg_audio_status)==null?void 0:y.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((S=t.msg_up_stream_info.msg_audio_status)==null?void 0:S.uint32_audio_level)||0)/sd},video:t.msg_up_stream_info.msg_video_status.filter(H=>L[H.uint32_video_stream_type]).map(H=>({bitrate:(H.uint32_video_codec_bitrate||0)/1e3,width:H.uint32_video_width,height:H.uint32_video_height,frameRate:H.uint32_video_enc_fps,videoType:L[H.uint32_video_stream_type]}))},remoteStatistics:t.msg_down_stream_info.map(H=>({userId:H.msg_user_info.str_identifier,audio:{bitrate:(H.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(H.msg_audio_status.uint32_audio_level||0)/sd,point2pointDelay:(H.msg_audio_status.uint32_audio_p2p_delay||0)+(H.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:H.msg_audio_status.uint32_audio_cache_ms||0},video:H.msg_video_status.map(lA=>({bitrate:(lA.uint32_video_codec_bitrate||0)/1e3,width:lA.uint32_video_width,height:lA.uint32_video_height,frameRate:lA.uint32_video_dec_fps,videoType:L[lA.uint32_video_stream_type],point2pointDelay:(lA.uint32_video_p2p_delay||0)+(lA.uint32_video_cache_ms||0),jitterBufferDelay:lA.uint32_video_cache_ms||0,codec:lA.uint32_video_codec}))}))};this.emit(Ao.STATISTICS,V)}).add("custom-message",t=>{this.emit(Ao.CUSTOM_MESSAGE,t)}).add("layerData",t=>this.emit(Ao.LAYER_DATA,t)).add("first-video-frame",t=>{this.emit(Ao.FIRST_VIDEO_FRAME,So(Di({},t),{streamType:iC(t.streamType)}))}).add("audio-frame",t=>{this.emit(Ao.AUDIO_FRAME,t)}).add("data-channel-message",t=>{var o,a,l,d,h;let{data:y}=t;if(y.sender==="")return;let S={segmentId:(o=y.payload)==null?void 0:o.roundid,speakerUserId:y.sender,sourceText:(a=y.payload)==null?void 0:a.text,translationTexts:(l=y.payload)==null?void 0:l.translate_msg,timestamp:(d=y.payload)==null?void 0:d.start_utc_ms,isCompleted:(h=y.payload)==null?void 0:h.end,robotId:y.robotid};S.sourceText!==""&&this.emit(Ao.REALTIME_TRANSCRIBER_MESSAGE,S)}).add("asr-robot-peer-join",t=>{this.emit(Ao.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"started",roomId:this.room.roomId,transcriberRobotId:t.userId})}).add("asr-robot-peer-leave",t=>{this.emit(Ao.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"stopped",roomId:this.room.roomId,transcriberRobotId:t.userId})}),gd(this,Kc).add("audioInputAdded",t=>{this.emit(Ao.DEVICE_CHANGED,{type:"microphone",action:"add",device:t})}).add("audioInputRemoved",t=>{this.emit(Ao.DEVICE_CHANGED,{type:"microphone",action:"remove",device:t})}).add("videoInputAdded",t=>{this.emit(Ao.DEVICE_CHANGED,{type:"camera",action:"add",device:t})}).add("videoInputRemoved",t=>{this.emit(Ao.DEVICE_CHANGED,{type:"camera",action:"remove",device:t})}).add("audioOutputAdded",t=>XA(this,null,function*(){if(this.emit(Ao.DEVICE_CHANGED,{type:"speaker",action:"add",device:t}),iI&&iI.deviceId===f0){let o=(yield Zv()).find(a=>a.deviceId===f0);o&&iI.groupId!==o.groupId&&(iI=o,this.emit(Ao.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}))}})).add("audioOutputRemoved",t=>XA(this,null,function*(){this.emit(Ao.DEVICE_CHANGED,{type:"speaker",action:"remove",device:t});let o=(yield Zv())[0];if(!o||!iI||iI.groupId===o.groupId)return;let a=iI.deviceId===t.deviceId,l=iI.deviceId===f0&&iI.deviceId===o.deviceId;(a||l)&&(iI=o,this.emit(Ao.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}))})),gd(this,U1).add("permission-state-change",t=>{this.emit(Ao.PERMISSION_STATE_CHANGE,t)}),this.room.enableSEI&&this.on(Ao.SEI_MESSAGE,t=>{var o;let a=(o=this.room.remotePublishedUserMap.get(t.userId))==null?void 0:o.remoteVideoTrack;a&&a.updateAlphaRenderInfo(t)})}getNetworkTime(){return Vf()}use(t){let o,a;return"plugin"in t?(o=t.plugin,a=t.assetsPath):o=t,o.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(o,a)}_use(t,o){let a=this._plugins.get(t.Name);if(a)return this._log.warn("duplicate install plugin",t.Name),a;let l=new t(CoA.call(this,{TRTC:Im,room:this._room,assetsPath:o,errorModule:{RtcError:Lo,ErrorCode:ko,CoreErrorCode:mt,ErrorCodeDictionary:S1}}));return this._plugins.set(t.Name,l),l.__v_skip=!0,t.autoStart&&this.startPlugin(t.Name),l}enterRoom(t){return XA(this,null,function*(){var o,a;this.enterRoomParams=t;let{scene:l="rtc",enableAutoPlayDialog:d=!0,autoReceiveAudio:h=!0,autoReceiveVideo:y=!1}=t;t.proxy&&(this._room.setProxyServer(t.proxy),!Ws(t.proxy)&&t.proxy.turnServer&&((a=(o=this._room).setTurnServer)==null||a.call(o,t.proxy.turnServer,t.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=d,this._room.autoReceiveAudio=h,this._room.autoReceiveVideo=y,br(t.preferHW)&&(this._room.preferHW=t.preferHW),t.playoutDelay&&(this._room.playoutDelay=t.playoutDelay),t.jitterBufferDelay&&(this._room.jitterBufferDelay=t.jitterBufferDelay);let S={sdkAppId:t.sdkAppId,userId:t.userId,userSig:t.userSig,privateMapKey:t.privateMapKey||null,latencyLevel:t.latencyLevel,role:t.role==="audience"?21:20,roomId:t.roomId||0,strRoomId:t.strRoomId||"",businessInfo:t.businessInfo||null,streamId:null,userDefineRecordId:t.userDefineRecordId||null,enableDataChannel:this._plugins.has("RealtimeTranscriber"),frameWorkType:t.frameWorkType,component:t.component,language:t.language,priority:t.priority,useVp8:t.useVp8,useH265:t.useH265||!1,keepAlive:t.keepAlive};t.strRoomId&&!t.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(S,l,Im.frameWorkType),this._checkTrackToPublish(),A8.start()})}exitRoom(){return XA(this,null,function*(){return yield this._exitRoom()})}switchRoom(t){return XA(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(t)}catch(o){if(!(o instanceof Jx)||o.code!==mt.API_CALL_TIMEOUT&&o.code!==mt.SWITCH_ROOM_FAILED)throw o;this._log.warn("switchRoom ".concat(o.code===mt.API_CALL_TIMEOUT?"timeout":"failed",", fallback to exitRoom() and enterRoom()")),yield this._rejoinRoom(t)}else yield this._rejoinRoom(t)})}_rejoinRoom(t){return XA(this,null,function*(){yield this.exitRoom();let o=Di(Di({},this.enterRoomParams),t);yield this.enterRoom(o)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(t=>{this._stopRemoteAudio({userId:t}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(t=>{let o=t.includes("main")?"main":"sub",a=t.split("_".concat(o))[0];a&&this._stopRemoteVideo({userId:a,streamType:o}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),function(t){let o=v_.get(t);o&&(o.forEach(a=>clearTimeout(a)),v_.delete(t))}(this),this._room.remotePublishedUserMap.forEach(t=>{Vs(t.remoteAudioTrack),Vs(t.remoteVideoTrack),Vs(t.remoteAuxiliaryTrack)})}switchRole(t,o){return XA(this,null,function*(){o!=null&&o.privateMapKey&&(this._room.privateMapKey=o.privateMapKey),o!=null&&o.latencyLevel&&(this._room.latencyLevel=o.latencyLevel),yield this._room.switchRole(t),t==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(t=>{var o;return(o=t.destroy)==null?void 0:o.call(t)}),this._plugins.clear(),Vs(this),this.removeAllListeners(),this._room.destroy(),ML.delete(this),ML.size===0&&A8.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),F.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return XA(this,arguments,function(){var t=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0};return function*(){if(t._localAudioTrack)return void t._log.warn("local audio is already started");let{publish:a=!0,mute:l,muteKeepVolumeDetection:d,option:h}=o,y=new AM(t._room.audioManager),S={},L={muted:!0};h&&(ze(h.microphoneId)?ze(h.audioTrack)||(S.customSource=h.audioTrack):S.deviceId=h.microphoneId,h&&Ys(h.captureVolume)&&y.setCaptureVolume(h.captureVolume),ze(h.profile)||(Ws(h.profile)?Tp[h.profile]&&y.setProfile(Tp[h.profile]):y.setProfile(h.profile)),Ys(h.earMonitorVolume)&&(L.muted=!(h.earMonitorVolume>0),L.volume=h.earMonitorVolume),ze(h.echoCancellation)||(y.profile.echoCancellation=h.echoCancellation),ze(h.noiseSuppression)||(y.profile.noiseSuppression=h.noiseSuppression),ze(h.autoGainControl)||(y.profile.autoGainControl=h.autoGainControl),br(t._enableAutoSwitchWhenRecapturing)&&(y.enableAutoSwitchWhenRecapturing=t._enableAutoSwitchWhenRecapturing)),y.on("5",V=>{t.emit(Ao.ERROR,new Lo({code:ko.DEVICE_ERROR,extraCode:5309,messageParams:{error:V}}))}),y.on("2",V=>{t.emit(Ao.DEVICE_CHANGED,{type:"microphone",action:"active",device:V})}),y.on("4",V=>{let H;V.error&&(H=Lo.convertFrom(V.error)),t.emit(Ao.PUBLISH_STATE_CHANGED,So(Di({},V),{error:H}))}),y.on("6",()=>{}),t._listenOutputTrackChanged(y),t._speakerId&&y.setAudioOutput(t._speakerId),yield y.capture(S),ze(l)||y.setMute(l,d),gd(y,y).add("player-state-changed",V=>{t.emit(Ao.AUDIO_PLAY_STATE_CHANGED,So(Di({},V),{userId:""}))}),a&&t._room.isJoined&&t._room.publish(y).catch(()=>{}),t._localAudioTrack=y,t._room.capturedLocalMainAudioTrack=y,t._localAudioConfig=So(Di({},o),{publish:a}),yield t._updateAudioPlayOption({playOption:L,track:y}),F.emit("113",{userId:"",room:t.room})}()})}updateLocalAudio(t){return XA(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:o,mute:a,muteKeepVolumeDetection:l,option:d}=t,h={};d&&(d.microphoneId?yield this._localAudioTrack.switchDevice(d.microphoneId):ze(d.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(d.audioTrack)),ze(d.captureVolume)||this._localAudioTrack.setCaptureVolume(d.captureVolume),ze(d.earMonitorVolume)||(h.muted=!(d.earMonitorVolume>0),h.volume=d.earMonitorVolume),yield this._localAudioTrack.update3A(d)),this._room.isJoined&&!ze(o)&&(o&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!o&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),ze(a)||this._localAudioTrack.setMute(a,l),yield this._updateAudioPlayOption({playOption:h,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),$h(this._localAudioConfig,t)})}stopLocalAudio(){return XA(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),F.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),Vs(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,delete this._room.capturedLocalMainAudioTrack)})}startLocalVideo(){return XA(this,arguments,function(){var t=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0,view:null,capture:!0};return function*(){var a,l,d;if(t._localVideoTrack)return void t._log.warn("local video is already started");let{view:h,publish:y=!0,capture:S=!0,mute:L,option:V,forcePublish:H=!1}=o,lA=y||H,hA=S,MA=new QQ(t._room.videoManager),oe={},fe={};if(V&&(br(V.avoidCropping)&&(MA.avoidCropping=V.avoidCropping),V.cameraId?oe.deviceId=V.cameraId:ze(V.useFrontCamera)?ze(V.videoTrack)||(oe.customSource=V.videoTrack):oe.facingMode=V.useFrontCamera?JA.FACING_MODE_USER:JA.FACING_MODE_ENVIRONMENT,ze(V.retryWhenExactFailed)||(oe.retryWhenExactFailed=V.retryWhenExactFailed),V.qosPreference&&(oe.contentHint=v1(V.qosPreference)),ze(V.profile)||(Ws(V.profile)?FC[V.profile]&&MA.setProfile(FC[V.profile]):MA.setProfile(V.profile)),ze(V.fillMode)||(fe.objectFit=V.fillMode),ze(V.mirror)||(fe.mirror=V.mirror),ze(V.small)||(ze(V.smallMode)||(t._room.smallMode=V.smallMode),br(V.small)&&V.small===!1?MA.stopSmall():MA.updateSmallConfig(M1(V.small,!0))),ze(V.rotation)||MA.setRotation(V.rotation),br(t._enableAutoSwitchWhenRecapturing)&&(MA.enableAutoSwitchWhenRecapturing=t._enableAutoSwitchWhenRecapturing)),MA.once("first-video-frame",je=>{t.emit(Ao.FIRST_VIDEO_FRAME,So(Di({},je),{streamType:iC(je.streamType)}))}),MA.on("5",je=>{t.emit(Ao.ERROR,new Lo({code:ko.DEVICE_ERROR,extraCode:5308,messageParams:{error:je}}))}),MA.on("2",je=>{t.emit(Ao.DEVICE_CHANGED,{type:"camera",action:"active",device:je})}),MA.on("4",je=>{let _e;je.error&&(_e=Lo.convertFrom(je.error)),t.emit(Ao.PUBLISH_STATE_CHANGED,So(Di({},je),{error:_e}))}),MA.on("6",()=>{}),t._listenOutputTrackChanged(MA),oe.customSource&&Lp(oe.customSource)?(MA.setOutputMediaStreamTrack(oe.customSource),hA=!1):hA?yield MA.capture(oe):(a=MA.manager)==null||a.changeInput(MA),ze(L)||(yield MA.setMute(L)),gd(MA,MA).add("player-state-changed",je=>{t.emit(Ao.VIDEO_PLAY_STATE_CHANGED,So(Di({},je),{userId:"",streamType:"main"}))}).add("video-size-changed",je=>{t.emit(Ao.VIDEO_SIZE_CHANGED,So(Di({},je),{streamType:iC(je.streamType)}))}),lA){let je=t._localScreenTrack&&((l=t._localScreenConfig)==null?void 0:l.publish)&&t._localScreenConfig.streamType==="main";t._room.isJoined?!je||H?(t._room.publish(MA).catch(()=>{}),((d=t._localScreenConfig)==null?void 0:d.streamType)==="main"&&t._localScreenConfig&&(t._localScreenConfig.publish=!1)):(lA=!1,t._log.warn("main stream is already published, local video track will not publish")):je&&(lA=!1)}t._localVideoTrack=MA,t._room.capturedLocalMainVideoTrack=MA,t._localVideoConfig=So(Di({},o),{view:h,publish:lA,capture:hA}),yield t._updateVideoPlayOption({view:h,playOption:fe,track:MA})}()})}updateLocalVideo(t){return XA(this,null,function*(){var o,a,l,d,h,y,S;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:L,publish:V=!0,mute:H,capture:lA,option:hA,forcePublish:MA=!1}=t,oe=V||MA,fe=lA,je={};if(!this._localVideoConfig.capture&&Lp((o=this.localVideoTrack)==null?void 0:o.outMediaTrack)&&(hA!=null&&hA.cameraId||hA!=null&&hA.videoTrack)&&this._localVideoTrack.outMediaTrack!==hA?.videoTrack&&(fe=!0),this._localVideoConfig.capture)fe!==!1?hA!=null&&hA.cameraId?yield this._localVideoTrack.switchDevice(hA?.cameraId):ze(hA?.useFrontCamera)?ze(hA?.videoTrack)||(Lp(hA?.videoTrack)?hA?.videoTrack!==((a=this.localVideoTrack)==null?void 0:a.outMediaTrack)&&(yield this._localVideoTrack.setOutputMediaStreamTrack(hA?.videoTrack)):yield this._localVideoTrack.setInputMediaStreamTrack(hA?.videoTrack)):yield this._localVideoTrack.switchDevice(hA!=null&&hA.useFrontCamera?JA.FACING_MODE_USER:JA.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(fe){let _e={};_e.deviceId=hA?.cameraId||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),_e.facingMode=hA!=null&&hA.useFrontCamera||(d=this._localVideoConfig.option)!=null&&d.useFrontCamera?JA.FACING_MODE_USER:JA.FACING_MODE_ENVIRONMENT,_e.customSource=hA!=null&&hA.videoTrack||!_e.deviceId?(h=this._localVideoConfig.option)==null?void 0:h.videoTrack:void 0,yield this._localVideoTrack.capture(_e)}hA&&(ze(hA.profile)||(Ws(hA.profile)?FC[hA.profile]&&this._localVideoTrack.setProfile(FC[hA.profile]):this._localVideoTrack.setProfile(hA.profile),(!hA.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(hA.cameraId||hA.useFrontCamera?JA.FACING_MODE_USER:JA.FACING_MODE_ENVIRONMENT))&&(yield this._localVideoTrack.applyProfile())),ze(hA.fillMode)||(je.objectFit=hA.fillMode),ze(hA.mirror)||(je.mirror=hA.mirror),ze(hA.rotation)||this._localVideoTrack.setRotation(hA.rotation),hA.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(v1(hA.qosPreference)),ze(hA.small)||(br(hA.small)&&!hA.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(M1(hA.small,!0)))),this._room.isJoined&&ze(oe)&&this._localVideoConfig.publish&&fe&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((oe??this._localVideoConfig.publish)||MA?this._localScreenTrack&&((y=this._localScreenConfig)!=null&&y.publish)&&this._localScreenConfig.streamType==="main"&&!MA?(oe=!1,this._log.warn("main stream is already published, local video track will not publish")):(this._room.publish(this._localVideoTrack).catch(()=>{}),((S=this._localScreenConfig)==null?void 0:S.streamType)==="main"&&this._localScreenConfig&&(this._localScreenConfig.publish=!1)):this._room.unpublish(this._localVideoTrack).catch(()=>{})),ze(H)||(yield this._localVideoTrack.setMute(H)),yield this._updateVideoPlayOption({view:L,playOption:je,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),$h(this._localVideoConfig,So(Di({},t),{publish:oe,capture:fe}))})}stopLocalVideo(){return XA(this,null,function*(){var t;this._localVideoTrack&&(this._room.isJoined&&(t=this._localVideoConfig)!=null&&t.publish&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),Vs(this._localVideoTrack),this._localVideoTrack=null,delete this._room.capturedLocalMainVideoTrack,this._localVideoConfig=null)})}startScreenShare(){return XA(this,arguments,function(){var t=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0,view:null};return function*(){var a,l,d;if(t._localScreenTrack)return void t._log.warn("screen share is already started");let{view:h=null,publish:y=!0,muteSystemAudio:S,option:L}=o,V=y,H=new eM(t._room.videoManager);H.on("4",fe=>{let je;fe.error&&(je=Lo.convertFrom(fe.error)),t.emit(Ao.PUBLISH_STATE_CHANGED,So(Di({},fe),{error:je}))}),H.once("first-video-frame",fe=>{t.emit(Ao.FIRST_VIDEO_FRAME,So(Di({},fe),{streamType:iC(fe.streamType)}))}),t._listenOutputTrackChanged(H),o.streamType==="main"&&(H.mediaType=4);let lA=null,hA={},MA={};L&&(ze(L.profile)||(Ws(L.profile)?Ub[L.profile]&&H.setProfile(Ub[L.profile]):H.setProfile(L.profile)),L.systemAudio&&(hA.systemAudio=!0,hA.echoCancellation=L.echoCancellation,hA.noiseSuppression=L.noiseSuppression,hA.autoGainControl=L.autoGainControl),ze(L.fillMode)||(MA.objectFit=L.fillMode),L.videoTrack&&(hA.videoTrack=L.videoTrack),L.audioTrack&&(hA.audioTrack=L.audioTrack),L.captureElement&&(hA.captureElement=L.captureElement),L.preferDisplaySurface&&(hA.preferDisplaySurface=L.preferDisplaySurface),L.qosPreference&&(hA.contentHint=v1(L.qosPreference)));let oe=yield H.capture(hA);if(H.mediaTrack.addEventListener(JA.ENDED,()=>{t._stopScreenShare(),t.emit(Ao.SCREEN_SHARE_STOPPED)}),oe.getAudioTracks()[0]){lA=new Dj(t._room.audioManager);let fe=oe.getAudioTracks()[0];(a=o.option)!=null&&a.systemAudio&&!((l=o.option)!=null&&l.audioTrack)&&(lA.sourceTrack=fe),yield lA.setInputMediaStreamTrack(fe),br(S)&&lA.mediaTrack&&(lA.mediaTrack.enabled=!S),t._speakerId&&lA.setAudioOutput(t._speakerId)}if(gd(H,H).add("player-state-changed",fe=>{t.emit(Ao.VIDEO_PLAY_STATE_CHANGED,So(Di({},fe),{userId:"",streamType:"sub"}))}),V){let fe=t._localVideoTrack&&((d=t._localVideoConfig)==null?void 0:d.publish),je=!(o.streamType==="main"&&fe);t._room.isJoined?(je?t._room.publish(H).catch(()=>{}):(V=!1,t._log.warn("main stream is already published, screen share main will not publish")),lA&&(t._checkScreenAudioEchoCancellation(H,lA),t._room.publish(lA).catch(()=>{}))):je||(V=!1)}t._localScreenTrack=H,t._room.capturedLocalAuxVideoTrack=H,t._localScreenAudioTrack=lA,t._localScreenConfig=So(Di({},o),{view:h,publish:V}),yield t._updateVideoPlayOption({view:h,playOption:MA,track:H})}()})}updateScreenShare(t){return XA(this,null,function*(){var o,a;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:l,publish:d,muteSystemAudio:h,option:y}=t,S=d,L={};if(y){if(ze(y.fillMode)||(L.objectFit=y.fillMode),y.qosPreference){let V=v1(y.qosPreference);this._localScreenTrack.setContentHint(V)}y.videoTrack&&this._localScreenTrack.setInputMediaStreamTrack(y.videoTrack),y.audioTrack&&this._localScreenAudioTrack&&this._localScreenAudioTrack.setInputMediaStreamTrack(y.audioTrack)}if(this._room.isJoined&&!ze(S)){if(S&&!this._localScreenConfig.publish){let V=this._localVideoTrack&&((o=this._localVideoConfig)==null?void 0:o.publish);this._localScreenConfig.streamType==="main"&&V?(S=!1,this._log.warn("main stream is already published, screen share main will not publish")):this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})}if(this._localScreenConfig.publish&&!S){let V=[this._localScreenTrack];this._localScreenAudioTrack&&V.push(this._localScreenAudioTrack),V.forEach(H=>this._room.unpublish(H).catch(()=>{}))}}(a=this._localScreenAudioTrack)!=null&&a.mediaTrack&&br(h)&&(this._localScreenAudioTrack.mediaTrack.enabled=!h),yield this._updateVideoPlayOption({view:l,playOption:L,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),$h(this._localScreenConfig,So(Di({},t),{publish:S}))})}stopScreenShare(){return XA(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(t){return XA(this,null,function*(){let{view:o,userId:a,streamType:l,option:d}=t,h="".concat(a,"_").concat(l);if(this._remoteVideoConfigMap.has(h))return void this._log.warn("remote video has already started. userId:".concat(a,", streamType:").concat(l));let y=this._room.remotePublishedUserMap.get(a);if(!y)return;let S={},L=l==="main"?y.remoteVideoTrack:y.remoteAuxiliaryTrack,V=this._bindRemoteVideoTrackEvents(L);this._listenOutputTrackChanged(L),d&&(ze(d.fillMode)||(S.objectFit=d.fillMode),ze(d.mirror)||(S.mirror=d.mirror),ze(d.poster)||(S.poster=d.poster),S.canvasRender=d.canvasRender,l==="main"&&!ze(d.small)&&(!y.remoteVideoTrack.isSubscribing&&!y.remoteVideoTrack.isSubscribed&&y.remoteVideoTrack.setMediaType(d.small?8:4),this._room.changeType(d.small,L.user)),ze(d.draggable)||L.setDraggable(d.draggable)),S.isLiveStream=!!this._playbackQualityList.find(H=>H.userId===a&&H.streamType===l),yield this._room.subscribe(L),yield this._enableVideoDecodeFallback(L,l),yield this._updateVideoPlayOption({view:o,playOption:S,track:L}),this._emitTrackEvent(L),this._remoteVideoConfigMap.set(h,{config:t,handlers:V}),d&&!ze(d.receiveWhenViewVisible)&&this._observeView({remoteTrack:L,view:o,receiveWhenViewVisible:d.receiveWhenViewVisible,viewRoot:d?.viewRoot})})}updateRemoteVideo(t){return XA(this,null,function*(){var o,a;let{view:l,userId:d,streamType:h,option:y,mute:S}=t,L="".concat(d,"_").concat(h),V=this._remoteVideoConfigMap.get(L);if(!V||!this._room.remotePublishedUserMap.has(d))return;let H={};y&&(ze(y.fillMode)||(H.objectFit=y.fillMode),ze(y.mirror)||(H.mirror=y.mirror));let lA=null,hA=this._room.remotePublishedUserMap.get(d);if(h==="main"&&hA!=null&&hA.muteState.hasVideo&&(lA=hA.remoteVideoTrack),h==="sub"&&hA!=null&&hA.muteState.hasAuxiliary&&(lA=hA.remoteAuxiliaryTrack),!lA)return;let{config:MA}=V;h==="main"&&y&&!ze(y.small)&&this._room.changeType(y.small,lA.user),y&&!ze(y.draggable)&&lA.setDraggable(y.draggable),y&&(br(y.pictureInPicture)&&(y.pictureInPicture?yield lA.player.enterPictureInPicture():yield lA.player.exitPictureInPicture()),br(y.fullScreen)&&(y.fullScreen?yield lA.player.enterFullscreen():yield lA.player.exitFullscreen())),br(S)&&(lA.ignoreUpdatePlayingState=!0,S?(yield lA.player.pause(),yield this.room.unsubscribe(lA)):(yield this.room.subscribe(lA),yield lA.player.resume(!0))),yield this._updateVideoPlayOption({view:l,playOption:H,track:lA,prevConfig:MA}),$h(MA,t);let oe=ze(y?.receiveWhenViewVisible)?(o=MA.option)==null?void 0:o.receiveWhenViewVisible:y.receiveWhenViewVisible,fe=ze(l)?MA.view:l,je=ze(y?.viewRoot)?(a=MA.option)==null?void 0:a.viewRoot:y.viewRoot;this._observeView({remoteTrack:lA,view:fe,receiveWhenViewVisible:oe,viewRoot:je})})}stopRemoteVideo(t){return XA(this,null,function*(){return this._stopRemoteVideo(t)})}_stopRemoteVideo(t){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return XA(this,null,function*(){let a=[],l=this._room.remotePublishedUserMap.get(t.userId);if(l){let{muteState:d,remoteVideoTrack:h,remoteAuxiliaryTrack:y}=l;t.streamType==="main"&&(h.stop(),d.hasVideo&&a.push(h)),t.streamType==="sub"&&(y.stop(),d.hasAuxiliary&&a.push(y))}for(let d of a)o&&(delete d.ignoreUpdatePlayingState,yield this._room.unsubscribe(d),this._mediaTrackMap.delete(d.outMediaTrack));this._removeRemoteVideoConfig(t.userId,t.streamType)})}_removeRemoteVideoConfig(t,o){let a="".concat(t,"_").concat(o),l=this._remoteVideoConfigMap.get(a);if(l&&(l.observer&&l.observer.disconnect(),l.handlers)){let d=this._room.remotePublishedUserMap.get(t);if(d){let h=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack;this._unbindRemoteVideoTrackEvents(h,l.handlers)}}this._remoteVideoConfigMap.delete(a)}_bindRemoteVideoTrackEvents(t){let o={onEnterPIP:()=>XA(this,null,function*(){yield t.player.enterPIPPromise,this.emit(Ao.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:iC(t.streamType),userId:t.userId,isPictureInPicture:!0,pictureInPictureWindow:t.player.pipWindow})}),onLeavePIP:()=>{this.emit(Ao.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:iC(t.streamType),userId:t.userId,isPictureInPicture:!1})},onEnterFullScreen:()=>{this.emit(Ao.FULL_SCREEN_STATE_CHANGED,{streamType:iC(t.streamType),userId:t.userId,isFullScreen:!0})},onLeaveFullScreen:()=>{this.emit(Ao.FULL_SCREEN_STATE_CHANGED,{streamType:iC(t.streamType),userId:t.userId,isFullScreen:!1})},onDecodeFailed:()=>{this.emit(Ao.ERROR,new Lo({code:ko.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))},onVideoSizeChanged:a=>{this.emit(Ao.VIDEO_SIZE_CHANGED,So(Di({},a),{streamType:iC(a.streamType)}))}};return t.player.on(Mo.ENTER_PICTURE_IN_PICTURE,o.onEnterPIP),t.player.on(Mo.LEAVE_PICTURE_IN_PICTURE,o.onLeavePIP),t.player.on(Mo.ENTER_FULL_SCREEN,o.onEnterFullScreen),t.player.on(Mo.LEAVE_FULL_SCREEN,o.onLeaveFullScreen),t.on("decode-failed",o.onDecodeFailed),t.on("video-size-changed",o.onVideoSizeChanged),o}_unbindRemoteVideoTrackEvents(t,o){t.player.off(Mo.ENTER_PICTURE_IN_PICTURE,o.onEnterPIP),t.player.off(Mo.LEAVE_PICTURE_IN_PICTURE,o.onLeavePIP),t.player.off(Mo.ENTER_FULL_SCREEN,o.onEnterFullScreen),t.player.off(Mo.LEAVE_FULL_SCREEN,o.onLeaveFullScreen),t.off("decode-failed",o.onDecodeFailed),t.off("video-size-changed",o.onVideoSizeChanged)}muteRemoteAudio(t,o){return XA(this,null,function*(){this._remoteAudioMuteMap.set(t,o);try{if(t==="*")if(o)yield this._stopRemoteAudio({userId:t});else{let a=[...this._room.remotePublishedUserMap.values()];for(let l of a)l.muteState.hasAudio&&!this._remoteAudioConfigMap.has(l.userId)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:l.userId}))}else o?yield this._stopRemoteAudio({userId:t}):!this._remoteAudioConfigMap.has(t)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:t}))}catch(a){throw a.code!==ko.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(t),a}})}setRemoteAudioVolume(t,o){if(t==="*"){this._remoteAudioVolumeMap.set("*",o),this._remoteAudioVolumeMap.forEach((l,d)=>this._remoteAudioVolumeMap.set(d,o));let a=[...this._room.remotePublishedUserMap.values()];for(let l of a)this._remoteAudioVolumeMap.set(l.userId,o),l.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:o},track:l.remoteAudioTrack})}else if(t){let a=this._room.remotePublishedUserMap.get(t);this._remoteAudioVolumeMap.set(t,o),a&&a.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:o},track:a.remoteAudioTrack})}}startPlugin(t,o){return XA(this,null,function*(){return t.start(o)})}updatePlugin(t,o){return XA(this,null,function*(){return t.update(o)})}stopPlugin(t,o){return XA(this,null,function*(){return t.stop(o)})}enableAudioVolumeEvaluation(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3,o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this._room.enableAudioVolumeEvaluation(t,o)}on(t,o,a){if(this.listeners(t).includes(o))return this;if(this._log.debug("on",t),super.on(t,o,a),this._eventListened.add(t),this.listeners(Ao.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:l}=this.room.audioManager;l.get("")||l.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return t==="realtime-transcriber-message"&&this._room.subscribeDataChannel(),this}emit(t){for(var o=arguments.length,a=new Array(o>1?o-1:0),l=1;l{d?.abort("off")}),l.clear()}return this}getAudioTrack(){let t,o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userId:"",streamType:"main"},a=null,l="main",d=!1;if(Ws(o)?t=o:(t=o.userId,d=o.processed===!0,o.streamType&&(l=o.streamType)),t){let h=this._room.remotePublishedUserMap.get(t);h&&(a=h.remoteAudioTrack)}else a=l==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return a?d&&a.outMediaTrack&&a.outMediaTrack!==a.mediaTrack?a.outMediaTrack.clone():a.mediaTrack:null}getVideoTrack(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userId:"",streamType:"main"},{userId:o="",streamType:a="main",processed:l=!1}=t,d=null;if(o==="")a==="main"&&this._localVideoTrack&&(d=this._localVideoTrack),a==="sub"&&this._localScreenTrack&&(d=this._localScreenTrack);else{let h=this._room.remotePublishedUserMap.get(o);h&&(d=a==="main"?h.remoteVideoTrack:h.remoteAuxiliaryTrack)}return d?l&&d.outMediaTrack&&d.outMediaTrack!==d.mediaTrack?d.outMediaTrack.clone():d.mediaTrack:null}getVideoSnapshot(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{userId:o,streamType:a="main"}=t;if(o){let l=this._room.remotePublishedUserMap.get(o);if(a==="main"&&l!=null&&l.muteState.hasVideo)return l.remoteVideoTrack.getVideoFrame();if(a==="sub"&&l!=null&&l.muteState.hasAuxiliary)return l.remoteAuxiliaryTrack.getVideoFrame()}else{if(a==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(a==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(t){var o,a;this._speakerId=t,(o=this._localAudioTrack)==null||o.setAudioOutput(t),(a=this._localScreenAudioTrack)==null||a.setAudioOutput(t),this._room.remotePublishedUserMap.forEach(l=>l.remoteAudioTrack.setAudioOutput(t))}setCurrentSpeaker(t){return XA(this,null,function*(){(yield Zv()).forEach(o=>{o.deviceId===t&&(this._setCurrentSpeaker(t),this.emit(Ao.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),iI=o)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: '.concat(zh,"/en/TRTC.html#.setCurrentSpeaker"))})}_startRemoteAudio(t){return this._doStartRemoteAudio(t)}_doStartRemoteAudio(t){return XA(this,null,function*(){var o;let{userId:a}=t;if(this._remoteAudioConfigMap.has(a))return void this._log.warn("remote audio has already started. userId:".concat(a));let l=this._room.remotePublishedUserMap.get(a);if(!l)return;let d={},h=l.remoteAudioTrack;h.on("decode-failed",y=>{this.emit(Ao.ERROR,new Lo({code:ko.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(h),this._speakerId&&h.setAudioOutput(this._speakerId);try{let y=(o=this._remoteAudioVolumeMap.get(a))!=null?o:this._remoteAudioVolumeMap.get("*"),S=Ys(y)?y:100;d.volume=S,this._remoteAudioConfigMap.set(a,t),yield this._room.subscribe(h),Ma(Ea(h,"decode-failed"),CE(Ea(h,gs.INIT)),Dl(()=>{this.startPlugin(o8.Name,{track:h,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:d,track:h}),F.emit("115",{userId:a,room:this.room}),h.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:h.outMediaTrack,refId:"ra-".concat(a)})}catch(y){throw this._remoteAudioConfigMap.delete(a),y}this._emitTrackEvent(h)})}_stopRemoteAudio(t){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return XA(this,null,function*(){let a=this._room.remotePublishedUserMap.get(t.userId);a&&(a.remoteAudioTrack.stop(),a.muteState.hasAudio&&o&&(yield this._room.unsubscribe(a.remoteAudioTrack)),this._mediaTrackMap.delete(a.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(t.userId)),F.emit("116",{userId:t.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:"ra-".concat(t.userId)})})}_enableVideoDecodeFallback(t,o){let a,l=this._room.videoDecodeFallbackType;l&&this._plugins.has("TRTCVideoDecoder")&&(t.log.debug("remote video will fall back when decode failed",t.id),Ma(Ea(t,"decode-failed"),CE(Ea(t,gs.INIT)),hj(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:t,config:{codec:"avc1.420028"},fallback:l})}),Q1(Ea(t,"decode-downgrade-state-changed")),Dl(d=>{a=d.state,this.emit(Ao.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,So(Di({},d),{streamType:o,userId:t.userId}))},d=>{t.log.error("fallback",d)},()=>{a==="STARTED"&&t.log.info("fallback complete")})))}_updateVideoPlayOption(t){return XA(this,arguments,function(o){let{view:a,playOption:l,track:d,prevConfig:h}=o;return function*(){if(d.setMirror(l.mirror),ze(a)&&h&&h.view&&!b0(l)){let y=dv(h.view);y.length>0&&(yield d.play(y,l))}if(!ze(a)){let y=dv(a);y.length>0?yield d.play(y,l):d.stop()}}()})}_updateAudioPlayOption(t){return XA(this,arguments,function(o){var a=this;let{playOption:l={},track:d,prevConfig:h}=o;return function*(){if(!d.isPlayCalled)try{yield d.play(null,l)}catch{}if(ze(l.muted)||d.setPlayerMute(l.muted),ze(l.volume)||d.setAudioVolume(l.volume/100),d instanceof AM&&d.mediaTrack){let y=l.muted===!1&&!ze(l.volume)&&l.volume>0?"add":"remove";a.room.audioManager.updateAudioReference({type:y,audioReference:d.mediaTrack,refId:"em"})}else if(d instanceof y1){let y=l.muted?0:l.volume;if(ze(y))return;a.room.audioManager.updateAudioReference({type:"updateVolume",refId:"ra-".concat(d.userId),volume:l.volume})}}()})}_listenOutputTrackChanged(t){t.listeners("output-media-track-changed").length===0&&t.on("output-media-track-changed",()=>this._emitTrackEvent(t,!1))}_emitTrackEvent(t){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],a=t.isRemote?t.userId:"";t.outMediaTrack&&(o&&this._mediaTrackMap.get(t.outMediaTrack)===a||(this._mediaTrackMap.set(t.outMediaTrack,a),this.emit(Ao.TRACK,{userId:a,streamType:iC(t.streamType),track:t.outMediaTrack,sourceTrack:t.mediaTrack})))}_checkTrackToPublish(){var t,o,a;let l=[];if((t=this._localAudioConfig)!=null&&t.publish&&this._localAudioTrack&&l.push(this._localAudioTrack),(o=this._localVideoConfig)!=null&&o.publish&&this._localVideoTrack&&l.push(this._localVideoTrack),(a=this._localScreenConfig)!=null&&a.publish&&(this._localScreenTrack&&l.push(this._localScreenTrack),this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),l.length!==0)return Promise.all(l.map(d=>this._room.publish(d).catch(()=>{})))}_observeView(t){let{remoteTrack:o,view:a,receiveWhenViewVisible:l,viewRoot:d}=t;if(ze(a)||ze(l))return;let h=this._remoteVideoConfigMap.get("".concat(o.userId,"_").concat(iC(o.streamType)));if(!h)return;let y=h.observer||void 0;if(a===null||ka(a)&&a.length===0||!l)return y?.disconnect(),void(o.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",o.userId,o.strMediaType),this._room.subscribe(o).catch(()=>{})));let S=h.visibleViewMap||new Map,L=-1;(!y||y.root!==d)&&(y?.disconnect(),S.clear(),y=new IntersectionObserver(H=>{H.forEach(lA=>{S.set(lA.target,lA.isIntersecting),o.log.info("view ".concat(lA.target.id," is").concat(lA.isIntersecting?"":" not"," visible"))}),clearTimeout(L),L=window.setTimeout(()=>{[...S.values()].find(lA=>lA)?o.isSubscribed||this._room.subscribe(o).catch(()=>{}):o.isSubscribed&&this._room.unsubscribe(o).catch(()=>{})},200)},{root:d}));let V=new Set(dv(a));S.forEach((H,lA)=>{V.has(lA)||(y.unobserve(lA),S.delete(lA))}),V.forEach(H=>{S.set(H,!0),y.observe(H)}),y.takeRecords().forEach(H=>{S.set(H.target,H.isIntersecting)}),h.visibleViewMap=S,h.observer=y}_exitRoom(){return XA(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return XA(this,null,function*(){var t,o;if(this._localScreenTrack){if(this._room.isJoined){let a=[];(t=this._localScreenConfig)!=null&&t.publish&&a.push(this._localScreenTrack),this._localScreenAudioTrack&&a.push(this._localScreenAudioTrack),yield Promise.all(a.map(l=>this._room.unpublish(l).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((o=this._localScreenAudioTrack.trackSettings)==null?void 0:o.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),Vs(this._localScreenTrack),this._localScreenTrack=null,delete this._room.capturedLocalAuxVideoTrack,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(t,o){return XA(this,null,function*(){var a,l;if(!t||!o)return;let d=(a=t.trackSettings)==null?void 0:a.displaySurface;if(((l=o.trackSettings)==null?void 0:l.echoCancellation)===!1&&(d==="monitor"||d==="browser"&&t.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(h){this._log.warn("start audioProcessor plugin failed: ",h)}}})}_onLocalTrackCaptured(t){let{track:o}=t;o.kind==="audio"&&(!iI||cL(iI))&&(this._initActiveSpeaker(),F.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return XA(this,null,function*(){if(iI&&!cL(iI))this.emit(Ao.DEVICE_CHANGED,{type:"speaker",action:"active",device:iI});else{let t=yield Zv();t[0]&&!cL(t[0])?(iI=t[0],this.emit(Ao.DEVICE_CHANGED,{type:"speaker",action:"active",device:t[0]})):F.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable(t){let{userId:o}=t,a=this._remoteAudioMuteMap.has(o)?this._remoteAudioMuteMap.get(o):this._remoteAudioMuteMap.get("*");(a===!1||this._room.autoReceiveAudio&&!a)&&this._doStartRemoteAudio({userId:o}).catch(()=>{})}_onVideoAvailable(t){let{userId:o,streamType:a}=t;if(!this._room.autoReceiveVideo)return;let l=this._room.remotePublishedUserMap.get(o);if(l){let d=a==="main"?l.remoteVideoTrack:l.remoteAuxiliaryTrack,h=[d];this._room.autoReceiveAudio&&l.remoteAudioTrack.isAvailable&&h.push(l.remoteAudioTrack),this._room.subscribe(...h).then(()=>{this._emitTrackEvent(d)}).catch(()=>{})}}_onAudioUnavailable(t){let{userId:o,muteState:a}=t;a.hasAudio&&a.audioMuted||this._stopRemoteAudio({userId:o},!1).catch(()=>{})}_onVideoUnavailable(t){let{userId:o,streamType:a}=t;this._stopRemoteVideo({userId:o,streamType:a},!1).catch(()=>{})}_onDataChannelAvailable(){if(this.listeners("realtime-transcriber-message").length>0)return this._room.subscribeDataChannel()}sendSEIMessage(t,o){var a;let l=this._plugins.get("SEI");l&&(l.update({buffer:t,options:So(Di({seiPayloadType:243},o),{small:!((a=this._localVideoTrack)==null||!a.small)})}),ri.addCount({key:5e5,useUV:!0}))}sendCustomMessage(t){var o,a;(a=(o=this._room).sendCustomMessage)==null||a.call(o,t),ri.addCount({key:500001,useUV:!0})}callExperimentalAPI(t,o){return XA(this,null,function*(){return this._log.info("callExperimentalAPI(".concat(t,", ").concat(JSON.stringify(o),")")),_oA.call(t,Di({trtcInstance:this},o))})}static setLogLevel(t,o){pA.setLogLevel(t),ze(o)||(o?pA.enableUploadLog():pA.disableUploadLog())}static isSupported(){return Hk(Im.frameWorkType)}static getPermissions(t){return XA(this,arguments,function(o){let{request:a=!0,types:l=["camera","microphone"]}=o;return function*(){a&&(yield U1.request(l).catch(y=>{var S;return pA.error("getPermissions request failed, error: ".concat((S=y?.message)!=null?S:y))}));let[d,h]=yield Promise.all([U1.get("camera"),U1.get("microphone")]);return{camera:d,microphone:h}}()})}static getCameraList(){return nm(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getMicrophoneList(){return om(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getSpeakerList(){return Zv(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static setCurrentSpeaker(t){return XA(this,null,function*(){if(za&&(t===yL.SPEAKER||t===yL.HEADSET)){let o=yield Im.getMicrophoneList(),a="";return o.forEach(l=>{l.label===t&&(a=l.deviceId)}),a?void ML.forEach(l=>XA(null,null,function*(){l._localAudioTrack&&(yield l.updateLocalAudio({option:{microphoneId:a}}))})):void 0}(yield Zv()).forEach(o=>{o.deviceId===t&&(ML.forEach(a=>{a._setCurrentSpeaker(t),a.emit(Ao.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),iI=o)})})}static _addKVStat(t){let{type:o,key:a,value:l,base:d,useUV:h,version:y,max:S}=t;switch(y&&(eB.version=y),o){case"count":eB.addCount({key:a,useUV:h});break;case"enum":eB.addEnum({key:a,value:l,useUV:h});break;case"number":eB.addNumber({key:a,value:l,split:d,max:S})}}get localVideoTrack(){return this._localVideoTrack}get localScreenTrack(){return this._localScreenTrack}get localScreenAudioTrack(){return this._localScreenAudioTrack}};Y(bn,"VERSION",Xz),Y(bn,"_loggerManager",pA),Y(bn,"EVENT",Ao),Y(bn,"ERROR_CODE",ko),Y(bn,"TYPE",yL),Y(bn,"frameWorkType",30),Qi([Ra({replaceArg:A=>({argIndex:0,value:{name:"plugin"in A?A.plugin.Name:A.Name,assetsPath:"assetsPath"in A?A?.assetsPath:"default"}})})],bn.prototype,"use"),Qi([mu(tI.TRTC.enterRoom),oM("room",(A,t)=>{let[o]=A,[a]=t;return(o.roomId||o.strRoomId)===(a.roomId||a.strRoomId)&&o.userId===a.userId&&o.sdkAppId===a.sdkAppId}),Xr(A=>function(t){return this._log.setUserId(t.userId),this._log.setSdkAppId(t.sdkAppId),A.call(this,t)}),Ra()],bn.prototype,"enterRoom"),Qi([Ra()],bn.prototype,"exitRoom"),Qi([mu(tI.TRTC.switchRoom),Ra(),lL()],bn.prototype,"switchRoom"),Qi([mu(tI.TRTC.switchRole),S_("room",{merge:(A,t)=>t}),Ra()],bn.prototype,"switchRole"),Qi([Ra()],bn.prototype,"destroy"),Qi([mu(tI.TRTC.startLocalAudio),oM("audio",(A,t)=>{let[o]=A,[a]=t;var l,d;return((l=o?.option)==null?void 0:l.microphoneId)===((d=a?.option)==null?void 0:d.microphoneId)}),Ra()],bn.prototype,"startLocalAudio"),Qi([mu(tI.TRTC.updateLocalAudio),S_("audio",{debounce:{delay:200,getKey:()=>"".concat(n8,"-localAudio"),isNeedToDebounce:A=>{var t;return!ze((t=A.option)==null?void 0:t.captureVolume)}}}),Ra()],bn.prototype,"updateLocalAudio"),Qi([nM("audio"),Ra()],bn.prototype,"stopLocalAudio"),Qi([mu(tI.TRTC.startLocalVideo),oM("video",(A,t)=>{let[o]=A,[a]=t;var l,d;return((l=o?.option)==null?void 0:l.cameraId)===((d=a?.option)==null?void 0:d.cameraId)}),Ra()],bn.prototype,"startLocalVideo"),Qi([mu(tI.TRTC.updateLocalVideo),S_("video"),Ra()],bn.prototype,"updateLocalVideo"),Qi([nM("video"),Ra()],bn.prototype,"stopLocalVideo"),Qi([mu(tI.TRTC.startScreenShare),oM("screen",()=>!0),Ra()],bn.prototype,"startScreenShare"),Qi([mu(tI.TRTC.updateScreenShare),S_("screen"),Ra()],bn.prototype,"updateScreenShare"),Qi([Ra()],bn.prototype,"stopScreenShare"),Qi([mu(tI.TRTC.startRemoteVideo),oM(A=>"v".concat(A.userId).concat(A.streamType),()=>!0),Ra({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],bn.prototype,"startRemoteVideo"),Qi([mu(tI.TRTC.updateRemoteVideo),S_(A=>"v".concat(A.userId).concat(A.streamType)),Ra({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],bn.prototype,"updateRemoteVideo"),Qi([mu(tI.TRTC.stopRemoteVideo),Xr(A=>function(t){return XA(this,null,function*(){if(t.userId==="*"){let o=[];return this._room.remotePublishedUserMap.forEach(a=>{this._remoteVideoConfigMap.has("".concat(a.userId,"_main"))&&o.push(this.stopRemoteVideo({streamType:"main",userId:a.userId}).catch(()=>{})),this._remoteVideoConfigMap.has("".concat(a.userId,"_sub"))&&o.push(this.stopRemoteVideo({streamType:"sub",userId:a.userId}).catch(()=>{}))}),Promise.all(o)}return A.call(this,t)})}),Ra({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],bn.prototype,"stopRemoteVideo"),Qi([nM(A=>"v".concat(A.userId).concat(A.streamType))],bn.prototype,"_stopRemoteVideo"),Qi([mu(...tI.TRTC.muteRemoteAudio),Ra({getRemoteId:A=>A})],bn.prototype,"muteRemoteAudio"),Qi([$z(...tI.TRTC.setRemoteAudioVolume),function(A,t){return Xr((o,a)=>function(){for(var l=arguments.length,d=new Array(l),h=0;h{var H;(H=v_.get(this))==null||H.delete(S)},A);y.set(S,V)}else{clearTimeout(L);let V=window.setTimeout(()=>{var H;o.apply(this,d),(H=v_.get(this))==null||H.delete(S)},A);y.set(S,V)}})}(200,A=>A),Ra({getRemoteId:A=>A})],bn.prototype,"setRemoteAudioVolume"),Qi([Gj("start"),Xv(A=>{var t;return(t=A.afterStart)==null?void 0:t.call(A)}),oM((A,t)=>A.disableRandomCall?null:A.getAlias()+A.getGroup(t)),Ra({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>j2[A.getName()],ignoreLog:A=>A.getName()==="Debug",ignoreErrorLog:A=>A.getName()==="AudioProcessor"})],bn.prototype,"startPlugin"),Qi([Gj("update"),S_((A,t)=>A.disableRandomCall?null:A.getAlias()+A.getGroup(t),{merge:(A,t)=>($h(A[1],t[1]),A)}),Ra({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>py[A.getName()]})],bn.prototype,"updatePlugin"),Qi([Gj("stop"),nM((A,t)=>{if(A.disableRandomCall)return null;let o=A.getGroup(t),a=A.getAlias();return o==="*"?new RegExp("".concat(a,".*")):a+o}),Ra({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>r_[A.getName()]})],bn.prototype,"stopPlugin"),Qi([$z(...tI.TRTC.enableAudioVolumeEvaluation)],bn.prototype,"enableAudioVolumeEvaluation"),Qi([Ra()],bn.prototype,"getVideoSnapshot"),Qi([Ra()],bn.prototype,"_setCurrentSpeaker"),Qi([oM(A=>"a".concat(A.userId),()=>!0)],bn.prototype,"_startRemoteAudio"),Qi([Xr(A=>function(t){return XA(this,null,function*(){return t.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(So(Di({},t),{userId:o.userId})).catch(()=>{}))):A.call(this,t)})}),nM(A=>"a".concat(A.userId))],bn.prototype,"_stopRemoteAudio"),Qi([nM("room")],bn.prototype,"_exitRoom"),Qi([nM("screen")],bn.prototype,"_stopScreenShare"),Qi([mu(...tI.TRTC.sendSEIMessage),Dz({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var A=arguments.length,t=new Array(A),o=0;oA.data.byteLength})],bn.prototype,"sendCustomMessage"),Qi([Ra()],bn.prototype,"callExperimentalAPI"),Qi([sM()],bn,"create"),Qi([mu(tI.TRTC.create)],bn,"_create"),Qi([sM()],bn,"setLogLevel"),Qi([sM()],bn,"isSupported"),Qi([sM(),Ra()],bn,"getPermissions"),Qi([sM()],bn,"getCameraList"),Qi([sM()],bn,"getMicrophoneList"),Qi([sM()],bn,"getSpeakerList");var RL=bn,GoA=class{constructor(){Y(this,"_set",new Set),F.on(rA.LEAVE_SUCCESS,this.delete,this),F.on(rA.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add(A){let{room:t,roomId:o}=A;if(t.scene==="rtc")return;let a=this.getKey(t.userId,o||t.roomId,t.sdkAppId,t.useStringRoomId);this._set.add(a)}delete(A){let{room:t,roomId:o}=A;if(t.scene==="rtc")return;let a=this.getKey(t.userId,t.roomId||o,t.sdkAppId,t.useStringRoomId);this._set.delete(a)}getKey(A,t,o,a){return"".concat(o,"_").concat(t,"_").concat(A,"_").concat(a)}isJoined(A){let{userId:t,roomId:o,sdkAppId:a,room:l}=A;return l.scene!=="rtc"&&this._set.has(this.getKey(t,o,a,l.useStringRoomId))}handleSwitchRoomSuccess(A){let{room:t,currentRoomId:o,targetRoomId:a}=A;t.scene!=="rtc"&&(this._set.delete(this.getKey(t.userId,o,t.sdkAppId,t.useStringRoomId)),this._set.add(this.getKey(t.userId,a,t.sdkAppId,t.useStringRoomId)))}};function boA(){return XA(this,null,function*(){let A,t;try{let hA=yield om();A=hA&&hA.length}catch{}try{let hA=yield nm();t=hA&&hA.length}catch{}let o={microphone:A,camera:t},{isH264EncodeSupported:a,isVp8EncodeSupported:l,isH264DecodeSupported:d,isVp8DecodeSupported:h,isH265EncodeSupported:y,isH265DecodeSupported:S}=this.checkSystemResult.detail,L=ge.basis(),V={webRTC:L.isWebRTCSupported,getUserMedia:L.isGetUserMediaSupported,webSocket:L.isWebSocketsSupported,screenShare:L.isScreenShareSupported,webAudio:L.isWebAudioSupported,h264Encode:a,h264Decode:d,vp8Encode:l,vp8Decode:h,h265Encode:y,h265Decode:S},H={browser:L.browser,os:L.os,trtc:V,devices:o},lA={isWebCodecSupported:L.isWebCodecSupported,isMediaSessionSupported:L.isMediaSessionSupported,isWebTransportSupported:L.isWebTransportSupported};ds.uploadEvent({log:"trtcstats-".concat(JSON.stringify(H)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(H))),ds.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(lA)),userId:this.userId}),Hv()})}var koA=dc($l()),s8="1",Yj="2",wL="3",LoA="4",F1="5",UoA="6",O1="7",r8="8",nB={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},FoA=[nB.UPDATE_REMOTE_MUTE_STAT,nB.UPLINK_NETWORK_STATS,nB.USER_LIST_RES,nB.MUTE_RESULT,nB.SERVER_FIRST_PACKAGE_RECEIVED,nB.RECEIVE_CUSTOM_MSG,nB.UPDATE_NETWORK_TIME_RESULT],Qn={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},a8="publish_change",OoA="join",PoA="leave",xoA="quality_report",g8="mute_uplink",c8="publish",Vj="publish_state_change",P1="unpublish",l8="subscribe",Hj="unsubscribe",Jj="subscribe_change",YoA="start_publishing",VoA="stop_publishing",HoA="start_push_user_cdn",JoA="stop_push_user_cdn",qoA="start_mcu_mix",KoA="stop_mcu_mix",joA="start_publish_cdn_stream",WoA="update_publish_cdn_stream",zoA="stop_publish_cdn_stream",ZoA="get_user_list",XoA="change_role",qj="update_constraint_config",$oA="rebuild_pc",AnA="join/v2",I8="publish/v2",u8="subscribe/v3",enA="ability_status_report",tnA="reconnect",inA="channel_msg",onA="switch_room",nnA="update_network_time",snA=new Set([c8,a8,Vj,P1,l8,Jj,Hj,I8,u8]),x1=new Set,rnA=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],anA=0,E8=class extends koA.default{constructor(A){var t,o,a;super(),Y(this,"room"),Y(this,"sdkAppId"),Y(this,"userId"),Y(this,"userSig"),Y(this,"url"),Y(this,"backupUrl"),Y(this,"destroyed",!1),Y(this,"_socketInUse"),Y(this,"_socket"),Y(this,"_backupSocket"),Y(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0}),Y(this,"_currentState","DISCONNECTED"),Y(this,"_isReconnecting",!1),Y(this,"_seq",0),Y(this,"_log"),Y(this,"_lastMessageTime",-1),Y(this,"_connectStartTime",-1),Y(this,"_stopConnectRetry"),Y(this,"_isFirstConnect",!0),Y(this,"bytesSent",0),Y(this,"bytesReceived",0),Y(this,"keepAlive",!1),Y(this,"signalDomainWhenUnifiedProxy"),Y(this,"stopKeepAliveTimeout"),Y(this,"stopPrelinkTimeout"),Y(this,"rtt",0),Y(this,"prelink",!1),Y(this,"_prelinkConfig"),this.room=A.room,this.sdkAppId=A.sdkAppId,this.userId=A.userId,this.userSig=A.userSig,this.signalDomainWhenUnifiedProxy=A.signalDomainWhenUnifiedProxy,this.prelink=A.prelink||!1;let l=((o=(t=this.room.scheduleResult)==null?void 0:t.config)==null?void 0:o.keepAliveClient)||0;(a=this.room.joinParams)!=null&&a.keepAlive&&!l&&(l=1),l-x1.size>0&&this.room.enableSPC&&(this.keepAlive=!0,x1.add(this)),this.url=A.url,this.backupUrl=A.backupUrl,this._seq=0,this._log=pA.createLogger({parent:this.room.getLogger(),id:"ws".concat(++anA),userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let A="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));this.signalDomainWhenUnifiedProxy&&(A+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy))),this.prelink&&(A+="&prelink=1");let t=new URLSearchParams(location.search);return rnA.forEach(o=>{let a=t.get("trtc_".concat(o));a&&(A+="&".concat(o,"=").concat(encodeURIComponent(a)))}),this.race?"".concat(A,"&race=1"):A}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12e3}connect(){return XA(this,arguments,function(){var A=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1e4;return function*(){if(A.isConnected)return Promise.resolve();A._log.info("connect to [".concat(A.url,", ").concat(A.backupUrl,"] ").concat(A.race?"race":"").concat(t?" timeout: ".concat(t):""," keepAlive: ").concat(Number(A.keepAlive))),A.emitConnectionStateChanged("CONNECTING"),A._connectStartTime=Oo();let o=[A.connectWS({url:A._urlWithParam,isMain:!0,timeout:t})];A.race&&A._backupUrlWithParam!==A._urlWithParam&&o.push(A.connectWS({url:A._backupUrlWithParam,isMain:!1,timeout:t})),A._socketInUse=yield uv(o),A.unbindAndCloseSocket(A._socketInUse===A._socket?JA.BACKUP:JA.MAIN),A._isFirstConnect&&(ri.addSuccessEvent({key:521720}),A._isFirstConnect=!1),A.emitConnectionStateChanged("CONNECTED")}()})}connectWS(A){let{url:t,timeout:o,isMain:a}=A,l=new WebSocket(t);this.bindSocket(l),a?this._socket=l:this._backupSocket=l;let d=-1;return new Promise((h,y)=>{l.onclose=y,l.onerror=y,l.onopen=()=>h(l),o&&(d=setTimeout(()=>{this.unbindAndCloseSocket(a?JA.MAIN:JA.BACKUP),y(new li({code:mt.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},o))}).finally(()=>{l.onclose=null,l.onerror=null,l.onopen=null,clearTimeout(d)})}bindSocket(A){A.addEventListener("close",this.onclose),A.addEventListener("error",this.onerror),A.addEventListener("message",this.onmessage)}unbindSocket(A){A.removeEventListener("close",this.onclose),A.removeEventListener("error",this.onerror),A.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(A){if(A===JA.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch{}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch{}this._backupSocket=null}}onclose(A){A.target===this._socketInUse&&(this._log.warn("".concat(A.target===this._socket?"main":"backup"," is closed code:").concat(A.code," ").concat(A.reason)),this.emitConnectionStateChanged("DISCONNECTED"),(!A.wasClean||A.code!==1e3&&A.code!==4013)&&this.startReconnection(),this.prelink&&A.code===4013&&this.room.clearNetworkQuality(),this.room.isJoining&&this.emit(F1,new li({code:mt.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(A){this._log.error("".concat(A.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),A.target===this._socketInUse&&(this.unbindAndCloseSocket(JA.MAIN),this.unbindAndCloseSocket(JA.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(F1,new li({code:mt.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(A){if(!this.isConnected)return;let{isOnline:t}=this;this._lastMessageTime=Date.now(),t||this.emit(r8),this.bytesReceived+=L0(A.data);let o=JSON.parse(A.data),{cmd:a,data:l}=o,d=Object.values(nB),h=Object.keys(nB)[d.indexOf(a)],y=Qn[h]||a;switch(FoA.includes(a)||(this._log.debug("received ".concat(a," msg: ").concat(A.data)),y&&this._log.info("Received event: [ ".concat(y," ]"))),a){case nB.CHANNEL_SETUP_RESULT:if(o.code===0)this._signalInfo.clientIp=l.clientIp,this._signalInfo.signalIp=l.signalInnerIp,l.svrTime&&ZB(l.svrTime-new Date().getTime()),this._log.info("ChannelSetup Success ".concat(Oo()-this._connectStartTime)),ri.addSuccessEvent({key:521701,cost:Oo()-this._connectStartTime}),this._connectStartTime=-1,this.room.firewallDetector.resetTimeoutCount(),this.emit(s8,{signalInfo:this._signalInfo});else{let S=new li({code:mt.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:o.code,message:sn({key:Go.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:o.code,errorMsg:o.message}})});this._log.error("".concat(o.code,", ").concat(o.message)),this.close(),ri.addFailedEvent({key:521701,error:S}),this.emit(F1,S)}break;case nB.JOIN_ROOM_RESULT:o.code===0&&(this._signalInfo.relayIp=l.relayOuterIp,this._signalInfo.relayInnerIp=l.relayInnerIp,this._signalInfo.bakRelayIps=l.bakRelayIps,this._signalInfo.relayPort=l.relayPort,this._signalInfo.tinyId=o.tinyId,this._signalInfo.endReportExtend=l.endReportExtend,this._signalInfo.reportToken=l.reportToken,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(y,{data:o});break;default:this.emit(String(y),{data:o})}}reGetSignalChannelUrl(){return XA(this,null,function*(){try{if(!this.room.joinParams)return;mQ(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:A,backupUrl:t}=this.room.getSignalChannelUrl();this.url=A,this.backupUrl=t}catch{}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let A=this._socketInUse===this._socket;this.unbindAndCloseSocket(A?JA.MAIN:JA.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return XA(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:A,useStringRoomId:t}=this.room,{relayIp:o,relayInnerIp:a,relayPort:l}=this._signalInfo,{data:d}=yield this.sendWaitForResponse({command:tnA,data:{roomId:A,useStringRoomId:t,relayInnerIp:a,relayOuterIp:o,relayPort:l},responseCommand:Qn.CHANNEL_RECONNECT_RESULT});d.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),ri.addSuccessEvent({key:521702,cost:Oo()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(ri.addFailedEvent({key:521702,error:d.code}),this._log.warn("reconnect failed, ".concat(d.code," ").concat(d.message)),this.room.reJoin())}catch(A){this._log.error(A),this.room.reJoin()}}})}send(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let o={cmd:A,data:t,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},a=JSON.stringify(o);return this._socketInUse.send(a),snA.has(A)&&this._log.info("send",A,t),this.bytesSent+=L0(a),o.seq}}sendWaitForResponse(A){let{command:t,data:o,timeout:a=5e3,responseCommand:l,commandDesc:d,enableLog:h=!0,addReceiveTime:y=!1}=A;return new Promise((S,L)=>{let V=()=>{clearTimeout(H),L(new li({code:mt.API_CALL_ABORTED,message:"".concat(t," aborted due to connection closed")}))};this.once(O1,V);let H=setTimeout(()=>{this.off(l,lA),this.off(O1,V);let MA=new li({code:mt.API_CALL_TIMEOUT,message:sn({key:Go.API_CALL_TIMEOUT,data:{commandDesc:d,command:t}})});h&&this._log.warn(MA),L(MA)},a),lA=MA=>{MA.data.seq===hA&&(clearTimeout(H),this.off(l,lA),this.off(O1,V),y&&(MA.data.receiveTime=Date.now()),S(MA))};this.on(l,lA);let hA=this.send(t,o)})}sendWaitForResponseWithRetry(A){let{commandDesc:t,command:o,retries:a=0,retryTimeout:l=0}=A;return Bv({retryFunction:this.sendWaitForResponse,onError:d=>{let{retry:h,reject:y,error:S}=d;!this.room.isJoined||this.destroyed||S.code===mt.API_CALL_ABORTED?y(S):this.isOnline?h():(this._log.warn("retry ".concat(o," when connected")),this.once(r8,h))},onRetrying:d=>{this._log.warn("".concat(t||o," timeout observed, retrying [").concat(d,"/").concat(a,"]"))},settings:{retries:a,timeout:l},context:this})(A)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),clearTimeout(this.stopPrelinkTimeout),x1.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(JA.MAIN),this.unbindAndCloseSocket(JA.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(O1)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var A;let t=(A=this._signalInfo.bakRelayIps)==null?void 0:A.shift();return t&&(t.relayPort=t.relayPort||this._signalInfo.relayPort),t}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(A,"s")),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(A,"s")),this.close(),this.off(Qn.JOIN_ROOM_RESULT,t)},1e3*A);let t=o=>{o.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(Qn.JOIN_ROOM_RESULT,t))};this.on(Qn.JOIN_ROOM_RESULT,t)}}stopPrelinkIn(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:300;if(this.keepAlive)return;this._log.info("stopPrelink in ".concat(A,"s")),this.stopPrelinkTimeout=setTimeout(()=>{this._log.info("close prelink due to not used in ".concat(A,"s")),this.close(),this.room.clearNetworkQuality(),this.off(Qn.JOIN_ROOM_RESULT,t)},1e3*A);let t=o=>{o.data.code===0&&(this._log.info("stopPrelink clear timeout"),clearTimeout(this.stopPrelinkTimeout),this.off(Qn.JOIN_ROOM_RESULT,t))};this.on(Qn.JOIN_ROOM_RESULT,t)}markPrelinkConnected(A){this._prelinkConfig=So(Di({},A),{linkedTime:Date.now()})}isPrelinkValid(A,t,o){return!(!this.prelink||!this._prelinkConfig)&&(A!==this._prelinkConfig.sdkAppId||t!==this._prelinkConfig.userId||o!==this._prelinkConfig.userSig?(this._log.warn("prelink params not match"),!1):!!this.isConnected||(this._log.warn("prelink is not connected"),!1))}consumePrelink(){this.prelink=!1,this._prelinkConfig=void 0}emitConnectionStateChanged(A){if(A===this._currentState)return;this._log.info("".concat(this._currentState," -> ").concat(A));let t={prevState:this._currentState,state:A};A==="CONNECTING"&&(t.isReconnecting=this._isReconnecting),this.emit(Yj,t),this._currentState=A,A==="CONNECTED"?this.emit(wL):A==="DISCONNECTED"&&this.emit(UoA)}};Qi([iB({settings:{retries:1/0,timeout:2e3},onError(A,t){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(ri.addFailedEvent({key:521720,error:A}),this._isFirstConnect=!1),this.room.firewallDetector.increaseTimeoutCount(),t())},onRetrying(A,t){this._log.warn("retrying to connect ".concat(A)),A>=3&&A%3==0&&this.reGetSignalChannelUrl(),t&&(this._stopConnectRetry=t,(this.room.isDestroyed||this.destroyed)&&t())}})],E8.prototype,"connect");var gnA=dc($l()),d8=!1,am=class{constructor(A){Y(this,"userId"),Y(this,"tinyId"),Y(this,"_sdpSemantics"),Y(this,"_isUplink"),Y(this,"_room"),Y(this,"_log"),Y(this,"_signalChannel"),Y(this,"_isErrorObserved",!1),Y(this,"_waitForPeerConnectionConnectedPromise"),Y(this,"_waitForPeerConnectionConnectedPromiseReject",null),Y(this,"_peerConnection",null),Y(this,"_emitter",new gnA.default),Y(this,"_currentState","DISCONNECTED"),Y(this,"_isReconnecting",!1),Y(this,"_reconnectionCount",0),Y(this,"_reconnectionTimer",-1),Y(this,"_isFirstConnection",!0),Y(this,"_prevTime",-1),Y(this,"_localAddress"),Y(this,"_remoteAddress"),Y(this,"isDestoyed",!1),this.userId=A.userId,this.tinyId=A.tinyId,this._room=A.room,this._sdpSemantics=A.room.sdpSemantics,this._isUplink=A.isUplink,this._log=A.room.getLogger().createChild({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=A.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=Oo())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,ri.addSuccessEvent({key:521705,cost:Math.min(Oo()-this._prevTime,3e4)})):this._isReconnecting&&ri.addSuccessEvent({key:521706,cost:Oo()-this._prevTime}),this._prevTime=-1}catch(A){throw this._isFirstConnection?(this._isFirstConnection=!1,ri.addFailedEvent({key:521705,error:A})):this._isReconnecting&&this._reconnectionCount>=3&&ri.addFailedEvent({key:521706,error:A}),A}}initialize(){let A={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(A),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(A){this._log.info("close connection"),this._emitter.emit("closed",A),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection()}destroy(){this.isDestoyed=!0}closePeerConnection(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,A&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new li({code:mt.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Zh;let A=null;if(this._isUplink){if(!xI()||this._peerConnection.getSenders().length===0)return Zh;A=this._peerConnection.getSenders()[0].transport}else{if(!yy()||this._peerConnection.getReceivers().length===0)return Zh;A=this._peerConnection.getReceivers()[0].transport}return A?A.state:Zh}onConnectionStateChange(A){let t=this._peerConnection.iceConnectionState,o=this.getDTLSTransportState();if(this._log.info("connectionState: ".concat(A.target.connectionState,", ICE: ").concat(t,", DTLS: ").concat(o)),A.target.connectionState===mo.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),A.target.connectionState===mo.FAILED||A.target.connectionState===mo.CLOSED){let a="connection ".concat(A.target.connectionState,". ICE Transport state: ").concat(t,", DTLS Transport state: ").concat(o),l=new li({message:a,code:mt.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",l)}(A.target.connectionState===mo.CONNECTED||A.target.connectionState===mo.COMPLETED)&&(this.logSelectedCandidate(),ds.logSuccessEvent({userId:this._room.userId,eventType:Wa.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(A){return A!==this._currentState&&(A==="CONNECTED"&&(this._room.firewallDetector.resetTimeoutCount(),d8=!0),F.emit(rA.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:A,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:A}),this._currentState=A,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return XA(this,null,function*(){if(!this._peerConnection)return;let A=yield this._peerConnection.getStats();for(let[,t]of A)if(Ov(t)){let o=A.get(t.localCandidateId),a=A.get(t.remoteCandidateId);o&&(this._log.info("local candidate: ".concat(o.candidateType," ").concat(o.protocol,":").concat(o.ip||o.address,":").concat(o.port," ").concat(o.networkType||""," ").concat(o.candidateType==="relay"?"relayProtocol:".concat(o.relayProtocol):"")),this._localAddress="".concat(o.ip||o.address,":").concat(o.port)),a&&(this._log.info("remote candidate: ".concat(a.candidateType," ").concat(a.protocol,":").concat(a.ip||a.address,":").concat(a.port)),this._remoteAddress="".concat(a.protocol,":").concat(a.ip||a.address));break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise((A,t)=>{if(this._currentState==="CONNECTED")return A();this._waitForPeerConnectionConnectedPromiseReject=t;let o=h=>{h.state==="CONNECTED"&&(clearTimeout(d),l(),A())},a=h=>{let{room:y}=h;y===this._room&&(clearTimeout(d),l(),t(new li({code:mt.API_CALL_ABORTED,message:sn({key:Go.CONNECTION_ABORTED,data:"leave room"})})))},l=()=>{F.off(rA.LEAVE_SUCCESS,a,this),this._emitter.off("connection-state-changed",o,this)},d=setTimeout(()=>{l();let h=new li({code:mt.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),t(h)},Hb);F.on(rA.LEAVE_SUCCESS,a,this),this._emitter.on("connection-state-changed",o,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null})),this._waitForPeerConnectionConnectedPromise}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(wL,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=jf()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let A=new li({code:this._isUplink?mt.UPLINK_RECONNECTION_FAILED:mt.DOWNLINK_RECONNECTION_FAILED,message:sn({key:this._isUplink?Go.UPLINK_RECONNECTION_FAILED:Go.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",A),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this._reconnectionCount,"]")),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(wL,this.reconnect,this),-1)}on(A,t,o){this._emitter.on(A,t,o)}off(A,t,o){this._emitter.off(A,t,o)}getIsReconnecting(){return this._isReconnecting}get isH264(){var A,t;return!((t=(A=this._peerConnection)==null?void 0:A.remoteDescription)==null||!t.sdp.includes("H264"))}setOffer(A){var t;return(t=this._peerConnection)==null?void 0:t.setLocalDescription(A)}setAnswer(A){var t;return(t=this._peerConnection)==null?void 0:t.setRemoteDescription(A)}};Qi([wy(521712,!1)],am.prototype,"setOffer"),Qi([wy(521713,!1)],am.prototype,"setAnswer");var C8=dc(Tb()),Qc=function(A){return C8.default.parse(A)},by=function(A){return C8.default.write(A)};function Kj(A){return Object.keys(A).filter(t=>A[t])}var Y1=class SX extends am{constructor(t){super(So(Di({},t),{isUplink:!1})),Y(this,"_flag",0),Y(this,"isRobot",!1),Y(this,"role","anchor"),Y(this,"remoteAudioTrack"),Y(this,"remoteVideoTrack"),Y(this,"remoteAuxiliaryTrack"),Y(this,"avPlayerStateSyncManager"),Y(this,"ssrc",{audio:0,video:0,auxiliary:0}),Y(this,"_isSDPExchanging",!1),Y(this,"_videoCodec"),Y(this,"fromType"),this.flag=t.flag,this.isRobot=t.isRobot||!1,this.remoteAudioTrack=t.remoteAudioTrack||new y1(this._room,this),this.remoteVideoTrack=t.remoteVideoTrack||new fL(this._room,this),this.remoteAuxiliaryTrack=t.remoteAuxiliaryTrack||new fz(this._room,this),this.avPlayerStateSyncManager=new _j({log:this._log,audioPlayer:this.remoteAudioTrack.player,videoPlayer:this.remoteVideoTrack.player})}get videoCodec(){var t,o;let a=(o=(t=this._peerConnection)==null?void 0:t.remoteDescription)==null?void 0:o.sdp;return a?a.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(t){this._videoCodec=t}get subscribeState(){let t={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?t.smallVideo=!0:t.video=!0),this.remoteAudioTrack.isSubscribed&&(t.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(t.auxiliary=!0),t}get muteState(){return kp(this.flag,this.userId)}get flag(){return this._flag}set flag(t){var o,a,l;t!==this._flag&&(this._flag=t,(o=this.remoteAudioTrack)==null||o.onFlagChanged(),(a=this.remoteVideoTrack)==null||a.onFlagChanged(),(l=this.remoteAuxiliaryTrack)==null||l.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(t){return t===JA.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(t){super.close(t),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.avPlayerStateSyncManager.destroy(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(t){var o,a;let l=this._currentState,d=super.emitConnectionStateChangedEvent(t);return d&&l!==t&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:l,state:t}),(a=this.remoteAuxiliaryTrack)==null||a.emit("connection-state-changed",{prevState:l,state:t})),d}onTrack(t){let o=t.streams[0],{track:a}=t,l=o.id===hu?JA.MAIN:JA.AUXILIARY;this._log.debug("ontrack ".concat(l," ").concat(a.kind));let d=JA.AUDIO;a.kind===JA.VIDEO&&(d=l===JA.MAIN?JA.VIDEO:JA.AUXILIARY);let h=this.remoteAudioTrack;d===JA.VIDEO?h=this.remoteVideoTrack:d===JA.AUXILIARY&&(h=this.remoteAuxiliaryTrack),h.setInputMediaStreamTrack(a)}addRRTRLine(t){let o=t.split(`\r `),a=new Map;o.forEach((d,h)=>{/^a=rtcp-fb:/.test(d)&&o[h+1]&&!/^a=rtcp-fb:/.test(o[h+1])&&a.set(h+1,"".concat(d.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))});let l=[...a];for(let d=0;d{a.type===JA.VIDEO&&a.fmtp.forEach(l=>{l.config+=";sps-pps-idr-in-keyframe=1"})}),by(o)}removeSDESDescription(t){let o=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],a=Qc(t);return a.media.forEach(l=>{l.ext&&(l.ext=l.ext.filter(d=>!o.includes(d.uri)))}),by(a)}isSubscriptionStateNotChanged(t){return JSON.stringify(t)===JSON.stringify(this.subscribeState)}subscribe(t,o){return XA(this,null,function*(){var a,l;try{if((((a=this._peerConnection)==null?void 0:a.connectionState)===mo.NEW||((l=this._peerConnection)==null?void 0:l.connectionState)===mo.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(t))return void(this._peerConnection||(this.initialize(),yield this.connect(t)));if(this._log.info("subscribe ".concat(o," ").concat(JSON.stringify(t))),this._peerConnection||this._isSDPExchanging){let d="subscribe_change";Object.values(t).find(h=>h===!0)||(d="unsubscribe"),yield this.sendSubscription(d,t)}else this.initialize(),yield this.connect(t)}catch(d){throw this._room.isJoined&&this.isStreamUnpublished(o)?(this._log.warn("".concat(d.message," ").concat(JSON.stringify(this.muteState))),new li({code:mt.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):d}})}unsubscribe(t){return XA(this,arguments,function(o){var a=this;let{remoteTracks:l,streamType:d}=o;return function*(){if(a._currentState==="CONNECTED"&&(d==="main"&&!a.isMainStreamSubscribed||d==="auxiliary"&&!a.isAuxStreamSubscribed))return void a._log.info("".concat(d," stream already unsubscribed"));let h=Di({},a.subscribeState);l.forEach(S=>{switch(S.mediaType){case 1:h.audio=!1;break;case 4:h.video=!1;break;case 8:h.smallVideo=!1;break;case 2:h.auxiliary=!1}});let y="subscribe_change";Object.values(h).find(S=>S===!0)||(y="unsubscribe"),a._log.info("".concat(y==="unsubscribe"?y:"subscribe"," ").concat(d," [").concat(Kj(h),"]")),yield a.sendSubscription(y,h),y==="unsubscribe"&&(a.closePeerConnection(),a.emitConnectionStateChangedEvent("DISCONNECTED"))}()})}unsubscribeDataChannel(){return XA(this,null,function*(){})}sendSubscription(t){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscribeState,a={srcTinyId:this.tinyId,srcUserId:this.userId},l=Hj,d=Qn.UNSUBSCRIBE_RESULT;return t==="subscribe_change"&&(a={audio:o.audio,bigVideo:o.video,auxVideo:o.auxiliary,smallVideo:o.smallVideo,srcTinyId:this.tinyId},l=Jj,d=Qn.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:l,data:a,responseCommand:d,timeout:1e4}).then(h=>{let{data:y}=h;if(y.code!==0){let S=new li({code:y.code,message:sn({key:Go.ERROR_MESSAGE,data:{type:t,message:y.message}})});throw this._log.error(S),S}})}connect(){return XA(this,arguments,function(){var t=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.subscribeState;return function*(){try{yield t.exchangeSDP(o),yield t.waitForPeerConnectionConnected()}catch(a){throw t.closePeerConnection(!0),a}}()})}exchangeSDP(t){return XA(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:o,sdp:a}=this._peerConnection.localDescription,l={type:o,sdp:a,srcUserId:this.userId,srcTinyId:this.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo},d=yield this._signalChannel.sendWaitForResponse({command:l8,commandDesc:"exchange sdp",data:l,responseCommand:Qn.SUBSCRIBE_RESULT,timeout:r2});if(!this._peerConnection){let h=new li({code:mt.INVALID_OPERATION,message:sn({key:Go.CONNECTION_CLOSED})});throw this._log.warn(h),h}yield this.onSubscribeResult(d),this._isSDPExchanging=!1}catch(o){throw this._isSDPExchanging=!1,o}})}createOffer(){return XA(this,null,function*(){let t={voiceActivityDetection:!1};AC()&&this._sdpSemantics===nv?(this._peerConnection.addTransceiver(JA.AUDIO,{direction:ir.RECVONLY}),this._peerConnection.addTransceiver(JA.VIDEO,{direction:ir.RECVONLY}),this._peerConnection.addTransceiver(JA.VIDEO,{direction:ir.RECVONLY})):(t.offerToReceiveAudio=!0,t.offerToReceiveVideo=!0);let o=yield this._peerConnection.createOffer(t);if(o.sdp){let{isH264DecodeSupported:a}=yield Vk();a||(this._log.warn("remove h264 desc from sdp"),o.sdp=function(l){let d=Qc(l);return d.media.forEach(h=>{var y,S;if(h.type===JA.VIDEO){let L=new Set;h.rtp.forEach(H=>{let{payload:lA,codec:hA}=H;return hA==="H264"&&L.add(lA)}),h.fmtp.forEach(H=>{let{payload:lA,config:hA}=H,MA=hA.match(/apt=(\d+)/);MA&&MA[1]&&L.has(Number(MA[1]))&&L.add(lA)});let V=H=>{let{payload:lA}=H;return!L.has(lA)};h.rtp=h.rtp.filter(V),h.rtcpFb=(y=h.rtcpFb)==null?void 0:y.filter(V),h.fmtp=h.fmtp.filter(V),h.payloads=(S=h.payloads)==null?void 0:S.split(" ").filter(H=>!L.has(Number(H))).join(" ")}}),by(d)}(o.sdp)),o.sdp=this.addRRTRLine(o.sdp),o.sdp=this.addSPSDescription(o.sdp),o.sdp=function(l){let d=Qc(l);return d.media.forEach(h=>{h.type===JA.AUDIO&&h.fmtp.forEach(y=>{y.config+=";sprop-stereo=1;stereo=1"})}),by(d)}(o.sdp),this._sdpSemantics===nv&&(o.sdp=this.removeSDESDescription(o.sdp))}yield this.setOffer(o)})}onSubscribeResult(t){return XA(this,null,function*(){let{code:o,message:a=""}=t&&t.data||{},{type:l,sdp:d}=t&&t.data&&t.data.data||{};if(o===m0)throw new li({code:mt.NOT_SUPPORTED_H264,message:sn({key:Go.NOT_SUPPORTED_H264DECODE})});try{if(o!==0)throw new li({code:o,message:sn({key:Go.EXCHANGE_SDP_FAILED,data:{errMsg:a}})});this._log.debug("accept remote answer: ".concat(d)),yield this.setAnswer({type:l,sdp:d}),this.updateSSRC(d)}catch(h){throw this._log.error(h),h}})}updateSSRC(t){try{Qc(t).media.forEach(o=>{if(o.ssrcs)if(o.type===JA.AUDIO){let a=o.ssrcs.find(l=>{var d;return(d=l.value)==null?void 0:d.includes(hu)});a&&(this.ssrc.audio=Number(a.id))}else{let a=o.ssrcs.find(d=>{var h;return(h=d.value)==null?void 0:h.includes(hu)}),l=o.ssrcs.find(d=>{var h;return(h=d.value)==null?void 0:h.includes(t2)});a&&(this.ssrc.video=Number(a.id)),l&&(this.ssrc.auxiliary=Number(l.id))}})}catch{}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return XA(this,null,function*(){if(!(UI(SX.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch{let o=bp(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(o/1e3,"s")),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},o)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay(t){let{audioDelay:o,videoDelay:a}=t;this.remoteAudioTrack.stat.end2EndDelay=o,this.remoteVideoTrack.stat.end2EndDelay=a}get audioReceiver(){var t;return((t=this._peerConnection)==null?void 0:t.getReceivers()[0])||null}};Qi([Xr(A=>function(){for(var t=arguments.length,o=new Array(t),a=0;a{let h=y=>{this._emitter.off("closed",h),d(new li({code:mt.API_CALL_ABORTED,message:sn({key:Go.CONNECTION_ABORTED,data:y})}))};this._emitter.on("closed",h),A.apply(this,o).then(l,d).finally(()=>{this._emitter.off("closed",h)})})})],Y1.prototype,"subscribe"),Qi([wy(521717,!1)],Y1.prototype,"unsubscribe"),Qi([Xv(am.prototype.afterConnect),Y5(am.prototype.beforeConnect)],Y1.prototype,"connect");var h8=Y1,B8={voiceActivityDetection:!1},V1=class vX extends am{constructor(t){super(So(Di({},t),{isUplink:!0})),Y(this,"localMainAudioTrack",null),Y(this,"localMainVideoTrack",null),Y(this,"localAuxAudioTrack",null),Y(this,"localAuxVideoTrack",null),Y(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),Y(this,"_isPublishingAux",!1),Y(this,"_publishingLocalAudioTrack"),Y(this,"_publishingLocalVideoTrack"),Y(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),Y(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(t){super.close(t),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(t,o){var a,l,d;let h=this._currentState,y=super.emitConnectionStateChangedEvent(t);return y&&h!==t&&(o?o.emit("connection-state-changed",{prevState:h,state:t}):((a=this.localMainVideoTrack)==null||a.emit("connection-state-changed",{prevState:h,state:t}),(l=this.localAuxVideoTrack)==null||l.emit("connection-state-changed",{prevState:h,state:t}),(d=this._publishingLocalVideoTrack)==null||d.emit("connection-state-changed",{prevState:h,state:t}))),y}publish(t){return XA(this,arguments,function(o){var a=this;let{localAudioTrack:l,localVideoTrack:d,isAuxiliary:h}=o;return function*(){let y;a._peerConnection||a.initialize(),l&&(a._publishingLocalAudioTrack=l),d&&(a._publishingLocalVideoTrack=d),a._isPublishingAux=h,d&&!h&&d.small&&(y=a._room.videoManager.smallTrack),a.sendMediaSettings(),AC()?yield a.publishByTransceiver({localAudioTrack:l,localVideoTrack:d,smallTrack:y,isAuxiliary:h}):yield a.publishByAddTrack({localAudioTrack:l,localVideoTrack:d,smallTrack:y}),a._publishingLocalAudioTrack=null,a._publishingLocalVideoTrack=null,a._isPublishingAux=!1,h?(d&&(a.localAuxVideoTrack=d),l&&(a.localAuxAudioTrack=l)):(d&&(a.localMainVideoTrack=d),l&&(a.localMainAudioTrack=l)),a.installTrackMuteEvents(l,d),a.sendMutedFlag()}()})}publishByTransceiver(t){return XA(this,arguments,function(o){var a=this;let{localAudioTrack:l,localVideoTrack:d,smallTrack:h,isAuxiliary:y}=o;return function*(){a._log.info("publish by transceiver");let S=new MediaStream,L=d?.outMediaTrack,V=l?.outMediaTrack;V&&S.addTrack(V),L&&S.addTrack(L);let H=a._peerConnection.getTransceivers();if(H.length===0)a._peerConnection.addTransceiver(V||JA.AUDIO,{direction:ir.SENDONLY,streams:[S]}),a._peerConnection.addTransceiver(y?JA.VIDEO:L||JA.VIDEO,{direction:ir.SENDONLY,streams:[S]}),a._peerConnection.addTransceiver(h||JA.VIDEO,{direction:ir.SENDONLY,streams:[S]}),a._peerConnection.addTransceiver(y&&L||JA.VIDEO,{direction:ir.SENDONLY,streams:[S]}),yield a.connect();else{let lA=[];if(V&&(H[0].sender.track||lA.push(0),yield H[0].sender.replaceTrack(V),yield a.setBandwidth({bandwidth:l?.profile.bitrate||40,type:JA.AUDIO})),L){let hA=y?3:1;yield H[hA].sender.replaceTrack(L),yield a.setBandwidth({bandwidth:d.profile.bitrate,type:JA.VIDEO,videoType:y?JA.AUXILIARY:JA.BIG}),lA.push(hA),h&&(yield H[2].sender.replaceTrack(h),yield a.setBandwidth({bandwidth:d.small.bitrate,type:JA.VIDEO,videoType:JA.SMALL}),lA.push(2))}yield a.setTransceiverDirection(ir.SENDONLY,lA),yield a.doPublishChange(),d?.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),d?.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()})}publishByAddTrack(t){return XA(this,arguments,function(o){var a=this;let{localAudioTrack:l,localVideoTrack:d,smallTrack:h}=o;return function*(){a._log.info("publish by addtrack");let y=d?.outMediaTrack,S=l?.outMediaTrack;if(a._peerConnection&&a._peerConnection.connectionState!=="new")return l&&S&&(yield a.addTrack(l)),void(y&&(yield a.addTrack(d)));let L=new MediaStream;if(S&&L.addTrack(S),y&&L.addTrack(y),S&&a._peerConnection.addTrack(S,L),y&&(a._peerConnection.addTrack(y,L),h)){let V=new MediaStream;V.addTrack(h),a._peerConnection.addTrack(h,V)}yield a.connect()}()})}enableSmall(t){return XA(this,null,function*(){let o=this._peerConnection.getTransceivers();t?this._room.videoManager.smallTrack&&(yield o[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(ir.SENDONLY,[2])):(yield o[2].sender.replaceTrack(null),yield this.setTransceiverDirection(ir.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(){for(var t=arguments.length,o=new Array(t),a=0;a{l&&(l?.on("mute",this.sendMutedFlag,this),l?.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(){for(var t=arguments.length,o=new Array(t),a=0;a{l&&(l?.off("mute",this.sendMutedFlag,this),l?.off("unmute",this.sendMutedFlag,this))})}unpublish(t){return XA(this,arguments,function(o){var a=this;let{localAudioTrack:l,localVideoTrack:d}=o;return function*(){if(!CQ())return l&&l.outMediaTrack&&!d&&a.localMainVideoTrack?(yield a.removeTrack(l),void(a.localMainAudioTrack=null)):d&&d.outMediaTrack&&!l&&a.localMainAudioTrack?(yield a.removeTrack(d),void(a.localMainVideoTrack=null)):(yield a.doUnpublish(),a.uninstallTrackMuteEvents(l,d),void a.emitConnectionStateChangedEvent("DISCONNECTED",d));let h=d&&d===a.localAuxVideoTrack,y=d?.outMediaTrack,S=a._peerConnection.getSenders(),L=[];l&&(h?a.localAuxAudioTrack=null:a.localMainAudioTrack=null,!a.localAuxAudioTrack&&!a.localMainAudioTrack&&(yield S[0].replaceTrack(null),L.push(0))),y&&(h?(yield S[3].replaceTrack(null),a.localAuxVideoTrack=null,a._mediaSettings=So(Di({},a._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),L.push(3)):(yield S[1].replaceTrack(null),yield S[2].replaceTrack(null),a.localMainVideoTrack=null,a._mediaSettings=So(Di({},a._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),L.push(1,2))),a.isMainStreamPublished||a.isAuxStreamPublished?(yield a.setTransceiverDirection(ir.INACTIVE,L),yield a.doPublishChange(!1)):yield a.doUnpublish(),a.uninstallTrackMuteEvents(l,d),d?.emit("connection-state-changed",{prevState:a._currentState,state:"DISCONNECTED"})}()})}doPublishChange(){let t=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return XA(this,null,function*(){let o={state:this._room.publishState,constraintConfig:this._mediaSettings},a=yield this._signalChannel.sendWaitForResponse({command:Vj,data:o,responseCommand:Qn.PUBLISH_STATE_CHANGE_RESULT,enableLog:t});this.checkPublishResultCode(a.data.code,a.data.message)})}doUnpublish(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this._signalChannel.sendWaitForResponse({command:P1,commandDesc:"unpublish",responseCommand:Qn.UNPUBLISH_RESULT,enableLog:t}).catch(o=>{if(o.getCode()===mt.API_CALL_TIMEOUT)return Promise.resolve();throw o})}updateMediaSettings(){let{detail:{isH264EncodeSupported:t,isVp8EncodeSupported:o}}=this._room.checkSystemResult;t?this._mediaSettings.videoCodec="H264":o&&(this._mediaSettings.videoCodec="VP8");let a=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:l,localAuxVideoTrack:d}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?d=this._publishingLocalVideoTrack:l=this._publishingLocalVideoTrack),Dy){if(a&&a.outMediaTrack){let h=a.outMediaTrack.getSettings();this._mediaSettings.audioChannel=h.channelCount||1,this._mediaSettings.audioBps=1e3*a.profile.bitrate,this._mediaSettings.audioFs=h.sampleRate||0}if(l&&l.outMediaTrack){let h=l.outMediaTrack.getSettings();this._mediaSettings.videoWidth=h.width||0,this._mediaSettings.videoHeight=h.height||0,this._mediaSettings.videoFps=h.frameRate||0,this._mediaSettings.videoBps=1e3*l.profile.bitrate,l.small&&(this._mediaSettings.smallVideoWidth=l.small.width,this._mediaSettings.smallVideoHeight=l.small.height,this._mediaSettings.smallVideoFps=l.small.frameRate,this._mediaSettings.smallVideoBps=1e3*l.small.bitrate)}if(d&&d.outMediaTrack){let h=d.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=h.width||0,this._mediaSettings.auxVideoHeight=h.height||0,this._mediaSettings.auxVideoFps=h.frameRate||0,this._mediaSettings.auxVideoBps=1e3*d.profile.bitrate}}else a&&a.outMediaTrack&&(this._mediaSettings.audioChannel=a.profile.channelCount,this._mediaSettings.audioBps=1e3*a.profile.bitrate,this._mediaSettings.audioFs=a.profile.sampleRate),l&&l.outMediaTrack&&(this._mediaSettings.videoWidth=l.profile.width,this._mediaSettings.videoHeight=l.profile.height,this._mediaSettings.videoFps=l.profile.frameRate,this._mediaSettings.videoBps=1e3*l.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:qj,data:this._mediaSettings,responseCommand:Qn.UPDATE_CONSTRAINT_CONFIG_RES}).then(t=>{t.data.code!==0&&this._log.warn(t.data.message)}).catch(()=>{})}addTrack(t){return XA(this,null,function*(){if(!this._peerConnection)return;let o=t===this.localAuxAudioTrack||t===this.localAuxVideoTrack;this._log.info("is adding ".concat(t.kind," track to current published local ").concat(o?JA.AUXILIARY:JA.MAIN," stream")),AC()?yield this.addTrackByTransceiver(t,o):yield this.addTrackBySender(t)})}addTrackByTransceiver(t,o){return XA(this,null,function*(){var a;if(!t.mediaTrack)return;let l=this._peerConnection.getTransceivers();if(t.kind===JA.AUDIO)yield l[0].sender.replaceTrack(t.outMediaTrack);else{let d=o?3:1;yield l[d].sender.replaceTrack(t.outMediaTrack),d===1&&(a=this.localMainVideoTrack)!=null&&a.small&&(yield l[2].sender.replaceTrack(this._room.videoManager.smallTrack)),l[d].direction===ir.INACTIVE&&(yield this.setTransceiverDirection(ir.SENDONLY,[d]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(t){return XA(this,null,function*(){if(!t.outMediaTrack)return;let o=t.outMediaTrack;CQ()&&this._peerConnection.getTransceivers().findIndex(l=>l.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",o));let a=this._peerConnection.getSenders().find(l=>l.track&&l.track.kind===o.kind);if(a&&a.track){this._log.warn("sender already exists, remove sender first");let l=a.track;this.removeSender(a),yield this.updateOffer("remove",l)}if(o&&this._peerConnection.addTrack(o,new MediaStream([o])),o.kind===JA.VIDEO&&t instanceof QQ&&t.small){let l=new MediaStream,{smallTrack:d}=this._room.videoManager;l.addTrack(d),this._peerConnection.addTrack(d,l)}yield this.updateOffer("add",o)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===p0||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:t}=this._peerConnection.localDescription,o=Qc(t);for(let a=0;aa.sender&&a.sender.track===t.track)),this._peerConnection.removeTrack(t),o&&ba(o.stop)&&(this._log.info("stop transceiver"),o.stop())}removeTrack(t){return XA(this,null,function*(){if(!this._peerConnection)return;let o=t===this.localAuxAudioTrack||t===this.localAuxVideoTrack;this._log.info("is removing ".concat(t.kind," track from current published local ").concat(o?JA.AUXILIARY:JA.MAIN," stream")),AC()?yield this.removeTrackByTransceiver(t,o):yield this.removeTrackBySender(t)})}removeTrackByTransceiver(t,o){return XA(this,null,function*(){if(!t.outMediaTrack)return;let a=this._peerConnection.getTransceivers();if(t.kind===JA.AUDIO)yield a[0].sender.replaceTrack(null);else{let l=o?3:1;yield a[l].sender.replaceTrack(null),l===1&&t.small&&(yield a[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(ir.INACTIVE,[l])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(t,o){return XA(this,null,function*(){if(!gr)return;let a=!1,l=!1;this._log.info("setting transceiver ".concat(o.join(",")," direction to ").concat(t));let d=this._peerConnection.getTransceivers();if(o.forEach(S=>{d[S].direction!==t&&(d[S].direction=t,a=!0)}),a){this._log.info("updating offer");let S=yield this._peerConnection.createOffer();yield this.setOffer(S)}let h=-1,y=this._peerConnection.remoteDescription.sdp.split(`\r `).map(S=>{if(S.match(new RegExp("a=(".concat(ir.INACTIVE,"|").concat(ir.RECVONLY,"|").concat(ir.SENDONLY,")")))&&h++,o.includes(h)){if(t===ir.INACTIVE&&S.includes("a=".concat(ir.RECVONLY)))return l=!0,"a=".concat(t);if(t===ir.SENDONLY&&S.includes("a=".concat(ir.INACTIVE)))return l=!0,"a=".concat(ir.RECVONLY)}return S}).join(`\r @@ -320,7 +320,7 @@ CPU core: `).concat(navigator.hardwareConcurrency,", GPU: ").concat(qp());if(ng& `):y)),t}updateAudioBandwidthRestriction(t,o){let a="AS";return gr&&(a="TIAS",o*=1e3),t=t.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r c=IN $2\r b=`.concat(a,":").concat(o,`\r -`))}removeBandwidthRestriction(t){return t.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(t){return t.replace(/urn:3gpp:video-orientation/,"")}connect(){return XA(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),this.uninstallEvents(),t}})}exchangeSDP(){return XA(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(t){throw t}})}createOffer(){return XA(this,null,function*(){try{let t=yield this._peerConnection.createOffer(B8);yield this.setOffer(t),t.sdp&&this.updateSSRC(t.sdp)}catch(t){throw t}})}doExchangeSDP(){let t={command:c8,responseCommand:Qn.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof eM||this.localAuxVideoTrack instanceof eM,state:this._room.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(t.data.sdp)),this._signalChannel.sendWaitForResponse(t).then(o=>{let{code:a,message:l,data:d}=o.data;return a===0?this.acceptAnswer(d):this.checkPublishResultCode(a,l)})}setSDPDirection(t,o){let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"all",l=Qc(t);return l.media.forEach(d=>{(a==="all"||d.type===a)&&(d.direction=o)}),by(l)}acceptAnswer(t){return XA(this,null,function*(){var o,a,l,d,h;try{let y;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let L=((o=this._publishingLocalVideoTrack)==null?void 0:o.profile.bitrate)||((a=this.localMainVideoTrack)==null?void 0:a.profile.bitrate),V=((l=this._publishingLocalAudioTrack)==null?void 0:l.profile.bitrate)||((d=this.localMainAudioTrack)==null?void 0:d.profile.bitrate);if(L){let H=this._isPublishingAux?JA.AUXILIARY:JA.BIG;y=yield this.setBandwidth({bandwidth:L,type:JA.VIDEO,sdp:y,videoType:H})}V&&(y=yield this.setBandwidth({bandwidth:V,type:JA.AUDIO,sdp:y}))}if(y=this.removeVideoOrientation(t.sdp),(h=this._publishingLocalVideoTrack)!=null&&h.small){let{smallStreamConfig:L}=this._room;y=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||L.bitrate,type:JA.VIDEO,videoType:JA.SMALL,sdp:y})}let S={type:t.type,sdp:y};yield this.setAnswer(S),this._log.debug("accepted answer: ".concat(y))}catch(y){throw this._log.error("failed to accept remote answer ".concat(y)),y}})}sendMutedFlag(t){t===this.localAuxAudioTrack||t===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.send(g8,this._room.muteState))}getIsReconnecting(){return this._isReconnecting}reconnect(){return XA(this,null,function*(){if(!(UI(vX.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:P1,responseCommand:Qn.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch{let o=bp(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(o/1e3,"s")),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},o)}})}handleConnectionStateChange(t){t.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&F.emit(rA.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(t){try{Qc(t).media.forEach((o,a)=>{if(o.type===JA.AUDIO){let l=o.ssrcs&&o.ssrcs[0];l&&(this.ssrc.audio=Number(l.id))}else{if(this._sdpSemantics===p0&&o.ssrcGroups)return void o.ssrcGroups.forEach((d,h)=>{let y=Number(d.ssrcs.split(" ")[0]);h===0?this.ssrc.video=y:h===1&&(this.ssrc.small=y)});let l=o.ssrcs&&o.ssrcs[0];if(!l)return;switch(a){case 1:this.ssrc.video=Number(l.id);break;case 2:this.ssrc.small=Number(l.id);break;case 3:this.ssrc.auxiliary=Number(l.id)}}})}catch{}}getVideoTrackId(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:JA.VIDEO;if(this._peerConnection){let o=this._peerConnection.getSenders();if(t===JA.AUXILIARY&&o[3]&&o[3].track)return o[3].track.id;if(t===JA.VIDEO&&o[1]&&o[1].track)return o[1].track.id}if(this.localMainVideoTrack&&t===JA.VIDEO){let o=this.localMainVideoTrack.mediaTrack;if(o)return o.id}if(this.localAuxVideoTrack&&t===JA.AUXILIARY){let o=this.localAuxVideoTrack.mediaTrack;if(o)return o.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(t,o){if(t!==0)throw t===m0?(this._log.error(Cc.NOT_SUPPORTED_H264ENCODE),new li({code:mt.NOT_SUPPORTED_H264,message:sn({key:Go.NOT_SUPPORTED_H264ENCODE})})):new li({code:mt.UNKNOWN,message:sn({key:Go.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Qn.PUBLISH_RESULT,code:t,message:o}})})}};Qi([Xr(A=>function(){for(var t=arguments.length,o=new Array(t),a=0;a{let h=y=>{this._emitter.off("closed",h),d(new li({code:mt.API_CALL_ABORTED,message:sn({key:Go.CONNECTION_ABORTED,data:y})}))};this._emitter.on("closed",h),A.apply(this,o).then(l,d).finally(()=>{this._emitter.off("closed",h)})})})],V1.prototype,"publish"),Qi([wy(521715,!1)],V1.prototype,"unpublish"),Qi([Xv(am.prototype.afterConnect),Y5(am.prototype.beforeConnect)],V1.prototype,"connect");var H1=V1,cnA=class{constructor(A,t){this.room=A,Y(this,"_log"),Y(this,"_prevReportTime",0),Y(this,"_prevReport",{}),Y(this,"_prevStats",null),Y(this,"_prevEncoderImplementation",""),Y(this,"_prevAuxEncoderImpl",""),Y(this,"_prevQualityLimitationReason",""),Y(this,"_prevAuxQualityLimitationReason",""),Y(this,"_prevDecoderImplementationMap",new Map),Y(this,"_decodeMap",new Map),Y(this,"_prevQpSum",0),Y(this,"_prevAuxQpSum",0),Y(this,"totalBytesSent",0),Y(this,"totalBytesReceived",0),Y(this,"_spcStats",null),this._log=t}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(A){return XA(this,null,function*(){var t,o,a,l,d,h,y;let S={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},L=A.getPeerConnection(),V=A.getSSRC();if(L)try{if((this._spcStats||(yield L.getStats())).forEach(H=>{var lA,hA,MA,oe,fe,je,_e,vi,Fe,Dt,pi,Mi,Wo;let zo,vs;if(H.type==="outbound-rtp")if((H.mediaType||H.kind)===JA.VIDEO){if(H.ssrc===V.video?(zo=JA.VIDEO,vs=A.localMainVideoTrack):H.ssrc===V.small?zo=JA.SMALL:H.ssrc===V.auxiliary&&(vs=A.localAuxVideoTrack,zo=JA.AUXILIARY),!zo)return;S[zo].bytesSent=H.bytesSent,S[zo].packetsSent=H.packetsSent,S[zo].framesEncoded=H.framesEncoded,ze(H.keyFramesEncoded)||(S[zo].keyFramesEncoded=H.keyFramesEncoded),ze(H.nackCount)||(S[zo].nackCount=H.nackCount),ze(H.pliCount)||(S[zo].pliCount=H.pliCount),ze(H.retransmittedPacketsSent)||(S[zo].retransmittedPacketsSent=H.retransmittedPacketsSent),ze(H.totalEncodeTime)||(S[zo].totalEncodeTime=H.totalEncodeTime),ze(H.totalPacketSendDelay)||(S[zo].totalPacketSendDelay=H.totalPacketSendDelay);let Zo=0;if(!ze(H.qpSum)&&!ze(H.framesEncoded)&&H.framesEncoded>0){let Vn=H.qpSum,yg=H.framesEncoded,wa=zo===JA.VIDEO?this._prevQpSum:this._prevAuxQpSum,fu=zo===JA.VIDEO?((hA=(lA=A.localMainVideoTrack)==null?void 0:lA.stat)==null?void 0:hA.framesEncoded)||0:((oe=(MA=A.localAuxVideoTrack)==null?void 0:MA.stat)==null?void 0:oe.framesEncoded)||0;if(yg>fu&&Vn>wa){let _L=Vn-wa,__=yg-fu;Zo=Math.round(_L/__),Zo>35&&A.videoCodec==="h264"&&this._log.warn("".concat(zo===JA.AUXILIARY?"aux ":"","video encoder QP is high: ").concat(Zo,", resolution: ").concat(H.frameWidth,"x").concat(H.frameHeight,", codec: ").concat(A.videoCodec,", "))}zo===JA.VIDEO?this._prevQpSum=Vn:zo===JA.AUXILIARY&&(this._prevAuxQpSum=Vn)}if(!ze(H.encoderImplementation)&&(zo===JA.VIDEO&&this._prevEncoderImplementation!==H.encoderImplementation||zo===JA.AUXILIARY&&this._prevAuxEncoderImpl!==H.encoderImplementation)){let Vn=2,yg=this._prevEncoderImplementation;zo===JA.AUXILIARY&&(Vn=7,yg=this._prevAuxEncoderImpl),F.emit("262",{userId:A.userId,streamType:Vn,prevImplementation:yg,implementation:H.encoderImplementation,codec:A.videoCodec,isHWCodec:H.powerEfficientEncoder}),this[zo===JA.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=H.encoderImplementation,vs?.log.info("encoderImplementation change to ".concat(H.encoderImplementation,"(").concat(A.videoCodec,") HWEncoder: ").concat(H.powerEfficientEncoder))}H.ssrc===V.video?!ze(H.qualityLimitationReason)&&H.bytesSent!==0&&this._prevQualityLimitationReason!==H.qualityLimitationReason&&(vs?.log.info("qualityLimitationReason change to ".concat(H.qualityLimitationReason)),F.emit("263",{userId:A.userId,reason:H.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(fe=A.localMainVideoTrack)==null?void 0:fe.isQosClearFirst}),this._prevQualityLimitationReason=H.qualityLimitationReason):H.ssrc===V.auxiliary&&!ze(H.qualityLimitationReason)&&H.bytesSent!==0&&this._prevAuxQualityLimitationReason!==H.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(H.qualityLimitationReason)),F.emit("263",{userId:A.userId,reason:H.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(je=A.localAuxVideoTrack)==null?void 0:je.isQosClearFirst}),this._prevAuxQualityLimitationReason=H.qualityLimitationReason)}else S.audio.bytesSent=H.bytesSent,S.audio.packetsSent=H.packetsSent;else if(H.type==="candidate-pair")Ov(H)&&(this.totalBytesSent=H.bytesSent,Ys(H.currentRoundTripTime)&&(S.rtt=Math.floor(1e3*H.currentRoundTripTime)));else if(H.type==="media-source"){if(H.kind===JA.AUDIO)S.audio.audioLevel=H.audioLevel||0,S.audio.totalAudioEnergy=H.totalAudioEnergy||0,H.echoReturnLoss,ze((Fe=(vi=(_e=A.localMainAudioTrack)==null?void 0:_e.sourceTrack)==null?void 0:vi.stats)==null?void 0:Fe.deliveredFramesDuration)?H.totalSamplesDuration&&(S.audio.totalSamplesDuration=H.totalSamplesDuration):S.audio.totalSamplesDuration=A.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(H.kind===JA.VIDEO)if(H.trackIdentifier===A.getVideoTrackId(JA.VIDEO))if((Mi=(pi=(Dt=A.localMainVideoTrack)==null?void 0:Dt.sourceTrack)==null?void 0:pi.stats)!=null&&Mi.deliveredFrames){let{deliveredFrames:Zo}=A.localMainVideoTrack.sourceTrack.stats;S.video.framesCaptured=Zo,A.localMainVideoTrack.stat.framesCaptured&&A.localMainVideoTrack.stat.framesCaptured>0&&Zo>=A.localMainVideoTrack.stat.framesCaptured?S.video.fpsCapture=Math.floor((Zo-A.localMainVideoTrack.stat.framesCaptured)/this.statInterval):S.video.fpsCapture=H.framesPerSecond}else S.video.fpsCapture=H.framesPerSecond;else H.trackIdentifier===A.getVideoTrackId(JA.AUXILIARY)?S.auxiliary.fpsCapture=H.framesPerSecond:S.small.fpsCapture=H.framesPerSecond}if(!ze(H.audioLevel)&&(Wo=A.localMainAudioTrack)!=null&&Wo.mediaTrack&&H.trackIdentifier===A.localMainAudioTrack.mediaTrack.id&&(S.audio.audioLevel=H.audioLevel||0),!ze(H.frameWidth)){let Zo=JA.SMALL;H.trackIdentifier===A.getVideoTrackId(JA.VIDEO)||H.ssrc===V.video?Zo=JA.VIDEO:(H.trackIdentifier===A.getVideoTrackId(JA.AUXILIARY)||H.ssrc===V.auxiliary)&&(Zo=JA.AUXILIARY),S[Zo].frameWidth=H.frameWidth,S[Zo].frameHeight=H.frameHeight,S[Zo].framesSent=H.framesSent}}),A.localMainAudioTrack||A.getRoom().capturedLocalMainAudioTrack){let H=A.localMainAudioTrack||A.getRoom().capturedLocalMainAudioTrack;if(H){let lA=H.getInternalAudioLevel(),hA=H.getInternalAudioLevelAfter3A();S.audio.audioCaptureEnergyAfter3a=hA,S.audio.micAudioLevel=lA,S.audio.audioLevel===0&&A.localMainAudioTrack&&(S.audio.audioLevel=hA??lA),!A.localMainAudioTrack&&!ze((o=(t=H.sourceTrack)==null?void 0:t.stats)==null?void 0:o.deliveredFramesDuration)&&(S.audio.totalSamplesDuration=H.sourceTrack.stats.deliveredFramesDuration/1e3)}}if(!A.localMainVideoTrack&&A.getRoom().capturedLocalMainVideoTrack){let H=A.getRoom().capturedLocalMainVideoTrack;if((l=(a=H?.sourceTrack)==null?void 0:a.stats)!=null&&l.deliveredFrames){let{deliveredFrames:lA}=H.sourceTrack.stats;S.video.framesCaptured=lA,H.stat.framesCaptured&&H.stat.framesCaptured>0&&lA>=H.stat.framesCaptured&&(S.video.fpsCapture=Math.floor((lA-H.stat.framesCaptured)/this.statInterval)),H.stat.framesCaptured=lA}}if(!A.localAuxVideoTrack&&A.getRoom().capturedLocalAuxVideoTrack){let H=A.getRoom().capturedLocalAuxVideoTrack;if((h=(d=H?.sourceTrack)==null?void 0:d.stats)!=null&&h.deliveredFrames){let{deliveredFrames:lA}=H.sourceTrack.stats;S.auxiliary.framesCaptured=lA,H.stat.framesCaptured&&H.stat.framesCaptured>0&&lA>=H.stat.framesCaptured&&(S.auxiliary.fpsCapture=Math.floor((lA-H.stat.framesCaptured)/this.statInterval)),H.stat.framesCaptured=lA}}this.totalBytesSent||(this.totalBytesSent+=S.audio.bytesSent+S.video.bytesSent+S.auxiliary.bytesSent),Object.keys(S).forEach(H=>{H===JA.AUDIO?(A.localMainAudioTrack&&(A.localMainAudioTrack.stat=S[H]),A.localAuxAudioTrack&&(A.localAuxAudioTrack.stat=S[H])):H===JA.VIDEO?A.localMainVideoTrack&&(A.localMainVideoTrack.stat=S[H]):H===JA.AUXILIARY&&A.localAuxVideoTrack&&(A.localAuxVideoTrack.stat=S[H])})}catch(H){this._log.warn("failed to getStats on sender connection ".concat(H))}return S.rtt===0&&(S.rtt=((y=this.room.networkQuality)==null?void 0:y.uplinkRTT)||0),S})}getReceiverStats(A){return XA(this,null,function*(){var t,o,a;let l={tinyId:A.tinyId,userId:A.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,avSyncDelay:0,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""}},d=A.getPeerConnection();if(d)try{let{ssrc:h}=A,{muteState:y,subscribeState:S}=A;(this._spcStats||(yield d.getStats())).forEach(H=>{var lA,hA;if(H.type==="codec"&&this._decodeMap.set(H.id,H),H.type==="inbound-rtp"){let MA=(H.mediaType||H.kind)===JA.AUDIO;if(MA){if(H.ssrc!==h.audio||!y.hasAudio)return;l.audio.packetsReceived=H.packetsReceived,l.audio.bytesReceived=H.bytesReceived,l.audio.packetsLost=H.packetsLost,H.insertedSamplesForDeceleration&&(l.audio.insertedSamplesForDeceleration=H.insertedSamplesForDeceleration),H.removedSamplesForAcceleration&&(l.audio.removedSamplesForAcceleration=H.removedSamplesForAcceleration),H.totalSamplesDuration&&(l.audio.totalSamplesDuration=H.totalSamplesDuration),H.totalSamplesReceived&&(l.audio.totalSamplesReceived=H.totalSamplesReceived),H.concealedSamples&&(l.audio.concealedSamples=H.concealedSamples),H.silentConcealedSamples&&(l.audio.silentConcealedSamples=H.silentConcealedSamples);let{remoteAudioTrack:oe}=A;oe.stat.packetsReceived=H.packetsReceived,oe.stat.bytesReceived=H.bytesReceived,oe.stat.packetsLost=H.packetsLost,l.audio.p2pDelay=oe.stat.end2EndDelay,l.hasAudio=!0}else{if(gr&&H.bytesReceived===0)return;let oe;H.ssrc===h.video&&y.hasVideo&&(l.video.packetsReceived=H.packetsReceived,l.video.bytesReceived=H.bytesReceived,l.video.packetsLost=H.packetsLost,l.video.framesReceived=H.framesReceived,l.video.framesDecoded=H.framesDecoded,l.video.fpsDecoded=H.framesPerSecond,l.hasVideo=!0,A.videoCodec=fl[(lA=this._decodeMap.get(H.codecId))==null?void 0:lA.mimeType.split("/")[1]]||"h264",l.video.codec=A.videoCodec,oe=A.remoteVideoTrack,y.hasSmall&&S.smallVideo&&(l.isSmallSubscribed=!0),H.decoderImplementation&&(!this._prevDecoderImplementationMap.has(l.userId)||this._prevDecoderImplementationMap.get(l.userId)!==H.decoderImplementation)&&(oe.log.info("decoderImplementation change to ".concat(H.decoderImplementation,"(").concat(A.videoCodec,") HWDecoder: ").concat(H.powerEfficientDecoder)),F.emit("262",{userId:this.room.userId,remoteUserId:l.userId,prevImplementation:this._prevDecoderImplementationMap.get(l.userId),implementation:H.decoderImplementation,codec:A.videoCodec,isHWCodec:H.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(l.userId,H.decoderImplementation)),ze(H.keyFramesDecoded)||oe.updateKeyFramesDecoded(H.keyFramesDecoded)),H.ssrc===h.auxiliary&&y.hasAuxiliary&&(l.auxiliary.packetsReceived=H.packetsReceived,l.auxiliary.bytesReceived=H.bytesReceived,l.auxiliary.packetsLost=H.packetsLost,l.auxiliary.framesReceived=H.framesReceived,l.auxiliary.framesDecoded=H.framesDecoded,l.auxiliary.fpsDecoded=H.framesPerSecond,oe=A.remoteAuxiliaryTrack,l.auxiliary.p2pDelay=oe.stat.end2EndDelay,l.hasAuxiliary=!0,l.video.codec=((hA=this._decodeMap.get(H.codecId))==null?void 0:hA.mimeType.split("/")[1].toLowerCase())||"h264",ze(H.keyFramesDecoded)||oe.updateKeyFramesDecoded(H.keyFramesDecoded)),oe&&(oe.stat.packetsReceived=H.packetsReceived,oe.stat.bytesReceived=H.bytesReceived,oe.stat.packetsLost=H.packetsLost,oe.stat.framesReceived=H.framesReceived,oe.stat.framesDecoded=H.framesDecoded,H.jitterBufferDelay&&(oe.stat.jitterBufferDelay=Math.floor(H.jitterBufferDelay/H.jitterBufferEmittedCount*1e3)),l.video.p2pDelay=oe.stat.end2EndDelay)}H.jitterBufferDelay&&(MA?(l.audio.totalJitter=H.jitterBufferDelay,l.audio.totalJitterCount=H.jitterBufferEmittedCount,l.audio.estimatedPlayoutTimestamp=H.estimatedPlayoutTimestamp):H.ssrc===h.video&&y.hasVideo?(l.video.totalJitter=H.jitterBufferDelay,l.video.totalJitterCount=H.jitterBufferEmittedCount,l.video.estimatedPlayoutTimestamp=H.estimatedPlayoutTimestamp):H.ssrc===h.auxiliary&&y.hasAuxiliary&&(l.auxiliary.totalJitter=H.jitterBufferDelay,l.auxiliary.totalJitterCount=H.jitterBufferEmittedCount))}else H.type==="candidate-pair"&&Ov(H)&&(this.totalBytesReceived=H.bytesReceived,Ys(H.currentRoundTripTime)&&(l.rtt=Math.floor(1e3*H.currentRoundTripTime)));ze(H.frameWidth)||((H.trackIdentifier===A.getMainStreamVideoTrackId()||H.ssrc===h.video)&&(l.video.frameWidth=H.frameWidth,l.video.frameHeight=H.frameHeight,A.remoteVideoTrack.stat.frameWidth=H.frameWidth,A.remoteVideoTrack.stat.frameHeight=H.frameHeight),(H.trackIdentifier===A.getAuxStreamVideoTrackId()||H.ssrc===h.auxiliary)&&(l.auxiliary.frameWidth=H.frameWidth,l.auxiliary.frameHeight=H.frameHeight,A.remoteAuxiliaryTrack.stat.frameWidth=H.frameWidth,A.remoteAuxiliaryTrack.stat.frameHeight=H.frameHeight)),!ze(H.audioLevel)&&A.muteState.audioAvailable&&A.remoteAudioTrack.mediaTrack&&H.trackIdentifier===A.remoteAudioTrack.mediaTrack.id&&(l.audio.audioLevel=H.audioLevel||0,l.audio.totalAudioEnergy=H.totalAudioEnergy||0)}),l.audio.audioLevel===0&&A.muteState.audioAvailable&&(l.audio.audioLevel=A.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=l.audio.bytesReceived+l.video.bytesReceived+l.auxiliary.bytesReceived),ze((t=A.remoteVideoTrack.player.stat)==null?void 0:t.fps)||(l.video.fpsRender=A.remoteVideoTrack.player.stat.fps),ze((o=A.remoteAuxiliaryTrack.player.stat)==null?void 0:o.fps)||(l.auxiliary.fpsRender=A.remoteAuxiliaryTrack.player.stat.fps);let L=l.audio.estimatedPlayoutTimestamp,V=l.video.estimatedPlayoutTimestamp;if(L&&V&&A.remoteAudioTrack.isAvailable&&A.remoteVideoTrack.isAvailable){let H=V-L;Math.abs(H)<=1e4&&(l.avSyncDelay=H,Math.abs(H)>150&&this._log.warn("av sync delay",H))}}catch(h){this._log.warn("failed to getStats on receiver connection ".concat(h))}return l.rtt===0&&(l.rtt=((a=this.room.networkQuality)==null?void 0:a.uplinkRTT)||0),l})}getStats(A,t){return XA(this,null,function*(){let o,a={},l=[];if(this.room.singlePC){let d=this.room.singlePC.getPeerConnection();if(!d)return{senderStats:a,receiverStats:l};let h=Oo(),y=yield d.getStats(),S=Oo();S-h>2e3&&this._log.warn("getStats cost ".concat(S-h,"ms"));let L=[],V=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec","media-playout"]);y.forEach(H=>V.has(H.type)&&L.push(H)),this._spcStats=L}A&&(a=yield this.getSenderStats(A));for(let[d,h]of t){let y=yield this.getReceiverStats(h);y&&l.push(y)}return t.size&&(o=this.getMediaPlayoutStats(this._spcStats)),{senderStats:a,receiverStats:l,mediaPlayoutStats:o}})}getDifferenceValue(A,t){if(sm(A))return t;let o=t-A;return o<0?0:o}prepareReport(A){let{stats:t,report:o,freezeMap:a,uplinkConnection:l}=A;var d,h,y,S,L,V,H,lA,hA;if(!sm(t.senderStats)){let Fe={uint32_audio_level:t.senderStats.audio.audioLevel*sd,uint32_audio_energy:1e6*(t.senderStats.audio.totalAudioEnergy||0),uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(Fe.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*sd),ze(t.senderStats.audio.audioCaptureEnergyAfter3a)||(Fe.uint32_audio_capture_energy_after3a=t.senderStats.audio.audioCaptureEnergyAfter3a*sd),t.senderStats.audio.totalSamplesDuration&&(o.msg_device_info.uint32_audio_capture_cost=t.senderStats.audio.totalSamplesDuration);let Dt=[];if(t.senderStats.video.bytesSent){let Mi={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:1e3*(t.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};Dt.push(Mi)}if(t.senderStats.small.bytesSent){let Mi={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:1e3*(t.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};Dt.push(Mi)}if(t.senderStats.auxiliary.bytesSent){let Mi={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(t.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};Dt.push(Mi)}let pi={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};o.msg_up_stream_info={msg_audio_status:Fe,msg_video_status:Dt,msg_network_status:pi}}let{statInterval:MA}=this;o.msg_down_stream_info=[],t.receiverStats.forEach(Fe=>{let Dt={msg_user_info:{str_identifier:Fe.userId,uint64_tinyid:Fe.tinyId},msg_network_status:{uint32_rtt:Fe.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(Fe.hasAudio){let pi={uint32_audio_p2p_delay:Fe.audio.p2pDelay,uint32_audio_cache_ms:Fe.audio.totalJitter,uint32_audio_cache_ms_count:Fe.audio.totalJitterCount,uint32_audio_codec_bitrate:Fe.audio.bytesReceived,uint32_audio_total_bitrate:Fe.audio.bytesReceived,uint32_audio_level:1e8*Fe.audio.audioLevel,uint32_audio_energy:1e6*Fe.audio.totalAudioEnergy,uint32_audio_receive:Fe.audio.packetsReceived,uint32_audio_origin_lost:Fe.audio.packetsLost};Dt.msg_audio_status=pi}if(Fe.hasVideo){let pi=a.get("".concat(Fe.userId,"_").concat(h0)),Mi=pi?pi.duration:0,Wo={uint32_video_stream_type:Fe.isSmallSubscribed?3:2,uint32_video_receive_fps:Fe.video.framesReceived,uint32_video_width:Fe.video.frameWidth,uint32_video_height:Fe.video.frameHeight,uint32_video_codec_bitrate:Fe.video.bytesReceived,uint32_video_receive:Fe.video.packetsReceived,uint32_video_origin_lost:Fe.video.packetsLost,uint32_video_block_time:Mi,uint32_video_dec_fps:Fe.video.framesDecoded,uint32_video_codec_fps:Fe.video.fpsRender,uint32_video_cache_ms:Fe.video.totalJitter,uint32_video_cache_ms_count:Fe.video.totalJitterCount,uint32_video_p2p_delay:Fe.video.p2pDelay,uint32_video_codec:Fe.video.codec,int32_video_audio_relative_delay:Fe.avSyncDelay+5e3};Dt.msg_video_status.push(Wo)}if(Fe.hasAuxiliary){let pi=a.get("".concat(Fe.userId,"_").concat(Pb)),Mi=pi?pi.duration:0,Wo={uint32_video_stream_type:7,uint32_video_receive_fps:Fe.auxiliary.framesReceived,uint32_video_width:Fe.auxiliary.frameWidth,uint32_video_height:Fe.auxiliary.frameHeight,uint32_video_codec_bitrate:Fe.auxiliary.bytesReceived,uint32_video_receive:Fe.auxiliary.packetsReceived+Fe.auxiliary.packetsLost,uint32_video_origin_lost:Fe.auxiliary.packetsLost,uint32_video_block_time:Mi,uint32_video_dec_fps:Fe.auxiliary.framesDecoded,uint32_video_codec_fps:Fe.video.fpsRender,uint32_video_cache_ms:Fe.auxiliary.totalJitter,uint32_video_cache_ms_count:Fe.auxiliary.totalJitterCount,uint32_video_p2p_delay:Fe.auxiliary.p2pDelay,uint32_video_codec:Fe.video.codec};Dt.msg_video_status.push(Wo)}o.msg_down_stream_info.push(Dt)}),t.mediaPlayoutStats&&!sm(t.mediaPlayoutStats)&&(t.mediaPlayoutStats.synthesizedSamplesDuration*=1e3,t.mediaPlayoutStats.totalSamplesDuration*=1e3);let oe=this._prevReport,fe=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(o)),this._prevStats=JSON.parse(JSON.stringify(t)),o.msg_up_stream_info.msg_audio_status&&oe.msg_up_stream_info.msg_audio_status){let Fe=oe.msg_up_stream_info.msg_audio_status,Dt=o.msg_up_stream_info.msg_audio_status;if(Fe.uint32_audio_codec_bitrate===0)Dt.uint32_audio_codec_bitrate=0;else{let pi=this.getDifferenceValue(Fe.uint32_audio_codec_bitrate,Dt.uint32_audio_codec_bitrate);Dt.uint32_audio_codec_bitrate=Math.round(8*pi/MA),o.msg_up_stream_info.msg_network_status.uint32_bitrate+=Dt.uint32_audio_codec_bitrate}(d=oe.msg_device_info)!=null&&d.uint32_audio_capture_cost?(o.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(oe.msg_device_info.uint32_audio_capture_cost,o.msg_device_info.uint32_audio_capture_cost)/MA),o.msg_device_info.uint32_audio_capture_cost>0&&((y=l?.localMainAudioTrack)==null||y.updateAfter3aSilenceStartTime((h=t.senderStats.audio.audioCaptureEnergyAfter3a)!=null?h:t.senderStats.audio.micAudioLevel))):delete o.msg_device_info.uint32_audio_capture_cost}let je=oe.msg_up_stream_info.msg_video_status;o.msg_up_stream_info.msg_video_status.forEach(Fe=>{let Dt=je.find(vs=>vs.uint32_video_stream_type===Fe.uint32_video_stream_type);if(!Dt||Dt.uint32_video_codec_bitrate===0)return Fe.uint32_video_codec_bitrate=0,Fe.uint32_video_enc_fps=0,void(Fe.uint32_video_codec_fps=0);let pi=0,Mi=0,Wo=0;Dt&&Fe.uint32_video_codec_bitrate>=Dt.uint32_video_codec_bitrate&&(pi=Dt.uint32_video_codec_bitrate,Mi=Dt.uint32_video_enc_fps,Wo=Dt.uint32_video_codec_fps);let zo=this.getDifferenceValue(pi,Fe.uint32_video_codec_bitrate);Fe.uint32_video_codec_bitrate=Math.round(8*zo/MA),o.msg_up_stream_info.msg_network_status.uint32_bitrate+=Fe.uint32_video_codec_bitrate,Fe.uint32_video_enc_fps=Math.round(this.getDifferenceValue(Mi,Fe.uint32_video_enc_fps)/MA),Fe.uint32_video_codec_fps=Math.round(this.getDifferenceValue(Wo,Fe.uint32_video_codec_fps)/MA),Dt.uint32_video_width===0&&Dt.uint32_video_height===0&&Dt.uint32_video_codec_fps===0&&(Fe.uint32_video_codec_fps=Fe.uint32_video_enc_fps),ze(Dt.uint32_key_frame_count)||(Fe.uint32_key_frame_count=Math.round(this.getDifferenceValue(Dt.uint32_key_frame_count,Fe.uint32_key_frame_count))),ze(Dt.uint32_nack_count)||(Fe.uint32_nack_count=Math.round(this.getDifferenceValue(Dt.uint32_nack_count,Fe.uint32_nack_count))),ze(Dt.uint32_pli_count)||(Fe.uint32_pli_count=Math.round(this.getDifferenceValue(Dt.uint32_pli_count,Fe.uint32_pli_count))),ze(Dt.uint32_video_arq_packets)||(Fe.uint32_video_arq_packets=Math.round(this.getDifferenceValue(Dt.uint32_video_arq_packets,Fe.uint32_video_arq_packets))),ze(Dt.uint32_encode_cost)||(Fe.uint32_encode_cost=Math.round(this.getDifferenceValue(Dt.uint32_encode_cost,Fe.uint32_encode_cost)/MA)),ze(Dt.uint32_send_packet_cost)||(Fe.uint32_send_packet_cost=Math.round(this.getDifferenceValue(Dt.uint32_send_packet_cost,Fe.uint32_send_packet_cost)/MA))});let _e=oe.msg_down_stream_info;o.msg_down_stream_info=o.msg_down_stream_info.filter(Fe=>_e.find(Dt=>Dt.msg_user_info.uint64_tinyid===Fe.msg_user_info.uint64_tinyid));let vi=o.msg_down_stream_info;if(vi.forEach(Fe=>{let Dt=_e.find(pi=>pi.msg_user_info.uint64_tinyid===Fe.msg_user_info.uint64_tinyid);if(sm(Fe.msg_audio_status)||sm(Dt.msg_audio_status))Fe.msg_audio_status={};else{let pi=Fe.msg_audio_status,Mi=Dt.msg_audio_status,Wo=this.getDifferenceValue(Mi.uint32_audio_cache_ms_count,pi.uint32_audio_cache_ms_count);delete pi.uint32_audio_cache_ms_count,pi.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(Mi.uint32_audio_cache_ms,pi.uint32_audio_cache_ms)/Wo)||0;let zo=this.room.remotePublishedUserMap.get(Fe.msg_user_info.str_identifier);zo&&(zo.remoteAudioTrack.stat.jitterBufferDelay=pi.uint32_audio_cache_ms),pi.uint32_audio_origin_lost=this.getDifferenceValue(Mi.uint32_audio_origin_lost,pi.uint32_audio_origin_lost),pi.uint32_audio_receive=this.getDifferenceValue(Mi.uint32_audio_receive,pi.uint32_audio_receive),pi.uint32_audio_receive+=pi.uint32_audio_origin_lost;let vs=this.getDifferenceValue(Mi.uint32_audio_codec_bitrate,pi.uint32_audio_codec_bitrate);pi.uint32_audio_codec_bitrate=Math.round(8*vs/MA),pi.uint32_audio_total_bitrate=Math.round(8*vs/MA)}if(Fe.msg_video_status&&Dt.msg_video_status){let pi=Dt.msg_video_status;Fe.msg_video_status=Fe.msg_video_status.filter(Mi=>pi.find(Wo=>Wo.uint32_video_stream_type===Mi.uint32_video_stream_type)),Fe.msg_video_status.forEach(Mi=>{let Wo=pi.find(__=>__.uint32_video_stream_type===Mi.uint32_video_stream_type),zo=Wo.uint32_video_receive,vs=Wo.uint32_video_origin_lost,Zo=Wo.uint32_video_codec_bitrate,Vn=Wo.uint32_video_receive_fps,yg=Wo.uint32_video_dec_fps;Mi.uint32_video_origin_lost=this.getDifferenceValue(vs,Mi.uint32_video_origin_lost),Mi.uint32_video_receive=this.getDifferenceValue(zo,Mi.uint32_video_receive)+Mi.uint32_video_origin_lost;let wa=this.getDifferenceValue(Zo,Mi.uint32_video_codec_bitrate);Mi.uint32_video_codec_bitrate=Math.round(8*wa/MA);let fu=this.getDifferenceValue(Vn,Mi.uint32_video_receive_fps);Mi.uint32_video_receive_fps=Math.round(fu/MA),Mi.uint32_video_dec_fps=Math.round(this.getDifferenceValue(yg,Mi.uint32_video_dec_fps)/MA);let _L=this.getDifferenceValue(Wo.uint32_video_cache_ms_count,Mi.uint32_video_cache_ms_count);delete Mi.uint32_video_cache_ms_count,Mi.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Wo.uint32_video_cache_ms,Mi.uint32_video_cache_ms)/_L)||0})}}),!ze((S=fe?.mediaPlayoutStats)==null?void 0:S.totalSamplesDuration)&&!ze((L=t.mediaPlayoutStats)==null?void 0:L.totalSamplesDuration)){let Fe=2*Math.floor(this.getDifferenceValue((V=fe?.mediaPlayoutStats)==null?void 0:V.synthesizedSamplesDuration,(H=t.mediaPlayoutStats)==null?void 0:H.synthesizedSamplesDuration)/MA),Dt=2*Math.floor(this.getDifferenceValue((lA=fe?.mediaPlayoutStats)==null?void 0:lA.totalSamplesDuration,(hA=t.mediaPlayoutStats)==null?void 0:hA.totalSamplesDuration)/MA);o.msg_device_info.uint32_audio_play_cost=Dt-Fe}return fe&&t.receiverStats.forEach(Fe=>{if(Fe.audio.concealedSamples&&Fe.audio.totalSamplesReceived){let Dt=fe.receiverStats.find(pi=>pi.userId===Fe.userId);if(Dt&&Dt.audio.concealedSamples&&Dt.audio.totalSamplesReceived){let pi=(Fe.audio.silentConcealedSamples||0)-(Dt.audio.silentConcealedSamples||0),Mi=Fe.audio.concealedSamples-Dt.audio.concealedSamples,Wo=Fe.audio.totalSamplesReceived-Dt.audio.totalSamplesReceived,zo=Math.floor((Mi-pi)/Wo*1e3*MA);if(zo>1e3*MA/5){let vs=vi.find(Zo=>Zo.msg_user_info.str_identifier===Fe.userId);vs&&(vs.msg_audio_status.uint32_audio_block_time=zo)}}}}),o.msg_down_stream_info.forEach(Fe=>{Fe.msg_video_status.forEach(Dt=>{Dt.uint32_video_codec_bitrate===0&&Dt.uint32_video_receive_fps===0&&(Dt.uint32_video_width=0,Dt.uint32_video_height=0)})}),o}getStatsReport(A){return XA(this,arguments,function(t){var o=this;let{uplinkConnection:a,downlinkConnections:l,freezeMap:d}=t;return function*(){let h={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_capture_energy_after3a:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0,uint32_video_codec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},y=yield o.getStats(a,l);return JSON.stringify(o._prevReport)==="{}"&&(o._prevReport=JSON.parse(JSON.stringify(h))),o.prepareReport({stats:y,report:h,freezeMap:d,uplinkConnection:a}),o._prevReportTime=Date.now(),h}()})}getMediaPlayoutStats(A){let t;if(ka(A)){for(let o of A)if(o.type==="media-playout"){let{synthesizedSamplesDuration:a,totalSamplesDuration:l}=o;t={synthesizedSamplesDuration:a,totalSamplesDuration:l};break}return t}}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map,[this.room.localMainVideoTrack,this.room.capturedLocalMainVideoTrack,this.room.localAuxVideoTrack,this.room.capturedLocalAuxVideoTrack].forEach(A=>{A!=null&&A.stat&&(A.stat.framesCaptured=0)})}},lnA=dc(Xl());function InA(A){return new Promise(t=>XA(null,null,function*(){let o=setTimeout(()=>{t({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),a=Date.now(),l="https://".concat(A,"/?t=").concat(a);try{yield fetch(l)}catch{}clearTimeout(o);let d=function(h){let y={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let S=performance.getEntriesByType("resource").reverse();for(let L of S)if(L.name===h){let V=Math.round(L.duration),H=Math.max(Math.round(L.domainLookupStart-L.startTime),0),lA=L.redirectStart>0?Math.max(Math.round(L.redirectEnd-L.redirectStart),0):0,hA=L.fetchStart>0?Math.max(Math.round(L.domainLookupStart-L.fetchStart),0):0,MA=Math.round(L.domainLookupEnd-L.domainLookupStart),oe=Math.round(L.requestStart-L.secureConnectionStart),fe=Math.round(L.secureConnectionStart-L.connectStart),je=Math.round(L.responseStart-L.requestStart),_e=Math.round(L.responseEnd-(L.responseStart||L.startTime));y=So(Di({},y),{totalCost:V,local:H,redirect:lA,httpCache:hA,dns:MA,tcp:fe,tls:oe,request:je,response:_e});break}}catch{}return y}(l);d.totalCost===0&&(d.totalCost=Date.now()-a),t(d)}))}var J1=class P_ extends lnA.default{constructor(t){let{signalChannel:o,room:a}=t;super(),Y(this,"_room"),Y(this,"_signalChannel"),Y(this,"_log"),Y(this,"uplinkRTT",0),Y(this,"uplinkLoss",0),Y(this,"downlinkRTT",0),Y(this,"downlinkLoss",0),Y(this,"pingResults",{}),Y(this,"_downlinkPrevStatMap",new Map),Y(this,"_downlinkLossAndRTTMap",new Map),Y(this,"_interval",-1),Y(this,"_uplinkNetworkQuality",0),Y(this,"_downlinkNetworkQuality",0),Y(this,"_uplinkQualityHistory",[]),Y(this,"_downlinkQualityHistory",[]),this._room=a,this._signalChannel=o,this._log=pA.createLogger({parent:a.getLogger(),id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(t){t!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(t,", rtt: ").concat(this.uplinkRTT,", loss: ").concat(this.uplinkLoss," ws-rtt: ").concat(this._signalChannel.rtt)),this._uplinkNetworkQuality=t,this._uplinkQualityHistory.push(t),this._uplinkQualityHistory.length>P_.HISTORY_SIZE&&this._uplinkQualityHistory.shift()}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(t){if(t!==this._downlinkNetworkQuality){let{rtt:o,loss:a}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(t,", rtt: ").concat(o,", loss: ").concat(a," ws-rtt: ").concat(this._signalChannel.rtt))}this._downlinkNetworkQuality=t,this._downlinkQualityHistory.push(t),this._downlinkQualityHistory.length>P_.HISTORY_SIZE&&this._downlinkQualityHistory.shift()}initialize(){this._signalChannel.on(Qn.UPLINK_NETWORK_STATS,t=>{this.handleUplinkNetworkQuality(t)}),this._signalChannel.on(Yj,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(t){var o,a;if(t.data.code!==0)return;let l=t.data.data;if(l.delay&&this.updateDelay(l.delay),this._room.signalChannel&&l.wsRtt&&(this._room.signalChannel.rtt=l.wsRtt),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this.uplinkLoss=0,void(this.uplinkRTT=0);let d=(a=(o=this._room)==null?void 0:o.uplinkConnection)==null?void 0:a.getPeerConnection();if(d&&this.isPeerConnectionDisconnected(d))return this.uplinkNetworkQuality=6,this.uplinkLoss=0,void(this.uplinkRTT=0);let h=l.expectAudPkg+l.expectVidPkg,y=l.recvAudPkg+l.recvVidPkg,S=h-y;h===0&&y===0||(this.uplinkLoss=S<=0?0:Math.round(S/h*100),this.uplinkRTT=l.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return XA(this,null,function*(){if(this._room.remotePublishedUserMap.size===0)return void(this.downlinkNetworkQuality=0);let t=[...this._room.remotePublishedUserMap.values()],o=new Set,a=t.filter(y=>{let S=y.getPeerConnection();return!(!S||o.has(S))&&(o.add(S),!0)}),l=a.filter(y=>{var S;return((S=y.getPeerConnection())==null?void 0:S.connectionState)===mo.CONNECTED});if(a.filter(y=>this.isPeerConnectionDisconnected(y.getPeerConnection())).length===t.length)return void(this.downlinkNetworkQuality=6);for(let y=0;y{this.isPeerConnectionDisconnected(y)&&(this._downlinkPrevStatMap.delete(y),this._downlinkLossAndRTTMap.delete(y))}),this._downlinkLossAndRTTMap.size===0)return this.downlinkRTT=0,this.downlinkLoss=0,void(this.downlinkNetworkQuality=0);let{rtt:d,loss:h}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=d,this.downlinkLoss=h,this.downlinkNetworkQuality=this.getNetworkQuality(h,d)})}getStat(t){return XA(this,null,function*(){let o={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!t||!yy())return o;let a=t.getReceivers();try{for(let l=0;l{d.type==="candidate-pair"&&Ys(d.currentRoundTripTime)&&(o.rtt=Math.round(1e3*d.currentRoundTripTime)),d.type==="inbound-rtp"&&(d.mediaType===JA.AUDIO||d.mediaType===JA.VIDEO)&&(o.totalPacketsLost+=d.packetsLost,o.totalPacketsReceived+=d.packetsReceived)});return o.rtt===0&&(o.rtt=this.uplinkRTT),o}catch{return o}})}getAverageLossAndRTT(t){let o={rtt:0,loss:0};return Array.isArray(t)&&t.length>0&&(t.forEach(a=>{o.rtt+=a.rtt,o.loss+=a.loss}),Object.keys(o).forEach(a=>{o[a]=Math.round(o[a]/t.length)})),o}getNetworkQuality(t,o){return t>50||o>500?5:t>30||o>350?4:t>20||o>200?3:t>10||o>100?2:t>=0||o>=0?1:0}handleSignalConnectionStateChange(t){t.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):t.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=1)}handleUplinkConnectionStateChange(t){let{state:o}=t;o==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):o==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(t){return!(!t||t.connectionState!==mo.DISCONNECTED&&t.connectionState!==mo.FAILED&&t.connectionState!==mo.CLOSED)}setUplinkConnection(t){this._room.uplinkConnection=t,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){this._interval===-1?(this._log.debug("start network quality calculating"),this._interval=kr.run("ric",()=>{var t;this.handleDownlinkNetworkQuality();let o=[...this._downlinkLossAndRTTMap.values()];F.emit(rA.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:o});let a=(t=this._room.scheduleResult.config)==null?void 0:t.pingDomainInfo,l={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};a&&(l=So(Di({},l),{pingResults:this.uplinkRTT>a.rttThreshold||this.downlinkRTT>a.rttThreshold?this.pingResults:{}})),this.emit(P_.EVENT_NETWORK_QUALITY,l);let d=Date.now();if(a&&(this.uplinkRTT>a.rttThreshold||this.downlinkRTT>a.rttThreshold)&&d-P_.lastPingTime>1e3*a.interval){P_.lastPingTime=Date.now();let h=a.domain.map(y=>InA(y).then(S=>({domain:y,cost:S.totalCost})));Promise.all(h).then(y=>{this.pingResults.isPoorNetwork=y.some(S=>S.cost>700),this.pingResults.timestamp=d,this.pingResults.data=y,y.forEach(S=>{ri.addSuccessEvent({key:521718,cost:S.cost})}),this._log.warn("All ping results: ".concat(JSON.stringify(y)))}).catch(y=>{this._log.warn("Error during pinging domains: ".concat(y))})}},{delay:2e3})):this._log.info("network quality calculating is already started")}hadRecentBadUplink(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2;return this._uplinkQualityHistory.some(o=>o>t)}hadRecentBadDownlink(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2;return this._downlinkQualityHistory.some(o=>o>t)}stop(){this._log.debug("stopped"),this._interval!==-1&&(kr.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(t){let{tinyIdToUserIdMap:o}=this._room;t.forEach(a=>{let{srcTinyId:l,videoDelay:d,audioDelay:h}=a,y=o.get(l);if(y){let S=this._room.remotePublishedUserMap.get(y);S?.setDelay({videoDelay:d,audioDelay:h})}})}};Y(J1,"HISTORY_SIZE",10),Y(J1,"EVENT_NETWORK_QUALITY","0"),Y(J1,"lastPingTime",0);var Q8=J1,p8=class{constructor(A){Y(this,"_frameWorkType"),Y(this,"_component"),Y(this,"_language"),Y(this,"connectionType"),Y(this,"_room"),Y(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0}),Y(this,"_keyPrefix"),Y(this,"_log"),Y(this,"_intervalId"),Y(this,"_firstPublishedUserList"),Y(this,"_networkQuality"),Y(this,"_basicInfo"),Y(this,"_pathJoinRoom"),Y(this,"_pathLeaveRoom"),Y(this,"_pathMainVideoMap"),Y(this,"_pathMainAudioMap"),Y(this,"_pathAuxiliaryMap"),Y(this,"_remoteStreamStatMap"),Y(this,"_localStreamStat"),Y(this,"_eventMap",new Map),Y(this,"_captureCostSum",0),Y(this,"_captureCostCount",0),Y(this,"isDestroyed",!1),this._frameWorkType=A.frameWorkType||30,this._component=A.component||0,this.connectionType=A.connectionType||1,this._language=A.language||0,this._room=A.room,this._keyPrefix="key_point",this._log=pA.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(t=>{t.startsWith("handle")&&ba(this[t])&&(this[t]=function(o){let{fn:a,context:l}=o;return function(){try{for(var d=arguments.length,h=new Array(d),y=0;ypA.error("".concat(a.name,"() error observed ").concat(L))):S}catch(S){pA.error("".concat(a.name,"() error observed ").concat(S))}}}({fn:this[t],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Wd,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0,uint32_audio_capture_thread_health_zero_cnt:0,uint32_after3a_silence_duration:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,Tv().then(()=>{this._basicInfo.string_os_version=jp(),this._basicInfo.string_device_name=lQ()||this._basicInfo.string_os_version})}addEvent(A,t){return this._eventMap.set(A,t),F.on(A,t),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(rA.JOIN_START,this.handleJoinStart).addEvent(rA.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(rA.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(rA.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(rA.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(rA.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(rA.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(rA.JOIN_FAILED,this.handleJoinFailed).addEvent(rA.LEAVE_START,this.handleLeaveStart).addEvent(rA.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(rA.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(rA.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(rA.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(rA.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(rA.PUBLISH_START,this.handlePublishStart).addEvent(rA.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(rA.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(rA.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(rA.PLAY_TRACK_START,this.handlePlayStart).addEvent(rA.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(rA.PLAYER_STATE_CHANGED,A=>{let{track:t,state:o,type:a}=A;!t.isRemote||!this.hitTest(t.room)||o==="PLAYING"&&(a===JA.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(rA.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(rA.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(rA.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(rA.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(rA.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(rA.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(rA.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:t,prevMuteState:o,muteState:a}=A;if(!this.hitTest(t))return;let l=o.hasAudio||o.hasVideo||o.hasSmall,d=o.hasAuxiliary,h=a.hasAudio||a.hasVideo||a.hasSmall,y=a.hasAuxiliary;!l&&h&&this.handleRemoteStreamAdded(a.userId,"main"),!d&&y&&this.handleRemoteStreamAdded(a.userId,"auxiliary")}).addEvent(rA.SINGLE_CONNECTION_STAT,A=>{let{room:t,stat:o}=A;this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=o.ice,this._pathJoinRoom.int32_dtls_cost=o.dtls,this._pathJoinRoom.int32_peer_connection_cost=o.peerConnection)})}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((A,t)=>F.off(t,A)),this._eventMap.clear()}destroy(){this.uninstallEvents(),kr.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(A){this.hitTest(A.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),A.params&&(ze(A.params.frameWorkType)||(this._frameWorkType=A.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),ze(A.params.component)||(this._component=A.params.component,this._basicInfo.uint32_component=this._component),ze(A.params.language)||(this._language=A.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(A){let{room:t,detailCost:o}=A;if(this.hitTest(t)&&o){let{totalCost:a,local:l,dns:d,tcp:h,tls:y,request:S,response:L}=o;this._pathJoinRoom.int32_schedule_cost=a,this._pathJoinRoom.int32_schedule_local=l,this._pathJoinRoom.int32_schedule_dns=d,this._pathJoinRoom.int32_schedule_tcp=h,this._pathJoinRoom.int32_schedule_tls=y,this._pathJoinRoom.int32_schedule_request=S,this._pathJoinRoom.int32_schedule_response=L}}handleSignalConnectionStart(A){let{room:t}=A;this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(A){let{room:t,error:o}=A;this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),o&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=o instanceof li?Number(o.getExtraCode()||o.getCode()):mt.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(A){this.hitTest(A.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(A){this.hitTest(A.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=A.code,A.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(A){this.hitTest(A.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=A.room.getSignalInfo())}handleJoinFailed(A){let{room:t,error:o}=A;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=o.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(A){this.hitTest(A.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=A.publishedUserList||[])}handleSendFirstVideoFrame(A){let{room:t}=A;this.hitTest(t)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(A){this.hitTest(A.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(A){var t;if(this.hitTest(A.room)&&this._pathLeaveRoom.uint64_end_time===0){if(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0){this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time;let o=(t=this._room.audioManager.localAudioTrack)==null?void 0:t.after3aSilenceStartTime;o&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=Oo()-o)}else this._log.warn("pathJoinRoom endTime is 0");this.report()}}handleLeaveSendCMD(A){this.hitTest(A.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleSwitchRoomStart(A){if(this.hitTest(A.room)){let t=Date.now();this.report().then(()=>{this._pathJoinRoom.uint64_start_time=t,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=t})}}handleSwitchRoomSuccess(A){let{room:t}=A;if(this.hitTest(t)&&this._pathJoinRoom.uint64_end_time===0){let o=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=o,this._pathJoinRoom.uint64_end_time=o,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed(A){let{room:t,error:o}=A;if(this.hitTest(t)){let a=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=a,this._pathJoinRoom.uint64_end_time=a,o&&(this._pathJoinRoom.int32_end_ret=o instanceof li?Number(o.getExtraCode()||o.getCode()):mt.UNKNOWN)}}handleRemoteStreamAdded(A,t){var o;let a="".concat(A,"_").concat(t);if(!this._remoteStreamStatMap.has(a)){let l={userId:A,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:So(Di({},unA),{msg_user_info:new jj({userId:A,tinyId:(o=this._room.remotePublishedUserMap.get(A))==null?void 0:o.tinyId,role:20})})};l.statsToReport.uint32_stream_type=t==="main"?2:7,this._remoteStreamStatMap.set(a,l)}}handleSubscribeStart(A){let{room:t,remotePublishedUser:o,streamType:a,subscribeState:l}=A;if(!this.hitTest(t))return;let{userId:d,tinyId:h,role:y}=o,S=new jj({userId:d,tinyId:h,role:y==="anchor"?20:21}),L=Date.now(),V="".concat(d,"_").concat(a),H=this._remoteStreamStatMap.get(V);H&&H.subscribeStartTime===0&&(H.subscribeStartTime=L),a==="main"?(o.muteState.hasVideo&&(l.video||l.smallVideo)&&!this._pathMainVideoMap.has(V)&&this._pathMainVideoMap.set(V,{statsToReport:{msg_user_info:S,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:d,sendSubscribeCMDTime:L}),o.muteState.hasAudio&&l.audio&&!this._pathMainAudioMap.has(V)&&this._pathMainAudioMap.set(V,{statsToReport:{msg_user_info:S,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:d,sendSubscribeCMDTime:L})):o.muteState.hasAuxiliary&&l.auxiliary&&!this._pathAuxiliaryMap.has(V)&&this._pathAuxiliaryMap.set(V,{sendSubscribeCMDTime:L})}handleSubscribed(A){let{room:t,remotePublishedUser:o,streamType:a}=A;if(this.hitTest(t)){let l="".concat(o.userId,"_").concat(a),d=this._remoteStreamStatMap.get(l);d&&d.subscribedTime===0&&(d.subscribedTime=Date.now())}}handlePlayStart(A){let{track:t}=A;if(!t.isRemote||!this.hitTest(t.room))return;let o="".concat(t.userId,"_").concat(t.streamType),a=this._remoteStreamStatMap.get(o);a?.playStreamTime===0&&(a.playStreamTime=Date.now())}handleVideoLoadedData(A){let{track:t}=A;if(!t.isRemote||!this.hitTest(t.room))return;let o="".concat(t.userId,"_").concat(t.streamType),a=this._pathMainVideoMap.get(o);a&&a.statsToReport.uint64_combine_first_frame_time===0&&(a.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(A){let t="".concat(A.userId,"_").concat(A.streamType),o=Date.now(),a=this._pathMainVideoMap.get(t),l=this._remoteStreamStatMap.get(t);if(l){let{statsToReport:d}=l;if(d.uint32_video_render_first||A.streamType!=="main"?this.hasAuxFlag(A.userId):this.hasVideoFlag(A.userId)){let h=o-this._pathJoinRoom.uint64_start_time;d.uint32_video_render_first=h,ri.addNumber({key:516820,value:h})}}a?.statsToReport.uint64_render_first_frame_time===0&&(a.statsToReport.uint64_render_first_frame_time=o)}handleAudioPlaying(A){let t="".concat(A.userId,"_").concat(A.streamType),o=this._pathMainAudioMap.get(t);o&&o.statsToReport.uint64_play_first_frame_time===0&&(o.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(A){this.hitTest(A.room)&&(this._networkQuality.totalUplinkLoss+=A.uplink.loss,this._networkQuality.totalUplinkRTT+=A.uplink.rtt,this._networkQuality.count++,A.downlinks.forEach(t=>{let{rtt:o,loss:a,userId:l,videoDelay:d,audioDelay:h}=t,y=this._networkQuality.totalDownlinkRTTAndLossMap.get(l);if(y)y.totalRTT+=o,y.totalLoss+=a,d&&(y.totalVideoDelay=(y.totalVideoDelay||0)+d,y.videoDelayCount=(y.videoDelayCount||0)+1),h&&(y.totalAudioDelay=(y.totalAudioDelay||0)+h,y.audioDelayCount=(y.audioDelayCount||0)+1),y.count++;else{let S,L,V,H;d&&(L=d,V=1),h&&(S=h,H=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(l,{totalRTT:o,totalLoss:a,count:1,totalAudioDelay:S,totalVideoDelay:L,audioDelayCount:H,videoDelayCount:V})}}))}handleHeartbeatStats(A){var t;if(this.hitTest(A.room)){let{msg_device_info:o,msg_up_stream_info:a,msg_down_stream_info:l}=A.report;if(a.msg_video_status[0]){let{uint32_video_codec_bitrate:d,uint32_video_enc_fps:h,uint32_video_width:y,uint32_video_height:S}=a.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=d,this._localStreamStat.totalVideoFPS+=h,this._localStreamStat.totalVideoWidth+=y,this._localStreamStat.totalVideoHeight+=S,this._localStreamStat.videoCount++}if(a.msg_audio_status){let{uint32_audio_level:d}=a.msg_audio_status;Math.floor(d/sd*100)>0&&(this._localStreamStat.totalAudioLevel+=d/sd,this._localStreamStat.audioLevelCount++)}l.forEach(d=>{let{msg_user_info:h,msg_audio_status:y,msg_video_status:S}=d,L=h.str_identifier,V=this._room.remotePublishedUserMap.get(L);if(S.forEach(H=>{let lA=H.uint32_video_stream_type===2,hA=H.uint32_video_stream_type===7,MA="".concat(L,"_").concat(lA?"main":"auxiliary"),oe=this._remoteStreamStatMap.get(MA);if(oe&&(lA&&V!=null&&V.remoteVideoTrack.isSubscribed||hA&&V!=null&&V.remoteAuxiliaryTrack)){oe.totalVideoFPS+=H.uint32_video_receive_fps,oe.totalVideoBitrate+=H.uint32_video_codec_bitrate,oe.videoCount++,oe.statsToReport.uint32_video_width===0&&(oe.statsToReport.uint32_video_width=H.uint32_video_width),oe.statsToReport.uint32_video_height===0&&(oe.statsToReport.uint32_video_height=H.uint32_video_height);let fe=lA?V.remoteVideoTrack:V.remoteAuxiliaryTrack;fe.stat.jitterBufferDelay&&(oe.videoJitterBufferDelay=fe.stat.jitterBufferDelay),fe.stat.framesReceived&&(oe.statsToReport.uint32_video_consume_render_rate=Math.floor(fe.stat.framesDecoded/fe.stat.framesReceived*zS(10,6)))}}),!b0(y)){let H="".concat(L,"_main"),lA=this._remoteStreamStatMap.get(H);this._remoteStreamStatMap.has(H)&&lA&&V!=null&&V.remoteAudioTrack.isSubscribed&&(lA.totalAudioBitrate+=y.uint32_audio_codec_bitrate,lA.audioCount++,V.remoteAudioTrack.stat.jitterBufferDelay&&(lA.audioJitterBufferDelay=V.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(y.uint32_audio_level/sd*100)>0&&(lA.totalAudioLevel+=y.uint32_audio_level/sd,lA.audioLevelCount++),y.uint32_audio_block_time&&(lA.statsToReport.uint32_audio_block_time+=y.uint32_audio_block_time))}}),o.uint32_audio_capture_cost&&(this._captureCostSum+=o.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0)),o.uint32_audio_capture_cost===0&&((t=this._room.audioManager.localAudioTrack)==null?void 0:t.muted)===!1&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}handlePublishStart(A){let{room:t}=A;this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(A){let{track:t}=A;t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(A){let{track:t}=A;t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(A){let{track:t,error:o}=A,a={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[o.name]||(o instanceof li?o.getExtraCode()||o.getCode():mt.UNKNOWN);t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=a,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=a,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(A){return this._firstPublishedUserList.findIndex(t=>t.userId===A&&t.flag&ev)>=0}hasAudioFlag(A){return this._firstPublishedUserList.findIndex(t=>t.userId===A&&t.flag&iv)>=0}hasAuxFlag(A){return this._firstPublishedUserList.findIndex(t=>t.userId===A&&t.flag&tv)>=0}hitTest(A){return A===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let A=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=A<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((A,t)=>{let{userId:o}=A,a=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(a){let{totalLoss:L,count:V,audioDelayCount:H,videoDelayCount:lA,totalAudioDelay:hA,totalVideoDelay:MA}=a;A.statsToReport.uint32_avg_down_loss=Math.floor(L/V),H&&hA&&(A.statsToReport.uint32_audio_network_p2p_delay=Math.floor(hA/H),A.audioJitterBufferDelay&&(A.statsToReport.uint32_p2p_delay=Math.floor(A.statsToReport.uint32_audio_network_p2p_delay+A.audioJitterBufferDelay))),lA&&MA&&(A.statsToReport.uint32_video_network_p2p_delay=Math.floor(MA/lA))}A.videoCount>0&&(A.statsToReport.uint32_video_avg_fps=Math.floor(A.totalVideoFPS/A.videoCount),A.statsToReport.uint32_video_avg_bitrate=Math.floor(A.totalVideoBitrate/A.videoCount)),A.audioCount>0&&(A.statsToReport.uint32_audio_recv_bitrate=A.statsToReport.uint32_audio_bitrate=Math.floor(A.totalAudioBitrate/A.audioCount)),A.audioLevelCount>0&&(A.statsToReport.uint32_audio_play_db=Math.floor(A.totalAudioLevel/A.audioLevelCount*100));let{callDurationCalculator:l}=this._room;l&&(A.statsToReport.uint32_audio_play_time=l.getDuration(t,JA.AUDIO),A.statsToReport.uint32_video_play_time=l.getDuration(t,JA.VIDEO)),A.statsToReport.uint32_video_render_first&&(A.statsToReport.uint32_video_render_first=Math.min(A.statsToReport.uint32_video_render_first,rM));let{badCaseDetector:d}=this._room,{dataFreeze:h,count:y}=d.getDataFreezeDuration(t),{renderFreeze:S}=d.getRenderFreezeDuration(t);A.statsToReport.uint32_video_block_count=y,A.statsToReport.uint32_video_block_time=Math.min(h,A.statsToReport.uint32_video_play_time),A.statsToReport.uint32_video_external_block_time=Math.min(S,A.statsToReport.uint32_video_play_time),A.statsToReport.uint32_audio_block_time=Math.min(A.statsToReport.uint32_audio_block_time,A.statsToReport.uint32_audio_play_time),d.isBlackStream(t)&&A.statsToReport.uint32_video_avg_fps===0?A.statsToReport.uint32_video_black_screen_subjective=1:A.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((A,t)=>{this.hasAudioFlag(A.userId)?A.statsToReport.uint64_play_first_frame_time-A.statsToReport.uint64_start_enter_time>rM&&(A.statsToReport.uint64_play_first_frame_time=A.statsToReport.uint64_start_enter_time+rM):this._pathMainAudioMap.delete(t)}),this._pathMainVideoMap.forEach((A,t)=>{this.hasVideoFlag(A.userId)?A.statsToReport.uint64_render_first_frame_time-A.statsToReport.uint64_start_enter_time>rM&&(A.statsToReport.uint64_render_first_frame_time=A.statsToReport.uint64_start_enter_time+rM):this._pathMainVideoMap.delete(t)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>rM&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+rM)}getReportData(){this._basicInfo.uint32_networkType=$f();let A={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new jj({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Ev(this._signalInfo.relayIp),uint32_client_ip:Ev(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*zS(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(t=>t.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(t=>t.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(t=>t.statsToReport),uint32_info_client_ip:Ev(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return U0(A),A}report(){return XA(this,null,function*(){try{this.prepareReport();let A=this.getReportData();yield this.upload(A),this.initData()}catch(A){this._log.warn(A)}finally{this.isDestroyed&&(this._room=null)}})}upload(A){return XA(this,null,function*(){if(A.msg_path_enter_room.uint64_start_time===0)return;let t=Number(this._room.sdkAppId),o=TA.enable?oQ(A,2001,t):yield ak(A),a=o instanceof ArrayBuffer,l="".concat(Xf(t,OI.KEY_POINT),"&gzip=").concat(+a),d=!1;navigator.sendBeacon&&(d=navigator.sendBeacon(l,o));let h=[this.uploadKVStat(ri),this.uploadKVStat(eB)];d||h.push(nQ({url:l,body:o,priority:"low"})),yield Promise.all(h)})}setConnectionType(A){this.connectionType=A,this._basicInfo.uint32_connection_type=A}uploadKVStat(A){return XA(this,arguments,function(t){var o=this;let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._room.sdkAppId;return function*(){var l,d;let h=t.getReportData((l=o._room)==null?void 0:l.userSig,(d=o._signalInfo)==null?void 0:d.reportToken);if(h.stats_count.length===0&&h.stats_distribution.length===0)return;h.msg_sdk_basic_info=So(Di({},h.msg_sdk_basic_info),{bytes_device_name:o._basicInfo.string_device_name||"",bytes_os_version:o._basicInfo.string_os_version||"",uint32_framework:o._frameWorkType,uint32_network_type:o._basicInfo.uint32_networkType||0}),o._log.debug(h);let y=TA.enable?oQ(h,2003,a):yield ak(h),S=y instanceof ArrayBuffer,L="".concat(Xf(+a,OI.KV_STAT),"&gzip=").concat(+S),V=!1;navigator.sendBeacon&&(V=navigator.sendBeacon(L,y)),V||nQ({url:L,body:y})}()})}};Qi([iB({settings:{timeout:500,retries:3}})],p8.prototype,"upload");var rM=5e3,unA={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},jj=class{constructor(A){Y(this,"str_identifier"),Y(this,"str_tinyid"),Y(this,"uint32_role"),this.str_identifier=String(A.userId),this.str_tinyid=String(A.tinyId||0),this.uint32_role=A.role}},EnA=p8,m8=class{constructor(){Y(this,"_startTime"),Y(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=Oo())}stop(){this._endTime===0&&(this._endTime=Oo())}getDuration(){return this._endTime===0?Oo()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},dnA=class{constructor(A){Y(this,"_room",null),Y(this,"_durationMap"),Y(this,"_eventMap",new Map),this._room=A.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(rA.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(rA.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(rA.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:t,prevMuteState:o,muteState:a}=A;var l;let{userId:d}=a;if(!this.hitTest(t))return;o.hasAudio&&!a.hasAudio&&this.stopDurationItem("".concat(d,"_main"),JA.AUDIO),o.hasVideo&&!a.hasVideo&&this.stopDurationItem("".concat(d,"_main"),JA.VIDEO),o.hasAuxiliary&&!a.hasAuxiliary&&this.stopDurationItem("".concat(d,"_auxiliary"),JA.VIDEO);let h=(l=this._room)==null?void 0:l.remotePublishedUserMap.get(d);h&&(!o.hasAudio&&a.hasAudio&&h.remoteAudioTrack.isSubscribed&&this.addDuractionItem(d,JA.AUDIO,"main"),!o.hasVideo&&a.hasVideo&&h.remoteVideoTrack.isSubscribed&&this.addDuractionItem(d,JA.VIDEO,"main"),!o.hasAuxiliary&&a.hasAuxiliary&&h.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(d,JA.VIDEO,"auxiliary"))}),this._eventMap.forEach((A,t)=>F.on(t,A,this))}uninstallEvents(){this._eventMap.forEach((A,t)=>F.off(t,A,this)),this._eventMap.clear()}handleSubscribed(A){let{track:t}=A;if(!this.hitTest(t.room))return;let{userId:o,streamType:a,kind:l}=t;t.isSubscribed?this.addDuractionItem(o,l,a):this.stopDurationItem("".concat(o,"_").concat(a),l)}handleUnsubscribed(A){let{track:t}=A;this.hitTest(t.room)&&this.stopDurationItem("".concat(t.userId,"_").concat(t.streamType),t.kind)}isRecording(A){return A.findIndex(t=>t.endTime===0)>=0}addDuractionItem(A,t,o){let a="".concat(A,"_").concat(o),l=new m8,d=this._durationMap.get(a);d?this.isRecording(d[t])||d[t].push(l):this._durationMap.set(a,{userId:A,type:o,audio:t===JA.AUDIO?[l]:[],video:t===JA.AUDIO?[]:[l]})}stopDurationItem(A,t){if(this._durationMap.has(A)){let o=this._durationMap.get(A)[t].find(a=>a.endTime===0);o&&o.stop()}}hitTest(A){return this._room===A}getDuration(A,t){return this._durationMap.has(A)?this._durationMap.get(A)[t].reduce((o,a)=>o+a.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},CnA=class{constructor(){Y(this,"renderFreezeMap",new Map),Y(this,"dataFreezeMap",new Map)}get(A,t){let o=this.renderFreezeMap.get(A),a=this.dataFreezeMap.get(A);return t?t==="data"?a:o:(mg||gr)&&o&&a&&o.duration>a.duration?o:a}set(A,t,o){o==="data"?this.dataFreezeMap.set(A,t):this.renderFreezeMap.set(A,t)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},hnA=class{constructor(A){Y(this,"_room"),Y(this,"_renderFreezeMap",new Map),Y(this,"_isVideoPlayingEventFiredMap",new Map),Y(this,"_dataFreezeMap",new Map),Y(this,"_monitorFreezeData",new CnA),Y(this,"_eventMap",new Map),Y(this,"_videoEncodeFailedCount",0),Y(this,"_audioEncodeFailedCount",0),Y(this,"_encodeFailedThreshold",3),Y(this,"ABNORMAL_TIME_LOWER_LIMIT",3e3),Y(this,"ABNORMAL_TIME_UPPER_LIMIT",5e3),Y(this,"_videoAbnormalTimestampMap",new Map),Y(this,"_remoteVideoAbnormalTimestampMap",new Map),Y(this,"_audioAbnormalTimestampMap",new Map),Y(this,"eventListenerMap",new Map),this._room=A.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(rA.LEAVE_SUCCESS,A=>{let{room:t}=A;this.hitTest(t)&&this.stop()}).set(rA.PLAY_TRACK_START,this.onPlayTrackStart).set(rA.UNSUBSCRIBE_SUCCESS,A=>{let{room:t,streamType:o,remotePublishedUser:a}=A;if(!this.hitTest(t))return;let{userId:l}=a,d="".concat(l,"_").concat(o);this.stopDataFreeze({key:d,userId:l,type:o})}).set(rA.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:t,prevMuteState:o,muteState:a}=A;if(!this.hitTest(t))return;let{userId:l}=a;if(o.hasVideo&&!a.hasVideo){let d="main",h="".concat(a.userId,"_").concat(d);this.stopDataFreeze({key:h,userId:l,type:d})}if(o.hasAuxiliary&&!a.hasAuxiliary){let d="auxiliary",h="".concat(a.userId,"_").concat(d);this.stopDataFreeze({key:h,userId:l,type:d})}}).set(rA.PLAYER_STATE_CHANGED,A=>{let{track:t,state:o,reason:a,type:l}=A;if(t.isRemote&&t.room&&this.hitTest(t.room)&&l===JA.VIDEO){if(o==="PLAYING"){let d="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(d,!0)}a===JA.MUTE?this.onVideoTrackMuted(t):a===JA.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(rA.HEARTBEAT_REPORT,this.onHearBeatReport).set(rA.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(rA.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((A,t)=>F.on(t,A,this))}uninstallEvents(){this._eventMap.forEach((A,t)=>F.off(t,A,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(A){if(!A.isSubscribed)return;let{userId:t,streamType:o}=A,a="".concat(t,"_").concat(o),l=this._dataFreezeMap.get(a),d=new m8;l?l.durationItemList.push(d):this._dataFreezeMap.set(a,{userId:t,type:o,durationItemList:[d],isFreezing(){let h=this.durationItemList[this.durationItemList.length-1];return h&&h.endTime===0}})}onVideoTrackUnmuted(A){if(!A.isSubscribed)return;let{userId:t,streamType:o}=A,a="".concat(t,"_").concat(o);this.stopDataFreeze({key:a,userId:t,type:o})}onHearBeatReport(A){let{room:t,report:o}=A;this.hitTest(t)&&(this.localMediaTrackDetector(o),this.remoteMediaTrackDetector(o))}remoteMediaTrackDetector(A){A.msg_down_stream_info.length>0&&A.msg_down_stream_info.forEach(t=>{var o;if(t.msg_video_status.length===0)return;let a=t.msg_user_info.str_identifier,l=(o=this._room.remotePublishedUserMap.get(a))==null?void 0:o.remoteVideoTrack;t.msg_video_status.forEach(d=>{let h=Oo();if(d.uint32_video_codec_bitrate!==void 0&&d.uint32_video_codec_bitrate>0&&d.uint32_video_receive_fps===0&&l!=null&&l.muted)if(this._remoteVideoAbnormalTimestampMap.has("".concat(a,"-decode"))){let y=this._remoteVideoAbnormalTimestampMap.get("".concat(a,"-decode"));y&&h-y>this.ABNORMAL_TIME_LOWER_LIMIT&&h-y=this.ABNORMAL_TIME_UPPER_LIMIT&&(ds.uploadEvent({userId:this._room.userId,log:"stat-".concat(Wa.VIDEO_DECODE_RESUME_DURING_CALL)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(a,"-decode")))}if(d.uint32_video_codec_bitrate!==void 0&&d.uint32_video_codec_bitrate>5e5&&d.uint32_video_dec_fps!==void 0&&d.uint32_video_dec_fps<=5)if(this._remoteVideoAbnormalTimestampMap.has("".concat(a,"-hardware"))){let y=this._remoteVideoAbnormalTimestampMap.get("".concat(a,"-hardware"));if(y&&h-y>this.ABNORMAL_TIME_LOWER_LIMIT/2&&h-y<2*this.ABNORMAL_TIME_UPPER_LIMIT){ds.uploadEvent({userId:this._room.userId,log:"stat-".concat(Wa.VIDEO_HARDWARE_DECODE_FAILED)});let S=this._room.remotePublishedUserMap.get(a);if(S){let L=d.uint32_video_stream_type===2?S.remoteVideoTrack:S.remoteAuxiliaryTrack;L&&(L.log.warn("decode failed during call"),L.emit("decode-failed-during-call"))}}}else this._remoteVideoAbnormalTimestampMap.set("".concat(a,"-hardware"),h);else{let y=this._remoteVideoAbnormalTimestampMap.get("".concat(a,"-hardware"));y&&h-y>=2*this.ABNORMAL_TIME_UPPER_LIMIT&&(ds.uploadEvent({userId:this._room.userId,log:"stat-".concat(Wa.VIDEO_HARDWARE_DECODE_RESUME)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(a,"-hardware")))}})})}localMediaTrackDetector(A){if(A.msg_up_stream_info.msg_video_status){let t=A.msg_up_stream_info.msg_video_status,o=Array.from(this._room.localTracks).find(l=>l.kind==="video"&&!l.isScreen),a=o?.stat.bytesSent||0;if(o?.isMediaTrackActive===!1||a<=0||o!=null&&o.isUseCustomSource)return;t.forEach(l=>{let d=Oo();if(l.uint32_video_stream_type===2)if(l.uint32_video_capture_fps!==0&&l.uint32_video_codec_bitrate===0&&l.uint32_video_enc_fps===0&&o!=null&&o.isPublished)if(this._videoAbnormalTimestampMap.has("local-encode")){let h=this._videoAbnormalTimestampMap.get("local-encode");h&&d-h>this.ABNORMAL_TIME_LOWER_LIMIT&&d-h=this.ABNORMAL_TIME_UPPER_LIMIT&&ds.uploadEvent({userId:this._room.userId,log:"stat-".concat(Wa.VIDEO_ENCODE_RESUME_DURING_CALL)}),this._videoAbnormalTimestampMap.delete("local-encode")}})}if(A.msg_up_stream_info.msg_audio_status){let t=A.msg_up_stream_info.msg_audio_status,o=Array.from(this._room.localTracks).find(d=>d.kind==="audio"),a=o?.stat.bytesSent||0;if(o?.isMediaTrackActive===!1||a<=0||o!=null&&o.isUseCustomSource)return;let l=Oo();if(t.uint32_audio_codec_bitrate===0&&o!=null&&o.isPublished)if(this._audioAbnormalTimestampMap.has("local-encode")){let d=this._audioAbnormalTimestampMap.get("local-encode");d&&l-d>this.ABNORMAL_TIME_LOWER_LIMIT&&l-d=this.ABNORMAL_TIME_UPPER_LIMIT&&ds.uploadEvent({userId:this._room.userId,log:"stat-".concat(Wa.AUDIO_ENCODE_RESUME_DURING_CALL)}),this._audioAbnormalTimestampMap.delete("local-encode")}}}stopDataFreeze(A){let{key:t,userId:o,type:a}=A,l=this._dataFreezeMap.get(t);if(!l||!l.isFreezing())return;let d=l.durationItemList[l.durationItemList.length-1];d.stop();let h=d.getDuration();if(h>Vb){let y=this._monitorFreezeData.get(t,"data");this._monitorFreezeData.set(t,{userId:o,type:a,duration:y?y.duration+h:h},"data")}else l.durationItemList.pop()}getTotalDuration(A){return A.reduce((t,o)=>{let a=o.getDuration();return t+Math.min(a,5e3)},0)}onPlayTrackStart(A){let{track:t}=A;if(!t.isRemote||!this.hitTest(t.room)||t.kind!==JA.VIDEO||!t.isRemotePublished)return;let o="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(o)||this._isVideoPlayingEventFiredMap.set(o,!1)}getDataFreezeDuration(A){let t={dataFreeze:0,count:0},o=this._dataFreezeMap.get(A);if(o){if(o.isFreezing()){let a=o.durationItemList[o.durationItemList.length-1];a.stop(),a.getDuration(){document.hidden||(l=0)};document.addEventListener("visibilitychange",d);let h=(y,S)=>{var L;if(l){let V=t.decodeFPS,H=V>0&&V<=5?600+1e3/V:600,lA=S.presentationTime-l;if(lA>H){lA=Math.min(lA,5e3);let hA="".concat(t.userId,"_").concat(t.streamType),MA=this._monitorFreezeData.get(hA,"render");MA?MA.duration+=lA:this._monitorFreezeData.set(hA,{userId:t.userId,type:t.streamType,duration:lA},"render");let oe=this._renderFreezeMap.get(hA);oe?(oe.totalDuration+=lA,oe.count+=1):this._renderFreezeMap.set(hA,{userId:t.userId,type:t.streamType,totalDuration:lA,count:1})}}l=S.presentationTime,(L=o.element)==null||L.requestVideoFrameCallback(h)};(a=o.element)==null||a.requestVideoFrameCallback(h),this.eventListenerMap.set("".concat(t.userId,"_").concat(t.streamType),{onVisibilityChange:d})}onRemoteVideoPlayEnd(A){let{track:t,player:o}=A,a="".concat(t.userId,"_").concat(t.streamType),l=this.eventListenerMap.get(a);l&&document.removeEventListener("visibilitychange",l.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(A){return A===this._room}destroy(){this.uninstallEvents()}},BnA=dc(Xl(),1),QnA=class{constructor(A,t,o,a,l){let d=arguments.length>5&&arguments[5]!==void 0?arguments[5]:1.3333333333333333;this.vbMode=A,this.faceDetectorHash=o,this.visionTaskRegistry=a,this.logger=l,Y(this,"animationState"),Y(this,"originalAspect"),Y(this,"totalOffsetX",0),Y(this,"totalOffsetY",0),Y(this,"defaultScaleRatio",.1),Y(this,"isRecovering",!1),Y(this,"boundaryY",280),Y(this,"lastActionTime",0),Y(this,"restTime",400),this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=d||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,t)}addEvent(A,t,o){let a=[{key:570704,error:o??(t?void 0:11)},{key:570705,error:o??(t?void 0:22)}][A-1];a&&(t?ri.addSuccessEvent({key:a.key}):ri.addFailedEvent({key:a.key,error:a.error}))}actionCentering(A){let t=Date.now();if(this.animation(),!this.faceDetectorHash||t-this.lastActionTimet/2?(l=t-o-a,d=o-l):(l=o,d=0),{min:l,offset:d}}calculateTargetPosition(A,t,o,a,l,d){let h,y,S=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.4,L=A+o/2,V=t+a/2,{min:H,offset:lA}=this.calculateBoundary(L,l,A,o),{min:hA,offset:MA}=this.calculateBoundary(V,d,t,a);return h=2*H+o,y=2*hA+a,h/y>this.originalAspect?(h=y*this.originalAspect,lA=L-h/2):(y=h/this.originalAspect,MA=V-y/2),o/l>S&&(lA=0,MA=0,h=l,y=d),lA=Math.max(0,Math.min(lA,l-h)),MA=Math.max(0,Math.min(MA,d-y)),{sx:lA,sy:MA,cropWidth:h,cropHeight:y,timestamp:Date.now()}}processFacePositionCrop(A,t,o){if(!this.animationState.current||!this.animationState.target){let h={sx:0,sy:0,cropWidth:t,cropHeight:o,timestamp:Date.now()};return this.animationState.current=h,void(this.animationState.target=h)}let a=this.positionDistance(this.animationState.target,A),l=this.positionDistance(this.animationState.current,A),d=this.animationState.current.cropWidth/t;a>this.animationState.debounceThreshold*d&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&l>this.animationState.movementThreshold*d&&(this.animationState.target=A,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(A){if(!this.animationState.current||!this.animationState.target)return this.animationState.current=Di({},A),void(this.animationState.target=Di({},A));let t=this.positionDistance(this.animationState.current,A),o=this.positionDistance(this.animationState.target,A);t>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&o>this.animationState.movementThreshold&&(this.animationState.current=A,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let A=Date.now()-this.animationState.startTime,t=Math.min(A/this.animationState.duration,1),o=a=>a<.5?2*a*a:(4-2*a)*a-1;if(this.animationState.current&&this.animationState.target){let a=(this.animationState.target.sx-this.animationState.current.sx)*o(t);this.animationState.current.sx+=a,this.totalOffsetX+=a;let l=(this.animationState.target.sy-this.animationState.current.sy)*o(t);if(this.animationState.current.sy+=l,this.totalOffsetY+=l,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*o(t),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*o(t),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*o(t)),Ys(this.animationState.current.scaleOffsetX)&&Ys(this.animationState.target.scaleOffsetX)&&Ys(this.animationState.current.scaleOffsetY)&&Ys(this.animationState.target.scaleOffsetY)){let d=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*o(t);this.animationState.current.scaleOffsetX+=d;let h=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*o(t);this.animationState.current.scaleOffsetY+=h}}t>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(A,t){return Math.sqrt(zS(A.sx-t.sx,2)+zS(A.sy-t.sy,2))}recoverOriginal(A,t){this.animationState.target={sx:0,sy:0,cropWidth:A,cropHeight:t,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(A,t,o,a,l,d){let h=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.3;if(this.isRecovering)return;let y=this.calculateTargetPosition(o,a,l,d,A,t);this.processFacePositionCrop(y,A,t),l*d/y.cropWidth/y.cropHeight>h&&this.recoverOriginal(A,t)}movingPortrait(A,t,o,a,l,d){var h,y,S,L,V,H,lA,hA,MA,oe,fe,je;let _e={sx:o+l/2+this.totalOffsetX,sy:a+d/2+this.totalOffsetY,cropWidth:A,cropHeight:t,scaleRatio:(y=(h=this.animationState.current)==null?void 0:h.scaleRatio)!=null?y:1,scaleOffsetX:(L=(S=this.animationState.current)==null?void 0:S.scaleOffsetX)!=null?L:0,scaleOffsetY:(H=(V=this.animationState.current)==null?void 0:V.scaleOffsetY)!=null?H:0,timestamp:Date.now()};this.animationState.target={sx:A/2,sy:a+d/2,cropWidth:A,cropHeight:t,scaleRatio:(hA=(lA=this.animationState.target)==null?void 0:lA.scaleRatio)!=null?hA:1,scaleOffsetX:(oe=(MA=this.animationState.target)==null?void 0:MA.scaleOffsetX)!=null?oe:0,scaleOffsetY:(je=(fe=this.animationState.target)==null?void 0:fe.scaleOffsetY)!=null?je:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(l*d/A/t/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=1-this.animationState.target.scaleRatio,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio{A.log.error(o),A.destroy(new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(o.message||o)})),this.resolvePreditReady()})}init(A){return XA(this,null,function*(){var t,o,a;this.predictReady=new Promise(y=>{this.resolvePreditReady=y});let l=A.Wasm,d=this.context.ctx;if(A.color&&(this._color=A.color),A.mat4&&(this._mat4=A.mat4),A.postProcessing&&(this._postProcessing=A.postProcessing),this._enableFaceCentering=(t=A.enableFaceCentering)!=null&&t,this._enableEffectOptimization=(o=A.enableEffectOptimization)!=null&&o,this.wasm=new l.AllIn1(d),this.wasm.blurRadius=A.blurRadius||3,this.wasm.mirror=!!A.mirror,this.wasm.rotation=A.rotation||0,this.wasm.vbMode=A.bg==="blur"?1:A.bg instanceof HTMLImageElement?2:A.bg==="color"?3:0,this._onAbort=A.onAbort,A.bg||this.resolvePreditReady(),A.waterMark){let{x:y,y:S,width:L,height:V}=A.waterMark;this.wasm.setWaterMark(y,S,L,V)}if(A.beautyParams){let{beauty:y,brightness:S,ruddy:L}=A.beautyParams;this.wasm.setBeauty(y,S,L,A?.width,A?.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),d.uniform1i(d.getUniformLocation(this.program,"mask"),1),A.bg instanceof HTMLImageElement&&(d.uniform1i(d.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(A.bg)),A.waterMark&&(d.uniform1i(d.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(A.waterMark.image));let h=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=d.getUniformLocation(this.program,"u_textureMatrix"),d.uniformMatrix4fv(this._textureMatrixLocation,!1,h),this._offsetMatrixLocation=d.getUniformLocation(this.program,"u_offsetMatrix"),d.uniformMatrix4fv(this._offsetMatrixLocation,!1,h),this._colorLocation=d.getUniformLocation(this.program,"u_color"),d.uniform1i(d.getUniformLocation(this.program,"lastMask"),4),this._weixin){let y=this.context.createShader(d.FRAGMENT_SHADER,`#version 300 es +`))}removeBandwidthRestriction(t){return t.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(t){return t.replace(/urn:3gpp:video-orientation/,"")}connect(){return XA(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(t){throw this.closePeerConnection(!0),this.uninstallEvents(),t}})}exchangeSDP(){return XA(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(t){throw t}})}createOffer(){return XA(this,null,function*(){try{let t=yield this._peerConnection.createOffer(B8);yield this.setOffer(t),t.sdp&&this.updateSSRC(t.sdp)}catch(t){throw t}})}doExchangeSDP(){let t={command:c8,responseCommand:Qn.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof eM||this.localAuxVideoTrack instanceof eM,state:this._room.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(t.data.sdp)),this._signalChannel.sendWaitForResponse(t).then(o=>{let{code:a,message:l,data:d}=o.data;return a===0?this.acceptAnswer(d):this.checkPublishResultCode(a,l)})}setSDPDirection(t,o){let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"all",l=Qc(t);return l.media.forEach(d=>{(a==="all"||d.type===a)&&(d.direction=o)}),by(l)}acceptAnswer(t){return XA(this,null,function*(){var o,a,l,d,h;try{let y;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let L=((o=this._publishingLocalVideoTrack)==null?void 0:o.profile.bitrate)||((a=this.localMainVideoTrack)==null?void 0:a.profile.bitrate),V=((l=this._publishingLocalAudioTrack)==null?void 0:l.profile.bitrate)||((d=this.localMainAudioTrack)==null?void 0:d.profile.bitrate);if(L){let H=this._isPublishingAux?JA.AUXILIARY:JA.BIG;y=yield this.setBandwidth({bandwidth:L,type:JA.VIDEO,sdp:y,videoType:H})}V&&(y=yield this.setBandwidth({bandwidth:V,type:JA.AUDIO,sdp:y}))}if(y=this.removeVideoOrientation(t.sdp),(h=this._publishingLocalVideoTrack)!=null&&h.small){let{smallStreamConfig:L}=this._room;y=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||L.bitrate,type:JA.VIDEO,videoType:JA.SMALL,sdp:y})}let S={type:t.type,sdp:y};yield this.setAnswer(S),this._log.debug("accepted answer: ".concat(y))}catch(y){throw this._log.error("failed to accept remote answer ".concat(y)),y}})}sendMutedFlag(t){t===this.localAuxAudioTrack||t===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.send(g8,this._room.muteState))}getIsReconnecting(){return this._isReconnecting}reconnect(){return XA(this,null,function*(){if(!(UI(vX.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:P1,responseCommand:Qn.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch{let o=bp(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(o/1e3,"s")),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},o)}})}handleConnectionStateChange(t){t.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&F.emit(rA.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(t){try{Qc(t).media.forEach((o,a)=>{if(o.type===JA.AUDIO){let l=o.ssrcs&&o.ssrcs[0];l&&(this.ssrc.audio=Number(l.id))}else{if(this._sdpSemantics===p0&&o.ssrcGroups)return void o.ssrcGroups.forEach((d,h)=>{let y=Number(d.ssrcs.split(" ")[0]);h===0?this.ssrc.video=y:h===1&&(this.ssrc.small=y)});let l=o.ssrcs&&o.ssrcs[0];if(!l)return;switch(a){case 1:this.ssrc.video=Number(l.id);break;case 2:this.ssrc.small=Number(l.id);break;case 3:this.ssrc.auxiliary=Number(l.id)}}})}catch{}}getVideoTrackId(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:JA.VIDEO;if(this._peerConnection){let o=this._peerConnection.getSenders();if(t===JA.AUXILIARY&&o[3]&&o[3].track)return o[3].track.id;if(t===JA.VIDEO&&o[1]&&o[1].track)return o[1].track.id}if(this.localMainVideoTrack&&t===JA.VIDEO){let o=this.localMainVideoTrack.mediaTrack;if(o)return o.id}if(this.localAuxVideoTrack&&t===JA.AUXILIARY){let o=this.localAuxVideoTrack.mediaTrack;if(o)return o.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(t,o){if(t!==0)throw t===m0?(this._log.error(Cc.NOT_SUPPORTED_H264ENCODE),new li({code:mt.NOT_SUPPORTED_H264,message:sn({key:Go.NOT_SUPPORTED_H264ENCODE})})):new li({code:mt.UNKNOWN,message:sn({key:Go.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Qn.PUBLISH_RESULT,code:t,message:o}})})}};Qi([Xr(A=>function(){for(var t=arguments.length,o=new Array(t),a=0;a{let h=y=>{this._emitter.off("closed",h),d(new li({code:mt.API_CALL_ABORTED,message:sn({key:Go.CONNECTION_ABORTED,data:y})}))};this._emitter.on("closed",h),A.apply(this,o).then(l,d).finally(()=>{this._emitter.off("closed",h)})})})],V1.prototype,"publish"),Qi([wy(521715,!1)],V1.prototype,"unpublish"),Qi([Xv(am.prototype.afterConnect),Y5(am.prototype.beforeConnect)],V1.prototype,"connect");var H1=V1,cnA=class{constructor(A,t){this.room=A,Y(this,"_log"),Y(this,"_prevReportTime",0),Y(this,"_prevReport",{}),Y(this,"_prevStats",null),Y(this,"_prevEncoderImplementation",""),Y(this,"_prevAuxEncoderImpl",""),Y(this,"_prevQualityLimitationReason",""),Y(this,"_prevAuxQualityLimitationReason",""),Y(this,"_prevDecoderImplementationMap",new Map),Y(this,"_decodeMap",new Map),Y(this,"_prevQpSum",0),Y(this,"_prevAuxQpSum",0),Y(this,"totalBytesSent",0),Y(this,"totalBytesReceived",0),Y(this,"_spcStats",null),this._log=t}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(A){return XA(this,null,function*(){var t,o,a,l,d,h,y;let S={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},L=A.getPeerConnection(),V=A.getSSRC();if(L)try{if((this._spcStats||(yield L.getStats())).forEach(H=>{var lA,hA,MA,oe,fe,je,_e,vi,Fe,Dt,pi,Mi,Wo;let zo,vs;if(H.type==="outbound-rtp")if((H.mediaType||H.kind)===JA.VIDEO){if(H.ssrc===V.video?(zo=JA.VIDEO,vs=A.localMainVideoTrack):H.ssrc===V.small?zo=JA.SMALL:H.ssrc===V.auxiliary&&(vs=A.localAuxVideoTrack,zo=JA.AUXILIARY),!zo)return;S[zo].bytesSent=H.bytesSent,S[zo].packetsSent=H.packetsSent,S[zo].framesEncoded=H.framesEncoded,ze(H.keyFramesEncoded)||(S[zo].keyFramesEncoded=H.keyFramesEncoded),ze(H.nackCount)||(S[zo].nackCount=H.nackCount),ze(H.pliCount)||(S[zo].pliCount=H.pliCount),ze(H.retransmittedPacketsSent)||(S[zo].retransmittedPacketsSent=H.retransmittedPacketsSent),ze(H.totalEncodeTime)||(S[zo].totalEncodeTime=H.totalEncodeTime),ze(H.totalPacketSendDelay)||(S[zo].totalPacketSendDelay=H.totalPacketSendDelay);let Zo=0;if(!ze(H.qpSum)&&!ze(H.framesEncoded)&&H.framesEncoded>0){let Vn=H.qpSum,Dg=H.framesEncoded,wa=zo===JA.VIDEO?this._prevQpSum:this._prevAuxQpSum,fu=zo===JA.VIDEO?((hA=(lA=A.localMainVideoTrack)==null?void 0:lA.stat)==null?void 0:hA.framesEncoded)||0:((oe=(MA=A.localAuxVideoTrack)==null?void 0:MA.stat)==null?void 0:oe.framesEncoded)||0;if(Dg>fu&&Vn>wa){let _L=Vn-wa,__=Dg-fu;Zo=Math.round(_L/__),Zo>35&&A.videoCodec==="h264"&&this._log.warn("".concat(zo===JA.AUXILIARY?"aux ":"","video encoder QP is high: ").concat(Zo,", resolution: ").concat(H.frameWidth,"x").concat(H.frameHeight,", codec: ").concat(A.videoCodec,", "))}zo===JA.VIDEO?this._prevQpSum=Vn:zo===JA.AUXILIARY&&(this._prevAuxQpSum=Vn)}if(!ze(H.encoderImplementation)&&(zo===JA.VIDEO&&this._prevEncoderImplementation!==H.encoderImplementation||zo===JA.AUXILIARY&&this._prevAuxEncoderImpl!==H.encoderImplementation)){let Vn=2,Dg=this._prevEncoderImplementation;zo===JA.AUXILIARY&&(Vn=7,Dg=this._prevAuxEncoderImpl),F.emit("262",{userId:A.userId,streamType:Vn,prevImplementation:Dg,implementation:H.encoderImplementation,codec:A.videoCodec,isHWCodec:H.powerEfficientEncoder}),this[zo===JA.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=H.encoderImplementation,vs?.log.info("encoderImplementation change to ".concat(H.encoderImplementation,"(").concat(A.videoCodec,") HWEncoder: ").concat(H.powerEfficientEncoder))}H.ssrc===V.video?!ze(H.qualityLimitationReason)&&H.bytesSent!==0&&this._prevQualityLimitationReason!==H.qualityLimitationReason&&(vs?.log.info("qualityLimitationReason change to ".concat(H.qualityLimitationReason)),F.emit("263",{userId:A.userId,reason:H.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(fe=A.localMainVideoTrack)==null?void 0:fe.isQosClearFirst}),this._prevQualityLimitationReason=H.qualityLimitationReason):H.ssrc===V.auxiliary&&!ze(H.qualityLimitationReason)&&H.bytesSent!==0&&this._prevAuxQualityLimitationReason!==H.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(H.qualityLimitationReason)),F.emit("263",{userId:A.userId,reason:H.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(je=A.localAuxVideoTrack)==null?void 0:je.isQosClearFirst}),this._prevAuxQualityLimitationReason=H.qualityLimitationReason)}else S.audio.bytesSent=H.bytesSent,S.audio.packetsSent=H.packetsSent;else if(H.type==="candidate-pair")Ov(H)&&(this.totalBytesSent=H.bytesSent,Ys(H.currentRoundTripTime)&&(S.rtt=Math.floor(1e3*H.currentRoundTripTime)));else if(H.type==="media-source"){if(H.kind===JA.AUDIO)S.audio.audioLevel=H.audioLevel||0,S.audio.totalAudioEnergy=H.totalAudioEnergy||0,H.echoReturnLoss,ze((Fe=(vi=(_e=A.localMainAudioTrack)==null?void 0:_e.sourceTrack)==null?void 0:vi.stats)==null?void 0:Fe.deliveredFramesDuration)?H.totalSamplesDuration&&(S.audio.totalSamplesDuration=H.totalSamplesDuration):S.audio.totalSamplesDuration=A.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(H.kind===JA.VIDEO)if(H.trackIdentifier===A.getVideoTrackId(JA.VIDEO))if((Mi=(pi=(Dt=A.localMainVideoTrack)==null?void 0:Dt.sourceTrack)==null?void 0:pi.stats)!=null&&Mi.deliveredFrames){let{deliveredFrames:Zo}=A.localMainVideoTrack.sourceTrack.stats;S.video.framesCaptured=Zo,A.localMainVideoTrack.stat.framesCaptured&&A.localMainVideoTrack.stat.framesCaptured>0&&Zo>=A.localMainVideoTrack.stat.framesCaptured?S.video.fpsCapture=Math.floor((Zo-A.localMainVideoTrack.stat.framesCaptured)/this.statInterval):S.video.fpsCapture=H.framesPerSecond}else S.video.fpsCapture=H.framesPerSecond;else H.trackIdentifier===A.getVideoTrackId(JA.AUXILIARY)?S.auxiliary.fpsCapture=H.framesPerSecond:S.small.fpsCapture=H.framesPerSecond}if(!ze(H.audioLevel)&&(Wo=A.localMainAudioTrack)!=null&&Wo.mediaTrack&&H.trackIdentifier===A.localMainAudioTrack.mediaTrack.id&&(S.audio.audioLevel=H.audioLevel||0),!ze(H.frameWidth)){let Zo=JA.SMALL;H.trackIdentifier===A.getVideoTrackId(JA.VIDEO)||H.ssrc===V.video?Zo=JA.VIDEO:(H.trackIdentifier===A.getVideoTrackId(JA.AUXILIARY)||H.ssrc===V.auxiliary)&&(Zo=JA.AUXILIARY),S[Zo].frameWidth=H.frameWidth,S[Zo].frameHeight=H.frameHeight,S[Zo].framesSent=H.framesSent}}),A.localMainAudioTrack||A.getRoom().capturedLocalMainAudioTrack){let H=A.localMainAudioTrack||A.getRoom().capturedLocalMainAudioTrack;if(H){let lA=H.getInternalAudioLevel(),hA=H.getInternalAudioLevelAfter3A();S.audio.audioCaptureEnergyAfter3a=hA,S.audio.micAudioLevel=lA,S.audio.audioLevel===0&&A.localMainAudioTrack&&(S.audio.audioLevel=hA??lA),!A.localMainAudioTrack&&!ze((o=(t=H.sourceTrack)==null?void 0:t.stats)==null?void 0:o.deliveredFramesDuration)&&(S.audio.totalSamplesDuration=H.sourceTrack.stats.deliveredFramesDuration/1e3)}}if(!A.localMainVideoTrack&&A.getRoom().capturedLocalMainVideoTrack){let H=A.getRoom().capturedLocalMainVideoTrack;if((l=(a=H?.sourceTrack)==null?void 0:a.stats)!=null&&l.deliveredFrames){let{deliveredFrames:lA}=H.sourceTrack.stats;S.video.framesCaptured=lA,H.stat.framesCaptured&&H.stat.framesCaptured>0&&lA>=H.stat.framesCaptured&&(S.video.fpsCapture=Math.floor((lA-H.stat.framesCaptured)/this.statInterval)),H.stat.framesCaptured=lA}}if(!A.localAuxVideoTrack&&A.getRoom().capturedLocalAuxVideoTrack){let H=A.getRoom().capturedLocalAuxVideoTrack;if((h=(d=H?.sourceTrack)==null?void 0:d.stats)!=null&&h.deliveredFrames){let{deliveredFrames:lA}=H.sourceTrack.stats;S.auxiliary.framesCaptured=lA,H.stat.framesCaptured&&H.stat.framesCaptured>0&&lA>=H.stat.framesCaptured&&(S.auxiliary.fpsCapture=Math.floor((lA-H.stat.framesCaptured)/this.statInterval)),H.stat.framesCaptured=lA}}this.totalBytesSent||(this.totalBytesSent+=S.audio.bytesSent+S.video.bytesSent+S.auxiliary.bytesSent),Object.keys(S).forEach(H=>{H===JA.AUDIO?(A.localMainAudioTrack&&(A.localMainAudioTrack.stat=S[H]),A.localAuxAudioTrack&&(A.localAuxAudioTrack.stat=S[H])):H===JA.VIDEO?A.localMainVideoTrack&&(A.localMainVideoTrack.stat=S[H]):H===JA.AUXILIARY&&A.localAuxVideoTrack&&(A.localAuxVideoTrack.stat=S[H])})}catch(H){this._log.warn("failed to getStats on sender connection ".concat(H))}return S.rtt===0&&(S.rtt=((y=this.room.networkQuality)==null?void 0:y.uplinkRTT)||0),S})}getReceiverStats(A){return XA(this,null,function*(){var t,o,a;let l={tinyId:A.tinyId,userId:A.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,avSyncDelay:0,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""}},d=A.getPeerConnection();if(d)try{let{ssrc:h}=A,{muteState:y,subscribeState:S}=A;(this._spcStats||(yield d.getStats())).forEach(H=>{var lA,hA;if(H.type==="codec"&&this._decodeMap.set(H.id,H),H.type==="inbound-rtp"){let MA=(H.mediaType||H.kind)===JA.AUDIO;if(MA){if(H.ssrc!==h.audio||!y.hasAudio)return;l.audio.packetsReceived=H.packetsReceived,l.audio.bytesReceived=H.bytesReceived,l.audio.packetsLost=H.packetsLost,H.insertedSamplesForDeceleration&&(l.audio.insertedSamplesForDeceleration=H.insertedSamplesForDeceleration),H.removedSamplesForAcceleration&&(l.audio.removedSamplesForAcceleration=H.removedSamplesForAcceleration),H.totalSamplesDuration&&(l.audio.totalSamplesDuration=H.totalSamplesDuration),H.totalSamplesReceived&&(l.audio.totalSamplesReceived=H.totalSamplesReceived),H.concealedSamples&&(l.audio.concealedSamples=H.concealedSamples),H.silentConcealedSamples&&(l.audio.silentConcealedSamples=H.silentConcealedSamples);let{remoteAudioTrack:oe}=A;oe.stat.packetsReceived=H.packetsReceived,oe.stat.bytesReceived=H.bytesReceived,oe.stat.packetsLost=H.packetsLost,l.audio.p2pDelay=oe.stat.end2EndDelay,l.hasAudio=!0}else{if(gr&&H.bytesReceived===0)return;let oe;H.ssrc===h.video&&y.hasVideo&&(l.video.packetsReceived=H.packetsReceived,l.video.bytesReceived=H.bytesReceived,l.video.packetsLost=H.packetsLost,l.video.framesReceived=H.framesReceived,l.video.framesDecoded=H.framesDecoded,l.video.fpsDecoded=H.framesPerSecond,l.hasVideo=!0,A.videoCodec=fl[(lA=this._decodeMap.get(H.codecId))==null?void 0:lA.mimeType.split("/")[1]]||"h264",l.video.codec=A.videoCodec,oe=A.remoteVideoTrack,y.hasSmall&&S.smallVideo&&(l.isSmallSubscribed=!0),H.decoderImplementation&&(!this._prevDecoderImplementationMap.has(l.userId)||this._prevDecoderImplementationMap.get(l.userId)!==H.decoderImplementation)&&(oe.log.info("decoderImplementation change to ".concat(H.decoderImplementation,"(").concat(A.videoCodec,") HWDecoder: ").concat(H.powerEfficientDecoder)),F.emit("262",{userId:this.room.userId,remoteUserId:l.userId,prevImplementation:this._prevDecoderImplementationMap.get(l.userId),implementation:H.decoderImplementation,codec:A.videoCodec,isHWCodec:H.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(l.userId,H.decoderImplementation)),ze(H.keyFramesDecoded)||oe.updateKeyFramesDecoded(H.keyFramesDecoded)),H.ssrc===h.auxiliary&&y.hasAuxiliary&&(l.auxiliary.packetsReceived=H.packetsReceived,l.auxiliary.bytesReceived=H.bytesReceived,l.auxiliary.packetsLost=H.packetsLost,l.auxiliary.framesReceived=H.framesReceived,l.auxiliary.framesDecoded=H.framesDecoded,l.auxiliary.fpsDecoded=H.framesPerSecond,oe=A.remoteAuxiliaryTrack,l.auxiliary.p2pDelay=oe.stat.end2EndDelay,l.hasAuxiliary=!0,l.video.codec=((hA=this._decodeMap.get(H.codecId))==null?void 0:hA.mimeType.split("/")[1].toLowerCase())||"h264",ze(H.keyFramesDecoded)||oe.updateKeyFramesDecoded(H.keyFramesDecoded)),oe&&(oe.stat.packetsReceived=H.packetsReceived,oe.stat.bytesReceived=H.bytesReceived,oe.stat.packetsLost=H.packetsLost,oe.stat.framesReceived=H.framesReceived,oe.stat.framesDecoded=H.framesDecoded,H.jitterBufferDelay&&(oe.stat.jitterBufferDelay=Math.floor(H.jitterBufferDelay/H.jitterBufferEmittedCount*1e3)),l.video.p2pDelay=oe.stat.end2EndDelay)}H.jitterBufferDelay&&(MA?(l.audio.totalJitter=H.jitterBufferDelay,l.audio.totalJitterCount=H.jitterBufferEmittedCount,l.audio.estimatedPlayoutTimestamp=H.estimatedPlayoutTimestamp):H.ssrc===h.video&&y.hasVideo?(l.video.totalJitter=H.jitterBufferDelay,l.video.totalJitterCount=H.jitterBufferEmittedCount,l.video.estimatedPlayoutTimestamp=H.estimatedPlayoutTimestamp):H.ssrc===h.auxiliary&&y.hasAuxiliary&&(l.auxiliary.totalJitter=H.jitterBufferDelay,l.auxiliary.totalJitterCount=H.jitterBufferEmittedCount))}else H.type==="candidate-pair"&&Ov(H)&&(this.totalBytesReceived=H.bytesReceived,Ys(H.currentRoundTripTime)&&(l.rtt=Math.floor(1e3*H.currentRoundTripTime)));ze(H.frameWidth)||((H.trackIdentifier===A.getMainStreamVideoTrackId()||H.ssrc===h.video)&&(l.video.frameWidth=H.frameWidth,l.video.frameHeight=H.frameHeight,A.remoteVideoTrack.stat.frameWidth=H.frameWidth,A.remoteVideoTrack.stat.frameHeight=H.frameHeight),(H.trackIdentifier===A.getAuxStreamVideoTrackId()||H.ssrc===h.auxiliary)&&(l.auxiliary.frameWidth=H.frameWidth,l.auxiliary.frameHeight=H.frameHeight,A.remoteAuxiliaryTrack.stat.frameWidth=H.frameWidth,A.remoteAuxiliaryTrack.stat.frameHeight=H.frameHeight)),!ze(H.audioLevel)&&A.muteState.audioAvailable&&A.remoteAudioTrack.mediaTrack&&H.trackIdentifier===A.remoteAudioTrack.mediaTrack.id&&(l.audio.audioLevel=H.audioLevel||0,l.audio.totalAudioEnergy=H.totalAudioEnergy||0)}),l.audio.audioLevel===0&&A.muteState.audioAvailable&&(l.audio.audioLevel=A.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=l.audio.bytesReceived+l.video.bytesReceived+l.auxiliary.bytesReceived),ze((t=A.remoteVideoTrack.player.stat)==null?void 0:t.fps)||(l.video.fpsRender=A.remoteVideoTrack.player.stat.fps),ze((o=A.remoteAuxiliaryTrack.player.stat)==null?void 0:o.fps)||(l.auxiliary.fpsRender=A.remoteAuxiliaryTrack.player.stat.fps);let L=l.audio.estimatedPlayoutTimestamp,V=l.video.estimatedPlayoutTimestamp;if(L&&V&&A.remoteAudioTrack.isAvailable&&A.remoteVideoTrack.isAvailable){let H=V-L;Math.abs(H)<=1e4&&(l.avSyncDelay=H,Math.abs(H)>150&&this._log.warn("av sync delay",H))}}catch(h){this._log.warn("failed to getStats on receiver connection ".concat(h))}return l.rtt===0&&(l.rtt=((a=this.room.networkQuality)==null?void 0:a.uplinkRTT)||0),l})}getStats(A,t){return XA(this,null,function*(){let o,a={},l=[];if(this.room.singlePC){let d=this.room.singlePC.getPeerConnection();if(!d)return{senderStats:a,receiverStats:l};let h=Oo(),y=yield d.getStats(),S=Oo();S-h>2e3&&this._log.warn("getStats cost ".concat(S-h,"ms"));let L=[],V=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec","media-playout"]);y.forEach(H=>V.has(H.type)&&L.push(H)),this._spcStats=L}A&&(a=yield this.getSenderStats(A));for(let[d,h]of t){let y=yield this.getReceiverStats(h);y&&l.push(y)}return t.size&&(o=this.getMediaPlayoutStats(this._spcStats)),{senderStats:a,receiverStats:l,mediaPlayoutStats:o}})}getDifferenceValue(A,t){if(sm(A))return t;let o=t-A;return o<0?0:o}prepareReport(A){let{stats:t,report:o,freezeMap:a,uplinkConnection:l}=A;var d,h,y,S,L,V,H,lA,hA;if(!sm(t.senderStats)){let Fe={uint32_audio_level:t.senderStats.audio.audioLevel*sd,uint32_audio_energy:1e6*(t.senderStats.audio.totalAudioEnergy||0),uint32_audio_codec_bitrate:t.senderStats.audio.bytesSent};t.senderStats.audio.micAudioLevel&&(Fe.uint32_mic_audio_level=t.senderStats.audio.micAudioLevel*sd),ze(t.senderStats.audio.audioCaptureEnergyAfter3a)||(Fe.uint32_audio_capture_energy_after3a=t.senderStats.audio.audioCaptureEnergyAfter3a*sd),t.senderStats.audio.totalSamplesDuration&&(o.msg_device_info.uint32_audio_capture_cost=t.senderStats.audio.totalSamplesDuration);let Dt=[];if(t.senderStats.video.bytesSent){let Mi={uint32_video_stream_type:2,uint32_video_codec_fps:t.senderStats.video.framesSent,uint32_video_capture_fps:t.senderStats.video.fpsCapture,uint32_video_width:t.senderStats.video.frameWidth,uint32_video_height:t.senderStats.video.frameHeight,uint32_video_codec_bitrate:t.senderStats.video.bytesSent,uint32_video_enc_fps:t.senderStats.video.framesEncoded,uint32_key_frame_count:t.senderStats.video.keyFramesEncoded,uint32_nack_count:t.senderStats.video.nackCount,uint32_pli_count:t.senderStats.video.pliCount,uint32_encode_cost:1e3*(t.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.video.retransmittedPacketsSent};Dt.push(Mi)}if(t.senderStats.small.bytesSent){let Mi={uint32_video_stream_type:3,uint32_video_codec_fps:t.senderStats.small.framesSent||0,uint32_video_capture_fps:t.senderStats.small.fpsCapture||0,uint32_video_width:t.senderStats.small.frameWidth||0,uint32_video_height:t.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.small.bytesSent,uint32_video_enc_fps:t.senderStats.small.framesEncoded||0,uint32_key_frame_count:t.senderStats.small.keyFramesEncoded,uint32_nack_count:t.senderStats.small.nackCount,uint32_pli_count:t.senderStats.small.pliCount,uint32_encode_cost:1e3*(t.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.small.retransmittedPacketsSent};Dt.push(Mi)}if(t.senderStats.auxiliary.bytesSent){let Mi={uint32_video_stream_type:7,uint32_video_codec_fps:t.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:t.senderStats.auxiliary.fpsCapture||0,uint32_video_width:t.senderStats.auxiliary.frameWidth||0,uint32_video_height:t.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:t.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:t.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:t.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:t.senderStats.auxiliary.nackCount,uint32_pli_count:t.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(t.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(t.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:t.senderStats.auxiliary.retransmittedPacketsSent};Dt.push(Mi)}let pi={uint32_bitrate:0,uint32_lost:0,uint32_rtt:t.senderStats.rtt};o.msg_up_stream_info={msg_audio_status:Fe,msg_video_status:Dt,msg_network_status:pi}}let{statInterval:MA}=this;o.msg_down_stream_info=[],t.receiverStats.forEach(Fe=>{let Dt={msg_user_info:{str_identifier:Fe.userId,uint64_tinyid:Fe.tinyId},msg_network_status:{uint32_rtt:Fe.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(Fe.hasAudio){let pi={uint32_audio_p2p_delay:Fe.audio.p2pDelay,uint32_audio_cache_ms:Fe.audio.totalJitter,uint32_audio_cache_ms_count:Fe.audio.totalJitterCount,uint32_audio_codec_bitrate:Fe.audio.bytesReceived,uint32_audio_total_bitrate:Fe.audio.bytesReceived,uint32_audio_level:1e8*Fe.audio.audioLevel,uint32_audio_energy:1e6*Fe.audio.totalAudioEnergy,uint32_audio_receive:Fe.audio.packetsReceived,uint32_audio_origin_lost:Fe.audio.packetsLost};Dt.msg_audio_status=pi}if(Fe.hasVideo){let pi=a.get("".concat(Fe.userId,"_").concat(h0)),Mi=pi?pi.duration:0,Wo={uint32_video_stream_type:Fe.isSmallSubscribed?3:2,uint32_video_receive_fps:Fe.video.framesReceived,uint32_video_width:Fe.video.frameWidth,uint32_video_height:Fe.video.frameHeight,uint32_video_codec_bitrate:Fe.video.bytesReceived,uint32_video_receive:Fe.video.packetsReceived,uint32_video_origin_lost:Fe.video.packetsLost,uint32_video_block_time:Mi,uint32_video_dec_fps:Fe.video.framesDecoded,uint32_video_codec_fps:Fe.video.fpsRender,uint32_video_cache_ms:Fe.video.totalJitter,uint32_video_cache_ms_count:Fe.video.totalJitterCount,uint32_video_p2p_delay:Fe.video.p2pDelay,uint32_video_codec:Fe.video.codec,int32_video_audio_relative_delay:Fe.avSyncDelay+5e3};Dt.msg_video_status.push(Wo)}if(Fe.hasAuxiliary){let pi=a.get("".concat(Fe.userId,"_").concat(Pb)),Mi=pi?pi.duration:0,Wo={uint32_video_stream_type:7,uint32_video_receive_fps:Fe.auxiliary.framesReceived,uint32_video_width:Fe.auxiliary.frameWidth,uint32_video_height:Fe.auxiliary.frameHeight,uint32_video_codec_bitrate:Fe.auxiliary.bytesReceived,uint32_video_receive:Fe.auxiliary.packetsReceived+Fe.auxiliary.packetsLost,uint32_video_origin_lost:Fe.auxiliary.packetsLost,uint32_video_block_time:Mi,uint32_video_dec_fps:Fe.auxiliary.framesDecoded,uint32_video_codec_fps:Fe.video.fpsRender,uint32_video_cache_ms:Fe.auxiliary.totalJitter,uint32_video_cache_ms_count:Fe.auxiliary.totalJitterCount,uint32_video_p2p_delay:Fe.auxiliary.p2pDelay,uint32_video_codec:Fe.video.codec};Dt.msg_video_status.push(Wo)}o.msg_down_stream_info.push(Dt)}),t.mediaPlayoutStats&&!sm(t.mediaPlayoutStats)&&(t.mediaPlayoutStats.synthesizedSamplesDuration*=1e3,t.mediaPlayoutStats.totalSamplesDuration*=1e3);let oe=this._prevReport,fe=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(o)),this._prevStats=JSON.parse(JSON.stringify(t)),o.msg_up_stream_info.msg_audio_status&&oe.msg_up_stream_info.msg_audio_status){let Fe=oe.msg_up_stream_info.msg_audio_status,Dt=o.msg_up_stream_info.msg_audio_status;if(Fe.uint32_audio_codec_bitrate===0)Dt.uint32_audio_codec_bitrate=0;else{let pi=this.getDifferenceValue(Fe.uint32_audio_codec_bitrate,Dt.uint32_audio_codec_bitrate);Dt.uint32_audio_codec_bitrate=Math.round(8*pi/MA),o.msg_up_stream_info.msg_network_status.uint32_bitrate+=Dt.uint32_audio_codec_bitrate}(d=oe.msg_device_info)!=null&&d.uint32_audio_capture_cost?(o.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(oe.msg_device_info.uint32_audio_capture_cost,o.msg_device_info.uint32_audio_capture_cost)/MA),o.msg_device_info.uint32_audio_capture_cost>0&&((y=l?.localMainAudioTrack)==null||y.updateAfter3aSilenceStartTime((h=t.senderStats.audio.audioCaptureEnergyAfter3a)!=null?h:t.senderStats.audio.micAudioLevel))):delete o.msg_device_info.uint32_audio_capture_cost}let je=oe.msg_up_stream_info.msg_video_status;o.msg_up_stream_info.msg_video_status.forEach(Fe=>{let Dt=je.find(vs=>vs.uint32_video_stream_type===Fe.uint32_video_stream_type);if(!Dt||Dt.uint32_video_codec_bitrate===0)return Fe.uint32_video_codec_bitrate=0,Fe.uint32_video_enc_fps=0,void(Fe.uint32_video_codec_fps=0);let pi=0,Mi=0,Wo=0;Dt&&Fe.uint32_video_codec_bitrate>=Dt.uint32_video_codec_bitrate&&(pi=Dt.uint32_video_codec_bitrate,Mi=Dt.uint32_video_enc_fps,Wo=Dt.uint32_video_codec_fps);let zo=this.getDifferenceValue(pi,Fe.uint32_video_codec_bitrate);Fe.uint32_video_codec_bitrate=Math.round(8*zo/MA),o.msg_up_stream_info.msg_network_status.uint32_bitrate+=Fe.uint32_video_codec_bitrate,Fe.uint32_video_enc_fps=Math.round(this.getDifferenceValue(Mi,Fe.uint32_video_enc_fps)/MA),Fe.uint32_video_codec_fps=Math.round(this.getDifferenceValue(Wo,Fe.uint32_video_codec_fps)/MA),Dt.uint32_video_width===0&&Dt.uint32_video_height===0&&Dt.uint32_video_codec_fps===0&&(Fe.uint32_video_codec_fps=Fe.uint32_video_enc_fps),ze(Dt.uint32_key_frame_count)||(Fe.uint32_key_frame_count=Math.round(this.getDifferenceValue(Dt.uint32_key_frame_count,Fe.uint32_key_frame_count))),ze(Dt.uint32_nack_count)||(Fe.uint32_nack_count=Math.round(this.getDifferenceValue(Dt.uint32_nack_count,Fe.uint32_nack_count))),ze(Dt.uint32_pli_count)||(Fe.uint32_pli_count=Math.round(this.getDifferenceValue(Dt.uint32_pli_count,Fe.uint32_pli_count))),ze(Dt.uint32_video_arq_packets)||(Fe.uint32_video_arq_packets=Math.round(this.getDifferenceValue(Dt.uint32_video_arq_packets,Fe.uint32_video_arq_packets))),ze(Dt.uint32_encode_cost)||(Fe.uint32_encode_cost=Math.round(this.getDifferenceValue(Dt.uint32_encode_cost,Fe.uint32_encode_cost)/MA)),ze(Dt.uint32_send_packet_cost)||(Fe.uint32_send_packet_cost=Math.round(this.getDifferenceValue(Dt.uint32_send_packet_cost,Fe.uint32_send_packet_cost)/MA))});let _e=oe.msg_down_stream_info;o.msg_down_stream_info=o.msg_down_stream_info.filter(Fe=>_e.find(Dt=>Dt.msg_user_info.uint64_tinyid===Fe.msg_user_info.uint64_tinyid));let vi=o.msg_down_stream_info;if(vi.forEach(Fe=>{let Dt=_e.find(pi=>pi.msg_user_info.uint64_tinyid===Fe.msg_user_info.uint64_tinyid);if(sm(Fe.msg_audio_status)||sm(Dt.msg_audio_status))Fe.msg_audio_status={};else{let pi=Fe.msg_audio_status,Mi=Dt.msg_audio_status,Wo=this.getDifferenceValue(Mi.uint32_audio_cache_ms_count,pi.uint32_audio_cache_ms_count);delete pi.uint32_audio_cache_ms_count,pi.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(Mi.uint32_audio_cache_ms,pi.uint32_audio_cache_ms)/Wo)||0;let zo=this.room.remotePublishedUserMap.get(Fe.msg_user_info.str_identifier);zo&&(zo.remoteAudioTrack.stat.jitterBufferDelay=pi.uint32_audio_cache_ms),pi.uint32_audio_origin_lost=this.getDifferenceValue(Mi.uint32_audio_origin_lost,pi.uint32_audio_origin_lost),pi.uint32_audio_receive=this.getDifferenceValue(Mi.uint32_audio_receive,pi.uint32_audio_receive),pi.uint32_audio_receive+=pi.uint32_audio_origin_lost;let vs=this.getDifferenceValue(Mi.uint32_audio_codec_bitrate,pi.uint32_audio_codec_bitrate);pi.uint32_audio_codec_bitrate=Math.round(8*vs/MA),pi.uint32_audio_total_bitrate=Math.round(8*vs/MA)}if(Fe.msg_video_status&&Dt.msg_video_status){let pi=Dt.msg_video_status;Fe.msg_video_status=Fe.msg_video_status.filter(Mi=>pi.find(Wo=>Wo.uint32_video_stream_type===Mi.uint32_video_stream_type)),Fe.msg_video_status.forEach(Mi=>{let Wo=pi.find(__=>__.uint32_video_stream_type===Mi.uint32_video_stream_type),zo=Wo.uint32_video_receive,vs=Wo.uint32_video_origin_lost,Zo=Wo.uint32_video_codec_bitrate,Vn=Wo.uint32_video_receive_fps,Dg=Wo.uint32_video_dec_fps;Mi.uint32_video_origin_lost=this.getDifferenceValue(vs,Mi.uint32_video_origin_lost),Mi.uint32_video_receive=this.getDifferenceValue(zo,Mi.uint32_video_receive)+Mi.uint32_video_origin_lost;let wa=this.getDifferenceValue(Zo,Mi.uint32_video_codec_bitrate);Mi.uint32_video_codec_bitrate=Math.round(8*wa/MA);let fu=this.getDifferenceValue(Vn,Mi.uint32_video_receive_fps);Mi.uint32_video_receive_fps=Math.round(fu/MA),Mi.uint32_video_dec_fps=Math.round(this.getDifferenceValue(Dg,Mi.uint32_video_dec_fps)/MA);let _L=this.getDifferenceValue(Wo.uint32_video_cache_ms_count,Mi.uint32_video_cache_ms_count);delete Mi.uint32_video_cache_ms_count,Mi.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Wo.uint32_video_cache_ms,Mi.uint32_video_cache_ms)/_L)||0})}}),!ze((S=fe?.mediaPlayoutStats)==null?void 0:S.totalSamplesDuration)&&!ze((L=t.mediaPlayoutStats)==null?void 0:L.totalSamplesDuration)){let Fe=2*Math.floor(this.getDifferenceValue((V=fe?.mediaPlayoutStats)==null?void 0:V.synthesizedSamplesDuration,(H=t.mediaPlayoutStats)==null?void 0:H.synthesizedSamplesDuration)/MA),Dt=2*Math.floor(this.getDifferenceValue((lA=fe?.mediaPlayoutStats)==null?void 0:lA.totalSamplesDuration,(hA=t.mediaPlayoutStats)==null?void 0:hA.totalSamplesDuration)/MA);o.msg_device_info.uint32_audio_play_cost=Dt-Fe}return fe&&t.receiverStats.forEach(Fe=>{if(Fe.audio.concealedSamples&&Fe.audio.totalSamplesReceived){let Dt=fe.receiverStats.find(pi=>pi.userId===Fe.userId);if(Dt&&Dt.audio.concealedSamples&&Dt.audio.totalSamplesReceived){let pi=(Fe.audio.silentConcealedSamples||0)-(Dt.audio.silentConcealedSamples||0),Mi=Fe.audio.concealedSamples-Dt.audio.concealedSamples,Wo=Fe.audio.totalSamplesReceived-Dt.audio.totalSamplesReceived,zo=Math.floor((Mi-pi)/Wo*1e3*MA);if(zo>1e3*MA/5){let vs=vi.find(Zo=>Zo.msg_user_info.str_identifier===Fe.userId);vs&&(vs.msg_audio_status.uint32_audio_block_time=zo)}}}}),o.msg_down_stream_info.forEach(Fe=>{Fe.msg_video_status.forEach(Dt=>{Dt.uint32_video_codec_bitrate===0&&Dt.uint32_video_receive_fps===0&&(Dt.uint32_video_width=0,Dt.uint32_video_height=0)})}),o}getStatsReport(A){return XA(this,arguments,function(t){var o=this;let{uplinkConnection:a,downlinkConnections:l,freezeMap:d}=t;return function*(){let h={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_capture_energy_after3a:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0,uint32_video_codec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},y=yield o.getStats(a,l);return JSON.stringify(o._prevReport)==="{}"&&(o._prevReport=JSON.parse(JSON.stringify(h))),o.prepareReport({stats:y,report:h,freezeMap:d,uplinkConnection:a}),o._prevReportTime=Date.now(),h}()})}getMediaPlayoutStats(A){let t;if(ka(A)){for(let o of A)if(o.type==="media-playout"){let{synthesizedSamplesDuration:a,totalSamplesDuration:l}=o;t={synthesizedSamplesDuration:a,totalSamplesDuration:l};break}return t}}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map,[this.room.localMainVideoTrack,this.room.capturedLocalMainVideoTrack,this.room.localAuxVideoTrack,this.room.capturedLocalAuxVideoTrack].forEach(A=>{A!=null&&A.stat&&(A.stat.framesCaptured=0)})}},lnA=dc($l());function InA(A){return new Promise(t=>XA(null,null,function*(){let o=setTimeout(()=>{t({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),a=Date.now(),l="https://".concat(A,"/?t=").concat(a);try{yield fetch(l)}catch{}clearTimeout(o);let d=function(h){let y={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let S=performance.getEntriesByType("resource").reverse();for(let L of S)if(L.name===h){let V=Math.round(L.duration),H=Math.max(Math.round(L.domainLookupStart-L.startTime),0),lA=L.redirectStart>0?Math.max(Math.round(L.redirectEnd-L.redirectStart),0):0,hA=L.fetchStart>0?Math.max(Math.round(L.domainLookupStart-L.fetchStart),0):0,MA=Math.round(L.domainLookupEnd-L.domainLookupStart),oe=Math.round(L.requestStart-L.secureConnectionStart),fe=Math.round(L.secureConnectionStart-L.connectStart),je=Math.round(L.responseStart-L.requestStart),_e=Math.round(L.responseEnd-(L.responseStart||L.startTime));y=So(Di({},y),{totalCost:V,local:H,redirect:lA,httpCache:hA,dns:MA,tcp:fe,tls:oe,request:je,response:_e});break}}catch{}return y}(l);d.totalCost===0&&(d.totalCost=Date.now()-a),t(d)}))}var J1=class P_ extends lnA.default{constructor(t){let{signalChannel:o,room:a}=t;super(),Y(this,"_room"),Y(this,"_signalChannel"),Y(this,"_log"),Y(this,"uplinkRTT",0),Y(this,"uplinkLoss",0),Y(this,"downlinkRTT",0),Y(this,"downlinkLoss",0),Y(this,"pingResults",{}),Y(this,"_downlinkPrevStatMap",new Map),Y(this,"_downlinkLossAndRTTMap",new Map),Y(this,"_interval",-1),Y(this,"_uplinkNetworkQuality",0),Y(this,"_downlinkNetworkQuality",0),Y(this,"_uplinkQualityHistory",[]),Y(this,"_downlinkQualityHistory",[]),this._room=a,this._signalChannel=o,this._log=pA.createLogger({parent:a.getLogger(),id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(t){t!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(t,", rtt: ").concat(this.uplinkRTT,", loss: ").concat(this.uplinkLoss," ws-rtt: ").concat(this._signalChannel.rtt)),this._uplinkNetworkQuality=t,this._uplinkQualityHistory.push(t),this._uplinkQualityHistory.length>P_.HISTORY_SIZE&&this._uplinkQualityHistory.shift()}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(t){if(t!==this._downlinkNetworkQuality){let{rtt:o,loss:a}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(t,", rtt: ").concat(o,", loss: ").concat(a," ws-rtt: ").concat(this._signalChannel.rtt))}this._downlinkNetworkQuality=t,this._downlinkQualityHistory.push(t),this._downlinkQualityHistory.length>P_.HISTORY_SIZE&&this._downlinkQualityHistory.shift()}initialize(){this._signalChannel.on(Qn.UPLINK_NETWORK_STATS,t=>{this.handleUplinkNetworkQuality(t)}),this._signalChannel.on(Yj,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(t){var o,a;if(t.data.code!==0)return;let l=t.data.data;if(l.delay&&this.updateDelay(l.delay),this._room.signalChannel&&l.wsRtt&&(this._room.signalChannel.rtt=l.wsRtt),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this.uplinkLoss=0,void(this.uplinkRTT=0);let d=(a=(o=this._room)==null?void 0:o.uplinkConnection)==null?void 0:a.getPeerConnection();if(d&&this.isPeerConnectionDisconnected(d))return this.uplinkNetworkQuality=6,this.uplinkLoss=0,void(this.uplinkRTT=0);let h=l.expectAudPkg+l.expectVidPkg,y=l.recvAudPkg+l.recvVidPkg,S=h-y;h===0&&y===0||(this.uplinkLoss=S<=0?0:Math.round(S/h*100),this.uplinkRTT=l.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return XA(this,null,function*(){if(this._room.remotePublishedUserMap.size===0)return void(this.downlinkNetworkQuality=0);let t=[...this._room.remotePublishedUserMap.values()],o=new Set,a=t.filter(y=>{let S=y.getPeerConnection();return!(!S||o.has(S))&&(o.add(S),!0)}),l=a.filter(y=>{var S;return((S=y.getPeerConnection())==null?void 0:S.connectionState)===mo.CONNECTED});if(a.filter(y=>this.isPeerConnectionDisconnected(y.getPeerConnection())).length===t.length)return void(this.downlinkNetworkQuality=6);for(let y=0;y{this.isPeerConnectionDisconnected(y)&&(this._downlinkPrevStatMap.delete(y),this._downlinkLossAndRTTMap.delete(y))}),this._downlinkLossAndRTTMap.size===0)return this.downlinkRTT=0,this.downlinkLoss=0,void(this.downlinkNetworkQuality=0);let{rtt:d,loss:h}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=d,this.downlinkLoss=h,this.downlinkNetworkQuality=this.getNetworkQuality(h,d)})}getStat(t){return XA(this,null,function*(){let o={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!t||!yy())return o;let a=t.getReceivers();try{for(let l=0;l{d.type==="candidate-pair"&&Ys(d.currentRoundTripTime)&&(o.rtt=Math.round(1e3*d.currentRoundTripTime)),d.type==="inbound-rtp"&&(d.mediaType===JA.AUDIO||d.mediaType===JA.VIDEO)&&(o.totalPacketsLost+=d.packetsLost,o.totalPacketsReceived+=d.packetsReceived)});return o.rtt===0&&(o.rtt=this.uplinkRTT),o}catch{return o}})}getAverageLossAndRTT(t){let o={rtt:0,loss:0};return Array.isArray(t)&&t.length>0&&(t.forEach(a=>{o.rtt+=a.rtt,o.loss+=a.loss}),Object.keys(o).forEach(a=>{o[a]=Math.round(o[a]/t.length)})),o}getNetworkQuality(t,o){return t>50||o>500?5:t>30||o>350?4:t>20||o>200?3:t>10||o>100?2:t>=0||o>=0?1:0}handleSignalConnectionStateChange(t){t.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):t.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=1)}handleUplinkConnectionStateChange(t){let{state:o}=t;o==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):o==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(t){return!(!t||t.connectionState!==mo.DISCONNECTED&&t.connectionState!==mo.FAILED&&t.connectionState!==mo.CLOSED)}setUplinkConnection(t){this._room.uplinkConnection=t,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){this._interval===-1?(this._log.debug("start network quality calculating"),this._interval=kr.run("ric",()=>{var t;this.handleDownlinkNetworkQuality();let o=[...this._downlinkLossAndRTTMap.values()];F.emit(rA.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:o});let a=(t=this._room.scheduleResult.config)==null?void 0:t.pingDomainInfo,l={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};a&&(l=So(Di({},l),{pingResults:this.uplinkRTT>a.rttThreshold||this.downlinkRTT>a.rttThreshold?this.pingResults:{}})),this.emit(P_.EVENT_NETWORK_QUALITY,l);let d=Date.now();if(a&&(this.uplinkRTT>a.rttThreshold||this.downlinkRTT>a.rttThreshold)&&d-P_.lastPingTime>1e3*a.interval){P_.lastPingTime=Date.now();let h=a.domain.map(y=>InA(y).then(S=>({domain:y,cost:S.totalCost})));Promise.all(h).then(y=>{this.pingResults.isPoorNetwork=y.some(S=>S.cost>700),this.pingResults.timestamp=d,this.pingResults.data=y,y.forEach(S=>{ri.addSuccessEvent({key:521718,cost:S.cost})}),this._log.warn("All ping results: ".concat(JSON.stringify(y)))}).catch(y=>{this._log.warn("Error during pinging domains: ".concat(y))})}},{delay:2e3})):this._log.info("network quality calculating is already started")}hadRecentBadUplink(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2;return this._uplinkQualityHistory.some(o=>o>t)}hadRecentBadDownlink(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2;return this._downlinkQualityHistory.some(o=>o>t)}stop(){this._log.debug("stopped"),this._interval!==-1&&(kr.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(t){let{tinyIdToUserIdMap:o}=this._room;t.forEach(a=>{let{srcTinyId:l,videoDelay:d,audioDelay:h}=a,y=o.get(l);if(y){let S=this._room.remotePublishedUserMap.get(y);S?.setDelay({videoDelay:d,audioDelay:h})}})}};Y(J1,"HISTORY_SIZE",10),Y(J1,"EVENT_NETWORK_QUALITY","0"),Y(J1,"lastPingTime",0);var Q8=J1,p8=class{constructor(A){Y(this,"_frameWorkType"),Y(this,"_component"),Y(this,"_language"),Y(this,"connectionType"),Y(this,"_room"),Y(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0}),Y(this,"_keyPrefix"),Y(this,"_log"),Y(this,"_intervalId"),Y(this,"_firstPublishedUserList"),Y(this,"_networkQuality"),Y(this,"_basicInfo"),Y(this,"_pathJoinRoom"),Y(this,"_pathLeaveRoom"),Y(this,"_pathMainVideoMap"),Y(this,"_pathMainAudioMap"),Y(this,"_pathAuxiliaryMap"),Y(this,"_remoteStreamStatMap"),Y(this,"_localStreamStat"),Y(this,"_eventMap",new Map),Y(this,"_captureCostSum",0),Y(this,"_captureCostCount",0),Y(this,"isDestroyed",!1),this._frameWorkType=A.frameWorkType||30,this._component=A.component||0,this.connectionType=A.connectionType||1,this._language=A.language||0,this._room=A.room,this._keyPrefix="key_point",this._log=pA.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(t=>{t.startsWith("handle")&&ba(this[t])&&(this[t]=function(o){let{fn:a,context:l}=o;return function(){try{for(var d=arguments.length,h=new Array(d),y=0;ypA.error("".concat(a.name,"() error observed ").concat(L))):S}catch(S){pA.error("".concat(a.name,"() error observed ").concat(S))}}}({fn:this[t],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:Wd,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0,uint32_audio_capture_thread_health_zero_cnt:0,uint32_after3a_silence_duration:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,Tv().then(()=>{this._basicInfo.string_os_version=jp(),this._basicInfo.string_device_name=lQ()||this._basicInfo.string_os_version})}addEvent(A,t){return this._eventMap.set(A,t),F.on(A,t),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(rA.JOIN_START,this.handleJoinStart).addEvent(rA.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(rA.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(rA.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(rA.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(rA.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(rA.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(rA.JOIN_FAILED,this.handleJoinFailed).addEvent(rA.LEAVE_START,this.handleLeaveStart).addEvent(rA.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(rA.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(rA.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(rA.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(rA.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(rA.PUBLISH_START,this.handlePublishStart).addEvent(rA.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(rA.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(rA.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(rA.PLAY_TRACK_START,this.handlePlayStart).addEvent(rA.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(rA.PLAYER_STATE_CHANGED,A=>{let{track:t,state:o,type:a}=A;!t.isRemote||!this.hitTest(t.room)||o==="PLAYING"&&(a===JA.AUDIO?this.handleAudioPlaying(t):this.handleVideoPlaying(t))}).addEvent(rA.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(rA.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(rA.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(rA.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(rA.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(rA.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(rA.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:t,prevMuteState:o,muteState:a}=A;if(!this.hitTest(t))return;let l=o.hasAudio||o.hasVideo||o.hasSmall,d=o.hasAuxiliary,h=a.hasAudio||a.hasVideo||a.hasSmall,y=a.hasAuxiliary;!l&&h&&this.handleRemoteStreamAdded(a.userId,"main"),!d&&y&&this.handleRemoteStreamAdded(a.userId,"auxiliary")}).addEvent(rA.SINGLE_CONNECTION_STAT,A=>{let{room:t,stat:o}=A;this.hitTest(t)&&(this._pathJoinRoom.int32_ice_cost=o.ice,this._pathJoinRoom.int32_dtls_cost=o.dtls,this._pathJoinRoom.int32_peer_connection_cost=o.peerConnection)})}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((A,t)=>F.off(t,A)),this._eventMap.clear()}destroy(){this.uninstallEvents(),kr.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(A){this.hitTest(A.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),A.params&&(ze(A.params.frameWorkType)||(this._frameWorkType=A.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),ze(A.params.component)||(this._component=A.params.component,this._basicInfo.uint32_component=this._component),ze(A.params.language)||(this._language=A.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(A){let{room:t,detailCost:o}=A;if(this.hitTest(t)&&o){let{totalCost:a,local:l,dns:d,tcp:h,tls:y,request:S,response:L}=o;this._pathJoinRoom.int32_schedule_cost=a,this._pathJoinRoom.int32_schedule_local=l,this._pathJoinRoom.int32_schedule_dns=d,this._pathJoinRoom.int32_schedule_tcp=h,this._pathJoinRoom.int32_schedule_tls=y,this._pathJoinRoom.int32_schedule_request=S,this._pathJoinRoom.int32_schedule_response=L}}handleSignalConnectionStart(A){let{room:t}=A;this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(A){let{room:t,error:o}=A;this.hitTest(t)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),o&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=o instanceof li?Number(o.getExtraCode()||o.getCode()):mt.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(A){this.hitTest(A.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(A){this.hitTest(A.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=A.code,A.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(A){this.hitTest(A.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=A.room.getSignalInfo())}handleJoinFailed(A){let{room:t,error:o}=A;this.hitTest(t)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=o.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(A){this.hitTest(A.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=A.publishedUserList||[])}handleSendFirstVideoFrame(A){let{room:t}=A;this.hitTest(t)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(A){this.hitTest(A.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(A){var t;if(this.hitTest(A.room)&&this._pathLeaveRoom.uint64_end_time===0){if(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0){this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time;let o=(t=this._room.audioManager.localAudioTrack)==null?void 0:t.after3aSilenceStartTime;o&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=Oo()-o)}else this._log.warn("pathJoinRoom endTime is 0");this.report()}}handleLeaveSendCMD(A){this.hitTest(A.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleSwitchRoomStart(A){if(this.hitTest(A.room)){let t=Date.now();this.report().then(()=>{this._pathJoinRoom.uint64_start_time=t,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=t})}}handleSwitchRoomSuccess(A){let{room:t}=A;if(this.hitTest(t)&&this._pathJoinRoom.uint64_end_time===0){let o=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=o,this._pathJoinRoom.uint64_end_time=o,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed(A){let{room:t,error:o}=A;if(this.hitTest(t)){let a=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=a,this._pathJoinRoom.uint64_end_time=a,o&&(this._pathJoinRoom.int32_end_ret=o instanceof li?Number(o.getExtraCode()||o.getCode()):mt.UNKNOWN)}}handleRemoteStreamAdded(A,t){var o;let a="".concat(A,"_").concat(t);if(!this._remoteStreamStatMap.has(a)){let l={userId:A,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:So(Di({},unA),{msg_user_info:new jj({userId:A,tinyId:(o=this._room.remotePublishedUserMap.get(A))==null?void 0:o.tinyId,role:20})})};l.statsToReport.uint32_stream_type=t==="main"?2:7,this._remoteStreamStatMap.set(a,l)}}handleSubscribeStart(A){let{room:t,remotePublishedUser:o,streamType:a,subscribeState:l}=A;if(!this.hitTest(t))return;let{userId:d,tinyId:h,role:y}=o,S=new jj({userId:d,tinyId:h,role:y==="anchor"?20:21}),L=Date.now(),V="".concat(d,"_").concat(a),H=this._remoteStreamStatMap.get(V);H&&H.subscribeStartTime===0&&(H.subscribeStartTime=L),a==="main"?(o.muteState.hasVideo&&(l.video||l.smallVideo)&&!this._pathMainVideoMap.has(V)&&this._pathMainVideoMap.set(V,{statsToReport:{msg_user_info:S,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:d,sendSubscribeCMDTime:L}),o.muteState.hasAudio&&l.audio&&!this._pathMainAudioMap.has(V)&&this._pathMainAudioMap.set(V,{statsToReport:{msg_user_info:S,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:d,sendSubscribeCMDTime:L})):o.muteState.hasAuxiliary&&l.auxiliary&&!this._pathAuxiliaryMap.has(V)&&this._pathAuxiliaryMap.set(V,{sendSubscribeCMDTime:L})}handleSubscribed(A){let{room:t,remotePublishedUser:o,streamType:a}=A;if(this.hitTest(t)){let l="".concat(o.userId,"_").concat(a),d=this._remoteStreamStatMap.get(l);d&&d.subscribedTime===0&&(d.subscribedTime=Date.now())}}handlePlayStart(A){let{track:t}=A;if(!t.isRemote||!this.hitTest(t.room))return;let o="".concat(t.userId,"_").concat(t.streamType),a=this._remoteStreamStatMap.get(o);a?.playStreamTime===0&&(a.playStreamTime=Date.now())}handleVideoLoadedData(A){let{track:t}=A;if(!t.isRemote||!this.hitTest(t.room))return;let o="".concat(t.userId,"_").concat(t.streamType),a=this._pathMainVideoMap.get(o);a&&a.statsToReport.uint64_combine_first_frame_time===0&&(a.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(A){let t="".concat(A.userId,"_").concat(A.streamType),o=Date.now(),a=this._pathMainVideoMap.get(t),l=this._remoteStreamStatMap.get(t);if(l){let{statsToReport:d}=l;if(d.uint32_video_render_first||A.streamType!=="main"?this.hasAuxFlag(A.userId):this.hasVideoFlag(A.userId)){let h=o-this._pathJoinRoom.uint64_start_time;d.uint32_video_render_first=h,ri.addNumber({key:516820,value:h})}}a?.statsToReport.uint64_render_first_frame_time===0&&(a.statsToReport.uint64_render_first_frame_time=o)}handleAudioPlaying(A){let t="".concat(A.userId,"_").concat(A.streamType),o=this._pathMainAudioMap.get(t);o&&o.statsToReport.uint64_play_first_frame_time===0&&(o.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(A){this.hitTest(A.room)&&(this._networkQuality.totalUplinkLoss+=A.uplink.loss,this._networkQuality.totalUplinkRTT+=A.uplink.rtt,this._networkQuality.count++,A.downlinks.forEach(t=>{let{rtt:o,loss:a,userId:l,videoDelay:d,audioDelay:h}=t,y=this._networkQuality.totalDownlinkRTTAndLossMap.get(l);if(y)y.totalRTT+=o,y.totalLoss+=a,d&&(y.totalVideoDelay=(y.totalVideoDelay||0)+d,y.videoDelayCount=(y.videoDelayCount||0)+1),h&&(y.totalAudioDelay=(y.totalAudioDelay||0)+h,y.audioDelayCount=(y.audioDelayCount||0)+1),y.count++;else{let S,L,V,H;d&&(L=d,V=1),h&&(S=h,H=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(l,{totalRTT:o,totalLoss:a,count:1,totalAudioDelay:S,totalVideoDelay:L,audioDelayCount:H,videoDelayCount:V})}}))}handleHeartbeatStats(A){var t;if(this.hitTest(A.room)){let{msg_device_info:o,msg_up_stream_info:a,msg_down_stream_info:l}=A.report;if(a.msg_video_status[0]){let{uint32_video_codec_bitrate:d,uint32_video_enc_fps:h,uint32_video_width:y,uint32_video_height:S}=a.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=d,this._localStreamStat.totalVideoFPS+=h,this._localStreamStat.totalVideoWidth+=y,this._localStreamStat.totalVideoHeight+=S,this._localStreamStat.videoCount++}if(a.msg_audio_status){let{uint32_audio_level:d}=a.msg_audio_status;Math.floor(d/sd*100)>0&&(this._localStreamStat.totalAudioLevel+=d/sd,this._localStreamStat.audioLevelCount++)}l.forEach(d=>{let{msg_user_info:h,msg_audio_status:y,msg_video_status:S}=d,L=h.str_identifier,V=this._room.remotePublishedUserMap.get(L);if(S.forEach(H=>{let lA=H.uint32_video_stream_type===2,hA=H.uint32_video_stream_type===7,MA="".concat(L,"_").concat(lA?"main":"auxiliary"),oe=this._remoteStreamStatMap.get(MA);if(oe&&(lA&&V!=null&&V.remoteVideoTrack.isSubscribed||hA&&V!=null&&V.remoteAuxiliaryTrack)){oe.totalVideoFPS+=H.uint32_video_receive_fps,oe.totalVideoBitrate+=H.uint32_video_codec_bitrate,oe.videoCount++,oe.statsToReport.uint32_video_width===0&&(oe.statsToReport.uint32_video_width=H.uint32_video_width),oe.statsToReport.uint32_video_height===0&&(oe.statsToReport.uint32_video_height=H.uint32_video_height);let fe=lA?V.remoteVideoTrack:V.remoteAuxiliaryTrack;fe.stat.jitterBufferDelay&&(oe.videoJitterBufferDelay=fe.stat.jitterBufferDelay),fe.stat.framesReceived&&(oe.statsToReport.uint32_video_consume_render_rate=Math.floor(fe.stat.framesDecoded/fe.stat.framesReceived*zS(10,6)))}}),!b0(y)){let H="".concat(L,"_main"),lA=this._remoteStreamStatMap.get(H);this._remoteStreamStatMap.has(H)&&lA&&V!=null&&V.remoteAudioTrack.isSubscribed&&(lA.totalAudioBitrate+=y.uint32_audio_codec_bitrate,lA.audioCount++,V.remoteAudioTrack.stat.jitterBufferDelay&&(lA.audioJitterBufferDelay=V.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(y.uint32_audio_level/sd*100)>0&&(lA.totalAudioLevel+=y.uint32_audio_level/sd,lA.audioLevelCount++),y.uint32_audio_block_time&&(lA.statsToReport.uint32_audio_block_time+=y.uint32_audio_block_time))}}),o.uint32_audio_capture_cost&&(this._captureCostSum+=o.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0)),o.uint32_audio_capture_cost===0&&((t=this._room.audioManager.localAudioTrack)==null?void 0:t.muted)===!1&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}handlePublishStart(A){let{room:t}=A;this.hitTest(t)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(A){let{track:t}=A;t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(A){let{track:t}=A;t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(A){let{track:t,error:o}=A,a={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[o.name]||(o instanceof li?o.getExtraCode()||o.getCode():mt.UNKNOWN);t.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=a,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),t.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=a,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(A){return this._firstPublishedUserList.findIndex(t=>t.userId===A&&t.flag&ev)>=0}hasAudioFlag(A){return this._firstPublishedUserList.findIndex(t=>t.userId===A&&t.flag&iv)>=0}hasAuxFlag(A){return this._firstPublishedUserList.findIndex(t=>t.userId===A&&t.flag&tv)>=0}hitTest(A){return A===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let A=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),t=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=A<<16|t}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((A,t)=>{let{userId:o}=A,a=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(a){let{totalLoss:L,count:V,audioDelayCount:H,videoDelayCount:lA,totalAudioDelay:hA,totalVideoDelay:MA}=a;A.statsToReport.uint32_avg_down_loss=Math.floor(L/V),H&&hA&&(A.statsToReport.uint32_audio_network_p2p_delay=Math.floor(hA/H),A.audioJitterBufferDelay&&(A.statsToReport.uint32_p2p_delay=Math.floor(A.statsToReport.uint32_audio_network_p2p_delay+A.audioJitterBufferDelay))),lA&&MA&&(A.statsToReport.uint32_video_network_p2p_delay=Math.floor(MA/lA))}A.videoCount>0&&(A.statsToReport.uint32_video_avg_fps=Math.floor(A.totalVideoFPS/A.videoCount),A.statsToReport.uint32_video_avg_bitrate=Math.floor(A.totalVideoBitrate/A.videoCount)),A.audioCount>0&&(A.statsToReport.uint32_audio_recv_bitrate=A.statsToReport.uint32_audio_bitrate=Math.floor(A.totalAudioBitrate/A.audioCount)),A.audioLevelCount>0&&(A.statsToReport.uint32_audio_play_db=Math.floor(A.totalAudioLevel/A.audioLevelCount*100));let{callDurationCalculator:l}=this._room;l&&(A.statsToReport.uint32_audio_play_time=l.getDuration(t,JA.AUDIO),A.statsToReport.uint32_video_play_time=l.getDuration(t,JA.VIDEO)),A.statsToReport.uint32_video_render_first&&(A.statsToReport.uint32_video_render_first=Math.min(A.statsToReport.uint32_video_render_first,rM));let{badCaseDetector:d}=this._room,{dataFreeze:h,count:y}=d.getDataFreezeDuration(t),{renderFreeze:S}=d.getRenderFreezeDuration(t);A.statsToReport.uint32_video_block_count=y,A.statsToReport.uint32_video_block_time=Math.min(h,A.statsToReport.uint32_video_play_time),A.statsToReport.uint32_video_external_block_time=Math.min(S,A.statsToReport.uint32_video_play_time),A.statsToReport.uint32_audio_block_time=Math.min(A.statsToReport.uint32_audio_block_time,A.statsToReport.uint32_audio_play_time),d.isBlackStream(t)&&A.statsToReport.uint32_video_avg_fps===0?A.statsToReport.uint32_video_black_screen_subjective=1:A.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((A,t)=>{this.hasAudioFlag(A.userId)?A.statsToReport.uint64_play_first_frame_time-A.statsToReport.uint64_start_enter_time>rM&&(A.statsToReport.uint64_play_first_frame_time=A.statsToReport.uint64_start_enter_time+rM):this._pathMainAudioMap.delete(t)}),this._pathMainVideoMap.forEach((A,t)=>{this.hasVideoFlag(A.userId)?A.statsToReport.uint64_render_first_frame_time-A.statsToReport.uint64_start_enter_time>rM&&(A.statsToReport.uint64_render_first_frame_time=A.statsToReport.uint64_start_enter_time+rM):this._pathMainVideoMap.delete(t)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>rM&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+rM)}getReportData(){this._basicInfo.uint32_networkType=$f();let A={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new jj({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Ev(this._signalInfo.relayIp),uint32_client_ip:Ev(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*zS(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(t=>t.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(t=>t.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(t=>t.statsToReport),uint32_info_client_ip:Ev(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return U0(A),A}report(){return XA(this,null,function*(){try{this.prepareReport();let A=this.getReportData();yield this.upload(A),this.initData()}catch(A){this._log.warn(A)}finally{this.isDestroyed&&(this._room=null)}})}upload(A){return XA(this,null,function*(){if(A.msg_path_enter_room.uint64_start_time===0)return;let t=Number(this._room.sdkAppId),o=TA.enable?oQ(A,2001,t):yield ak(A),a=o instanceof ArrayBuffer,l="".concat(Xf(t,OI.KEY_POINT),"&gzip=").concat(+a),d=!1;navigator.sendBeacon&&(d=navigator.sendBeacon(l,o));let h=[this.uploadKVStat(ri),this.uploadKVStat(eB)];d||h.push(nQ({url:l,body:o,priority:"low"})),yield Promise.all(h)})}setConnectionType(A){this.connectionType=A,this._basicInfo.uint32_connection_type=A}uploadKVStat(A){return XA(this,arguments,function(t){var o=this;let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._room.sdkAppId;return function*(){var l,d;let h=t.getReportData((l=o._room)==null?void 0:l.userSig,(d=o._signalInfo)==null?void 0:d.reportToken);if(h.stats_count.length===0&&h.stats_distribution.length===0)return;h.msg_sdk_basic_info=So(Di({},h.msg_sdk_basic_info),{bytes_device_name:o._basicInfo.string_device_name||"",bytes_os_version:o._basicInfo.string_os_version||"",uint32_framework:o._frameWorkType,uint32_network_type:o._basicInfo.uint32_networkType||0}),o._log.debug(h);let y=TA.enable?oQ(h,2003,a):yield ak(h),S=y instanceof ArrayBuffer,L="".concat(Xf(+a,OI.KV_STAT),"&gzip=").concat(+S),V=!1;navigator.sendBeacon&&(V=navigator.sendBeacon(L,y)),V||nQ({url:L,body:y})}()})}};Qi([iB({settings:{timeout:500,retries:3}})],p8.prototype,"upload");var rM=5e3,unA={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},jj=class{constructor(A){Y(this,"str_identifier"),Y(this,"str_tinyid"),Y(this,"uint32_role"),this.str_identifier=String(A.userId),this.str_tinyid=String(A.tinyId||0),this.uint32_role=A.role}},EnA=p8,m8=class{constructor(){Y(this,"_startTime"),Y(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=Oo())}stop(){this._endTime===0&&(this._endTime=Oo())}getDuration(){return this._endTime===0?Oo()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},dnA=class{constructor(A){Y(this,"_room",null),Y(this,"_durationMap"),Y(this,"_eventMap",new Map),this._room=A.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(rA.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(rA.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(rA.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:t,prevMuteState:o,muteState:a}=A;var l;let{userId:d}=a;if(!this.hitTest(t))return;o.hasAudio&&!a.hasAudio&&this.stopDurationItem("".concat(d,"_main"),JA.AUDIO),o.hasVideo&&!a.hasVideo&&this.stopDurationItem("".concat(d,"_main"),JA.VIDEO),o.hasAuxiliary&&!a.hasAuxiliary&&this.stopDurationItem("".concat(d,"_auxiliary"),JA.VIDEO);let h=(l=this._room)==null?void 0:l.remotePublishedUserMap.get(d);h&&(!o.hasAudio&&a.hasAudio&&h.remoteAudioTrack.isSubscribed&&this.addDuractionItem(d,JA.AUDIO,"main"),!o.hasVideo&&a.hasVideo&&h.remoteVideoTrack.isSubscribed&&this.addDuractionItem(d,JA.VIDEO,"main"),!o.hasAuxiliary&&a.hasAuxiliary&&h.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(d,JA.VIDEO,"auxiliary"))}),this._eventMap.forEach((A,t)=>F.on(t,A,this))}uninstallEvents(){this._eventMap.forEach((A,t)=>F.off(t,A,this)),this._eventMap.clear()}handleSubscribed(A){let{track:t}=A;if(!this.hitTest(t.room))return;let{userId:o,streamType:a,kind:l}=t;t.isSubscribed?this.addDuractionItem(o,l,a):this.stopDurationItem("".concat(o,"_").concat(a),l)}handleUnsubscribed(A){let{track:t}=A;this.hitTest(t.room)&&this.stopDurationItem("".concat(t.userId,"_").concat(t.streamType),t.kind)}isRecording(A){return A.findIndex(t=>t.endTime===0)>=0}addDuractionItem(A,t,o){let a="".concat(A,"_").concat(o),l=new m8,d=this._durationMap.get(a);d?this.isRecording(d[t])||d[t].push(l):this._durationMap.set(a,{userId:A,type:o,audio:t===JA.AUDIO?[l]:[],video:t===JA.AUDIO?[]:[l]})}stopDurationItem(A,t){if(this._durationMap.has(A)){let o=this._durationMap.get(A)[t].find(a=>a.endTime===0);o&&o.stop()}}hitTest(A){return this._room===A}getDuration(A,t){return this._durationMap.has(A)?this._durationMap.get(A)[t].reduce((o,a)=>o+a.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},CnA=class{constructor(){Y(this,"renderFreezeMap",new Map),Y(this,"dataFreezeMap",new Map)}get(A,t){let o=this.renderFreezeMap.get(A),a=this.dataFreezeMap.get(A);return t?t==="data"?a:o:(fg||gr)&&o&&a&&o.duration>a.duration?o:a}set(A,t,o){o==="data"?this.dataFreezeMap.set(A,t):this.renderFreezeMap.set(A,t)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},hnA=class{constructor(A){Y(this,"_room"),Y(this,"_renderFreezeMap",new Map),Y(this,"_isVideoPlayingEventFiredMap",new Map),Y(this,"_dataFreezeMap",new Map),Y(this,"_monitorFreezeData",new CnA),Y(this,"_eventMap",new Map),Y(this,"_videoEncodeFailedCount",0),Y(this,"_audioEncodeFailedCount",0),Y(this,"_encodeFailedThreshold",3),Y(this,"ABNORMAL_TIME_LOWER_LIMIT",3e3),Y(this,"ABNORMAL_TIME_UPPER_LIMIT",5e3),Y(this,"_videoAbnormalTimestampMap",new Map),Y(this,"_remoteVideoAbnormalTimestampMap",new Map),Y(this,"_audioAbnormalTimestampMap",new Map),Y(this,"eventListenerMap",new Map),this._room=A.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(rA.LEAVE_SUCCESS,A=>{let{room:t}=A;this.hitTest(t)&&this.stop()}).set(rA.PLAY_TRACK_START,this.onPlayTrackStart).set(rA.UNSUBSCRIBE_SUCCESS,A=>{let{room:t,streamType:o,remotePublishedUser:a}=A;if(!this.hitTest(t))return;let{userId:l}=a,d="".concat(l,"_").concat(o);this.stopDataFreeze({key:d,userId:l,type:o})}).set(rA.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:t,prevMuteState:o,muteState:a}=A;if(!this.hitTest(t))return;let{userId:l}=a;if(o.hasVideo&&!a.hasVideo){let d="main",h="".concat(a.userId,"_").concat(d);this.stopDataFreeze({key:h,userId:l,type:d})}if(o.hasAuxiliary&&!a.hasAuxiliary){let d="auxiliary",h="".concat(a.userId,"_").concat(d);this.stopDataFreeze({key:h,userId:l,type:d})}}).set(rA.PLAYER_STATE_CHANGED,A=>{let{track:t,state:o,reason:a,type:l}=A;if(t.isRemote&&t.room&&this.hitTest(t.room)&&l===JA.VIDEO){if(o==="PLAYING"){let d="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.set(d,!0)}a===JA.MUTE?this.onVideoTrackMuted(t):a===JA.UNMUTE&&this.onVideoTrackUnmuted(t)}}).set(rA.HEARTBEAT_REPORT,this.onHearBeatReport).set(rA.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(rA.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((A,t)=>F.on(t,A,this))}uninstallEvents(){this._eventMap.forEach((A,t)=>F.off(t,A,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(A){if(!A.isSubscribed)return;let{userId:t,streamType:o}=A,a="".concat(t,"_").concat(o),l=this._dataFreezeMap.get(a),d=new m8;l?l.durationItemList.push(d):this._dataFreezeMap.set(a,{userId:t,type:o,durationItemList:[d],isFreezing(){let h=this.durationItemList[this.durationItemList.length-1];return h&&h.endTime===0}})}onVideoTrackUnmuted(A){if(!A.isSubscribed)return;let{userId:t,streamType:o}=A,a="".concat(t,"_").concat(o);this.stopDataFreeze({key:a,userId:t,type:o})}onHearBeatReport(A){let{room:t,report:o}=A;this.hitTest(t)&&(this.localMediaTrackDetector(o),this.remoteMediaTrackDetector(o))}remoteMediaTrackDetector(A){A.msg_down_stream_info.length>0&&A.msg_down_stream_info.forEach(t=>{var o;if(t.msg_video_status.length===0)return;let a=t.msg_user_info.str_identifier,l=(o=this._room.remotePublishedUserMap.get(a))==null?void 0:o.remoteVideoTrack;t.msg_video_status.forEach(d=>{let h=Oo();if(d.uint32_video_codec_bitrate!==void 0&&d.uint32_video_codec_bitrate>0&&d.uint32_video_receive_fps===0&&l!=null&&l.muted)if(this._remoteVideoAbnormalTimestampMap.has("".concat(a,"-decode"))){let y=this._remoteVideoAbnormalTimestampMap.get("".concat(a,"-decode"));y&&h-y>this.ABNORMAL_TIME_LOWER_LIMIT&&h-y=this.ABNORMAL_TIME_UPPER_LIMIT&&(ds.uploadEvent({userId:this._room.userId,log:"stat-".concat(Wa.VIDEO_DECODE_RESUME_DURING_CALL)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(a,"-decode")))}if(d.uint32_video_codec_bitrate!==void 0&&d.uint32_video_codec_bitrate>5e5&&d.uint32_video_dec_fps!==void 0&&d.uint32_video_dec_fps<=5)if(this._remoteVideoAbnormalTimestampMap.has("".concat(a,"-hardware"))){let y=this._remoteVideoAbnormalTimestampMap.get("".concat(a,"-hardware"));if(y&&h-y>this.ABNORMAL_TIME_LOWER_LIMIT/2&&h-y<2*this.ABNORMAL_TIME_UPPER_LIMIT){ds.uploadEvent({userId:this._room.userId,log:"stat-".concat(Wa.VIDEO_HARDWARE_DECODE_FAILED)});let S=this._room.remotePublishedUserMap.get(a);if(S){let L=d.uint32_video_stream_type===2?S.remoteVideoTrack:S.remoteAuxiliaryTrack;L&&(L.log.warn("decode failed during call"),L.emit("decode-failed-during-call"))}}}else this._remoteVideoAbnormalTimestampMap.set("".concat(a,"-hardware"),h);else{let y=this._remoteVideoAbnormalTimestampMap.get("".concat(a,"-hardware"));y&&h-y>=2*this.ABNORMAL_TIME_UPPER_LIMIT&&(ds.uploadEvent({userId:this._room.userId,log:"stat-".concat(Wa.VIDEO_HARDWARE_DECODE_RESUME)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(a,"-hardware")))}})})}localMediaTrackDetector(A){if(A.msg_up_stream_info.msg_video_status){let t=A.msg_up_stream_info.msg_video_status,o=Array.from(this._room.localTracks).find(l=>l.kind==="video"&&!l.isScreen),a=o?.stat.bytesSent||0;if(o?.isMediaTrackActive===!1||a<=0||o!=null&&o.isUseCustomSource)return;t.forEach(l=>{let d=Oo();if(l.uint32_video_stream_type===2)if(l.uint32_video_capture_fps!==0&&l.uint32_video_codec_bitrate===0&&l.uint32_video_enc_fps===0&&o!=null&&o.isPublished)if(this._videoAbnormalTimestampMap.has("local-encode")){let h=this._videoAbnormalTimestampMap.get("local-encode");h&&d-h>this.ABNORMAL_TIME_LOWER_LIMIT&&d-h=this.ABNORMAL_TIME_UPPER_LIMIT&&ds.uploadEvent({userId:this._room.userId,log:"stat-".concat(Wa.VIDEO_ENCODE_RESUME_DURING_CALL)}),this._videoAbnormalTimestampMap.delete("local-encode")}})}if(A.msg_up_stream_info.msg_audio_status){let t=A.msg_up_stream_info.msg_audio_status,o=Array.from(this._room.localTracks).find(d=>d.kind==="audio"),a=o?.stat.bytesSent||0;if(o?.isMediaTrackActive===!1||a<=0||o!=null&&o.isUseCustomSource)return;let l=Oo();if(t.uint32_audio_codec_bitrate===0&&o!=null&&o.isPublished)if(this._audioAbnormalTimestampMap.has("local-encode")){let d=this._audioAbnormalTimestampMap.get("local-encode");d&&l-d>this.ABNORMAL_TIME_LOWER_LIMIT&&l-d=this.ABNORMAL_TIME_UPPER_LIMIT&&ds.uploadEvent({userId:this._room.userId,log:"stat-".concat(Wa.AUDIO_ENCODE_RESUME_DURING_CALL)}),this._audioAbnormalTimestampMap.delete("local-encode")}}}stopDataFreeze(A){let{key:t,userId:o,type:a}=A,l=this._dataFreezeMap.get(t);if(!l||!l.isFreezing())return;let d=l.durationItemList[l.durationItemList.length-1];d.stop();let h=d.getDuration();if(h>Vb){let y=this._monitorFreezeData.get(t,"data");this._monitorFreezeData.set(t,{userId:o,type:a,duration:y?y.duration+h:h},"data")}else l.durationItemList.pop()}getTotalDuration(A){return A.reduce((t,o)=>{let a=o.getDuration();return t+Math.min(a,5e3)},0)}onPlayTrackStart(A){let{track:t}=A;if(!t.isRemote||!this.hitTest(t.room)||t.kind!==JA.VIDEO||!t.isRemotePublished)return;let o="".concat(t.userId,"_").concat(t.streamType);this._isVideoPlayingEventFiredMap.has(o)||this._isVideoPlayingEventFiredMap.set(o,!1)}getDataFreezeDuration(A){let t={dataFreeze:0,count:0},o=this._dataFreezeMap.get(A);if(o){if(o.isFreezing()){let a=o.durationItemList[o.durationItemList.length-1];a.stop(),a.getDuration(){document.hidden||(l=0)};document.addEventListener("visibilitychange",d);let h=(y,S)=>{var L;if(l){let V=t.decodeFPS,H=V>0&&V<=5?600+1e3/V:600,lA=S.presentationTime-l;if(lA>H){lA=Math.min(lA,5e3);let hA="".concat(t.userId,"_").concat(t.streamType),MA=this._monitorFreezeData.get(hA,"render");MA?MA.duration+=lA:this._monitorFreezeData.set(hA,{userId:t.userId,type:t.streamType,duration:lA},"render");let oe=this._renderFreezeMap.get(hA);oe?(oe.totalDuration+=lA,oe.count+=1):this._renderFreezeMap.set(hA,{userId:t.userId,type:t.streamType,totalDuration:lA,count:1})}}l=S.presentationTime,(L=o.element)==null||L.requestVideoFrameCallback(h)};(a=o.element)==null||a.requestVideoFrameCallback(h),this.eventListenerMap.set("".concat(t.userId,"_").concat(t.streamType),{onVisibilityChange:d})}onRemoteVideoPlayEnd(A){let{track:t,player:o}=A,a="".concat(t.userId,"_").concat(t.streamType),l=this.eventListenerMap.get(a);l&&document.removeEventListener("visibilitychange",l.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(A){return A===this._room}destroy(){this.uninstallEvents()}},BnA=dc($l(),1),QnA=class{constructor(A,t,o,a,l){let d=arguments.length>5&&arguments[5]!==void 0?arguments[5]:1.3333333333333333;this.vbMode=A,this.faceDetectorHash=o,this.visionTaskRegistry=a,this.logger=l,Y(this,"animationState"),Y(this,"originalAspect"),Y(this,"totalOffsetX",0),Y(this,"totalOffsetY",0),Y(this,"defaultScaleRatio",.1),Y(this,"isRecovering",!1),Y(this,"boundaryY",280),Y(this,"lastActionTime",0),Y(this,"restTime",400),this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=d||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,t)}addEvent(A,t,o){let a=[{key:570704,error:o??(t?void 0:11)},{key:570705,error:o??(t?void 0:22)}][A-1];a&&(t?ri.addSuccessEvent({key:a.key}):ri.addFailedEvent({key:a.key,error:a.error}))}actionCentering(A){let t=Date.now();if(this.animation(),!this.faceDetectorHash||t-this.lastActionTimet/2?(l=t-o-a,d=o-l):(l=o,d=0),{min:l,offset:d}}calculateTargetPosition(A,t,o,a,l,d){let h,y,S=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.4,L=A+o/2,V=t+a/2,{min:H,offset:lA}=this.calculateBoundary(L,l,A,o),{min:hA,offset:MA}=this.calculateBoundary(V,d,t,a);return h=2*H+o,y=2*hA+a,h/y>this.originalAspect?(h=y*this.originalAspect,lA=L-h/2):(y=h/this.originalAspect,MA=V-y/2),o/l>S&&(lA=0,MA=0,h=l,y=d),lA=Math.max(0,Math.min(lA,l-h)),MA=Math.max(0,Math.min(MA,d-y)),{sx:lA,sy:MA,cropWidth:h,cropHeight:y,timestamp:Date.now()}}processFacePositionCrop(A,t,o){if(!this.animationState.current||!this.animationState.target){let h={sx:0,sy:0,cropWidth:t,cropHeight:o,timestamp:Date.now()};return this.animationState.current=h,void(this.animationState.target=h)}let a=this.positionDistance(this.animationState.target,A),l=this.positionDistance(this.animationState.current,A),d=this.animationState.current.cropWidth/t;a>this.animationState.debounceThreshold*d&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&l>this.animationState.movementThreshold*d&&(this.animationState.target=A,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(A){if(!this.animationState.current||!this.animationState.target)return this.animationState.current=Di({},A),void(this.animationState.target=Di({},A));let t=this.positionDistance(this.animationState.current,A),o=this.positionDistance(this.animationState.target,A);t>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&o>this.animationState.movementThreshold&&(this.animationState.current=A,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let A=Date.now()-this.animationState.startTime,t=Math.min(A/this.animationState.duration,1),o=a=>a<.5?2*a*a:(4-2*a)*a-1;if(this.animationState.current&&this.animationState.target){let a=(this.animationState.target.sx-this.animationState.current.sx)*o(t);this.animationState.current.sx+=a,this.totalOffsetX+=a;let l=(this.animationState.target.sy-this.animationState.current.sy)*o(t);if(this.animationState.current.sy+=l,this.totalOffsetY+=l,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*o(t),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*o(t),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*o(t)),Ys(this.animationState.current.scaleOffsetX)&&Ys(this.animationState.target.scaleOffsetX)&&Ys(this.animationState.current.scaleOffsetY)&&Ys(this.animationState.target.scaleOffsetY)){let d=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*o(t);this.animationState.current.scaleOffsetX+=d;let h=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*o(t);this.animationState.current.scaleOffsetY+=h}}t>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(A,t){return Math.sqrt(zS(A.sx-t.sx,2)+zS(A.sy-t.sy,2))}recoverOriginal(A,t){this.animationState.target={sx:0,sy:0,cropWidth:A,cropHeight:t,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(A,t,o,a,l,d){let h=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.3;if(this.isRecovering)return;let y=this.calculateTargetPosition(o,a,l,d,A,t);this.processFacePositionCrop(y,A,t),l*d/y.cropWidth/y.cropHeight>h&&this.recoverOriginal(A,t)}movingPortrait(A,t,o,a,l,d){var h,y,S,L,V,H,lA,hA,MA,oe,fe,je;let _e={sx:o+l/2+this.totalOffsetX,sy:a+d/2+this.totalOffsetY,cropWidth:A,cropHeight:t,scaleRatio:(y=(h=this.animationState.current)==null?void 0:h.scaleRatio)!=null?y:1,scaleOffsetX:(L=(S=this.animationState.current)==null?void 0:S.scaleOffsetX)!=null?L:0,scaleOffsetY:(H=(V=this.animationState.current)==null?void 0:V.scaleOffsetY)!=null?H:0,timestamp:Date.now()};this.animationState.target={sx:A/2,sy:a+d/2,cropWidth:A,cropHeight:t,scaleRatio:(hA=(lA=this.animationState.target)==null?void 0:lA.scaleRatio)!=null?hA:1,scaleOffsetX:(oe=(MA=this.animationState.target)==null?void 0:MA.scaleOffsetX)!=null?oe:0,scaleOffsetY:(je=(fe=this.animationState.target)==null?void 0:fe.scaleOffsetY)!=null?je:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(l*d/A/t/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=1-this.animationState.target.scaleRatio,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio{A.log.error(o),A.destroy(new li({code:mt.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(o.message||o)})),this.resolvePreditReady()})}init(A){return XA(this,null,function*(){var t,o,a;this.predictReady=new Promise(y=>{this.resolvePreditReady=y});let l=A.Wasm,d=this.context.ctx;if(A.color&&(this._color=A.color),A.mat4&&(this._mat4=A.mat4),A.postProcessing&&(this._postProcessing=A.postProcessing),this._enableFaceCentering=(t=A.enableFaceCentering)!=null&&t,this._enableEffectOptimization=(o=A.enableEffectOptimization)!=null&&o,this.wasm=new l.AllIn1(d),this.wasm.blurRadius=A.blurRadius||3,this.wasm.mirror=!!A.mirror,this.wasm.rotation=A.rotation||0,this.wasm.vbMode=A.bg==="blur"?1:A.bg instanceof HTMLImageElement?2:A.bg==="color"?3:0,this._onAbort=A.onAbort,A.bg||this.resolvePreditReady(),A.waterMark){let{x:y,y:S,width:L,height:V}=A.waterMark;this.wasm.setWaterMark(y,S,L,V)}if(A.beautyParams){let{beauty:y,brightness:S,ruddy:L}=A.beautyParams;this.wasm.setBeauty(y,S,L,A?.width,A?.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),d.uniform1i(d.getUniformLocation(this.program,"mask"),1),A.bg instanceof HTMLImageElement&&(d.uniform1i(d.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(A.bg)),A.waterMark&&(d.uniform1i(d.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(A.waterMark.image));let h=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=d.getUniformLocation(this.program,"u_textureMatrix"),d.uniformMatrix4fv(this._textureMatrixLocation,!1,h),this._offsetMatrixLocation=d.getUniformLocation(this.program,"u_offsetMatrix"),d.uniformMatrix4fv(this._offsetMatrixLocation,!1,h),this._colorLocation=d.getUniformLocation(this.program,"u_color"),d.uniform1i(d.getUniformLocation(this.program,"lastMask"),4),this._weixin){let y=this.context.createShader(d.FRAGMENT_SHADER,`#version 300 es precision highp float; uniform sampler2D u_texture; uniform sampler2D mask; @@ -361,17 +361,17 @@ void main() { void main() { gl_Position = vertexPos; textureCoord = texturePos; - }`}),Y(this,"yTextureRef"),Y(this,"uTextureRef"),Y(this,"vTextureRef"),Y(this,"Y"),Y(this,"U"),Y(this,"V"),this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=A._canvas}_initTexture(A,t){let o=this.context.ctx,a=o.createTexture();return o.bindTexture(o.TEXTURE_2D,a),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.bindTexture(o.TEXTURE_2D,null),o.uniform1i(o.getUniformLocation(this.program,A),t),a}render(A){let t=this.context.ctx,o=this.width,a=this.height;return this.useProgram(),t.viewport(0,0,o,a),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,o,a,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,o/2,a/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,o/2,a/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(A,t){super.resize(A,t);let o=this.context.ctx;o.activeTexture(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,this.yTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,A,t,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE1),o.bindTexture(o.TEXTURE_2D,this.uTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,A/2,t/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this.vTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,A/2,t/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null)}},f8=(A,t)=>{switch(A){case"webCodecs":return t==="videoFrame"?514705:514706;case"wasm":return t==="webgl"?514707:t==="videoFrame"?514708:514709}throw new Error("decoder type not supported")},fnA=0,ynA=class{constructor(A){Y(this,"id",fnA++),Y(this,"trackDoneOB"),Y(this,"startOB"),Y(this,"stopOB"),Y(this,"decoder"),Y(this,"videoContext"),Y(this,"gop",0),Y(this,"gop_helper",0),Y(this,"waitFirstKeyFrame",!0),Y(this,"startTimestamp",0),Y(this,"startTime",0),Y(this,"startPerformanceTime",0),Y(this,"inputFrameCount",0),Y(this,"decodedFrameCount",0),Y(this,"decodeFrameCount",0),Y(this,"downgradeLevel",0),Y(this,"lastDowngradeTime",0),Y(this,"lastFrameDiff",0),Y(this,"lastDecodeFrameTimestamp",0),Y(this,"config"),Y(this,"gop_before_configure",[]),Y(this,"videoElement"),Y(this,"type","wasm"),Y(this,"goodType"),Y(this,"renderer","2d"),Y(this,"wasmOption"),Y(this,"createDecoder"),Y(this,"_decodeSink"),Y(this,"isReported",!1),Y(this,"track"),Y(this,"stateChangeOB"),Y(this,"failedReason");let{track:t,createDecoder:o}=A;if(this.stateChangeOB=BQ(),this.track=t,this.createDecoder=o,this.wasmOption={yuvMode:A.renderer==="webgl",wasmPath:A.wasmPath,workerMode:A.workerMode,canvas:A.canvas},this.config=A.config,this.videoElement=A.videoElement,this.renderer=A.renderer,this.trackDoneOB=Ea(t.availableState,gs.OFF),this.stopOB=BQ(),A.type==="auto"){switch(A.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=A.type;this.changeRenderer(this.renderer),Ma(this.stateChangeOB,rz((a,l)=>(a!==l&&t.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:a,state:l}),l),"INITIALIZED"),CE(this.stopOB),Dl()),this.start()}start(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let t=Ma(this.pipe(this.track),CE(this.stopOB),IL());Ma(t,Dl(()=>{this.track.stat.framesDecoded++},o=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(o," retryCount: ").concat(A)),ri.addFailedEvent({key:f8(this.type,this.renderer),error:o}),A>4)this.failedReason=o,this.stateChangeOB.next("FAILED"),ri.addFailedEvent({key:514704});else{if(this.goodType)return void this.start(A);switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":this.renderer==="webgl"&&this.changeRenderer("videoFrame")}this.start(A+1)}},()=>{this.track.log.warn("".concat(this.id," decoderOB completed")),ri.addSuccessEvent({key:f8(this.type,this.renderer)}),ri.addSuccessEvent({key:514704})})),Ma(t,p_(1),Dl(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(A){this._decodeSink?this._decodeSink.error(A):this.start()}close(A){this.stopOB.next(A)}changeRenderer(A){this.renderer=A,this.renderer==="videoFrame"&&!Uv()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(A){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var o,a;if(this.failedReason)return;this.inputFrameCount++;let l=new Uint8Array(A.data);if((d=l)[0]!==0||d[1]!==0||d[2]!==0||d[3]!==1||l.length<5)return this.stateChangeOB.next("FAILED"),this.close("not h26x frame ".concat(l.subarray(0,5))),A;var d;let h=!1;switch(31&l[4]){case 5:case 7:h=!0}if(((o=this.decoder)==null?void 0:o.state)!=="configured")return this.track.log.debug("not configured ".concat(this.inputFrameCount)),h&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:A.data,timestamp:A.timestamp,type:A.type}),A;this.gop_before_configure.length>0&&!t&&(this.gop_before_configure.forEach(S=>this.decode(S,!0)),this.gop_before_configure=[]);let{timestamp:y}=A;if(h?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!h)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount," ").concat(l.subarray(0,5).join(" ")));this.waitFirstKeyFrame=!1,this.startTimestamp=y,this.startTime=Date.now(),this.startPerformanceTime=Oo()}switch(this.downgradeLevel){case 0:case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}return(this.decodeFrameCount<10||this.decodeFrameCount%500==0)&&this.track.log.debug("decode ".concat(this.decodeFrameCount," gop: ").concat(this.gop," ").concat(y," ").concat((a=A.getMetadata)==null?void 0:a.call(A).rtpTimestamp)),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=y,void this.decoder.decode({data:A.data,type:A.type,timestamp:this.lastDecodeFrameTimestamp})}return A}checkDowngradeByFrameDiff(){let A=this.downgradeLevel,t=this.decodeFrameCount-this.decodedFrameCount;t>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):t<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==A&&this.track.log.debug("downgrade level ".concat(A," to ").concat(this.downgradeLevel," ").concat(this.decodeFrameCount," frameDiff: ").concat(t,", lastFrameDiff: ").concat(this.lastFrameDiff)),this.lastFrameDiff=t,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(A){let t=this.downgradeLevel;this.lastDecodeFrameTimestamp-A>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==t&&this.track.log.debug("downgrade level ".concat(t," to ").concat(this.downgradeLevel))}pipe(A){return t=>XA(this,null,function*(){this._decodeSink=t;let o,a=A.mediaTrack;t.defer(()=>{var h;a&&(A.player.setCanvas(),A.setInputMediaStreamTrack(a)),o?.close(),(h=this.videoContext)==null||h.destroy(),delete this._decodeSink});let{renderer:l,type:d}=this;A.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(d){case"wasm":o=this.createDecoder(d,this.wasmOption);break;case"webCodecs":o=this.createDecoder(d);break;default:throw new Error("not supported yet")}let h=0;if(o.on("videoFrame",y=>{this.decodedFrameCount++,h++,(h<=10||h%500==0)&&A.log.debug("frame ".concat(h," ").concat(this.decodedFrameCount,"/").concat(this.decodeFrameCount," decoded ").concat(y.timestamp)),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(y.timestamp)),t.next(y)}),o.on("error",y=>{A.log.error(y),t.error(d==="webCodecs"?4:8)}),yield o.initialize(this.videoElement),!this._decodeSink)return;if(o.configure(this.config),d==="wasm"&&l==="webgl"){this.videoContext=new qC({frameRate:15,logger:A.log,name:A.userId}),this.videoContext.create(),this.videoContext.on(qC.UNAVAILABLE,S=>{A.log.error(S),t.error(7)});let y=new mnA(this.videoContext);o.on("videoCodecInfo",S=>y.resize(S.width,S.height)),o.on("videoFrame",S=>{({y:y.Y,u:y.U,v:y.V}=S),this.downgradeLevel===1?this.decodedFrameCount%2==0&&y.render(this.decodedFrameCount):y.render(this.decodedFrameCount)}),A.source=y,A.player.setCanvas(this.videoContext._canvas,2)}else if(l==="videoFrame"){A.player.setCanvas();let y=new MediaStreamTrackGenerator({kind:"video"}),S=y.writable.getWriter();A.setInputMediaStreamTrack(y),o.on("videoFrame",L=>S.write(L))}else{this.videoContext=new pQ({frameRate:15,logger:A.log,name:A.userId}),this.videoContext.create({alpha:!1});let y=this.videoContext.createVideoImageSource();o.on("videoFrame",L=>{try{y.image=L,y.update()}catch(V){delete this.goodType,A.log.error(V),t.error(11)}});let S=new Qj(this.videoContext,{name:"remotePlayer",logger:A.log});y.connect(S),A.source=y,A.player.setCanvas(this.videoContext._canvas,2)}this.decoder=o}catch(h){A.log.error(h),t.error(d==="webCodecs"?2:6)}})}},y8=Promise.resolve(),D8=class extends BnA.EventEmitter{constructor(A){super(),this.room=A,Y(this,"videoContext"),Y(this,"_glVideoContext"),Y(this,"_2dVideoContext"),Y(this,"destination"),Y(this,"smallVideoContext"),Y(this,"smallDestination"),Y(this,"smallTrackSource"),Y(this,"smallImageSource"),Y(this,"_isMirror",!1),Y(this,"_rotation",0),Y(this,"cameraTrack"),Y(this,"cameraNode"),Y(this,"transformNode"),Y(this,"mixNode"),Y(this,"screenTrack"),Y(this,"screenNode"),Y(this,"selfModel",!1),Y(this,"blurRadius",3),Y(this,"arTrack"),Y(this,"_enableFaceCentering",!1),Y(this,"_enableEffectOptimization",!1),Y(this,"onAbort"),Y(this,"_color"),Y(this,"Wasm"),Y(this,"waterMarkNode"),Y(this,"_waterMarkOption"),Y(this,"watermarkImageList",[]),Y(this,"_beautyParams"),Y(this,"isUsingArTrack",!1),Y(this,"mixTrack"),Y(this,"_isMixScreen",!1),Y(this,"_virtualBackground"),Y(this,"_virtualBackgroundAbortCallback"),Y(this,"virtualBackgroundInstance"),Y(this,"_bgAssetPath"),Y(this,"log"),Y(this,"_mat4"),Y(this,"_postProcessing"),Y(this,"_checkId",0),Y(this,"_use2d",!1),Y(this,"_autoSwitchRenderMode",!0),Y(this,"encodePipeline",[]),Y(this,"decodePipeline",[]),Y(this,"updated",y8),Y(this,"_updateFlag",!1),this.log=pA.createLogger({parent:A?.getLogger(),id:"vm",userId:A?.userId,sdkAppId:A?.sdkAppId}),this.smallVideoContext=new pQ({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var A;return((A=this.room)==null?void 0:A.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return this._rotation!==0}get _isTransform(){return this._isMirror||this._isRotate}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(A){if(this._autoSwitchRenderMode=A==="auto",this._autoSwitchRenderMode)return;let t=A==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get cameraResolution(){var A;let{width:t,height:o}=((A=this.cameraTrack)==null?void 0:A.settings)||{};return iQ(this._rotation)?{width:o,height:t}:{width:t,height:o}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new pQ({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new qC({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(O2<=22),this._glVideoContext.on(qC.UNAVAILABLE,A=>{var t;this.emit("error",A),this.log.warn("video context unavailable",A),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,A),this.update().catch(o=>{this.log.error(o)})})}catch(A){this.emit("error",A)}}initVirtualBackground(A,t,o){this.onAbort=A,this._mat4=t,this._postProcessing=o}enablePrintDetail(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;this._checkId=kr.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:A})}destroy(){var A,t;(A=this._2dVideoContext)==null||A.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),kr.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Hp||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(){let A=arguments.length>1?arguments[1]:void 0,t=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"videoCtxGl")==="videoCtxGl"?512700:512701;A?ri.addFailedEvent({key:t,error:A}):ri.addSuccessEvent({key:t})}checkOrCreateVideoContext(){let A=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&A===this._hasVirtualBg)this.clear();else{if(!t||!this._use2d)return!0;this.clear()}}else{if(this._glVideoContext=new qC({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var A;return(A=this.smallDestination)==null?void 0:A.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var A;return(A=this.cameraTrack)==null?void 0:A.mediaTrack}setSmallVideo(A,t){if(this.smallMode!=="api")if(A){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new WiA(this.smallVideoContext,A,this.log),this.smallVideoContext.on(qC.UNAVAILABLE,o=>{this.log.warn("small video context lost",o)})}if(this.smallVideoContext.frameRate=A.frameRate,this.smallDestination.resolution=A,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:o,height:a}=this.cameraTrack.settings;this.smallTrackSource.resize(o,a),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(A){var t,o;try{let a=this.cameraTrack,{small:l,player:d}=a;Hp&&d.setCanvas(A);let h=A&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),h=this.arTrack),this.log.info("set main output ".concat(h?h.label:"no output track")),this.setSmallVideo(l,A),F.emit(rA.LOCAL_VIDEO_TRACK_PREPROCESSED,{mediaTrack:h,profile:(o=this.cameraTrack)==null?void 0:o.profile,room:this.room}),a.setOutputMediaStreamTrack(h)}catch(a){this.log.error("set main output failed",a)}}update(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return XA(this,null,function*(){var t;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:o,profile:a}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(tC.RENDER,l=>{var d;(d=this.cameraTrack)==null||d.emit("render",l)})),$d===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof m_?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof m_?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(o.width,o.height);else if(A&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new jiA(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(tC.RENDER,y=>{var S;(S=this.cameraTrack)==null||S.emit("render",y)}));let{width:l,height:d}=this.cameraResolution,h=yield this.getWatermarkImage(l,d);this._waterMarkOption={x:0,y:0,width:h.width,height:h.height,image:h},this.cameraNode=new pnA(this.videoContext,{input:this.initialTrack,width:l,height:d,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=a.frameRate,this._use2d){let l=this.cameraNode;if(l.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new Ny(this.videoContext,this.log,this._isMirror,this._rotation),l=l.connect(this.transformNode),l.disconnect(),this.log.info("start mirror ".concat(this._isMirror," rotate ").concat(this.rotation))),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new pz(this.videoContext,this.log),l.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:d,height:h}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(d,h),d&&h&&this.waterMarkNode.resize(d,h)}(t=this.waterMarkNode)==null||t.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),l=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))}l.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext.canvas)})}clearLastFrame(){var A;this.destination&&((A=this.destination.ctx2d)==null||A.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(A){var t,o,a,l,d;if(A instanceof eM)return this.log.info("change screen input",(t=A.mediaTrack)==null?void 0:t.label),this.setScreenTrack(A);if(A instanceof QQ)return this.log.info("change video input",(o=A.mediaTrack)==null?void 0:o.label),this.setCameraTrack(A);if(A instanceof fL){this.log.info("change remote input",(a=A.mediaTrack)==null?void 0:a.label);let h=A.mediaTrack;return A.setOutputMediaStreamTrack(h)}if(A instanceof mj)return this.log.info("change mix input",(l=A.outMediaTrack)==null?void 0:l.label),this.setMixTrack(A);this.log.warn("change unknown input",(d=A.mediaTrack)==null?void 0:d.label)}removeInput(A){var t;A instanceof eM?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):A instanceof QQ?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):A instanceof fL?A.source&&A.source.context.destroy():A instanceof mj&&(delete this.mixTrack,this.update())}setMixTrack(A){this.mixTrack=A}setCameraTrack(A){return this.cameraTrack=A,this.update(!0)}setScreenTrack(A){return XA(this,null,function*(){return this.screenTrack=A,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(A.mediaTrack):yield this.update()),A.setOutputMediaStreamTrack(A.mediaTrack)})}getWatermarkImage(A,t){return XA(this,null,function*(){let o=document.createElement("canvas");t&&A&&(o.height=t,o.width=A);let a=o.getContext("2d");if(!a)throw new li({code:mt.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((l,d)=>l.zIndex-d.zIndex),this.watermarkImageList.forEach(l=>{let{image:d,x:h,y,width:S,height:L,fillVideo:V}=l,H=V&&A||S,lA=V&&t||L,hA=V?0:h,MA=V?0:y;a.drawImage(d,hA,MA,H,lA)}),Cv(o.toDataURL())})}pushWaterMarkImageList(A){let{type:t}=A;this.watermarkImageList.some(o=>o.imageUrl===A.imageUrl&&o.height===A.height&&o.width===A.width&&o.x===A.x&&o.y===A.y&&o.type===A.type&&o.zIndex===A.zIndex&&o.fillVideo===A.fillVideo)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(o=>o.type!==t)),this.watermarkImageList.push(A))}setBeautyParams(A){return XA(this,null,function*(){this._beautyParams=A,this.update()})}stopBeauty(){return XA(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(A){return XA(this,null,function*(){let t;try{t=yield Cv(A?.imageElement||A.imageUrl)}catch{throw new li({code:mt.INVALID_PARAMETER,message:"load image failed, url: ".concat(A.imageUrl)})}let{x:o=0,y:a=0,width:l=t.width,height:d=t.height,type:h="watermark",zIndex:y=2,fillVideo:S=!1}=A;this.watermarkImageList.some(L=>L.type===h)?(this.watermarkImageList=this.watermarkImageList.filter(L=>L.type!==h),this.pushWaterMarkImageList({x:o,y:a,width:l,height:d,image:t,zIndex:y,type:h,imageUrl:A.imageUrl,fillVideo:S}),t=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:o,y:a,width:l,height:d,image:t,zIndex:y,type:h,imageUrl:A.imageUrl,fillVideo:S}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(L,V)=>L==="imageUrl"?void 0:V))})}deleteWatermark(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"watermark";return XA(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==A),this.log.info("delete watermark",A,JSON.stringify(this.watermarkImageList,(t,o)=>t==="imageUrl"?void 0:o)),yield this.freshWatermark()})}freshWatermark(){return XA(this,null,function*(){var A;(A=this.waterMarkNode)==null||A.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:t,height:o}=this.cameraResolution,a=yield this.getWatermarkImage(t,o);this._waterMarkOption={x:0,y:0,width:a.width,height:a.height,image:a},this.update()})}setVirtualBackground(A){return XA(this,null,function*(){var t,o,a;if(A){if(A.onAbort&&(this._virtualBackgroundAbortCallback=A.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=A.assetPath,A.type==="image"?this._virtualBackground=yield Cv(A.imageUrl):(this.blurRadius=A.blurLevel||this.blurRadius||3,this._virtualBackground=A.type),this._enableFaceCentering=(t=A.enableFaceCentering)!=null?t:this._enableFaceCentering,this._enableEffectOptimization=(o=A.enableEffectOptimization)!=null?o:this._enableEffectOptimization,this._color=(a=A.color)!=null?a:[0,1,0]}else delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;if(this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat(A?.type||"",", ").concat(this.blurRadius||"")),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new li({code:mt.INVALID_OPERATION,message:"webgl context create failed, ".concat(this._glVideoContext.error)})})}get mixScreen(){return this._isMixScreen}set mixScreen(A){var t;this._isMixScreen=A,this._isMixScreen||((t=this.screenNode)==null||t.close(),delete this.screenNode),this.update()}set mirror(A){var t;this._isMirror!==A&&(this._isMirror=A,this._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(A){var t;this._rotation!==A&&(this._rotation=A,this._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(A){this.arTrack=A,this.isUsingArTrack=!0,this.update()}updateAr(){return XA(this,null,function*(){var A;(A=this.cameraTrack)!=null&&A.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var A;this.isUsingArTrack=!1,(A=this.arTrack)==null||A.stop(),this.arTrack=void 0,this.update()}createDecodeContext(A){return new ynA(A)}clear(){var A,t;(A=this.videoContext)==null||A.disconnect(),(t=this.destination)==null||t.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor(A){let{processor:t,type:o}=A;var a;this.encodePipeline.includes(t)||(this.encodePipeline[o]=t,(a=this.room)==null||a.enableInsertableStreams())}addDecodeProcessor(A){let{processor:t,type:o}=A;var a;this.decodePipeline.includes(t)||(this.decodePipeline[o]=t,(a=this.room)==null||a.enableInsertableStreams())}removeEncodeProcessor(A){let{type:t}=A;this.encodePipeline[t]=void 0}removeDecodeProcessor(A){let{type:t}=A;this.decodePipeline[t]=void 0}};Qi([V5(function(A){this.log.error("update failed",A)}),Xr(A=>function(){for(var t=arguments.length,o=new Array(t),a=0;a{A.apply(this,o).then(l,d),setTimeout(d,5e3,new li({code:mt.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],D8.prototype,"update");var DnA=0,SnA=class extends gs{constructor(A){super("room"),Y(this,"seq",++DnA),Y(this,"sdkAppId"),Y(this,"userId"),Y(this,"userSig"),Y(this,"privateMapKey"),Y(this,"latencyLevel"),Y(this,"tinyId"),Y(this,"scene"),Y(this,"roomId"),Y(this,"useStringRoomId"),Y(this,"role","anchor"),Y(this,"joinParams",null),Y(this,"localPublishFlag",0),Y(this,"localTracks",new Set),Y(this,"enableAutoPlayDialog",!0),Y(this,"autoReceiveAudio",!0),Y(this,"autoReceiveVideo",!0),Y(this,"proxy_ws"),Y(this,"proxy_wt"),Y(this,"proxy_unified"),Y(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0,isH265EncodeSupported:!0,isH265DecodeSupported:!0}}),Y(this,"keyPointManager"),Y(this,"audioManager"),Y(this,"videoManager"),Y(this,"callDurationCalculator"),Y(this,"badCaseDetector"),Y(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),Y(this,"videoDecodeFallbackType"),Y(this,"smallMode","canvas"),Y(this,"prelinkPromise",null),Y(this,"enableChorus",!1),Y(this,"_isUsingCachedSchedule",!1),Y(this,"_log"),Y(this,"_joinedTimestamp",0),Y(this,"_sdkType"),Y(this,"heartbeatReport"),Y(this,"heartbeatCount",0),Y(this,"quality"),Y(this,"enableSEI"),Y(this,"isDestroyed",!1),this._log=pA.createLogger({parent:A.logger,id:"r".concat(this.seq)}),this.useStringRoomId=!!A.useStringRoomId,br(A.autoReceiveAudio)&&(this.autoReceiveAudio=A.autoReceiveAudio),br(A.autoReceiveVideo)&&(this.autoReceiveVideo=A.autoReceiveVideo),br(A.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=A.enableAutoPlayDialog),this._sdkType=A.sdkType,this.keyPointManager=new EnA({room:this,frameWorkType:A.frameWorkType,component:A.component,language:A.language}),this.callDurationCalculator=new dnA({room:this}),this.badCaseDetector=new hnA({room:this}),this.audioManager=new eoA(this),this.videoManager=new D8(this)}get videoCodec(){return"h264"}get scriptTransformWorker(){}get isMainStreamPublished(){for(let A of this.localTracks)if(4&A.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let A of this.localTracks)if(2&A.mediaType)return!0;return!1}get hasAuxStream(){for(let A of this.remotePublishedUserMap.values())if(A.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainAudioTrack(){for(let A of this.localTracks)if(1&A.mediaType)return A;return null}get localMainVideoTrack(){for(let A of this.localTracks)if(4&A.mediaType)return A;return null}get localAuxVideoTrack(){for(let A of this.localTracks)if(2&A.mediaType)return A;return null}get publishState(){let A={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};return this.localTracks.forEach(t=>{if(t.isPublished||t.isPublishing)switch(t.mediaType){case 1:A.audio=!0;break;case 4:A.bigVideo=!0,A.smallVideo=t.hasSmall;break;case 2:A.auxVideo=!0}}),A}get muteState(){var A,t,o;return{audio:!((A=this.localMainAudioTrack)==null||!A.muted),bigVideo:!((t=this.localMainVideoTrack)==null||!t.muted),auxVideo:!((o=this.localAuxVideoTrack)==null||!o.muted)}}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(A){return XA(this,null,function*(){return this.publish(A)})}removeTrack(A){return XA(this,null,function*(){return this.unpublish(A)})}replaceTrack(A){return XA(this,null,function*(){})}setEncodedDataProcessingListener(A){throw new Error("Method not implemented.")}enableAIVoice(A){throw new Error("Method not implemented.")}setProxyServer(A){if(Ws(A))/^wss?:\/\//i.test(A)?this.proxy_ws=A:/^https?:\/\//i.test(A)&&(this.proxy_wt=A);else if(uE(A)){let{websocketProxy:t,webtransportProxy:o,loggerProxy:a,scheduleProxy:l,unifiedProxy:d}=A;this.proxy_ws=t,this.proxy_wt=o,this.proxy_unified=d,d?(vj([d,d]),XS("https://".concat(d))):(a&&XS(a),l&&vj(l))}F.once(rA.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:rm.main,sched_back_domain:rm.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return XA(this,null,function*(){let A={};return this.remotePublishedUserMap.forEach(t=>{A[t.userId]=t.remoteAudioTrack.stat}),A})}getTransportStats(){return XA(this,null,function*(){var A;let t={rtt:((A=this.quality)==null?void 0:A.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let o of this.quality.downlinkInfo)t.downlinksRTT[o.userId]=o.rtt;return t})}getRemoteVideoStats(){return XA(this,arguments,function(){var A=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"main";return function*(){let o={};return A.remotePublishedUserMap.forEach(a=>{let l=t==="auxiliary"?a.remoteAuxiliaryTrack:a.remoteVideoTrack;o[a.userId]=l.stat}),o}()})}checkDestroy(){if(this.isDestroyed)throw new li({code:mt.INVALID_OPERATION,message:sn({key:Go.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Cc.INVALID_DESTROY),new li({code:mt.INVALID_OPERATION,message:sn({key:Go.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,F.emit(rA.ROOM_DESTROY,{room:this})}schedule(A,t){return XA(this,null,function*(){var o,a,l,d;let h=Oo();try{let{isCached:y,result:S,detailCost:L}=yield Fz({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?A.strRoomId:A.roomId,useStringRoomId:this.useStringRoomId,version:Wd,userSig:this.userSig,role:this.scene==="live"?A.role:void 0,frameWorkType:t,latencyLevel:A.latencyLevel});this._isUsingCachedSchedule=y,this._log.info("schedule cache:".concat(+y," ").concat(Xd(S,{keysToExclude:["username","credential"]}))),y&&F.once(rA.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=Di(Di({},this.scheduleResult),S),Ys((o=S.config)==null?void 0:o.retryCount)&&Q0(S.config.retryCount),Ws((a=S.config)==null?void 0:a.loggerDomain)&&XS(S.config.loggerDomain),this.videoDecodeFallbackType=((l=S.config)==null?void 0:l.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((d=S.config)==null?void 0:d.smallMode)||this.smallMode,F.emit(rA.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:L}),ri.addSuccessEvent({key:521700,cost:Oo()-h})}catch(y){throw ri.addFailedEvent({key:521700,error:y}),y}})}sendAbilityStatus(A){}enableInsertableStreams(){return Promise.resolve()}switchRoom(A){return Promise.reject()}isSwitchRoomSupported(){return!1}prelink(A,t,o,a,l,d){return XA(this,null,function*(){return Promise.resolve()})}closePrelink(){return XA(this,null,function*(){return Promise.resolve()})}},vnA=dc(Xl()),S8=dc(Tb());function v8(A){var t;let o=[];for(let a=0;ad.payload===A.rtp[a].payload)[0];o.push({payload:A.rtp[a].payload,codec:A.rtp[a].codec,fmtp:l?l.config:"",rate:A.rtp[a].rate,rtx:((t=A.rtp[a+1])==null?void 0:t.codec)==="rtx"?A.rtp[a+1].payload:0,rtcpfb:(A?.rtcpFb||[]).filter(d=>d.payload===A.rtp[a].payload).map(d=>{let{type:h,subtype:y}=d;return{id:h,params:y?[y]:[]}})})}return o}var MnA=(A,t,o)=>XA(null,null,function*(){var a;let l=Qc(A),d={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:o};d.ice.ufrag=String(l.media[0].iceUfrag),d.ice.password=l.media[0].icePwd||"",l.fingerprint&&(d.dtls.hash=l.fingerprint.type,d.dtls.fingerprint=l.fingerprint.hash,d.dtls.setup=l.setup||""),l.media[0].fingerprint&&(d.dtls.hash=l.media[0].fingerprint.type,d.dtls.fingerprint=l.media[0].fingerprint.hash),d.dtls.setup=l.media[0].setup||"";let h=l.media[0],y=l.media[1];h.ext&&(d.audio.extensions=h.ext.map(L=>({id:L.value,uri:L.uri}))),y.ext&&(d.video.extensions=y.ext.map(L=>({id:L.value,uri:L.uri})));for(let L of h.rtp){if(L.codec!=="opus")continue;let V=h.fmtp.find(lA=>lA.payload===L.payload);if(!V)continue;let H={codec:L.codec,fmtp:V.config,payload:V.payload,rate:L.rate,channels:L.encoding,rtcpfb:[],rtx:0};(a=h.rtcpFb)==null||a.forEach(lA=>{let{payload:hA,type:MA,subtype:oe}=lA;if(hA===H.payload){let fe={id:MA,params:[]};oe&&fe.params.push(oe),H.rtcpfb.push(fe)}}),d.audio.codecs.push(H);break}let S=["h264","vp8","h265"];return t&&S.shift(),d.video.codecs=[...v8(y)].filter(L=>S.includes(L.codec.toLocaleLowerCase())),d.video.decoders=(yield function(){return XA(this,null,function*(){let L=new RTCPeerConnection;L.addTransceiver(JA.VIDEO,{direction:JA.TRANSCEIVER_DIRECTION_RECVONLY});let V=yield L.createOffer();if(!V.sdp)return[];let H=v8(Qc(V.sdp).media[0]);return L.close(),H})}()).filter(L=>["h264","vp8","h265"].includes(L.codec.toLocaleLowerCase())),d}),M8=(A,t)=>{let o=(A||"").trim(),a=(t||"").trim(),l="profile-level-id",d="".concat(l,"=[0-9a-fA-F]{6}");if(new RegExp(d).test(o)){let y=new RegExp(d,"g");return o.replace(y,"".concat(l,"=").concat(a))}if(!o)return"".concat(l,"=").concat(a);let h=o.endsWith(";")?"":";";return"".concat(o).concat(h).concat(l,"=").concat(a)},RnA=A=>{let{serverAbility:t,clientAbility:o,offerSDP:a,enableCustomMessage:l,profileLevelIdConfig:d}=A,h=Qc(a),y={extmapAllowMixed:"extmap-allow-mixed",groups:h.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},S={candidates:t.candidates.map(V=>({component:1,foundation:"1",generation:0,ip:V.ip,port:V.port,priority:V.priority,transport:V.foundation,type:V.type})),connection:{version:4,ip:"0.0.0.0"},direction:JA.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map(V=>({value:V.id,uri:V.uri})),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:"0",payloads:String(t.audio.codecs[0].payload),port:h.media[0].port,protocol:h.media[0].protocol,type:JA.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map(V=>({payload:t.audio.codecs[0].payload,type:V.id,subtype:V.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:t.audio.codecs[0].payload,codec:t.audio.codecs[0].codec,rate:t.audio.codecs[0].rate,encoding:t.audio.codecs[0].channels}]};y.media.push(S);let L=[d?.big,d?.small,d?.aux];return[1,2,3].forEach((V,H)=>{y.media.push(R8({mid:V,serverAbility:t,clientAbility:o,parsedOffer:h,profileLevelId:L[H]}))}),l&&y.media.push(h.media.find(V=>V.mid==="dc")),by(y)},R8=A=>{let{mid:t,serverAbility:o,clientAbility:a,parsedOffer:l,isDownlink:d=!1,profileLevelId:h}=A,y={candidates:o.candidates.map(S=>({component:1,foundation:"1",generation:0,ip:S.ip,port:S.port,priority:S.priority,transport:S.foundation,type:S.type})),connection:{version:4,ip:"0.0.0.0"},direction:JA.TRANSCEIVER_DIRECTION_RECVONLY,ext:o.video.extensions.map(S=>({value:S.id,uri:S.uri})),fingerprint:{type:o.dtls.hash,hash:o.dtls.fingerprint},fmtp:[],icePwd:o.ice.password,iceUfrag:o.ice.ufrag,mid:String(t),payloads:"",port:l.media[0].port,protocol:l.media[0].protocol,type:JA.VIDEO,setup:o.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(d){let S=o.video.decoders;(!S||S.length===0)&&(S=o.video.codecs),(!S||S.length===0)&&(S=a.video.decoders),S.forEach(L=>{R_(y,L)})}else{let S;S=o.useH265?o.video.codecs.findIndex(V=>V.codec.toLowerCase()==="h265"):o.video.codecs.findIndex(V=>V.codec.toLowerCase()===(o.useVp8?"vp8":"h264"));let L=o.video.codecs[S]||a.video.codecs[0];R_(y,L)}if(!d&&h){let S=y.fmtp,L=y.rtp.find(V=>{var H;return((H=V.codec)==null?void 0:H.toLowerCase())==="h264"});if(L){let V=S.find(H=>String(H.payload)===String(L.payload));V&&(V.config=M8(V.config,h))}}return y},R_=(A,t)=>{A.payloads="".concat(A.payloads," ").concat(t.payload).trim(),A.fmtp.push({payload:t.payload,config:t.fmtp}),A.rtcpFb=[...A.rtcpFb||[],...t.rtcpfb.map(o=>({payload:t.payload,type:o.id,subtype:o.params[0]}))],A.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(A.payloads="".concat(A.payloads," ").concat(t.rtx),A.fmtp.push({payload:t.rtx,config:"apt=".concat(t.payload)}),A.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))},wnA=(A,t,o)=>{let a=S8.default.parse(A);return a.media.forEach((l,d)=>{var h;if((l.type===JA.AUDIO||l.type===JA.VIDEO)&&(function(y){if(!y.rtcpFb)return;let S=[];y.rtcpFb.forEach((L,V)=>{var H;S.push(L),y.rtcpFb&&((H=y.rtcpFb[V+1])==null?void 0:H.payload)!==L.payload&&L.type!=="rrtr"&&S.push({payload:L.payload,type:"rrtr"})}),y.rtcpFb=S}(l),function(y){y.type===JA.VIDEO&&y.fmtp&&y.fmtp.forEach(S=>{S.config.includes("apt")||(S.config+=";sps-pps-idr-in-keyframe=1")})}(l),function(y){y.type===JA.AUDIO&&y.fmtp&&y.fmtp.forEach(S=>{S.config+=";sprop-stereo=1;stereo=1"})}(l),function(y){let S=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);y.ext&&(y.ext=y.ext.filter(L=>!S.has(L.uri)))}(l),l.type===JA.VIDEO)){if(d<4)l.payloads="",l.fmtp=[],l.rtp=[],l.rtcpFb=[],t.video.codecs.forEach(y=>R_(l,y));else if(o){l.payloads="",l.fmtp=[],l.rtp=[],l.rtcpFb=[];let y=o.video.decoders;(!y||y.length===0)&&(y=o.video.codecs),(!y||y.length===0)&&(y=t.video.decoders),y.forEach(S=>R_(l,S))}}(h=l.payloads)!=null&&h.includes("datachannel")&&a.groups&&l.mid&&(a.groups[0].mids=a.groups[0].mids.replace(l.mid,"dc"),l.mid="dc")}),S8.default.write(a)};function Wj(A){var t,o;let a=/profile-level-id=([0-9a-fA-F]{6})/.exec(A);return(o=(t=a?.[1])==null?void 0:t.toLowerCase())!=null?o:null}function zj(A){let t=A.toLowerCase();if(!/^[0-9a-f]{6}$/.test(t))return"unknown";let o=parseInt(t.slice(0,2),16);return o===66?"baseline":o===77?"main":o===100?"high":"unknown"}function w8(A,t){if(!t)return"";let o=A.trim().toLowerCase().replace(/_/g,"-");if(!o)return"";if(/^[0-9a-f]{6}$/.test(o))return o;if(o!=="baseline"&&o!=="main"&&o!=="high")return"";for(let a of t.video.codecs){let l=Wj(a.fmtp);if(l&&zj(l)===o)return l}return""}var _nA=dc(Xl()),_8=class extends _nA.EventEmitter{constructor(A){super(),this.room=A,Y(this,"mainFpsHealth",1),Y(this,"mainBitrateHealth",1),Y(this,"badMainBitrateHealthCount",0),Y(this,"lastEmitBadHealthTime",0),Y(this,"log"),!za&&EE&&F.on("262",this.onVideoCodecChanged,this),this.log=A.getLogger().createChild({id:"h-d"})}onVideoCodecChanged(A){let{remoteUserId:t,streamType:o,isHWCodec:a,codec:l}=A;if(!t&&o!==7&&l==="h264"){if(!a)return void this.room.off("heartbeat-report",this.onHeartbeatReport,this);this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(A){Date.now()-this.lastEmitBadHealthTime<3e4||(A.msg_up_stream_info.msg_video_status.forEach(t=>{if(t.uint32_video_enc_fps&&t.uint32_video_capture_fps){let o=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=o)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:o}=this.room;o&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/o.profile.bitrate)}}),this.log.debug("mainBitrateHealth: ".concat(this.mainBitrateHealth," mainFpsHealth: ").concat(this.mainFpsHealth)),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn("bad main bitrate health: ".concat(this.mainBitrateHealth)),this.emit("1",{isAux:!1}))))}destroy(){F.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};Y(_8,"EVENT_BAD_HEALTH","bad_health");var TnA=_8,w_=(A=>(A.TRACK="track",A.DATA_CHANNEL_MESSAGE="data_channel_msg",A[A.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",A[A.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",A.RECONNECTED="spc-reconnected",A.RECONNECT_FAILED="spc-reconnect-failed",A.ERROR="error",A.SEI_MESSAGE="sei-message",A.DUMP="dump",A))(w_||{}),NnA=1,ky=class extends vnA.default{constructor(A){let{signalChannel:t,room:o,enableDataChannel:a}=A;super(),Y(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),Y(this,"isDestroyed",!1),Y(this,"currentState","DISCONNECTED"),Y(this,"_room"),Y(this,"_signalChannel"),Y(this,"_peerConnection",null),Y(this,"_datachannel",null),Y(this,"_enableDataChannel"),Y(this,"_log"),Y(this,"_downlinkMIDMap",new Map),Y(this,"_downlinkMIDUserIDMap",new Map),Y(this,"_reconnectionTimer",-1),Y(this,"reconnectionCount",0),Y(this,"clientAbility"),Y(this,"_serverAbility",null),Y(this,"addDownlinkQueue",new Set),Y(this,"removeDownlinkQueue",new Set),Y(this,"_parsedAnswer",null),Y(this,"_updateSDPPromise",null),Y(this,"_waitForPCConnectedPromise"),Y(this,"clearWaitForConnectedPromise"),Y(this,"clearConnectTimeout"),Y(this,"_isSDPLogged",!1),Y(this,"enableInsertableStreams",!1),Y(this,"insertableStreamsAbortMap",new Map),Y(this,"receiverRemoteTrackMap",new WeakMap),Y(this,"scriptTransformWorker"),Y(this,"_isRelayTried",!1),Y(this,"_rttOverCount",0),Y(this,"originOffer",null),Y(this,"autoSubscribedSsrcGroups",new Map),Y(this,"autoSubscribedUserMap",new Map),Y(this,"_h265DecodeFailed",!1),this._room=o,this._enableDataChannel=a,this._signalChannel=t,this._log=pA.createLogger({parent:this._room.getLogger(),id:"spc".concat(NnA++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&($p?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let A=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(A=A&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),A}addAbortController(A,t){var o;(o=this.insertableStreamsAbortMap.get(A))==null||o.abort("destroy"),this.insertableStreamsAbortMap.set(A,t)}get isVP8EncodeSupported(){let A=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(A=A&&this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="vp8")),A}get isH265EncodeSupported(){let A=this._room.checkSystemResult.detail.isH265EncodeSupported;return this._serverAbility&&(A=A&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h265")),A}get videoCodec(){var A,t,o;let a=(A=this._parsedAnswer)==null?void 0:A.media[1].rtp.find(l=>["h264","vp8","h265"].includes(l.codec.toLowerCase()));return a?a.codec.toLowerCase():(t=this._serverAbility)!=null&&t.useH265?"h265":(o=this._serverAbility)!=null&&o.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var A,t,o;return(A=this._serverAbility)!=null&&A.useH265&&(t=this._serverAbility)!=null&&t.video.decoders.find(a=>a.codec.toLowerCase()==="h265")&&!this._h265DecodeFailed?"h265":(o=this._serverAbility)!=null&&o.video.decoders.find(a=>a.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get isUsingH265(){return this.videoCodec==="h265"}get isUsingVP8(){return this.videoCodec==="vp8"}get is42001fSupported(){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find(A=>A.fmtp.includes("42001f"))}isProfileLevelIdSupported(A){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find(t=>t.fmtp.includes(A))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(A=>{let t=Qc(A),o={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return t.media.forEach((a,l)=>{var d;if(a.ssrcs&&!ze(a.ssrcs[0].id)){let h=Number(a.ssrcs[0].id),y=Number((d=a.ssrcs.filter(S=>S.attribute==="cname")[1])==null?void 0:d.id);switch(l){case 0:o.audioSsrc=h;break;case 1:o.bigVideoSsrc=h,o.bigVideoRtxSsrc=y;break;case 2:o.smallVideoSsrc=h,o.smallVideoRtxSsrc=y;break;case 3:o.auxVideoSsrc=h,o.auxVideoRtxSsrc=y}}}),o})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(A){}initScriptTransformWorker(){c_&&(this.scriptTransformWorker=Wz({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=A=>{A.data.type==="sei"?this.emit("sei-message",A.data):A.data.type,A.data.type==="dump"&&this.emit("dump",A.data)},this.scriptTransformWorker.onerror=A=>{this._log.error("scriptTransformWorker error: ",A.message)})}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let A=this._peerConnection.getSenders();return A.length===0?null:A[0].transport}getPeerConnectionConfig(A){var t;let o={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:A,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},a=(t=this._peerConnection)==null?void 0:t.getConfiguration().encodedInsertableStreams;return _2(a)&&(o.encodedInsertableStreams=a),this._log.debug("getPeerConnectionConfig",JSON.stringify(o)),o}initialize(A){return XA(this,null,function*(){var t;let o;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(A)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let a=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(a)),a==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():a==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),ri.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):a==="failed"&&ri.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var a;let l=((a=this._peerConnection)==null?void 0:a.signalingState)||"";this._log[l==="closed"?"debug":"info"]("signaling state: ".concat(l))},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=a=>this.emit("track",a),this._enableDataChannel&&(this._datachannel=this._peerConnection.createDataChannel("".concat(this._room.userId,"dc")),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=a=>{let l=new bnA(a.data);this.emit("data_channel_msg",{data:l})},this._datachannel.onerror=a=>{this._log.warn("datachannel error",a)}),this._peerConnection.addTransceiver(JA.AUDIO,{direction:JA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(JA.VIDEO,{direction:JA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(JA.VIDEO,{direction:JA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(JA.VIDEO,{direction:JA.TRANSCEIVER_DIRECTION_SENDONLY}),o=yield this._peerConnection.createOffer(),this.clientAbility=yield MnA(o.sdp,((t=this._room.scheduleResult.config)==null?void 0:t.remove264FromSDP)||!1,this._enableDataChannel),this.originOffer=o,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:a}=this;a&&(this._log.debug("dtls state: ".concat(a.state)),a.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():a.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),ri.addSuccessEvent({key:521707}),this.clientAbility}catch(a){throw ri.addFailedEvent({key:521707,error:a}),this._log.error("initialize failed ".concat(a,` + }`}),Y(this,"yTextureRef"),Y(this,"uTextureRef"),Y(this,"vTextureRef"),Y(this,"Y"),Y(this,"U"),Y(this,"V"),this.useProgram();let t=this.context.ctx;t.pixelStorei(t.PACK_ALIGNMENT,1),t.pixelStorei(t.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=A._canvas}_initTexture(A,t){let o=this.context.ctx,a=o.createTexture();return o.bindTexture(o.TEXTURE_2D,a),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.bindTexture(o.TEXTURE_2D,null),o.uniform1i(o.getUniformLocation(this.program,A),t),a}render(A){let t=this.context.ctx,o=this.width,a=this.height;return this.useProgram(),t.viewport(0,0,o,a),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,this.yTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,o,a,t.LUMINANCE,t.UNSIGNED_BYTE,this.Y),t.activeTexture(t.TEXTURE1),t.bindTexture(t.TEXTURE_2D,this.uTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,o/2,a/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.U),t.activeTexture(t.TEXTURE2),t.bindTexture(t.TEXTURE_2D,this.vTextureRef),t.texSubImage2D(t.TEXTURE_2D,0,0,0,o/2,a/2,t.LUMINANCE,t.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(A,t){super.resize(A,t);let o=this.context.ctx;o.activeTexture(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,this.yTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,A,t,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE1),o.bindTexture(o.TEXTURE_2D,this.uTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,A/2,t/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this.vTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,A/2,t/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null)}},f8=(A,t)=>{switch(A){case"webCodecs":return t==="videoFrame"?514705:514706;case"wasm":return t==="webgl"?514707:t==="videoFrame"?514708:514709}throw new Error("decoder type not supported")},fnA=0,ynA=class{constructor(A){Y(this,"id",fnA++),Y(this,"trackDoneOB"),Y(this,"startOB"),Y(this,"stopOB"),Y(this,"decoder"),Y(this,"videoContext"),Y(this,"gop",0),Y(this,"gop_helper",0),Y(this,"waitFirstKeyFrame",!0),Y(this,"startTimestamp",0),Y(this,"startTime",0),Y(this,"startPerformanceTime",0),Y(this,"inputFrameCount",0),Y(this,"decodedFrameCount",0),Y(this,"decodeFrameCount",0),Y(this,"downgradeLevel",0),Y(this,"lastDowngradeTime",0),Y(this,"lastFrameDiff",0),Y(this,"lastDecodeFrameTimestamp",0),Y(this,"config"),Y(this,"gop_before_configure",[]),Y(this,"videoElement"),Y(this,"type","wasm"),Y(this,"goodType"),Y(this,"renderer","2d"),Y(this,"wasmOption"),Y(this,"createDecoder"),Y(this,"_decodeSink"),Y(this,"isReported",!1),Y(this,"track"),Y(this,"stateChangeOB"),Y(this,"failedReason");let{track:t,createDecoder:o}=A;if(this.stateChangeOB=BQ(),this.track=t,this.createDecoder=o,this.wasmOption={yuvMode:A.renderer==="webgl",wasmPath:A.wasmPath,workerMode:A.workerMode,canvas:A.canvas},this.config=A.config,this.videoElement=A.videoElement,this.renderer=A.renderer,this.trackDoneOB=Ea(t.availableState,gs.OFF),this.stopOB=BQ(),A.type==="auto"){switch(A.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=A.type;this.changeRenderer(this.renderer),Ma(this.stateChangeOB,rz((a,l)=>(a!==l&&t.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:a,state:l}),l),"INITIALIZED"),CE(this.stopOB),Dl()),this.start()}start(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let t=Ma(this.pipe(this.track),CE(this.stopOB),IL());Ma(t,Dl(()=>{this.track.stat.framesDecoded++},o=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(o," retryCount: ").concat(A)),ri.addFailedEvent({key:f8(this.type,this.renderer),error:o}),A>4)this.failedReason=o,this.stateChangeOB.next("FAILED"),ri.addFailedEvent({key:514704});else{if(this.goodType)return void this.start(A);switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":this.renderer==="webgl"&&this.changeRenderer("videoFrame")}this.start(A+1)}},()=>{this.track.log.warn("".concat(this.id," decoderOB completed")),ri.addSuccessEvent({key:f8(this.type,this.renderer)}),ri.addSuccessEvent({key:514704})})),Ma(t,p_(1),Dl(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(A){this._decodeSink?this._decodeSink.error(A):this.start()}close(A){this.stopOB.next(A)}changeRenderer(A){this.renderer=A,this.renderer==="videoFrame"&&!Uv()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(A){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var o,a;if(this.failedReason)return;this.inputFrameCount++;let l=new Uint8Array(A.data);if((d=l)[0]!==0||d[1]!==0||d[2]!==0||d[3]!==1||l.length<5)return this.stateChangeOB.next("FAILED"),this.close("not h26x frame ".concat(l.subarray(0,5))),A;var d;let h=!1;switch(31&l[4]){case 5:case 7:h=!0}if(((o=this.decoder)==null?void 0:o.state)!=="configured")return this.track.log.debug("not configured ".concat(this.inputFrameCount)),h&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:A.data,timestamp:A.timestamp,type:A.type}),A;this.gop_before_configure.length>0&&!t&&(this.gop_before_configure.forEach(S=>this.decode(S,!0)),this.gop_before_configure=[]);let{timestamp:y}=A;if(h?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!h)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount," ").concat(l.subarray(0,5).join(" ")));this.waitFirstKeyFrame=!1,this.startTimestamp=y,this.startTime=Date.now(),this.startPerformanceTime=Oo()}switch(this.downgradeLevel){case 0:case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}return(this.decodeFrameCount<10||this.decodeFrameCount%500==0)&&this.track.log.debug("decode ".concat(this.decodeFrameCount," gop: ").concat(this.gop," ").concat(y," ").concat((a=A.getMetadata)==null?void 0:a.call(A).rtpTimestamp)),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=y,void this.decoder.decode({data:A.data,type:A.type,timestamp:this.lastDecodeFrameTimestamp})}return A}checkDowngradeByFrameDiff(){let A=this.downgradeLevel,t=this.decodeFrameCount-this.decodedFrameCount;t>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):t<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==A&&this.track.log.debug("downgrade level ".concat(A," to ").concat(this.downgradeLevel," ").concat(this.decodeFrameCount," frameDiff: ").concat(t,", lastFrameDiff: ").concat(this.lastFrameDiff)),this.lastFrameDiff=t,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(A){let t=this.downgradeLevel;this.lastDecodeFrameTimestamp-A>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==t&&this.track.log.debug("downgrade level ".concat(t," to ").concat(this.downgradeLevel))}pipe(A){return t=>XA(this,null,function*(){this._decodeSink=t;let o,a=A.mediaTrack;t.defer(()=>{var h;a&&(A.player.setCanvas(),A.setInputMediaStreamTrack(a)),o?.close(),(h=this.videoContext)==null||h.destroy(),delete this._decodeSink});let{renderer:l,type:d}=this;A.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(d){case"wasm":o=this.createDecoder(d,this.wasmOption);break;case"webCodecs":o=this.createDecoder(d);break;default:throw new Error("not supported yet")}let h=0;if(o.on("videoFrame",y=>{this.decodedFrameCount++,h++,(h<=10||h%500==0)&&A.log.debug("frame ".concat(h," ").concat(this.decodedFrameCount,"/").concat(this.decodeFrameCount," decoded ").concat(y.timestamp)),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(y.timestamp)),t.next(y)}),o.on("error",y=>{A.log.error(y),t.error(d==="webCodecs"?4:8)}),yield o.initialize(this.videoElement),!this._decodeSink)return;if(o.configure(this.config),d==="wasm"&&l==="webgl"){this.videoContext=new qC({frameRate:15,logger:A.log,name:A.userId}),this.videoContext.create(),this.videoContext.on(qC.UNAVAILABLE,S=>{A.log.error(S),t.error(7)});let y=new mnA(this.videoContext);o.on("videoCodecInfo",S=>y.resize(S.width,S.height)),o.on("videoFrame",S=>{({y:y.Y,u:y.U,v:y.V}=S),this.downgradeLevel===1?this.decodedFrameCount%2==0&&y.render(this.decodedFrameCount):y.render(this.decodedFrameCount)}),A.source=y,A.player.setCanvas(this.videoContext._canvas,2)}else if(l==="videoFrame"){A.player.setCanvas();let y=new MediaStreamTrackGenerator({kind:"video"}),S=y.writable.getWriter();A.setInputMediaStreamTrack(y),o.on("videoFrame",L=>S.write(L))}else{this.videoContext=new pQ({frameRate:15,logger:A.log,name:A.userId}),this.videoContext.create({alpha:!1});let y=this.videoContext.createVideoImageSource();o.on("videoFrame",L=>{try{y.image=L,y.update()}catch(V){delete this.goodType,A.log.error(V),t.error(11)}});let S=new Qj(this.videoContext,{name:"remotePlayer",logger:A.log});y.connect(S),A.source=y,A.player.setCanvas(this.videoContext._canvas,2)}this.decoder=o}catch(h){A.log.error(h),t.error(d==="webCodecs"?2:6)}})}},y8=Promise.resolve(),D8=class extends BnA.EventEmitter{constructor(A){super(),this.room=A,Y(this,"videoContext"),Y(this,"_glVideoContext"),Y(this,"_2dVideoContext"),Y(this,"destination"),Y(this,"smallVideoContext"),Y(this,"smallDestination"),Y(this,"smallTrackSource"),Y(this,"smallImageSource"),Y(this,"_isMirror",!1),Y(this,"_rotation",0),Y(this,"cameraTrack"),Y(this,"cameraNode"),Y(this,"transformNode"),Y(this,"mixNode"),Y(this,"screenTrack"),Y(this,"screenNode"),Y(this,"selfModel",!1),Y(this,"blurRadius",3),Y(this,"arTrack"),Y(this,"_enableFaceCentering",!1),Y(this,"_enableEffectOptimization",!1),Y(this,"onAbort"),Y(this,"_color"),Y(this,"Wasm"),Y(this,"waterMarkNode"),Y(this,"_waterMarkOption"),Y(this,"watermarkImageList",[]),Y(this,"_beautyParams"),Y(this,"isUsingArTrack",!1),Y(this,"mixTrack"),Y(this,"_isMixScreen",!1),Y(this,"_virtualBackground"),Y(this,"_virtualBackgroundAbortCallback"),Y(this,"virtualBackgroundInstance"),Y(this,"_bgAssetPath"),Y(this,"log"),Y(this,"_mat4"),Y(this,"_postProcessing"),Y(this,"_checkId",0),Y(this,"_use2d",!1),Y(this,"_autoSwitchRenderMode",!0),Y(this,"encodePipeline",[]),Y(this,"decodePipeline",[]),Y(this,"updated",y8),Y(this,"_updateFlag",!1),this.log=pA.createLogger({parent:A?.getLogger(),id:"vm",userId:A?.userId,sdkAppId:A?.sdkAppId}),this.smallVideoContext=new pQ({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var A;return((A=this.room)==null?void 0:A.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return this._rotation!==0}get _isTransform(){return this._isMirror||this._isRotate}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(A){if(this._autoSwitchRenderMode=A==="auto",this._autoSwitchRenderMode)return;let t=A==="2d";this._use2d!==t&&(this._use2d=t,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get cameraResolution(){var A;let{width:t,height:o}=((A=this.cameraTrack)==null?void 0:A.settings)||{};return iQ(this._rotation)?{width:o,height:t}:{width:t,height:o}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new pQ({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new qC({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(O2<=22),this._glVideoContext.on(qC.UNAVAILABLE,A=>{var t;this.emit("error",A),this.log.warn("video context unavailable",A),(t=this._virtualBackgroundAbortCallback)==null||t.call(this,A),this.update().catch(o=>{this.log.error(o)})})}catch(A){this.emit("error",A)}}initVirtualBackground(A,t,o){this.onAbort=A,this._mat4=t,this._postProcessing=o}enablePrintDetail(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;this._checkId=kr.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:A})}destroy(){var A,t;(A=this._2dVideoContext)==null||A.destroy(),(t=this._glVideoContext)==null||t.destroy(),this.smallVideoContext.destroy(),kr.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Hp||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(){let A=arguments.length>1?arguments[1]:void 0,t=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"videoCtxGl")==="videoCtxGl"?512700:512701;A?ri.addFailedEvent({key:t,error:A}):ri.addSuccessEvent({key:t})}checkOrCreateVideoContext(){let A=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let t=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&A===this._hasVirtualBg)this.clear();else{if(!t||!this._use2d)return!0;this.clear()}}else{if(this._glVideoContext=new qC({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var A;return(A=this.smallDestination)==null?void 0:A.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var A;return(A=this.cameraTrack)==null?void 0:A.mediaTrack}setSmallVideo(A,t){if(this.smallMode!=="api")if(A){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new WiA(this.smallVideoContext,A,this.log),this.smallVideoContext.on(qC.UNAVAILABLE,o=>{this.log.warn("small video context lost",o)})}if(this.smallVideoContext.frameRate=A.frameRate,this.smallDestination.resolution=A,t)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=t:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(t),this.smallImageSource.resize(t.width,t.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:o,height:a}=this.cameraTrack.settings;this.smallTrackSource.resize(o,a),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(A){var t,o;try{let a=this.cameraTrack,{small:l,player:d}=a;Hp&&d.setCanvas(A);let h=A&&((t=this.destination)==null?void 0:t.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),h=this.arTrack),this.log.info("set main output ".concat(h?h.label:"no output track")),this.setSmallVideo(l,A),F.emit(rA.LOCAL_VIDEO_TRACK_PREPROCESSED,{mediaTrack:h,profile:(o=this.cameraTrack)==null?void 0:o.profile,room:this.room}),a.setOutputMediaStreamTrack(h)}catch(a){this.log.error("set main output failed",a)}}update(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return XA(this,null,function*(){var t;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:o,profile:a}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(tC.RENDER,l=>{var d;(d=this.cameraTrack)==null||d.emit("render",l)})),$d===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof m_?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof m_?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(o.width,o.height);else if(A&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new jiA(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(tC.RENDER,y=>{var S;(S=this.cameraTrack)==null||S.emit("render",y)}));let{width:l,height:d}=this.cameraResolution,h=yield this.getWatermarkImage(l,d);this._waterMarkOption={x:0,y:0,width:h.width,height:h.height,image:h},this.cameraNode=new pnA(this.videoContext,{input:this.initialTrack,width:l,height:d,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=a.frameRate,this._use2d){let l=this.cameraNode;if(l.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new Ny(this.videoContext,this.log,this._isMirror,this._rotation),l=l.connect(this.transformNode),l.disconnect(),this.log.info("start mirror ".concat(this._isMirror," rotate ").concat(this.rotation))),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new pz(this.videoContext,this.log),l.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:d,height:h}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(d,h),d&&h&&this.waterMarkNode.resize(d,h)}(t=this.waterMarkNode)==null||t.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),l=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))}l.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext.canvas)})}clearLastFrame(){var A;this.destination&&((A=this.destination.ctx2d)==null||A.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(A){var t,o,a,l,d;if(A instanceof eM)return this.log.info("change screen input",(t=A.mediaTrack)==null?void 0:t.label),this.setScreenTrack(A);if(A instanceof QQ)return this.log.info("change video input",(o=A.mediaTrack)==null?void 0:o.label),this.setCameraTrack(A);if(A instanceof fL){this.log.info("change remote input",(a=A.mediaTrack)==null?void 0:a.label);let h=A.mediaTrack;return A.setOutputMediaStreamTrack(h)}if(A instanceof mj)return this.log.info("change mix input",(l=A.outMediaTrack)==null?void 0:l.label),this.setMixTrack(A);this.log.warn("change unknown input",(d=A.mediaTrack)==null?void 0:d.label)}removeInput(A){var t;A instanceof eM?((t=this.screenNode)==null||t.close(),delete this.screenNode,delete this.screenTrack,this.update()):A instanceof QQ?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):A instanceof fL?A.source&&A.source.context.destroy():A instanceof mj&&(delete this.mixTrack,this.update())}setMixTrack(A){this.mixTrack=A}setCameraTrack(A){return this.cameraTrack=A,this.update(!0)}setScreenTrack(A){return XA(this,null,function*(){return this.screenTrack=A,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(A.mediaTrack):yield this.update()),A.setOutputMediaStreamTrack(A.mediaTrack)})}getWatermarkImage(A,t){return XA(this,null,function*(){let o=document.createElement("canvas");t&&A&&(o.height=t,o.width=A);let a=o.getContext("2d");if(!a)throw new li({code:mt.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((l,d)=>l.zIndex-d.zIndex),this.watermarkImageList.forEach(l=>{let{image:d,x:h,y,width:S,height:L,fillVideo:V}=l,H=V&&A||S,lA=V&&t||L,hA=V?0:h,MA=V?0:y;a.drawImage(d,hA,MA,H,lA)}),Cv(o.toDataURL())})}pushWaterMarkImageList(A){let{type:t}=A;this.watermarkImageList.some(o=>o.imageUrl===A.imageUrl&&o.height===A.height&&o.width===A.width&&o.x===A.x&&o.y===A.y&&o.type===A.type&&o.zIndex===A.zIndex&&o.fillVideo===A.fillVideo)||((t==="mute"||t==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(o=>o.type!==t)),this.watermarkImageList.push(A))}setBeautyParams(A){return XA(this,null,function*(){this._beautyParams=A,this.update()})}stopBeauty(){return XA(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(A){return XA(this,null,function*(){let t;try{t=yield Cv(A?.imageElement||A.imageUrl)}catch{throw new li({code:mt.INVALID_PARAMETER,message:"load image failed, url: ".concat(A.imageUrl)})}let{x:o=0,y:a=0,width:l=t.width,height:d=t.height,type:h="watermark",zIndex:y=2,fillVideo:S=!1}=A;this.watermarkImageList.some(L=>L.type===h)?(this.watermarkImageList=this.watermarkImageList.filter(L=>L.type!==h),this.pushWaterMarkImageList({x:o,y:a,width:l,height:d,image:t,zIndex:y,type:h,imageUrl:A.imageUrl,fillVideo:S}),t=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:t.width,height:t.height,image:t},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(t.width,t.height),this.waterMarkNode.image=t):this.update()):(this.pushWaterMarkImageList({x:o,y:a,width:l,height:d,image:t,zIndex:y,type:h,imageUrl:A.imageUrl,fillVideo:S}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(L,V)=>L==="imageUrl"?void 0:V))})}deleteWatermark(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"watermark";return XA(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(t=>t.type!==A),this.log.info("delete watermark",A,JSON.stringify(this.watermarkImageList,(t,o)=>t==="imageUrl"?void 0:o)),yield this.freshWatermark()})}freshWatermark(){return XA(this,null,function*(){var A;(A=this.waterMarkNode)==null||A.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:t,height:o}=this.cameraResolution,a=yield this.getWatermarkImage(t,o);this._waterMarkOption={x:0,y:0,width:a.width,height:a.height,image:a},this.update()})}setVirtualBackground(A){return XA(this,null,function*(){var t,o,a;if(A){if(A.onAbort&&(this._virtualBackgroundAbortCallback=A.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=A.assetPath,A.type==="image"?this._virtualBackground=yield Cv(A.imageUrl):(this.blurRadius=A.blurLevel||this.blurRadius||3,this._virtualBackground=A.type),this._enableFaceCentering=(t=A.enableFaceCentering)!=null?t:this._enableFaceCentering,this._enableEffectOptimization=(o=A.enableEffectOptimization)!=null?o:this._enableEffectOptimization,this._color=(a=A.color)!=null?a:[0,1,0]}else delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;if(this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat(A?.type||"",", ").concat(this.blurRadius||"")),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new li({code:mt.INVALID_OPERATION,message:"webgl context create failed, ".concat(this._glVideoContext.error)})})}get mixScreen(){return this._isMixScreen}set mixScreen(A){var t;this._isMixScreen=A,this._isMixScreen||((t=this.screenNode)==null||t.close(),delete this.screenNode),this.update()}set mirror(A){var t;this._isMirror!==A&&(this._isMirror=A,this._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(A){var t;this._rotation!==A&&(this._rotation=A,this._isTransform||((t=this.transformNode)==null||t.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(A){this.arTrack=A,this.isUsingArTrack=!0,this.update()}updateAr(){return XA(this,null,function*(){var A;(A=this.cameraTrack)!=null&&A.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var A;this.isUsingArTrack=!1,(A=this.arTrack)==null||A.stop(),this.arTrack=void 0,this.update()}createDecodeContext(A){return new ynA(A)}clear(){var A,t;(A=this.videoContext)==null||A.disconnect(),(t=this.destination)==null||t.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor(A){let{processor:t,type:o}=A;var a;this.encodePipeline.includes(t)||(this.encodePipeline[o]=t,(a=this.room)==null||a.enableInsertableStreams())}addDecodeProcessor(A){let{processor:t,type:o}=A;var a;this.decodePipeline.includes(t)||(this.decodePipeline[o]=t,(a=this.room)==null||a.enableInsertableStreams())}removeEncodeProcessor(A){let{type:t}=A;this.encodePipeline[t]=void 0}removeDecodeProcessor(A){let{type:t}=A;this.decodePipeline[t]=void 0}};Qi([V5(function(A){this.log.error("update failed",A)}),Xr(A=>function(){for(var t=arguments.length,o=new Array(t),a=0;a{A.apply(this,o).then(l,d),setTimeout(d,5e3,new li({code:mt.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],D8.prototype,"update");var DnA=0,SnA=class extends gs{constructor(A){super("room"),Y(this,"seq",++DnA),Y(this,"sdkAppId"),Y(this,"userId"),Y(this,"userSig"),Y(this,"privateMapKey"),Y(this,"latencyLevel"),Y(this,"tinyId"),Y(this,"scene"),Y(this,"roomId"),Y(this,"useStringRoomId"),Y(this,"role","anchor"),Y(this,"joinParams",null),Y(this,"localPublishFlag",0),Y(this,"localTracks",new Set),Y(this,"enableAutoPlayDialog",!0),Y(this,"autoReceiveAudio",!0),Y(this,"autoReceiveVideo",!0),Y(this,"proxy_ws"),Y(this,"proxy_wt"),Y(this,"proxy_unified"),Y(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0,isH265EncodeSupported:!0,isH265DecodeSupported:!0}}),Y(this,"keyPointManager"),Y(this,"audioManager"),Y(this,"videoManager"),Y(this,"callDurationCalculator"),Y(this,"badCaseDetector"),Y(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),Y(this,"videoDecodeFallbackType"),Y(this,"smallMode","canvas"),Y(this,"prelinkPromise",null),Y(this,"enableChorus",!1),Y(this,"_isUsingCachedSchedule",!1),Y(this,"_log"),Y(this,"_joinedTimestamp",0),Y(this,"_sdkType"),Y(this,"heartbeatReport"),Y(this,"heartbeatCount",0),Y(this,"quality"),Y(this,"enableSEI"),Y(this,"isDestroyed",!1),this._log=pA.createLogger({parent:A.logger,id:"r".concat(this.seq)}),this.useStringRoomId=!!A.useStringRoomId,br(A.autoReceiveAudio)&&(this.autoReceiveAudio=A.autoReceiveAudio),br(A.autoReceiveVideo)&&(this.autoReceiveVideo=A.autoReceiveVideo),br(A.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=A.enableAutoPlayDialog),this._sdkType=A.sdkType,this.keyPointManager=new EnA({room:this,frameWorkType:A.frameWorkType,component:A.component,language:A.language}),this.callDurationCalculator=new dnA({room:this}),this.badCaseDetector=new hnA({room:this}),this.audioManager=new eoA(this),this.videoManager=new D8(this)}get videoCodec(){return"h264"}get scriptTransformWorker(){}get isMainStreamPublished(){for(let A of this.localTracks)if(4&A.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let A of this.localTracks)if(2&A.mediaType)return!0;return!1}get hasAuxStream(){for(let A of this.remotePublishedUserMap.values())if(A.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainAudioTrack(){for(let A of this.localTracks)if(1&A.mediaType)return A;return null}get localMainVideoTrack(){for(let A of this.localTracks)if(4&A.mediaType)return A;return null}get localAuxVideoTrack(){for(let A of this.localTracks)if(2&A.mediaType)return A;return null}get publishState(){let A={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};return this.localTracks.forEach(t=>{if(t.isPublished||t.isPublishing)switch(t.mediaType){case 1:A.audio=!0;break;case 4:A.bigVideo=!0,A.smallVideo=t.hasSmall;break;case 2:A.auxVideo=!0}}),A}get muteState(){var A,t,o;return{audio:!((A=this.localMainAudioTrack)==null||!A.muted),bigVideo:!((t=this.localMainVideoTrack)==null||!t.muted),auxVideo:!((o=this.localAuxVideoTrack)==null||!o.muted)}}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(A){return XA(this,null,function*(){return this.publish(A)})}removeTrack(A){return XA(this,null,function*(){return this.unpublish(A)})}replaceTrack(A){return XA(this,null,function*(){})}setEncodedDataProcessingListener(A){throw new Error("Method not implemented.")}enableAIVoice(A){throw new Error("Method not implemented.")}setProxyServer(A){if(Ws(A))/^wss?:\/\//i.test(A)?this.proxy_ws=A:/^https?:\/\//i.test(A)&&(this.proxy_wt=A);else if(uE(A)){let{websocketProxy:t,webtransportProxy:o,loggerProxy:a,scheduleProxy:l,unifiedProxy:d}=A;this.proxy_ws=t,this.proxy_wt=o,this.proxy_unified=d,d?(vj([d,d]),XS("https://".concat(d))):(a&&XS(a),l&&vj(l))}F.once(rA.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:rm.main,sched_back_domain:rm.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return XA(this,null,function*(){let A={};return this.remotePublishedUserMap.forEach(t=>{A[t.userId]=t.remoteAudioTrack.stat}),A})}getTransportStats(){return XA(this,null,function*(){var A;let t={rtt:((A=this.quality)==null?void 0:A.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let o of this.quality.downlinkInfo)t.downlinksRTT[o.userId]=o.rtt;return t})}getRemoteVideoStats(){return XA(this,arguments,function(){var A=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"main";return function*(){let o={};return A.remotePublishedUserMap.forEach(a=>{let l=t==="auxiliary"?a.remoteAuxiliaryTrack:a.remoteVideoTrack;o[a.userId]=l.stat}),o}()})}checkDestroy(){if(this.isDestroyed)throw new li({code:mt.INVALID_OPERATION,message:sn({key:Go.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(Cc.INVALID_DESTROY),new li({code:mt.INVALID_OPERATION,message:sn({key:Go.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,F.emit(rA.ROOM_DESTROY,{room:this})}schedule(A,t){return XA(this,null,function*(){var o,a,l,d;let h=Oo();try{let{isCached:y,result:S,detailCost:L}=yield Fz({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?A.strRoomId:A.roomId,useStringRoomId:this.useStringRoomId,version:Wd,userSig:this.userSig,role:this.scene==="live"?A.role:void 0,frameWorkType:t,latencyLevel:A.latencyLevel});this._isUsingCachedSchedule=y,this._log.info("schedule cache:".concat(+y," ").concat(Xd(S,{keysToExclude:["username","credential"]}))),y&&F.once(rA.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=Di(Di({},this.scheduleResult),S),Ys((o=S.config)==null?void 0:o.retryCount)&&Q0(S.config.retryCount),Ws((a=S.config)==null?void 0:a.loggerDomain)&&XS(S.config.loggerDomain),this.videoDecodeFallbackType=((l=S.config)==null?void 0:l.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((d=S.config)==null?void 0:d.smallMode)||this.smallMode,F.emit(rA.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:L}),ri.addSuccessEvent({key:521700,cost:Oo()-h})}catch(y){throw ri.addFailedEvent({key:521700,error:y}),y}})}sendAbilityStatus(A){}enableInsertableStreams(){return Promise.resolve()}switchRoom(A){return Promise.reject()}isSwitchRoomSupported(){return!1}prelink(A,t,o,a,l,d){return XA(this,null,function*(){return Promise.resolve()})}closePrelink(){return XA(this,null,function*(){return Promise.resolve()})}},vnA=dc($l()),S8=dc(Tb());function v8(A){var t;let o=[];for(let a=0;ad.payload===A.rtp[a].payload)[0];o.push({payload:A.rtp[a].payload,codec:A.rtp[a].codec,fmtp:l?l.config:"",rate:A.rtp[a].rate,rtx:((t=A.rtp[a+1])==null?void 0:t.codec)==="rtx"?A.rtp[a+1].payload:0,rtcpfb:(A?.rtcpFb||[]).filter(d=>d.payload===A.rtp[a].payload).map(d=>{let{type:h,subtype:y}=d;return{id:h,params:y?[y]:[]}})})}return o}var MnA=(A,t,o)=>XA(null,null,function*(){var a;let l=Qc(A),d={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:o};d.ice.ufrag=String(l.media[0].iceUfrag),d.ice.password=l.media[0].icePwd||"",l.fingerprint&&(d.dtls.hash=l.fingerprint.type,d.dtls.fingerprint=l.fingerprint.hash,d.dtls.setup=l.setup||""),l.media[0].fingerprint&&(d.dtls.hash=l.media[0].fingerprint.type,d.dtls.fingerprint=l.media[0].fingerprint.hash),d.dtls.setup=l.media[0].setup||"";let h=l.media[0],y=l.media[1];h.ext&&(d.audio.extensions=h.ext.map(L=>({id:L.value,uri:L.uri}))),y.ext&&(d.video.extensions=y.ext.map(L=>({id:L.value,uri:L.uri})));for(let L of h.rtp){if(L.codec!=="opus")continue;let V=h.fmtp.find(lA=>lA.payload===L.payload);if(!V)continue;let H={codec:L.codec,fmtp:V.config,payload:V.payload,rate:L.rate,channels:L.encoding,rtcpfb:[],rtx:0};(a=h.rtcpFb)==null||a.forEach(lA=>{let{payload:hA,type:MA,subtype:oe}=lA;if(hA===H.payload){let fe={id:MA,params:[]};oe&&fe.params.push(oe),H.rtcpfb.push(fe)}}),d.audio.codecs.push(H);break}let S=["h264","vp8","h265"];return t&&S.shift(),d.video.codecs=[...v8(y)].filter(L=>S.includes(L.codec.toLocaleLowerCase())),d.video.decoders=(yield function(){return XA(this,null,function*(){let L=new RTCPeerConnection;L.addTransceiver(JA.VIDEO,{direction:JA.TRANSCEIVER_DIRECTION_RECVONLY});let V=yield L.createOffer();if(!V.sdp)return[];let H=v8(Qc(V.sdp).media[0]);return L.close(),H})}()).filter(L=>["h264","vp8","h265"].includes(L.codec.toLocaleLowerCase())),d}),M8=(A,t)=>{let o=(A||"").trim(),a=(t||"").trim(),l="profile-level-id",d="".concat(l,"=[0-9a-fA-F]{6}");if(new RegExp(d).test(o)){let y=new RegExp(d,"g");return o.replace(y,"".concat(l,"=").concat(a))}if(!o)return"".concat(l,"=").concat(a);let h=o.endsWith(";")?"":";";return"".concat(o).concat(h).concat(l,"=").concat(a)},RnA=A=>{let{serverAbility:t,clientAbility:o,offerSDP:a,enableCustomMessage:l,profileLevelIdConfig:d}=A,h=Qc(a),y={extmapAllowMixed:"extmap-allow-mixed",groups:h.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},S={candidates:t.candidates.map(V=>({component:1,foundation:"1",generation:0,ip:V.ip,port:V.port,priority:V.priority,transport:V.foundation,type:V.type})),connection:{version:4,ip:"0.0.0.0"},direction:JA.TRANSCEIVER_DIRECTION_RECVONLY,ext:t.audio.extensions.map(V=>({value:V.id,uri:V.uri})),fingerprint:{type:t.dtls.hash,hash:t.dtls.fingerprint},fmtp:[{payload:t.audio.codecs[0].payload,config:t.audio.codecs[0].fmtp}],icePwd:t.ice.password,iceUfrag:t.ice.ufrag,mid:"0",payloads:String(t.audio.codecs[0].payload),port:h.media[0].port,protocol:h.media[0].protocol,type:JA.AUDIO,setup:t.dtls.setup,rtcpFb:t.audio.codecs[0].rtcpfb.map(V=>({payload:t.audio.codecs[0].payload,type:V.id,subtype:V.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:t.audio.codecs[0].payload,codec:t.audio.codecs[0].codec,rate:t.audio.codecs[0].rate,encoding:t.audio.codecs[0].channels}]};y.media.push(S);let L=[d?.big,d?.small,d?.aux];return[1,2,3].forEach((V,H)=>{y.media.push(R8({mid:V,serverAbility:t,clientAbility:o,parsedOffer:h,profileLevelId:L[H]}))}),l&&y.media.push(h.media.find(V=>V.mid==="dc")),by(y)},R8=A=>{let{mid:t,serverAbility:o,clientAbility:a,parsedOffer:l,isDownlink:d=!1,profileLevelId:h}=A,y={candidates:o.candidates.map(S=>({component:1,foundation:"1",generation:0,ip:S.ip,port:S.port,priority:S.priority,transport:S.foundation,type:S.type})),connection:{version:4,ip:"0.0.0.0"},direction:JA.TRANSCEIVER_DIRECTION_RECVONLY,ext:o.video.extensions.map(S=>({value:S.id,uri:S.uri})),fingerprint:{type:o.dtls.hash,hash:o.dtls.fingerprint},fmtp:[],icePwd:o.ice.password,iceUfrag:o.ice.ufrag,mid:String(t),payloads:"",port:l.media[0].port,protocol:l.media[0].protocol,type:JA.VIDEO,setup:o.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(d){let S=o.video.decoders;(!S||S.length===0)&&(S=o.video.codecs),(!S||S.length===0)&&(S=a.video.decoders),S.forEach(L=>{R_(y,L)})}else{let S;S=o.useH265?o.video.codecs.findIndex(V=>V.codec.toLowerCase()==="h265"):o.video.codecs.findIndex(V=>V.codec.toLowerCase()===(o.useVp8?"vp8":"h264"));let L=o.video.codecs[S]||a.video.codecs[0];R_(y,L)}if(!d&&h){let S=y.fmtp,L=y.rtp.find(V=>{var H;return((H=V.codec)==null?void 0:H.toLowerCase())==="h264"});if(L){let V=S.find(H=>String(H.payload)===String(L.payload));V&&(V.config=M8(V.config,h))}}return y},R_=(A,t)=>{A.payloads="".concat(A.payloads," ").concat(t.payload).trim(),A.fmtp.push({payload:t.payload,config:t.fmtp}),A.rtcpFb=[...A.rtcpFb||[],...t.rtcpfb.map(o=>({payload:t.payload,type:o.id,subtype:o.params[0]}))],A.rtp.push({payload:t.payload,codec:t.codec.toUpperCase(),rate:t.rate}),t.rtx&&(A.payloads="".concat(A.payloads," ").concat(t.rtx),A.fmtp.push({payload:t.rtx,config:"apt=".concat(t.payload)}),A.rtp.push({payload:t.rtx,codec:"rtx",rate:t.rate}))},wnA=(A,t,o)=>{let a=S8.default.parse(A);return a.media.forEach((l,d)=>{var h;if((l.type===JA.AUDIO||l.type===JA.VIDEO)&&(function(y){if(!y.rtcpFb)return;let S=[];y.rtcpFb.forEach((L,V)=>{var H;S.push(L),y.rtcpFb&&((H=y.rtcpFb[V+1])==null?void 0:H.payload)!==L.payload&&L.type!=="rrtr"&&S.push({payload:L.payload,type:"rrtr"})}),y.rtcpFb=S}(l),function(y){y.type===JA.VIDEO&&y.fmtp&&y.fmtp.forEach(S=>{S.config.includes("apt")||(S.config+=";sps-pps-idr-in-keyframe=1")})}(l),function(y){y.type===JA.AUDIO&&y.fmtp&&y.fmtp.forEach(S=>{S.config+=";sprop-stereo=1;stereo=1"})}(l),function(y){let S=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);y.ext&&(y.ext=y.ext.filter(L=>!S.has(L.uri)))}(l),l.type===JA.VIDEO)){if(d<4)l.payloads="",l.fmtp=[],l.rtp=[],l.rtcpFb=[],t.video.codecs.forEach(y=>R_(l,y));else if(o){l.payloads="",l.fmtp=[],l.rtp=[],l.rtcpFb=[];let y=o.video.decoders;(!y||y.length===0)&&(y=o.video.codecs),(!y||y.length===0)&&(y=t.video.decoders),y.forEach(S=>R_(l,S))}}(h=l.payloads)!=null&&h.includes("datachannel")&&a.groups&&l.mid&&(a.groups[0].mids=a.groups[0].mids.replace(l.mid,"dc"),l.mid="dc")}),S8.default.write(a)};function Wj(A){var t,o;let a=/profile-level-id=([0-9a-fA-F]{6})/.exec(A);return(o=(t=a?.[1])==null?void 0:t.toLowerCase())!=null?o:null}function zj(A){let t=A.toLowerCase();if(!/^[0-9a-f]{6}$/.test(t))return"unknown";let o=parseInt(t.slice(0,2),16);return o===66?"baseline":o===77?"main":o===100?"high":"unknown"}function w8(A,t){if(!t)return"";let o=A.trim().toLowerCase().replace(/_/g,"-");if(!o)return"";if(/^[0-9a-f]{6}$/.test(o))return o;if(o!=="baseline"&&o!=="main"&&o!=="high")return"";for(let a of t.video.codecs){let l=Wj(a.fmtp);if(l&&zj(l)===o)return l}return""}var _nA=dc($l()),_8=class extends _nA.EventEmitter{constructor(A){super(),this.room=A,Y(this,"mainFpsHealth",1),Y(this,"mainBitrateHealth",1),Y(this,"badMainBitrateHealthCount",0),Y(this,"lastEmitBadHealthTime",0),Y(this,"log"),!za&&EE&&F.on("262",this.onVideoCodecChanged,this),this.log=A.getLogger().createChild({id:"h-d"})}onVideoCodecChanged(A){let{remoteUserId:t,streamType:o,isHWCodec:a,codec:l}=A;if(!t&&o!==7&&l==="h264"){if(!a)return void this.room.off("heartbeat-report",this.onHeartbeatReport,this);this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(A){Date.now()-this.lastEmitBadHealthTime<3e4||(A.msg_up_stream_info.msg_video_status.forEach(t=>{if(t.uint32_video_enc_fps&&t.uint32_video_capture_fps){let o=t.uint32_video_enc_fps/t.uint32_video_capture_fps;t.uint32_video_stream_type===2&&(this.mainFpsHealth=o)}if(t.uint32_video_codec_bitrate&&t.uint32_video_stream_type===2){let{localMainVideoTrack:o}=this.room;o&&(this.mainBitrateHealth=t.uint32_video_codec_bitrate/1e3/o.profile.bitrate)}}),this.log.debug("mainBitrateHealth: ".concat(this.mainBitrateHealth," mainFpsHealth: ").concat(this.mainFpsHealth)),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn("bad main bitrate health: ".concat(this.mainBitrateHealth)),this.emit("1",{isAux:!1}))))}destroy(){F.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};Y(_8,"EVENT_BAD_HEALTH","bad_health");var TnA=_8,w_=(A=>(A.TRACK="track",A.DATA_CHANNEL_MESSAGE="data_channel_msg",A[A.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",A[A.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",A.RECONNECTED="spc-reconnected",A.RECONNECT_FAILED="spc-reconnect-failed",A.ERROR="error",A.SEI_MESSAGE="sei-message",A.DUMP="dump",A))(w_||{}),NnA=1,ky=class extends vnA.default{constructor(A){let{signalChannel:t,room:o,enableDataChannel:a}=A;super(),Y(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),Y(this,"isDestroyed",!1),Y(this,"currentState","DISCONNECTED"),Y(this,"_room"),Y(this,"_signalChannel"),Y(this,"_peerConnection",null),Y(this,"_datachannel",null),Y(this,"_enableDataChannel"),Y(this,"_log"),Y(this,"_downlinkMIDMap",new Map),Y(this,"_downlinkMIDUserIDMap",new Map),Y(this,"_reconnectionTimer",-1),Y(this,"reconnectionCount",0),Y(this,"clientAbility"),Y(this,"_serverAbility",null),Y(this,"addDownlinkQueue",new Set),Y(this,"removeDownlinkQueue",new Set),Y(this,"_parsedAnswer",null),Y(this,"_updateSDPPromise",null),Y(this,"_waitForPCConnectedPromise"),Y(this,"clearWaitForConnectedPromise"),Y(this,"clearConnectTimeout"),Y(this,"_isSDPLogged",!1),Y(this,"enableInsertableStreams",!1),Y(this,"insertableStreamsAbortMap",new Map),Y(this,"receiverRemoteTrackMap",new WeakMap),Y(this,"scriptTransformWorker"),Y(this,"_isRelayTried",!1),Y(this,"_rttOverCount",0),Y(this,"originOffer",null),Y(this,"autoSubscribedSsrcGroups",new Map),Y(this,"autoSubscribedUserMap",new Map),Y(this,"_h265DecodeFailed",!1),this._room=o,this._enableDataChannel=a,this._signalChannel=t,this._log=pA.createLogger({parent:this._room.getLogger(),id:"spc".concat(NnA++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&($p?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let A=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(A=A&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h264")),A}addAbortController(A,t){var o;(o=this.insertableStreamsAbortMap.get(A))==null||o.abort("destroy"),this.insertableStreamsAbortMap.set(A,t)}get isVP8EncodeSupported(){let A=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(A=A&&this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="vp8")),A}get isH265EncodeSupported(){let A=this._room.checkSystemResult.detail.isH265EncodeSupported;return this._serverAbility&&(A=A&&!!this._serverAbility.video.codecs.find(t=>t.codec.toLowerCase()==="h265")),A}get videoCodec(){var A,t,o;let a=(A=this._parsedAnswer)==null?void 0:A.media[1].rtp.find(l=>["h264","vp8","h265"].includes(l.codec.toLowerCase()));return a?a.codec.toLowerCase():(t=this._serverAbility)!=null&&t.useH265?"h265":(o=this._serverAbility)!=null&&o.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var A,t,o;return(A=this._serverAbility)!=null&&A.useH265&&(t=this._serverAbility)!=null&&t.video.decoders.find(a=>a.codec.toLowerCase()==="h265")&&!this._h265DecodeFailed?"h265":(o=this._serverAbility)!=null&&o.video.decoders.find(a=>a.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get isUsingH265(){return this.videoCodec==="h265"}get isUsingVP8(){return this.videoCodec==="vp8"}get is42001fSupported(){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find(A=>A.fmtp.includes("42001f"))}isProfileLevelIdSupported(A){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find(t=>t.fmtp.includes(A))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(A=>{let t=Qc(A),o={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return t.media.forEach((a,l)=>{var d;if(a.ssrcs&&!ze(a.ssrcs[0].id)){let h=Number(a.ssrcs[0].id),y=Number((d=a.ssrcs.filter(S=>S.attribute==="cname")[1])==null?void 0:d.id);switch(l){case 0:o.audioSsrc=h;break;case 1:o.bigVideoSsrc=h,o.bigVideoRtxSsrc=y;break;case 2:o.smallVideoSsrc=h,o.smallVideoRtxSsrc=y;break;case 3:o.auxVideoSsrc=h,o.auxVideoRtxSsrc=y}}}),o})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(A){}initScriptTransformWorker(){c_&&(this.scriptTransformWorker=Wz({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=A=>{A.data.type==="sei"?this.emit("sei-message",A.data):A.data.type,A.data.type==="dump"&&this.emit("dump",A.data)},this.scriptTransformWorker.onerror=A=>{this._log.error("scriptTransformWorker error: ",A.message)})}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let A=this._peerConnection.getSenders();return A.length===0?null:A[0].transport}getPeerConnectionConfig(A){var t;let o={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:A,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},a=(t=this._peerConnection)==null?void 0:t.getConfiguration().encodedInsertableStreams;return _2(a)&&(o.encodedInsertableStreams=a),this._log.debug("getPeerConnectionConfig",JSON.stringify(o)),o}initialize(A){return XA(this,null,function*(){var t;let o;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(A)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let a=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(a)),a==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():a==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),ri.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):a==="failed"&&ri.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var a;let l=((a=this._peerConnection)==null?void 0:a.signalingState)||"";this._log[l==="closed"?"debug":"info"]("signaling state: ".concat(l))},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=a=>this.emit("track",a),this._enableDataChannel&&(this._datachannel=this._peerConnection.createDataChannel("".concat(this._room.userId,"dc")),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=a=>{let l=new bnA(a.data);this.emit("data_channel_msg",{data:l})},this._datachannel.onerror=a=>{this._log.warn("datachannel error",a)}),this._peerConnection.addTransceiver(JA.AUDIO,{direction:JA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(JA.VIDEO,{direction:JA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(JA.VIDEO,{direction:JA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(JA.VIDEO,{direction:JA.TRANSCEIVER_DIRECTION_SENDONLY}),o=yield this._peerConnection.createOffer(),this.clientAbility=yield MnA(o.sdp,((t=this._room.scheduleResult.config)==null?void 0:t.remove264FromSDP)||!1,this._enableDataChannel),this.originOffer=o,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:a}=this;a&&(this._log.debug("dtls state: ".concat(a.state)),a.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():a.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),ri.addSuccessEvent({key:521707}),this.clientAbility}catch(a){throw ri.addFailedEvent({key:521707,error:a}),this._log.error("initialize failed ".concat(a,` offer: `).concat(o?.sdp)),a}})}setIceServers(A){return XA(this,null,function*(){var t;if(this._peerConnection&&A.length!==0)try{if(this._log.info("setIceServers",JSON.stringify(A,(o,a)=>o==="username"||o==="credential"?"hided":a)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(A)),(t=this._peerConnection)!=null&&t.localDescription||!this.originOffer)return void this._log.warn("setIceServers already has localDescription or no origin Offer");yield this.setOffer(this.originOffer)}catch(o){this._log.warn("setIceServers error ",o)}})}setPriority(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"high";if(this._peerConnection)try{this._peerConnection.getSenders().forEach(t=>{let o=t.getParameters();o.encodings[0]&&(o.encodings[0].priority=A,o.encodings[0].networkPriority=A,t.setParameters(o).catch(a=>{this._log.warn("setPriority error ",a)}))})}catch(t){this._log.warn("setPriority error ",t)}}connect(A){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return XA(this,null,function*(){var o,a,l;try{if(this.currentState==="CONNECTED")return;((o=this._peerConnection)==null||!o.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let d=Oo(),h=this.getProfileLevelIdConfig(),y={type:"answer",sdp:RnA({serverAbility:A,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableDataChannel,profileLevelIdConfig:h})};this._serverAbility=A,yield this.setAnswer(y),yield this.waitForPeerConnectionConnected(),this._room.firewallDetector.resetTimeoutCount();let S=((a=this._room.scheduleResult.config)==null?void 0:a.priority)||((l=this._room.joinParams)==null?void 0:l.priority)||new URLSearchParams(location.search).get("priority");S&&this.setPriority(S),t||ri.addSuccessEvent({key:521703,cost:Oo()-d})}catch(d){let h=d instanceof li&&d.code===mt.API_CALL_ABORTED;throw h||this._log.error("connect failed: ".concat(d),A),this.reset(),!h&&!this.isReconnecting&&!this.isDestroyed&&(ri.addFailedEvent({key:521703,error:d}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),d}})}reconnect(){return XA(this,null,function*(){if(this._reconnectionTimer===-1){if(!this._signalChannel.isConnected)return this._log.warn("reconnect() wait signal channel is connected"),void this._signalChannel.once(wL,this.reconnect,this);try{this.reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this.reconnectionCount,"]")),this.reset();let A=this._signalChannel.getBackupRelayIpPair(),t=yield this.initialize(this._room.getIceServers(A!=null&&A.iceServer?[A.iceServer]:[])),o=Di({ability:t},A),a=yield this._signalChannel.sendWaitForResponse({command:$oA,responseCommand:Qn.REBUILD_PEER_CONNECTION_RES,data:o,enableLog:!1});if(a.data.code!==0)throw new li({code:a.data.code,message:a.data.message});yield this.connect(a.data.data.ability,!0),ri.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),F.emit(rA.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(A){if(!this.isReconnecting||this.isDestroyed)return;if(A!=null&&A.message.includes("timeout")){let t=bp(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(t/1e3,"s")),yield OC(t,o=>{this._reconnectionTimer=o}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(A?.code," ").concat(A)),ri.addFailedEvent({key:521704,error:A}),this.reconnectionCount>=jf()&&this._log.warn("SDK has tried reconnect for ".concat(jf()," times, but all failed, please check your network")),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}}else this._log.warn("reconnect() is reconnecting, ignore current reconnection")})}getPeerConnection(){return this._peerConnection}startReconnection(){return XA(this,null,function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())})}stopReconnection(){var A;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),(A=this.clearConnectTimeout)==null||A.call(this),this._signalChannel.off(wL,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var A;!this.isReconnecting&&((A=this._peerConnection)==null?void 0:A.connectionState)===mo.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(A){var t;let o=((t=this._peerConnection)==null?void 0:t.iceConnectionState)||"closed",a=this.getDTLSTransportState();this._log.info("connectionState: ".concat(A.target.connectionState," ICE: ").concat(o," DTLS: ").concat(a)),A.target.connectionState===mo.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(A.target.connectionState===mo.FAILED||A.target.connectionState===mo.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(A.target.connectionState===mo.CONNECTED||A.target.connectionState===mo.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),F.emit(rA.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return Zh;let A=null;return xI()&&this._peerConnection.getSenders().length!==0?(A=this._peerConnection.getSenders()[0].transport,yy()&&this._peerConnection.getReceivers().length!==0&&A?A.state:Zh):Zh}emitConnectionStateChangedEvent(A){A!==this.currentState&&(this.currentState==="RECONNECTING"&&A==="CONNECTING"||(this.emit(w_.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:A}),this.currentState=A))}logSelectedCandidate(){return XA(this,null,function*(){if(!this._peerConnection)return;let A=yield this._peerConnection.getStats();for(let[t,o]of A)if(Ov(o)){let a=A.get(o.localCandidateId),l=A.get(o.remoteCandidateId);a&&(this._log.info("local candidate: ".concat(a.candidateType," ").concat(a.protocol,":").concat(a.ip||a.address,":").concat(a.port," ").concat(a.networkType||""," ").concat(a.relayProtocol?"relayProtocol:".concat(a.relayProtocol," url: ").concat(a.url):"")),a.networkType&&T0(a.networkType)),l&&this._log.info("remote candidate: ".concat(l.candidateType," ").concat(l.protocol,":").concat(l.ip||l.address,":").concat(l.port));break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise((A,t)=>{if(this.currentState==="CONNECTED")return A();let o=h=>{h.state==="CONNECTED"&&(clearTimeout(d),l(),A())},a=h=>{let{room:y}=h;y===this._room&&(clearTimeout(d),l(),t(new li({code:mt.API_CALL_ABORTED,message:sn({key:Go.CONNECTION_ABORTED,data:"leave room"})})))},l=()=>{F.off(rA.LEAVE_SUCCESS,a,this),this.off(w_.CONNECTION_STATE_CHANGED,o,this)},d=setTimeout(()=>{l();let h=new li({code:mt.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),t(h)},Hb);this.clearConnectTimeout=()=>{l(),clearTimeout(d),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,t(new li({code:mt.API_CALL_TIMEOUT,message:"connection timeout"}))},F.on(rA.LEAVE_SUCCESS,a,this),this.on(w_.CONNECTION_STATE_CHANGED,o,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout})),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise((A,t)=>{this.once("spc-reconnected",A),this.once("error",t)}):Promise.resolve()}addDownlink(A){return XA(this,null,function*(){if(this._log.info("addDownlink(".concat(A.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(A),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info("addDownlink(".concat(A.userId,") done"))}catch(t){this._log.error("addDownlink(".concat(A.userId,") failed ").concat(t)),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig(A){let{ssrc:t,userId:o,tinyId:a,prevMids:l}=A;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(o," ").concat(JSON.stringify(t))),this._parsedAnswer||(this._parsedAnswer=Qc(this._peerConnection.remoteDescription.sdp));let d,h,y,S=this._parsedAnswer.media.filter(H=>{var lA;return(lA=H.ssrcs)==null?void 0:lA.find(hA=>{var MA;return(MA=hA.value)==null?void 0:MA.includes(a)})});if(S.length===3)d=S[0],h=S[1],y=S[2];else{let H,lA=this._peerConnection.getTransceivers().slice(4);if(l?.length===3&&l.every(MA=>{var oe;return((oe=lA.find(fe=>Number(fe.mid)===MA))==null?void 0:oe.direction)==="inactive"})?(H=l,this._log.info("reusing previous mids for ".concat(o,": ").concat(H.join(","))),lA.forEach(MA=>{H.includes(Number(MA.mid))&&(MA.direction=JA.TRANSCEIVER_DIRECTION_RECVONLY)})):H=lA.filter(MA=>MA.direction==="inactive").slice(0,3).map(MA=>(MA.direction=JA.TRANSCEIVER_DIRECTION_RECVONLY,Number(MA.mid))),H.length===3)d=this._parsedAnswer.media.find(MA=>Number(MA.mid)===Number(H[0])),h=this._parsedAnswer.media.find(MA=>Number(MA.mid)===Number(H[1])),y=this._parsedAnswer.media.find(MA=>Number(MA.mid)===Number(H[2]));else if(H.length===0){this._peerConnection.addTransceiver(JA.AUDIO,{direction:JA.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(JA.VIDEO,{direction:JA.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(JA.VIDEO,{direction:JA.TRANSCEIVER_DIRECTION_RECVONLY}),d=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let MA=R8({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:Qc(this._peerConnection.localDescription.sdp),isDownlink:!0});h=JSON.parse(JSON.stringify(MA)),y=JSON.parse(JSON.stringify(MA)),d.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(d),h.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(h),y.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(y)}}d.direction=JA.TRANSCEIVER_DIRECTION_SENDONLY;let L="".concat(a,"-").concat(t.audio);d.ssrcs=[{id:t.audio,attribute:"cname",value:"".concat(L)},{id:t.audio,attribute:"msid",value:"".concat(L,"-").concat(JA.MAIN," ").concat(L,"-audio")}],h.direction=JA.TRANSCEIVER_DIRECTION_SENDONLY,h.ssrcs=[{id:t.video,attribute:"cname",value:"".concat(L)},{id:t.video,attribute:"msid",value:"".concat(L,"-").concat(JA.MAIN," ").concat(L,"-bigvideo")},{id:t.videoRtx,attribute:"cname",value:"".concat(L)},{id:t.videoRtx,attribute:"msid",value:"".concat(L,"-").concat(JA.MAIN," ").concat(L,"-bigvideo")}],h.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.video," ").concat(t.videoRtx)}],y.direction=JA.TRANSCEIVER_DIRECTION_SENDONLY;let V="".concat(L,"-aux");y.ssrcs=[{id:t.auxiliary,attribute:"cname",value:V},{id:t.auxiliary,attribute:"msid",value:"".concat(V," ").concat(L,"-aux").concat(JA.VIDEO)},{id:t.auxiliaryRtx,attribute:"cname",value:"".concat(V," ").concat(L,"-aux").concat(JA.VIDEO)},{id:t.auxiliaryRtx,attribute:"msid",value:"".concat(V," ").concat(L,"-aux").concat(JA.VIDEO)}],y.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(t.auxiliary," ").concat(t.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(H=>H.mid).join(" ")),this._downlinkMIDMap.set(o,[d.mid,h.mid,y.mid]),this._downlinkMIDUserIDMap.set(d.mid,o),this._downlinkMIDUserIDMap.set(h.mid,o),this._downlinkMIDUserIDMap.set(y.mid,o)}removeDownlink(A){return XA(this,null,function*(){if(!this._downlinkMIDMap.has(A)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(A,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let t=this._downlinkMIDMap.get(A),o=!1;return this._peerConnection.getTransceivers().forEach(a=>{t!=null&&t.includes(Number(a.mid))&&(o=!0,a.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=Qc(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(a=>{t!=null&&t.includes(Number(a.mid))&&(o=!0,a.direction="inactive",a.ssrcs=[],a.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&o&&(yield this.updateSDP()),this._downlinkMIDMap.delete(A),t?.forEach(a=>this._downlinkMIDUserIDMap.delete(a)),this._log.info("removeDownlink(".concat(A,") done")),t})}setBandwidth(A){return XA(this,null,function*(){if(!this._peerConnection)return;let{audio:t,bigVideo:o,smallVideo:a,auxVideo:l}=A;try{if(Zk()){let d=this._peerConnection.getSenders().slice(0,4);for(let y=0;y5e3?5e3:t),!0)}setSenderMaxBitrate(A,t){let o=A.getParameters();if((!o.encodings||o.encodings.length===0)&&(o.encodings=[{}]),t==="unlimited")delete o.encodings[0].maxBitrate;else{if(o.encodings[0].maxBitrate===1e3*t)return;o.encodings[0].maxBitrate=1e3*t}return A.setParameters(o)}setBandwidthBySDP(A){let{audio:t,bigVideo:o,smallVideo:a,auxVideo:l}=A;if(!this._peerConnection||!this._peerConnection.localDescription)return;let d=Qc(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=Qc(this._peerConnection.remoteDescription.sdp));let h=gr?"TIAS":"AS";t&&(d.media[0].bandwidth=[{type:h,limit:gr?1e3*t:t}],this._parsedAnswer.media[0].bandwidth=[{type:h,limit:gr?1e3*t:t}]),o&&(d.media[1].bandwidth=[{type:h,limit:gr?1e3*o:o}],this._parsedAnswer.media[1].bandwidth=[{type:h,limit:gr?1e3*o:o}]),a&&(d.media[2].bandwidth=[{type:h,limit:gr?1e3*a:a}],this._parsedAnswer.media[2].bandwidth=[{type:h,limit:gr?1e3*a:a}]),l&&(d.media[3].bandwidth=[{type:h,limit:gr?1e3*l:l}],this._parsedAnswer.media[3].bandwidth=[{type:h,limit:gr?1e3*l:l}]);let y={type:"offer",sdp:by(d)};return this.updateSDP({localDescription:y})}setScaleResolutionDownBy(A,t,o){let a=A.getParameters();(!a.encodings||a.encodings.length===0)&&(a.encodings=[{}]);let l=a.encodings[0].scaleResolutionDownBy;if(ze(l)?t===1:t===l)return;let d="setScaleResolutionDownBy ".concat(o," ").concat(t);return l&&(d+=" prevScale: ".concat(l)),this._log.warn(d),a.encodings[0].scaleResolutionDownBy=t,A.setParameters(a)}setDegradationPreference(A,t,o){if(EE&&nd<83||ng&&wk(PI,"12.1")||gr&&J0<138)return;let a=A.getParameters(),l="balanced";if(t==="motion"?l="maintain-framerate":t==="detail"&&(l="maintain-resolution"),a.degradationPreference===l)return;let d="setDegradationPreference ".concat(o," ").concat(l);return this._log.info(d),a.degradationPreference=l,A.setParameters(a).catch(h=>this._log.warn("".concat(d," failed: ").concat(h)))}updateSDP(){let{localDescription:A}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let t=by(this._parsedAnswer);return this._updateSDPPromise=new Promise((o,a)=>XA(this,null,function*(){var l,d;try{!A&&this._peerConnection&&(this._log.info("creating offer"),A=yield this._peerConnection.createOffer()),A&&(yield this.setOffer(A)),yield this.setAnswer({type:"answer",sdp:t}),this._updateSDPPromise=null,o()}catch(h){this._log.error(h),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection((l=this._peerConnection.localDescription)==null?void 0:l.sdp),` next offer: `).concat(this.filterSDPDirection(A?.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection((d=this._peerConnection.remoteDescription)==null?void 0:d.sdp),` -next answer: `).concat(this.filterSDPDirection(t))),this._log.warn("offer: ".concat(A?.sdp)),this._log.warn("answer: ".concat(t)),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map(y=>{let{mid:S,currentDirection:L,direction:V,stopped:H}=y;return{mid:S,currentDirection:L,direction:V,stopped:H}})))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,a(h)}})),this._updateSDPPromise}setTransceiverDirection(A,t){return XA(this,null,function*(){if(!gr||!this._peerConnection||!this._parsedAnswer)return;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(A));let o=this._peerConnection.getTransceivers();t.forEach(a=>{o[a].direction!==A&&(o[a].direction=A)});for(let a of t){let l=this._parsedAnswer.media[a].direction;A===ir.INACTIVE&&l===ir.RECVONLY&&(this._parsedAnswer.media[a].direction=A),A===ir.SENDONLY&&l===ir.INACTIVE&&(this._parsedAnswer.media[a].direction=ir.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(){return Qc(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"").media.map(A=>A.direction)}setOffer(A){this._log.info("setting offer");let t=wnA(A.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(A){return this._log.info("setting answer"),this._log.debug(A.sdp),this._peerConnection.setRemoteDescription(A)}switchVideoEncoder(A){return XA(this,null,function*(){if(this._parsedAnswer||(this._parsedAnswer=Qc(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(o=>{var a;if(o.type===JA.VIDEO){let l=this._serverAbility.video.codecs.find(d=>d.codec.toLowerCase()===A);l&&((a=o.payloads)==null||!a.includes(String(l.payload)))&&(o.fmtp=[],o.payloads="",o.rtp=[],o.rtcpFb=[],R_(o,l),t=!0)}}),t&&(this._log.warn("switch video encoder to ".concat(A)),yield this.updateSDP())})}getScheduleProfileLevelId(A){var t;try{let o=(t=this._room.scheduleResult.config)==null?void 0:t.profileLevelId,a="";if(A===2?a=gk(o?.big)?o.big:"":A===3?a=gk(o?.small)?o.small:"":A===7&&(a=gk(o?.aux)?o.aux:""),!a)return"";let l=w8(a,this.clientAbility);return l?this._log.info("use schedule profile level id: streamType=".concat(A,", raw=").concat(a,", resolved=").concat(l)):this._log.warn("schedule profile level id not resolved: streamType=".concat(A,", raw=").concat(a)),l}catch(o){return this._log.warn("getScheduleProfileLevelId error: ".concat(o)),""}}getProfileLevelIdConfig(){try{let A=new URLSearchParams(location.search).get("profileLevelId")||"",t=w8(A,this.clientAbility);if(t)return this._log.info("use url profile level id: raw=".concat(A,", resolved=").concat(t)),{big:t,small:t,aux:t};let o=this.getScheduleProfileLevelId(2),a=this.getScheduleProfileLevelId(3),l=this.getScheduleProfileLevelId(7);if(!o&&!a&&!l)return;let d={};return o&&(d.big=o),a&&(d.small=a),l&&(d.aux=l),d}catch(A){return void this._log.warn("getProfileLevelIdConfig error: ".concat(A))}}setH264ProfileLevelId(A,t){return XA(this,null,function*(){if(!this._peerConnection||!this._serverAbility)return;this._updateSDPPromise&&(yield this._updateSDPPromise),this._log.info("set H264 profile-level-id to ".concat(t?"high":"default"," for ").concat(A)),this._parsedAnswer||(this._parsedAnswer=Qc(this._peerConnection.remoteDescription.sdp));let o=A==="main"?1:3,a=this._parsedAnswer.media[o];if(!a||a.type!==JA.VIDEO)return;let l=a.rtp||[],d=a.fmtp||[],h=l.find(lA=>{var hA;return((hA=lA.codec)==null?void 0:hA.toLowerCase())==="h264"});if(!h)return;let y=d.find(lA=>String(lA.payload)===String(h.payload));if(!y)return;let S=Wj(y.config);if(!S)return;let L=zj(S)==="high";if(t&&L||!t&&!L)return;let V=this._serverAbility.video.codecs.map(lA=>Wj(lA.fmtp)).filter(Boolean).find(lA=>{let hA=zj(lA);return t?hA==="high":hA!=="high"});if(!V)return;let H=y.config;y.config=M8(y.config,V),y.config!==H&&(yield this.updateSDP(),this._log.info("set H264 profile-level-id to ".concat(t?"high":"default"," success")))})}useHWEncoder(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0],t=arguments.length>1?arguments[1]:void 0;return XA(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let o=!1,a=[];ze(t)?a=this._parsedAnswer.media.slice(1,4):t===2?a.push(this._parsedAnswer.media[1]):t===3?a.push(this._parsedAnswer.media[2]):t===7&&a.push(this._parsedAnswer.media[3]),a.forEach(l=>{var d;if(l.type===JA.VIDEO){let h;A&&this.is42001fSupported?h=this.clientAbility.video.codecs.find(y=>y.fmtp.includes("42001f")):A||(h=this._serverAbility.video.codecs.find(y=>y.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),h&&((d=l.payloads)==null||!d.includes(String(h.payload)))&&(l.fmtp=[],l.payloads="",l.rtp=[],l.rtcpFb=[],R_(l,h),o=!0)}}),o&&(this._log.warn("use ".concat(A?"hw":"sw"," encoder")),yield this.updateSDP())})}sendDataChannelMessage(A){var t;(t=this._datachannel)==null||t.send(A)}reset(){var A;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),this._datachannel=null,(A=this.clearWaitForConnectedPromise)==null||A.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.isDestroyed=!0,this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(A=>Fp(A.abort)&&A.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(A){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(A)||[]).map(o=>t[o])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP(A){let{uplinkRTT:t,downlinkRTT:o}=A;var a;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let l=this._signalChannel.rtt,d=Math.max(t,o),{rttRatioThreshold:h,rttThreshold:y}=((a=this._room.scheduleResult.config)==null?void 0:a.useTurnTcpInfo)||{};if(!(h&&y&&l&&d))return;let S=Math.floor(d/l),L=(this._isRelayTried||S>h)&&d>y;L?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(l," upRTT: ").concat(t," downRTT: ").concat(o," ratio: ").concat(S," over-count: ").concat(this._rttOverCount," isOver: ").concat(L," isRelayTried: ").concat(this._isRelayTried," force-relay: ").concat(this._room.forceRelay)),this.isUsingRelay||this._isRelayTried?this._room.forceRelay&&this.switchRelay(!1):(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0))):this._rttOverCount=0}switchRelay(A){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return XA(this,null,function*(){if(this.isUsingRelay===A)return;let o=A?"relay":"udp",a=A?521709:521710;try{this._room.forceRelay=A,this._log.warn("switchRelay ".concat(o));let l=Date.now();yield this.doSwitchRelay(o),this._log.warn("switchRelay ".concat(o," success")),ri.addSuccessEvent({key:a,cost:Date.now()-l})}catch(l){this._log.warn("switchRelay ".concat(o," failed"),l),ri.addFailedEvent({key:a,error:l}),t?this._room.reJoin():yield this.switchRelay(!A,!0)}})}doSwitchRelay(A){return new Promise((t,o)=>{let a=setTimeout(()=>{this.stopReconnection(),o(new Error("switch ".concat(A," timeout")))},1e4);this.startReconnection().then(t,o).finally(()=>clearTimeout(a))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}requestRemoteFallbackToH264(){this._log.warn("H265 decode failed, remote need to fallback h264"),this._h265DecodeFailed=!0,this._signalChannel.sendWaitForResponse({command:qj,data:{videoDecCodec:"h264"},responseCommand:Qn.UPDATE_CONSTRAINT_CONFIG_RES}).then(A=>{A.data.code!==0&&this._log.warn(A.data.message)})}};Qi([J5("reconnect")],ky.prototype,"startReconnection"),Qi([Ry(A=>A.userId)],ky.prototype,"addDownlink"),Qi([Ry(A=>A)],ky.prototype,"removeDownlink"),Qi([lL(!0)],ky.prototype,"updateSDP"),Qi([wy(521712,!1),f1(10,0)],ky.prototype,"setOffer"),Qi([wy(521713,!1),f1(10,0)],ky.prototype,"setAnswer"),Qi([Xr((A,t)=>function(){for(var o=arguments.length,a=new Array(o),l=0;lclearTimeout(d)),this._checkPendingPromiseSet.clear()),A.apply(this,a)})],ky.prototype,"close");var GnA=class{constructor(A){Y(this,"tag"),Y(this,"len"),Y(this,"data");let t=new DataView(A);this.tag=t.getUint16(),this.len=t.getUint16(2),this.data=new Uint8Array(A).slice(4,4+this.len).buffer}},bnA=class{constructor(A){Y(this,"tinyId"),Y(this,"data");let t=new DataView(A),o=0,a=[];for(;o{S.tag===1?this.tinyId=new TextDecoder().decode(S.data):S.tag===2&&l.push(S.data)});let d=l.reduce((S,L)=>S+L.byteLength,0),h=new Uint8Array(d),y=0;l.forEach(S=>{h.set(new Uint8Array(S),y),y+=S.byteLength}),this.data=h.buffer}},T8=new Set;function sB(){let A=Math.floor(4294967296*Math.random());return T8.has(A)?sB():(T8.add(A),A)}var knA=dc(Xl()),N8=class extends knA.default{constructor(A){super(),Y(this,"userId"),Y(this,"tinyId"),Y(this,"_sdpSemantics"),Y(this,"_isUplink"),Y(this,"_room"),Y(this,"_log"),Y(this,"_currentState","DISCONNECTED"),Y(this,"_prevTime",-1),Y(this,"_blackSmallVideoDetectionId"),Y(this,"isDestroyed",!1),this.userId=A.userId,this.tinyId=A.tinyId,this._room=A.room,this._sdpSemantics=A.room.sdpSemantics,this._isUplink=A.isUplink,this._log=pA.createLogger({parent:this._room.getLogger(),id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var A;return((A=this.singlePC)==null?void 0:A.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(A){this._log.info("close connection"),this.emit("closed",A)}destroy(){this.isDestroyed=!0}emitConnectionStateChangedEvent(A){return A!==this._currentState&&(F.emit(rA.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:A,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:A}),this._currentState=A,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var A,t;return!((t=(A=this._peerConnection)==null?void 0:A.remoteDescription)==null||!t.sdp.includes("H264"))}};function G8(A){let{when:t,onSkip:o}=A;return Xr((a,l)=>function(){for(var d=arguments.length,h=new Array(d),y=0;y{let{mid:S,currentDirection:L,direction:V,stopped:H}=y;return{mid:S,currentDirection:L,direction:V,stopped:H}})))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,a(h)}})),this._updateSDPPromise}setTransceiverDirection(A,t){return XA(this,null,function*(){if(!gr||!this._peerConnection||!this._parsedAnswer)return;this._log.info("setting transceiver ".concat(t.join(",")," direction to ").concat(A));let o=this._peerConnection.getTransceivers();t.forEach(a=>{o[a].direction!==A&&(o[a].direction=A)});for(let a of t){let l=this._parsedAnswer.media[a].direction;A===ir.INACTIVE&&l===ir.RECVONLY&&(this._parsedAnswer.media[a].direction=A),A===ir.SENDONLY&&l===ir.INACTIVE&&(this._parsedAnswer.media[a].direction=ir.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(){return Qc(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"").media.map(A=>A.direction)}setOffer(A){this._log.info("setting offer");let t=wnA(A.sdp,this.clientAbility,this._serverAbility);return this._log.debug(t),this._peerConnection.setLocalDescription({type:"offer",sdp:t})}setAnswer(A){return this._log.info("setting answer"),this._log.debug(A.sdp),this._peerConnection.setRemoteDescription(A)}switchVideoEncoder(A){return XA(this,null,function*(){if(this._parsedAnswer||(this._parsedAnswer=Qc(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let t=!1;this._parsedAnswer.media.forEach(o=>{var a;if(o.type===JA.VIDEO){let l=this._serverAbility.video.codecs.find(d=>d.codec.toLowerCase()===A);l&&((a=o.payloads)==null||!a.includes(String(l.payload)))&&(o.fmtp=[],o.payloads="",o.rtp=[],o.rtcpFb=[],R_(o,l),t=!0)}}),t&&(this._log.warn("switch video encoder to ".concat(A)),yield this.updateSDP())})}getScheduleProfileLevelId(A){var t;try{let o=(t=this._room.scheduleResult.config)==null?void 0:t.profileLevelId,a="";if(A===2?a=gk(o?.big)?o.big:"":A===3?a=gk(o?.small)?o.small:"":A===7&&(a=gk(o?.aux)?o.aux:""),!a)return"";let l=w8(a,this.clientAbility);return l?this._log.info("use schedule profile level id: streamType=".concat(A,", raw=").concat(a,", resolved=").concat(l)):this._log.warn("schedule profile level id not resolved: streamType=".concat(A,", raw=").concat(a)),l}catch(o){return this._log.warn("getScheduleProfileLevelId error: ".concat(o)),""}}getProfileLevelIdConfig(){try{let A=new URLSearchParams(location.search).get("profileLevelId")||"",t=w8(A,this.clientAbility);if(t)return this._log.info("use url profile level id: raw=".concat(A,", resolved=").concat(t)),{big:t,small:t,aux:t};let o=this.getScheduleProfileLevelId(2),a=this.getScheduleProfileLevelId(3),l=this.getScheduleProfileLevelId(7);if(!o&&!a&&!l)return;let d={};return o&&(d.big=o),a&&(d.small=a),l&&(d.aux=l),d}catch(A){return void this._log.warn("getProfileLevelIdConfig error: ".concat(A))}}setH264ProfileLevelId(A,t){return XA(this,null,function*(){if(!this._peerConnection||!this._serverAbility)return;this._updateSDPPromise&&(yield this._updateSDPPromise),this._log.info("set H264 profile-level-id to ".concat(t?"high":"default"," for ").concat(A)),this._parsedAnswer||(this._parsedAnswer=Qc(this._peerConnection.remoteDescription.sdp));let o=A==="main"?1:3,a=this._parsedAnswer.media[o];if(!a||a.type!==JA.VIDEO)return;let l=a.rtp||[],d=a.fmtp||[],h=l.find(lA=>{var hA;return((hA=lA.codec)==null?void 0:hA.toLowerCase())==="h264"});if(!h)return;let y=d.find(lA=>String(lA.payload)===String(h.payload));if(!y)return;let S=Wj(y.config);if(!S)return;let L=zj(S)==="high";if(t&&L||!t&&!L)return;let V=this._serverAbility.video.codecs.map(lA=>Wj(lA.fmtp)).filter(Boolean).find(lA=>{let hA=zj(lA);return t?hA==="high":hA!=="high"});if(!V)return;let H=y.config;y.config=M8(y.config,V),y.config!==H&&(yield this.updateSDP(),this._log.info("set H264 profile-level-id to ".concat(t?"high":"default"," success")))})}useHWEncoder(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0],t=arguments.length>1?arguments[1]:void 0;return XA(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let o=!1,a=[];ze(t)?a=this._parsedAnswer.media.slice(1,4):t===2?a.push(this._parsedAnswer.media[1]):t===3?a.push(this._parsedAnswer.media[2]):t===7&&a.push(this._parsedAnswer.media[3]),a.forEach(l=>{var d;if(l.type===JA.VIDEO){let h;A&&this.is42001fSupported?h=this.clientAbility.video.codecs.find(y=>y.fmtp.includes("42001f")):A||(h=this._serverAbility.video.codecs.find(y=>y.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),h&&((d=l.payloads)==null||!d.includes(String(h.payload)))&&(l.fmtp=[],l.payloads="",l.rtp=[],l.rtcpFb=[],R_(l,h),o=!0)}}),o&&(this._log.warn("use ".concat(A?"hw":"sw"," encoder")),yield this.updateSDP())})}sendDataChannelMessage(A){var t;(t=this._datachannel)==null||t.send(A)}reset(){var A;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),this._datachannel=null,(A=this.clearWaitForConnectedPromise)==null||A.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.isDestroyed=!0,this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(A=>Fp(A.abort)&&A.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(A){if(!this._peerConnection)return[];let t=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(A)||[]).map(o=>t[o])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP(A){let{uplinkRTT:t,downlinkRTT:o}=A;var a;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let l=this._signalChannel.rtt,d=Math.max(t,o),{rttRatioThreshold:h,rttThreshold:y}=((a=this._room.scheduleResult.config)==null?void 0:a.useTurnTcpInfo)||{};if(!(h&&y&&l&&d))return;let S=Math.floor(d/l),L=(this._isRelayTried||S>h)&&d>y;L?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(l," upRTT: ").concat(t," downRTT: ").concat(o," ratio: ").concat(S," over-count: ").concat(this._rttOverCount," isOver: ").concat(L," isRelayTried: ").concat(this._isRelayTried," force-relay: ").concat(this._room.forceRelay)),this.isUsingRelay||this._isRelayTried?this._room.forceRelay&&this.switchRelay(!1):(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0))):this._rttOverCount=0}switchRelay(A){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return XA(this,null,function*(){if(this.isUsingRelay===A)return;let o=A?"relay":"udp",a=A?521709:521710;try{this._room.forceRelay=A,this._log.warn("switchRelay ".concat(o));let l=Date.now();yield this.doSwitchRelay(o),this._log.warn("switchRelay ".concat(o," success")),ri.addSuccessEvent({key:a,cost:Date.now()-l})}catch(l){this._log.warn("switchRelay ".concat(o," failed"),l),ri.addFailedEvent({key:a,error:l}),t?this._room.reJoin():yield this.switchRelay(!A,!0)}})}doSwitchRelay(A){return new Promise((t,o)=>{let a=setTimeout(()=>{this.stopReconnection(),o(new Error("switch ".concat(A," timeout")))},1e4);this.startReconnection().then(t,o).finally(()=>clearTimeout(a))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}requestRemoteFallbackToH264(){this._log.warn("H265 decode failed, remote need to fallback h264"),this._h265DecodeFailed=!0,this._signalChannel.sendWaitForResponse({command:qj,data:{videoDecCodec:"h264"},responseCommand:Qn.UPDATE_CONSTRAINT_CONFIG_RES}).then(A=>{A.data.code!==0&&this._log.warn(A.data.message)})}};Qi([J5("reconnect")],ky.prototype,"startReconnection"),Qi([Ry(A=>A.userId)],ky.prototype,"addDownlink"),Qi([Ry(A=>A)],ky.prototype,"removeDownlink"),Qi([lL(!0)],ky.prototype,"updateSDP"),Qi([wy(521712,!1),f1(10,0)],ky.prototype,"setOffer"),Qi([wy(521713,!1),f1(10,0)],ky.prototype,"setAnswer"),Qi([Xr((A,t)=>function(){for(var o=arguments.length,a=new Array(o),l=0;lclearTimeout(d)),this._checkPendingPromiseSet.clear()),A.apply(this,a)})],ky.prototype,"close");var GnA=class{constructor(A){Y(this,"tag"),Y(this,"len"),Y(this,"data");let t=new DataView(A);this.tag=t.getUint16(),this.len=t.getUint16(2),this.data=new Uint8Array(A).slice(4,4+this.len).buffer}},bnA=class{constructor(A){Y(this,"tinyId"),Y(this,"data");let t=new DataView(A),o=0,a=[];for(;o{S.tag===1?this.tinyId=new TextDecoder().decode(S.data):S.tag===2&&l.push(S.data)});let d=l.reduce((S,L)=>S+L.byteLength,0),h=new Uint8Array(d),y=0;l.forEach(S=>{h.set(new Uint8Array(S),y),y+=S.byteLength}),this.data=h.buffer}},T8=new Set;function sB(){let A=Math.floor(4294967296*Math.random());return T8.has(A)?sB():(T8.add(A),A)}var knA=dc($l()),N8=class extends knA.default{constructor(A){super(),Y(this,"userId"),Y(this,"tinyId"),Y(this,"_sdpSemantics"),Y(this,"_isUplink"),Y(this,"_room"),Y(this,"_log"),Y(this,"_currentState","DISCONNECTED"),Y(this,"_prevTime",-1),Y(this,"_blackSmallVideoDetectionId"),Y(this,"isDestroyed",!1),this.userId=A.userId,this.tinyId=A.tinyId,this._room=A.room,this._sdpSemantics=A.room.sdpSemantics,this._isUplink=A.isUplink,this._log=pA.createLogger({parent:this._room.getLogger(),id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var A;return((A=this.singlePC)==null?void 0:A.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(A){this._log.info("close connection"),this.emit("closed",A)}destroy(){this.isDestroyed=!0}emitConnectionStateChangedEvent(A){return A!==this._currentState&&(F.emit(rA.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:A,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:A}),this._currentState=A,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var A,t;return!((t=(A=this._peerConnection)==null?void 0:A.remoteDescription)==null||!t.sdp.includes("H264"))}};function G8(A){let{when:t,onSkip:o}=A;return Xr((a,l)=>function(){for(var d=arguments.length,h=new Array(d),y=0;ypostMessage({type:"log",message:"[worker] "+t.join(" ")});function startDetection(e,t,a){if(!tracks.has(e)){const c={reader:a.getReader(),blackCount:0,timeoutId:null,intervalId:null};tracks.set(e,c),c.timeoutId=setTimeout(()=>stopDetection(e,"timeout"),t),c.intervalId=setInterval(async()=>{try{await isFrameBlack(e)?(c.blackCount++,postMessage({type:"blackCount",trackId:e,count:c.blackCount}),3<=c.blackCount&&(postMessage({type:"black",trackId:e}),stopDetection(e,"black"))):c.blackCount=0}catch(t){log("check black video error:",t.message),stopDetection(e,"error")}},1e3)}}function stopDetection(t,e){var a=tracks.get(t);a&&(a.timeoutId&&clearTimeout(a.timeoutId),a.intervalId&&clearInterval(a.intervalId),a.reader&&a.reader.cancel(),tracks.delete(t),postMessage({type:e,trackId:t}))}async function isFrameBlack(t){t=tracks.get(t);if(!t)return!1;var t=t.reader,{done:t,value:e}=await t.read();if(!e||t)return!1;canvas||(canvas=new OffscreenCanvas(e.codedWidth,e.codedHeight),ctx=canvas.getContext("2d",{willReadFrequently:!0})),canvas.width===e.codedWidth&&canvas.height===e.codedHeight||(canvas.width=e.codedWidth,canvas.height=e.codedHeight,ctx=canvas.getContext("2d",{willReadFrequently:!0})),ctx.drawImage(e,0,0,canvas.width,canvas.height);t=getFrameBlackRatio(ctx.getImageData(0,0,canvas.width,canvas.height));return e.close(),1===t}function getFrameBlackRatio(t){var e=t.data;let a=0;for(let t=0;t<100;t++){var c=4*Math.floor(Math.random()*(e.length/4)),[c,r,n,o]=[e[c],e[1+c],e[2+c],e[3+c]];0{var{type:t,trackId:e,timeout:a,readable:c}=t.data;"addTrack"===t&&startDetection(e,a,c),"removeTrack"===t&&stopDetection(e)}; - `],{type:"application/javascript"}),t=URL.createObjectURL(A);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=o=>this._log.warn("worker error:",o.message,o.filename||"unknown",o.lineno||"unknown"),this.worker.onmessage=o=>{var a;let{type:l,trackId:d,message:h,count:y}=o.data;if(l==="black")(a=this.callbacks.get(d))==null||a();else if(l==="log")this._log.warn(h);else if(l==="blackCount"){let S=this.userIdMap.get(d);this._log.warn("".concat(S||d," black count: ").concat(y))}}}return this.worker}start(A){let{track:t,isUplink:o,room:a,userId:l,onBlack:d}=A;if(this._log.debug("start detect black video",t.id),!Uv()||!d||!t||typeof Worker>"u")return void this._log.warn("black video detector not supported");let h=y=>{var S,L,V,H;let lA;if(o)lA=(L=(S=y.msg_up_stream_info)==null?void 0:S.msg_video_status)==null?void 0:L.filter(hA=>hA.uint32_video_stream_type===3)[0];else{let hA=(V=y.msg_down_stream_info)==null?void 0:V.filter(MA=>{var oe;return((oe=MA.msg_user_info)==null?void 0:oe.str_identifier)===l})[0];lA=(H=hA?.msg_video_status)==null?void 0:H.filter(MA=>MA.uint32_video_stream_type===3)[0]}if(lA){let hA=(lA.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[t.id]&&this.sleep[t.id]>0)return void(this.sleep[t.id]-=1);hA>0&&hA<10&&(this.sleep[t.id]=30,this._log.info("track bitrate",hA,"start check"),this.checkOnce(t,3e4))}};return a.on("heartbeat-report",h),this.heartbeatListenerCleaner.set(t.id,()=>a.off("heartbeat-report",h)),this.callbacks.set(t.id,d),this.userIdMap.set(t.id,l),t.id}checkOnce(A,t){try{let o=this.getWorker();if(!o)throw new Error("Worker not available");let a=new MediaStreamTrackProcessor({track:A});o.postMessage({type:"addTrack",trackId:A.id,timeout:t,readable:a.readable},[a.readable])}catch(o){this._log.warn("check error:",o),this.stop(A.id)}}stop(A){if(A){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:A}),this.callbacks.delete(A),delete this.sleep[A];let t=this.heartbeatListenerCleaner.get(A);t&&t(),this.heartbeatListenerCleaner.delete(A),this.userIdMap.delete(A)}}destroy(){this.callbacks.forEach((A,t)=>this.stop(t)),this.worker&&(this.worker.terminate(),this.worker=null)}},q1=class extends N8{constructor(A){super(So(Di({},A),{isUplink:!0})),Y(this,"localMainAudioTrack",null),Y(this,"localMainVideoTrack",null),Y(this,"localAuxAudioTrack",null),Y(this,"localAuxVideoTrack",null),Y(this,"_isPublishingAux",!1),Y(this,"_publishingLocalAudioTrack"),Y(this,"_publishingLocalVideoTrack"),Y(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,videoDecCodec:"",audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),Y(this,"_flag",0),Y(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get videoCodec(){var A;return((A=this.singlePC)==null?void 0:A.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:A,bigVideoSsrc:t,bigVideoRtxSsrc:o,smallVideoSsrc:a,smallVideoRtxSsrc:l,auxVideoSsrc:d,auxVideoRtxSsrc:h}=this.singlePC.uplinkSSRC;return{audio:A||0,video:t||0,videoRtx:o||0,small:a||0,smallRtx:l||0,auxiliary:d||0,auxiliaryRtx:h||0}}get flag(){return this._flag}set flag(A){this._flag!==A&&(this._flag=A,this.checkPublishState())}checkPublishState(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];try{if(!A&&this._checkPublishStateTimeoutId>0)return;let{serverPublishState:t}=this,{publishState:o}=this._room,a=Object.keys(o).filter(l=>{if(o[l]!==t[l]&&o[l])switch(l){case"audio":return!(!this.localMainAudioTrack||!this.localMainAudioTrack.isMediaTrackActive);case"bigVideo":case"smallVideo":return!(!this.localMainVideoTrack||!this.localMainVideoTrack.isMediaTrackActive);case"auxVideo":return!(!this.localAuxVideoTrack||!this.localAuxVideoTrack.isMediaTrackActive)}return!1});if(a.length>0){if(!A)return void(this._checkPublishStateTimeoutId=kr.run("timeout",()=>this.checkPublishState(!0),{delay:1e4,count:1}));ri.addCount({key:521e3}),a.forEach(l=>{this._log.warn("".concat(l," publish failed during call ").concat(jp()," ").concat(lQ())),ri.addEnum({key:521719,value:b8[l]})}),kr.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(t){this._log.warn("checkPublishState failed",t)}}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get serverPublishState(){return{audio:!!(this.flag&iv),bigVideo:!!(this.flag&ev),smallVideo:!!(this.flag&Fb),auxVideo:!!(this.flag&tv)}}initialize(){this.installEvents()}close(A){var t;let o=((t=this._peerConnection)==null?void 0:t.getSenders())||[];for(let a of o)a.replaceTrack(null);super.close(A),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var A,t;(A=this.singlePC)!=null&&A.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var A;(A=this.singlePC)==null||A.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(A,t){var o,a,l;let d=this._currentState,h=super.emitConnectionStateChangedEvent(A);return h&&d!==A&&(t?t.emit("connection-state-changed",{prevState:d,state:A}):((o=this.localMainVideoTrack)==null||o.emit("connection-state-changed",{prevState:d,state:A}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:d,state:A}),(l=this._publishingLocalVideoTrack)==null||l.emit("connection-state-changed",{prevState:d,state:A}))),h}onVideoEncodeFailed(A){return XA(this,null,function*(){if(!A||!A.isMediaTrackActive)return;let{videoCodec:t,singlePC:o}=this;if(!o)return;let a={h265:{supported:o.isH264EncodeSupported,target:"h264",log:"h265 encoder not working"},h264:{supported:o.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}};if(t==="vp9"||t==="av1")return;let l=a[t];this._log.warn(l.log),l!=null&&l.supported&&(yield o.switchVideoEncoder(l.target))})}publish(A){return XA(this,arguments,function(t){var o=this;let{localAudioTrack:a,localVideoTrack:l,isAuxiliary:d}=t;return function*(){var h,y,S,L,V,H,lA;if(!o.singlePC)return;if(o.installEvents(),o.installTrackMuteEvents(a,l),l&&(l.retryEncodeFailed=o.onVideoEncodeFailed.bind(o),ng&&(uy(PI,"26.2",!0)||uy(aQ,"26.2",!0)||sQ&&uy(PI,"18.7",!0)))){o._log.warn("detectH264Supported for fallback 26.2 video encode issue");try{yield ge.detectH264SupportedByFakeStreaming(500)}catch{}}if(yield o.singlePC.waitForPeerConnectionConnected(),a&&(o._publishingLocalAudioTrack=a),l){if(!o.singlePC.isH264EncodeSupported&&!o.singlePC.isVP8EncodeSupported)throw new li({code:mt.NOT_SUPPORTED_H264,message:sn({key:Go.NOT_SUPPORTED_H264ENCODE})});o.singlePC.isUsingH264&&!o.singlePC.isH264EncodeSupported&&o.singlePC.isVP8EncodeSupported&&(o._log.warn("h264 encoder not supported"),yield o.singlePC.switchVideoEncoder("vp8")),za&&wv()===115&&l.profile.width*l.profile.height<=230400&&(o._log.warn("fallback video to defaultBigVideoProfile: ".concat(JSON.stringify(Av))),l.setProfile(Av),yield l.applyProfile()),o._publishingLocalVideoTrack=l}let hA;if(o._isPublishingAux=d,l&&!d&&l.small&&(hA=o._room.videoManager.smallTrack),yield o._signalChannel.sendWaitForResponseWithRetry({command:I8,responseCommand:Qn.SPC_PUBLISH_RESULT,data:So(Di({},o.singlePC.uplinkSSRC),{state:o._room.publishState,muteState:o._room.muteState}),retries:3}),l&&(yield o.checkHighProfile({streamType:l.streamType,newWidth:l.settings.width,newHeight:l.settings.height})),yield o.publishByTransceiver({localAudioTrack:a,localVideoTrack:l,smallTrack:hA,isAuxiliary:d}),o._publishingLocalAudioTrack=null,o._publishingLocalVideoTrack=null,o._isPublishingAux=!1,l){o[d?"localAuxVideoTrack":"localMainVideoTrack"]=l,yield o.singlePC.setDegradationPreference(o._peerConnection.getSenders()[d?3:1],l.contentHint,l.streamType);let{scaleResolutionDownBy:oe}=l;yield o.singlePC.setScaleResolutionDownBy(o._peerConnection.getSenders()[d?3:1],oe,l.streamType)}a&&(o[d?"localAuxAudioTrack":"localMainAudioTrack"]=a),yield o.singlePC.setBandwidth({audio:((h=o.localMainAudioTrack)==null?void 0:h.profile.bitrate)||((y=o.localAuxAudioTrack)==null?void 0:y.profile.bitrate),bigVideo:(S=o.localMainVideoTrack)==null?void 0:S.profile.bitrate,smallVideo:(V=(L=o.localMainVideoTrack)==null?void 0:L.small)==null?void 0:V.bitrate,auxVideo:(H=o.localAuxVideoTrack)==null?void 0:H.profile.bitrate}),o.sendMediaSettings();let MA=d?7:2;(o._room.preferHW||(lA=o._room.scheduleResult.config)!=null&&lA.preferHW)&&l&&l.profile.width*l.profile.height>=921600&&o.singlePC.useHWEncoder(!0,MA)}()})}publishByTransceiver(A){let{localAudioTrack:t,localVideoTrack:o,smallTrack:a,isAuxiliary:l}=A;if(!AC())return;this._log.info("publish by transceiver");let d=o?.outMediaTrack,h=t?.outMediaTrack,y=this._peerConnection.getTransceivers(),S=[],L=[],V=(lA,hA,MA)=>{var oe;let fe=y[hA].sender.replaceTrack(MA);L.push(hA),(oe=this.singlePC)!=null&&oe.enableInsertableStreams&&fe.then(()=>this.createEncodedStreams(y[hA].sender,lA)),this.initSenderTransform(y[hA].sender,lA),S.push(fe)};h&&V(t.mediaType,0,h),d&&V(o.mediaType,l?3:1,d),o!=null&&o.small&&S.push(this.publishSmall(this._room.videoManager.smallMode,o));let H=this.singlePC.setTransceiverDirection(ir.SENDONLY,L);return S.push(H),Promise.all(S)}getTrackByMediaType(A){switch(A){case 1:return this.localMainAudioTrack||this._room.localMainAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._room.localMainVideoTrack;case 2:return this.localAuxVideoTrack||this._room.localAuxVideoTrack;default:return null}}createEncodedStreams(A,t){var o,a;if(this.singlePC.insertableStreamsAbortMap.has(A))return;let l=A.createEncodedStreams(),d=new AbortController;(o=this.singlePC)==null||o.addAbortController(A,d),((a=this.getTrackByMediaType(t))!=null&&a.enableEncodeFrame?l.readable.pipeThrough(new TransformStream({transform:(h,y)=>{var S,L;let V=this.getTrackByMediaType(t);if(!V||!V.encodeFrame)return y.enqueue(h);V.isAudio?y.enqueue(V.enableEncodeFrame?V.encodeFrame(h):h):y.enqueue((S=this.singlePC)!=null&&S.isUsingH264||(L=this.singlePC)!=null&&L.isUsingH265?V.encodeFrame(h,t===8):h)}}),d):l.readable).pipeTo(l.writable,d).catch(h=>{this._log.debug("encoded stream error",h),h!=="destroy"&&this._log.warn(h)})}initSenderTransform(A,t){if(!(this._peerConnection&&this.singlePC&&this.singlePC.scriptTransformWorker&&c_))return;let o=t!==2,a=t===8;A.transform||(A.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:o,isSmall:a}))}enableSmall(A){return XA(this,null,function*(){A?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(A){return XA(this,arguments,function(t){var o=this;let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.localMainVideoTrack;return function*(){var l;if(!o.singlePC)return;if(t==="canvas"&&!g_())return void o._log.warn("canvas mode small stream is not supported");let d=o._peerConnection.getTransceivers(),{sender:h}=d[2],y=yield o.doPublishSmall(t,a),S=t==="canvas"?524700:524701;ri.addSuccessEvent({key:S}),y?((l=o.singlePC)!=null&&l.enableInsertableStreams&&o.createEncodedStreams(h,8),o.initSenderTransform(h,8),yield o.singlePC.setTransceiverDirection(ir.SENDONLY,[2]),o.updateMediaSettings(),yield o.doPublishChange(),h.track&&(o._blackSmallVideoDetectionId=aM.start({track:h.track,room:o._room,isUplink:!0,userId:o.userId,onBlack:()=>{o._log.warn("small video is black");let L=t==="canvas"?524700:524701;ri.addFailedEvent({key:L,error:10002}),aM.stop(o._blackSmallVideoDetectionId),o._blackSmallVideoDetectionId=void 0}}))):ri.addFailedEvent({key:S,error:10001})}()})}doPublishSmall(A){return XA(this,arguments,function(t){var o=this;let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.localMainVideoTrack;return function*(){if(!o.singlePC)return null;o._log.info("publish small",t);let l=o._peerConnection.getTransceivers(),{sender:d}=l[2];if(t==="canvas"&&o._room.videoManager.smallTrack)return yield d.replaceTrack(o._room.videoManager.smallTrack),"canvas";if(t==="api"&&a!=null&&a.outMediaTrack&&a!=null&&a.small){yield d.replaceTrack(a?.outMediaTrack);let h=d.getParameters(),y=F0(a?.profile,a?.small);return o._log.info("small scaleResolutionDownBy",y),h.encodings[0].scaleResolutionDownBy=y,d.setParameters(h),"api"}return o._log.warn("small track can not be enabled, smallMode: ".concat(o._room.videoManager.smallMode,", smallTrack: ").concat(!!o._room.videoManager.smallTrack,", bigVideoTrack: ").concat(!(a==null||!a.outMediaTrack))),null}()})}unpublishSmall(){return XA(this,null,function*(){this.singlePC&&(this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(ir.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),aM.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)})}checkHighProfile(A){return XA(this,null,function*(){var t,o;if((((t=this._room.scheduleResult.config)==null?void 0:t.profileLevelId)||{})[A.streamType==="main"?"big":"aux"]!=="high")return;let a=A.newWidth*A.newHeight>=921600&&!Ey();try{yield(o=this.singlePC)==null?void 0:o.setH264ProfileLevelId(A.streamType,a)}catch(l){this._log.warn("setH264ProfileLevelId failed, ignore",l)}})}installTrackMuteEvents(){for(var A=arguments.length,t=new Array(A),o=0;o{a&&(a?.on("mute",this.sendMutedFlag,this),a?.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(){for(var A=arguments.length,t=new Array(A),o=0;o{a&&(a?.off("mute",this.sendMutedFlag,this),a?.off("unmute",this.sendMutedFlag,this))})}unpublish(A){return XA(this,arguments,function(t){var o=this;let{localAudioTrack:a,localVideoTrack:l}=t;return function*(){var d;yield(d=o.singlePC)==null?void 0:d.waitForPeerConnectionConnected();let h=l&&l===o.localAuxVideoTrack||a&&a===o.localAuxAudioTrack,y=l?.outMediaTrack,S=o._peerConnection.getSenders(),L=[];a&&(h?o.localAuxAudioTrack=null:o.localMainAudioTrack=null,!o.localMainAudioTrack&&!o.localAuxAudioTrack&&(yield S[0].replaceTrack(null),L.push(0))),y&&(h?(yield S[3].replaceTrack(null),o.localAuxVideoTrack=null,o._mediaSettings=So(Di({},o._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),L.push(3)):(yield S[1].replaceTrack(null),yield S[2].replaceTrack(null),o.localMainVideoTrack=null,o._mediaSettings=So(Di({},o._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),L.push(1,2))),o.isMainStreamPublished||o.isAuxStreamPublished?(yield o.singlePC.setTransceiverDirection(ir.INACTIVE,L),yield o.doPublishChange(!1)):yield o.doUnpublish(),o.uninstallTrackMuteEvents(a,l),l?.emit("connection-state-changed",{prevState:o._currentState,state:"DISCONNECTED"})}()})}doPublishChange(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return XA(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},o=yield this._signalChannel.sendWaitForResponseWithRetry({command:Vj,data:t,responseCommand:Qn.PUBLISH_STATE_CHANGE_RESULT,enableLog:A,retries:3});this.checkPublishResultCode(o.data.code,o.data.message)})}doUnpublish(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this._signalChannel.sendWaitForResponse({command:P1,commandDesc:"unpublish",responseCommand:Qn.UNPUBLISH_RESULT,enableLog:A}).catch(t=>{if(t.getCode()===mt.API_CALL_TIMEOUT||t.getCode()===mt.API_CALL_ABORTED)return Promise.resolve();throw t})}updateMediaSettings(){var A,t;this._mediaSettings.videoCodec=((A=this.singlePC)==null?void 0:A.videoCodec)||"h264",this._mediaSettings.videoDecCodec=((t=this.singlePC)==null?void 0:t.downlinkVideoCodec)||"h264";let o=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:a,localAuxVideoTrack:l}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?l=this._publishingLocalVideoTrack:a=this._publishingLocalVideoTrack),Dy){if(o&&o.outMediaTrack){let d=o.outMediaTrack.getSettings();this._mediaSettings.audioChannel=d.channelCount||1,this._mediaSettings.audioBps=1e3*o.profile.bitrate,this._mediaSettings.audioFs=d.sampleRate||0}if(a&&a.outMediaTrack){let d=a.outMediaTrack.getSettings(),{scaleResolutionDownBy:h}=a;this._mediaSettings.videoWidth=(d.width||0)/h||0,this._mediaSettings.videoHeight=(d.height||0)/h||0,this._mediaSettings.videoFps=d.frameRate||0,this._mediaSettings.videoBps=1e3*a.profile.bitrate,a.small&&(this._mediaSettings.smallVideoWidth=a.small.width,this._mediaSettings.smallVideoHeight=a.small.height,this._mediaSettings.smallVideoFps=a.small.frameRate,this._mediaSettings.smallVideoBps=1e3*a.small.bitrate)}if(l&&l.outMediaTrack){let d=l.outMediaTrack.getSettings(),{scaleResolutionDownBy:h}=l;this._mediaSettings.auxVideoWidth=(d.width||0)/h||0,this._mediaSettings.auxVideoHeight=(d.height||0)/h||0,this._mediaSettings.auxVideoFps=d.frameRate||0,this._mediaSettings.auxVideoBps=1e3*l.profile.bitrate}}else o&&o.outMediaTrack&&(this._mediaSettings.audioChannel=o.profile.channelCount,this._mediaSettings.audioBps=1e3*o.profile.bitrate,this._mediaSettings.audioFs=o.profile.sampleRate),a&&a.outMediaTrack&&(this._mediaSettings.videoWidth=a.profile.width,this._mediaSettings.videoHeight=a.profile.height,this._mediaSettings.videoFps=a.profile.frameRate,this._mediaSettings.videoBps=1e3*a.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:qj,data:this._mediaSettings,responseCommand:Qn.UPDATE_CONSTRAINT_CONFIG_RES}).then(A=>{A.data.code!==0&&this._log.warn(A.data.message)}).catch(()=>{})}addTrack(A){return XA(this,null,function*(){if(!this._peerConnection)return;let t=A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;this._log.info("is adding ".concat(A.kind," track to current published local ").concat(t?JA.AUXILIARY:JA.MAIN," stream")),CQ()&&(yield this.addTrackByTransceiver(A,t))})}addTrackByTransceiver(A,t){return XA(this,null,function*(){var o;if(!A.mediaTrack)return;let a=this._peerConnection.getTransceivers();if(A.kind===JA.AUDIO)yield a[0].sender.replaceTrack(A.outMediaTrack);else{let l=t?3:1;yield a[l].sender.replaceTrack(A.outMediaTrack),l===1&&(o=this.localMainVideoTrack)!=null&&o.small&&this._room.videoManager.smallTrack&&(yield a[2].sender.replaceTrack(this._room.videoManager.smallTrack)),a[l].direction===ir.INACTIVE&&(yield this.singlePC.setTransceiverDirection(ir.SENDONLY,[l]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(A){return XA(this,null,function*(){if(!this._peerConnection)return;let t=A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;this._log.info("is removing ".concat(A.kind," track from current published local ").concat(t?JA.AUXILIARY:JA.MAIN," stream")),CQ()&&(yield this.removeTrackByTransceiver(A,t))})}removeTrackByTransceiver(A,t){return XA(this,null,function*(){if(!A.mediaTrack)return;let o=this._peerConnection.getTransceivers();if(A.kind===JA.AUDIO)yield o[0].sender.replaceTrack(null);else{let a=t?3:1;yield o[a].sender.replaceTrack(null),a===1&&this._room.videoManager.hasSmall&&(yield o[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(ir.INACTIVE,[a])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(A){return XA(this,null,function*(){var t;let o=(t=this._peerConnection)==null?void 0:t.getSenders(),a=A.outMediaTrack||A.mediaTrack;if(!o||o.length===0||!a||o.find(d=>d.track===a))return!1;let l=A.mediaType===2||A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(a.kind," track ").concat(a.id," ").concat(a.label," on ").concat(l?JA.AUXILIARY:JA.MAIN," stream")),a.kind===JA.AUDIO&&o[0]&&(yield o[0].replaceTrack(a)),a.kind===JA.VIDEO&&(!l&&o[1]&&(yield o[1].replaceTrack(a)),l&&o[3]&&(yield o[3].replaceTrack(a))),!0})}setBandwidth(A){return XA(this,arguments,function(t){var o=this;let{bandwidth:a,type:l,videoType:d}=t;return function*(){if(o.singlePC){let h={};l===JA.AUDIO?h.audio=a:d==="big"?h.bigVideo=a:d==="small"?h.smallVideo=a:h.auxVideo=a,yield o.singlePC.setBandwidth(h)}}()})}sendMutedFlag(A){A===this.localAuxAudioTrack||A===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:g8,responseCommand:Qn.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(A){A.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&F.emit(rA.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:JA.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(A===JA.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(A===JA.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&A===JA.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&A===JA.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(A,t){if(A!==0)throw A===m0?(this._log.error(Cc.NOT_SUPPORTED_H264ENCODE),new li({code:mt.NOT_SUPPORTED_H264,message:sn({key:Go.NOT_SUPPORTED_H264ENCODE})})):new li({code:mt.UNKNOWN,message:sn({key:Go.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Qn.PUBLISH_RESULT,code:A,message:t}})})}onSinglePCReconnected(){return XA(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};Qi([Xv(A=>{let{localVideoTrack:t}=A;t==null||delete t.retryEncodeFailed})],q1.prototype,"unpublish"),Qi([G8({when(){return this.isDestroyed}})],q1.prototype,"doPublishChange"),Qi([G8({when(){return this.isDestroyed}})],q1.prototype,"doUnpublish");var b8=(A=>(A[A.audio=1]="audio",A[A.bigVideo=2]="bigVideo",A[A.smallVideo=3]="smallVideo",A[A.auxVideo=4]="auxVideo",A))(b8||{}),k8=q1;function L8(A){return Object.keys(A).filter(t=>A[t])}var K1=class extends N8{constructor(A){super(So(Di({},A),{isUplink:!1})),Y(this,"_flag",0),Y(this,"isRobot",!1),Y(this,"role","anchor"),Y(this,"fromType"),Y(this,"remoteAudioTrack"),Y(this,"remoteVideoTrack"),Y(this,"remoteAuxiliaryTrack"),Y(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),Y(this,"_prevMids"),Y(this,"jitterBufferTimeoutId",-1),Y(this,"_jitterBufferResolve"),Y(this,"_videoCodec"),Y(this,"avPlayerStateSyncManager"),Y(this,"isDataChannelSubscribed",!1),this.flag=A.flag,this.isRobot=A.isRobot||!1,this.fromType=A.fromType,this.remoteAudioTrack=new y1(this._room,this),this.remoteVideoTrack=new fL(this._room,this),this.remoteAuxiliaryTrack=new fz(this._room,this),this.avPlayerStateSyncManager=new _j({log:this._log,audioPlayer:this.remoteAudioTrack.player,videoPlayer:this.remoteVideoTrack.player}),this.initialize()}get videoCodec(){var A;return this._videoCodec||((A=this.singlePC)==null?void 0:A.downlinkVideoCodec)||"h264"}set videoCodec(A){this._videoCodec=A}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing,datachannel:this.isDataChannelSubscribed}}get muteState(){return kp(this.flag,this.userId)}get flag(){return this._flag}set flag(A){var t,o,a;A!==this._flag&&(this._flag=A,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(o=this.remoteVideoTrack)==null||o.onFlagChanged(),(a=this.remoteAuxiliaryTrack)==null||a.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(A){return A===JA.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(A){clearTimeout(this.jitterBufferTimeoutId),super.close(A),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.avPlayerStateSyncManager.destroy(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.on("decode-failed",this.onDecodeFailed,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.off("decode-failed",this.onDecodeFailed,this))}emitConnectionStateChangedEvent(A){var t,o;let a=this._currentState,l=super.emitConnectionStateChangedEvent(A);return l&&a!==A&&((t=this.remoteVideoTrack)==null||t.emit("connection-state-changed",{prevState:a,state:A}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:a,state:A})),l}onTrack(A){var t,o;let a=A.streams[0],{track:l,receiver:d}=A;if(!a.id.includes(this.tinyId))return;let h=a.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(h," ").concat(l.kind));let y=JA.AUDIO;l.kind===JA.VIDEO&&(y=h===JA.MAIN?JA.VIDEO:JA.AUXILIARY);let S=this.remoteAudioTrack;y===JA.VIDEO?S=this.remoteVideoTrack:y===JA.AUXILIARY&&(S=this.remoteAuxiliaryTrack),(t=this.singlePC)==null||t.receiverRemoteTrackMap.set(d,S),(o=this.singlePC)!=null&&o.scriptTransformWorker&&this.initReceiverTransform(d,h,l.kind===JA.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(d),S.setInputMediaStreamTrack(l)}createEncodedStreams(A){if(!this.singlePC.insertableStreamsAbortMap.has(A)){let t=A.createEncodedStreams(),o=new AbortController,a={abortController:o,enqueue:l=>{var d,h,y;let S=(d=this.singlePC)==null?void 0:d.receiverRemoteTrackMap.get(A);return S&&(S.kind!=="video"||(h=this.singlePC)!=null&&h.isUsingH264||(y=this.singlePC)!=null&&y.isUsingH265)?S.decodeFrame(l):l}};t.readable.pipeThrough(new TransformStream({transform:(l,d)=>{let h=a.enqueue(l);h&&d.enqueue(h)}})).pipeTo(t.writable,o).catch(l=>{l!=="destroy"&&this._log.warn(l)}),this.singlePC.addAbortController(A,o)}}initReceiverTransform(A,t,o){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||A.transform||(A.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:o,userId:this.userId,streamType:t}))}subscribe(A,t){return XA(this,null,function*(){var o,a;try{let l=!0;if(this._log.info("subscribe ".concat(t," ").concat(L8(A))),this.hasSSRC){let y="subscribe_change";Object.values(A).find(S=>S===!0)||(y="unsubscribe"),yield this.sendSubscription(y,A)}else{if(yield this._room.switchRoomSubedReq,(o=this.singlePC)!=null&&o.autoSubscribedUserMap.size){let y=this.singlePC.autoSubscribedUserMap.get(this.userId);if(y){this.singlePC.autoSubscribedUserMap.delete(this.userId);let S=(a=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:a[y.groupIndex];S&&(this.ssrc={audio:S.audioSsrc,video:S.bigVideoSsrc,videoRtx:S.bigVideoRtxSsrc,auxiliary:S.auxVideoSsrc,auxiliaryRtx:S.auxVideoRtxSsrc},l=!1)}}yield this.doSubscribe(A,l),this.checkTrackEnded(A)}let{user:d,mediaTrack:h}=this.remoteVideoTrack;A.smallVideo&&h?(ri.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=aM.start({track:h,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,d),ri.addFailedEvent({key:524702}),aM.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(aM.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}catch(l){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(l.message," ").concat(JSON.stringify(this.muteState))),new li({code:mt.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):l}})}checkTrackEnded(A){var t,o,a;if((A.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||A.video&&((o=this.remoteVideoTrack.mediaTrack)==null?void 0:o.readyState)==="ended"||A.auxiliary&&((a=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:a.readyState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),EE&&nd<92)return;this.singlePC.startReconnection()}}unsubscribe(A){return XA(this,arguments,function(t){var o=this;let{remoteTracks:a,streamType:l}=t;return function*(){var d;if(l==="main"&&!o.isMainStreamSubscribed||l==="auxiliary"&&!o.isAuxStreamSubscribed)return void o._log.info("".concat(l," stream already unsubscribed"));let h=Di({},o.subscribeState);a.forEach(S=>{switch(S.mediaType){case 1:h.audio=!1;break;case 4:h.video=!1;break;case 8:h.smallVideo=!1;break;case 2:h.auxiliary=!1}});let y="subscribe_change";Object.values(h).find(S=>S===!0)||(y="unsubscribe"),o._log.info("".concat(y==="unsubscribe"?y:"subscribe"," ").concat(l," [").concat(L8(h),"]")),y==="unsubscribe"&&((d=o.singlePC)==null||d.removeDownlinkQueue.add(o.tinyId)),yield o.sendSubscription(y,h),l==="main"&&(aM.stop(o._blackSmallVideoDetectionId),o._blackSmallVideoDetectionId=void 0),y==="unsubscribe"&&(yield o.removeDownlink())}()})}subscribeDataChannel(){return XA(this,null,function*(){if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let A=So(Di({},this.subscribeState),{datachannel:!0});yield this.doSubscribe(A)})}unsubscribeDataChannel(){return XA(this,null,function*(){let A=So(Di({},this.subscribeState),{datachannel:!1});yield this.sendSubscription("unsubscribe",A),yield this.removeDownlink()})}sendSubscription(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscribeState,o={srcTinyId:this.tinyId,srcUserId:this.userId},a=Hj,l=Qn.UNSUBSCRIBE_RESULT;return A==="subscribe_change"&&(o={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:t.datachannel,srcTinyId:this.tinyId},a=Jj,l=Qn.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:a,data:o,responseCommand:l,timeout:1e4,retries:3}).then(d=>{let{data:h}=d;if(h.code!==0){let y=new li({code:h.code,message:sn({key:Go.ERROR_MESSAGE,data:{type:A,message:h.message}})});throw this._log.error(y),y}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay(A){let{audioDelay:t,videoDelay:o}=A;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=o}onSinglePCReconnected(){return XA(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary||this.isDataChannelSubscribed)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return XA(this,arguments,function(){var A=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.subscribeState,o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return function*(){var a,l;if(A.singlePC){A.singlePC.addDownlinkQueue.add(A.tinyId),yield A.singlePC.waitForPeerConnectionConnected();try{if(o||!A.hasSSRC){let d={audioSsrc:sB(),bigVideoSsrc:sB(),bigVideoRtxSsrc:sB(),auxVideoSsrc:sB(),auxVideoRtxSsrc:sB()},{audioSsrc:h,bigVideoSsrc:y,bigVideoRtxSsrc:S,auxVideoSsrc:L,auxVideoRtxSsrc:V}=d;A.ssrc={audio:h,video:y,videoRtx:S,auxiliary:L,auxiliaryRtx:V},A.singlePC.addDownlinkQueue.delete(A.tinyId),yield A.singlePC.addDownlink({userId:A.userId,tinyId:A.tinyId,ssrc:A.ssrc,prevMids:A._prevMids});try{let H=yield A._signalChannel.sendWaitForResponseWithRetry({command:u8,responseCommand:Qn.SPC_SUBSCRIBE_RESULT,data:{srcUserId:A.userId,srcTinyId:A.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:(a=t.datachannel)!=null&&a,ssrc:d},retries:3,retryTimeout:0});if(H.data.code!==0&&H.data.code!==-10036)throw new li({code:H.data.code,message:H.data.message});A.isDataChannelSubscribed=(l=t.datachannel)!=null&&l}catch(H){throw yield A.removeDownlink(),H}return}A.singlePC.addDownlinkQueue.delete(A.tinyId),yield A.singlePC.addDownlink({userId:A.userId,tinyId:A.tinyId,ssrc:A.ssrc,prevMids:A._prevMids})}finally{if((t.audio||t.video||t.smallVideo||t.auxiliary||!t.datachannel)&&hQ){let{main:d,aux:h}=A._room.jitterBufferDelay||{},{jitterDelay:y=d,jitterDelayAux:S=h}=A._room.scheduleResult.config||{};(Ys(y)||Ys(S))&&A.setJitterBufferDelay({mainDelay:y,auxDelay:S})}}}}()})}removeDownlink(){return XA(this,null,function*(){this.singlePC&&(this.isDataChannelSubscribed=!1,this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),clearTimeout(this.jitterBufferTimeoutId),this._jitterBufferResolve&&(this._jitterBufferResolve(),this._jitterBufferResolve=void 0),this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),this._prevMids=yield this.singlePC.removeDownlink(this.userId))})}setJitterBufferDelay(A){let{mainDelay:t,auxDelay:o}=A;if(!hQ||!this.singlePC||!this._peerConnection||td(t)&&td(o))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(o));let a=this.singlePC.getReceiversByUserId(this.userId);return Ys(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),Ys(o)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=o,td(t)&&(this.remoteAudioTrack.jitterBufferDelay=o)),new Promise(l=>{this._jitterBufferResolve=l,this.doSetJitterBufferDelay({mainDelay:t,auxDelay:o,receivers:a,resolve:l})})}doSetJitterBufferDelay(A){let{mainDelay:t,auxDelay:o,receivers:a,resolve:l}=A;try{if(t===0&&o===0)return a.forEach(d=>d.jitterBufferTarget=0),this._jitterBufferResolve=void 0,l();if(a.forEach(d=>{var h;let y=d.track===this.remoteAuxiliaryTrack.outMediaTrack||td(t)&&d.track===this.remoteAudioTrack.outMediaTrack;if(y&&td(o)||!y&&td(t))return;let S=y?o||0:t,L=(d.jitterBufferTarget||0)+100;L>S||(d.jitterBufferTarget=L,this._log.debug("set ".concat(y?"aux ":"").concat((h=d?.track)==null?void 0:h.kind," jitterBuffer delay ").concat(L," -> ").concat(S)))}),!a.find(d=>{let h=d.track===this.remoteAuxiliaryTrack.outMediaTrack?o||0:t;return d.jitterBufferTarget{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:o,receivers:a,resolve:l})},1e3)}catch(d){this._log.warn("set jitterBuffer delay error: ".concat(d)),clearTimeout(this.jitterBufferTimeoutId),this._jitterBufferResolve=void 0,l()}}get audioReceiver(){var A;return((A=this.singlePC)==null?void 0:A.getReceiversByUserId(this.userId)[0])||null}onDecodeFailed(){this._room.downlinkVideoCodec==="h265"&&this._room.requestRemoteFallbackToH264()}};Qi([lL(),Xr(A=>function(){for(var t=arguments.length,o=new Array(t),a=0;a{let h=y=>{this.off("closed",h),d(new li({code:mt.API_CALL_ABORTED,message:sn({key:Go.CONNECTION_ABORTED,data:y})}))};this.on("closed",h),A.apply(this,o).then(l,d).finally(()=>{this.off("closed",h)})})})],K1.prototype,"subscribe"),Qi([lL()],K1.prototype,"unsubscribe"),Qi([Ry(()=>"jitter")],K1.prototype,"setJitterBufferDelay");var LnA=K1,UnA=dc(Xl()),U8=class MX extends UnA.EventEmitter{constructor(t,o){super(),this.room=t,this.signalChannel=o,Y(this,"log"),Y(this,"cmdIdSeqMap",new Map),Y(this,"messageMap",new Map),this.log=pA.createLogger({parent:t.getLogger(),id:"cmm",userId:t.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),o.on(Qn.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",a=>{let{userId:l}=a;[...this.messageMap.keys()].forEach(d=>{d.split("_").slice(0,-1).join("_")===l&&this.messageMap.delete(d)})})}send(t){let{cmdId:o,data:a}=t,l=this.cmdIdSeqMap.get(o)||Math.floor(16383*Math.random()),d={cmdId:o,msg:btoa(String.fromCharCode(...new Uint8Array(a))),ordered:!0,reliable:!0,streamSeq:l};this.cmdIdSeqMap.set(o,l+1),this.signalChannel.send(inA,d),this.log.debug("send custom msg: ".concat(JSON.stringify(d)))}onReceiveMsg(t){let{data:o}=t.data,a=this.room.tinyIdToUserIdMap.get(o.srcTinyId);if(a){let l={userId:a,cmdId:o.cmdId,seq:o.streamSeq,data:Uint8Array.from(atob(o.msg),d=>d.charCodeAt(0)).buffer};if(o.ordered){let d="".concat(a,"_").concat(l.cmdId),h=this.messageMap.get(d);if(h&&h.lastSeq!==0)if(Math.abs(h.lastSeq-l.seq)>MX.SEQ_INTERVAL)this.messageMap.set(d,{lastSeq:l.seq,cachedMessageMap:new Map}),this.emitMessage(l);else if(l.seq>h.lastSeq){if(l.seq===h.lastSeq+1)this.emitMessage(l);else if(!h.cachedMessageMap.has(l.seq)){let y=setTimeout(()=>this.emitMessage(l,!0),5e3);h.cachedMessageMap.set(l.seq,{message:l,timeoutId:y})}}else this.log.debug("drop message ".concat(l.userId,"-").concat(l.cmdId,"-").concat(l.seq));else h||(h={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(d,h),setTimeout(()=>this.emitMessage(l,!0),100)),h.cachedMessageMap.set(l.seq,{message:l})}else this.emit("message",l)}else{this.log.warn("receive msg from unknown user, wait peer-join tinyId: ".concat(o.srcTinyId));let l=d=>{d.tinyId===o.srcTinyId&&(this.room.off("peer-join",l),this.onReceiveMsg(t))};this.room.on("peer-join",l),OC(2e3).then(()=>this.room.off("peer-join",l))}}emitMessage(t){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var a;let l=this.messageMap.get("".concat(t.userId,"_").concat(t.cmdId)),d=t;if(l){if(o){let y=[...l.cachedMessageMap.values()].sort((S,L)=>S.message.seq-L.message.seq);y[0]&&(d=y[0].message)}l.lastSeq!==0&&d.seq-l.lastSeq>1&&this.log.debug("msg lost userId: ".concat(d.userId," seq: ").concat(l.lastSeq," -> ").concat(d.seq)),l.lastSeq=d.seq,clearTimeout((a=l.cachedMessageMap.get(d.seq))==null?void 0:a.timeoutId),l.cachedMessageMap.delete(d.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(d))),this.emit("message",d);let h=l?.cachedMessageMap.get(d.seq+1);h&&this.emitMessage(h.message)}};Y(U8,"SEQ_INTERVAL",300);var FnA=U8,{isString:F8,isUndefined:gM,getNetworkType:OnA,isEmpty:PnA}=Kd,Ly=class extends SnA{constructor(A){super(A),Y(this,"_businessInfo"),Y(this,"userManager"),Y(this,"_version"),Y(this,"_heartbeat",-1),Y(this,"_lastHeartBeatTime",-1),Y(this,"_stats"),Y(this,"_joinTimeout",-1),Y(this,"_firstPublishedList",null),Y(this,"_joinReject",null),Y(this,"_isRelayChanged",!1),Y(this,"sdpSemantics"),Y(this,"signalChannel",null),Y(this,"uplinkConnection",null),Y(this,"singlePC",null),Y(this,"enableSPC",Yv),Y(this,"_changeBigSmallRecords",new Map),Y(this,"networkQuality"),Y(this,"_iceTransportPolicy"),Y(this,"forceRelay",!1),Y(this,"_turnServers",[]),Y(this,"_iceServersFromJoin"),Y(this,"_syncUserListInterval",-1),Y(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),Y(this,"enableSEI",!1),Y(this,"_enableAudioVolumeEvaluation",!1),Y(this,"_audioVolumeIntervalId",0),Y(this,"_enableMultiAuxStream",!1),Y(this,"_pureAudioPushMode",!1),Y(this,"_customMessageManager"),Y(this,"_enableDataChannel",!1),Y(this,"preferHW",!1),Y(this,"healthDetector"),Y(this,"playoutDelay"),Y(this,"jitterBufferDelay"),Y(this,"_updateAudioLevelTaskId",-1),Y(this,"switchRoomSubedReq"),Y(this,"resolveSwitchRoomSubedReq"),Y(this,"enableVolumeControlInIOS"),Y(this,"capturedLocalMainAudioTrack"),Y(this,"capturedLocalMainVideoTrack"),Y(this,"capturedLocalAuxVideoTrack"),Y(this,"PRELINK_EXPIRED_TIME",3e5),Y(this,"PRELINK_TIMEOUT",1e4),Y(this,"prelinkTimeoutId",null),Y(this,"firewallDetector"),this.firewallDetector=new roA,this.firewallDetector.on("firewall-restriction",()=>{this._log.warn("firewall restriction"),this.emit("firewall-restriction")}),this._stats=new cnA(this,this._log),this.userManager=new noA(this.userId,this._log),this._version=Wd,this.sdpSemantics=p0,gM(A.sdpSemantics)?ge.isUnifiedPlanDefault()&&(this.sdpSemantics=nv):this.sdpSemantics=A.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(OnA())),A.iceTransportPolicy&&(this._iceTransportPolicy=A.iceTransportPolicy),this._enableMultiAuxStream=!gM(A.enableMultiAuxStream)&&A.enableMultiAuxStream,this.enableSEI=A.enableSEI&&Yv,!gM(A.enableSPC)&&Yv&&(this.enableSPC=A.enableSPC),this.preferHW=!!A.preferHW,this.enableVolumeControlInIOS=A.enableVolumeControlInIOS,this._initBusinessInfo(A),this.healthDetector=new TnA(this)}get isMainStreamPublished(){var A;return!((A=this.uplinkConnection)==null||!A.isMainStreamPublished)}get isMainAudioPublished(){var A;return!((A=this.uplinkConnection)==null||!A.localMainAudioTrack)}get isAuxStreamPublished(){var A;return!((A=this.uplinkConnection)==null||!A.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(A=>A.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(A=>[A.tinyId,A.userId]))}get videoCodec(){var A;return((A=this.singlePC)==null?void 0:A.videoCodec)||"h264"}get downlinkVideoCodec(){var A;return((A=this.singlePC)==null?void 0:A.downlinkVideoCodec)||"h264"}join(A,t,o){return XA(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",a=>{this.emit("peer-join",a)}),this.userManager.on("8",a=>{this.emit("asr-robot-peer-join",a)}),this.userManager.on("9",a=>{this.emit("asr-robot-peer-leave",a)}),this.userManager.on("2",a=>{let{userId:l,reason:d}=a;this.closeDownLinkConnection(l,"remote user exitRoom"),this.emit("peer-leave",{userId:l,reason:d})}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",a=>{var l=Yx(a,[]);F.emit(rA.REMOTE_PUBLISH_STATE_CHANGED,Di({room:this},l)),this.emit("remote-publish-state-changed",Di({},l))}),this.joinParams=A,br(A.enableDataChannel)&&(this._enableDataChannel=A.enableDataChannel),new Promise((a,l)=>XA(this,null,function*(){var d,h;this._joinReject=l;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(S){if(!(S instanceof li&&S.code===mt.SPC_INITIALIZED_FAILED))return l(S);(d=this.signalChannel)==null||d.destroy(),yield this.initialize()}let y=Oo();yield this.doJoin(A,(h=this.singlePC)==null?void 0:h.clientAbility),ri.addSuccessEvent({key:521708,cost:Oo()-y}),a(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(y){ri.addFailedEvent({key:521708,error:y}),l(y)}this._joinReject=null}))})}initSinglePC(){return XA(this,null,function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new ky({signalChannel:this.signalChannel,room:this,enableDataChannel:this._enableDataChannel}),this.singlePC.on("sei-message",A=>this.emit("sei-message",A)),this.singlePC.on("dump",A=>this.emit("dump",A)),this.singlePC.once("error",()=>this.fallbackToMPC()),this.singlePC.on("data_channel_msg",A=>{let t=new TextDecoder().decode(A.data.data||A.data);try{this.emit("data-channel-message",{data:JSON.parse(t)})}catch{}});try{return yield this.singlePC.initialize()}catch(A){throw this.fallbackToMPC(),new li({code:mt.SPC_INITIALIZED_FAILED,message:A?.message})}}})}doJoin(A,t){return new Promise((o,a)=>XA(this,null,function*(){var l,d,h,y,S,L,V,H;A.privateMapKey&&(this.privateMapKey=A.privateMapKey),A.latencyLevel&&(this.latencyLevel=A.latencyLevel),this.signalChannel.once(F1,MA=>{this.clearJoinTimeout(),F.emit(rA.JOIN_SIGNAL_CONNECTION_END,{room:this,error:MA}),a(MA)}),br((d=(l=this.scheduleResult)==null?void 0:l.config)==null?void 0:d.singlePC)&&Yv&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),(!((y=(h=this.scheduleResult)==null?void 0:h.config)!=null&&y.jitterDelay)&&!((L=(S=this.scheduleResult)==null?void 0:S.config)!=null&&L.jitterDelayAux)||!hQ)&&t&&this.playoutDelay&&(this._log.info("set playoutDelay",JSON.stringify(this.playoutDelay)),t.playoutDelay=this.playoutDelay);let lA={roomId:String(A.roomId||A.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:A.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:ys(),netType:$f(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&a_(),transcription:this._enableDataChannel,downUseVp8:((V=this.scheduleResult.config)==null?void 0:V.downUseVp8)||!1};this._log.debug("join room signal data: ".concat(JSON.stringify(lA)));let hA=5e3;(H=this.scheduleResult.config)!=null&&H.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(hA=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout(()=>{a(new li({code:mt.JOIN_ROOM_FAILED,message:sn({key:Go.JOIN_ROOM_TIMEOUT})}))},hA),F.emit(rA.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?AnA:OoA,lA),this.signalChannel.once(Qn.JOIN_ROOM_RESULT,MA=>XA(this,null,function*(){this.clearJoinTimeout();let{code:oe,message:fe,data:je,tinyId:_e}=MA.data;F.emit(rA.JOIN_RECEIVED_CMD_RES,{room:this,code:oe}),oe===0?(this._log.info("Join room success, start heartbeat"),_e&&(this.tinyId=_e),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=je.publishers,this._iceServersFromJoin=je.iceServer?[je.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var vi;(vi=this.singlePC)==null||vi.connect(So(Di({},je.ability),{useVp8:je.ability.useVp8||!!A.useVp8,useH265:je.ability.useH265&&!!A.useH265})).catch(()=>{})}),o()):(this._log.error("Join room failed result: ".concat(oe," error: ").concat(fe)),a(new li({code:mt.JOIN_ROOM_FAILED,extraCode:oe,message:sn({key:Go.JOIN_ROOM_FAILED,data:{error:fe,code:oe}})})))}))}))}reJoin(){return XA(this,null,function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this.joinParams.roomId));let A,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(o=>(A=o,o)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(So(Di({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),A),this._log.warn("reJoin success"),ds.logSuccessEvent({userId:this.userId,eventType:Wa.REJOIN}),this.singlePC){let o=a=>{var l;a.state==="CONNECTED"&&((l=this.singlePC)==null||l.off(w_.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof k8&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(d=>{d.installEvents(),d.onSinglePCReconnected()}))};this.singlePC.on(w_.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof H1&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(A){this._log.warn("reJoin fail ".concat(A)),this.reset(),ds.logFailedEvent({userId:this.userId,eventType:Wa.REJOIN,error:A}),this.emit("error",new li({code:mt.JOIN_ROOM_FAILED,message:sn({key:Go.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")})}initialize(A){return XA(this,null,function*(){var t,o;if(!(A!=null&&A.isPrelink)&&this.prelinkPromise&&(yield this.prelinkPromise),(t=this.signalChannel)!=null&&t.isPrelinkValid(this.sdkAppId,this.userId,this.userSig))return this._log.info("reuse prelink signal channel"),void this.signalChannel.consumePrelink();(o=this.signalChannel)!=null&&o.prelink&&this.signalChannel.close();let a,{mainUrl:l,backupUrl:d}=this.getSignalChannelUrl(),h=this.signalChannel||function(S){return[...x1.values()].find(V=>V.room.userId===S&&!V.room.isJoined)||null}(this.userId),y=!!(h&&h.isConnected&&h.keepAlive&&h.userId===this.userId);return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(a=this.scheduleResult.domains[0]),this._log.info("".concat(y?"reuse":"setup"," signal channel")),y?(h.url=l,h.backupUrl=d,h.room.setSignalChannel(null),h.room=this,this.signalChannel=h):(h&&h.close(),this.signalChannel=new E8({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:l,backupUrl:d,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?a:void 0,prelink:A?.isPrelink}),this._customMessageManager=new FnA(this,this.signalChannel),this._customMessageManager.on("message",S=>{this.emit("custom-message",S)})),this.networkQuality||(this.networkQuality=new Q8({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Q8.EVENT_NETWORK_QUALITY,S=>{var L;this.emit("network-quality",S),(L=this.singlePC)==null||L.detectTCPAndUDP(S)})),gd(this,this.signalChannel).add(Yj,S=>{F.emit(rA.SIGNAL_CONNECTION_STATE_CHANGED,Di({room:this},S)),this.emit("signal-connection-state-changed",S)}).add(LoA,S=>{this.reset(),this.emit("error",S)}).add(Qn.PEER_JOIN,S=>{let{srcTinyId:L,userId:V,role:H,fromType:lA}=S.data.data;this.userManager.addUser({userId:V,tinyId:L,role:H,fromType:lA})}).add(Qn.PEER_LEAVE,S=>{let{userId:L,reason:V=0}=S.data.data;this.userManager.deleteUser(L,V)}).add(Qn.UPDATE_REMOTE_MUTE_STAT,S=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(S.data)}).add(Qn.CLIENT_BANNED,S=>{let L=S.data.data,{reason:V}=L;if(ds.uploadEvent({log:"stat-banned:".concat(V),userId:this.userId}),V==="user_time_out")return this._log.warn("".concat(V," last heart beat time: ").concat(this._lastHeartBeatTime," interval: ").concat(Date.now()-this._lastHeartBeatTime,", visibility: ").concat(document.visibilityState)),void this.reJoin();this._log[V==="kick"?"error":"info"]("user was banned because of [".concat(V,"]")),this.reset(),this.emit("banned",{reason:V})}).add(Qn.SEND_SWITCH_ROOM_SUBED_REQ,S=>{if(!this.singlePC)return;let{subList:L}=S.data.data;this._log.info("auto subscribe ".concat(Xd(L,{keysToInclude:["userId"]}))),L.forEach(V=>{this.singlePC.autoSubscribedUserMap.set(V.userId,V)}),this.resolveSwitchRoomSubedReq()}).add(Qn.FALLBACK_CODEC,S=>XA(this,null,function*(){var L,V,H,lA,hA;let MA=S.data.data;((L=MA.videoControlInfo)==null?void 0:L.enableH265Enc)===0&&((V=this.singlePC)==null?void 0:V.videoCodec)==="h265"&&(this._log.warn("fallback codec enableH265Enc: ".concat((H=MA.videoControlInfo)==null?void 0:H.enableH265Enc)),ri.addCount({key:513e3}),yield(lA=this.singlePC)==null?void 0:lA.switchVideoEncoder("h264"),yield(hA=this.uplinkConnection)==null?void 0:hA.sendMediaSettings())})),this.signalChannel.once(s8,S=>{this.tinyId=S.signalInfo.tinyId,F.emit(rA.JOIN_SIGNAL_CONNECTION_END,{room:this})}),F.emit(rA.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),y&&F.emit(rA.JOIN_SIGNAL_CONNECTION_END,{room:this}),y})}setSignalChannel(A){this.signalChannel=A,A||Vs(this)}leave(){return XA(this,null,function*(){var A;try{yield this.doHeartbeat()}catch{}this._log.info("leave() => leaving room"),F.emit(rA.LEAVE_SEND_CMD,{room:this}),(A=this.signalChannel)==null||A.send(PoA),this.switchRoomSubedReq=void 0,this._changeBigSmallRecords.clear()})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(A=>{this.closeDownLinkConnection(A.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=kr.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),kr.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return XA(this,null,function*(){var A;let t=this.badCaseDetector.getMonitorFreeze(),o=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});this.badCaseDetector.resetMonitor();let a=(A=this.signalChannel)!=null&&A.isConnected?function(d){if(f_.has(d)){let h=f_.get(d).map(y=>({uint32_event_id:y.eventId,uint64_date:y.timestamp,str_userid:y.remoteUserId,uint32_param1:y.param1,uint32_param2:y.param2,uint32_video_stream_type:y.streamType}));return f_.delete(d),h}return[]}(this.userId):[],l=So(Di({str_sdk_version:l0,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:a,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},o),{msg_device_info:Di({uint32_terminal_type:15,str_device_name:lQ(),str_os_version:"",uint32_net_type:$f()},o.msg_device_info)});if(this.heartbeatReport=l,this.heartbeatCount++,F.emit(rA.HEARTBEAT_REPORT,{room:this,report:l}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(xoA,l);let d=Date.now();this._lastHeartBeatTime>0&&d-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(d-this._lastHeartBeatTime)),this._lastHeartBeatTime=d,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",So(Di({},l),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(A){if(!this.isJoined)return;let t=!1,o=A.data.userList||[],a=A.data.mixRobotList||[],l=[];for(let h of o){if(h.flag===Ob)continue;let{userId:y,srcTinyId:S,flag:L,fromType:V}=h;y===this.userId&&(t=!0,this.uplinkConnection&&(this.uplinkConnection.flag=L),this.localPublishFlag!==L&&(this.localPublishFlag=L,this.emit("local-publish-flag-changed",L))),l.push({userId:y,tinyId:S,flag:L,fromType:V})}let d=[...a.map(h=>{let{userId:y,srcTinyId:S,flag:L,mixUserList:V,fromType:H}=h;return{userId:y,tinyId:S,flag:L,isRobot:!0,mixUserList:V,fromType:H}}),...l];d.forEach(h=>{let{userId:y}=h,S=this.remotePublishedUserMap.get(y);S&&this.checkSubscribeBigSmallVideo(S)}),A.data.fakeMixUser&&(A.data.fakeMixUser.tinyId=A.data.fakeMixUser.srcTinyId,d.push(A.data.fakeMixUser)),F.emit(rA.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:d}),t||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),this.userManager.setRemotePublishedUserList(d)}closeUplink(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish().catch(()=>{}),this.uplinkConnection.close(A),A==="you exitRoom"&&(this.uplinkConnection.destroy(),this.uplinkConnection=null),this.uplinkConnection instanceof H1&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection(A){let{userId:t,tinyId:o,flag:a,isRobot:l,fromType:d}=A,h=new(this.singlePC?LnA:h8)({userId:t,tinyId:o,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:a,isRobot:l,fromType:d});this.userManager.addRemotePublishedUser(h),this.installDownlinkEvents(h,t),this.emit("remote-published",h)}closeDownLinkConnection(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"remote user unpublished",o=this.remotePublishedUserMap.get(A);o&&(o.close(t),this.emit("remote-unpublished",o))}installDownlinkEvents(A,t){A.on("error",o=>{let a=o.getCode();a!==mt.ICE_TRANSPORT_ERROR&&(a===mt.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",o))}),A.on("connection-state-changed",o=>{this.emit("media-connection-state-changed",So(Di({},o),{userId:A.userId}))})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=kr.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){kr.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(A=>{this.userManager.setUserList(A)}).catch(A=>{this._log.debug("sync user list failed: ".concat(A))})}getUserList(){var A;return(A=this.signalChannel)!=null&&A.isConnected?this.signalChannel.sendWaitForResponse({command:ZoA,responseCommand:Qn.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(t=>{let{data:o}=t,{code:a,message:l}=o;if(a===0)return(o.data&&o.data.userList||[]).map(d=>{let{userId:h,srcTinyId:y,role:S,fromType:L}=d;return{userId:h,tinyId:y,role:S,fromType:L}});throw sn({key:Go.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Qn.USER_LIST_RES,code:a,message:l}})}):Promise.reject("not connected")}getAllConnections(){let A=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&A.push(this.uplinkConnection),A}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!d8)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let A=this.getAllConnections();if(A.length===0)return!1;for(let t=0;t{if(t instanceof am&&!t.getIsReconnecting()){let o=t.getPeerConnection();o&&o.connectionState===mo.CLOSED&&(this._log.warn("[".concat(t.getUserId(),"] pc is closed but not reconnect")),t.startReconnection())}})}fallbackToMPC(){return XA(this,null,function*(){var A;if(this._log.warn("fallback to multi pc"),ds.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(A=this.singlePC)==null||A.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new H1({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}for(let t of[...this.remotePublishedUserMap.values()]){let o=new h8({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(o,t.userId),this.remotePublishedUserMap.set(t.userId,o),t.isMainStreamSubscribed&&(yield o.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield o.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new li({code:mt.INVALID_OPERATION,message:sn({key:Go.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.firewallDetector.destroy(),this.removeAllListeners(),this.healthDetector.destroy(),kr.clearTask(this._audioVolumeIntervalId))}switchRole(A){return XA(this,null,function*(){this.role!==A&&(A==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(A))})}doSwitchRole(A){let t={command:XoA,data:{role:A==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:Qn.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(t.data))),this.signalChannel.sendWaitForResponseWithRetry(t).then(o=>{let{code:a,message:l}=o.data;if(a!==0)throw new li({code:mt.SWITCH_ROLE_FAILED,message:sn({key:Go.SWITCH_ROLE_FAILED,data:{message:l,code:a}})});this.role=A}).catch(o=>{throw o instanceof li&&o.getCode()===mt.API_CALL_TIMEOUT&&(o=new li({code:mt.SWITCH_ROLE_FAILED,message:sn({key:Go.SWITCH_ROLE_TIMEOUT})})),this._log.error(o),o})}subscribeDataChannel(){return XA(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let A=[...this.remotePublishedUserMap.values()].filter(t=>t.fromType===D0);this._log.info("subscribeDataChannel",A.map(t=>t.userId)),yield Promise.all(A.map(t=>XA(this,null,function*(){try{yield t.subscribe(So(Di({},t.subscribeState),{datachannel:!0}),"main")}catch(o){this._log.error("subscribeDataChannel failed:",t.userId,o)}})))})}unsubscribeDataChannel(){return XA(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let A=[...this.remotePublishedUserMap.values()].filter(t=>t.fromType===D0);this._log.info("unsubscribeDataChannel",A.map(t=>t.userId)),yield Promise.all(A.map(t=>t.unsubscribeDataChannel()))})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new k8({userId:this.userId,tinyId:this.tinyId,room:this}):new H1({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",A=>{this.emit("media-connection-state-changed",So(Di({},A),{userId:this.userId}))}),this.uplinkConnection.on("error",A=>{let t=A.getCode();t!==mt.ICE_TRANSPORT_ERROR&&(t===mt.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",A))})}publish(A){return XA(this,null,function*(){var t;this.uplinkConnection||this._initUplinkConnection();let o="".concat(A.streamType," ").concat(A.isAudio&&A.isScreen?"screen":"").concat(A.kind);this._log.info("publish() => ".concat(o)),yield(t=this.singlePC)==null?void 0:t.waitForPeerConnectionConnected(),yield this.uplinkConnection.publish({localAudioTrack:A instanceof AM?A:null,localVideoTrack:A instanceof QQ?A:null,isAuxiliary:A.streamType==="auxiliary"})})}unpublish(A){return XA(this,null,function*(){if((this.scene!=="live"||this.role==="anchor")&&(this.isMainStreamPublished||this.isAuxStreamPublished)&&this.uplinkConnection){try{let t="".concat(A.streamType," ").concat(A.isAudio&&A.isScreen?"screen":"").concat(A.kind);this._log.info("unpublish() => ".concat(t)),yield this.uplinkConnection.unpublish({localAudioTrack:A instanceof AM?A:null,localVideoTrack:A instanceof QQ?A:null})}catch{}this.localTracks.size===0&&this.closeUplink("you unpublished")}})}addTrack(A){if(!this.uplinkConnection||!A.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(A);return A.publish(this,t),t}removeTrack(A){return this.uplinkConnection&&A.mediaTrack?(A.unpublish(),this.uplinkConnection.removeTrack(A)):Promise.resolve()}replaceTrack(A){return this.uplinkConnection&&A.mediaTrack&&X2()?this.uplinkConnection.replaceTrack(A).then(t=>{t&&F.emit(rA.LOCAL_TRACK_REPLACED,{track:A})}):Promise.resolve()}setBandWidth(A){return XA(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(A),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(A){return XA(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();A&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:JA.VIDEO,videoType:JA.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(A)})}subscribe(){for(var A=arguments.length,t=new Array(A),o=0;o!h.isSubscribed),t.length===0)return;let{userId:a}=t[0],l=this.remotePublishedUserMap.get(a);if(!l)return;let d=t.find(h=>h.mediaType===2)?"auxiliary":"main";try{let h=Di({},l.subscribeState);t.forEach(S=>{switch(S.mediaType){case 1:h.audio=!0;break;case 4:h.video=!0;break;case 8:h.smallVideo=!0;break;case 2:h.auxiliary=!0}});let y=this._changeBigSmallRecords.get(a);y&&y.options.smallVideo&&l.muteState.hasSmall&&h.video&&(h.video=!1,h.smallVideo=!0),F.emit(rA.SUBSCRIBE_START,{room:this,streamType:d,remotePublishedUser:l,subscribeState:h}),this._log.info("subscribe() => ".concat(a," ").concat(d," ").concat(t.map(S=>S.strMediaType).join(",")," [").concat(Kj(h),"] prev: [").concat(Kj(l.subscribeState),"]")),yield l.subscribe(h,d),this._log.info("subscribe ".concat(a," ").concat(d," done"));for(let S of t)S.mediaTrack||(yield S.waitHasMediaTrack());F.emit(rA.SUBSCRIBE_SUCCESS,{room:this,streamType:d,remotePublishedUser:l})}catch(h){let y=h instanceof li?h.getCode():mt.UNKNOWN,S=h;throw h instanceof li?y===mt.REMOTE_STREAM_NOT_EXIST&&(S=new li({code:mt.API_CALL_ABORTED,message:sn({key:Go.API_CALL_ABORTED,data:{message:h.message,userId:a,streamType:d}})}),this._log.warn(S)):(S=new li({code:y,message:sn({key:Go.SUBSCRIBE_FAILED,data:{message:h.message,userId:a,streamType:d}})}),this._log.error(S)),S}})}unsubscribe(){for(var A=arguments.length,t=new Array(A),o=0;oh.mediaType===2)?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(a," ").concat(d," ").concat(t.map(h=>h.strMediaType).join(",")));try{yield l.unsubscribe({remoteTracks:t,streamType:d})}catch(h){this._log.warn("unsubscribe() => failed ".concat(h))}t.forEach(h=>{h.unsubscribe(),h.mediaType===8&&h.setMediaType(4)}),F.emit(rA.UNSUBSCRIBE_SUCCESS,{room:this,streamType:d,remotePublishedUser:l})})}setEncodedDataProcessingListener(A){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3,t=arguments.length>1?arguments[1]:void 0;if(A<=0)return this._enableAudioVolumeEvaluation=!1,void kr.clearTask(this._audioVolumeIntervalId);A=Math.floor(Math.max(A,100)),F.emit(rA.AUDIO_LEVEL_INTERVAL,{interval:A}),this._audioVolumeIntervalId&&kr.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=kr.run("intervalInWorker",()=>{var o;g1.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(A,t);let a=[];(o=this.remotePublishedUserMap)==null||o.forEach(l=>{if(l.muteState.hasAudio){!g1.isRunning&&l.muteState.audioAvailable&&l.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(l):l.remoteAudioTrack.volume=0;let d=Math.floor(100*l.remoteAudioTrack.getAudioLevel());a.push({userId:l.userId,volume:d,floatVolume:l.remoteAudioTrack.getInternalAudioLevel()})}}),this.emit("audio-volume",a)},{delay:A,backgroundTask:t})}updateAudioLevelFromSenderStat(A,t){return XA(this,null,function*(){var o;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let a=(o=this.uplinkConnection.getPeerConnection())==null?void 0:o.getSenders()[0];if(!a)return;let l=Math.max(A,500);this._log.warn("updateAudioLevelFromSenderStat ".concat(l)),this._updateAudioLevelTaskId=kr.run("intervalInWorker",()=>XA(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack)return void this.stopUpdateAudioLevelFromSenderStat();let d=yield a.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:h}=this.uplinkConnection;d.forEach(y=>{y.type==="media-source"&&y.audioLevel&&(h.volume=y.audioLevel)})}),{delay:l,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var A;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),kr.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(A=this.uplinkConnection)!=null&&A.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(A){var t;let{audioReceiver:o}=A;if(!Xk||!o)return;let a=(t=o.getSynchronizationSources()[0])==null?void 0:t.audioLevel;Ys(a)?A.remoteAudioTrack.volume=Math.min(2*a,1):o.getStats().then(l=>{l.forEach(d=>{d.type==="inbound-rtp"&&Ys(d.audioLevel)&&(A.remoteAudioTrack.volume=d.audioLevel)})})}getLocalAudioStats(){return XA(this,null,function*(){var A;let t={};return t[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(A=this.uplinkConnection)!=null&&A.localMainAudioTrack&&(t[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),t})}getLocalVideoStats(){return XA(this,null,function*(){var A,t;let o={};return o[this.userId]=((t=(A=this.uplinkConnection)==null?void 0:A.localMainVideoTrack)==null?void 0:t.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},o})}getTransportStats(){return XA(this,null,function*(){let A={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);A.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let o=yield this._stats.getReceiverStats(t);A.downlinksRTT[o.userId]=o.rtt}return A})}getRemoteVideoStats(A){return XA(this,null,function*(){let t={};for(let[o,a]of this.remotePublishedUserMap)A==="main"&&a.muteState.hasVideo&&(t[o]=a.remoteVideoTrack.stat),A==="auxiliary"&&a.muteState.hasAuxiliary&&(t[o]=a.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return XA(this,null,function*(){let A={};for(let[t,o]of this.remotePublishedUserMap)o.muteState.hasAudio&&(A[t]=o.remoteAudioTrack.stat);return A})}setTurnServer(A,t){this._log.info("set turn server: ".concat(JSON.stringify(A)," ").concat(t||""));let o=[];Array.isArray(A)?A.forEach(a=>o.push(Kd.getTurnServer(a))):Kd.isPlainObject(A)&&o.push(Kd.getTurnServer(A)),this._turnServers=o,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(A){return this.signalChannel.sendWaitForResponse({command:qoA,data:A,timeout:5e3,responseCommand:Qn.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(t=>{if(t.code!==mt.API_CALL_ABORTED)throw t})}sendStopMixTranscode(A){return this.signalChannel.sendWaitForResponse({command:KoA,data:A,timeout:5e3,responseCommand:Qn.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(t=>{if(t.code!==mt.API_CALL_ABORTED)throw t})}sendStartPublishCDN(A){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?YoA:HoA,data:A,timeout:5e3,responseCommand:t?Qn.START_PUBLISH_TENCENT_CDN_RES:Qn.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(o=>{if(o.code!==mt.API_CALL_ABORTED)throw o})}sendStopPublishCDN(A){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?VoA:JoA,data:A,timeout:5e3,responseCommand:t?Qn.STOP_PUBLISH_TENCENT_CDN_RES:Qn.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(o=>{if(o.code!==mt.API_CALL_ABORTED)throw o})}sendStartPushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:joA,data:A,timeout:5e3,responseCommand:Qn.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(t=>{if(t.code!==mt.API_CALL_ABORTED)throw t})}sendUpdatePushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:WoA,data:A,timeout:5e3,responseCommand:Qn.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(t=>{if(t.code!==mt.API_CALL_ABORTED)throw t})}sendStopPushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:zoA,data:A,timeout:5e3,responseCommand:Qn.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(t=>{if(t.code!==mt.API_CALL_ABORTED)throw t})}sendAbilityStatus(A){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:enA,data:A,timeout:5e3,responseCommand:Qn.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(o=>{})}getIceServers(A){var t,o;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:A!=null&&A.length?A:(o=this._iceServersFromJoin)!=null&&o.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let A={mainUrl:"",backupUrl:""},t=Kd.getEnv();return t?(A.mainUrl="wss://".concat(Kd.getTestSignalDomain(t)),A.backupUrl=A.mainUrl):this.proxy_ws?(A.mainUrl=this.proxy_ws,A.backupUrl=A.mainUrl):this.proxy_unified?(A.mainUrl="wss://".concat(this.proxy_unified),A.backupUrl=A.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(A.mainUrl="wss://".concat(this.scheduleResult.domains[0]),A.backupUrl=A.mainUrl,this.scheduleResult.domains[1]&&(A.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),A}getSignalInfo(){var A;return((A=this.signalChannel)==null?void 0:A.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(A&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this.localPublishFlag=0,this.heartbeatCount=0,this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null},this.clearPrelinkTimeout(),this.prelinkPromise=null}prelink(A,t,o,a,l,d){return XA(this,null,function*(){var h;if(this.isJoined)throw new li({code:mt.INVALID_OPERATION,message:"already joined room"});if(!l&&!d)throw new li({code:mt.INVALID_OPERATION,message:"roomId or strRoomId is required"});if((h=this.signalChannel)!=null&&h.prelink){if(this.signalChannel.isConnecting)return void this._log.warn("prelink is connecting, please wait");if(this.signalChannel.isConnected)return void this._log.warn("prelink is already connected")}return this.userId=t,this.sdkAppId=A,this.userSig=o,this.roomId=String(l||d),this.useStringRoomId=!(!d||l),this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.prelinkPromise=Promise.race([this.doPrelink(A,t,o,a,l,d),new Promise((y,S)=>{this.prelinkTimeoutId=setTimeout(()=>{S(new li({code:mt.INVALID_OPERATION,message:"prelink timeout after ".concat(this.PRELINK_TIMEOUT,"ms")}))},this.PRELINK_TIMEOUT)})]).then(()=>{this.clearPrelinkTimeout()}).catch(y=>{throw this.clearPrelinkTimeout(),this.closePrelink().catch(()=>{}),y}),this.prelinkPromise})}doPrelink(A,t,o,a,l,d){return XA(this,null,function*(){var h,y,S;try{if(!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Kd.getEnv()&&(yield this.schedule({sdkAppId:A,userId:t,userSig:o,roomId:l,strRoomId:d,role:20,privateMapKey:null,businessInfo:null,streamId:null,userDefineRecordId:null},a)),(h=this.scheduleResult.config)==null||!h.prelink)throw new li({code:mt.INVALID_OPERATION,message:"prelink failed: your sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it."});yield this.initialize({isPrelink:!0}),(y=this.signalChannel)==null||y.markPrelinkConnected({sdkAppId:A,userId:t,userSig:o}),(S=this.signalChannel)==null||S.stopPrelinkIn(this.PRELINK_EXPIRED_TIME/1e3),this._log.info("prelink success")}catch(L){throw this._log.error("prelink failed",L),L}})}clearPrelinkTimeout(){this.prelinkTimeoutId&&(clearTimeout(this.prelinkTimeoutId),this.prelinkTimeoutId=null)}closePrelink(){return XA(this,null,function*(){var A;if(this.isJoined)throw new li({code:mt.INVALID_OPERATION,message:"close prelink failed: has joined room"});if((A=this.signalChannel)!=null&&A.prelink){if(this.signalChannel.keepAlive)return void this._log.info("skip close prelink: use keepAlive");this.reset()}})}checkSubscribeBigSmallVideo(A){return XA(this,null,function*(){let{subscribeState:t,userId:o,muteState:{hasSmall:a,hasVideo:l}}=A;if(!a&&!l||!t.video&&!t.smallVideo)return;let d=this._changeBigSmallRecords.get(o);if(!d||d.isSubscribing||d.reSubscribeCount<=0)return;let{options:h,reSubscribeCount:y}=d;if(h.video&&t.video||h.smallVideo&&t.smallVideo&&a)return;let S={audio:A.remoteAudioTrack.isSubscribed||A.remoteAudioTrack.isSubscribing,auxiliary:A.remoteAuxiliaryTrack.isSubscribed||A.remoteAuxiliaryTrack.isSubscribing,video:h.video,smallVideo:h.smallVideo,datachannel:A.subscribeState.datachannel};try{if(!a&&S.smallVideo&&(S.video=!0,S.smallVideo=!1),S.smallVideo===t.smallVideo&&S.video===t.video)return;d.isSubscribing=!0,d.reSubscribeCount=y-1,yield A.subscribe(S,"main"),A.remoteVideoTrack.setMediaType(S.smallVideo?8:4),this._log.info("change [".concat(o,"] to ").concat(S.smallVideo?"small":"big"," video successfully. count ").concat(rv-d.reSubscribeCount,".")),d.isSubscribing=!1,d.reSubscribeCount=rv}catch(L){this._log.info("change [".concat(o,"] to ").concat(S.smallVideo?"small":"big"," video failed. count ").concat(rv-d.reSubscribeCount,". reason: ").concat(L)),d.isSubscribing=!1,d.reSubscribeCount===0&&this._changeBigSmallRecords.delete(o)}})}changeType(A,t){let o={options:{video:!A,smallVideo:A},isSubscribing:!1,reSubscribeCount:rv};this._changeBigSmallRecords.set(t.userId,o),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(A?"small":"big")),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:A});let a=this.remotePublishedUserMap.get(t.userId);a&&this.checkSubscribeBigSmallVideo(a)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(A){this._businessInfo=A.businessInfo;let t={};if(F8(A.businessInfo)&&(t=JSON.parse(A.businessInfo)),!gM(A.pureAudioPushMode)){if(!Number.isInteger(Number(A.pureAudioPushMode)))throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_PURE_AUDIO})});this._pureAudioPushMode=A.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!gM(A.userDefineRecordId)){let o=/^[A-Za-z0-9_-]{1,64}$/gi;if(A.userDefineRecordId.match(o)===null)throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=A.userDefineRecordId}if(!gM(A.userDefinePushArgs)){if(!(F8(A.userDefinePushArgs)&&String(A.userDefinePushArgs)&&String(A.userDefinePushArgs).length<=256))throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=A.userDefinePushArgs}PnA(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(A){var t;(t=this._customMessageManager)==null||t.send(A)}enableInsertableStreams(){return XA(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&$p)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(A){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(A):Promise.reject(new li({code:mt.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var A;return(A=this.singlePC)==null?void 0:A.scriptTransformWorker}switchRoom(A){return XA(this,null,function*(){var t;if(!this.signalChannel||!this.singlePC)return;let{roomId:o,strRoomId:a,userSig:l,privateMapKey:d}=A,h=((t=this.scheduleResult.config)==null?void 0:t.autoSubscribeCount)||A?.autoSubscribeCount||1,y=String(this.useStringRoomId?a:o),S=[];for(let lA=0;lA{this.resolveSwitchRoomSubedReq=lA,OC(5e3).then(lA)}),F.emit(rA.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();try{this.userManager.clear(),V=yield this.signalChannel.sendWaitForResponse({command:onA,responseCommand:Qn.SEND_SWITCH_ROOM_RES,data:L});let{code:lA,message:hA}=V.data;if(lA!==0){this._log.error("switch room failed. result: ".concat(lA," error: ").concat(hA));let MA=new li({code:mt.SWITCH_ROOM_FAILED,extraCode:lA,message:hA});throw F.emit(rA.SWITCH_ROOM_FAILED,{room:this,error:MA}),MA}this.userSig=l,gM(d)||(this.privateMapKey=d),F.emit(rA.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:H,targetRoomId:y})}catch(lA){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=H,this.resolveSwitchRoomSubedReq(),lA}})}isSwitchRoomSupported(){var A;let t="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((A=this.scheduleResult.config)==null?void 0:A.switchRoom)!==!0?(this._log.warn("".concat(t," Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.")),!1):this.scene!=="live"?(this._log.warn("".concat(t," Reason: the scene is not 'live'.")),!1):this.role!=="audience"?(this._log.warn("".concat(t," Reason: the role is not 'audience'.")),!1):!!this.singlePC||(this._log.warn("".concat(t," Reason: is not using single peerConnection.")),!1)}requestRemoteFallbackToH264(){var A;(A=this.singlePC)==null||A.requestRemoteFallbackToH264()}startUpdateNTPTime(){if(!this.signalChannel)return;let A=[];for(let t=0;t<5;t++)A.push(this.updateNTPTime());return Promise.all(A).then(t=>{var o;let a=t[0].offset,l=t[0].offset;t.forEach(y=>{a=Math.min(y.offset,a),l=Math.max(y.offset,l)});let d=Math.floor(t.reduce((y,S)=>y+S.rtt,0)/t.length),h=Math.floor(t.reduce((y,S)=>y+S.offset,0)/t.length);(l-a>30||d>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),ZB(h),(o=this.scriptTransformWorker)==null||o.postMessage({type:"ntp-offset",data:h}),this._log.debug("ntp updated offset: ".concat(h)),this.emit("ntp-time-updated")}).catch(t=>{this._log.warn("ntp updated failed: ".concat(t))})}updateNTPTime(){let A=Date.now();return this.signalChannel.sendWaitForResponse({command:nnA,responseCommand:Qn.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(A)},enableLog:!1}).then(t=>{let o=Number(t.data.data.serverSendTime),a=Number(t.data.data.serverRecvTime),l=t.data.receiveTime||Date.now();return{rtt:l-A-(a-o),offset:(a-A+(o-l))/2}})}};return Qi([hc(["left",gs.INIT],"joined"),iB({settings:{retries:1,timeout:0},onRetrying(A){this._log.warn("join retry ".concat(A))},onRetryFailed(A){this._log.error("join failed",A)},onError(A,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),mQ(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),Xr(A=>{let t=new GoA;return function(o,a,l){return XA(this,null,function*(){let d=String(o.roomId||o.strRoomId);if(this.userId=o.userId,this.sdkAppId=o.sdkAppId,this.userSig=o.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=a,o.privateMapKey=o.privateMapKey||"",this.isJoined)throw new li({code:mt.INVALID_OPERATION,message:sn({key:Go.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:d,sdkAppId:this.sdkAppId,room:this}))throw new li({code:mt.INVALID_OPERATION,message:sn({key:Go.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:d}),this.role=o.role===21?"audience":"anchor",this._log.info("Join() => joining room: ".concat(d," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),F.emit(rA.JOIN_START,{room:this,roomId:d,params:o});let h=Kd.getEnv();h||(h=XB.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Hf.OLD_CLOUD_LADDER)?h=XB.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Hf.WEBRTC)&&(h=XB.WEBRTC))),ds.setConfig({env:h,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:d}),ge.checkSystemRequirementsInternal(l).then(y=>{this.checkSystemResult=y,boA.call(this)});try{!this.prelinkPromise&&!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Kd.getEnv()&&(yield this.schedule(o,l));let y=yield A.call(this,o,a,l);return this.roomId=d,this._joinedTimestamp=Kd.performanceNow(),F.emit(rA.JOIN_SUCCESS,{room:this}),l===30&&!o.component&&ds.uploadEvent({log:"stat-conv-".concat(Number(Jp),"-").concat(location.hostname),userId:this.userId}),y}catch(y){throw t.delete({room:this,roomId:d}),F.emit(rA.JOIN_FAILED,{room:this,error:y}),y}})}})],Ly.prototype,"join"),Qi([hc("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Xr(A=>function(){for(var t=arguments.length,o=new Array(t),a=0;aA.mediaType),Xr(A=>function(){for(var t=arguments.length,o=new Array(t),a=0;ad.outMediaTrack&&d.state==="ready"),!o.length))return;F.emit("61",{room:this});let l=A.apply(this,o);return Promise.all(o.map(d=>d.publish(this,l)))})}),iB({settings:{retries:jf,timeout:A=>bp(A)},onError(A,t,o,a){let[l]=a;var d;(d=A.message)!=null&&d.includes("timeout")?(this._log.warn("publish ".concat(l.strMediaType," timeout"),A),t()):(this._log.error("publish ".concat(l.strMediaType," failed: ").concat(A)),o(A),F.emit(rA.PUBLISH_FAILED,{room:this}))}})],Ly.prototype,"publish"),Qi([d_({fnName:"publish"}),Ry(A=>A.mediaType),Xr(A=>function(){for(var t=arguments.length,o=new Array(t),a=0;ad.unpublish()),l}),Xv(function(){var A,t;this.localTracks.size===0&&xI()&&((t=(A=this.singlePC)==null?void 0:A.getPeerConnection())==null||t.getSenders().forEach(o=>o.track&&o.replaceTrack(null)))})],Ly.prototype,"unpublish"),Qi([V5(A=>{if(A.code!==mt.API_CALL_ABORTED)throw A}),Ry(A=>A.userId)],Ly.prototype,"replaceTrack"),Qi([Ry(function(){for(var A=arguments.length,t=new Array(A),o=0;ofunction(){for(var t=arguments.length,o=new Array(t),a=0;a!d.isSubscribed&&d.subscribe(l)),l}),iB({settings:{retries:jf,timeout:A=>bp(A)},onError(A,t,o,a){if(A.message.includes("timeout"))this._log.warn("subscribe timeout"),t();else{let l=A?.code===mt.API_CALL_ABORTED;this._log[l?"warn":"error"]("subscribe failed ".concat(a.map(d=>d.strMediaType).join(","),": ").concat(A)),o(A),F.emit(rA.SUBSCRIBE_FAILED,{room:this,remoteTracks:a})}}})],Ly.prototype,"subscribe"),Qi([d_({fnName:"subscribe",callback(){for(var A=arguments.length,t=new Array(A),o=0;o{let l=this.remotePublishedUserMap.get(a.userId);l&&!l.isMainStreamSubscribed&&!l.isAuxStreamSubscribed&&l.close("you unsubscribed")})}}),Ry(function(){for(var A=arguments.length,t=new Array(A),o=0;oi in e?FV(e,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[i]=n,LaA=(e,i)=>{for(var n in i||(i={}))_X.call(i,n)&&EW(e,n,i[n]);if(NZ)for(var n of NZ(i))kaA.call(i,n)&&EW(e,n,i[n]);return e},UaA=(e,i)=>function(){return i||(0,e[wX(e)[0]])((i={exports:{}}).exports,i),i.exports},FaA=(e,i,n,c)=>{if(i&&typeof i=="object"||typeof i=="function")for(let I of wX(i))_X.call(e,I)||I===n||FV(e,I,{get:()=>i[I],enumerable:!(c=RX(i,I))||c.enumerable});return e},OaA=(e,i,n)=>(n=e!=null?GaA(baA(e)):{},FaA(FV(n,"default",{value:e,enumerable:!0}),e)),z_=(e,i,n,c)=>{for(var I,C=RX(i,n),m=e.length-1;m>=0;m--)(I=e[m])&&(C=I(i,n,C)||C);return C&&FV(i,n,C),C},Ms=(e,i,n)=>EW(e,typeof i!="symbol"?i+"":i,n),PaA=UaA({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(e,i){var n=Object.prototype.hasOwnProperty,c="~";function I(){}function C(T,b,J){this.fn=T,this.context=b,this.once=J||!1}function m(T,b,J,cA,eA){if(typeof J!="function")throw new TypeError("The listener must be a function");var CA=new C(J,cA||T,eA),IA=c?c+b:b;return T._events[IA]?T._events[IA].fn?T._events[IA]=[T._events[IA],CA]:T._events[IA].push(CA):(T._events[IA]=CA,T._eventsCount++),T}function R(T,b){--T._eventsCount===0?T._events=new I:delete T._events[b]}function _(){this._events=new I,this._eventsCount=0}Object.create&&(I.prototype=Object.create(null),new I().__proto__||(c=!1)),_.prototype.eventNames=function(){var T,b,J=[];if(this._eventsCount===0)return J;for(b in T=this._events)n.call(T,b)&&J.push(c?b.slice(1):b);return Object.getOwnPropertySymbols?J.concat(Object.getOwnPropertySymbols(T)):J},_.prototype.listeners=function(T){var b=c?c+T:T,J=this._events[b];if(!J)return[];if(J.fn)return[J.fn];for(var cA=0,eA=J.length,CA=new Array(eA);cA{if(!navigator.userAgent.includes("Firefox"))return e;const i=e.split(`\r + `],{type:"application/javascript"}),t=URL.createObjectURL(A);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.onerror=o=>this._log.warn("worker error:",o.message,o.filename||"unknown",o.lineno||"unknown"),this.worker.onmessage=o=>{var a;let{type:l,trackId:d,message:h,count:y}=o.data;if(l==="black")(a=this.callbacks.get(d))==null||a();else if(l==="log")this._log.warn(h);else if(l==="blackCount"){let S=this.userIdMap.get(d);this._log.warn("".concat(S||d," black count: ").concat(y))}}}return this.worker}start(A){let{track:t,isUplink:o,room:a,userId:l,onBlack:d}=A;if(this._log.debug("start detect black video",t.id),!Uv()||!d||!t||typeof Worker>"u")return void this._log.warn("black video detector not supported");let h=y=>{var S,L,V,H;let lA;if(o)lA=(L=(S=y.msg_up_stream_info)==null?void 0:S.msg_video_status)==null?void 0:L.filter(hA=>hA.uint32_video_stream_type===3)[0];else{let hA=(V=y.msg_down_stream_info)==null?void 0:V.filter(MA=>{var oe;return((oe=MA.msg_user_info)==null?void 0:oe.str_identifier)===l})[0];lA=(H=hA?.msg_video_status)==null?void 0:H.filter(MA=>MA.uint32_video_stream_type===3)[0]}if(lA){let hA=(lA.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[t.id]&&this.sleep[t.id]>0)return void(this.sleep[t.id]-=1);hA>0&&hA<10&&(this.sleep[t.id]=30,this._log.info("track bitrate",hA,"start check"),this.checkOnce(t,3e4))}};return a.on("heartbeat-report",h),this.heartbeatListenerCleaner.set(t.id,()=>a.off("heartbeat-report",h)),this.callbacks.set(t.id,d),this.userIdMap.set(t.id,l),t.id}checkOnce(A,t){try{let o=this.getWorker();if(!o)throw new Error("Worker not available");let a=new MediaStreamTrackProcessor({track:A});o.postMessage({type:"addTrack",trackId:A.id,timeout:t,readable:a.readable},[a.readable])}catch(o){this._log.warn("check error:",o),this.stop(A.id)}}stop(A){if(A){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:A}),this.callbacks.delete(A),delete this.sleep[A];let t=this.heartbeatListenerCleaner.get(A);t&&t(),this.heartbeatListenerCleaner.delete(A),this.userIdMap.delete(A)}}destroy(){this.callbacks.forEach((A,t)=>this.stop(t)),this.worker&&(this.worker.terminate(),this.worker=null)}},q1=class extends N8{constructor(A){super(So(Di({},A),{isUplink:!0})),Y(this,"localMainAudioTrack",null),Y(this,"localMainVideoTrack",null),Y(this,"localAuxAudioTrack",null),Y(this,"localAuxVideoTrack",null),Y(this,"_isPublishingAux",!1),Y(this,"_publishingLocalAudioTrack"),Y(this,"_publishingLocalVideoTrack"),Y(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,videoDecCodec:"",audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),Y(this,"_flag",0),Y(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get videoCodec(){var A;return((A=this.singlePC)==null?void 0:A.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:A,bigVideoSsrc:t,bigVideoRtxSsrc:o,smallVideoSsrc:a,smallVideoRtxSsrc:l,auxVideoSsrc:d,auxVideoRtxSsrc:h}=this.singlePC.uplinkSSRC;return{audio:A||0,video:t||0,videoRtx:o||0,small:a||0,smallRtx:l||0,auxiliary:d||0,auxiliaryRtx:h||0}}get flag(){return this._flag}set flag(A){this._flag!==A&&(this._flag=A,this.checkPublishState())}checkPublishState(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];try{if(!A&&this._checkPublishStateTimeoutId>0)return;let{serverPublishState:t}=this,{publishState:o}=this._room,a=Object.keys(o).filter(l=>{if(o[l]!==t[l]&&o[l])switch(l){case"audio":return!(!this.localMainAudioTrack||!this.localMainAudioTrack.isMediaTrackActive);case"bigVideo":case"smallVideo":return!(!this.localMainVideoTrack||!this.localMainVideoTrack.isMediaTrackActive);case"auxVideo":return!(!this.localAuxVideoTrack||!this.localAuxVideoTrack.isMediaTrackActive)}return!1});if(a.length>0){if(!A)return void(this._checkPublishStateTimeoutId=kr.run("timeout",()=>this.checkPublishState(!0),{delay:1e4,count:1}));ri.addCount({key:521e3}),a.forEach(l=>{this._log.warn("".concat(l," publish failed during call ").concat(jp()," ").concat(lQ())),ri.addEnum({key:521719,value:b8[l]})}),kr.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(t){this._log.warn("checkPublishState failed",t)}}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get serverPublishState(){return{audio:!!(this.flag&iv),bigVideo:!!(this.flag&ev),smallVideo:!!(this.flag&Fb),auxVideo:!!(this.flag&tv)}}initialize(){this.installEvents()}close(A){var t;let o=((t=this._peerConnection)==null?void 0:t.getSenders())||[];for(let a of o)a.replaceTrack(null);super.close(A),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var A,t;(A=this.singlePC)!=null&&A.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(t=this.singlePC)==null||t.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var A;(A=this.singlePC)==null||A.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(A,t){var o,a,l;let d=this._currentState,h=super.emitConnectionStateChangedEvent(A);return h&&d!==A&&(t?t.emit("connection-state-changed",{prevState:d,state:A}):((o=this.localMainVideoTrack)==null||o.emit("connection-state-changed",{prevState:d,state:A}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:d,state:A}),(l=this._publishingLocalVideoTrack)==null||l.emit("connection-state-changed",{prevState:d,state:A}))),h}onVideoEncodeFailed(A){return XA(this,null,function*(){if(!A||!A.isMediaTrackActive)return;let{videoCodec:t,singlePC:o}=this;if(!o)return;let a={h265:{supported:o.isH264EncodeSupported,target:"h264",log:"h265 encoder not working"},h264:{supported:o.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}};if(t==="vp9"||t==="av1")return;let l=a[t];this._log.warn(l.log),l!=null&&l.supported&&(yield o.switchVideoEncoder(l.target))})}publish(A){return XA(this,arguments,function(t){var o=this;let{localAudioTrack:a,localVideoTrack:l,isAuxiliary:d}=t;return function*(){var h,y,S,L,V,H,lA;if(!o.singlePC)return;if(o.installEvents(),o.installTrackMuteEvents(a,l),l&&(l.retryEncodeFailed=o.onVideoEncodeFailed.bind(o),ng&&(uy(PI,"26.2",!0)||uy(aQ,"26.2",!0)||sQ&&uy(PI,"18.7",!0)))){o._log.warn("detectH264Supported for fallback 26.2 video encode issue");try{yield ge.detectH264SupportedByFakeStreaming(500)}catch{}}if(yield o.singlePC.waitForPeerConnectionConnected(),a&&(o._publishingLocalAudioTrack=a),l){if(!o.singlePC.isH264EncodeSupported&&!o.singlePC.isVP8EncodeSupported)throw new li({code:mt.NOT_SUPPORTED_H264,message:sn({key:Go.NOT_SUPPORTED_H264ENCODE})});o.singlePC.isUsingH264&&!o.singlePC.isH264EncodeSupported&&o.singlePC.isVP8EncodeSupported&&(o._log.warn("h264 encoder not supported"),yield o.singlePC.switchVideoEncoder("vp8")),za&&wv()===115&&l.profile.width*l.profile.height<=230400&&(o._log.warn("fallback video to defaultBigVideoProfile: ".concat(JSON.stringify(Av))),l.setProfile(Av),yield l.applyProfile()),o._publishingLocalVideoTrack=l}let hA;if(o._isPublishingAux=d,l&&!d&&l.small&&(hA=o._room.videoManager.smallTrack),yield o._signalChannel.sendWaitForResponseWithRetry({command:I8,responseCommand:Qn.SPC_PUBLISH_RESULT,data:So(Di({},o.singlePC.uplinkSSRC),{state:o._room.publishState,muteState:o._room.muteState}),retries:3}),l&&(yield o.checkHighProfile({streamType:l.streamType,newWidth:l.settings.width,newHeight:l.settings.height})),yield o.publishByTransceiver({localAudioTrack:a,localVideoTrack:l,smallTrack:hA,isAuxiliary:d}),o._publishingLocalAudioTrack=null,o._publishingLocalVideoTrack=null,o._isPublishingAux=!1,l){o[d?"localAuxVideoTrack":"localMainVideoTrack"]=l,yield o.singlePC.setDegradationPreference(o._peerConnection.getSenders()[d?3:1],l.contentHint,l.streamType);let{scaleResolutionDownBy:oe}=l;yield o.singlePC.setScaleResolutionDownBy(o._peerConnection.getSenders()[d?3:1],oe,l.streamType)}a&&(o[d?"localAuxAudioTrack":"localMainAudioTrack"]=a),yield o.singlePC.setBandwidth({audio:((h=o.localMainAudioTrack)==null?void 0:h.profile.bitrate)||((y=o.localAuxAudioTrack)==null?void 0:y.profile.bitrate),bigVideo:(S=o.localMainVideoTrack)==null?void 0:S.profile.bitrate,smallVideo:(V=(L=o.localMainVideoTrack)==null?void 0:L.small)==null?void 0:V.bitrate,auxVideo:(H=o.localAuxVideoTrack)==null?void 0:H.profile.bitrate}),o.sendMediaSettings();let MA=d?7:2;(o._room.preferHW||(lA=o._room.scheduleResult.config)!=null&&lA.preferHW)&&l&&l.profile.width*l.profile.height>=921600&&o.singlePC.useHWEncoder(!0,MA)}()})}publishByTransceiver(A){let{localAudioTrack:t,localVideoTrack:o,smallTrack:a,isAuxiliary:l}=A;if(!AC())return;this._log.info("publish by transceiver");let d=o?.outMediaTrack,h=t?.outMediaTrack,y=this._peerConnection.getTransceivers(),S=[],L=[],V=(lA,hA,MA)=>{var oe;let fe=y[hA].sender.replaceTrack(MA);L.push(hA),(oe=this.singlePC)!=null&&oe.enableInsertableStreams&&fe.then(()=>this.createEncodedStreams(y[hA].sender,lA)),this.initSenderTransform(y[hA].sender,lA),S.push(fe)};h&&V(t.mediaType,0,h),d&&V(o.mediaType,l?3:1,d),o!=null&&o.small&&S.push(this.publishSmall(this._room.videoManager.smallMode,o));let H=this.singlePC.setTransceiverDirection(ir.SENDONLY,L);return S.push(H),Promise.all(S)}getTrackByMediaType(A){switch(A){case 1:return this.localMainAudioTrack||this._room.localMainAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._room.localMainVideoTrack;case 2:return this.localAuxVideoTrack||this._room.localAuxVideoTrack;default:return null}}createEncodedStreams(A,t){var o,a;if(this.singlePC.insertableStreamsAbortMap.has(A))return;let l=A.createEncodedStreams(),d=new AbortController;(o=this.singlePC)==null||o.addAbortController(A,d),((a=this.getTrackByMediaType(t))!=null&&a.enableEncodeFrame?l.readable.pipeThrough(new TransformStream({transform:(h,y)=>{var S,L;let V=this.getTrackByMediaType(t);if(!V||!V.encodeFrame)return y.enqueue(h);V.isAudio?y.enqueue(V.enableEncodeFrame?V.encodeFrame(h):h):y.enqueue((S=this.singlePC)!=null&&S.isUsingH264||(L=this.singlePC)!=null&&L.isUsingH265?V.encodeFrame(h,t===8):h)}}),d):l.readable).pipeTo(l.writable,d).catch(h=>{this._log.debug("encoded stream error",h),h!=="destroy"&&this._log.warn(h)})}initSenderTransform(A,t){if(!(this._peerConnection&&this.singlePC&&this.singlePC.scriptTransformWorker&&c_))return;let o=t!==2,a=t===8;A.transform||(A.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:t===1,isMain:o,isSmall:a}))}enableSmall(A){return XA(this,null,function*(){A?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(A){return XA(this,arguments,function(t){var o=this;let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.localMainVideoTrack;return function*(){var l;if(!o.singlePC)return;if(t==="canvas"&&!g_())return void o._log.warn("canvas mode small stream is not supported");let d=o._peerConnection.getTransceivers(),{sender:h}=d[2],y=yield o.doPublishSmall(t,a),S=t==="canvas"?524700:524701;ri.addSuccessEvent({key:S}),y?((l=o.singlePC)!=null&&l.enableInsertableStreams&&o.createEncodedStreams(h,8),o.initSenderTransform(h,8),yield o.singlePC.setTransceiverDirection(ir.SENDONLY,[2]),o.updateMediaSettings(),yield o.doPublishChange(),h.track&&(o._blackSmallVideoDetectionId=aM.start({track:h.track,room:o._room,isUplink:!0,userId:o.userId,onBlack:()=>{o._log.warn("small video is black");let L=t==="canvas"?524700:524701;ri.addFailedEvent({key:L,error:10002}),aM.stop(o._blackSmallVideoDetectionId),o._blackSmallVideoDetectionId=void 0}}))):ri.addFailedEvent({key:S,error:10001})}()})}doPublishSmall(A){return XA(this,arguments,function(t){var o=this;let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.localMainVideoTrack;return function*(){if(!o.singlePC)return null;o._log.info("publish small",t);let l=o._peerConnection.getTransceivers(),{sender:d}=l[2];if(t==="canvas"&&o._room.videoManager.smallTrack)return yield d.replaceTrack(o._room.videoManager.smallTrack),"canvas";if(t==="api"&&a!=null&&a.outMediaTrack&&a!=null&&a.small){yield d.replaceTrack(a?.outMediaTrack);let h=d.getParameters(),y=F0(a?.profile,a?.small);return o._log.info("small scaleResolutionDownBy",y),h.encodings[0].scaleResolutionDownBy=y,d.setParameters(h),"api"}return o._log.warn("small track can not be enabled, smallMode: ".concat(o._room.videoManager.smallMode,", smallTrack: ").concat(!!o._room.videoManager.smallTrack,", bigVideoTrack: ").concat(!(a==null||!a.outMediaTrack))),null}()})}unpublishSmall(){return XA(this,null,function*(){this.singlePC&&(this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(ir.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),aM.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)})}checkHighProfile(A){return XA(this,null,function*(){var t,o;if((((t=this._room.scheduleResult.config)==null?void 0:t.profileLevelId)||{})[A.streamType==="main"?"big":"aux"]!=="high")return;let a=A.newWidth*A.newHeight>=921600&&!Ey();try{yield(o=this.singlePC)==null?void 0:o.setH264ProfileLevelId(A.streamType,a)}catch(l){this._log.warn("setH264ProfileLevelId failed, ignore",l)}})}installTrackMuteEvents(){for(var A=arguments.length,t=new Array(A),o=0;o{a&&(a?.on("mute",this.sendMutedFlag,this),a?.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(){for(var A=arguments.length,t=new Array(A),o=0;o{a&&(a?.off("mute",this.sendMutedFlag,this),a?.off("unmute",this.sendMutedFlag,this))})}unpublish(A){return XA(this,arguments,function(t){var o=this;let{localAudioTrack:a,localVideoTrack:l}=t;return function*(){var d;yield(d=o.singlePC)==null?void 0:d.waitForPeerConnectionConnected();let h=l&&l===o.localAuxVideoTrack||a&&a===o.localAuxAudioTrack,y=l?.outMediaTrack,S=o._peerConnection.getSenders(),L=[];a&&(h?o.localAuxAudioTrack=null:o.localMainAudioTrack=null,!o.localMainAudioTrack&&!o.localAuxAudioTrack&&(yield S[0].replaceTrack(null),L.push(0))),y&&(h?(yield S[3].replaceTrack(null),o.localAuxVideoTrack=null,o._mediaSettings=So(Di({},o._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),L.push(3)):(yield S[1].replaceTrack(null),yield S[2].replaceTrack(null),o.localMainVideoTrack=null,o._mediaSettings=So(Di({},o._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),L.push(1,2))),o.isMainStreamPublished||o.isAuxStreamPublished?(yield o.singlePC.setTransceiverDirection(ir.INACTIVE,L),yield o.doPublishChange(!1)):yield o.doUnpublish(),o.uninstallTrackMuteEvents(a,l),l?.emit("connection-state-changed",{prevState:o._currentState,state:"DISCONNECTED"})}()})}doPublishChange(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return XA(this,null,function*(){let t={state:this._room.publishState,constraintConfig:this._mediaSettings},o=yield this._signalChannel.sendWaitForResponseWithRetry({command:Vj,data:t,responseCommand:Qn.PUBLISH_STATE_CHANGE_RESULT,enableLog:A,retries:3});this.checkPublishResultCode(o.data.code,o.data.message)})}doUnpublish(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this._signalChannel.sendWaitForResponse({command:P1,commandDesc:"unpublish",responseCommand:Qn.UNPUBLISH_RESULT,enableLog:A}).catch(t=>{if(t.getCode()===mt.API_CALL_TIMEOUT||t.getCode()===mt.API_CALL_ABORTED)return Promise.resolve();throw t})}updateMediaSettings(){var A,t;this._mediaSettings.videoCodec=((A=this.singlePC)==null?void 0:A.videoCodec)||"h264",this._mediaSettings.videoDecCodec=((t=this.singlePC)==null?void 0:t.downlinkVideoCodec)||"h264";let o=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:a,localAuxVideoTrack:l}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?l=this._publishingLocalVideoTrack:a=this._publishingLocalVideoTrack),Dy){if(o&&o.outMediaTrack){let d=o.outMediaTrack.getSettings();this._mediaSettings.audioChannel=d.channelCount||1,this._mediaSettings.audioBps=1e3*o.profile.bitrate,this._mediaSettings.audioFs=d.sampleRate||0}if(a&&a.outMediaTrack){let d=a.outMediaTrack.getSettings(),{scaleResolutionDownBy:h}=a;this._mediaSettings.videoWidth=(d.width||0)/h||0,this._mediaSettings.videoHeight=(d.height||0)/h||0,this._mediaSettings.videoFps=d.frameRate||0,this._mediaSettings.videoBps=1e3*a.profile.bitrate,a.small&&(this._mediaSettings.smallVideoWidth=a.small.width,this._mediaSettings.smallVideoHeight=a.small.height,this._mediaSettings.smallVideoFps=a.small.frameRate,this._mediaSettings.smallVideoBps=1e3*a.small.bitrate)}if(l&&l.outMediaTrack){let d=l.outMediaTrack.getSettings(),{scaleResolutionDownBy:h}=l;this._mediaSettings.auxVideoWidth=(d.width||0)/h||0,this._mediaSettings.auxVideoHeight=(d.height||0)/h||0,this._mediaSettings.auxVideoFps=d.frameRate||0,this._mediaSettings.auxVideoBps=1e3*l.profile.bitrate}}else o&&o.outMediaTrack&&(this._mediaSettings.audioChannel=o.profile.channelCount,this._mediaSettings.audioBps=1e3*o.profile.bitrate,this._mediaSettings.audioFs=o.profile.sampleRate),a&&a.outMediaTrack&&(this._mediaSettings.videoWidth=a.profile.width,this._mediaSettings.videoHeight=a.profile.height,this._mediaSettings.videoFps=a.profile.frameRate,this._mediaSettings.videoBps=1e3*a.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:qj,data:this._mediaSettings,responseCommand:Qn.UPDATE_CONSTRAINT_CONFIG_RES}).then(A=>{A.data.code!==0&&this._log.warn(A.data.message)}).catch(()=>{})}addTrack(A){return XA(this,null,function*(){if(!this._peerConnection)return;let t=A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;this._log.info("is adding ".concat(A.kind," track to current published local ").concat(t?JA.AUXILIARY:JA.MAIN," stream")),CQ()&&(yield this.addTrackByTransceiver(A,t))})}addTrackByTransceiver(A,t){return XA(this,null,function*(){var o;if(!A.mediaTrack)return;let a=this._peerConnection.getTransceivers();if(A.kind===JA.AUDIO)yield a[0].sender.replaceTrack(A.outMediaTrack);else{let l=t?3:1;yield a[l].sender.replaceTrack(A.outMediaTrack),l===1&&(o=this.localMainVideoTrack)!=null&&o.small&&this._room.videoManager.smallTrack&&(yield a[2].sender.replaceTrack(this._room.videoManager.smallTrack)),a[l].direction===ir.INACTIVE&&(yield this.singlePC.setTransceiverDirection(ir.SENDONLY,[l]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(A){return XA(this,null,function*(){if(!this._peerConnection)return;let t=A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;this._log.info("is removing ".concat(A.kind," track from current published local ").concat(t?JA.AUXILIARY:JA.MAIN," stream")),CQ()&&(yield this.removeTrackByTransceiver(A,t))})}removeTrackByTransceiver(A,t){return XA(this,null,function*(){if(!A.mediaTrack)return;let o=this._peerConnection.getTransceivers();if(A.kind===JA.AUDIO)yield o[0].sender.replaceTrack(null);else{let a=t?3:1;yield o[a].sender.replaceTrack(null),a===1&&this._room.videoManager.hasSmall&&(yield o[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(ir.INACTIVE,[a])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(A){return XA(this,null,function*(){var t;let o=(t=this._peerConnection)==null?void 0:t.getSenders(),a=A.outMediaTrack||A.mediaTrack;if(!o||o.length===0||!a||o.find(d=>d.track===a))return!1;let l=A.mediaType===2||A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(a.kind," track ").concat(a.id," ").concat(a.label," on ").concat(l?JA.AUXILIARY:JA.MAIN," stream")),a.kind===JA.AUDIO&&o[0]&&(yield o[0].replaceTrack(a)),a.kind===JA.VIDEO&&(!l&&o[1]&&(yield o[1].replaceTrack(a)),l&&o[3]&&(yield o[3].replaceTrack(a))),!0})}setBandwidth(A){return XA(this,arguments,function(t){var o=this;let{bandwidth:a,type:l,videoType:d}=t;return function*(){if(o.singlePC){let h={};l===JA.AUDIO?h.audio=a:d==="big"?h.bigVideo=a:d==="small"?h.smallVideo=a:h.auxVideo=a,yield o.singlePC.setBandwidth(h)}}()})}sendMutedFlag(A){A===this.localAuxAudioTrack||A===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:g8,responseCommand:Qn.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(A){A.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&F.emit(rA.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:JA.VIDEO;if(this._peerConnection){let t=this._peerConnection.getSenders();if(A===JA.AUXILIARY&&t[3]&&t[3].track)return t[3].track.id;if(A===JA.VIDEO&&t[1]&&t[1].track)return t[1].track.id}if(this.localMainVideoTrack&&A===JA.VIDEO){let t=this.localMainVideoTrack.mediaTrack;if(t)return t.id}if(this.localAuxVideoTrack&&A===JA.AUXILIARY){let t=this.localAuxVideoTrack.mediaTrack;if(t)return t.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(A,t){if(A!==0)throw A===m0?(this._log.error(Cc.NOT_SUPPORTED_H264ENCODE),new li({code:mt.NOT_SUPPORTED_H264,message:sn({key:Go.NOT_SUPPORTED_H264ENCODE})})):new li({code:mt.UNKNOWN,message:sn({key:Go.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Qn.PUBLISH_RESULT,code:A,message:t}})})}onSinglePCReconnected(){return XA(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};Qi([Xv(A=>{let{localVideoTrack:t}=A;t==null||delete t.retryEncodeFailed})],q1.prototype,"unpublish"),Qi([G8({when(){return this.isDestroyed}})],q1.prototype,"doPublishChange"),Qi([G8({when(){return this.isDestroyed}})],q1.prototype,"doUnpublish");var b8=(A=>(A[A.audio=1]="audio",A[A.bigVideo=2]="bigVideo",A[A.smallVideo=3]="smallVideo",A[A.auxVideo=4]="auxVideo",A))(b8||{}),k8=q1;function L8(A){return Object.keys(A).filter(t=>A[t])}var K1=class extends N8{constructor(A){super(So(Di({},A),{isUplink:!1})),Y(this,"_flag",0),Y(this,"isRobot",!1),Y(this,"role","anchor"),Y(this,"fromType"),Y(this,"remoteAudioTrack"),Y(this,"remoteVideoTrack"),Y(this,"remoteAuxiliaryTrack"),Y(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),Y(this,"_prevMids"),Y(this,"jitterBufferTimeoutId",-1),Y(this,"_jitterBufferResolve"),Y(this,"_videoCodec"),Y(this,"avPlayerStateSyncManager"),Y(this,"isDataChannelSubscribed",!1),this.flag=A.flag,this.isRobot=A.isRobot||!1,this.fromType=A.fromType,this.remoteAudioTrack=new y1(this._room,this),this.remoteVideoTrack=new fL(this._room,this),this.remoteAuxiliaryTrack=new fz(this._room,this),this.avPlayerStateSyncManager=new _j({log:this._log,audioPlayer:this.remoteAudioTrack.player,videoPlayer:this.remoteVideoTrack.player}),this.initialize()}get videoCodec(){var A;return this._videoCodec||((A=this.singlePC)==null?void 0:A.downlinkVideoCodec)||"h264"}set videoCodec(A){this._videoCodec=A}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing,datachannel:this.isDataChannelSubscribed}}get muteState(){return kp(this.flag,this.userId)}get flag(){return this._flag}set flag(A){var t,o,a;A!==this._flag&&(this._flag=A,(t=this.remoteAudioTrack)==null||t.onFlagChanged(),(o=this.remoteVideoTrack)==null||o.onFlagChanged(),(a=this.remoteAuxiliaryTrack)==null||a.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(A){return A===JA.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(A){clearTimeout(this.jitterBufferTimeoutId),super.close(A),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.avPlayerStateSyncManager.destroy(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.on("decode-failed",this.onDecodeFailed,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.off("decode-failed",this.onDecodeFailed,this))}emitConnectionStateChangedEvent(A){var t,o;let a=this._currentState,l=super.emitConnectionStateChangedEvent(A);return l&&a!==A&&((t=this.remoteVideoTrack)==null||t.emit("connection-state-changed",{prevState:a,state:A}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:a,state:A})),l}onTrack(A){var t,o;let a=A.streams[0],{track:l,receiver:d}=A;if(!a.id.includes(this.tinyId))return;let h=a.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(h," ").concat(l.kind));let y=JA.AUDIO;l.kind===JA.VIDEO&&(y=h===JA.MAIN?JA.VIDEO:JA.AUXILIARY);let S=this.remoteAudioTrack;y===JA.VIDEO?S=this.remoteVideoTrack:y===JA.AUXILIARY&&(S=this.remoteAuxiliaryTrack),(t=this.singlePC)==null||t.receiverRemoteTrackMap.set(d,S),(o=this.singlePC)!=null&&o.scriptTransformWorker&&this.initReceiverTransform(d,h,l.kind===JA.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(d),S.setInputMediaStreamTrack(l)}createEncodedStreams(A){if(!this.singlePC.insertableStreamsAbortMap.has(A)){let t=A.createEncodedStreams(),o=new AbortController,a={abortController:o,enqueue:l=>{var d,h,y;let S=(d=this.singlePC)==null?void 0:d.receiverRemoteTrackMap.get(A);return S&&(S.kind!=="video"||(h=this.singlePC)!=null&&h.isUsingH264||(y=this.singlePC)!=null&&y.isUsingH265)?S.decodeFrame(l):l}};t.readable.pipeThrough(new TransformStream({transform:(l,d)=>{let h=a.enqueue(l);h&&d.enqueue(h)}})).pipeTo(t.writable,o).catch(l=>{l!=="destroy"&&this._log.warn(l)}),this.singlePC.addAbortController(A,o)}}initReceiverTransform(A,t,o){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||A.transform||(A.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:o,userId:this.userId,streamType:t}))}subscribe(A,t){return XA(this,null,function*(){var o,a;try{let l=!0;if(this._log.info("subscribe ".concat(t," ").concat(L8(A))),this.hasSSRC){let y="subscribe_change";Object.values(A).find(S=>S===!0)||(y="unsubscribe"),yield this.sendSubscription(y,A)}else{if(yield this._room.switchRoomSubedReq,(o=this.singlePC)!=null&&o.autoSubscribedUserMap.size){let y=this.singlePC.autoSubscribedUserMap.get(this.userId);if(y){this.singlePC.autoSubscribedUserMap.delete(this.userId);let S=(a=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:a[y.groupIndex];S&&(this.ssrc={audio:S.audioSsrc,video:S.bigVideoSsrc,videoRtx:S.bigVideoRtxSsrc,auxiliary:S.auxVideoSsrc,auxiliaryRtx:S.auxVideoRtxSsrc},l=!1)}}yield this.doSubscribe(A,l),this.checkTrackEnded(A)}let{user:d,mediaTrack:h}=this.remoteVideoTrack;A.smallVideo&&h?(ri.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=aM.start({track:h,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,d),ri.addFailedEvent({key:524702}),aM.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(aM.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}catch(l){throw this._room.isJoined&&this.isStreamUnpublished(t)?(this._log.warn("".concat(l.message," ").concat(JSON.stringify(this.muteState))),new li({code:mt.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):l}})}checkTrackEnded(A){var t,o,a;if((A.audio&&((t=this.remoteAudioTrack.mediaTrack)==null?void 0:t.readyState)==="ended"||A.video&&((o=this.remoteVideoTrack.mediaTrack)==null?void 0:o.readyState)==="ended"||A.auxiliary&&((a=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:a.readyState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),EE&&nd<92)return;this.singlePC.startReconnection()}}unsubscribe(A){return XA(this,arguments,function(t){var o=this;let{remoteTracks:a,streamType:l}=t;return function*(){var d;if(l==="main"&&!o.isMainStreamSubscribed||l==="auxiliary"&&!o.isAuxStreamSubscribed)return void o._log.info("".concat(l," stream already unsubscribed"));let h=Di({},o.subscribeState);a.forEach(S=>{switch(S.mediaType){case 1:h.audio=!1;break;case 4:h.video=!1;break;case 8:h.smallVideo=!1;break;case 2:h.auxiliary=!1}});let y="subscribe_change";Object.values(h).find(S=>S===!0)||(y="unsubscribe"),o._log.info("".concat(y==="unsubscribe"?y:"subscribe"," ").concat(l," [").concat(L8(h),"]")),y==="unsubscribe"&&((d=o.singlePC)==null||d.removeDownlinkQueue.add(o.tinyId)),yield o.sendSubscription(y,h),l==="main"&&(aM.stop(o._blackSmallVideoDetectionId),o._blackSmallVideoDetectionId=void 0),y==="unsubscribe"&&(yield o.removeDownlink())}()})}subscribeDataChannel(){return XA(this,null,function*(){if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let A=So(Di({},this.subscribeState),{datachannel:!0});yield this.doSubscribe(A)})}unsubscribeDataChannel(){return XA(this,null,function*(){let A=So(Di({},this.subscribeState),{datachannel:!1});yield this.sendSubscription("unsubscribe",A),yield this.removeDownlink()})}sendSubscription(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscribeState,o={srcTinyId:this.tinyId,srcUserId:this.userId},a=Hj,l=Qn.UNSUBSCRIBE_RESULT;return A==="subscribe_change"&&(o={audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:t.datachannel,srcTinyId:this.tinyId},a=Jj,l=Qn.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:a,data:o,responseCommand:l,timeout:1e4,retries:3}).then(d=>{let{data:h}=d;if(h.code!==0){let y=new li({code:h.code,message:sn({key:Go.ERROR_MESSAGE,data:{type:A,message:h.message}})});throw this._log.error(y),y}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay(A){let{audioDelay:t,videoDelay:o}=A;this.remoteAudioTrack.stat.end2EndDelay=t,this.remoteVideoTrack.stat.end2EndDelay=o}onSinglePCReconnected(){return XA(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary||this.isDataChannelSubscribed)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return XA(this,arguments,function(){var A=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.subscribeState,o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return function*(){var a,l;if(A.singlePC){A.singlePC.addDownlinkQueue.add(A.tinyId),yield A.singlePC.waitForPeerConnectionConnected();try{if(o||!A.hasSSRC){let d={audioSsrc:sB(),bigVideoSsrc:sB(),bigVideoRtxSsrc:sB(),auxVideoSsrc:sB(),auxVideoRtxSsrc:sB()},{audioSsrc:h,bigVideoSsrc:y,bigVideoRtxSsrc:S,auxVideoSsrc:L,auxVideoRtxSsrc:V}=d;A.ssrc={audio:h,video:y,videoRtx:S,auxiliary:L,auxiliaryRtx:V},A.singlePC.addDownlinkQueue.delete(A.tinyId),yield A.singlePC.addDownlink({userId:A.userId,tinyId:A.tinyId,ssrc:A.ssrc,prevMids:A._prevMids});try{let H=yield A._signalChannel.sendWaitForResponseWithRetry({command:u8,responseCommand:Qn.SPC_SUBSCRIBE_RESULT,data:{srcUserId:A.userId,srcTinyId:A.tinyId,audio:t.audio,bigVideo:t.video,auxVideo:t.auxiliary,smallVideo:t.smallVideo,customData:(a=t.datachannel)!=null&&a,ssrc:d},retries:3,retryTimeout:0});if(H.data.code!==0&&H.data.code!==-10036)throw new li({code:H.data.code,message:H.data.message});A.isDataChannelSubscribed=(l=t.datachannel)!=null&&l}catch(H){throw yield A.removeDownlink(),H}return}A.singlePC.addDownlinkQueue.delete(A.tinyId),yield A.singlePC.addDownlink({userId:A.userId,tinyId:A.tinyId,ssrc:A.ssrc,prevMids:A._prevMids})}finally{if((t.audio||t.video||t.smallVideo||t.auxiliary||!t.datachannel)&&hQ){let{main:d,aux:h}=A._room.jitterBufferDelay||{},{jitterDelay:y=d,jitterDelayAux:S=h}=A._room.scheduleResult.config||{};(Ys(y)||Ys(S))&&A.setJitterBufferDelay({mainDelay:y,auxDelay:S})}}}}()})}removeDownlink(){return XA(this,null,function*(){this.singlePC&&(this.isDataChannelSubscribed=!1,this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),clearTimeout(this.jitterBufferTimeoutId),this._jitterBufferResolve&&(this._jitterBufferResolve(),this._jitterBufferResolve=void 0),this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),this._prevMids=yield this.singlePC.removeDownlink(this.userId))})}setJitterBufferDelay(A){let{mainDelay:t,auxDelay:o}=A;if(!hQ||!this.singlePC||!this._peerConnection||td(t)&&td(o))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(t," aux: ").concat(o));let a=this.singlePC.getReceiversByUserId(this.userId);return Ys(t)&&(this.remoteAudioTrack.jitterBufferDelay=t,this.remoteVideoTrack.jitterBufferDelay=t),Ys(o)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=o,td(t)&&(this.remoteAudioTrack.jitterBufferDelay=o)),new Promise(l=>{this._jitterBufferResolve=l,this.doSetJitterBufferDelay({mainDelay:t,auxDelay:o,receivers:a,resolve:l})})}doSetJitterBufferDelay(A){let{mainDelay:t,auxDelay:o,receivers:a,resolve:l}=A;try{if(t===0&&o===0)return a.forEach(d=>d.jitterBufferTarget=0),this._jitterBufferResolve=void 0,l();if(a.forEach(d=>{var h;let y=d.track===this.remoteAuxiliaryTrack.outMediaTrack||td(t)&&d.track===this.remoteAudioTrack.outMediaTrack;if(y&&td(o)||!y&&td(t))return;let S=y?o||0:t,L=(d.jitterBufferTarget||0)+100;L>S||(d.jitterBufferTarget=L,this._log.debug("set ".concat(y?"aux ":"").concat((h=d?.track)==null?void 0:h.kind," jitterBuffer delay ").concat(L," -> ").concat(S)))}),!a.find(d=>{let h=d.track===this.remoteAuxiliaryTrack.outMediaTrack?o||0:t;return d.jitterBufferTarget{this.doSetJitterBufferDelay({mainDelay:t,auxDelay:o,receivers:a,resolve:l})},1e3)}catch(d){this._log.warn("set jitterBuffer delay error: ".concat(d)),clearTimeout(this.jitterBufferTimeoutId),this._jitterBufferResolve=void 0,l()}}get audioReceiver(){var A;return((A=this.singlePC)==null?void 0:A.getReceiversByUserId(this.userId)[0])||null}onDecodeFailed(){this._room.downlinkVideoCodec==="h265"&&this._room.requestRemoteFallbackToH264()}};Qi([lL(),Xr(A=>function(){for(var t=arguments.length,o=new Array(t),a=0;a{let h=y=>{this.off("closed",h),d(new li({code:mt.API_CALL_ABORTED,message:sn({key:Go.CONNECTION_ABORTED,data:y})}))};this.on("closed",h),A.apply(this,o).then(l,d).finally(()=>{this.off("closed",h)})})})],K1.prototype,"subscribe"),Qi([lL()],K1.prototype,"unsubscribe"),Qi([Ry(()=>"jitter")],K1.prototype,"setJitterBufferDelay");var LnA=K1,UnA=dc($l()),U8=class MX extends UnA.EventEmitter{constructor(t,o){super(),this.room=t,this.signalChannel=o,Y(this,"log"),Y(this,"cmdIdSeqMap",new Map),Y(this,"messageMap",new Map),this.log=pA.createLogger({parent:t.getLogger(),id:"cmm",userId:t.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),o.on(Qn.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",a=>{let{userId:l}=a;[...this.messageMap.keys()].forEach(d=>{d.split("_").slice(0,-1).join("_")===l&&this.messageMap.delete(d)})})}send(t){let{cmdId:o,data:a}=t,l=this.cmdIdSeqMap.get(o)||Math.floor(16383*Math.random()),d={cmdId:o,msg:btoa(String.fromCharCode(...new Uint8Array(a))),ordered:!0,reliable:!0,streamSeq:l};this.cmdIdSeqMap.set(o,l+1),this.signalChannel.send(inA,d),this.log.debug("send custom msg: ".concat(JSON.stringify(d)))}onReceiveMsg(t){let{data:o}=t.data,a=this.room.tinyIdToUserIdMap.get(o.srcTinyId);if(a){let l={userId:a,cmdId:o.cmdId,seq:o.streamSeq,data:Uint8Array.from(atob(o.msg),d=>d.charCodeAt(0)).buffer};if(o.ordered){let d="".concat(a,"_").concat(l.cmdId),h=this.messageMap.get(d);if(h&&h.lastSeq!==0)if(Math.abs(h.lastSeq-l.seq)>MX.SEQ_INTERVAL)this.messageMap.set(d,{lastSeq:l.seq,cachedMessageMap:new Map}),this.emitMessage(l);else if(l.seq>h.lastSeq){if(l.seq===h.lastSeq+1)this.emitMessage(l);else if(!h.cachedMessageMap.has(l.seq)){let y=setTimeout(()=>this.emitMessage(l,!0),5e3);h.cachedMessageMap.set(l.seq,{message:l,timeoutId:y})}}else this.log.debug("drop message ".concat(l.userId,"-").concat(l.cmdId,"-").concat(l.seq));else h||(h={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(d,h),setTimeout(()=>this.emitMessage(l,!0),100)),h.cachedMessageMap.set(l.seq,{message:l})}else this.emit("message",l)}else{this.log.warn("receive msg from unknown user, wait peer-join tinyId: ".concat(o.srcTinyId));let l=d=>{d.tinyId===o.srcTinyId&&(this.room.off("peer-join",l),this.onReceiveMsg(t))};this.room.on("peer-join",l),OC(2e3).then(()=>this.room.off("peer-join",l))}}emitMessage(t){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var a;let l=this.messageMap.get("".concat(t.userId,"_").concat(t.cmdId)),d=t;if(l){if(o){let y=[...l.cachedMessageMap.values()].sort((S,L)=>S.message.seq-L.message.seq);y[0]&&(d=y[0].message)}l.lastSeq!==0&&d.seq-l.lastSeq>1&&this.log.debug("msg lost userId: ".concat(d.userId," seq: ").concat(l.lastSeq," -> ").concat(d.seq)),l.lastSeq=d.seq,clearTimeout((a=l.cachedMessageMap.get(d.seq))==null?void 0:a.timeoutId),l.cachedMessageMap.delete(d.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(d))),this.emit("message",d);let h=l?.cachedMessageMap.get(d.seq+1);h&&this.emitMessage(h.message)}};Y(U8,"SEQ_INTERVAL",300);var FnA=U8,{isString:F8,isUndefined:gM,getNetworkType:OnA,isEmpty:PnA}=Kd,Ly=class extends SnA{constructor(A){super(A),Y(this,"_businessInfo"),Y(this,"userManager"),Y(this,"_version"),Y(this,"_heartbeat",-1),Y(this,"_lastHeartBeatTime",-1),Y(this,"_stats"),Y(this,"_joinTimeout",-1),Y(this,"_firstPublishedList",null),Y(this,"_joinReject",null),Y(this,"_isRelayChanged",!1),Y(this,"sdpSemantics"),Y(this,"signalChannel",null),Y(this,"uplinkConnection",null),Y(this,"singlePC",null),Y(this,"enableSPC",Yv),Y(this,"_changeBigSmallRecords",new Map),Y(this,"networkQuality"),Y(this,"_iceTransportPolicy"),Y(this,"forceRelay",!1),Y(this,"_turnServers",[]),Y(this,"_iceServersFromJoin"),Y(this,"_syncUserListInterval",-1),Y(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),Y(this,"enableSEI",!1),Y(this,"_enableAudioVolumeEvaluation",!1),Y(this,"_audioVolumeIntervalId",0),Y(this,"_enableMultiAuxStream",!1),Y(this,"_pureAudioPushMode",!1),Y(this,"_customMessageManager"),Y(this,"_enableDataChannel",!1),Y(this,"preferHW",!1),Y(this,"healthDetector"),Y(this,"playoutDelay"),Y(this,"jitterBufferDelay"),Y(this,"_updateAudioLevelTaskId",-1),Y(this,"switchRoomSubedReq"),Y(this,"resolveSwitchRoomSubedReq"),Y(this,"enableVolumeControlInIOS"),Y(this,"capturedLocalMainAudioTrack"),Y(this,"capturedLocalMainVideoTrack"),Y(this,"capturedLocalAuxVideoTrack"),Y(this,"PRELINK_EXPIRED_TIME",3e5),Y(this,"PRELINK_TIMEOUT",1e4),Y(this,"prelinkTimeoutId",null),Y(this,"firewallDetector"),this.firewallDetector=new roA,this.firewallDetector.on("firewall-restriction",()=>{this._log.warn("firewall restriction"),this.emit("firewall-restriction")}),this._stats=new cnA(this,this._log),this.userManager=new noA(this.userId,this._log),this._version=Wd,this.sdpSemantics=p0,gM(A.sdpSemantics)?ge.isUnifiedPlanDefault()&&(this.sdpSemantics=nv):this.sdpSemantics=A.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(OnA())),A.iceTransportPolicy&&(this._iceTransportPolicy=A.iceTransportPolicy),this._enableMultiAuxStream=!gM(A.enableMultiAuxStream)&&A.enableMultiAuxStream,this.enableSEI=A.enableSEI&&Yv,!gM(A.enableSPC)&&Yv&&(this.enableSPC=A.enableSPC),this.preferHW=!!A.preferHW,this.enableVolumeControlInIOS=A.enableVolumeControlInIOS,this._initBusinessInfo(A),this.healthDetector=new TnA(this)}get isMainStreamPublished(){var A;return!((A=this.uplinkConnection)==null||!A.isMainStreamPublished)}get isMainAudioPublished(){var A;return!((A=this.uplinkConnection)==null||!A.localMainAudioTrack)}get isAuxStreamPublished(){var A;return!((A=this.uplinkConnection)==null||!A.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(A=>A.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(A=>[A.tinyId,A.userId]))}get videoCodec(){var A;return((A=this.singlePC)==null?void 0:A.videoCodec)||"h264"}get downlinkVideoCodec(){var A;return((A=this.singlePC)==null?void 0:A.downlinkVideoCodec)||"h264"}join(A,t,o){return XA(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",a=>{this.emit("peer-join",a)}),this.userManager.on("8",a=>{this.emit("asr-robot-peer-join",a)}),this.userManager.on("9",a=>{this.emit("asr-robot-peer-leave",a)}),this.userManager.on("2",a=>{let{userId:l,reason:d}=a;this.closeDownLinkConnection(l,"remote user exitRoom"),this.emit("peer-leave",{userId:l,reason:d})}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",a=>{var l=Yx(a,[]);F.emit(rA.REMOTE_PUBLISH_STATE_CHANGED,Di({room:this},l)),this.emit("remote-publish-state-changed",Di({},l))}),this.joinParams=A,br(A.enableDataChannel)&&(this._enableDataChannel=A.enableDataChannel),new Promise((a,l)=>XA(this,null,function*(){var d,h;this._joinReject=l;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(S){if(!(S instanceof li&&S.code===mt.SPC_INITIALIZED_FAILED))return l(S);(d=this.signalChannel)==null||d.destroy(),yield this.initialize()}let y=Oo();yield this.doJoin(A,(h=this.singlePC)==null?void 0:h.clientAbility),ri.addSuccessEvent({key:521708,cost:Oo()-y}),a(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(y){ri.addFailedEvent({key:521708,error:y}),l(y)}this._joinReject=null}))})}initSinglePC(){return XA(this,null,function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new ky({signalChannel:this.signalChannel,room:this,enableDataChannel:this._enableDataChannel}),this.singlePC.on("sei-message",A=>this.emit("sei-message",A)),this.singlePC.on("dump",A=>this.emit("dump",A)),this.singlePC.once("error",()=>this.fallbackToMPC()),this.singlePC.on("data_channel_msg",A=>{let t=new TextDecoder().decode(A.data.data||A.data);try{this.emit("data-channel-message",{data:JSON.parse(t)})}catch{}});try{return yield this.singlePC.initialize()}catch(A){throw this.fallbackToMPC(),new li({code:mt.SPC_INITIALIZED_FAILED,message:A?.message})}}})}doJoin(A,t){return new Promise((o,a)=>XA(this,null,function*(){var l,d,h,y,S,L,V,H;A.privateMapKey&&(this.privateMapKey=A.privateMapKey),A.latencyLevel&&(this.latencyLevel=A.latencyLevel),this.signalChannel.once(F1,MA=>{this.clearJoinTimeout(),F.emit(rA.JOIN_SIGNAL_CONNECTION_END,{room:this,error:MA}),a(MA)}),br((d=(l=this.scheduleResult)==null?void 0:l.config)==null?void 0:d.singlePC)&&Yv&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),(!((y=(h=this.scheduleResult)==null?void 0:h.config)!=null&&y.jitterDelay)&&!((L=(S=this.scheduleResult)==null?void 0:S.config)!=null&&L.jitterDelayAux)||!hQ)&&t&&this.playoutDelay&&(this._log.info("set playoutDelay",JSON.stringify(this.playoutDelay)),t.playoutDelay=this.playoutDelay);let lA={roomId:String(A.roomId||A.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:A.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:ys(),netType:$f(),bussinessInfo:this._businessInfo,ability:t,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&a_(),transcription:this._enableDataChannel,downUseVp8:((V=this.scheduleResult.config)==null?void 0:V.downUseVp8)||!1};this._log.debug("join room signal data: ".concat(JSON.stringify(lA)));let hA=5e3;(H=this.scheduleResult.config)!=null&&H.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(hA=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout(()=>{a(new li({code:mt.JOIN_ROOM_FAILED,message:sn({key:Go.JOIN_ROOM_TIMEOUT})}))},hA),F.emit(rA.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?AnA:OoA,lA),this.signalChannel.once(Qn.JOIN_ROOM_RESULT,MA=>XA(this,null,function*(){this.clearJoinTimeout();let{code:oe,message:fe,data:je,tinyId:_e}=MA.data;F.emit(rA.JOIN_RECEIVED_CMD_RES,{room:this,code:oe}),oe===0?(this._log.info("Join room success, start heartbeat"),_e&&(this.tinyId=_e),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=je.publishers,this._iceServersFromJoin=je.iceServer?[je.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var vi;(vi=this.singlePC)==null||vi.connect(So(Di({},je.ability),{useVp8:je.ability.useVp8||!!A.useVp8,useH265:je.ability.useH265&&!!A.useH265})).catch(()=>{})}),o()):(this._log.error("Join room failed result: ".concat(oe," error: ").concat(fe)),a(new li({code:mt.JOIN_ROOM_FAILED,extraCode:oe,message:sn({key:Go.JOIN_ROOM_FAILED,data:{error:fe,code:oe}})})))}))}))}reJoin(){return XA(this,null,function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this.joinParams.roomId));let A,t=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,t.push(this.initSinglePC().then(o=>(A=o,o)))),this.signalChannel&&(this.signalChannel.close(),t.push(this.signalChannel.connect())),yield Promise.all(t),yield this.doJoin(So(Di({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),A),this._log.warn("reJoin success"),ds.logSuccessEvent({userId:this.userId,eventType:Wa.REJOIN}),this.singlePC){let o=a=>{var l;a.state==="CONNECTED"&&((l=this.singlePC)==null||l.off(w_.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof k8&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(d=>{d.installEvents(),d.onSinglePCReconnected()}))};this.singlePC.on(w_.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof H1&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(A){this._log.warn("reJoin fail ".concat(A)),this.reset(),ds.logFailedEvent({userId:this.userId,eventType:Wa.REJOIN,error:A}),this.emit("error",new li({code:mt.JOIN_ROOM_FAILED,message:sn({key:Go.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")})}initialize(A){return XA(this,null,function*(){var t,o;if(!(A!=null&&A.isPrelink)&&this.prelinkPromise&&(yield this.prelinkPromise),(t=this.signalChannel)!=null&&t.isPrelinkValid(this.sdkAppId,this.userId,this.userSig))return this._log.info("reuse prelink signal channel"),void this.signalChannel.consumePrelink();(o=this.signalChannel)!=null&&o.prelink&&this.signalChannel.close();let a,{mainUrl:l,backupUrl:d}=this.getSignalChannelUrl(),h=this.signalChannel||function(S){return[...x1.values()].find(V=>V.room.userId===S&&!V.room.isJoined)||null}(this.userId),y=!!(h&&h.isConnected&&h.keepAlive&&h.userId===this.userId);return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(a=this.scheduleResult.domains[0]),this._log.info("".concat(y?"reuse":"setup"," signal channel")),y?(h.url=l,h.backupUrl=d,h.room.setSignalChannel(null),h.room=this,this.signalChannel=h):(h&&h.close(),this.signalChannel=new E8({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:l,backupUrl:d,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?a:void 0,prelink:A?.isPrelink}),this._customMessageManager=new FnA(this,this.signalChannel),this._customMessageManager.on("message",S=>{this.emit("custom-message",S)})),this.networkQuality||(this.networkQuality=new Q8({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Q8.EVENT_NETWORK_QUALITY,S=>{var L;this.emit("network-quality",S),(L=this.singlePC)==null||L.detectTCPAndUDP(S)})),gd(this,this.signalChannel).add(Yj,S=>{F.emit(rA.SIGNAL_CONNECTION_STATE_CHANGED,Di({room:this},S)),this.emit("signal-connection-state-changed",S)}).add(LoA,S=>{this.reset(),this.emit("error",S)}).add(Qn.PEER_JOIN,S=>{let{srcTinyId:L,userId:V,role:H,fromType:lA}=S.data.data;this.userManager.addUser({userId:V,tinyId:L,role:H,fromType:lA})}).add(Qn.PEER_LEAVE,S=>{let{userId:L,reason:V=0}=S.data.data;this.userManager.deleteUser(L,V)}).add(Qn.UPDATE_REMOTE_MUTE_STAT,S=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(S.data)}).add(Qn.CLIENT_BANNED,S=>{let L=S.data.data,{reason:V}=L;if(ds.uploadEvent({log:"stat-banned:".concat(V),userId:this.userId}),V==="user_time_out")return this._log.warn("".concat(V," last heart beat time: ").concat(this._lastHeartBeatTime," interval: ").concat(Date.now()-this._lastHeartBeatTime,", visibility: ").concat(document.visibilityState)),void this.reJoin();this._log[V==="kick"?"error":"info"]("user was banned because of [".concat(V,"]")),this.reset(),this.emit("banned",{reason:V})}).add(Qn.SEND_SWITCH_ROOM_SUBED_REQ,S=>{if(!this.singlePC)return;let{subList:L}=S.data.data;this._log.info("auto subscribe ".concat(Xd(L,{keysToInclude:["userId"]}))),L.forEach(V=>{this.singlePC.autoSubscribedUserMap.set(V.userId,V)}),this.resolveSwitchRoomSubedReq()}).add(Qn.FALLBACK_CODEC,S=>XA(this,null,function*(){var L,V,H,lA,hA;let MA=S.data.data;((L=MA.videoControlInfo)==null?void 0:L.enableH265Enc)===0&&((V=this.singlePC)==null?void 0:V.videoCodec)==="h265"&&(this._log.warn("fallback codec enableH265Enc: ".concat((H=MA.videoControlInfo)==null?void 0:H.enableH265Enc)),ri.addCount({key:513e3}),yield(lA=this.singlePC)==null?void 0:lA.switchVideoEncoder("h264"),yield(hA=this.uplinkConnection)==null?void 0:hA.sendMediaSettings())})),this.signalChannel.once(s8,S=>{this.tinyId=S.signalInfo.tinyId,F.emit(rA.JOIN_SIGNAL_CONNECTION_END,{room:this})}),F.emit(rA.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),y&&F.emit(rA.JOIN_SIGNAL_CONNECTION_END,{room:this}),y})}setSignalChannel(A){this.signalChannel=A,A||Vs(this)}leave(){return XA(this,null,function*(){var A;try{yield this.doHeartbeat()}catch{}this._log.info("leave() => leaving room"),F.emit(rA.LEAVE_SEND_CMD,{room:this}),(A=this.signalChannel)==null||A.send(PoA),this.switchRoomSubedReq=void 0,this._changeBigSmallRecords.clear()})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(A=>{this.closeDownLinkConnection(A.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=kr.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),kr.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return XA(this,null,function*(){var A;let t=this.badCaseDetector.getMonitorFreeze(),o=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:t});this.badCaseDetector.resetMonitor();let a=(A=this.signalChannel)!=null&&A.isConnected?function(d){if(f_.has(d)){let h=f_.get(d).map(y=>({uint32_event_id:y.eventId,uint64_date:y.timestamp,str_userid:y.remoteUserId,uint32_param1:y.param1,uint32_param2:y.param2,uint32_video_stream_type:y.streamType}));return f_.delete(d),h}return[]}(this.userId):[],l=So(Di({str_sdk_version:l0,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:a,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},o),{msg_device_info:Di({uint32_terminal_type:15,str_device_name:lQ(),str_os_version:"",uint32_net_type:$f()},o.msg_device_info)});if(this.heartbeatReport=l,this.heartbeatCount++,F.emit(rA.HEARTBEAT_REPORT,{room:this,report:l}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(xoA,l);let d=Date.now();this._lastHeartBeatTime>0&&d-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(d-this._lastHeartBeatTime)),this._lastHeartBeatTime=d,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",So(Di({},l),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(A){if(!this.isJoined)return;let t=!1,o=A.data.userList||[],a=A.data.mixRobotList||[],l=[];for(let h of o){if(h.flag===Ob)continue;let{userId:y,srcTinyId:S,flag:L,fromType:V}=h;y===this.userId&&(t=!0,this.uplinkConnection&&(this.uplinkConnection.flag=L),this.localPublishFlag!==L&&(this.localPublishFlag=L,this.emit("local-publish-flag-changed",L))),l.push({userId:y,tinyId:S,flag:L,fromType:V})}let d=[...a.map(h=>{let{userId:y,srcTinyId:S,flag:L,mixUserList:V,fromType:H}=h;return{userId:y,tinyId:S,flag:L,isRobot:!0,mixUserList:V,fromType:H}}),...l];d.forEach(h=>{let{userId:y}=h,S=this.remotePublishedUserMap.get(y);S&&this.checkSubscribeBigSmallVideo(S)}),A.data.fakeMixUser&&(A.data.fakeMixUser.tinyId=A.data.fakeMixUser.srcTinyId,d.push(A.data.fakeMixUser)),F.emit(rA.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:d}),t||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),this.userManager.setRemotePublishedUserList(d)}closeUplink(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish().catch(()=>{}),this.uplinkConnection.close(A),A==="you exitRoom"&&(this.uplinkConnection.destroy(),this.uplinkConnection=null),this.uplinkConnection instanceof H1&&(this.uplinkConnection=null)),this.localTracks.forEach(t=>t.unpublish()),this.localTracks.clear()}createDownlinkConnection(A){let{userId:t,tinyId:o,flag:a,isRobot:l,fromType:d}=A,h=new(this.singlePC?LnA:h8)({userId:t,tinyId:o,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:a,isRobot:l,fromType:d});this.userManager.addRemotePublishedUser(h),this.installDownlinkEvents(h,t),this.emit("remote-published",h)}closeDownLinkConnection(A){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"remote user unpublished",o=this.remotePublishedUserMap.get(A);o&&(o.close(t),this.emit("remote-unpublished",o))}installDownlinkEvents(A,t){A.on("error",o=>{let a=o.getCode();a!==mt.ICE_TRANSPORT_ERROR&&(a===mt.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(t),this.emit("error",o))}),A.on("connection-state-changed",o=>{this.emit("media-connection-state-changed",So(Di({},o),{userId:A.userId}))})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=kr.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){kr.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(A=>{this.userManager.setUserList(A)}).catch(A=>{this._log.debug("sync user list failed: ".concat(A))})}getUserList(){var A;return(A=this.signalChannel)!=null&&A.isConnected?this.signalChannel.sendWaitForResponse({command:ZoA,responseCommand:Qn.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(t=>{let{data:o}=t,{code:a,message:l}=o;if(a===0)return(o.data&&o.data.userList||[]).map(d=>{let{userId:h,srcTinyId:y,role:S,fromType:L}=d;return{userId:h,tinyId:y,role:S,fromType:L}});throw sn({key:Go.SIGNAL_RESPONSE_FAILED,data:{signalResponse:Qn.USER_LIST_RES,code:a,message:l}})}):Promise.reject("not connected")}getAllConnections(){let A=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&A.push(this.uplinkConnection),A}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!d8)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let A=this.getAllConnections();if(A.length===0)return!1;for(let t=0;t{if(t instanceof am&&!t.getIsReconnecting()){let o=t.getPeerConnection();o&&o.connectionState===mo.CLOSED&&(this._log.warn("[".concat(t.getUserId(),"] pc is closed but not reconnect")),t.startReconnection())}})}fallbackToMPC(){return XA(this,null,function*(){var A;if(this._log.warn("fallback to multi pc"),ds.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(A=this.singlePC)==null||A.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let t=this.uplinkConnection;this.uplinkConnection=new H1({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),t.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localMainAudioTrack,localVideoTrack:t.localMainVideoTrack,isAuxiliary:!1})),t.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:t.localAuxAudioTrack,localVideoTrack:t.localAuxVideoTrack,isAuxiliary:!0})),t.close()}for(let t of[...this.remotePublishedUserMap.values()]){let o=new h8({userId:t.userId,tinyId:t.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:t.flag,remoteAudioTrack:t.remoteAudioTrack,remoteVideoTrack:t.remoteVideoTrack,remoteAuxiliaryTrack:t.remoteAuxiliaryTrack});this.installDownlinkEvents(o,t.userId),this.remotePublishedUserMap.set(t.userId,o),t.isMainStreamSubscribed&&(yield o.subscribe(t.subscribeState,"main")),t.isAuxStreamSubscribed&&(yield o.subscribe(t.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new li({code:mt.INVALID_OPERATION,message:sn({key:Go.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.firewallDetector.destroy(),this.removeAllListeners(),this.healthDetector.destroy(),kr.clearTask(this._audioVolumeIntervalId))}switchRole(A){return XA(this,null,function*(){this.role!==A&&(A==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(A))})}doSwitchRole(A){let t={command:XoA,data:{role:A==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:Qn.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(t.data))),this.signalChannel.sendWaitForResponseWithRetry(t).then(o=>{let{code:a,message:l}=o.data;if(a!==0)throw new li({code:mt.SWITCH_ROLE_FAILED,message:sn({key:Go.SWITCH_ROLE_FAILED,data:{message:l,code:a}})});this.role=A}).catch(o=>{throw o instanceof li&&o.getCode()===mt.API_CALL_TIMEOUT&&(o=new li({code:mt.SWITCH_ROLE_FAILED,message:sn({key:Go.SWITCH_ROLE_TIMEOUT})})),this._log.error(o),o})}subscribeDataChannel(){return XA(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let A=[...this.remotePublishedUserMap.values()].filter(t=>t.fromType===D0);this._log.info("subscribeDataChannel",A.map(t=>t.userId)),yield Promise.all(A.map(t=>XA(this,null,function*(){try{yield t.subscribe(So(Di({},t.subscribeState),{datachannel:!0}),"main")}catch(o){this._log.error("subscribeDataChannel failed:",t.userId,o)}})))})}unsubscribeDataChannel(){return XA(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let A=[...this.remotePublishedUserMap.values()].filter(t=>t.fromType===D0);this._log.info("unsubscribeDataChannel",A.map(t=>t.userId)),yield Promise.all(A.map(t=>t.unsubscribeDataChannel()))})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new k8({userId:this.userId,tinyId:this.tinyId,room:this}):new H1({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",A=>{this.emit("media-connection-state-changed",So(Di({},A),{userId:this.userId}))}),this.uplinkConnection.on("error",A=>{let t=A.getCode();t!==mt.ICE_TRANSPORT_ERROR&&(t===mt.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",A))})}publish(A){return XA(this,null,function*(){var t;this.uplinkConnection||this._initUplinkConnection();let o="".concat(A.streamType," ").concat(A.isAudio&&A.isScreen?"screen":"").concat(A.kind);this._log.info("publish() => ".concat(o)),yield(t=this.singlePC)==null?void 0:t.waitForPeerConnectionConnected(),yield this.uplinkConnection.publish({localAudioTrack:A instanceof AM?A:null,localVideoTrack:A instanceof QQ?A:null,isAuxiliary:A.streamType==="auxiliary"})})}unpublish(A){return XA(this,null,function*(){if((this.scene!=="live"||this.role==="anchor")&&(this.isMainStreamPublished||this.isAuxStreamPublished)&&this.uplinkConnection){try{let t="".concat(A.streamType," ").concat(A.isAudio&&A.isScreen?"screen":"").concat(A.kind);this._log.info("unpublish() => ".concat(t)),yield this.uplinkConnection.unpublish({localAudioTrack:A instanceof AM?A:null,localVideoTrack:A instanceof QQ?A:null})}catch{}this.localTracks.size===0&&this.closeUplink("you unpublished")}})}addTrack(A){if(!this.uplinkConnection||!A.mediaTrack)return Promise.resolve();let t=this.uplinkConnection.addTrack(A);return A.publish(this,t),t}removeTrack(A){return this.uplinkConnection&&A.mediaTrack?(A.unpublish(),this.uplinkConnection.removeTrack(A)):Promise.resolve()}replaceTrack(A){return this.uplinkConnection&&A.mediaTrack&&X2()?this.uplinkConnection.replaceTrack(A).then(t=>{t&&F.emit(rA.LOCAL_TRACK_REPLACED,{track:A})}):Promise.resolve()}setBandWidth(A){return XA(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(A),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(A){return XA(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();A&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:JA.VIDEO,videoType:JA.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(A)})}subscribe(){for(var A=arguments.length,t=new Array(A),o=0;o!h.isSubscribed),t.length===0)return;let{userId:a}=t[0],l=this.remotePublishedUserMap.get(a);if(!l)return;let d=t.find(h=>h.mediaType===2)?"auxiliary":"main";try{let h=Di({},l.subscribeState);t.forEach(S=>{switch(S.mediaType){case 1:h.audio=!0;break;case 4:h.video=!0;break;case 8:h.smallVideo=!0;break;case 2:h.auxiliary=!0}});let y=this._changeBigSmallRecords.get(a);y&&y.options.smallVideo&&l.muteState.hasSmall&&h.video&&(h.video=!1,h.smallVideo=!0),F.emit(rA.SUBSCRIBE_START,{room:this,streamType:d,remotePublishedUser:l,subscribeState:h}),this._log.info("subscribe() => ".concat(a," ").concat(d," ").concat(t.map(S=>S.strMediaType).join(",")," [").concat(Kj(h),"] prev: [").concat(Kj(l.subscribeState),"]")),yield l.subscribe(h,d),this._log.info("subscribe ".concat(a," ").concat(d," done"));for(let S of t)S.mediaTrack||(yield S.waitHasMediaTrack());F.emit(rA.SUBSCRIBE_SUCCESS,{room:this,streamType:d,remotePublishedUser:l})}catch(h){let y=h instanceof li?h.getCode():mt.UNKNOWN,S=h;throw h instanceof li?y===mt.REMOTE_STREAM_NOT_EXIST&&(S=new li({code:mt.API_CALL_ABORTED,message:sn({key:Go.API_CALL_ABORTED,data:{message:h.message,userId:a,streamType:d}})}),this._log.warn(S)):(S=new li({code:y,message:sn({key:Go.SUBSCRIBE_FAILED,data:{message:h.message,userId:a,streamType:d}})}),this._log.error(S)),S}})}unsubscribe(){for(var A=arguments.length,t=new Array(A),o=0;oh.mediaType===2)?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(a," ").concat(d," ").concat(t.map(h=>h.strMediaType).join(",")));try{yield l.unsubscribe({remoteTracks:t,streamType:d})}catch(h){this._log.warn("unsubscribe() => failed ".concat(h))}t.forEach(h=>{h.unsubscribe(),h.mediaType===8&&h.setMediaType(4)}),F.emit(rA.UNSUBSCRIBE_SUCCESS,{room:this,streamType:d,remotePublishedUser:l})})}setEncodedDataProcessingListener(A){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3,t=arguments.length>1?arguments[1]:void 0;if(A<=0)return this._enableAudioVolumeEvaluation=!1,void kr.clearTask(this._audioVolumeIntervalId);A=Math.floor(Math.max(A,100)),F.emit(rA.AUDIO_LEVEL_INTERVAL,{interval:A}),this._audioVolumeIntervalId&&kr.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=kr.run("intervalInWorker",()=>{var o;g1.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(A,t);let a=[];(o=this.remotePublishedUserMap)==null||o.forEach(l=>{if(l.muteState.hasAudio){!g1.isRunning&&l.muteState.audioAvailable&&l.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(l):l.remoteAudioTrack.volume=0;let d=Math.floor(100*l.remoteAudioTrack.getAudioLevel());a.push({userId:l.userId,volume:d,floatVolume:l.remoteAudioTrack.getInternalAudioLevel()})}}),this.emit("audio-volume",a)},{delay:A,backgroundTask:t})}updateAudioLevelFromSenderStat(A,t){return XA(this,null,function*(){var o;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let a=(o=this.uplinkConnection.getPeerConnection())==null?void 0:o.getSenders()[0];if(!a)return;let l=Math.max(A,500);this._log.warn("updateAudioLevelFromSenderStat ".concat(l)),this._updateAudioLevelTaskId=kr.run("intervalInWorker",()=>XA(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack)return void this.stopUpdateAudioLevelFromSenderStat();let d=yield a.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:h}=this.uplinkConnection;d.forEach(y=>{y.type==="media-source"&&y.audioLevel&&(h.volume=y.audioLevel)})}),{delay:l,backgroundTask:t})})}stopUpdateAudioLevelFromSenderStat(){var A;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),kr.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(A=this.uplinkConnection)!=null&&A.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(A){var t;let{audioReceiver:o}=A;if(!Xk||!o)return;let a=(t=o.getSynchronizationSources()[0])==null?void 0:t.audioLevel;Ys(a)?A.remoteAudioTrack.volume=Math.min(2*a,1):o.getStats().then(l=>{l.forEach(d=>{d.type==="inbound-rtp"&&Ys(d.audioLevel)&&(A.remoteAudioTrack.volume=d.audioLevel)})})}getLocalAudioStats(){return XA(this,null,function*(){var A;let t={};return t[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(A=this.uplinkConnection)!=null&&A.localMainAudioTrack&&(t[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),t})}getLocalVideoStats(){return XA(this,null,function*(){var A,t;let o={};return o[this.userId]=((t=(A=this.uplinkConnection)==null?void 0:A.localMainVideoTrack)==null?void 0:t.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},o})}getTransportStats(){return XA(this,null,function*(){let A={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let t=yield this._stats.getSenderStats(this.uplinkConnection);A.rtt=t.rtt}for(let[,t]of this.remotePublishedUserMap){let o=yield this._stats.getReceiverStats(t);A.downlinksRTT[o.userId]=o.rtt}return A})}getRemoteVideoStats(A){return XA(this,null,function*(){let t={};for(let[o,a]of this.remotePublishedUserMap)A==="main"&&a.muteState.hasVideo&&(t[o]=a.remoteVideoTrack.stat),A==="auxiliary"&&a.muteState.hasAuxiliary&&(t[o]=a.remoteAuxiliaryTrack.stat);return t})}getRemoteAudioStats(){return XA(this,null,function*(){let A={};for(let[t,o]of this.remotePublishedUserMap)o.muteState.hasAudio&&(A[t]=o.remoteAudioTrack.stat);return A})}setTurnServer(A,t){this._log.info("set turn server: ".concat(JSON.stringify(A)," ").concat(t||""));let o=[];Array.isArray(A)?A.forEach(a=>o.push(Kd.getTurnServer(a))):Kd.isPlainObject(A)&&o.push(Kd.getTurnServer(A)),this._turnServers=o,t&&(this._iceTransportPolicy=t)}sendStartMixTranscode(A){return this.signalChannel.sendWaitForResponse({command:qoA,data:A,timeout:5e3,responseCommand:Qn.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(t=>{if(t.code!==mt.API_CALL_ABORTED)throw t})}sendStopMixTranscode(A){return this.signalChannel.sendWaitForResponse({command:KoA,data:A,timeout:5e3,responseCommand:Qn.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(t=>{if(t.code!==mt.API_CALL_ABORTED)throw t})}sendStartPublishCDN(A){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?YoA:HoA,data:A,timeout:5e3,responseCommand:t?Qn.START_PUBLISH_TENCENT_CDN_RES:Qn.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(o=>{if(o.code!==mt.API_CALL_ABORTED)throw o})}sendStopPublishCDN(A){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:t?VoA:JoA,data:A,timeout:5e3,responseCommand:t?Qn.STOP_PUBLISH_TENCENT_CDN_RES:Qn.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(o=>{if(o.code!==mt.API_CALL_ABORTED)throw o})}sendStartPushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:joA,data:A,timeout:5e3,responseCommand:Qn.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(t=>{if(t.code!==mt.API_CALL_ABORTED)throw t})}sendUpdatePushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:WoA,data:A,timeout:5e3,responseCommand:Qn.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(t=>{if(t.code!==mt.API_CALL_ABORTED)throw t})}sendStopPushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:zoA,data:A,timeout:5e3,responseCommand:Qn.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(t=>{if(t.code!==mt.API_CALL_ABORTED)throw t})}sendAbilityStatus(A){var t;(t=this.signalChannel)==null||t.sendWaitForResponse({command:enA,data:A,timeout:5e3,responseCommand:Qn.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(o=>{})}getIceServers(A){var t,o;return this._turnServers.length>0?this._turnServers:(t=this.scheduleResult.iceServers)!=null&&t.length?this.scheduleResult.iceServers:A!=null&&A.length?A:(o=this._iceServersFromJoin)!=null&&o.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let A={mainUrl:"",backupUrl:""},t=Kd.getEnv();return t?(A.mainUrl="wss://".concat(Kd.getTestSignalDomain(t)),A.backupUrl=A.mainUrl):this.proxy_ws?(A.mainUrl=this.proxy_ws,A.backupUrl=A.mainUrl):this.proxy_unified?(A.mainUrl="wss://".concat(this.proxy_unified),A.backupUrl=A.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(A.mainUrl="wss://".concat(this.scheduleResult.domains[0]),A.backupUrl=A.mainUrl,this.scheduleResult.domains[1]&&(A.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),A}getSignalInfo(){var A;return((A=this.signalChannel)==null?void 0:A.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(A&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this.localPublishFlag=0,this.heartbeatCount=0,this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null},this.clearPrelinkTimeout(),this.prelinkPromise=null}prelink(A,t,o,a,l,d){return XA(this,null,function*(){var h;if(this.isJoined)throw new li({code:mt.INVALID_OPERATION,message:"already joined room"});if(!l&&!d)throw new li({code:mt.INVALID_OPERATION,message:"roomId or strRoomId is required"});if((h=this.signalChannel)!=null&&h.prelink){if(this.signalChannel.isConnecting)return void this._log.warn("prelink is connecting, please wait");if(this.signalChannel.isConnected)return void this._log.warn("prelink is already connected")}return this.userId=t,this.sdkAppId=A,this.userSig=o,this.roomId=String(l||d),this.useStringRoomId=!(!d||l),this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.prelinkPromise=Promise.race([this.doPrelink(A,t,o,a,l,d),new Promise((y,S)=>{this.prelinkTimeoutId=setTimeout(()=>{S(new li({code:mt.INVALID_OPERATION,message:"prelink timeout after ".concat(this.PRELINK_TIMEOUT,"ms")}))},this.PRELINK_TIMEOUT)})]).then(()=>{this.clearPrelinkTimeout()}).catch(y=>{throw this.clearPrelinkTimeout(),this.closePrelink().catch(()=>{}),y}),this.prelinkPromise})}doPrelink(A,t,o,a,l,d){return XA(this,null,function*(){var h,y,S;try{if(!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Kd.getEnv()&&(yield this.schedule({sdkAppId:A,userId:t,userSig:o,roomId:l,strRoomId:d,role:20,privateMapKey:null,businessInfo:null,streamId:null,userDefineRecordId:null},a)),(h=this.scheduleResult.config)==null||!h.prelink)throw new li({code:mt.INVALID_OPERATION,message:"prelink failed: your sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it."});yield this.initialize({isPrelink:!0}),(y=this.signalChannel)==null||y.markPrelinkConnected({sdkAppId:A,userId:t,userSig:o}),(S=this.signalChannel)==null||S.stopPrelinkIn(this.PRELINK_EXPIRED_TIME/1e3),this._log.info("prelink success")}catch(L){throw this._log.error("prelink failed",L),L}})}clearPrelinkTimeout(){this.prelinkTimeoutId&&(clearTimeout(this.prelinkTimeoutId),this.prelinkTimeoutId=null)}closePrelink(){return XA(this,null,function*(){var A;if(this.isJoined)throw new li({code:mt.INVALID_OPERATION,message:"close prelink failed: has joined room"});if((A=this.signalChannel)!=null&&A.prelink){if(this.signalChannel.keepAlive)return void this._log.info("skip close prelink: use keepAlive");this.reset()}})}checkSubscribeBigSmallVideo(A){return XA(this,null,function*(){let{subscribeState:t,userId:o,muteState:{hasSmall:a,hasVideo:l}}=A;if(!a&&!l||!t.video&&!t.smallVideo)return;let d=this._changeBigSmallRecords.get(o);if(!d||d.isSubscribing||d.reSubscribeCount<=0)return;let{options:h,reSubscribeCount:y}=d;if(h.video&&t.video||h.smallVideo&&t.smallVideo&&a)return;let S={audio:A.remoteAudioTrack.isSubscribed||A.remoteAudioTrack.isSubscribing,auxiliary:A.remoteAuxiliaryTrack.isSubscribed||A.remoteAuxiliaryTrack.isSubscribing,video:h.video,smallVideo:h.smallVideo,datachannel:A.subscribeState.datachannel};try{if(!a&&S.smallVideo&&(S.video=!0,S.smallVideo=!1),S.smallVideo===t.smallVideo&&S.video===t.video)return;d.isSubscribing=!0,d.reSubscribeCount=y-1,yield A.subscribe(S,"main"),A.remoteVideoTrack.setMediaType(S.smallVideo?8:4),this._log.info("change [".concat(o,"] to ").concat(S.smallVideo?"small":"big"," video successfully. count ").concat(rv-d.reSubscribeCount,".")),d.isSubscribing=!1,d.reSubscribeCount=rv}catch(L){this._log.info("change [".concat(o,"] to ").concat(S.smallVideo?"small":"big"," video failed. count ").concat(rv-d.reSubscribeCount,". reason: ").concat(L)),d.isSubscribing=!1,d.reSubscribeCount===0&&this._changeBigSmallRecords.delete(o)}})}changeType(A,t){let o={options:{video:!A,smallVideo:A},isSubscribing:!1,reSubscribeCount:rv};this._changeBigSmallRecords.set(t.userId,o),this._log.info("set [".concat(t.userId,"] video prefer type: ").concat(A?"small":"big")),this.emit("subscribe-small-video-changed",{userId:t.userId,isSmall:A});let a=this.remotePublishedUserMap.get(t.userId);a&&this.checkSubscribeBigSmallVideo(a)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(A){this._businessInfo=A.businessInfo;let t={};if(F8(A.businessInfo)&&(t=JSON.parse(A.businessInfo)),!gM(A.pureAudioPushMode)){if(!Number.isInteger(Number(A.pureAudioPushMode)))throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_PURE_AUDIO})});this._pureAudioPushMode=A.pureAudioPushMode,t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!gM(A.userDefineRecordId)){let o=/^[A-Za-z0-9_-]{1,64}$/gi;if(A.userDefineRecordId.match(o)===null)throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_USER_DEFINE_RECORDID})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_record_id=A.userDefineRecordId}if(!gM(A.userDefinePushArgs)){if(!(F8(A.userDefinePushArgs)&&String(A.userDefinePushArgs)&&String(A.userDefinePushArgs).length<=256))throw new li({code:mt.INVALID_PARAMETER,message:sn({key:Go.INVALID_USER_DEFINE_PUSH_ARGS})});t.Str_uc_params||(t.Str_uc_params={}),t.Str_uc_params.userdefine_push_args=A.userDefinePushArgs}PnA(t)||(this._businessInfo=JSON.stringify(t))}sendCustomMessage(A){var t;(t=this._customMessageManager)==null||t.send(A)}enableInsertableStreams(){return XA(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&$p)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(A){var t;return this.signalChannel?(t=this.signalChannel)==null?void 0:t.sendWaitForResponseWithRetry(A):Promise.reject(new li({code:mt.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var A;return(A=this.singlePC)==null?void 0:A.scriptTransformWorker}switchRoom(A){return XA(this,null,function*(){var t;if(!this.signalChannel||!this.singlePC)return;let{roomId:o,strRoomId:a,userSig:l,privateMapKey:d}=A,h=((t=this.scheduleResult.config)==null?void 0:t.autoSubscribeCount)||A?.autoSubscribeCount||1,y=String(this.useStringRoomId?a:o),S=[];for(let lA=0;lA{this.resolveSwitchRoomSubedReq=lA,OC(5e3).then(lA)}),F.emit(rA.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();try{this.userManager.clear(),V=yield this.signalChannel.sendWaitForResponse({command:onA,responseCommand:Qn.SEND_SWITCH_ROOM_RES,data:L});let{code:lA,message:hA}=V.data;if(lA!==0){this._log.error("switch room failed. result: ".concat(lA," error: ").concat(hA));let MA=new li({code:mt.SWITCH_ROOM_FAILED,extraCode:lA,message:hA});throw F.emit(rA.SWITCH_ROOM_FAILED,{room:this,error:MA}),MA}this.userSig=l,gM(d)||(this.privateMapKey=d),F.emit(rA.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:H,targetRoomId:y})}catch(lA){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=H,this.resolveSwitchRoomSubedReq(),lA}})}isSwitchRoomSupported(){var A;let t="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((A=this.scheduleResult.config)==null?void 0:A.switchRoom)!==!0?(this._log.warn("".concat(t," Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.")),!1):this.scene!=="live"?(this._log.warn("".concat(t," Reason: the scene is not 'live'.")),!1):this.role!=="audience"?(this._log.warn("".concat(t," Reason: the role is not 'audience'.")),!1):!!this.singlePC||(this._log.warn("".concat(t," Reason: is not using single peerConnection.")),!1)}requestRemoteFallbackToH264(){var A;(A=this.singlePC)==null||A.requestRemoteFallbackToH264()}startUpdateNTPTime(){if(!this.signalChannel)return;let A=[];for(let t=0;t<5;t++)A.push(this.updateNTPTime());return Promise.all(A).then(t=>{var o;let a=t[0].offset,l=t[0].offset;t.forEach(y=>{a=Math.min(y.offset,a),l=Math.max(y.offset,l)});let d=Math.floor(t.reduce((y,S)=>y+S.rtt,0)/t.length),h=Math.floor(t.reduce((y,S)=>y+S.offset,0)/t.length);(l-a>30||d>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),ZB(h),(o=this.scriptTransformWorker)==null||o.postMessage({type:"ntp-offset",data:h}),this._log.debug("ntp updated offset: ".concat(h)),this.emit("ntp-time-updated")}).catch(t=>{this._log.warn("ntp updated failed: ".concat(t))})}updateNTPTime(){let A=Date.now();return this.signalChannel.sendWaitForResponse({command:nnA,responseCommand:Qn.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(A)},enableLog:!1}).then(t=>{let o=Number(t.data.data.serverSendTime),a=Number(t.data.data.serverRecvTime),l=t.data.receiveTime||Date.now();return{rtt:l-A-(a-o),offset:(a-A+(o-l))/2}})}};return Qi([hc(["left",gs.INIT],"joined"),iB({settings:{retries:1,timeout:0},onRetrying(A){this._log.warn("join retry ".concat(A))},onRetryFailed(A){this._log.error("join failed",A)},onError(A,t){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),mQ(!0),this.reset(),t()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),t()):(this.reset(),t())}}),Xr(A=>{let t=new GoA;return function(o,a,l){return XA(this,null,function*(){let d=String(o.roomId||o.strRoomId);if(this.userId=o.userId,this.sdkAppId=o.sdkAppId,this.userSig=o.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=a,o.privateMapKey=o.privateMapKey||"",this.isJoined)throw new li({code:mt.INVALID_OPERATION,message:sn({key:Go.INVALID_JOIN})});if(this.checkDestroy(),t.isJoined({userId:this.userId,roomId:d,sdkAppId:this.sdkAppId,room:this}))throw new li({code:mt.INVALID_OPERATION,message:sn({key:Go.REPEAT_JOIN,data:this.userId})});t.add({room:this,roomId:d}),this.role=o.role===21?"audience":"anchor",this._log.info("Join() => joining room: ".concat(d," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),F.emit(rA.JOIN_START,{room:this,roomId:d,params:o});let h=Kd.getEnv();h||(h=XB.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Hf.OLD_CLOUD_LADDER)?h=XB.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Hf.WEBRTC)&&(h=XB.WEBRTC))),ds.setConfig({env:h,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:d}),ge.checkSystemRequirementsInternal(l).then(y=>{this.checkSystemResult=y,boA.call(this)});try{!this.prelinkPromise&&!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Kd.getEnv()&&(yield this.schedule(o,l));let y=yield A.call(this,o,a,l);return this.roomId=d,this._joinedTimestamp=Kd.performanceNow(),F.emit(rA.JOIN_SUCCESS,{room:this}),l===30&&!o.component&&ds.uploadEvent({log:"stat-conv-".concat(Number(Jp),"-").concat(location.hostname),userId:this.userId}),y}catch(y){throw t.delete({room:this,roomId:d}),F.emit(rA.JOIN_FAILED,{room:this,error:y}),y}})}})],Ly.prototype,"join"),Qi([hc("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Xr(A=>function(){for(var t=arguments.length,o=new Array(t),a=0;aA.mediaType),Xr(A=>function(){for(var t=arguments.length,o=new Array(t),a=0;ad.outMediaTrack&&d.state==="ready"),!o.length))return;F.emit("61",{room:this});let l=A.apply(this,o);return Promise.all(o.map(d=>d.publish(this,l)))})}),iB({settings:{retries:jf,timeout:A=>bp(A)},onError(A,t,o,a){let[l]=a;var d;(d=A.message)!=null&&d.includes("timeout")?(this._log.warn("publish ".concat(l.strMediaType," timeout"),A),t()):(this._log.error("publish ".concat(l.strMediaType," failed: ").concat(A)),o(A),F.emit(rA.PUBLISH_FAILED,{room:this}))}})],Ly.prototype,"publish"),Qi([d_({fnName:"publish"}),Ry(A=>A.mediaType),Xr(A=>function(){for(var t=arguments.length,o=new Array(t),a=0;ad.unpublish()),l}),Xv(function(){var A,t;this.localTracks.size===0&&xI()&&((t=(A=this.singlePC)==null?void 0:A.getPeerConnection())==null||t.getSenders().forEach(o=>o.track&&o.replaceTrack(null)))})],Ly.prototype,"unpublish"),Qi([V5(A=>{if(A.code!==mt.API_CALL_ABORTED)throw A}),Ry(A=>A.userId)],Ly.prototype,"replaceTrack"),Qi([Ry(function(){for(var A=arguments.length,t=new Array(A),o=0;ofunction(){for(var t=arguments.length,o=new Array(t),a=0;a!d.isSubscribed&&d.subscribe(l)),l}),iB({settings:{retries:jf,timeout:A=>bp(A)},onError(A,t,o,a){if(A.message.includes("timeout"))this._log.warn("subscribe timeout"),t();else{let l=A?.code===mt.API_CALL_ABORTED;this._log[l?"warn":"error"]("subscribe failed ".concat(a.map(d=>d.strMediaType).join(","),": ").concat(A)),o(A),F.emit(rA.SUBSCRIBE_FAILED,{room:this,remoteTracks:a})}}})],Ly.prototype,"subscribe"),Qi([d_({fnName:"subscribe",callback(){for(var A=arguments.length,t=new Array(A),o=0;o{let l=this.remotePublishedUserMap.get(a.userId);l&&!l.isMainStreamSubscribed&&!l.isAuxStreamSubscribed&&l.close("you unsubscribed")})}}),Ry(function(){for(var A=arguments.length,t=new Array(A),o=0;oi in e?FV(e,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[i]=n,LaA=(e,i)=>{for(var n in i||(i={}))_X.call(i,n)&&EW(e,n,i[n]);if(NZ)for(var n of NZ(i))kaA.call(i,n)&&EW(e,n,i[n]);return e},UaA=(e,i)=>function(){return i||(0,e[wX(e)[0]])((i={exports:{}}).exports,i),i.exports},FaA=(e,i,n,c)=>{if(i&&typeof i=="object"||typeof i=="function")for(let I of wX(i))_X.call(e,I)||I===n||FV(e,I,{get:()=>i[I],enumerable:!(c=RX(i,I))||c.enumerable});return e},OaA=(e,i,n)=>(n=e!=null?GaA(baA(e)):{},FaA(FV(n,"default",{value:e,enumerable:!0}),e)),z_=(e,i,n,c)=>{for(var I,C=RX(i,n),m=e.length-1;m>=0;m--)(I=e[m])&&(C=I(i,n,C)||C);return C&&FV(i,n,C),C},Ms=(e,i,n)=>EW(e,typeof i!="symbol"?i+"":i,n),PaA=UaA({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(e,i){var n=Object.prototype.hasOwnProperty,c="~";function I(){}function C(T,b,J){this.fn=T,this.context=b,this.once=J||!1}function m(T,b,J,gA,eA){if(typeof J!="function")throw new TypeError("The listener must be a function");var CA=new C(J,gA||T,eA),IA=c?c+b:b;return T._events[IA]?T._events[IA].fn?T._events[IA]=[T._events[IA],CA]:T._events[IA].push(CA):(T._events[IA]=CA,T._eventsCount++),T}function R(T,b){--T._eventsCount===0?T._events=new I:delete T._events[b]}function _(){this._events=new I,this._eventsCount=0}Object.create&&(I.prototype=Object.create(null),new I().__proto__||(c=!1)),_.prototype.eventNames=function(){var T,b,J=[];if(this._eventsCount===0)return J;for(b in T=this._events)n.call(T,b)&&J.push(c?b.slice(1):b);return Object.getOwnPropertySymbols?J.concat(Object.getOwnPropertySymbols(T)):J},_.prototype.listeners=function(T){var b=c?c+T:T,J=this._events[b];if(!J)return[];if(J.fn)return[J.fn];for(var gA=0,eA=J.length,CA=new Array(eA);gA{if(!navigator.userAgent.includes("Firefox"))return e;const i=e.split(`\r `),n=[],c=[];i.forEach(m=>{const R=m.toLowerCase();R.includes("a=rtpmap")&&R.includes("h264")&&n.push(m)}),n.length>1&&c.push(...n.slice(1));const I=c.map(m=>{const R=/a=rtpmap:(\d+)\s/.exec(m);return R&&R.length>1?R[1]:null}).filter(m=>m!==null),C=[];return i.forEach(m=>{let R=m;if(m.includes("a=setup")&&(R="a=setup:passive"),(m.includes("m=audio")||m.includes("m=video"))&&(R=m.split(" ").filter((_,T)=>T<3||!I.includes(_)).join(" ")),m.includes("a=fmtp")||m.includes("a=rtcp-fb")||m.includes("a=rtpmap")){const _=/a=(?:fmtp|rtcp-fb|rtpmap):(\d+)\s/.exec(m);if(_&&_.length>1&&I.includes(_[1]))return}C.push(R)}),C.join(`\r `)},GZ=e=>{const i=e.split(`\r `),n=[];i.forEach(m=>{const R=m.toLowerCase();R.includes("a=rtpmap")&&R.includes("h264")&&n.push(m)});const c=n.map(m=>{const R=/a=rtpmap:(\d+)\s/.exec(m);return R&&R.length>1?R[1]:null}).filter(m=>m!==null),I=[];i.forEach(m=>{let R=m;if(m.includes("a=fmtp:111")&&(R=`${m};stereo=1`),m.includes("a=fmtp")){const _=/a=fmtp:(\d+)\s/.exec(m);_&&_.length>1&&c.includes(_[1])&&(R=`${m};sps-pps-idr-in-keyframe=1`)}I.push(R)});const C=I.join(`\r -`);return YaA(C)},VaA="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",l3=(e=21)=>{let i="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)i+=VaA[63&n[e]];return i},x_=e=>typeof e=="function",HaA=0,JaA=1,bZ=2;function qaA({retryFunction:e,settings:i,onError:n,onRetrying:c,onRetryFailed:I,onRetrySuccess:C,context:m}){return function(...R){const{retries:_=5,timeout:T=1e3}=i;let b=0,J=-1,cA=HaA;const eA=async(CA,IA)=>{const oA=m||this;try{const vA=await e.apply(oA,R);b>0&&C&&C.call(this,b),b=0,CA(vA)}catch(vA){const qA=()=>{clearTimeout(J),b=0,cA=bZ,IA(vA)},Ae=()=>{cA!==bZ&&b<(x_(_)?_():_)?(b++,cA=JaA,x_(c)&&c.call(this,b,qA),J=window.setTimeout(()=>{J=-1,eA(CA,IA)},x_(T)?T(b):T)):(qA(),x_(I)&&I.call(this,vA))};x_(n)?n.call(this,{error:vA,retry:Ae,reject:IA,retryFuncArgs:R,retriedCount:b}):Ae()}};return new Promise(eA)}}var KaA=qaA,DQ=new WeakMap;function jaA({settings:e={retries:5,timeout:2e3},onError:i,onRetrying:n,onRetryFailed:c}){return function(I,C,m){const R=KaA({retryFunction:m.value,settings:e,onError({error:_,retry:T,reject:b,retryFuncArgs:J}){var cA;i?i.call(this,_,()=>{var eA;(eA=DQ.get(I))!=null&&eA.has(C)?T():b(_)},b,J):(cA=DQ.get(I))!=null&&cA.has(C)?T():b(_)},onRetrying(_,T){var b;x_(n)&&n.call(this,_,T),(b=DQ.get(I))!=null&&b.has(C)&&(DQ.get(I).get(C).stopRetry=T)},onRetryFailed:c});return m.value=function(..._){const T=DQ.get(I);return T?T.set(C,{args:_}):DQ.set(I,new Map([[C,{args:_}]])),R.apply(this,_).finally(()=>{var b;return(b=DQ.get(I))==null?void 0:b.delete(C)})},m}}function WaA({fnName:e,callback:i,validateArgs:n=!0}){return function(c,I,C){const m=C.value;return C.value=function(...R){var _,T;if((_=DQ.get(c))!=null&&_.has(e)){const{stopRetry:b,args:J}=DQ.get(c).get(e);let cA=!0;if(n){for(const eA of J)if(!R.find(CA=>CA===eA)){cA=!1;break}}cA&&(i&&i.apply(this,R),b&&b(),(T=DQ.get(c))==null||T.delete(e))}return m.apply(this,R)},C}}var zaA=class{constructor(e,i){this.core=i,Ms(this,"peerConnection"),Ms(this,"audioTransceiver",null),Ms(this,"videoTransceiver",null),Ms(this,"timerId",null),Ms(this,"callback",null),Ms(this,"previousRawStats",null),Ms(this,"_prevReportTime",0),Ms(this,"_prevDecoderImplementation",""),Ms(this,"_decodeMap",new Map),this.peerConnection=e,this.findTransceivers()}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}findTransceivers(){const e=this.peerConnection.getTransceivers();for(const i of e)if(i.receiver&&i.receiver.track){const{track:n}=i.receiver;n.kind==="audio"?this.audioTransceiver=i:n.kind==="video"&&(this.videoTransceiver=i)}}start(e,i=2e3){this.stop(),this.callback=e,this.collectStats(),this.timerId=window.setInterval(()=>{this.collectStats()},i)}stop(){this.timerId!==null&&(clearInterval(this.timerId),this.timerId=null),this.callback=null,this.previousRawStats=null,this._prevReportTime=0}async collectStats(){if(this.callback)try{const e=await this.peerConnection.getStats(),i=new Set(["inbound-rtp","track","candidate-pair","media-source","codec"]),n=[];e.forEach(R=>i.has(R.type)&&n.push(R));const c=Date.now(),I=this.parseAudioStats(n),C=this.parseVideoStats(n),m=this.parseNetworkStats(n);this._prevReportTime=c,this.callback({audio:I,video:C,network:m})}catch(e){this.core.log.error("Failed to collect WebRTC stats:",e)}}getDifferenceValue(e,i){if(this.core.utils.isUndefined(e))return i;const n=(i||0)-e;return n<0?0:n}parseAudioStats(e){var i,n,c,I;const C={bitrate:0,volume:0,packetLossRate:0,jitterBufferDelay:0,bytesReceived:0,packetsReceived:0,packetsLost:0};for(const m of e){if(m.type==="inbound-rtp"&&(m.mediaType==="audio"||m.kind==="audio")){if(C.bytesReceived=m.bytesReceived||0,C.packetsReceived=m.packetsReceived||0,C.packetsLost=m.packetsLost||0,this.previousRawStats&&this.previousRawStats.audio){const T=this.getDifferenceValue(this.previousRawStats.audio.bytesReceived,C.bytesReceived);C.bitrate=Math.round(8*T/this.statInterval/1e3)}const R=this.getDifferenceValue((i=this.previousRawStats)==null?void 0:i.audio.packetsLost,C.packetsLost),_=this.getDifferenceValue((n=this.previousRawStats)==null?void 0:n.audio.packetsReceived,C.packetsReceived)+R;if(_>0&&(C.packetLossRate=Math.round(R/_*100)),this.core.utils.isUndefined(m.audioLevel)||(C.volume=m.audioLevel||0),m.jitterBufferDelay&&m.jitterBufferEmittedCount){let{jitterBufferEmittedCount:T}=m,{jitterBufferDelay:b}=m;(c=this.previousRawStats)!=null&&c.audio&&(T=this.getDifferenceValue(this.previousRawStats.audio.jitterBufferEmittedCount,m.jitterBufferEmittedCount),b=this.getDifferenceValue(this.previousRawStats.audio.jitterBufferDelay,m.jitterBufferDelay)),T>0&&(C.jitterBufferDelay=Math.floor(b/T*1e3)),this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.audio.jitterBufferDelay=m.jitterBufferDelay,this.previousRawStats.audio.jitterBufferEmittedCount=m.jitterBufferEmittedCount}this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.audio.bytesReceived=C.bytesReceived,this.previousRawStats.audio.packetsReceived=C.packetsReceived,this.previousRawStats.audio.packetsLost=C.packetsLost}!this.core.utils.isUndefined(m.audioLevel)&&((I=this.audioTransceiver)!=null&&I.receiver.track)&&m.trackIdentifier===this.audioTransceiver.receiver.track.id&&(C.volume=m.audioLevel||0)}return C}parseVideoStats(e){var i,n,c,I,C;const m={bitrate:0,frameRate:0,width:0,height:0,packetLossRate:0,jitterBufferDelay:0,bytesReceived:0,packetsReceived:0,packetsLost:0,framesDecoded:0};for(const R of e){if(R.type==="codec"&&this._decodeMap.set(R.id,R),R.type==="inbound-rtp"&&(R.mediaType==="video"||R.kind==="video")){if(m.bytesReceived=R.bytesReceived||0,m.packetsReceived=R.packetsReceived||0,m.packetsLost=R.packetsLost||0,m.framesDecoded=R.framesDecoded||0,this.core.utils.isUndefined(R.framesPerSecond)||(m.frameRate=Math.round(R.framesPerSecond)),R.decoderImplementation&&this._prevDecoderImplementation!==R.decoderImplementation){const b=this._decodeMap.get(R.codecId),J=((i=b?.mimeType)==null?void 0:i.split("/")[1])||"unknown",cA=R.powerEfficientDecoder;this.core.log.info(`decoderImplementation change to ${R.decoderImplementation}(${J}) HWDecoder: ${cA}`),this._prevDecoderImplementation=R.decoderImplementation}if(this.previousRawStats&&this.previousRawStats.video){const b=this.getDifferenceValue(this.previousRawStats.video.bytesReceived,m.bytesReceived);m.bitrate=Math.round(8*b/this.statInterval/1e3)}const _=this.getDifferenceValue((n=this.previousRawStats)==null?void 0:n.video.packetsLost,m.packetsLost),T=this.getDifferenceValue((c=this.previousRawStats)==null?void 0:c.video.packetsReceived,m.packetsReceived)+_;if(T>0&&(m.packetLossRate=Math.round(_/T*100)),R.jitterBufferDelay&&R.jitterBufferEmittedCount){let{jitterBufferEmittedCount:b}=R,{jitterBufferDelay:J}=R;(I=this.previousRawStats)!=null&&I.video&&(b=this.getDifferenceValue(this.previousRawStats.video.jitterBufferEmittedCount,R.jitterBufferEmittedCount),J=this.getDifferenceValue(this.previousRawStats.video.jitterBufferDelay,R.jitterBufferDelay)),b>0&&(m.jitterBufferDelay=Math.floor(J/b*1e3)),this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.video.jitterBufferDelay=R.jitterBufferDelay,this.previousRawStats.video.jitterBufferEmittedCount=R.jitterBufferEmittedCount}this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.video.bytesReceived=m.bytesReceived,this.previousRawStats.video.packetsReceived=m.packetsReceived,this.previousRawStats.video.packetsLost=m.packetsLost}!this.core.utils.isUndefined(R.frameWidth)&&((C=this.videoTransceiver)!=null&&C.receiver.track)&&R.trackIdentifier===this.videoTransceiver.receiver.track.id&&(m.width=R.frameWidth,m.height=R.frameHeight)}return m}parseNetworkStats(e){const i={rtt:0};for(const n of e)if(n.type==="candidate-pair"&&(n.selected||n.state==="succeeded")&&this.core.utils.isNumber(n.currentRoundTripTime)){i.rtt=Math.floor(1e3*n.currentRoundTripTime);break}return i}initPreviousRawStats(){this.previousRawStats={timestamp:Date.now(),audio:{bytesReceived:0,packetsReceived:0,packetsLost:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0}}}},ZaA=OaA(PaA()),kZ=Symbol("instance"),$1=Symbol("cacheResult"),I3=class{constructor(i,n,c){this.oldState=i,this.newState=n,this.action=c,this.aborted=!1}abort(i){this.aborted=!0,dU.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},u3=class extends Error{constructor(i,n,c){super(n),this.state=i,this.message=n,this.cause=c}};function XaA(e){return typeof e=="object"&&e&&"then"in e}var EU=new Map;function AY(e,i,n={}){return(c,I,C)=>{const m=n.action||I;if(!n.context){const _=EU.get(c)||[];EU.has(c)||EU.set(c,_),_.push({from:e,to:i,action:m})}const R=C.value;C.value=function(..._){let T=this;if(n.context&&(T=eh.get(typeof n.context=="function"?n.context.call(this,..._):n.context)),T.state===i)return n.sync?T[$1]:Promise.resolve(T[$1]);T.state instanceof I3&&T.state.action==n.abortAction&&T.state.abort(T);let b=null;Array.isArray(e)?e.length==0?T.state instanceof I3&&T.state.abort(T):typeof T.state=="string"&&e.includes(T.state)||(b=new u3(T._state,`${T.name} ${m} to ${i} failed: current state ${T._state} not from ${e.join("|")}`)):e!==T.state&&(b=new u3(T._state,`${T.name} ${m} to ${i} failed: current state ${T._state} not from ${e}`));const J=oA=>{if(n.fail&&n.fail.call(this,oA),n.sync){if(n.ignoreError)return oA;throw oA}return n.ignoreError?Promise.resolve(oA):Promise.reject(oA)};if(b)return J(b);const cA=T.state,eA=new I3(cA,i,m);dU.call(T,eA);const CA=oA=>{var vA;return T[$1]=oA,eA.aborted||(dU.call(T,i),(vA=n.success)===null||vA===void 0||vA.call(this,T[$1])),oA},IA=oA=>(dU.call(T,cA,oA),J(oA));try{const oA=R.apply(this,_);return XaA(oA)?oA.then(CA).catch(IA):n.sync?CA(oA):Promise.resolve(CA(oA))}catch(oA){return IA(new u3(T._state,`${T.name} ${m} from ${e} to ${i} failed: ${oA}`,oA instanceof Error?oA:new Error(String(oA))))}}}}var $aA=typeof window<"u"&&window.__AFSM__?(n,c)=>{window.dispatchEvent(new CustomEvent(n,{detail:c}))}:typeof importScripts<"u"?(n,c)=>{postMessage({type:n,payload:c})}:()=>{};function dU(e,i){const n=this._state;this._state=e;const c=e.toString();e&&this.emit(c,n),this.emit(eh.STATECHANGED,e,n,i),this.updateDevTools({value:e,old:n,err:i instanceof Error?i.message:String(i)})}var eh=class ZC extends ZaA.default{constructor(i,n,c){super(),this.name=i,this.groupName=n,this._state=ZC.INIT,i||(i=Date.now().toString(36)),c?Object.setPrototypeOf(this,c):c=Object.getPrototypeOf(this),n||(this.groupName=this.constructor.name);const I=c[kZ];I?this.name=I.name+"-"+I.count++:c[kZ]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){const i=Object.getPrototypeOf(this),n=EU.get(i)||[];let c=new Set,I=[],C=[];const m=new Set,R=Object.getPrototypeOf(i);EU.has(R)&&(R.stateDiagram.forEach(T=>c.add(T)),R.allStates.forEach(T=>m.add(T))),n.forEach(({from:T,to:b,action:J})=>{typeof T=="string"?I.push({from:T,to:b,action:J}):T.length?T.forEach(cA=>{I.push({from:cA,to:b,action:J})}):C.push({to:b,action:J})}),I.forEach(({from:T,to:b,action:J})=>{m.add(T),m.add(b),m.add(J+"ing"),c.add(`${T} --> ${J}ing : ${J}`),c.add(`${J}ing --> ${b} : ${J} 🟢`),c.add(`${J}ing --> ${T} : ${J} 🔴`)}),C.forEach(({to:T,action:b})=>{c.add(`${b}ing --> ${T} : ${b} 🟢`),m.forEach(J=>{J!==T&&c.add(`${J} --> ${b}ing : ${b}`)})});const _=[...c];return Object.defineProperties(i,{stateDiagram:{value:_},allStates:{value:m}}),_}static get(i){let n;return typeof i=="string"?(n=ZC.instances.get(i),n||ZC.instances.set(i,n=new ZC(i,void 0,Object.create(ZC.prototype)))):(n=ZC.instances2.get(i),n||ZC.instances2.set(i,n=new ZC(i.constructor.name,void 0,Object.create(ZC.prototype)))),n}static getState(i){var n;return(n=ZC.get(i))===null||n===void 0?void 0:n.state}updateDevTools(i={}){$aA(ZC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){dU.call(this,i)}};eh.STATECHANGED="stateChanged",eh.UPDATEAFSM="updateAFSM",eh.INIT="[*]",eh.ON="on",eh.OFF="off",eh.instances=new Map,eh.instances2=new WeakMap;var KL=class extends eh{constructor(i,n){super(),this.core=i,Ms(this,"audioPlayer"),Ms(this,"videoPlayer"),Ms(this,"callback"),Ms(this,"avPlayerStateSyncManager"),Ms(this,"_log"),Ms(this,"_videoPlayerLog"),Ms(this,"_audioPlayerLog"),Ms(this,"lastPausedReason"),Ms(this,"muted",!1),this._log=n,this._videoPlayerLog=this._log.createChild({id:"vp"}),this._audioPlayerLog=this._log.createChild({id:"ap"}),this.videoPlayer=new i.VideoPlayer({id:"vp",log:this._videoPlayerLog,track:null,muted:!1,container:null,enableLogTrackState:!0}),this.audioPlayer=new i.RemoteAudioPlayer({id:"ap",log:this._audioPlayerLog,track:null,muted:!1,container:null,enableVolumeControlInIOS:!0,enableLogTrackState:!0}),this.audioPlayer.on(i.PlayerEvent.AUTOPLAY_FAILED,c=>this.handleAutoPlayFailed(this.audioPlayer,c)),this.videoPlayer.on(i.PlayerEvent.LOAD_START,()=>this.handleLoadStart("video")),this.audioPlayer.on(i.PlayerEvent.LOAD_START,()=>this.handleLoadStart("audio")),this.videoPlayer.on(i.PlayerEvent.PLAYER_STATE_CHANGED,this.handlePlayerStateChanged,this),this.audioPlayer.on(i.PlayerEvent.PLAYER_STATE_CHANGED,this.handlePlayerStateChanged,this),this.videoPlayer.on(i.PlayerEvent.ENTER_PICTURE_IN_PICTURE,this.handleEnterPictureInPicture,this),this.videoPlayer.on(i.PlayerEvent.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePictureInPicture,this),this.videoPlayer.on(i.PlayerEvent.ENTER_FULL_SCREEN,this.handleEnterFullScreen,this),this.videoPlayer.on(i.PlayerEvent.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.avPlayerStateSyncManager=new i.AVPlayerStateSyncManager({log:this._log,audioPlayer:this.audioPlayer,videoPlayer:this.videoPlayer})}get isPlaying(){return this.videoPlayer.isPlaying&&this.audioPlayer.isPlaying}get isPaused(){return this.videoPlayer.isPaused&&this.audioPlayer.isPaused}get isStopped(){return this.videoPlayer.isStopped&&this.audioPlayer.isStopped}setCallback(i){this.callback=i}updateLogConfig(i){this._audioPlayerLog.setSdkAppId(i.sdkAppId),this._audioPlayerLog.setUserId(i.userId),this._videoPlayerLog.setSdkAppId(i.sdkAppId),this._videoPlayerLog.setUserId(i.userId)}handleLoadStart(i){this.onLoadStart()}handlePlayerStateChanged(i){i.state==="PLAYING"&&this.isPlaying&&this.onPlaying(),i.state==="PAUSED"&&this.isPaused&&this.onPaused(i.reason),i.state==="STOPPED"&&this.isStopped&&this.onStopped()}async handleEnterPictureInPicture(){var i,n;await this.videoPlayer.enterPIPPromise,(n=(i=this.callback)==null?void 0:i.onPictureInPictureStateChanged)==null||n.call(i,{isPictureInPicture:!0,pictureInPictureWindow:this.videoPlayer.pipWindow})}handleLeavePictureInPicture(){var i,n;(n=(i=this.callback)==null?void 0:i.onPictureInPictureStateChanged)==null||n.call(i,{isPictureInPicture:!1})}handleEnterFullScreen(){var i,n;(n=(i=this.callback)==null?void 0:i.onFullScreenStateChanged)==null||n.call(i,{isFullScreen:!0})}handleLeaveFullScreen(){var i,n;(n=(i=this.callback)==null?void 0:i.onFullScreenStateChanged)==null||n.call(i,{isFullScreen:!1})}onLoadStart(){}onPlaying(){}onPaused(i){this.lastPausedReason=i}onStopped(){}setVideoContainer(i){if(this.core.utils.isString(i)){const n=document.getElementById(i);n&&this.videoPlayer.setContainer(n)}else this.videoPlayer.setContainer(i)}setVolume(i){this.core.utils.isUndefined(i)||this.audioPlayer.setVolume(i/100)}setMuted(i){this.core.utils.isUndefined(i)||(this.muted=i,this.audioPlayer.setMuted(i))}setFillMode(i){i&&this.videoPlayer.setObjectFit(i)}setAudioTrack(i){this.audioPlayer.setTrack(i)}setVideoTrack(i){this.videoPlayer.setTrack(i)}async play(){const i=this.videoPlayer.play().catch(c=>{this.handleAutoPlayFailed(this.videoPlayer,c,"video")}),n=this.audioPlayer.play().catch(c=>{this.handleAutoPlayFailed(this.audioPlayer,c)});await Promise.all([i,n])}handleAutoPlayFailed(i,n,c="audio"){var I,C;this._log.warn("handleAutoPlayFailed",n);const m=()=>{this.audioPlayer.resume().then(()=>{document.removeEventListener("click",m,!0)})};document.addEventListener("click",m,!0),(C=(I=this.callback)==null?void 0:I.onAutoPlayFailed)==null||C.call(I,{type:c,resume:()=>i.resume()})}pause(){this.videoPlayer.pause(!0),this.audioPlayer.setMuted(!0),this.audioPlayer.pause()}resume(){this.videoPlayer.resume(!0),this.audioPlayer.setMuted(this.muted),this.audioPlayer.resume()}async enterFullscreen(){await this.videoPlayer.enterFullscreen()}async exitFullscreen(){await this.videoPlayer.exitFullscreen()}async enterPictureInPicture(){await this.videoPlayer.enterPictureInPicture()}async exitPictureInPicture(){await this.videoPlayer.exitPictureInPicture()}stop(){this.videoPlayer&&this.videoPlayer.stop(),this.audioPlayer&&(this.audioPlayer.stop(),this.audioPlayer.setMuted(!1))}};z_([AY([eh.INIT,"PAUSED"],"LOADSTART",{ignoreError:!0,sync:!0,success(){var e,i;(i=(e=this.callback)==null?void 0:e.onLoadStart)==null||i.call(e)},fail(e){this._log.warn("onLoadStart",e)}})],KL.prototype,"onLoadStart"),z_([AY(["LOADSTART","PAUSED"],"PLAYING",{ignoreError:!0,sync:!0,success(){var e,i;(i=(e=this.callback)==null?void 0:e.onPlaying)==null||i.call(e)},fail(e){this._log.warn("onPlaying",e)}})],KL.prototype,"onPlaying"),z_([AY("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(){var e,i;(i=(e=this.callback)==null?void 0:e.onPaused)==null||i.call(e,{reason:this.lastPausedReason})},fail(e){this._log.warn("onPaused",e)}})],KL.prototype,"onPaused"),z_([AY([],eh.INIT,{ignoreError:!0,sync:!0,success(){var e,i;(i=(e=this.callback)==null?void 0:e.onStopped)==null||i.call(e)},fail(e){this._log.warn("onStopped",e)}})],KL.prototype,"onStopped");var LZ=KL,AgA=["overseas-webrtc.tlivewebrtc.com","oswebrtc-lint.tliveplay.com"],vY=class TX{constructor(i){this.core=i,Ms(this,"_sdkAppId"),Ms(this,"_userId"),Ms(this,"connectedRoomIdSet",new Set),Ms(this,"updateSeq",0),Ms(this,"_log"),Ms(this,"player"),Ms(this,"peerConnection"),Ms(this,"svrSig"),Ms(this,"streamURL"),Ms(this,"signalURL"),Ms(this,"insertableStreamsAbortMap",new Map),Ms(this,"scriptTransformWorker"),Ms(this,"connectionState","disconnected"),Ms(this,"isStarted",!1),Ms(this,"isStopped",!0),Ms(this,"isReconnecting",!1),Ms(this,"callback"),Ms(this,"isFireWallErrorEmitted",!1),Ms(this,"stat"),Ms(this,"isH264DecodeSupported"),Ms(this,"connectionTimeoutId"),Ms(this,"streamHealthCheckTimeoutId"),Ms(this,"streamHealthCheckReject"),i.loggerManager.startUpload(),this._log=this.core.log.createChild({id:`${this.getAlias()}`}),this.player=new LZ(i,this._log),i.innerEmitter.on(i.INNER_EVENT.SEI_MESSAGE,this.onSEIMessage,this)}getName(){return TX.Name}getAlias(){return"LEB"}getGroup(){return""}getValidateRule(i){switch(i){case"start":return xaA;case"update":case"stop":return{}}}get enableSEI(){return this.core.room.enableSEI&&(this.core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED||this.core.rtcDectection.IS_SCRIPT_TRANSFORM_SUPPORTED)}wrapCallback(i){if(!i)return;const n={},c=["onStats","onSEIMessage"];for(const I of Object.keys(i)){const C=i[I];typeof C=="function"&&(c.includes(I)?n[I]=C:n[I]=(...m)=>(this._log.debug(`callback ${I} called`,m.length>0?m[0]:""),C(...m)))}return n}async start(i){var n;this.isStopped=!1;const{view:c,url:I,volume:C,muted:m,fillMode:R,loggerConfig:_,callback:T}=i;this.callback=this.wrapCallback(T),this.player.setCallback(this.callback);const{errorModule:{RtcError:b,ErrorCode:J,ErrorCodeDictionary:cA},loggerManager:eA,rtcDectection:CA}=this.core;if(this._sdkAppId=_.sdkAppId,this._userId=_.userId,this._log.setSdkAppId(_.sdkAppId),this._log.setUserId(_.userId),this.player.updateLogConfig(_),eA.addJoinedUser(_),!CA.isWebRTCSupported()||!CA.isAddTransceiverSupported())throw new b({code:J.ENV_NOT_SUPPORTED,extraCode:cA.NOT_SUPPORTED_WEBRTC,message:"webrtc not supported"});if(!(await CA.decodeSupportStatus()).isH264DecodeSupported||this.isH264DecodeSupported===!1)throw this.isH264DecodeSupported=!1,new b({code:J.ENV_NOT_SUPPORTED,extraCode:cA.NOT_SUPPORTED_H264_DECODE,message:"h264 not supported"});!CA.IS_SEI_SUPPORTED&&T?.onSEIMessage&&((n=T.onError)==null||n.call(T,new b({code:J.ENV_NOT_SUPPORTED,extraCode:cA.NOT_SUPPORTED_SEI,message:"sei not supported"}))),this.player.setVideoContainer(c),this.player.setMuted(m),this.player.setFillMode(R);try{await this.connect(I),this.stat=new zaA(this.peerConnection,this.core),this.stat.start(vA=>{var qA,Ae;return(Ae=(qA=this.callback)==null?void 0:qA.onStats)==null?void 0:Ae.call(qA,vA)});const IA=this.player.play();this.player.setVolume(C);const oA=this.createStreamHealthCheckPromise();await Promise.race([IA,oA]),this.clearStreamHealthCheck(),this.isStarted=!0}catch(IA){throw this.stop(),IA}}async update(i){const{view:n,url:c,volume:I,muted:C,fillMode:m,action:R,fullScreen:_,pictureInPicture:T}=i;c&&c!==this.streamURL&&await this.switchStream(c),this.player.setMuted(C),this.player.setVolume(I),this.player.setFillMode(m),n&&this.player.videoPlayer.setContainer(this.core.utils.isString(n)?document.getElementById(n):n),R==="pause"?this.player.pause():R==="resume"&&this.player.resume(),this.core.utils.isBoolean(_)&&(_?await this.player.enterFullscreen():await this.player.exitFullscreen()),this.core.utils.isBoolean(T)&&(T?await this.player.enterPictureInPicture():await this.player.exitPictureInPicture())}async switchStream(i){this._log.info("switchStream",i);const n=this.peerConnection,c=this.streamURL,I=this.signalURL,C=this.svrSig,m=new Map(this.insertableStreamsAbortMap),R=this.player;delete this.peerConnection,delete this.streamURL,delete this.signalURL,delete this.svrSig,this.insertableStreamsAbortMap.clear();const _=new LZ(this.core,this._log);_.setVideoContainer(R.videoPlayer.container),_.setFillMode(R.videoPlayer.objectFit),_.setMuted(R.muted),_.setCallback(this.callback);const T=b=>{const{track:J}=b;this.createEncodedStreams(b.receiver),this.initReceiverTransform(b.receiver,J.kind==="audio"),J.kind==="audio"?_.setAudioTrack(J):_.setVideoTrack(J)};try{await this.connectForSwitch(i,T),this._log.info("switchStream: new connection established"),await this.waitForNewPlayerFirstFrame(_),this._log.info("switchStream: new stream first frame received"),R.audioPlayer.setMuted(!0),R.stop(),this.player=_,n&&(clearTimeout(this.connectionTimeoutId),n.close(),n.getReceivers().forEach(b=>m.delete(b)),c&&C&&I&&this.fetchStopStreamWithParams(c,I,C).catch(b=>{this._log.warn("switchStream: stop old stream failed",b)})),this._log.info("switchStream: switch completed successfully")}catch(b){this._log.error("switchStream failed",b),_.stop();const J=this.peerConnection;throw J&&(J.close(),J.getReceivers().forEach(cA=>this.insertableStreamsAbortMap.delete(cA))),this.peerConnection=n,this.streamURL=c,this.signalURL=I,this.svrSig=C,this.insertableStreamsAbortMap=m,this.player=R,R.audioPlayer.setMuted(R.muted),b}}waitForNewPlayerFirstFrame(i){return new Promise((n,c)=>{let I=0,C=!1;const m=i.videoPlayer.getElement();if(!m)return void c(new Error("VideoPlayer has no video element"));const R=()=>{C=!0,clearInterval(b),m.removeEventListener("loadeddata",_),m.removeEventListener("playing",T)},_=()=>{C||(this._log.info("waitForNewPlayerFirstFrame: loadeddata event fired"),R(),n())},T=()=>{C||(this._log.info("waitForNewPlayerFirstFrame: playing event fired"),R(),n())};m.addEventListener("loadeddata",_,{once:!0}),m.addEventListener("playing",T,{once:!0}),i.play().catch(J=>{this._log.warn("waitForNewPlayerFirstFrame: play failed",J)});const b=setInterval(()=>{if(!C){if(I+=100,m.videoWidth>0&&m.videoHeight>0)return this._log.info(`waitForNewPlayerFirstFrame: video has valid dimensions ${m.videoWidth}x${m.videoHeight}`),R(),void n();I>=1e4&&(R(),c(new Error("waitForNewPlayerFirstFrame timeout")))}},100)})}connectForSwitch(i,n){return new Promise((c,I)=>{try{this.initScriptTransformWorker();const C={encodedInsertableStreams:this.enableSEI,iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},m=new RTCPeerConnection(C);this.peerConnection=m,m.onconnectionstatechange=()=>{this.connectionState=m.connectionState,this._log.info("connectForSwitch connectionState",m.connectionState),m.connectionState!=="failed"&&m.connectionState!=="closed"||I(new Error(`connection is ${m.connectionState}`)),m.connectionState==="connected"&&(this.logSelectedCandidate(),c())},m.ontrack=n,m.addTransceiver("audio",{direction:"recvonly"}),m.addTransceiver("video",{direction:"recvonly"}),this._log.info("connectForSwitch createOffer"),m.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}).then(R=>(R.sdp=GZ(R.sdp),this._log.info("connectForSwitch setOffer"),m.setLocalDescription(R))).then(()=>{const R={sessionId:l3(),streamurl:i,clientinfo:this.core.environment.getOSString(),localsdp:m.localDescription};return this.exchangeSDP(i,R)}).then(R=>(this._log.info("connectForSwitch setAnswer"),m.setRemoteDescription(R))).catch(I)}catch(C){I(C)}this.connectionTimeoutId=setTimeout(()=>I(new Error("connection timeout")),1e4)})}async fetchStopStreamWithParams(i,n,c){try{const I=`${n}/webrtc/v1/stopstream`,C=await eY(I,{streamurl:i,svrsig:c},{timeout:3}),{errcode:m,errmsg:R}=C;if(m!==0)throw new Error(`errCode:${m}, errmsg:${R}`);return C}catch(I){this._log.error("fetchStopStreamWithParams error",I)}}async stop(){this.isStopped=!0,this.clearStreamHealthCheck(),this.player.stop(),this.peerConnection&&(clearTimeout(this.connectionTimeoutId),this.peerConnection.close(),this.peerConnection.getReceivers().forEach(i=>this.insertableStreamsAbortMap.delete(i)),delete this.peerConnection,await this.fetchStopStream(),delete this.streamURL,delete this.signalURL,delete this.svrSig),this.stat&&(this.stat.stop(),delete this.stat),this.core.room.keyPointManager.uploadKVStat(this.core.kvStatManager,this._sdkAppId)}destroy(){this.stop(),this.core.innerEmitter.off(this.core.INNER_EVENT.SEI_MESSAGE,this.onSEIMessage,this)}createStreamHealthCheckPromise(){return new Promise((i,n)=>{this.streamHealthCheckReject=n,this.streamHealthCheckTimeoutId=window.setTimeout(()=>this.checkStreamHealth(n),5e3)})}clearStreamHealthCheck(){this.streamHealthCheckTimeoutId&&(clearTimeout(this.streamHealthCheckTimeoutId),delete this.streamHealthCheckTimeoutId),delete this.streamHealthCheckReject}async checkStreamHealth(i){if(!this.isStopped&&this.peerConnection)try{const n=this.peerConnection.getReceivers().find(J=>{var cA;return((cA=J.track)==null?void 0:cA.kind)==="video"});if(!n)return void this._log.warn("checkStreamHealth: no video receiver found");const c=await n.getStats();let I=0,C=0;c.forEach(J=>{J.type==="inbound-rtp"&&(J.mediaType==="video"||J.kind==="video")&&(I=J.bytesReceived||0,C=J.framesDecoded||0)});const{isPlaying:m}=this.player,R=m||C>0;this._log.info(`checkStreamHealth: bytesReceived=${I}, framesDecoded=${C}, isPlaying=${m}`);const{RtcError:_,ErrorCode:T,ErrorCodeDictionary:b}=this.core.errorModule;I===0?(this._log.warn("checkStreamHealth: no stream data received after 5s"),i(new _({code:T.OPERATION_FAILED,message:"no stream data received"}))):R||(this._log.warn("checkStreamHealth: decode failed"),this.isH264DecodeSupported=!1,i(new _({code:T.ENV_NOT_SUPPORTED,extraCode:b.NOT_SUPPORTED_H264_DECODE,message:"h264 decode failed"})))}catch(n){this._log.warn("checkStreamHealth error",n)}}connect(i){return new Promise((n,c)=>{try{this.initScriptTransformWorker();const I={encodedInsertableStreams:this.enableSEI,iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},C=new RTCPeerConnection(I);this.peerConnection=C,C.onconnectionstatechange=()=>{this.connectionState=C.connectionState,this._log.info("connectionState",C.connectionState),C.connectionState!=="failed"&&C.connectionState!=="closed"||(this.isStarted?this.reconnect(i):c(new Error(`connection is ${C.connectionState}`))),C.connectionState==="connected"&&(this.logSelectedCandidate(),n())},C.ontrack=m=>this.onTrack(m),C.addTransceiver("audio",{direction:"recvonly"}),C.addTransceiver("video",{direction:"recvonly"}),this._log.info("createOffer"),C.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}).then(m=>(m.sdp=GZ(m.sdp),this._log.info("setOffer"),C.setLocalDescription(m))).then(()=>{const m={sessionId:l3(),streamurl:i,clientinfo:this.core.environment.getOSString(),localsdp:C.localDescription};return this.exchangeSDP(i,m)}).then(m=>(this._log.info("setAnswer"),C.setRemoteDescription(m))).catch(c)}catch(I){c(I)}this.connectionTimeoutId=setTimeout(()=>c(new Error("connection timeout")),1e4)})}async exchangeSDP(i,n){let c,I,C;try{this._log.info("exchangeSDP");const m=egA(i);if(!m)throw new Error("streamDomain is empty");const{signalDomain:R,cached:_}=await this.fetchSignalDomain(m);if(!R)throw new Error("signalDomain is empty");{this._log.info("try exchangeSDP signalDomain:",R,_);const T=await this.doExchangeSDP(`https://${R}`,n,3);c=T.url,I=T.remoteSdp,C=T.svrSig}}catch(m){this._log.warn("exchangeSDP failed, fallback",m);try{const R=await this.core.utils.promiseAny(AgA.map(_=>this.doExchangeSDP(`https://${_}`,n,3)));c=R.url,I=R.remoteSdp,C=R.svrSig}catch(R){throw this._log.error("exchangeSDP failed",R),R[0]||R}}return this.streamURL=i,this.signalURL=c,this.svrSig=C,I}async reconnect(i){var n,c;if(!this.isReconnecting){this.isReconnecting=!0;try{this._log.warn("start reconnect"),await this.connect(i),this._log.warn("reconnect success")}catch(I){this._log.error("reconnect error",I);const{RtcError:C,ErrorCode:m}=this.core.errorModule;(c=(n=this.callback)==null?void 0:n.onError)==null||c.call(n,new C({code:m.OPERATION_FAILED,message:"reconnect failed"}))}finally{this.isReconnecting=!1}}}async logSelectedCandidate(){if(!this.peerConnection)return;const i=await this.peerConnection.getStats();for(const[n,c]of i)if(this.core.rtcDectection.isSelectedCandidatePair(c)){const I=i.get(c.localCandidateId),C=i.get(c.remoteCandidateId);I&&this._log.info(`local candidate: ${I.candidateType} ${I.protocol}:${I.ip||I.address}:${I.port} ${I.networkType||""} ${I.relayProtocol?`relayProtocol:${I.relayProtocol} url: ${I.url}`:""}`),C&&this._log.info(`remote candidate: ${C.candidateType} ${C.protocol}:${C.ip||C.address}:${C.port}`);break}}async doExchangeSDP(i,n,c){const I=`${i}/webrtc/v1/pullstream`,C=await eY(I,n,{timeout:c}),{errcode:m,errmsg:R,remotesdp:_,svrsig:T}=C;if(m!==0){const b=new Error(`errCode:${m}, errMsg:${R}`);throw b.name="RequestSignalError",b}return{url:i,remoteSdp:_,svrSig:T}}createEncodedStreams(i){var n;if(this.enableSEI&&this.core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED)try{if(this._log.warn("enableSEI",this.enableSEI),!this.insertableStreamsAbortMap.has(i)){const c=i.createEncodedStreams(),I=new AbortController,C={abortController:I,enqueue:m=>i.track.kind==="audio"?m:this.decodeVideoFrame(m)};c.readable.pipeThrough(new TransformStream({transform:(m,R)=>{const _=C.enqueue(m);_&&R.enqueue(_)}})).pipeTo(c.writable,I).catch(m=>{m!=="destroy"&&this._log.warn(m)}),(n=this.insertableStreamsAbortMap.get(i))==null||n.abort("destroy"),this.insertableStreamsAbortMap.set(i,I)}}catch(c){this._log.warn(`createEncodedStreams ${i.track.kind} failed`,c)}}initReceiverTransform(i,n){this.peerConnection&&this.enableSEI&&this.scriptTransformWorker&&!i.transform&&(i.transform=new RTCRtpScriptTransform(this.scriptTransformWorker,{isReceiver:!0,isAudio:n,userId:"",streamType:this.core.enums.RemoteStreamType.Main}))}initScriptTransformWorker(){const{room:i,rtcDectection:n,createScriptTransformWorker:c,trtc:I,TRTC:C}=this.core;!this.enableSEI||n.IS_INSERTABLE_STREAM_SUPPORTED||this.scriptTransformWorker||n.IS_SCRIPT_TRANSFORM_SUPPORTED&&(this._log.info("initScriptTransformWorker"),this.scriptTransformWorker=c({videoEncodePipeline:i.videoManager.encodePipeline,videoDecodePipeline:i.videoManager.decodePipeline,audioEncodePipeline:i.audioManager.encodePipeline,audioDecodePipeline:i.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=m=>{var R,_;m.data.type==="sei"&&((_=(R=this.callback)==null?void 0:R.onSEIMessage)==null||_.call(R,{data:m.data.data,seiPayloadType:m.data.seiPayloadType}))},this.scriptTransformWorker.onerror=m=>{this._log.error("scriptTransformWorker error: ",m.message)})}decodeVideoFrame(i){if(!this.core.room.videoManager)return i;for(const n of this.core.room.videoManager.decodePipeline)if(n&&!(i=n({frame:i})))return;return i}async fetchStopStream(){if(this.streamURL&&this.svrSig&&this.signalURL)try{const i=`${this.signalURL}/webrtc/v1/stopstream`,n=await eY(i,{streamurl:this.streamURL,svrsig:this.svrSig},{timeout:3}),{errcode:c,errmsg:I}=n;if(c!==0)throw new Error(`errCode:${c}, errmsg:${I}`);return n}catch(i){this._log.error("fetchStopStream error",i)}}onTrack(i){const{track:n}=i;this.createEncodedStreams(i.receiver),this.initReceiverTransform(i.receiver,n.kind==="audio"),n.kind==="audio"?this.player.setAudioTrack(n):this.player.setVideoTrack(n)}onSEIMessage({room:i,nalu:n}){var c,I;i===this.core.room&&((I=(c=this.callback)==null?void 0:c.onSEIMessage)==null||I.call(c,{data:n.seiPayload.buffer,seiPayloadType:n.seiPayloadType}))}async fetchSignalDomain(i,n=tY[0]){var c;const I=`https://${n}/signal_query`;try{const C=window.localStorage.getItem(E3);if(C){const b=JSON.parse(C);if(((c=b[i])==null?void 0:c.expire)-new Date().getTime()>0)return{signalDomain:b[i].signal,cached:!0}}const m=await eY(I,{domain:i,requestid:l3(16),client_type:"Web",client_info:window.navigator.userAgent}),{errcode:R,errmsg:_,data:T}=m;if(R===0){const{signal_domain:b,cache_time:J}=T;let cA={};const eA=window.localStorage.getItem(E3);eA&&(cA=JSON.parse(eA)),cA[i]={signal:b,expire:new Date().getTime()+1e3*J};try{window.localStorage.setItem(E3,JSON.stringify(cA))}catch{}return{signalDomain:b,cached:!1}}throw new Error(`errCode:${R} errmsg:${_}`)}catch(C){return this._log.error("fetchSignalDomain error",C),tY[1]&&n!==tY[1]?this.fetchSignalDomain(i,tY[1]):{signalDomain:"",cached:!1}}}};Ms(vY,"Name","LEBPlayer"),z_([WaA({fnName:"connect"})],vY.prototype,"stop"),z_([jaA({settings:{retries:1/0,timeout:2e3},onRetrying(e){var i;if(this._log.warn(`retry connect ${e}`),e>=3&&((i=this.callback)==null?void 0:i.onError)&&!this.isFireWallErrorEmitted){const{RtcError:n,ErrorCode:c,ErrorCodeDictionary:I}=this.core.errorModule;this.isFireWallErrorEmitted=!0,this.callback.onError(new n({code:c.OPERATION_FAILED,extraCode:I.FIREWALL_RESTRICTION,message:"firewall restriction"}))}},onError(e,i,n,c){var I;if(this._log.warn("connect failed",e),this.peerConnection&&(this.peerConnection.close(),delete this.peerConnection),!this.isStopped&&((I=e.message||e)==null?void 0:I.includes("connection")))i();else{const{RtcError:C,ErrorCode:m}=this.core.errorModule;n(new C({code:m.UNKNOWN_ERROR,message:e.message}))}}})],vY.prototype,"connect");var NX=vY,eY=async(e,i,n={})=>{const{timeout:c=10}=n;let I,C=0,m={};window.AbortController&&(I=new window.AbortController,m={signal:I.signal},C=window.setTimeout(()=>I.abort(),1e3*c));const R=await fetch(e,LaA({body:JSON.stringify(i),cache:"no-cache",credentials:"same-origin",headers:{"content-type":"text/plain;charset=utf-8"},method:"POST",mode:"cors"},m));if(C&&window.clearTimeout(C),R.status!==200)throw new Error(`Network Error, status code:${R.status}`);return R.json()},tY=["webrtc-signal-scheduler.tlivesource.com","bak-webrtc-signal-scheduler.tlivesource.com"],E3="LEB_PLAYER_STORAGE_KEY",egA=e=>{const i=/^(?:webrtc:\/\/)([0-9.\-A-Za-z_]+)(?:\/)(?:[0-9.\-A-Za-z_=]+)(?:\/)(?:[^?#]*)(?:\?*)(?:[^?#]*)/.exec(e);return i?i[1]:""},tgA=NX;const igA=Object.freeze(Object.defineProperty({__proto__:null,LEBPlayer:NX,default:tgA},Symbol.toStringTag,{value:"Module"})),ogA=$U(igA);var GX=Object.defineProperty,ngA=Object.defineProperties,sgA=Object.getOwnPropertyDescriptors,UZ=Object.getOwnPropertySymbols,rgA=Object.prototype.hasOwnProperty,agA=Object.prototype.propertyIsEnumerable,dW=(e,i,n)=>i in e?GX(e,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[i]=n,ggA=(e,i)=>{for(var n in i||(i={}))rgA.call(i,n)&&dW(e,n,i[n]);if(UZ)for(var n of UZ(i))agA.call(i,n)&&dW(e,n,i[n]);return e},cgA=(e,i)=>ngA(e,sgA(i)),lgA=(e,i)=>{for(var n in i)GX(e,n,{get:i[n],enumerable:!0})},jg=(e,i,n)=>dW(e,typeof i!="symbol"?i+"":i,n);async function IgA({sdkAppId:e,userId:i,userSig:n,core:c}){var I;const C=Math.round(new Date().getTime()/1e3);try{const m=await c.schedule.getAbilityConfig(e,c.schedule.ScheduleRequestType.TRTC_AUTO_CONF,{sdkAppId:e,userId:i,userSig:n,timestamp:C});c.log.info(`virtual background ability response: ${JSON.stringify(m)}`);const{data:R}=m;return(I=R?.trtcAutoConf)!=null&&I.web_ar?{auth:!0,timestamp:C}:{auth:!1}}catch(m){return c.log.error("virtual background fetch error",m),{auth:!1}}}var ugA={sdkAppId:{required:!0,type:"number"},userId:{required:!0,type:"string"},userSig:{required:!0,type:"string"}};function EgA(e){return{name:"VirtualBackgroundOptions",type:"object",required:!0,allowEmpty:!1,properties:cgA(ggA({},ugA),{type:{required:!1,type:"string",values:["image","blur","color"]},src:{required:!1,type:"string"},blurLevel:{required:!1,type:"number",min:1,max:10},onAbort:{required:!1},color:{required:!1,type:["array","string"]},enableFaceCentering:{required:!1,type:"boolean"},enableEffectOptimization:{required:!1,type:"boolean"}}),validate(i,n,c,I){var C;const{RtcError:m,ErrorCode:R,ErrorCodeDictionary:_}=e.errorModule;if(!i)return;const{type:T,src:b,onAbort:J}=i;if(T==="image"&&!b)throw new m({code:R.INVALID_PARAMETER,extraCode:_.INVALID_PARAMETER_REQUIRED,fnName:c,messageParams:{key:"src"}});if(J&&!e.utils.isFunction(J))throw new m({code:R.INVALID_PARAMETER,extraCode:_.INVALID_PARAMETER_TYPE,fnName:c,messageParams:{key:"onAbort",value:typeof J,rule:{type:"Function"}}});if(!((C=e.room.videoManager.cameraTrack)!=null&&C.mediaTrack))throw new m({code:R.INVALID_OPERATION,extraCode:_.INVALID_OPERATION_NEED_VIDEO,fnName:c})}}}function dgA(e){return{name:"UpdateVirtualBackgroundOptions",type:"object",required:!0,allowEmpty:!1,properties:{type:{required:!0,type:"string",values:["image","blur","color"]},src:{required:!1,type:"string"},blurLevel:{required:!1,type:"number",min:1,max:10},color:{required:!1,type:["array","string"]},enableFaceCentering:{required:!1,type:"boolean"},enableEffectOptimization:{required:!1,type:"boolean"}},validate(i,n,c,I){if(!i)return;const{RtcError:C,ErrorCode:m,ErrorCodeDictionary:R}=e.errorModule,{type:_,src:T}=i;if(_==="image"&&!T)throw new C({code:m.INVALID_PARAMETER,extraCode:R.INVALID_PARAMETER_REQUIRED,fnName:c,messageParams:{key:"src"}})}}}function CgA(e){return{name:"StopVirtualBackgroundOptions",required:!1}}var hgA=(()=>{var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(i={}){var n,c,I=i;I.ready=new Promise(($,j)=>{n=$,c=j});var C=Object.assign({},I),m="";typeof document<"u"&&document.currentScript&&(m=document.currentScript.src),e&&(m=e),m=m.indexOf("blob:")!==0?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var R,_,T=I.print||console.log.bind(console),b=I.printErr||console.error.bind(console);function J($){if($t($))return function(j){for(var RA=atob(j),ZA=new Uint8Array(RA.length),ne=0;ne$.startsWith(pt);function Pt($){return Promise.resolve().then(()=>function(j){if(j==ae&&R)return new Uint8Array(R);var RA=J(j);if(RA)return RA;throw"both async and sync fetching of the wasm failed"}($))}function ii($,j,RA,ZA){return function(ne,De,Ke){return Pt(ne).then(qe=>WebAssembly.instantiate(qe,De)).then(qe=>qe).then(Ke,qe=>{b(`failed to asynchronously prepare wasm: ${qe}`),Xe(qe)})}(j,RA,ZA)}$t(ae="data:application/octet-stream;base64,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IAEoAgA2AgAgAiABKAIENgIEIAIgASgCCDYCCCACIAEoAgw2AgwgAiABKAIQNgIQIAIgASgCFDYCFCACIAEoAhg2AhggAiABKAIcNgIcIAIgASgCIDYCICACIAEoAiQ2AiQgAiABKAIoNgIoIAIgASgCLDYCLCACIAEoAjA2AjAgAiABKAI0NgI0IAIgASgCODYCOCACIAEoAjw2AjwgAUFAayEBIAJBQGsiAiAFTQ0ACwsgAiAETw0BA0AgAiABKAIANgIAIAFBBGohASACQQRqIgIgBEkNAAsMAQsgA0EESQRAIAAhAgwBCyAAIANBBGsiBEsEQCAAIQIMAQsgACECA0AgAiABLQAAOgAAIAIgAS0AAToAASACIAEtAAI6AAIgAiABLQADOgADIAFBBGohASACQQRqIgIgBE0NAAsLIAIgA0kEQANAIAIgAS0AADoAACABQQFqIQEgAkEBaiICIANHDQALCyAACwsAIAEgAiAAEEIaCxIAIAFBAXRB8MoAakECIAAQQgv5AQEEfwJ/IAEQKiECIwBBEGsiBSQAAn8gAC0AC0EHdgRAIAAoAgQMAQsgAC0AC0H/AHELIgRBAE8EQAJAIAIgAC0AC0EHdgR/IAAoAghB/////wdxQQFrBUEKCyIDIARrTQRAIAJFDQECfyAALQALQQd2BEAgACgCAAwBCyAACyIDIAQEfyACIANqIAMgBBBFIAEgAkEAIAMgBGogAUsbQQAgASADTxtqBSABCyACEEUgACACIARqIgEQMSAFQQA6AA8gASADaiAFLQAPOgAADAELIAAgAyACIARqIANrIARBACACIAEQRAsgBUEQaiQAIAAMAQsQJwALC/ICAgJ/AX4CQCACRQ0AIAAgAToAACAAIAJqIgNBAWsgAToAACACQQNJDQAgACABOgACIAAgAToAASADQQNrIAE6AAAgA0ECayABOgAAIAJBB0kNACAAIAE6AAMgA0EEayABOgAAIAJBCUkNACAAQQAgAGtBA3EiBGoiAyABQf8BcUGBgoQIbCIBNgIAIAMgAiAEa0F8cSIEaiICQQRrIAE2AgAgBEEJSQ0AIAMgATYCCCADIAE2AgQgAkEIayABNgIAIAJBDGsgATYCACAEQRlJDQAgAyABNgIYIAMgATYCFCADIAE2AhAgAyABNgIMIAJBEGsgATYCACACQRRr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ACACQQA6AA8DQCABBEAgACACLQAPOgAAIAFBAWshASAAQQFqIQAMAQsLIAJBEGokAAsaACAALQALQQd2BEAgACgCCBogACgCABAZCwvmAQEFfyMAQRBrIgUkACMAQSBrIgMkACMAQRBrIgQkACAEIAA2AgwgBCAAIAFqNgIIIAMgBCgCDDYCGCADIAQoAgg2AhwgBEEQaiQAIAMoAhghBCADKAIcIQYjAEEQayIBJAAgASAGNgIMIAIgBCAGIARrIgQQQyABIAIgBGo2AgggAyABKAIMNgIQIAMgASgCCDYCFCABQRBqJAAgAyAAIAMoAhAgAGtqNgIMIAMgAiADKAIUIAJrajYCCCAFIAMoAgw2AgggBSADKAIINgIMIANBIGokACAFKAIMIQcgBUEQaiQAIAcLDwAgAgRAIAAgASACEDILC/UCAQV/IwBBEGsiByQAIAIgAUF/c0Hv////B2pNBEACfyAALQALQQd2BEAgACgCAAwBCyAACyEIIAdBBGoiCSAAIAFB5////wNJBH8gByABQQF0NgIMIAcgASACajYCBCMAQRBrIgIkACAJKAIAIAdBDGoiCigCAEkhCyACQRBqJAAgCiAJIAsbKAIAIgJBC08EfyACQRBqQXBxIgIgAkEBayICIAJBC0YbBUEKC0EBagVB7////wcLEDAgBygCBCECIAcoAggaIAQEQCACIAggBBAjCyAFBEAgAiAEaiAGIAUQIwsgAyAEayEGIAMgBEcEQCACIARqIAVqIAQgCGogBhAjCyABQQpHBEAgCBAZCyAAIAI2AgAgACAAKAIIQYCAgIB4cSAHKAIIQf////8HcXI2AgggACAAKAIIQYCAgIB4cjYCCCAAIAQgBWogBmoiADYCBCAHQQA6AAwgACACaiAHLQAMOgAAIAdBEGokAA8LECcACwoAIAAgASACEEMLuQEBBH8jAEEQayIEJAAgBCACNgIMIwBBoAFrIgMkACADIAAgA0GeAWogARsiBjYClAFBfyEFIAMgAUEBayIAQQAgACABTRs2ApgBIANBAEGQARAmIgBBfzYCTCAAQSA2AiQgAEF/NgJQIAAgAEGfAWo2AiwgACAAQZQBajYCVAJAIAFBAEgEQEHo3gBBPTYCAAwBCyAGQQA6AAAgAEH9CiACQR8QTSEFCyAAQaABaiQAIARBEGokACAFCwQA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KAIARQ0AIAIgBCgCGDYCAAsgAEEBRiEFDAELQQAhBQsgBEFAayQAIAULMQAgACABKAIIQQAQHgRAIAEgAiADED0PCyAAKAIIIgAgASACIAMgACgCACgCHBEGAAsYACAAIAEoAghBABAeBEAgASACIAMQPQsLnQEBAn8jAEFAaiIDJAACf0EBIAAgAUEAEB4NABpBACABRQ0AGkEAIAFBjM0AECAiAUUNABogA0EMakEAQTQQJhogA0EBNgI4IANBfzYCFCADIAA2AhAgAyABNgIIIAEgA0EIaiACKAIAQQEgASgCACgCHBEGACADKAIgIgBBAUYEQCACIAMoAhg2AgALIABBAUYLIQQgA0FAayQAIAQLCgAgACABQQAQHgtOAgF/AXwjAEEQayICJAAgAkEANgIMIAEoAgRB1M8AIAJBDGoQCSEDIAIoAgwiAQRAIAEQAQsgACADRAAAAAAAAAAAYjoAOCACQRBqJAALNwEBfyMAQRBrIgIkACACIAEtADg2AgggAEHUzwAgAkEIahAHNgIEIABB1NUANgIAIAJBEGokAAuoAQEFfyAAKAJUIgMoAgAhBSADKAIEIgQgACgCFCAAKAIcIgdrIgYgBCAGSRsiBgRAIAUgByAGECIaIAMgAygCACAGaiIFNgIAIAMgAygCBCAGayIENgIECyAEIAIgAiAESxsiBARAIAUgASAEECIaIAMgAygCACAEaiIFNgIAIAMgAygCBCAEazYCBAsgBUEAOgAAIAAgACgCLCIBNgIcIAAgATYCFCACC5wBAQJ/IwBBEGsiAiQAQcgAEBwhASAAKAIEIgAQAiACIAA2AgggAUHMLSACQQhqEAc2AgQgAUHU1QA2AgAgAUEBNgIcIAFB1NUANgIYIAFBATYCFCABQdTVADYCECABQQE2AgwgAUHU1QA2AgggAUEAOgAgIAFBADYCRCABQoCAgIAwNwI8IAFBADsANyABQQA7ACsgAkEQaiQAIAELigUCBn4CfyABIAEoAgBBB2pBeHEiAUEQajYCACAAIQkgASkDACEDIAEpAwghBSMAQSBrIgAkAAJAIAVC////////////AIMiBEKAgICAgIDAgDx9IARCgICAgICAwP/DAH1UBEAgBUIEhiADQjyIhCEEIANC//////////8PgyIDQoGAgICAgICACFoEQCAEQoGAgICAgICAwAB8IQIMAgsgBEKAgICAgICAgEB9IQIgA0KAgICAgICAgAhSDQEgAiAEQgGDfCECDAELIANQIARCgICAgICAwP//AFQgBEKAgICAgIDA//8AURtFBEAgBUIEhiADQjyIhEL/////////A4NCgICAgICAgPz/AIQhAgwBC0KAgICAgICA+P8AIQIgBEL///////+//8MAVg0AQgAhAiAEQjCIpyIBQZH3AEkNACADIQIgBUL///////8/g0KAgICAgIDAAIQiBCEGAkAgAUGB9wBrIghBwABxBEAgAyAIQUBqrYYhBkIAIQIMAQsgCEUNACAGIAitIgeGIAJBwAAgCGutiIQhBiACIAeGIQILIAAgAjcDECAAIAY3AxgCQEGB+AAgAWsiAUHAAHEEQCAEIAFBQGqtiCEDQgAhBAwBCyABRQ0AIARBwAAgAWuthiADIAGtIgKIhCEDIAQgAoghBAsgACADNwMAIAAgBDcDCCAAKQMIQgSGIAApAwAiA0I8iIQhAiAAKQMQIAApAxiEQgBSrSADQv//////////D4OEIgNCgYCAgICAgIAIWgRAIAJCAXwhAgwBCyADQoCAgICAgICACFINACACQgGDIAJ8IQILIABBIGokACAJIAIgBUKAgICAgICAgIB/g4S/OQMAC0ABAn8jAEEQayICJAAgAiABNgIMIAJB1NUANgIIIAJBCGogABEBACEDIAIoAgwiAQRAIAEQAwsgAkEQaiQAIAMLBABCAAsEAEEAC/YCAQh/IwBBIGsiAyQAIAMgACgCHCIENgIQIAAoAhQhBSADIAI2AhwgAyABNgIYIAMgBSAEayIBNgIUIAEgAmohBUECIQcCfwJAAkACQCAAKAI8IANBEGoiAUECIANBDGoQDSIEBH9B6N4AIAQ2AgBBfwVBAAsEQCABIQQMAQsDQCAFIAMoAgwiBkYNAiAGQQBIBEAgASEEDAQLIAEgBiABKAIEIghLIglBA3RqIgQgBiAIQQAgCRtrIgggBCgCAGo2AgAgAUEMQQQgCRtqIgEgASgCACAIazYCACAFIAZrIQUgACgCPCAEIgEgByAJayIHIANBDGoQDSIGBH9B6N4AIAY2AgBBfwVBAAtFDQALCyAFQX9HDQELIAAgACgCLCIBNgIcIAAgATYCFCAAIAEgACgCMGo2AhAgAgwBCyAAQQA2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EGokAAsiAQF+IAEgAq0gA61CIIaEIAQgABEMACIFQiCIpyQBIAWnCzcBAX8jAEEQayICJAAgAiABKAI8NgIIIABBnNAAIAJBCGoQBzYCBCAAQdTVADYCACACQRBqJAALC/NKFQBBgAgLhCZzZXRCZWF1dHkALSsgICAwWDB4AC0wWCswWCAwWC0weCsweCAweAB1bnNpZ25lZCBzaG9ydAB1bnNpZ25lZCBpbnQAaW5pdABmbG9hdAB1aW50NjRfdABibHVyUmFkaXVzAHZlY3RvcgBtaXJyb3IAYXR0YWNoU2hhZGVyAGRlbGV0ZVNoYWRlcgBjcmVhdGVTaGFkZXIAY29tcGlsZVNoYWRlcgB1bnNpZ25lZCBjaGFyAHN0ZDo6ZXhjZXB0aW9uAHJvdGF0aW9uAG5hbgBsaW5rUHJvZ3JhbQBkZWxldGVQcm9ncmFtAGNyZWF0ZVByb2dyYW0AYm9vbABlbXNjcmlwdGVuOjp2YWwAc2V0V2F0ZXJNYXJrAHN0b3BXYXRlck1hcmsAdW5zaWduZWQgbG9uZwBzdGQ6OndzdHJpbmcAYmFzaWNfc3RyaW5nAHN0ZDo6c3RyaW5nAHN0ZDo6dTE2c3RyaW5nAHN0ZDo6dTMyc3RyaW5nAGluZgAlZgBjbG9zZQBkb3VibGUAdmJNb2RlAHNoYWRlclNvdXJjZQB2b2lkAHNhbXBsZUNvbG9yICs9IHRleHR1cmUoZnJhbWUsIGJsdXJDb29yZGluYXRlc1sATkFOAElORgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxzaG9ydD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgc2hvcnQ+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGludD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgaW50PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxmbG9hdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dWludDhfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50OF90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1aW50MTZfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50MTZfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dWludDY0X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGludDY0X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PHVpbnQzMl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxpbnQzMl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxjaGFyPgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1bnNpZ25lZCBjaGFyPgBzdGQ6OmJhc2ljX3N0cmluZzx1bnNpZ25lZCBjaGFyPgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxzaWduZWQgY2hhcj4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8bG9uZz4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgbG9uZz4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8ZG91YmxlPgB2ZWMyIGMgPSB2X3RleENvb3JkOwB2ZWMyIGMgPSB2ZWMyKDEuMCAtIHZfdGV4Q29vcmQueCwgdl90ZXhDb29yZC55KTsAYyA9IHZlYzIoMS4wIC0gYy54LCAxLjAgLSBjLnkpOwBjID0gdmVjMihjLnksIDEuMCAtIGMueCk7AGMgPSB2ZWMyKDEuMCAtIGMueSwgYy54KTsAQWxsSW4xAC4ALjAsAC4wKSpvKSoAKG51bGwpACkqby55KTsgICAgdmVjMiBjb29yZDIgPSB2ZWMyKGZsb2F0KAAgICAgYyA9IHZlYzIodl90ZXhDb29yZC54LCAxLjAgLSB2X3RleENvb3JkLnkpOyAgICB2ZWMyIGNvb3JkMSA9IHZlYzIoZmxvYXQoACksIChjLnkgLWNvb3JkMS55KSAvIG8ueSAvIGZsb2F0KAApKm8ueSk7ICAgIGlmIChjLnggPiBjb29yZDEueCAmJiBjLnggPCBjb29yZDIueCAmJiBjLnkgPiBjb29yZDEueSAmJiBjLnkgPCBjb29yZDIueSkgeyAgICAgIHZlYzQgd2F0ZXJDb2xvciA9IHRleHR1cmUod2F0ZXJNYXJrLCB2ZWMyKChjLnggLSBjb29yZDEueCkgIC8gby54IC8gZmxvYXQoACkgKiBvLngsIGZsb2F0KABvdXRDb2xvci5yZ2IgKz0gdmVjMygAKTsgICAgICAgdmVjMyBzbW9vdGhDb2xvciA9IG91dENvbG9yLnJnYiArIChvdXRDb2xvci5yZ2ItdmVjMyhoaWdoUGFzcykpKmFscGhhKjAuMTsgICAgICAgc21vb3RoQ29sb3IgPSBtYXgoc21vb3RoQ29sb3IsIHZlYzMoMC4wKSk7ICAgICAgIHNtb290aENvbG9yID0gY2xhbXAocG93KHNtb290aENvbG9yLCB2ZWMzKABnKz1HKGMsdmVjMigAICAgICAgdmVjMiBvZmZzZXQgPSB2ZWMyKABdID0gdl90ZXhDb29yZC54eSArIG9mZnNldCAqIHZlYzIoADsgACkpLCB2ZWMzKDAuMCksIHZlYzMoMS4wKSk7ICAgICAgdmVjMyBzY3JlZW4gPSB2ZWMzKDEuMCkgLSAodmVjMygxLjApLXNtb290aENvbG9yKSAqICh2ZWMzKDEuMCktb3V0Q29sb3IucmdiKTsgICAgICAgdmVjMyBsaWdodGVuID0gbWF4KHNtb290aENvbG9yLCBvdXRDb2xvci5yZ2IpOyAgICAgICB2ZWMzIGJlYXV0eUNvbG9yID0gbWl4KG1peChvdXRDb2xvci5yZ2IsIHNjcmVlbiwgYWxwaGEpLCBsaWdodGVuLCBhbHBoYSk7ICAgICAgb3V0Q29sb3IucmdiID0gbWl4KG91dENvbG9yLnJnYiwgYmVhdXR5Q29sb3IsIAAKICAgICAgY29uc3QgbWF0MyBzYXR1cmF0ZU1hdHJpeCA9IG1hdDMoMS4xMTAyLC0wLjA1OTgsLTAuMDYxLC0wLjA3NzQsMS4wODI2LC0wLjExODYsLTAuMDIyOCwtMC4wMjI4LDEuMTc3Mik7CiAgICAgIHZlYzMgd2FybUNvbG9yID0gb3V0Q29sb3IucmdiICogc2F0dXJhdGVNYXRyaXg7CiAgICAgIG91dENvbG9yLnJnYiA9IG1peChvdXRDb2xvci5yZ2IsIHdhcm1Db2xvciwgACAgICAgIHNhbXBsZUNvbG9yID0gc2FtcGxlQ29sb3IgLyA2Mi4wOyAgICAgICBmbG9hdCBoaWdoUGFzcyA9IG91dENvbG9yLmcgLSBzYW1wbGVDb2xvciArIDAuNTsgICAgICAgY29uc3QgaGlnaHAgdmVjMyBXID0gdmVjMygwLjI5OSwwLjU4NywwLjExNCk7ICAgICAgZmxvYXQgbHVtaW5hbmNlID0gZG90KG91dENvbG9yLnJnYiwgVyk7ICAgICAgIGZsb2F0IGFscGhhID0gcG93KGx1bWluYW5jZSwgAF0pLmcgKiAAKSkpOyAgICAgIG91dENvbG9yID0gbWl4KG91dENvbG9yLHdhdGVyQ29sb3IsICB3YXRlckNvbG9yLmEpOyAgICB9ICAgIAApOyAgICAAKTsgICAgICB2ZWMyIGJsdXJDb29yZGluYXRlc1syNF07ICAgICAgACAgICAgIGZsb2F0IHNhbXBsZUNvbG9yID0gb3V0Q29sb3IuZyAqIDIyLjA7ICAgICAgIAAjdmVyc2lvbiAzMDAgZXMKICAgIHByZWNpc2lvbiBoaWdocCBmbG9hdDsKICAgIHVuaWZvcm0gc2FtcGxlcjJEIGZyYW1lOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgbWFzazsKICAgIHVuaWZvcm0gc2FtcGxlcjJEIGJnOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgd2F0ZXJNYXJrOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgbGFzdE1hc2s7CiAgICB1bmlmb3JtIG1hdDQgdV9vZmZzZXRNYXRyaXg7CiAgICB1bmlmb3JtIHZlYzMgdV9jb2xvcjsKICAgIGluIHZlYzIgdl90ZXhDb29yZDsKICAgIG91dCB2ZWM0IG91dENvbG9yOwogICAgdmVjNCBHKHZlYzIgYyx2ZWMyIHMpewogICAgICByZXR1cm4gdGV4dHVyZShmcmFtZSx0ZXh0dXJlKG1hc2ssYytzKS5yPjAuMz9jOmMrcyk7CiAgICB9CiAgICB2b2lkIG1haW4oKSB7CiAgICAgIAAKICAgICAgdmVjMiBvZmZzZXRNYXNrVVYgPSAodV9vZmZzZXRNYXRyaXggKiB2ZWM0KGMsIDAsIDEpKS54eTsKICAgICAgZmxvYXQgaXNJbnNpZGVYID0gKG9mZnNldE1hc2tVVi54ID49IDAuMCkgJiYgKG9mZnNldE1hc2tVVi54IDw9IDEuMCkgPyAxLjAgOiAwLjA7CiAgICAgIGZsb2F0IGlzSW5zaWRlWSA9IChvZmZzZXRNYXNrVVYueSA+PSAwLjApICYmIChvZmZzZXRNYXNrVVYueSA8PSAxLjApID8gMS4wIDogMC4wOwogICAgICBmbG9hdCBpc0luc2lkZSA9IGlzSW5zaWRlWCAqIGlzSW5zaWRlWTsKICAgICAgZmxvYXQgbWFza2VkQWxwaGEgPSB0ZXh0dXJlKG1hc2ssIG9mZnNldE1hc2tVVikuciAqIGlzSW5zaWRlOwogICAgICBtYXNrZWRBbHBoYSA9IG1hc2tlZEFscGhhPDAuNT8yLjAqbWFza2VkQWxwaGEqbWFza2VkQWxwaGE6MS4wLTIuMCooMS4wLW1hc2tlZEFscGhhKSooMS4wLW1hc2tlZEFscGhhKTsKICAgICAgc3JjX2NvbG9yID0gdGV4dHVyZShmcmFtZSwgb2Zmc2V0TWFza1VWICwgaXNJbnNpZGUpOwogICAgICBvdXRDb2xvciA9IG1peCh0ZXh0dXJlKGJnLCBjKSwgc3JjX2NvbG9yLCBtYXNrZWRBbHBoYSk7CiAgICAACiAgICB2ZWM0IGcgPSB2ZWM0KDAuMCk7CiAgICAACiAgICAgIGMueSA9IDEuMCAtIGMueTsKICAgICAgdmVjNCBzcmNfY29sb3IgPSB0ZXh0dXJlKGZyYW1lLCBjKTsKICAgICAgZmxvYXQgYSA9IHRleHR1cmUobWFzaywgYykucjsKICAgICAgYSA9IGE8MC41PzIuMCphKmE6MS4wLTIuMCooMS4wLWEpKigxLjAtYSk7CiAgICAgIC8vIGZsb2F0IGEyID0gdGV4dHVyZShsYXN0TWFzaywgYykuYTsKICAgICAgLy8gYTIgPSBhMjwwLjU/Mi4wKmEyKmEyOjEuMC0yLjAqKDEuMC1hMikqKDEuMC1hMik7CiAgICAgIC8vIGZsb2F0IGRlbHRhID0gYSAtIGEyOwogICAgICAvLyBpZiAoZGVsdGEgPCAwLjI1ICYmIGRlbHRhID4gLTAuMjUpCiAgICAgIC8vIHsKICAgICAgLy8gICAgIGEgPSBhICsgMC41KmRlbHRhOwogICAgICAvLyB9CiAgICAgIAogICAgICB2ZWMyIG8gPSAxLjAgLyB2ZWMyKHRleHR1cmVTaXplKGZyYW1lLCAwKSk7CiAgICAACiAgICAgIG91dENvbG9yID0gZzsKICAAI3ZlcnNpb24gMzAwIGVzCmluIHZlYzIgYV9wb3NpdGlvbjsKaW4gdmVjMiBhX3RleENvb3JkOwoKdW5pZm9ybSBtYXQ0IHVfdGV4dHVyZU1hdHJpeDsKCm91dCB2ZWMyIHZfdGV4Q29vcmQ7CnZvaWQgbWFpbigpIHsKICBnbF9Qb3NpdGlvbiA9IHZlYzQoYV9wb3NpdGlvbi54LCBhX3Bvc2l0aW9uLnksIDAsIDEpOwogIHZfdGV4Q29vcmQgPSh1X3RleHR1cmVNYXRyaXggKiB2ZWM0KGFfdGV4Q29vcmQsIDAsIDEpKS54eTsKfQoAc2V0QmVhdXR5ICVmICVmICVmICVmICVmCgBvdXRDb2xvciA9IHNyY19jb2xvcjsKAG91dENvbG9yID0gbWl4KHZlYzQodV9jb2xvciwxLjApLHNyY19jb2xvcixhKTsKADZBbGxJbjEAAIAoAABfFgAAUDZBbGxJbjEAAAAABCkAAHAWAAAAAAAAaBYAAFBLNkFsbEluMQAAAAQpAACMFgAAAQAAAGgWAABpaQB2AHZpAHwWAADMFgAATjEwZW1zY3JpcHRlbjN2YWxFAACAKAAAuBYAAGlpaQB2aWlpAAAAALwnAAB8FgAAcCgAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkZABBkC4LyAi8JwAAfBYAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkALwnAAB8FgAAdmlpALwnAADMFgAAzBYAAHwWAADMFgAAHCgAALwnAADMFgAAoBcAAE5TdDNfXzIxMmJhc2ljX3N0cmluZ0ljTlNfMTFjaGFyX3RyYWl0c0ljRUVOU185YWxsb2NhdG9ySWNFRUVFAACAKAAAYBcAAMwWAAC8JwAAzBYAAMwWAABOU3QzX18yMTJiYXNpY19zdHJpbmdJaE5TXzExY2hhcl90cmFpdHNJaEVFTlNfOWFsbG9jYXRvckloRUVFRQAAgCgAALgXAABOU3QzX18yMTJiYXNpY19zdHJpbmdJd05TXzExY2hhcl90cmFpdHNJd0VFTlNfOWFsbG9jYXRvckl3RUVFRQAAgCgAAAAYAABOU3QzX18yMTJiYXNpY19zdHJpbmdJRHNOU18xMWNoYXJfdHJhaXRzSURzRUVOU185YWxsb2NhdG9ySURzRUVFRQAAAIAoAABIGAAATlN0M19fMjEyYmFzaWNfc3RyaW5nSURpTlNfMTFj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")||(Je=ae,ae=I.locateFile?I.locateFile(Je,m):m+Je);var ki=$=>{for(;$.length>0;)$.shift()(I)};I.noExitRuntime;function ao($){this.excPtr=$,this.ptr=$-24,this.set_type=function(j){vA[this.ptr+4>>2]=j},this.get_type=function(){return vA[this.ptr+4>>2]},this.set_destructor=function(j){vA[this.ptr+8>>2]=j},this.get_destructor=function(){return vA[this.ptr+8>>2]},this.set_caught=function(j){j=j?1:0,cA[this.ptr+12|0]=j},this.get_caught=function(){return cA[this.ptr+12|0]!=0},this.set_rethrown=function(j){j=j?1:0,cA[this.ptr+13|0]=j},this.get_rethrown=function(){return cA[this.ptr+13|0]!=0},this.init=function(j,RA){this.set_adjusted_ptr(0),this.set_type(j),this.set_destructor(RA)},this.set_adjusted_ptr=function(j){vA[this.ptr+16>>2]=j},this.get_adjusted_ptr=function(){return vA[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Oa(this.get_type()))return vA[this.excPtr>>2];var j=this.get_adjusted_ptr();return j!==0?j:this.excPtr}}var Ji,Vi,wn,Fi=$=>{for(var j="",RA=$;eA[RA];)j+=Ji[eA[RA++]];return j},en={},Ro={},oo={},Ai=$=>{throw new Vi($)},no=$=>{throw new wn($)},Ri=($,j,RA)=>{function ZA(qe){var Et=RA(qe);Et.length!==$.length&&no("Mismatched type converter count");for(var ft=0;ft<$.length;++ft)pn($[ft],Et[ft])}$.forEach(function(qe){oo[qe]=j});var ne=new Array(j.length),De=[],Ke=0;j.forEach((qe,Et)=>{Ro.hasOwnProperty(qe)?ne[Et]=Ro[qe]:(De.push(qe),en.hasOwnProperty(qe)||(en[qe]=[]),en[qe].push(()=>{ne[Et]=Ro[qe],++Ke===De.length&&ZA(ne)}))}),De.length===0&&ZA(ne)};function pn($,j,RA={}){if(!("argPackAdvance"in j))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(ZA,ne,De={}){var Ke=ne.name;if(ZA||Ai(`type "${Ke}" must have a positive integer typeid pointer`),Ro.hasOwnProperty(ZA)){if(De.ignoreDuplicateRegistrations)return;Ai(`Cannot register type '${Ke}' twice`)}if(Ro[ZA]=ne,delete oo[ZA],en.hasOwnProperty(ZA)){var qe=en[ZA];delete en[ZA],qe.forEach(Et=>Et())}}($,j,RA)}var jA,ue=$=>{Ai($.$$.ptrType.registeredClass.name+" instance already deleted")},He=!1,Lt=$=>{},ct=$=>{$.count.value-=1,$.count.value===0&&(j=>{j.smartPtr?j.smartPtrType.rawDestructor(j.smartPtr):j.ptrType.registeredClass.rawDestructor(j.ptr)})($)},Ct=($,j,RA)=>{if(j===RA)return $;if(RA.baseClass===void 0)return null;var ZA=Ct($,j,RA.baseClass);return ZA===null?null:RA.downcast(ZA)},ei={},Ht=()=>Object.keys(Hi).length,Le=()=>{var $=[];for(var j in Hi)Hi.hasOwnProperty(j)&&$.push(Hi[j]);return $},it=[],Tt=()=>{for(;it.length;){var $=it.pop();$.$$.deleteScheduled=!1,$.delete()}},Gt=$=>{jA=$,it.length&&jA&&jA(Tt)},Hi={},po=($,j)=>(j=((RA,ZA)=>{for(ZA===void 0&&Ai("ptr should not be undefined");RA.baseClass;)ZA=RA.upcast(ZA),RA=RA.baseClass;return ZA})($,j),Hi[j]),To=($,j)=>(j.ptrType&&j.ptr||no("makeClassHandle requires ptr and ptrType"),!!j.smartPtrType!=!!j.smartPtr&&no("Both smartPtrType and smartPtr must be specified"),j.count={value:1},wo(Object.create($,{$$:{value:j}})));function Zi($){var j=this.getPointee($);if(!j)return this.destructor($),null;var RA=po(this.registeredClass,j);if(RA!==void 0){if(RA.$$.count.value===0)return RA.$$.ptr=j,RA.$$.smartPtr=$,RA.clone();var ZA=RA.clone();return this.destructor($),ZA}function ne(){return this.isSmartPointer?To(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:j,smartPtrType:this,smartPtr:$}):To(this.registeredClass.instancePrototype,{ptrType:this,ptr:$})}var De,Ke=this.registeredClass.getActualType(j),qe=ei[Ke];if(!qe)return ne.call(this);De=this.isConst?qe.constPointerType:qe.pointerType;var Et=Ct(j,this.registeredClass,De.registeredClass);return Et===null?ne.call(this):this.isSmartPointer?To(De.registeredClass.instancePrototype,{ptrType:De,ptr:Et,smartPtrType:this,smartPtr:$}):To(De.registeredClass.instancePrototype,{ptrType:De,ptr:Et})}var wo=$=>typeof FinalizationRegistry>"u"?(wo=j=>j,$):(He=new FinalizationRegistry(j=>{ct(j.$$)}),Lt=j=>He.unregister(j),(wo=j=>{var RA=j.$$;if(RA.smartPtr){var ZA={$$:RA};He.register(j,ZA,j)}return j})($));function Cn(){}var an=($,j)=>Object.defineProperty(j,"name",{value:$}),Vo=($,j,RA)=>{if($[j].overloadTable===void 0){var ZA=$[j];$[j]=function(){return $[j].overloadTable.hasOwnProperty(arguments.length)||Ai(`Function '${RA}' called with an invalid number of arguments (${arguments.length}) - expects one of (${$[j].overloadTable})!`),$[j].overloadTable[arguments.length].apply(this,arguments)},$[j].overloadTable=[],$[j].overloadTable[ZA.argCount]=ZA}};function jn($,j,RA,ZA,ne,De,Ke,qe){this.name=$,this.constructor=j,this.instancePrototype=RA,this.rawDestructor=ZA,this.baseClass=ne,this.getActualType=De,this.upcast=Ke,this.downcast=qe,this.pureVirtualFunctions=[]}var vo=($,j,RA)=>{for(;j!==RA;)j.upcast||Ai(`Expected null or instance of ${RA.name}, got an instance of ${j.name}`),$=j.upcast($),j=j.baseClass;return $};function mA($,j){if(j===null)return this.isReference&&Ai(`null is not a valid ${this.name}`),0;j.$$||Ai(`Cannot pass "${ce(j)}" as a ${this.name}`),j.$$.ptr||Ai(`Cannot pass deleted object as a pointer of type ${this.name}`);var RA=j.$$.ptrType.registeredClass;return vo(j.$$.ptr,RA,this.registeredClass)}function xs($,j){var RA;if(j===null)return this.isReference&&Ai(`null is not a valid ${this.name}`),this.isSmartPointer?(RA=this.rawConstructor(),$!==null&&$.push(this.rawDestructor,RA),RA):0;j.$$||Ai(`Cannot pass "${ce(j)}" as a ${this.name}`),j.$$.ptr||Ai(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&j.$$.ptrType.isConst&&Ai(`Cannot convert argument of type ${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type ${this.name}`);var ZA=j.$$.ptrType.registeredClass;if(RA=vo(j.$$.ptr,ZA,this.registeredClass),this.isSmartPointer)switch(j.$$.smartPtr===void 0&&Ai("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:j.$$.smartPtrType===this?RA=j.$$.smartPtr:Ai(`Cannot convert argument of type ${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:RA=j.$$.smartPtr;break;case 2:if(j.$$.smartPtrType===this)RA=j.$$.smartPtr;else{var ne=j.clone();RA=this.rawShare(RA,ts.toHandle(()=>ne.delete())),$!==null&&$.push(this.rawDestructor,RA)}break;default:Ai("Unsupporting sharing policy")}return RA}function Zs($,j){if(j===null)return this.isReference&&Ai(`null is not a valid ${this.name}`),0;j.$$||Ai(`Cannot pass "${ce(j)}" as a ${this.name}`),j.$$.ptr||Ai(`Cannot pass deleted object as a pointer of type ${this.name}`),j.$$.ptrType.isConst&&Ai(`Cannot convert argument of type ${j.$$.ptrType.name} to parameter type ${this.name}`);var RA=j.$$.ptrType.registeredClass;return vo(j.$$.ptr,RA,this.registeredClass)}function mn($){return this.fromWireType(vA[$>>2])}function Fr($,j,RA,ZA,ne,De,Ke,qe,Et,ft,Nt){this.name=$,this.registeredClass=j,this.isReference=RA,this.isConst=ZA,this.isSmartPointer=ne,this.pointeeType=De,this.sharingPolicy=Ke,this.rawGetPointee=qe,this.rawConstructor=Et,this.rawShare=ft,this.rawDestructor=Nt,ne||j.baseClass!==void 0?this.toWireType=xs:ZA?(this.toWireType=mA,this.destructorFunction=null):(this.toWireType=Zs,this.destructorFunction=null)}var qi,tn,Ks=[],_n=$=>{var j=Ks[$];return j||($>=Ks.length&&(Ks.length=$+1),Ks[$]=j=qi.get($)),j},Is=($,j,RA)=>$.includes("j")?((ZA,ne,De)=>{var Ke=I["dynCall_"+ZA];return De&&De.length?Ke.apply(null,[ne].concat(De)):Ke.call(null,ne)})($,j,RA):_n(j).apply(null,RA),qt=($,j)=>{var RA,ZA,ne,De=($=Fi($)).includes("j")?(RA=$,ZA=j,ne=[],function(){return ne.length=0,Object.assign(ne,arguments),Is(RA,ZA,ne)}):_n(j);return typeof De!="function"&&Ai(`unknown function pointer with signature ${$}: ${j}`),De},$a=$=>{var j=pa($),RA=Fi(j);return _s(j),RA},Ls=($,j)=>{var RA=[],ZA={};throw j.forEach(function ne(De){ZA[De]||Ro[De]||(oo[De]?oo[De].forEach(ne):(RA.push(De),ZA[De]=!0))}),new tn(`${$}: `+RA.map($a).join([", "]))},Bs=($,j)=>{for(var RA=[],ZA=0;ZA<$;ZA++)RA.push(vA[j+4*ZA>>2]);return RA},Un=$=>{for(;$.length;){var j=$.pop();$.pop()(j)}};function Ir($,j,RA,ZA,ne,De){var Ke=j.length;Ke<2&&Ai("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var qe=j[1]!==null&&RA!==null,Et=!1,ft=1;ft($ instanceof Object||Ai(`${RA} with invalid "this": ${$}`),$ instanceof j.registeredClass.constructor||Ai(`${RA} incompatible with "this" of type ${$.constructor.name}`),$.$$.ptr||Ai(`cannot call emscripten binding method ${RA} on deleted object`),vo($.$$.ptr,$.$$.ptrType.registeredClass,j.registeredClass));function rr(){this.allocated=[void 0],this.freelist=[]}var fo=new rr,es=$=>{$>=fo.reserved&&--fo.get($).refcount===0&&fo.free($)},vc=()=>{for(var $=0,j=fo.reserved;j($||Ai("Cannot use deleted val. handle = "+$),fo.get($).value),toHandle:$=>{switch($){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return fo.allocate({refcount:1,value:$})}}};function ur($){return this.fromWireType(oA[$>>2])}var On,vg,yn,ce=$=>{if($===null)return"null";var j=typeof $;return j==="object"||j==="array"||j==="function"?$.toString():""+$},ot=($,j)=>{switch(j){case 4:return function(RA){return this.fromWireType(qA[RA>>2])};case 8:return function(RA){return this.fromWireType(Ae[RA>>3])};default:throw new TypeError(`invalid float width (${j}): ${$}`)}},Zt=($,j,RA)=>{switch(j){case 1:return RA?ZA=>cA[ZA|0]:ZA=>eA[ZA|0];case 2:return RA?ZA=>CA[ZA>>1]:ZA=>IA[ZA>>1];case 4:return RA?ZA=>oA[ZA>>2]:ZA=>vA[ZA>>2];default:throw new TypeError(`invalid integer width (${j}): ${$}`)}},Ho=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ba=($,j,RA)=>{for(var ZA=j+RA,ne=j;$[ne]&&!(ne>=ZA);)++ne;if(ne-j>16&&$.buffer&&Ho)return Ho.decode($.subarray(j,ne));for(var De="";j>10,56320|1023&ft)}}else De+=String.fromCharCode((31&Ke)<<6|qe)}else De+=String.fromCharCode(Ke)}return De},WI=($,j)=>$?Ba(eA,$,j):"",gn=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,ro=($,j)=>{for(var RA=$,ZA=RA>>1,ne=ZA+j/2;!(ZA>=ne)&&IA[ZA];)++ZA;if((RA=ZA<<1)-$>32&&gn)return gn.decode(eA.subarray($,RA));for(var De="",Ke=0;!(Ke>=j/2);++Ke){var qe=CA[$+2*Ke>>1];if(qe==0)break;De+=String.fromCharCode(qe)}return De},Mc=($,j,RA)=>{if(RA===void 0&&(RA=2147483647),RA<2)return 0;for(var ZA=j,ne=(RA-=2)<2*$.length?RA/2:$.length,De=0;De>1]=Ke,j+=2}return CA[j>>1]=0,j-ZA},gg=$=>2*$.length,Mg=($,j)=>{for(var RA=0,ZA="";!(RA>=j/4);){var ne=oA[$+4*RA>>2];if(ne==0)break;if(++RA,ne>=65536){var De=ne-65536;ZA+=String.fromCharCode(55296|De>>10,56320|1023&De)}else ZA+=String.fromCharCode(ne)}return ZA},Qa=($,j,RA)=>{if(RA===void 0&&(RA=2147483647),RA<4)return 0;for(var ZA=j,ne=ZA+RA-4,De=0;De<$.length;++De){var Ke=$.charCodeAt(De);if(Ke>=55296&&Ke<=57343&&(Ke=65536+((1023&Ke)<<10)|1023&$.charCodeAt(++De)),oA[j>>2]=Ke,(j+=4)+4>ne)break}return oA[j>>2]=0,j-ZA},Fo=$=>{for(var j=0,RA=0;RA<$.length;++RA){var ZA=$.charCodeAt(RA);ZA>=55296&&ZA<=57343&&++RA,j+=4}return j},Aa=($,j)=>{var RA=Ro[$];return RA===void 0&&Ai(j+" has unknown type "+$a($)),RA},Uo=($,j,RA)=>{var ZA=[],ne=$.toWireType(ZA,RA);return ZA.length&&(vA[j>>2]=ts.toHandle(ZA)),ne},Zc={},Xs=[],is=Reflect.construct,Rg=[null,[],[]],Rc=($,j)=>{var RA=Rg[$];j===0||j===10?(($===1?T:b)(Ba(RA,0)),RA.length=0):RA.push(j)};(()=>{for(var $=new Array(256),j=0;j<256;++j)$[j]=String.fromCharCode(j);Ji=$})(),Vi=I.BindingError=class extends Error{constructor($){super($),this.name="BindingError"}},wn=I.InternalError=class extends Error{constructor($){super($),this.name="InternalError"}},Object.assign(Cn.prototype,{isAliasOf($){if(!(this instanceof Cn)||!($ instanceof Cn))return!1;var j=this.$$.ptrType.registeredClass,RA=this.$$.ptr;$.$$=$.$$;for(var ZA=$.$$.ptrType.registeredClass,ne=$.$$.ptr;j.baseClass;)RA=j.upcast(RA),j=j.baseClass;for(;ZA.baseClass;)ne=ZA.upcast(ne),ZA=ZA.baseClass;return j===ZA&&RA===ne},clone(){if(this.$$.ptr||ue(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var $,j=wo(Object.create(Object.getPrototypeOf(this),{$$:{value:($=this.$$,{count:$.count,deleteScheduled:$.deleteScheduled,preservePointerOnDelete:$.preservePointerOnDelete,ptr:$.ptr,ptrType:$.ptrType,smartPtr:$.smartPtr,smartPtrType:$.smartPtrType})}}));return j.$$.count.value+=1,j.$$.deleteScheduled=!1,j},delete(){this.$$.ptr||ue(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ai("Object already scheduled for deletion"),Lt(this),ct(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||ue(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ai("Object already scheduled for deletion"),it.push(this),it.length===1&&jA&&jA(Tt),this.$$.deleteScheduled=!0,this}}),I.getInheritedInstanceCount=Ht,I.getLiveInheritedInstances=Le,I.flushPendingDeletes=Tt,I.setDelayFunction=Gt,Object.assign(Fr.prototype,{getPointee($){return this.rawGetPointee&&($=this.rawGetPointee($)),$},destructor($){this.rawDestructor&&this.rawDestructor($)},argPackAdvance:8,readValueFromPointer:mn,deleteObject($){$!==null&&$.delete()},fromWireType:Zi}),tn=I.UnboundTypeError=(On=Error,(yn=an(vg="UnboundTypeError",function($){this.name=vg,this.message=$;var j=new Error($).stack;j!==void 0&&(this.stack=this.toString()+` -`+j.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(On.prototype),yn.prototype.constructor=yn,yn.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},yn),Object.assign(rr.prototype,{get($){return this.allocated[$]},has($){return this.allocated[$]!==void 0},allocate($){var j=this.freelist.pop()||this.allocated.length;return this.allocated[j]=$,j},free($){this.allocated[$]=void 0,this.freelist.push($)}}),fo.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),fo.reserved=fo.allocated.length,I.count_emval_handles=vc;var ws,Fa={w:($,j,RA)=>{throw new ao($).init(j,RA),$},q:($,j,RA,ZA,ne)=>{},u:($,j,RA,ZA)=>{pn($,{name:j=Fi(j),fromWireType:function(ne){return!!ne},toWireType:function(ne,De){return De?RA:ZA},argPackAdvance:8,readValueFromPointer:function(ne){return this.fromWireType(eA[ne])},destructorFunction:null})},y:($,j,RA,ZA,ne,De,Ke,qe,Et,ft,Nt,Kt,di)=>{Nt=Fi(Nt),De=qt(ne,De),qe&&(qe=qt(Ke,qe)),ft&&(ft=qt(Et,ft)),di=qt(Kt,di);var Bt=(Jt=>{if(Jt===void 0)return"_unknown";var $i=(Jt=Jt.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return $i>=48&&$i<=57?`_${Jt}`:Jt})(Nt);((Jt,$i,eo)=>{I.hasOwnProperty(Jt)?(Ai(`Cannot register public name '${Jt}' twice`),Vo(I,Jt,Jt),I.hasOwnProperty(eo)&&Ai(`Cannot register multiple overloads of a function with the same number of arguments (${eo})!`),I[Jt].overloadTable[eo]=$i):I[Jt]=$i})(Bt,function(){Ls(`Cannot construct ${Nt} due to unbound types`,[ZA])}),Ri([$,j,RA],ZA?[ZA]:[],function(Jt){var $i,eo;Jt=Jt[0],eo=ZA?($i=Jt.registeredClass).instancePrototype:Cn.prototype;var os=an(Nt,function(){if(Object.getPrototypeOf(this)!==Ti)throw new Vi("Use 'new' to construct "+Nt);if(on.constructor_body===void 0)throw new Vi(Nt+" has no accessible constructor");var js=on.constructor_body[arguments.length];if(js===void 0)throw new Vi(`Tried to invoke ctor of ${Nt} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(on.constructor_body).toString()}) parameters instead!`);return js.apply(this,arguments)}),Ti=Object.create(eo,{constructor:{value:os}});os.prototype=Ti;var on=new jn(Nt,os,Ti,di,$i,De,qe,ft);on.baseClass&&(on.baseClass.__derivedClasses===void 0&&(on.baseClass.__derivedClasses=[]),on.baseClass.__derivedClasses.push(on));var wg=new Fr(Nt,on,!0,!1,!1),Er=new Fr(Nt+"*",on,!1,!1,!1),Mr=new Fr(Nt+" const*",on,!1,!0,!1);return ei[$]={pointerType:Er,constPointerType:Mr},((js,Tl,ns)=>{I.hasOwnProperty(js)||no("Replacing nonexistant public symbol"),I[js].overloadTable!==void 0&&ns!==void 0?I[js].overloadTable[ns]=Tl:(I[js]=Tl,I[js].argCount=ns)})(Bt,os),[wg,Er,Mr]})},x:($,j,RA,ZA,ne,De)=>{var Ke=Bs(j,RA);ne=qt(ZA,ne),Ri([],[$],function(qe){var Et=`constructor ${(qe=qe[0]).name}`;if(qe.registeredClass.constructor_body===void 0&&(qe.registeredClass.constructor_body=[]),qe.registeredClass.constructor_body[j-1]!==void 0)throw new Vi(`Cannot register multiple constructors with identical number of parameters (${j-1}) for class '${qe.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return qe.registeredClass.constructor_body[j-1]=()=>{Ls(`Cannot construct ${qe.name} due to unbound types`,Ke)},Ri([],Ke,ft=>(ft.splice(1,0,null),qe.registeredClass.constructor_body[j-1]=Ir(Et,ft,null,ne,De),[])),[]})},i:($,j,RA,ZA,ne,De,Ke,qe,Et)=>{var ft=Bs(RA,ZA);j=(Nt=>{const Kt=(Nt=Nt.trim()).indexOf("(");return Kt!==-1?Nt.substr(0,Kt):Nt})(j=Fi(j)),De=qt(ne,De),Ri([],[$],function(Nt){var Kt=`${(Nt=Nt[0]).name}.${j}`;function di(){Ls(`Cannot call ${Kt} due to unbound types`,ft)}j.startsWith("@@")&&(j=Symbol[j.substring(2)]),qe&&Nt.registeredClass.pureVirtualFunctions.push(j);var Bt=Nt.registeredClass.instancePrototype,Jt=Bt[j];return Jt===void 0||Jt.overloadTable===void 0&&Jt.className!==Nt.name&&Jt.argCount===RA-2?(di.argCount=RA-2,di.className=Nt.name,Bt[j]=di):(Vo(Bt,j,Kt),Bt[j].overloadTable[RA-2]=di),Ri([],ft,function($i){var eo=Ir(Kt,$i,Nt,De,Ke);return Bt[j].overloadTable===void 0?(eo.argCount=RA-2,Bt[j]=eo):Bt[j].overloadTable[RA-2]=eo,[]}),[]})},k:($,j,RA,ZA,ne,De,Ke,qe,Et,ft)=>{j=Fi(j),ne=qt(ZA,ne),Ri([],[$],function(Nt){var Kt=`${(Nt=Nt[0]).name}.${j}`,di={get(){Ls(`Cannot access ${Kt} due to unbound types`,[RA,Ke])},enumerable:!0,configurable:!0};return di.set=Et?()=>Ls(`Cannot access ${Kt} due to unbound types`,[RA,Ke]):Bt=>Ai(Kt+" is a read-only property"),Object.defineProperty(Nt.registeredClass.instancePrototype,j,di),Ri([],Et?[RA,Ke]:[RA],function(Bt){var Jt=Bt[0],$i={get(){var os=Fn(this,Nt,Kt+" getter");return Jt.fromWireType(ne(De,os))},enumerable:!0};if(Et){Et=qt(qe,Et);var eo=Bt[1];$i.set=function(os){var Ti=Fn(this,Nt,Kt+" setter"),on=[];Et(ft,Ti,eo.toWireType(on,os)),Un(on)}}return Object.defineProperty(Nt.registeredClass.instancePrototype,j,$i),[]}),[]})},t:($,j)=>{pn($,{name:j=Fi(j),fromWireType:RA=>{var ZA=ts.toValue(RA);return es(RA),ZA},toWireType:(RA,ZA)=>ts.toHandle(ZA),argPackAdvance:8,readValueFromPointer:ur,destructorFunction:null})},p:($,j,RA)=>{pn($,{name:j=Fi(j),fromWireType:ZA=>ZA,toWireType:(ZA,ne)=>ne,argPackAdvance:8,readValueFromPointer:ot(j,RA),destructorFunction:null})},g:($,j,RA,ZA,ne)=>{j=Fi(j);var De=Et=>Et;if(ZA===0){var Ke=32-8*RA;De=Et=>Et<>>Ke}var qe=j.includes("unsigned");pn($,{name:j,fromWireType:De,toWireType:qe?function(Et,ft){return this.name,ft>>>0}:function(Et,ft){return this.name,ft},argPackAdvance:8,readValueFromPointer:Zt(j,RA,ZA!==0),destructorFunction:null})},a:($,j,RA)=>{var ZA=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][j];function ne(De){var Ke=vA[De>>2],qe=vA[De+4>>2];return new ZA(cA.buffer,qe,Ke)}pn($,{name:RA=Fi(RA),fromWireType:ne,argPackAdvance:8,readValueFromPointer:ne},{ignoreDuplicateRegistrations:!0})},o:($,j)=>{var RA=(j=Fi(j))==="std::string";pn($,{name:j,fromWireType(ZA){var ne,De=vA[ZA>>2],Ke=ZA+4;if(RA)for(var qe=Ke,Et=0;Et<=De;++Et){var ft=Ke+Et;if(Et==De||eA[ft]==0){var Nt=WI(qe,ft-qe);ne===void 0?ne=Nt:(ne+="\0",ne+=Nt),qe=ft+1}}else{var Kt=new Array(De);for(Et=0;Et{for(var di=0,Bt=0;Bt=55296&&Jt<=57343?(di+=4,++Bt):di+=3}return di})(ne):ne.length;var qe=Tn(4+De+1),Et=qe+4;if(vA[qe>>2]=De,RA&&Ke)((Kt,di,Bt,Jt)=>{if(!(Jt>0))return 0;for(var $i=Bt,eo=Bt+Jt-1,os=0;os=55296&&Ti<=57343&&(Ti=65536+((1023&Ti)<<10)|1023&Kt.charCodeAt(++os)),Ti<=127){if(Bt>=eo)break;di[Bt++]=Ti}else if(Ti<=2047){if(Bt+1>=eo)break;di[Bt++]=192|Ti>>6,di[Bt++]=128|63&Ti}else if(Ti<=65535){if(Bt+2>=eo)break;di[Bt++]=224|Ti>>12,di[Bt++]=128|Ti>>6&63,di[Bt++]=128|63&Ti}else{if(Bt+3>=eo)break;di[Bt++]=240|Ti>>18,di[Bt++]=128|Ti>>12&63,di[Bt++]=128|Ti>>6&63,di[Bt++]=128|63&Ti}}di[Bt]=0})(ne,eA,Et,De+1);else if(Ke)for(var ft=0;ft255&&(_s(Et),Ai("String has UTF-16 code units that do not fit in 8 bits")),eA[Et+ft]=Nt}else for(ft=0;ft{var ZA,ne,De,Ke,qe;RA=Fi(RA),j===2?(ZA=ro,ne=Mc,Ke=gg,De=()=>IA,qe=1):j===4&&(ZA=Mg,ne=Qa,Ke=Fo,De=()=>vA,qe=2),pn($,{name:RA,fromWireType:Et=>{for(var ft,Nt=vA[Et>>2],Kt=De(),di=Et+4,Bt=0;Bt<=Nt;++Bt){var Jt=Et+4+Bt*j;if(Bt==Nt||Kt[Jt>>qe]==0){var $i=ZA(di,Jt-di);ft===void 0?ft=$i:(ft+="\0",ft+=$i),di=Jt+j}}return _s(Et),ft},toWireType:(Et,ft)=>{typeof ft!="string"&&Ai(`Cannot pass non-string to C++ string type ${RA}`);var Nt=Ke(ft),Kt=Tn(4+Nt+j);return vA[Kt>>2]=Nt>>qe,ne(ft,Kt+4,Nt+j),Et!==null&&Et.push(_s,Kt),Kt},argPackAdvance:8,readValueFromPointer:ur,destructorFunction(Et){_s(Et)}})},v:($,j)=>{pn($,{isVoid:!0,name:j=Fi(j),argPackAdvance:0,fromWireType:()=>{},toWireType:(RA,ZA)=>{}})},j:($,j,RA)=>($=ts.toValue($),j=Aa(j,"emval::as"),Uo(j,RA,$)),e:($,j,RA,ZA,ne)=>{var De,Ke;return($=Xs[$])(j=ts.toValue(j),j[RA=(Ke=Zc[De=RA])===void 0?Fi(De):Ke],ZA,ne)},d:es,f:($,j,RA)=>{var ZA=((ft,Nt)=>{for(var Kt=new Array(ft),di=0;di>2],"parameter "+di);return Kt})($,j),ne=ZA.shift();$--;var De,Ke,qe=new Array($),Et=`methodCaller<(${ZA.map(ft=>ft.name).join(", ")}) => ${ne.name}>`;return De=an(Et,(ft,Nt,Kt,di)=>{for(var Bt=0,Jt=0;Jt<$;++Jt)qe[Jt]=ZA[Jt].readValueFromPointer(di+Bt),Bt+=ZA[Jt].argPackAdvance;var $i=RA===1?is(Nt,qe):Nt.apply(ft,qe);for(Jt=0;Jt<$;++Jt)ZA[Jt].deleteObject&&ZA[Jt].deleteObject(qe[Jt]);return Uo(ne,Kt,$i)}),Ke=Xs.length,Xs.push(De),Ke},c:$=>{$>4&&(fo.get($).refcount+=1)},b:$=>{var j=ts.toValue($);Un(j),es($)},h:($,j)=>{var RA=($=Aa($,"_emval_take_value")).readValueFromPointer(j);return ts.toHandle(RA)},m:()=>{Xe("")},s:($,j,RA)=>eA.copyWithin($,j,j+RA),r:$=>{eA.length,Xe("OOM")},n:($,j,RA,ZA)=>{for(var ne=0,De=0;De>2],qe=vA[j+4>>2];j+=8;for(var Et=0;Et>2]=ne,0}},Qs=function(){var $={a:Fa};function j(RA,ZA){var ne,De;return Qs=RA.exports,_=Qs.z,ne=_.buffer,I.HEAP8=cA=new Int8Array(ne),I.HEAP16=CA=new Int16Array(ne),I.HEAPU8=eA=new Uint8Array(ne),I.HEAPU16=IA=new Uint16Array(ne),I.HEAP32=oA=new Int32Array(ne),I.HEAPU32=vA=new Uint32Array(ne),I.HEAPF32=qA=new Float32Array(ne),I.HEAPF64=Ae=new Float64Array(ne),qi=Qs.C,De=Qs.A,WA.unshift(De),function(){if(we--,I.monitorRunDependencies&&I.monitorRunDependencies(we),we==0&&et){var Ke=et;et=null,Ke()}}(),Qs}if(we++,I.monitorRunDependencies&&I.monitorRunDependencies(we),I.instantiateWasm)try{return I.instantiateWasm($,j)}catch(RA){b(`Module.instantiateWasm callback failed with error: ${RA}`),c(RA)}return ii(0,ae,$,function(RA){j(RA.instance)}).catch(c),{}}(),Tn=$=>(Tn=Qs.B)($),pa=$=>(pa=Qs.D)($),_s=$=>(_s=Qs.E)($),Oa=$=>(Oa=Qs.F)($);I.dynCall_jiji=($,j,RA,ZA,ne)=>(I.dynCall_jiji=Qs.G)($,j,RA,ZA,ne),I._vertexShaderSource=10688;function Ta(){function $(){ws||(ws=!0,I.calledRun=!0,HA||(ki(WA),n(I),I.onRuntimeInitialized&&I.onRuntimeInitialized(),function(){if(I.postRun)for(typeof I.postRun=="function"&&(I.postRun=[I.postRun]);I.postRun.length;)Pe(I.postRun.shift());ki(Ye)}()))}we>0||(function(){if(I.preRun)for(typeof I.preRun=="function"&&(I.preRun=[I.preRun]);I.preRun.length;)We(I.preRun.shift());ki(se)}(),we>0||(I.setStatus?(I.setStatus("Running..."),setTimeout(function(){setTimeout(function(){I.setStatus("")},1),$()},1)):$()))}if(et=function $(){ws||Ta(),ws||(et=$)},I.preInit)for(typeof I.preInit=="function"&&(I.preInit=[I.preInit]);I.preInit.length>0;)I.preInit.pop()();return Ta(),i.ready}})(),BgA=hgA,Qm=typeof navigator>"u"?"":navigator.userAgent,$n=e=>new RegExp(e,"i").test(Qm),Dc=e=>{if($n(e)){const i=new RegExp(`${e}\\/([\\d.]+)`),n=Qm.match(i);if(n&&n[1])return n[1]}return""},OV=e=>{if($n(e)){const i=new RegExp(`${e}\\/(\\d+)`),n=Qm.match(i);if(n&&n[1])return parseFloat(n[1])}return NaN},FZ=/AppleWebKit\/([\d.]+)/i.exec(Qm);FZ&&parseFloat(FZ[1]);var bX=$n("iPad"),kX=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&$n("Macintosh"),LX=$n("iPhone")&&!bX,QgA=$n("iPod"),UX=LX||bX||QgA||kX,p4=$n("Android"),pgA=function(){if(p4){const e=Qm.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(e){const i=e[1]&&parseFloat(e[1]),n=e[2]&&parseFloat(e[2]);if(i&&n)return parseFloat(`${e[1]}.${e[2]}`);if(i)return i}}return NaN}();p4&&$n("webkit")&&pgA<2.3;var mgA=$n("Firefox"),fgA=Dc("Firefox");OV("Firefox");var FX=$n("Edge"),ygA=Dc("Edge"),OX=$n("Edg"),DgA=Dc("Edg");OV("Edg");var PX=$n("SogouMobileBrowser"),SgA=Dc("SogouMobileBrowser"),xX=$n("MetaSr\\s"),vgA=Dc("MetaSr\\s"),JM=$n("TBS"),MgA=Dc("TBS"),YX=$n("XWEB"),RgA=Dc("XWEB");$n("MSIE\\s8\\.0");var wgA=$n("MSIE\\/\\d+");(function(){if(wgA){const e=/MSIE\s(\d+)\.\d/.exec(Qm);let i=e&&parseFloat(e[1]);return!i&&/Trident\/7.0/i.test(Qm)&&/rv:11.0/.test(Qm)&&(i=11),i}return NaN})();var _gA=$n("(micromessenger|webbrowser)"),TgA=Dc("MicroMessenger"),m4=!JM&&$n("MQQBrowser")&&$n("COVC"),f4=!JM&&$n("MQQBrowser")&&!$n("COVC"),OZ=f4||m4?Dc("MQQBrowser"):"",VX=!JM&&$n(" QQBrowser"),NgA=Dc(" QQBrowser"),HX=!JM&&$n("QQBrowserLite"),GgA=Dc("QQBrowserLite"),JX=!JM&&$n("MQBHD"),bgA=Dc("MQBHD");$n("Windows");!UX&&$n("MAC OS X");!p4&&$n("Linux");$n("CrOS");$n("MicroMessenger");$n("UCBrowser");$n("Electron");var qX=$n("MiuiBrowser"),kgA=Dc("MiuiBrowser"),KX=$n("HuaweiBrowser");$n("Huawei")||$n("HUAWEI");$n("Honor")||$n("HONOR");var LgA=Dc("HuaweiBrowser"),jX=$n("SamsungBrowser"),UgA=Dc("SamsungBrowser"),WX=$n("HeyTapBrowser"),FgA=Dc("HeyTapBrowser"),zX=$n("VivoBrowser"),OgA=Dc("VivoBrowser");$n("OpenHarmony");Dc("OpenHarmony");var PgA=()=>OV("Chrome"),PZ=$n("CriOS"),ZX=$n("Chrome"),xgA=!FX&&!xX&&!PX&&!JM&&!YX&&!OX&&!VX&&!qX&&!KX&&!jX&&!WX&&!zX&&ZX;$n("HeadlessChrome");var YgA=PgA(),VgA=Dc("Chrome");OV("Electron");var HgA=!ZX&&!f4&&!m4&&!HX&&!JX&&$n("Safari"),XX=Dc("Version"),$X=(()=>{if(kX)return XX;if(UX){const e=Qm.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let i=e[1];return e[2]&&(i+=`.${e[2]}`),i}}return""})();Number($X.split(".")[0]);(()=>{const e=Number($X.split(".")[0]);return e===14||e===13})();JgA();function JgA(){const e=new Map([[mgA,["Firefox",fgA]],[OX,["Edg",DgA]],[xgA,["Chrome",VgA]],[PZ,["ChiOS",Dc("CriOS")]],[HgA&&!PZ,["Safari",XX]],[JM,["TBS",MgA]],[YX,["XWEB",RgA]],[_gA&&LX,["WeChat",TgA]],[VX,["QQ(Win)",NgA]],[f4,["QQ(Mobile)",OZ]],[m4,["QQ(Mobile X5)",OZ]],[HX,["QQ(Mac)",GgA]],[JX,["QQ(iPad)",bgA]],[qX,["MI",kgA]],[KX,["HW",LgA]],[jX,["Samsung",UgA]],[WX,["OPPO",FgA]],[zX,["VIVO",OgA]],[FX,["EDGE",ygA]],[PX,["SogouMobile",SgA]],[xX,["Sogou",vgA]]]);let i="unknown",n="unknown";return e.has(!0)&&([i,n]=e.get(!0)),{name:i,version:n}}var fc=1e-6,hT=typeof Float32Array<"u"?Float32Array:Array,A7={};function qgA(){var e=new hT(16);return hT!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0),e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function KgA(e){var i=new hT(16);return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15],i}function jgA(e,i){return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],e}function WgA(e,i,n,c,I,C,m,R,_,T,b,J,cA,eA,CA,IA){var oA=new hT(16);return oA[0]=e,oA[1]=i,oA[2]=n,oA[3]=c,oA[4]=I,oA[5]=C,oA[6]=m,oA[7]=R,oA[8]=_,oA[9]=T,oA[10]=b,oA[11]=J,oA[12]=cA,oA[13]=eA,oA[14]=CA,oA[15]=IA,oA}function zgA(e,i,n,c,I,C,m,R,_,T,b,J,cA,eA,CA,IA,oA){return e[0]=i,e[1]=n,e[2]=c,e[3]=I,e[4]=C,e[5]=m,e[6]=R,e[7]=_,e[8]=T,e[9]=b,e[10]=J,e[11]=cA,e[12]=eA,e[13]=CA,e[14]=IA,e[15]=oA,e}function e7(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function ZgA(e,i){if(e===i){var n=i[1],c=i[2],I=i[3],C=i[6],m=i[7],R=i[11];e[1]=i[4],e[2]=i[8],e[3]=i[12],e[4]=n,e[6]=i[9],e[7]=i[13],e[8]=c,e[9]=C,e[11]=i[14],e[12]=I,e[13]=m,e[14]=R}else e[0]=i[0],e[1]=i[4],e[2]=i[8],e[3]=i[12],e[4]=i[1],e[5]=i[5],e[6]=i[9],e[7]=i[13],e[8]=i[2],e[9]=i[6],e[10]=i[10],e[11]=i[14],e[12]=i[3],e[13]=i[7],e[14]=i[11],e[15]=i[15];return e}function XgA(e,i){var n=i[0],c=i[1],I=i[2],C=i[3],m=i[4],R=i[5],_=i[6],T=i[7],b=i[8],J=i[9],cA=i[10],eA=i[11],CA=i[12],IA=i[13],oA=i[14],vA=i[15],qA=n*R-c*m,Ae=n*_-I*m,HA=n*T-C*m,se=c*_-I*R,WA=c*T-C*R,Ye=I*T-C*_,We=b*IA-J*CA,Pe=b*oA-cA*CA,we=b*vA-eA*CA,et=J*oA-cA*IA,Xe=J*vA-eA*IA,ae=cA*vA-eA*oA,Je=qA*ae-Ae*Xe+HA*et+se*we-WA*Pe+Ye*We;return Je?(Je=1/Je,e[0]=(R*ae-_*Xe+T*et)*Je,e[1]=(I*Xe-c*ae-C*et)*Je,e[2]=(IA*Ye-oA*WA+vA*se)*Je,e[3]=(cA*WA-J*Ye-eA*se)*Je,e[4]=(_*we-m*ae-T*Pe)*Je,e[5]=(n*ae-I*we+C*Pe)*Je,e[6]=(oA*HA-CA*Ye-vA*Ae)*Je,e[7]=(b*Ye-cA*HA+eA*Ae)*Je,e[8]=(m*Xe-R*we+T*We)*Je,e[9]=(c*we-n*Xe-C*We)*Je,e[10]=(CA*WA-IA*HA+vA*qA)*Je,e[11]=(J*HA-b*WA-eA*qA)*Je,e[12]=(R*Pe-m*et-_*We)*Je,e[13]=(n*et-c*Pe+I*We)*Je,e[14]=(IA*Ae-CA*se-oA*qA)*Je,e[15]=(b*se-J*Ae+cA*qA)*Je,e):null}function $gA(e,i){var n=i[0],c=i[1],I=i[2],C=i[3],m=i[4],R=i[5],_=i[6],T=i[7],b=i[8],J=i[9],cA=i[10],eA=i[11],CA=i[12],IA=i[13],oA=i[14],vA=i[15],qA=n*R-c*m,Ae=n*_-I*m,HA=n*T-C*m,se=c*_-I*R,WA=c*T-C*R,Ye=I*T-C*_,We=b*IA-J*CA,Pe=b*oA-cA*CA,we=b*vA-eA*CA,et=J*oA-cA*IA,Xe=J*vA-eA*IA,ae=cA*vA-eA*oA;return e[0]=R*ae-_*Xe+T*et,e[1]=I*Xe-c*ae-C*et,e[2]=IA*Ye-oA*WA+vA*se,e[3]=cA*WA-J*Ye-eA*se,e[4]=_*we-m*ae-T*Pe,e[5]=n*ae-I*we+C*Pe,e[6]=oA*HA-CA*Ye-vA*Ae,e[7]=b*Ye-cA*HA+eA*Ae,e[8]=m*Xe-R*we+T*We,e[9]=c*we-n*Xe-C*We,e[10]=CA*WA-IA*HA+vA*qA,e[11]=J*HA-b*WA-eA*qA,e[12]=R*Pe-m*et-_*We,e[13]=n*et-c*Pe+I*We,e[14]=IA*Ae-CA*se-oA*qA,e[15]=b*se-J*Ae+cA*qA,e}function AcA(e){var i=e[0],n=e[1],c=e[2],I=e[3],C=e[4],m=e[5],R=e[6],_=e[7],T=e[8],b=e[9],J=e[10],cA=e[11],eA=e[12],CA=e[13],IA=e[14],oA=i*m-n*C,vA=i*R-c*C,qA=n*R-c*m,Ae=T*CA-b*eA,HA=T*IA-J*eA,se=b*IA-J*CA;return _*(i*se-n*HA+c*Ae)-I*(C*se-m*HA+R*Ae)+e[15]*(T*qA-b*vA+J*oA)-cA*(eA*qA-CA*vA+IA*oA)}function t7(e,i,n){var c=i[0],I=i[1],C=i[2],m=i[3],R=i[4],_=i[5],T=i[6],b=i[7],J=i[8],cA=i[9],eA=i[10],CA=i[11],IA=i[12],oA=i[13],vA=i[14],qA=i[15],Ae=n[0],HA=n[1],se=n[2],WA=n[3];return e[0]=Ae*c+HA*R+se*J+WA*IA,e[1]=Ae*I+HA*_+se*cA+WA*oA,e[2]=Ae*C+HA*T+se*eA+WA*vA,e[3]=Ae*m+HA*b+se*CA+WA*qA,Ae=n[4],HA=n[5],se=n[6],WA=n[7],e[4]=Ae*c+HA*R+se*J+WA*IA,e[5]=Ae*I+HA*_+se*cA+WA*oA,e[6]=Ae*C+HA*T+se*eA+WA*vA,e[7]=Ae*m+HA*b+se*CA+WA*qA,Ae=n[8],HA=n[9],se=n[10],WA=n[11],e[8]=Ae*c+HA*R+se*J+WA*IA,e[9]=Ae*I+HA*_+se*cA+WA*oA,e[10]=Ae*C+HA*T+se*eA+WA*vA,e[11]=Ae*m+HA*b+se*CA+WA*qA,Ae=n[12],HA=n[13],se=n[14],WA=n[15],e[12]=Ae*c+HA*R+se*J+WA*IA,e[13]=Ae*I+HA*_+se*cA+WA*oA,e[14]=Ae*C+HA*T+se*eA+WA*vA,e[15]=Ae*m+HA*b+se*CA+WA*qA,e}function ecA(e,i,n){var c,I,C,m,R,_,T,b,J,cA,eA,CA,IA=n[0],oA=n[1],vA=n[2];return i===e?(e[12]=i[0]*IA+i[4]*oA+i[8]*vA+i[12],e[13]=i[1]*IA+i[5]*oA+i[9]*vA+i[13],e[14]=i[2]*IA+i[6]*oA+i[10]*vA+i[14],e[15]=i[3]*IA+i[7]*oA+i[11]*vA+i[15]):(c=i[0],I=i[1],C=i[2],m=i[3],R=i[4],_=i[5],T=i[6],b=i[7],J=i[8],cA=i[9],eA=i[10],CA=i[11],e[0]=c,e[1]=I,e[2]=C,e[3]=m,e[4]=R,e[5]=_,e[6]=T,e[7]=b,e[8]=J,e[9]=cA,e[10]=eA,e[11]=CA,e[12]=c*IA+R*oA+J*vA+i[12],e[13]=I*IA+_*oA+cA*vA+i[13],e[14]=C*IA+T*oA+eA*vA+i[14],e[15]=m*IA+b*oA+CA*vA+i[15]),e}function tcA(e,i,n){var c=n[0],I=n[1],C=n[2];return e[0]=i[0]*c,e[1]=i[1]*c,e[2]=i[2]*c,e[3]=i[3]*c,e[4]=i[4]*I,e[5]=i[5]*I,e[6]=i[6]*I,e[7]=i[7]*I,e[8]=i[8]*C,e[9]=i[9]*C,e[10]=i[10]*C,e[11]=i[11]*C,e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],e}function icA(e,i,n,c){var I,C,m,R,_,T,b,J,cA,eA,CA,IA,oA,vA,qA,Ae,HA,se,WA,Ye,We,Pe,we,et,Xe=c[0],ae=c[1],Je=c[2],pt=Math.sqrt(Xe*Xe+ae*ae+Je*Je);return pt0?(n[0]=2*(R*m+b*c+_*C-T*I)/J,n[1]=2*(_*m+b*I+T*c-R*C)/J,n[2]=2*(T*m+b*C+R*I-_*c)/J):(n[0]=2*(R*m+b*c+_*C-T*I),n[1]=2*(_*m+b*I+T*c-R*C),n[2]=2*(T*m+b*C+R*I-_*c)),i7(e,i,n),e}function EcA(e,i){return e[0]=i[12],e[1]=i[13],e[2]=i[14],e}function o7(e,i){var n=i[0],c=i[1],I=i[2],C=i[4],m=i[5],R=i[6],_=i[8],T=i[9],b=i[10];return e[0]=Math.sqrt(n*n+c*c+I*I),e[1]=Math.sqrt(C*C+m*m+R*R),e[2]=Math.sqrt(_*_+T*T+b*b),e}function dcA(e,i){var n=new hT(3);o7(n,i);var c=1/n[0],I=1/n[1],C=1/n[2],m=i[0]*c,R=i[1]*I,_=i[2]*C,T=i[4]*c,b=i[5]*I,J=i[6]*C,cA=i[8]*c,eA=i[9]*I,CA=i[10]*C,IA=m+b+CA,oA=0;return IA>0?(oA=2*Math.sqrt(IA+1),e[3]=.25*oA,e[0]=(J-eA)/oA,e[1]=(cA-_)/oA,e[2]=(R-T)/oA):m>b&&m>CA?(oA=2*Math.sqrt(1+m-b-CA),e[3]=(J-eA)/oA,e[0]=.25*oA,e[1]=(R+T)/oA,e[2]=(cA+_)/oA):b>CA?(oA=2*Math.sqrt(1+b-m-CA),e[3]=(cA-_)/oA,e[0]=(R+T)/oA,e[1]=.25*oA,e[2]=(J+eA)/oA):(oA=2*Math.sqrt(1+CA-m-b),e[3]=(R-T)/oA,e[0]=(cA+_)/oA,e[1]=(J+eA)/oA,e[2]=.25*oA),e}function CcA(e,i,n,c){i[0]=c[12],i[1]=c[13],i[2]=c[14];var I=c[0],C=c[1],m=c[2],R=c[4],_=c[5],T=c[6],b=c[8],J=c[9],cA=c[10];n[0]=Math.sqrt(I*I+C*C+m*m),n[1]=Math.sqrt(R*R+_*_+T*T),n[2]=Math.sqrt(b*b+J*J+cA*cA);var eA=1/n[0],CA=1/n[1],IA=1/n[2],oA=I*eA,vA=C*CA,qA=m*IA,Ae=R*eA,HA=_*CA,se=T*IA,WA=b*eA,Ye=J*CA,We=cA*IA,Pe=oA+HA+We,we=0;return Pe>0?(we=2*Math.sqrt(Pe+1),e[3]=.25*we,e[0]=(se-Ye)/we,e[1]=(WA-qA)/we,e[2]=(vA-Ae)/we):oA>HA&&oA>We?(we=2*Math.sqrt(1+oA-HA-We),e[3]=(se-Ye)/we,e[0]=.25*we,e[1]=(vA+Ae)/we,e[2]=(WA+qA)/we):HA>We?(we=2*Math.sqrt(1+HA-oA-We),e[3]=(WA-qA)/we,e[0]=(vA+Ae)/we,e[1]=.25*we,e[2]=(se+Ye)/we):(we=2*Math.sqrt(1+We-oA-HA),e[3]=(vA-Ae)/we,e[0]=(WA+qA)/we,e[1]=(se+Ye)/we,e[2]=.25*we),e}function hcA(e,i,n,c){var I=i[0],C=i[1],m=i[2],R=i[3],_=I+I,T=C+C,b=m+m,J=I*_,cA=I*T,eA=I*b,CA=C*T,IA=C*b,oA=m*b,vA=R*_,qA=R*T,Ae=R*b,HA=c[0],se=c[1],WA=c[2];return e[0]=(1-(CA+oA))*HA,e[1]=(cA+Ae)*HA,e[2]=(eA-qA)*HA,e[3]=0,e[4]=(cA-Ae)*se,e[5]=(1-(J+oA))*se,e[6]=(IA+vA)*se,e[7]=0,e[8]=(eA+qA)*WA,e[9]=(IA-vA)*WA,e[10]=(1-(J+CA))*WA,e[11]=0,e[12]=n[0],e[13]=n[1],e[14]=n[2],e[15]=1,e}function BcA(e,i,n,c,I){var C=i[0],m=i[1],R=i[2],_=i[3],T=C+C,b=m+m,J=R+R,cA=C*T,eA=C*b,CA=C*J,IA=m*b,oA=m*J,vA=R*J,qA=_*T,Ae=_*b,HA=_*J,se=c[0],WA=c[1],Ye=c[2],We=I[0],Pe=I[1],we=I[2],et=(1-(IA+vA))*se,Xe=(eA+HA)*se,ae=(CA-Ae)*se,Je=(eA-HA)*WA,pt=(1-(cA+vA))*WA,$t=(oA+qA)*WA,Pt=(CA+Ae)*Ye,ii=(oA-qA)*Ye,ki=(1-(cA+IA))*Ye;return e[0]=et,e[1]=Xe,e[2]=ae,e[3]=0,e[4]=Je,e[5]=pt,e[6]=$t,e[7]=0,e[8]=Pt,e[9]=ii,e[10]=ki,e[11]=0,e[12]=n[0]+We-(et*We+Je*Pe+Pt*we),e[13]=n[1]+Pe-(Xe*We+pt*Pe+ii*we),e[14]=n[2]+we-(ae*We+$t*Pe+ki*we),e[15]=1,e}function QcA(e,i){var n=i[0],c=i[1],I=i[2],C=i[3],m=n+n,R=c+c,_=I+I,T=n*m,b=c*m,J=c*R,cA=I*m,eA=I*R,CA=I*_,IA=C*m,oA=C*R,vA=C*_;return e[0]=1-J-CA,e[1]=b+vA,e[2]=cA-oA,e[3]=0,e[4]=b-vA,e[5]=1-T-CA,e[6]=eA+IA,e[7]=0,e[8]=cA+oA,e[9]=eA-IA,e[10]=1-T-J,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function pcA(e,i,n,c,I,C,m){var R=1/(n-i),_=1/(I-c),T=1/(C-m);return e[0]=2*C*R,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=2*C*_,e[6]=0,e[7]=0,e[8]=(n+i)*R,e[9]=(I+c)*_,e[10]=(m+C)*T,e[11]=-1,e[12]=0,e[13]=0,e[14]=m*C*2*T,e[15]=0,e}function n7(e,i,n,c,I){var C=1/Math.tan(i/2);if(e[0]=C/n,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=C,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=-1,e[12]=0,e[13]=0,e[15]=0,I!=null&&I!==1/0){var m=1/(c-I);e[10]=(I+c)*m,e[14]=2*I*c*m}else e[10]=-1,e[14]=-2*c;return e}lgA(A7,{add:()=>_cA,adjoint:()=>$gA,clone:()=>KgA,copy:()=>jgA,create:()=>qgA,decompose:()=>CcA,determinant:()=>AcA,equals:()=>bcA,exactEquals:()=>GcA,frob:()=>wcA,fromQuat:()=>QcA,fromQuat2:()=>ucA,fromRotation:()=>gcA,fromRotationTranslation:()=>i7,fromRotationTranslationScale:()=>hcA,fromRotationTranslationScaleOrigin:()=>BcA,fromScaling:()=>acA,fromTranslation:()=>rcA,fromValues:()=>WgA,fromXRotation:()=>ccA,fromYRotation:()=>lcA,fromZRotation:()=>IcA,frustum:()=>pcA,getRotation:()=>dcA,getScaling:()=>o7,getTranslation:()=>EcA,identity:()=>e7,invert:()=>XgA,lookAt:()=>vcA,mul:()=>kcA,multiply:()=>t7,multiplyScalar:()=>TcA,multiplyScalarAndAdd:()=>NcA,ortho:()=>DcA,orthoNO:()=>s7,orthoZO:()=>ScA,perspective:()=>mcA,perspectiveFromFieldOfView:()=>ycA,perspectiveNO:()=>n7,perspectiveZO:()=>fcA,rotate:()=>icA,rotateX:()=>ocA,rotateY:()=>ncA,rotateZ:()=>scA,scale:()=>tcA,set:()=>zgA,str:()=>RcA,sub:()=>LcA,subtract:()=>r7,targetTo:()=>McA,translate:()=>ecA,transpose:()=>ZgA});var mcA=n7;function fcA(e,i,n,c,I){var C=1/Math.tan(i/2);if(e[0]=C/n,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=C,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=-1,e[12]=0,e[13]=0,e[15]=0,I!=null&&I!==1/0){var m=1/(c-I);e[10]=I*m,e[14]=I*c*m}else e[10]=-1,e[14]=-c;return e}function ycA(e,i,n,c){var I=Math.tan(i.upDegrees*Math.PI/180),C=Math.tan(i.downDegrees*Math.PI/180),m=Math.tan(i.leftDegrees*Math.PI/180),R=Math.tan(i.rightDegrees*Math.PI/180),_=2/(m+R),T=2/(I+C);return e[0]=_,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=T,e[6]=0,e[7]=0,e[8]=-(m-R)*_*.5,e[9]=(I-C)*T*.5,e[10]=c/(n-c),e[11]=-1,e[12]=0,e[13]=0,e[14]=c*n/(n-c),e[15]=0,e}function s7(e,i,n,c,I,C,m){var R=1/(i-n),_=1/(c-I),T=1/(C-m);return e[0]=-2*R,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=-2*_,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=2*T,e[11]=0,e[12]=(i+n)*R,e[13]=(I+c)*_,e[14]=(m+C)*T,e[15]=1,e}var DcA=s7;function ScA(e,i,n,c,I,C,m){var R=1/(i-n),_=1/(c-I),T=1/(C-m);return e[0]=-2*R,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=-2*_,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=T,e[11]=0,e[12]=(i+n)*R,e[13]=(I+c)*_,e[14]=C*T,e[15]=1,e}function vcA(e,i,n,c){var I,C,m,R,_,T,b,J,cA,eA,CA=i[0],IA=i[1],oA=i[2],vA=c[0],qA=c[1],Ae=c[2],HA=n[0],se=n[1],WA=n[2];return Math.abs(CA-HA)0&&(b*=eA=1/Math.sqrt(eA),J*=eA,cA*=eA);var CA=_*cA-T*J,IA=T*b-R*cA,oA=R*J-_*b;return(eA=CA*CA+IA*IA+oA*oA)>0&&(CA*=eA=1/Math.sqrt(eA),IA*=eA,oA*=eA),e[0]=CA,e[1]=IA,e[2]=oA,e[3]=0,e[4]=J*oA-cA*IA,e[5]=cA*CA-b*oA,e[6]=b*IA-J*CA,e[7]=0,e[8]=b,e[9]=J,e[10]=cA,e[11]=0,e[12]=I,e[13]=C,e[14]=m,e[15]=1,e}function RcA(e){return"mat4("+e[0]+", "+e[1]+", "+e[2]+", "+e[3]+", "+e[4]+", "+e[5]+", "+e[6]+", "+e[7]+", "+e[8]+", "+e[9]+", "+e[10]+", "+e[11]+", "+e[12]+", "+e[13]+", "+e[14]+", "+e[15]+")"}function wcA(e){return Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]+e[3]*e[3]+e[4]*e[4]+e[5]*e[5]+e[6]*e[6]+e[7]*e[7]+e[8]*e[8]+e[9]*e[9]+e[10]*e[10]+e[11]*e[11]+e[12]*e[12]+e[13]*e[13]+e[14]*e[14]+e[15]*e[15])}function _cA(e,i,n){return e[0]=i[0]+n[0],e[1]=i[1]+n[1],e[2]=i[2]+n[2],e[3]=i[3]+n[3],e[4]=i[4]+n[4],e[5]=i[5]+n[5],e[6]=i[6]+n[6],e[7]=i[7]+n[7],e[8]=i[8]+n[8],e[9]=i[9]+n[9],e[10]=i[10]+n[10],e[11]=i[11]+n[11],e[12]=i[12]+n[12],e[13]=i[13]+n[13],e[14]=i[14]+n[14],e[15]=i[15]+n[15],e}function r7(e,i,n){return e[0]=i[0]-n[0],e[1]=i[1]-n[1],e[2]=i[2]-n[2],e[3]=i[3]-n[3],e[4]=i[4]-n[4],e[5]=i[5]-n[5],e[6]=i[6]-n[6],e[7]=i[7]-n[7],e[8]=i[8]-n[8],e[9]=i[9]-n[9],e[10]=i[10]-n[10],e[11]=i[11]-n[11],e[12]=i[12]-n[12],e[13]=i[13]-n[13],e[14]=i[14]-n[14],e[15]=i[15]-n[15],e}function TcA(e,i,n){return e[0]=i[0]*n,e[1]=i[1]*n,e[2]=i[2]*n,e[3]=i[3]*n,e[4]=i[4]*n,e[5]=i[5]*n,e[6]=i[6]*n,e[7]=i[7]*n,e[8]=i[8]*n,e[9]=i[9]*n,e[10]=i[10]*n,e[11]=i[11]*n,e[12]=i[12]*n,e[13]=i[13]*n,e[14]=i[14]*n,e[15]=i[15]*n,e}function NcA(e,i,n,c){return e[0]=i[0]+n[0]*c,e[1]=i[1]+n[1]*c,e[2]=i[2]+n[2]*c,e[3]=i[3]+n[3]*c,e[4]=i[4]+n[4]*c,e[5]=i[5]+n[5]*c,e[6]=i[6]+n[6]*c,e[7]=i[7]+n[7]*c,e[8]=i[8]+n[8]*c,e[9]=i[9]+n[9]*c,e[10]=i[10]+n[10]*c,e[11]=i[11]+n[11]*c,e[12]=i[12]+n[12]*c,e[13]=i[13]+n[13]*c,e[14]=i[14]+n[14]*c,e[15]=i[15]+n[15]*c,e}function GcA(e,i){return e[0]===i[0]&&e[1]===i[1]&&e[2]===i[2]&&e[3]===i[3]&&e[4]===i[4]&&e[5]===i[5]&&e[6]===i[6]&&e[7]===i[7]&&e[8]===i[8]&&e[9]===i[9]&&e[10]===i[10]&&e[11]===i[11]&&e[12]===i[12]&&e[13]===i[13]&&e[14]===i[14]&&e[15]===i[15]}function bcA(e,i){var n=e[0],c=e[1],I=e[2],C=e[3],m=e[4],R=e[5],_=e[6],T=e[7],b=e[8],J=e[9],cA=e[10],eA=e[11],CA=e[12],IA=e[13],oA=e[14],vA=e[15],qA=i[0],Ae=i[1],HA=i[2],se=i[3],WA=i[4],Ye=i[5],We=i[6],Pe=i[7],we=i[8],et=i[9],Xe=i[10],ae=i[11],Je=i[12],pt=i[13],$t=i[14],Pt=i[15];return Math.abs(n-qA)<=fc*Math.max(1,Math.abs(n),Math.abs(qA))&&Math.abs(c-Ae)<=fc*Math.max(1,Math.abs(c),Math.abs(Ae))&&Math.abs(I-HA)<=fc*Math.max(1,Math.abs(I),Math.abs(HA))&&Math.abs(C-se)<=fc*Math.max(1,Math.abs(C),Math.abs(se))&&Math.abs(m-WA)<=fc*Math.max(1,Math.abs(m),Math.abs(WA))&&Math.abs(R-Ye)<=fc*Math.max(1,Math.abs(R),Math.abs(Ye))&&Math.abs(_-We)<=fc*Math.max(1,Math.abs(_),Math.abs(We))&&Math.abs(T-Pe)<=fc*Math.max(1,Math.abs(T),Math.abs(Pe))&&Math.abs(b-we)<=fc*Math.max(1,Math.abs(b),Math.abs(we))&&Math.abs(J-et)<=fc*Math.max(1,Math.abs(J),Math.abs(et))&&Math.abs(cA-Xe)<=fc*Math.max(1,Math.abs(cA),Math.abs(Xe))&&Math.abs(eA-ae)<=fc*Math.max(1,Math.abs(eA),Math.abs(ae))&&Math.abs(CA-Je)<=fc*Math.max(1,Math.abs(CA),Math.abs(Je))&&Math.abs(IA-pt)<=fc*Math.max(1,Math.abs(IA),Math.abs(pt))&&Math.abs(oA-$t)<=fc*Math.max(1,Math.abs(oA),Math.abs($t))&&Math.abs(vA-Pt)<=fc*Math.max(1,Math.abs(vA),Math.abs(Pt))}var kcA=t7,LcA=r7,bL=`#version 300 es +`);return YaA(C)},VaA="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",l3=(e=21)=>{let i="",n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)i+=VaA[63&n[e]];return i},x_=e=>typeof e=="function",HaA=0,JaA=1,bZ=2;function qaA({retryFunction:e,settings:i,onError:n,onRetrying:c,onRetryFailed:I,onRetrySuccess:C,context:m}){return function(...R){const{retries:_=5,timeout:T=1e3}=i;let b=0,J=-1,gA=HaA;const eA=async(CA,IA)=>{const oA=m||this;try{const vA=await e.apply(oA,R);b>0&&C&&C.call(this,b),b=0,CA(vA)}catch(vA){const qA=()=>{clearTimeout(J),b=0,gA=bZ,IA(vA)},Ae=()=>{gA!==bZ&&b<(x_(_)?_():_)?(b++,gA=JaA,x_(c)&&c.call(this,b,qA),J=window.setTimeout(()=>{J=-1,eA(CA,IA)},x_(T)?T(b):T)):(qA(),x_(I)&&I.call(this,vA))};x_(n)?n.call(this,{error:vA,retry:Ae,reject:IA,retryFuncArgs:R,retriedCount:b}):Ae()}};return new Promise(eA)}}var KaA=qaA,DQ=new WeakMap;function jaA({settings:e={retries:5,timeout:2e3},onError:i,onRetrying:n,onRetryFailed:c}){return function(I,C,m){const R=KaA({retryFunction:m.value,settings:e,onError({error:_,retry:T,reject:b,retryFuncArgs:J}){var gA;i?i.call(this,_,()=>{var eA;(eA=DQ.get(I))!=null&&eA.has(C)?T():b(_)},b,J):(gA=DQ.get(I))!=null&&gA.has(C)?T():b(_)},onRetrying(_,T){var b;x_(n)&&n.call(this,_,T),(b=DQ.get(I))!=null&&b.has(C)&&(DQ.get(I).get(C).stopRetry=T)},onRetryFailed:c});return m.value=function(..._){const T=DQ.get(I);return T?T.set(C,{args:_}):DQ.set(I,new Map([[C,{args:_}]])),R.apply(this,_).finally(()=>{var b;return(b=DQ.get(I))==null?void 0:b.delete(C)})},m}}function WaA({fnName:e,callback:i,validateArgs:n=!0}){return function(c,I,C){const m=C.value;return C.value=function(...R){var _,T;if((_=DQ.get(c))!=null&&_.has(e)){const{stopRetry:b,args:J}=DQ.get(c).get(e);let gA=!0;if(n){for(const eA of J)if(!R.find(CA=>CA===eA)){gA=!1;break}}gA&&(i&&i.apply(this,R),b&&b(),(T=DQ.get(c))==null||T.delete(e))}return m.apply(this,R)},C}}var zaA=class{constructor(e,i){this.core=i,Ms(this,"peerConnection"),Ms(this,"audioTransceiver",null),Ms(this,"videoTransceiver",null),Ms(this,"timerId",null),Ms(this,"callback",null),Ms(this,"previousRawStats",null),Ms(this,"_prevReportTime",0),Ms(this,"_prevDecoderImplementation",""),Ms(this,"_decodeMap",new Map),this.peerConnection=e,this.findTransceivers()}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}findTransceivers(){const e=this.peerConnection.getTransceivers();for(const i of e)if(i.receiver&&i.receiver.track){const{track:n}=i.receiver;n.kind==="audio"?this.audioTransceiver=i:n.kind==="video"&&(this.videoTransceiver=i)}}start(e,i=2e3){this.stop(),this.callback=e,this.collectStats(),this.timerId=window.setInterval(()=>{this.collectStats()},i)}stop(){this.timerId!==null&&(clearInterval(this.timerId),this.timerId=null),this.callback=null,this.previousRawStats=null,this._prevReportTime=0}async collectStats(){if(this.callback)try{const e=await this.peerConnection.getStats(),i=new Set(["inbound-rtp","track","candidate-pair","media-source","codec"]),n=[];e.forEach(R=>i.has(R.type)&&n.push(R));const c=Date.now(),I=this.parseAudioStats(n),C=this.parseVideoStats(n),m=this.parseNetworkStats(n);this._prevReportTime=c,this.callback({audio:I,video:C,network:m})}catch(e){this.core.log.error("Failed to collect WebRTC stats:",e)}}getDifferenceValue(e,i){if(this.core.utils.isUndefined(e))return i;const n=(i||0)-e;return n<0?0:n}parseAudioStats(e){var i,n,c,I;const C={bitrate:0,volume:0,packetLossRate:0,jitterBufferDelay:0,bytesReceived:0,packetsReceived:0,packetsLost:0};for(const m of e){if(m.type==="inbound-rtp"&&(m.mediaType==="audio"||m.kind==="audio")){if(C.bytesReceived=m.bytesReceived||0,C.packetsReceived=m.packetsReceived||0,C.packetsLost=m.packetsLost||0,this.previousRawStats&&this.previousRawStats.audio){const T=this.getDifferenceValue(this.previousRawStats.audio.bytesReceived,C.bytesReceived);C.bitrate=Math.round(8*T/this.statInterval/1e3)}const R=this.getDifferenceValue((i=this.previousRawStats)==null?void 0:i.audio.packetsLost,C.packetsLost),_=this.getDifferenceValue((n=this.previousRawStats)==null?void 0:n.audio.packetsReceived,C.packetsReceived)+R;if(_>0&&(C.packetLossRate=Math.round(R/_*100)),this.core.utils.isUndefined(m.audioLevel)||(C.volume=m.audioLevel||0),m.jitterBufferDelay&&m.jitterBufferEmittedCount){let{jitterBufferEmittedCount:T}=m,{jitterBufferDelay:b}=m;(c=this.previousRawStats)!=null&&c.audio&&(T=this.getDifferenceValue(this.previousRawStats.audio.jitterBufferEmittedCount,m.jitterBufferEmittedCount),b=this.getDifferenceValue(this.previousRawStats.audio.jitterBufferDelay,m.jitterBufferDelay)),T>0&&(C.jitterBufferDelay=Math.floor(b/T*1e3)),this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.audio.jitterBufferDelay=m.jitterBufferDelay,this.previousRawStats.audio.jitterBufferEmittedCount=m.jitterBufferEmittedCount}this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.audio.bytesReceived=C.bytesReceived,this.previousRawStats.audio.packetsReceived=C.packetsReceived,this.previousRawStats.audio.packetsLost=C.packetsLost}!this.core.utils.isUndefined(m.audioLevel)&&((I=this.audioTransceiver)!=null&&I.receiver.track)&&m.trackIdentifier===this.audioTransceiver.receiver.track.id&&(C.volume=m.audioLevel||0)}return C}parseVideoStats(e){var i,n,c,I,C;const m={bitrate:0,frameRate:0,width:0,height:0,packetLossRate:0,jitterBufferDelay:0,bytesReceived:0,packetsReceived:0,packetsLost:0,framesDecoded:0};for(const R of e){if(R.type==="codec"&&this._decodeMap.set(R.id,R),R.type==="inbound-rtp"&&(R.mediaType==="video"||R.kind==="video")){if(m.bytesReceived=R.bytesReceived||0,m.packetsReceived=R.packetsReceived||0,m.packetsLost=R.packetsLost||0,m.framesDecoded=R.framesDecoded||0,this.core.utils.isUndefined(R.framesPerSecond)||(m.frameRate=Math.round(R.framesPerSecond)),R.decoderImplementation&&this._prevDecoderImplementation!==R.decoderImplementation){const b=this._decodeMap.get(R.codecId),J=((i=b?.mimeType)==null?void 0:i.split("/")[1])||"unknown",gA=R.powerEfficientDecoder;this.core.log.info(`decoderImplementation change to ${R.decoderImplementation}(${J}) HWDecoder: ${gA}`),this._prevDecoderImplementation=R.decoderImplementation}if(this.previousRawStats&&this.previousRawStats.video){const b=this.getDifferenceValue(this.previousRawStats.video.bytesReceived,m.bytesReceived);m.bitrate=Math.round(8*b/this.statInterval/1e3)}const _=this.getDifferenceValue((n=this.previousRawStats)==null?void 0:n.video.packetsLost,m.packetsLost),T=this.getDifferenceValue((c=this.previousRawStats)==null?void 0:c.video.packetsReceived,m.packetsReceived)+_;if(T>0&&(m.packetLossRate=Math.round(_/T*100)),R.jitterBufferDelay&&R.jitterBufferEmittedCount){let{jitterBufferEmittedCount:b}=R,{jitterBufferDelay:J}=R;(I=this.previousRawStats)!=null&&I.video&&(b=this.getDifferenceValue(this.previousRawStats.video.jitterBufferEmittedCount,R.jitterBufferEmittedCount),J=this.getDifferenceValue(this.previousRawStats.video.jitterBufferDelay,R.jitterBufferDelay)),b>0&&(m.jitterBufferDelay=Math.floor(J/b*1e3)),this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.video.jitterBufferDelay=R.jitterBufferDelay,this.previousRawStats.video.jitterBufferEmittedCount=R.jitterBufferEmittedCount}this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.video.bytesReceived=m.bytesReceived,this.previousRawStats.video.packetsReceived=m.packetsReceived,this.previousRawStats.video.packetsLost=m.packetsLost}!this.core.utils.isUndefined(R.frameWidth)&&((C=this.videoTransceiver)!=null&&C.receiver.track)&&R.trackIdentifier===this.videoTransceiver.receiver.track.id&&(m.width=R.frameWidth,m.height=R.frameHeight)}return m}parseNetworkStats(e){const i={rtt:0};for(const n of e)if(n.type==="candidate-pair"&&(n.selected||n.state==="succeeded")&&this.core.utils.isNumber(n.currentRoundTripTime)){i.rtt=Math.floor(1e3*n.currentRoundTripTime);break}return i}initPreviousRawStats(){this.previousRawStats={timestamp:Date.now(),audio:{bytesReceived:0,packetsReceived:0,packetsLost:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0}}}},ZaA=OaA(PaA()),kZ=Symbol("instance"),$1=Symbol("cacheResult"),I3=class{constructor(i,n,c){this.oldState=i,this.newState=n,this.action=c,this.aborted=!1}abort(i){this.aborted=!0,dU.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},u3=class extends Error{constructor(i,n,c){super(n),this.state=i,this.message=n,this.cause=c}};function XaA(e){return typeof e=="object"&&e&&"then"in e}var EU=new Map;function AY(e,i,n={}){return(c,I,C)=>{const m=n.action||I;if(!n.context){const _=EU.get(c)||[];EU.has(c)||EU.set(c,_),_.push({from:e,to:i,action:m})}const R=C.value;C.value=function(..._){let T=this;if(n.context&&(T=eh.get(typeof n.context=="function"?n.context.call(this,..._):n.context)),T.state===i)return n.sync?T[$1]:Promise.resolve(T[$1]);T.state instanceof I3&&T.state.action==n.abortAction&&T.state.abort(T);let b=null;Array.isArray(e)?e.length==0?T.state instanceof I3&&T.state.abort(T):typeof T.state=="string"&&e.includes(T.state)||(b=new u3(T._state,`${T.name} ${m} to ${i} failed: current state ${T._state} not from ${e.join("|")}`)):e!==T.state&&(b=new u3(T._state,`${T.name} ${m} to ${i} failed: current state ${T._state} not from ${e}`));const J=oA=>{if(n.fail&&n.fail.call(this,oA),n.sync){if(n.ignoreError)return oA;throw oA}return n.ignoreError?Promise.resolve(oA):Promise.reject(oA)};if(b)return J(b);const gA=T.state,eA=new I3(gA,i,m);dU.call(T,eA);const CA=oA=>{var vA;return T[$1]=oA,eA.aborted||(dU.call(T,i),(vA=n.success)===null||vA===void 0||vA.call(this,T[$1])),oA},IA=oA=>(dU.call(T,gA,oA),J(oA));try{const oA=R.apply(this,_);return XaA(oA)?oA.then(CA).catch(IA):n.sync?CA(oA):Promise.resolve(CA(oA))}catch(oA){return IA(new u3(T._state,`${T.name} ${m} from ${e} to ${i} failed: ${oA}`,oA instanceof Error?oA:new Error(String(oA))))}}}}var $aA=typeof window<"u"&&window.__AFSM__?(n,c)=>{window.dispatchEvent(new CustomEvent(n,{detail:c}))}:typeof importScripts<"u"?(n,c)=>{postMessage({type:n,payload:c})}:()=>{};function dU(e,i){const n=this._state;this._state=e;const c=e.toString();e&&this.emit(c,n),this.emit(eh.STATECHANGED,e,n,i),this.updateDevTools({value:e,old:n,err:i instanceof Error?i.message:String(i)})}var eh=class ZC extends ZaA.default{constructor(i,n,c){super(),this.name=i,this.groupName=n,this._state=ZC.INIT,i||(i=Date.now().toString(36)),c?Object.setPrototypeOf(this,c):c=Object.getPrototypeOf(this),n||(this.groupName=this.constructor.name);const I=c[kZ];I?this.name=I.name+"-"+I.count++:c[kZ]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){const i=Object.getPrototypeOf(this),n=EU.get(i)||[];let c=new Set,I=[],C=[];const m=new Set,R=Object.getPrototypeOf(i);EU.has(R)&&(R.stateDiagram.forEach(T=>c.add(T)),R.allStates.forEach(T=>m.add(T))),n.forEach(({from:T,to:b,action:J})=>{typeof T=="string"?I.push({from:T,to:b,action:J}):T.length?T.forEach(gA=>{I.push({from:gA,to:b,action:J})}):C.push({to:b,action:J})}),I.forEach(({from:T,to:b,action:J})=>{m.add(T),m.add(b),m.add(J+"ing"),c.add(`${T} --> ${J}ing : ${J}`),c.add(`${J}ing --> ${b} : ${J} 🟢`),c.add(`${J}ing --> ${T} : ${J} 🔴`)}),C.forEach(({to:T,action:b})=>{c.add(`${b}ing --> ${T} : ${b} 🟢`),m.forEach(J=>{J!==T&&c.add(`${J} --> ${b}ing : ${b}`)})});const _=[...c];return Object.defineProperties(i,{stateDiagram:{value:_},allStates:{value:m}}),_}static get(i){let n;return typeof i=="string"?(n=ZC.instances.get(i),n||ZC.instances.set(i,n=new ZC(i,void 0,Object.create(ZC.prototype)))):(n=ZC.instances2.get(i),n||ZC.instances2.set(i,n=new ZC(i.constructor.name,void 0,Object.create(ZC.prototype)))),n}static getState(i){var n;return(n=ZC.get(i))===null||n===void 0?void 0:n.state}updateDevTools(i={}){$aA(ZC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){dU.call(this,i)}};eh.STATECHANGED="stateChanged",eh.UPDATEAFSM="updateAFSM",eh.INIT="[*]",eh.ON="on",eh.OFF="off",eh.instances=new Map,eh.instances2=new WeakMap;var KL=class extends eh{constructor(i,n){super(),this.core=i,Ms(this,"audioPlayer"),Ms(this,"videoPlayer"),Ms(this,"callback"),Ms(this,"avPlayerStateSyncManager"),Ms(this,"_log"),Ms(this,"_videoPlayerLog"),Ms(this,"_audioPlayerLog"),Ms(this,"lastPausedReason"),Ms(this,"muted",!1),this._log=n,this._videoPlayerLog=this._log.createChild({id:"vp"}),this._audioPlayerLog=this._log.createChild({id:"ap"}),this.videoPlayer=new i.VideoPlayer({id:"vp",log:this._videoPlayerLog,track:null,muted:!1,container:null,enableLogTrackState:!0}),this.audioPlayer=new i.RemoteAudioPlayer({id:"ap",log:this._audioPlayerLog,track:null,muted:!1,container:null,enableVolumeControlInIOS:!0,enableLogTrackState:!0}),this.audioPlayer.on(i.PlayerEvent.AUTOPLAY_FAILED,c=>this.handleAutoPlayFailed(this.audioPlayer,c)),this.videoPlayer.on(i.PlayerEvent.LOAD_START,()=>this.handleLoadStart("video")),this.audioPlayer.on(i.PlayerEvent.LOAD_START,()=>this.handleLoadStart("audio")),this.videoPlayer.on(i.PlayerEvent.PLAYER_STATE_CHANGED,this.handlePlayerStateChanged,this),this.audioPlayer.on(i.PlayerEvent.PLAYER_STATE_CHANGED,this.handlePlayerStateChanged,this),this.videoPlayer.on(i.PlayerEvent.ENTER_PICTURE_IN_PICTURE,this.handleEnterPictureInPicture,this),this.videoPlayer.on(i.PlayerEvent.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePictureInPicture,this),this.videoPlayer.on(i.PlayerEvent.ENTER_FULL_SCREEN,this.handleEnterFullScreen,this),this.videoPlayer.on(i.PlayerEvent.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.avPlayerStateSyncManager=new i.AVPlayerStateSyncManager({log:this._log,audioPlayer:this.audioPlayer,videoPlayer:this.videoPlayer})}get isPlaying(){return this.videoPlayer.isPlaying&&this.audioPlayer.isPlaying}get isPaused(){return this.videoPlayer.isPaused&&this.audioPlayer.isPaused}get isStopped(){return this.videoPlayer.isStopped&&this.audioPlayer.isStopped}setCallback(i){this.callback=i}updateLogConfig(i){this._audioPlayerLog.setSdkAppId(i.sdkAppId),this._audioPlayerLog.setUserId(i.userId),this._videoPlayerLog.setSdkAppId(i.sdkAppId),this._videoPlayerLog.setUserId(i.userId)}handleLoadStart(i){this.onLoadStart()}handlePlayerStateChanged(i){i.state==="PLAYING"&&this.isPlaying&&this.onPlaying(),i.state==="PAUSED"&&this.isPaused&&this.onPaused(i.reason),i.state==="STOPPED"&&this.isStopped&&this.onStopped()}async handleEnterPictureInPicture(){var i,n;await this.videoPlayer.enterPIPPromise,(n=(i=this.callback)==null?void 0:i.onPictureInPictureStateChanged)==null||n.call(i,{isPictureInPicture:!0,pictureInPictureWindow:this.videoPlayer.pipWindow})}handleLeavePictureInPicture(){var i,n;(n=(i=this.callback)==null?void 0:i.onPictureInPictureStateChanged)==null||n.call(i,{isPictureInPicture:!1})}handleEnterFullScreen(){var i,n;(n=(i=this.callback)==null?void 0:i.onFullScreenStateChanged)==null||n.call(i,{isFullScreen:!0})}handleLeaveFullScreen(){var i,n;(n=(i=this.callback)==null?void 0:i.onFullScreenStateChanged)==null||n.call(i,{isFullScreen:!1})}onLoadStart(){}onPlaying(){}onPaused(i){this.lastPausedReason=i}onStopped(){}setVideoContainer(i){if(this.core.utils.isString(i)){const n=document.getElementById(i);n&&this.videoPlayer.setContainer(n)}else this.videoPlayer.setContainer(i)}setVolume(i){this.core.utils.isUndefined(i)||this.audioPlayer.setVolume(i/100)}setMuted(i){this.core.utils.isUndefined(i)||(this.muted=i,this.audioPlayer.setMuted(i))}setFillMode(i){i&&this.videoPlayer.setObjectFit(i)}setAudioTrack(i){this.audioPlayer.setTrack(i)}setVideoTrack(i){this.videoPlayer.setTrack(i)}async play(){const i=this.videoPlayer.play().catch(c=>{this.handleAutoPlayFailed(this.videoPlayer,c,"video")}),n=this.audioPlayer.play().catch(c=>{this.handleAutoPlayFailed(this.audioPlayer,c)});await Promise.all([i,n])}handleAutoPlayFailed(i,n,c="audio"){var I,C;this._log.warn("handleAutoPlayFailed",n);const m=()=>{this.audioPlayer.resume().then(()=>{document.removeEventListener("click",m,!0)})};document.addEventListener("click",m,!0),(C=(I=this.callback)==null?void 0:I.onAutoPlayFailed)==null||C.call(I,{type:c,resume:()=>i.resume()})}pause(){this.videoPlayer.pause(!0),this.audioPlayer.setMuted(!0),this.audioPlayer.pause()}resume(){this.videoPlayer.resume(!0),this.audioPlayer.setMuted(this.muted),this.audioPlayer.resume()}async enterFullscreen(){await this.videoPlayer.enterFullscreen()}async exitFullscreen(){await this.videoPlayer.exitFullscreen()}async enterPictureInPicture(){await this.videoPlayer.enterPictureInPicture()}async exitPictureInPicture(){await this.videoPlayer.exitPictureInPicture()}stop(){this.videoPlayer&&this.videoPlayer.stop(),this.audioPlayer&&(this.audioPlayer.stop(),this.audioPlayer.setMuted(!1))}};z_([AY([eh.INIT,"PAUSED"],"LOADSTART",{ignoreError:!0,sync:!0,success(){var e,i;(i=(e=this.callback)==null?void 0:e.onLoadStart)==null||i.call(e)},fail(e){this._log.warn("onLoadStart",e)}})],KL.prototype,"onLoadStart"),z_([AY(["LOADSTART","PAUSED"],"PLAYING",{ignoreError:!0,sync:!0,success(){var e,i;(i=(e=this.callback)==null?void 0:e.onPlaying)==null||i.call(e)},fail(e){this._log.warn("onPlaying",e)}})],KL.prototype,"onPlaying"),z_([AY("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(){var e,i;(i=(e=this.callback)==null?void 0:e.onPaused)==null||i.call(e,{reason:this.lastPausedReason})},fail(e){this._log.warn("onPaused",e)}})],KL.prototype,"onPaused"),z_([AY([],eh.INIT,{ignoreError:!0,sync:!0,success(){var e,i;(i=(e=this.callback)==null?void 0:e.onStopped)==null||i.call(e)},fail(e){this._log.warn("onStopped",e)}})],KL.prototype,"onStopped");var LZ=KL,AgA=["overseas-webrtc.tlivewebrtc.com","oswebrtc-lint.tliveplay.com"],vY=class TX{constructor(i){this.core=i,Ms(this,"_sdkAppId"),Ms(this,"_userId"),Ms(this,"connectedRoomIdSet",new Set),Ms(this,"updateSeq",0),Ms(this,"_log"),Ms(this,"player"),Ms(this,"peerConnection"),Ms(this,"svrSig"),Ms(this,"streamURL"),Ms(this,"signalURL"),Ms(this,"insertableStreamsAbortMap",new Map),Ms(this,"scriptTransformWorker"),Ms(this,"connectionState","disconnected"),Ms(this,"isStarted",!1),Ms(this,"isStopped",!0),Ms(this,"isReconnecting",!1),Ms(this,"callback"),Ms(this,"isFireWallErrorEmitted",!1),Ms(this,"stat"),Ms(this,"isH264DecodeSupported"),Ms(this,"connectionTimeoutId"),Ms(this,"streamHealthCheckTimeoutId"),Ms(this,"streamHealthCheckReject"),i.loggerManager.startUpload(),this._log=this.core.log.createChild({id:`${this.getAlias()}`}),this.player=new LZ(i,this._log),i.innerEmitter.on(i.INNER_EVENT.SEI_MESSAGE,this.onSEIMessage,this)}getName(){return TX.Name}getAlias(){return"LEB"}getGroup(){return""}getValidateRule(i){switch(i){case"start":return xaA;case"update":case"stop":return{}}}get enableSEI(){return this.core.room.enableSEI&&(this.core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED||this.core.rtcDectection.IS_SCRIPT_TRANSFORM_SUPPORTED)}wrapCallback(i){if(!i)return;const n={},c=["onStats","onSEIMessage"];for(const I of Object.keys(i)){const C=i[I];typeof C=="function"&&(c.includes(I)?n[I]=C:n[I]=(...m)=>(this._log.debug(`callback ${I} called`,m.length>0?m[0]:""),C(...m)))}return n}async start(i){var n;this.isStopped=!1;const{view:c,url:I,volume:C,muted:m,fillMode:R,loggerConfig:_,callback:T}=i;this.callback=this.wrapCallback(T),this.player.setCallback(this.callback);const{errorModule:{RtcError:b,ErrorCode:J,ErrorCodeDictionary:gA},loggerManager:eA,rtcDectection:CA}=this.core;if(this._sdkAppId=_.sdkAppId,this._userId=_.userId,this._log.setSdkAppId(_.sdkAppId),this._log.setUserId(_.userId),this.player.updateLogConfig(_),eA.addJoinedUser(_),!CA.isWebRTCSupported()||!CA.isAddTransceiverSupported())throw new b({code:J.ENV_NOT_SUPPORTED,extraCode:gA.NOT_SUPPORTED_WEBRTC,message:"webrtc not supported"});if(!(await CA.decodeSupportStatus()).isH264DecodeSupported||this.isH264DecodeSupported===!1)throw this.isH264DecodeSupported=!1,new b({code:J.ENV_NOT_SUPPORTED,extraCode:gA.NOT_SUPPORTED_H264_DECODE,message:"h264 not supported"});!CA.IS_SEI_SUPPORTED&&T?.onSEIMessage&&((n=T.onError)==null||n.call(T,new b({code:J.ENV_NOT_SUPPORTED,extraCode:gA.NOT_SUPPORTED_SEI,message:"sei not supported"}))),this.player.setVideoContainer(c),this.player.setMuted(m),this.player.setFillMode(R);try{await this.connect(I),this.stat=new zaA(this.peerConnection,this.core),this.stat.start(vA=>{var qA,Ae;return(Ae=(qA=this.callback)==null?void 0:qA.onStats)==null?void 0:Ae.call(qA,vA)});const IA=this.player.play();this.player.setVolume(C);const oA=this.createStreamHealthCheckPromise();await Promise.race([IA,oA]),this.clearStreamHealthCheck(),this.isStarted=!0}catch(IA){throw this.stop(),IA}}async update(i){const{view:n,url:c,volume:I,muted:C,fillMode:m,action:R,fullScreen:_,pictureInPicture:T}=i;c&&c!==this.streamURL&&await this.switchStream(c),this.player.setMuted(C),this.player.setVolume(I),this.player.setFillMode(m),n&&this.player.videoPlayer.setContainer(this.core.utils.isString(n)?document.getElementById(n):n),R==="pause"?this.player.pause():R==="resume"&&this.player.resume(),this.core.utils.isBoolean(_)&&(_?await this.player.enterFullscreen():await this.player.exitFullscreen()),this.core.utils.isBoolean(T)&&(T?await this.player.enterPictureInPicture():await this.player.exitPictureInPicture())}async switchStream(i){this._log.info("switchStream",i);const n=this.peerConnection,c=this.streamURL,I=this.signalURL,C=this.svrSig,m=new Map(this.insertableStreamsAbortMap),R=this.player;delete this.peerConnection,delete this.streamURL,delete this.signalURL,delete this.svrSig,this.insertableStreamsAbortMap.clear();const _=new LZ(this.core,this._log);_.setVideoContainer(R.videoPlayer.container),_.setFillMode(R.videoPlayer.objectFit),_.setMuted(R.muted),_.setCallback(this.callback);const T=b=>{const{track:J}=b;this.createEncodedStreams(b.receiver),this.initReceiverTransform(b.receiver,J.kind==="audio"),J.kind==="audio"?_.setAudioTrack(J):_.setVideoTrack(J)};try{await this.connectForSwitch(i,T),this._log.info("switchStream: new connection established"),await this.waitForNewPlayerFirstFrame(_),this._log.info("switchStream: new stream first frame received"),R.audioPlayer.setMuted(!0),R.stop(),this.player=_,n&&(clearTimeout(this.connectionTimeoutId),n.close(),n.getReceivers().forEach(b=>m.delete(b)),c&&C&&I&&this.fetchStopStreamWithParams(c,I,C).catch(b=>{this._log.warn("switchStream: stop old stream failed",b)})),this._log.info("switchStream: switch completed successfully")}catch(b){this._log.error("switchStream failed",b),_.stop();const J=this.peerConnection;throw J&&(J.close(),J.getReceivers().forEach(gA=>this.insertableStreamsAbortMap.delete(gA))),this.peerConnection=n,this.streamURL=c,this.signalURL=I,this.svrSig=C,this.insertableStreamsAbortMap=m,this.player=R,R.audioPlayer.setMuted(R.muted),b}}waitForNewPlayerFirstFrame(i){return new Promise((n,c)=>{let I=0,C=!1;const m=i.videoPlayer.getElement();if(!m)return void c(new Error("VideoPlayer has no video element"));const R=()=>{C=!0,clearInterval(b),m.removeEventListener("loadeddata",_),m.removeEventListener("playing",T)},_=()=>{C||(this._log.info("waitForNewPlayerFirstFrame: loadeddata event fired"),R(),n())},T=()=>{C||(this._log.info("waitForNewPlayerFirstFrame: playing event fired"),R(),n())};m.addEventListener("loadeddata",_,{once:!0}),m.addEventListener("playing",T,{once:!0}),i.play().catch(J=>{this._log.warn("waitForNewPlayerFirstFrame: play failed",J)});const b=setInterval(()=>{if(!C){if(I+=100,m.videoWidth>0&&m.videoHeight>0)return this._log.info(`waitForNewPlayerFirstFrame: video has valid dimensions ${m.videoWidth}x${m.videoHeight}`),R(),void n();I>=1e4&&(R(),c(new Error("waitForNewPlayerFirstFrame timeout")))}},100)})}connectForSwitch(i,n){return new Promise((c,I)=>{try{this.initScriptTransformWorker();const C={encodedInsertableStreams:this.enableSEI,iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},m=new RTCPeerConnection(C);this.peerConnection=m,m.onconnectionstatechange=()=>{this.connectionState=m.connectionState,this._log.info("connectForSwitch connectionState",m.connectionState),m.connectionState!=="failed"&&m.connectionState!=="closed"||I(new Error(`connection is ${m.connectionState}`)),m.connectionState==="connected"&&(this.logSelectedCandidate(),c())},m.ontrack=n,m.addTransceiver("audio",{direction:"recvonly"}),m.addTransceiver("video",{direction:"recvonly"}),this._log.info("connectForSwitch createOffer"),m.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}).then(R=>(R.sdp=GZ(R.sdp),this._log.info("connectForSwitch setOffer"),m.setLocalDescription(R))).then(()=>{const R={sessionId:l3(),streamurl:i,clientinfo:this.core.environment.getOSString(),localsdp:m.localDescription};return this.exchangeSDP(i,R)}).then(R=>(this._log.info("connectForSwitch setAnswer"),m.setRemoteDescription(R))).catch(I)}catch(C){I(C)}this.connectionTimeoutId=setTimeout(()=>I(new Error("connection timeout")),1e4)})}async fetchStopStreamWithParams(i,n,c){try{const I=`${n}/webrtc/v1/stopstream`,C=await eY(I,{streamurl:i,svrsig:c},{timeout:3}),{errcode:m,errmsg:R}=C;if(m!==0)throw new Error(`errCode:${m}, errmsg:${R}`);return C}catch(I){this._log.error("fetchStopStreamWithParams error",I)}}async stop(){this.isStopped=!0,this.clearStreamHealthCheck(),this.player.stop(),this.peerConnection&&(clearTimeout(this.connectionTimeoutId),this.peerConnection.close(),this.peerConnection.getReceivers().forEach(i=>this.insertableStreamsAbortMap.delete(i)),delete this.peerConnection,await this.fetchStopStream(),delete this.streamURL,delete this.signalURL,delete this.svrSig),this.stat&&(this.stat.stop(),delete this.stat),this.core.room.keyPointManager.uploadKVStat(this.core.kvStatManager,this._sdkAppId)}destroy(){this.stop(),this.core.innerEmitter.off(this.core.INNER_EVENT.SEI_MESSAGE,this.onSEIMessage,this)}createStreamHealthCheckPromise(){return new Promise((i,n)=>{this.streamHealthCheckReject=n,this.streamHealthCheckTimeoutId=window.setTimeout(()=>this.checkStreamHealth(n),5e3)})}clearStreamHealthCheck(){this.streamHealthCheckTimeoutId&&(clearTimeout(this.streamHealthCheckTimeoutId),delete this.streamHealthCheckTimeoutId),delete this.streamHealthCheckReject}async checkStreamHealth(i){if(!this.isStopped&&this.peerConnection)try{const n=this.peerConnection.getReceivers().find(J=>{var gA;return((gA=J.track)==null?void 0:gA.kind)==="video"});if(!n)return void this._log.warn("checkStreamHealth: no video receiver found");const c=await n.getStats();let I=0,C=0;c.forEach(J=>{J.type==="inbound-rtp"&&(J.mediaType==="video"||J.kind==="video")&&(I=J.bytesReceived||0,C=J.framesDecoded||0)});const{isPlaying:m}=this.player,R=m||C>0;this._log.info(`checkStreamHealth: bytesReceived=${I}, framesDecoded=${C}, isPlaying=${m}`);const{RtcError:_,ErrorCode:T,ErrorCodeDictionary:b}=this.core.errorModule;I===0?(this._log.warn("checkStreamHealth: no stream data received after 5s"),i(new _({code:T.OPERATION_FAILED,message:"no stream data received"}))):R||(this._log.warn("checkStreamHealth: decode failed"),this.isH264DecodeSupported=!1,i(new _({code:T.ENV_NOT_SUPPORTED,extraCode:b.NOT_SUPPORTED_H264_DECODE,message:"h264 decode failed"})))}catch(n){this._log.warn("checkStreamHealth error",n)}}connect(i){return new Promise((n,c)=>{try{this.initScriptTransformWorker();const I={encodedInsertableStreams:this.enableSEI,iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},C=new RTCPeerConnection(I);this.peerConnection=C,C.onconnectionstatechange=()=>{this.connectionState=C.connectionState,this._log.info("connectionState",C.connectionState),C.connectionState!=="failed"&&C.connectionState!=="closed"||(this.isStarted?this.reconnect(i):c(new Error(`connection is ${C.connectionState}`))),C.connectionState==="connected"&&(this.logSelectedCandidate(),n())},C.ontrack=m=>this.onTrack(m),C.addTransceiver("audio",{direction:"recvonly"}),C.addTransceiver("video",{direction:"recvonly"}),this._log.info("createOffer"),C.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}).then(m=>(m.sdp=GZ(m.sdp),this._log.info("setOffer"),C.setLocalDescription(m))).then(()=>{const m={sessionId:l3(),streamurl:i,clientinfo:this.core.environment.getOSString(),localsdp:C.localDescription};return this.exchangeSDP(i,m)}).then(m=>(this._log.info("setAnswer"),C.setRemoteDescription(m))).catch(c)}catch(I){c(I)}this.connectionTimeoutId=setTimeout(()=>c(new Error("connection timeout")),1e4)})}async exchangeSDP(i,n){let c,I,C;try{this._log.info("exchangeSDP");const m=egA(i);if(!m)throw new Error("streamDomain is empty");const{signalDomain:R,cached:_}=await this.fetchSignalDomain(m);if(!R)throw new Error("signalDomain is empty");{this._log.info("try exchangeSDP signalDomain:",R,_);const T=await this.doExchangeSDP(`https://${R}`,n,3);c=T.url,I=T.remoteSdp,C=T.svrSig}}catch(m){this._log.warn("exchangeSDP failed, fallback",m);try{const R=await this.core.utils.promiseAny(AgA.map(_=>this.doExchangeSDP(`https://${_}`,n,3)));c=R.url,I=R.remoteSdp,C=R.svrSig}catch(R){throw this._log.error("exchangeSDP failed",R),R[0]||R}}return this.streamURL=i,this.signalURL=c,this.svrSig=C,I}async reconnect(i){var n,c;if(!this.isReconnecting){this.isReconnecting=!0;try{this._log.warn("start reconnect"),await this.connect(i),this._log.warn("reconnect success")}catch(I){this._log.error("reconnect error",I);const{RtcError:C,ErrorCode:m}=this.core.errorModule;(c=(n=this.callback)==null?void 0:n.onError)==null||c.call(n,new C({code:m.OPERATION_FAILED,message:"reconnect failed"}))}finally{this.isReconnecting=!1}}}async logSelectedCandidate(){if(!this.peerConnection)return;const i=await this.peerConnection.getStats();for(const[n,c]of i)if(this.core.rtcDectection.isSelectedCandidatePair(c)){const I=i.get(c.localCandidateId),C=i.get(c.remoteCandidateId);I&&this._log.info(`local candidate: ${I.candidateType} ${I.protocol}:${I.ip||I.address}:${I.port} ${I.networkType||""} ${I.relayProtocol?`relayProtocol:${I.relayProtocol} url: ${I.url}`:""}`),C&&this._log.info(`remote candidate: ${C.candidateType} ${C.protocol}:${C.ip||C.address}:${C.port}`);break}}async doExchangeSDP(i,n,c){const I=`${i}/webrtc/v1/pullstream`,C=await eY(I,n,{timeout:c}),{errcode:m,errmsg:R,remotesdp:_,svrsig:T}=C;if(m!==0){const b=new Error(`errCode:${m}, errMsg:${R}`);throw b.name="RequestSignalError",b}return{url:i,remoteSdp:_,svrSig:T}}createEncodedStreams(i){var n;if(this.enableSEI&&this.core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED)try{if(this._log.warn("enableSEI",this.enableSEI),!this.insertableStreamsAbortMap.has(i)){const c=i.createEncodedStreams(),I=new AbortController,C={abortController:I,enqueue:m=>i.track.kind==="audio"?m:this.decodeVideoFrame(m)};c.readable.pipeThrough(new TransformStream({transform:(m,R)=>{const _=C.enqueue(m);_&&R.enqueue(_)}})).pipeTo(c.writable,I).catch(m=>{m!=="destroy"&&this._log.warn(m)}),(n=this.insertableStreamsAbortMap.get(i))==null||n.abort("destroy"),this.insertableStreamsAbortMap.set(i,I)}}catch(c){this._log.warn(`createEncodedStreams ${i.track.kind} failed`,c)}}initReceiverTransform(i,n){this.peerConnection&&this.enableSEI&&this.scriptTransformWorker&&!i.transform&&(i.transform=new RTCRtpScriptTransform(this.scriptTransformWorker,{isReceiver:!0,isAudio:n,userId:"",streamType:this.core.enums.RemoteStreamType.Main}))}initScriptTransformWorker(){const{room:i,rtcDectection:n,createScriptTransformWorker:c,trtc:I,TRTC:C}=this.core;!this.enableSEI||n.IS_INSERTABLE_STREAM_SUPPORTED||this.scriptTransformWorker||n.IS_SCRIPT_TRANSFORM_SUPPORTED&&(this._log.info("initScriptTransformWorker"),this.scriptTransformWorker=c({videoEncodePipeline:i.videoManager.encodePipeline,videoDecodePipeline:i.videoManager.decodePipeline,audioEncodePipeline:i.audioManager.encodePipeline,audioDecodePipeline:i.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=m=>{var R,_;m.data.type==="sei"&&((_=(R=this.callback)==null?void 0:R.onSEIMessage)==null||_.call(R,{data:m.data.data,seiPayloadType:m.data.seiPayloadType}))},this.scriptTransformWorker.onerror=m=>{this._log.error("scriptTransformWorker error: ",m.message)})}decodeVideoFrame(i){if(!this.core.room.videoManager)return i;for(const n of this.core.room.videoManager.decodePipeline)if(n&&!(i=n({frame:i})))return;return i}async fetchStopStream(){if(this.streamURL&&this.svrSig&&this.signalURL)try{const i=`${this.signalURL}/webrtc/v1/stopstream`,n=await eY(i,{streamurl:this.streamURL,svrsig:this.svrSig},{timeout:3}),{errcode:c,errmsg:I}=n;if(c!==0)throw new Error(`errCode:${c}, errmsg:${I}`);return n}catch(i){this._log.error("fetchStopStream error",i)}}onTrack(i){const{track:n}=i;this.createEncodedStreams(i.receiver),this.initReceiverTransform(i.receiver,n.kind==="audio"),n.kind==="audio"?this.player.setAudioTrack(n):this.player.setVideoTrack(n)}onSEIMessage({room:i,nalu:n}){var c,I;i===this.core.room&&((I=(c=this.callback)==null?void 0:c.onSEIMessage)==null||I.call(c,{data:n.seiPayload.buffer,seiPayloadType:n.seiPayloadType}))}async fetchSignalDomain(i,n=tY[0]){var c;const I=`https://${n}/signal_query`;try{const C=window.localStorage.getItem(E3);if(C){const b=JSON.parse(C);if(((c=b[i])==null?void 0:c.expire)-new Date().getTime()>0)return{signalDomain:b[i].signal,cached:!0}}const m=await eY(I,{domain:i,requestid:l3(16),client_type:"Web",client_info:window.navigator.userAgent}),{errcode:R,errmsg:_,data:T}=m;if(R===0){const{signal_domain:b,cache_time:J}=T;let gA={};const eA=window.localStorage.getItem(E3);eA&&(gA=JSON.parse(eA)),gA[i]={signal:b,expire:new Date().getTime()+1e3*J};try{window.localStorage.setItem(E3,JSON.stringify(gA))}catch{}return{signalDomain:b,cached:!1}}throw new Error(`errCode:${R} errmsg:${_}`)}catch(C){return this._log.error("fetchSignalDomain error",C),tY[1]&&n!==tY[1]?this.fetchSignalDomain(i,tY[1]):{signalDomain:"",cached:!1}}}};Ms(vY,"Name","LEBPlayer"),z_([WaA({fnName:"connect"})],vY.prototype,"stop"),z_([jaA({settings:{retries:1/0,timeout:2e3},onRetrying(e){var i;if(this._log.warn(`retry connect ${e}`),e>=3&&((i=this.callback)==null?void 0:i.onError)&&!this.isFireWallErrorEmitted){const{RtcError:n,ErrorCode:c,ErrorCodeDictionary:I}=this.core.errorModule;this.isFireWallErrorEmitted=!0,this.callback.onError(new n({code:c.OPERATION_FAILED,extraCode:I.FIREWALL_RESTRICTION,message:"firewall restriction"}))}},onError(e,i,n,c){var I;if(this._log.warn("connect failed",e),this.peerConnection&&(this.peerConnection.close(),delete this.peerConnection),!this.isStopped&&((I=e.message||e)==null?void 0:I.includes("connection")))i();else{const{RtcError:C,ErrorCode:m}=this.core.errorModule;n(new C({code:m.UNKNOWN_ERROR,message:e.message}))}}})],vY.prototype,"connect");var NX=vY,eY=async(e,i,n={})=>{const{timeout:c=10}=n;let I,C=0,m={};window.AbortController&&(I=new window.AbortController,m={signal:I.signal},C=window.setTimeout(()=>I.abort(),1e3*c));const R=await fetch(e,LaA({body:JSON.stringify(i),cache:"no-cache",credentials:"same-origin",headers:{"content-type":"text/plain;charset=utf-8"},method:"POST",mode:"cors"},m));if(C&&window.clearTimeout(C),R.status!==200)throw new Error(`Network Error, status code:${R.status}`);return R.json()},tY=["webrtc-signal-scheduler.tlivesource.com","bak-webrtc-signal-scheduler.tlivesource.com"],E3="LEB_PLAYER_STORAGE_KEY",egA=e=>{const i=/^(?:webrtc:\/\/)([0-9.\-A-Za-z_]+)(?:\/)(?:[0-9.\-A-Za-z_=]+)(?:\/)(?:[^?#]*)(?:\?*)(?:[^?#]*)/.exec(e);return i?i[1]:""},tgA=NX;const igA=Object.freeze(Object.defineProperty({__proto__:null,LEBPlayer:NX,default:tgA},Symbol.toStringTag,{value:"Module"})),ogA=$U(igA);var GX=Object.defineProperty,ngA=Object.defineProperties,sgA=Object.getOwnPropertyDescriptors,UZ=Object.getOwnPropertySymbols,rgA=Object.prototype.hasOwnProperty,agA=Object.prototype.propertyIsEnumerable,dW=(e,i,n)=>i in e?GX(e,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[i]=n,ggA=(e,i)=>{for(var n in i||(i={}))rgA.call(i,n)&&dW(e,n,i[n]);if(UZ)for(var n of UZ(i))agA.call(i,n)&&dW(e,n,i[n]);return e},cgA=(e,i)=>ngA(e,sgA(i)),lgA=(e,i)=>{for(var n in i)GX(e,n,{get:i[n],enumerable:!0})},Wg=(e,i,n)=>dW(e,typeof i!="symbol"?i+"":i,n);async function IgA({sdkAppId:e,userId:i,userSig:n,core:c}){var I;const C=Math.round(new Date().getTime()/1e3);try{const m=await c.schedule.getAbilityConfig(e,c.schedule.ScheduleRequestType.TRTC_AUTO_CONF,{sdkAppId:e,userId:i,userSig:n,timestamp:C});c.log.info(`virtual background ability response: ${JSON.stringify(m)}`);const{data:R}=m;return(I=R?.trtcAutoConf)!=null&&I.web_ar?{auth:!0,timestamp:C}:{auth:!1}}catch(m){return c.log.error("virtual background fetch error",m),{auth:!1}}}var ugA={sdkAppId:{required:!0,type:"number"},userId:{required:!0,type:"string"},userSig:{required:!0,type:"string"}};function EgA(e){return{name:"VirtualBackgroundOptions",type:"object",required:!0,allowEmpty:!1,properties:cgA(ggA({},ugA),{type:{required:!1,type:"string",values:["image","blur","color"]},src:{required:!1,type:"string"},blurLevel:{required:!1,type:"number",min:1,max:10},onAbort:{required:!1},color:{required:!1,type:["array","string"]},enableFaceCentering:{required:!1,type:"boolean"},enableEffectOptimization:{required:!1,type:"boolean"}}),validate(i,n,c,I){var C;const{RtcError:m,ErrorCode:R,ErrorCodeDictionary:_}=e.errorModule;if(!i)return;const{type:T,src:b,onAbort:J}=i;if(T==="image"&&!b)throw new m({code:R.INVALID_PARAMETER,extraCode:_.INVALID_PARAMETER_REQUIRED,fnName:c,messageParams:{key:"src"}});if(J&&!e.utils.isFunction(J))throw new m({code:R.INVALID_PARAMETER,extraCode:_.INVALID_PARAMETER_TYPE,fnName:c,messageParams:{key:"onAbort",value:typeof J,rule:{type:"Function"}}});if(!((C=e.room.videoManager.cameraTrack)!=null&&C.mediaTrack))throw new m({code:R.INVALID_OPERATION,extraCode:_.INVALID_OPERATION_NEED_VIDEO,fnName:c})}}}function dgA(e){return{name:"UpdateVirtualBackgroundOptions",type:"object",required:!0,allowEmpty:!1,properties:{type:{required:!0,type:"string",values:["image","blur","color"]},src:{required:!1,type:"string"},blurLevel:{required:!1,type:"number",min:1,max:10},color:{required:!1,type:["array","string"]},enableFaceCentering:{required:!1,type:"boolean"},enableEffectOptimization:{required:!1,type:"boolean"}},validate(i,n,c,I){if(!i)return;const{RtcError:C,ErrorCode:m,ErrorCodeDictionary:R}=e.errorModule,{type:_,src:T}=i;if(_==="image"&&!T)throw new C({code:m.INVALID_PARAMETER,extraCode:R.INVALID_PARAMETER_REQUIRED,fnName:c,messageParams:{key:"src"}})}}}function CgA(e){return{name:"StopVirtualBackgroundOptions",required:!1}}var hgA=(()=>{var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(i={}){var n,c,I=i;I.ready=new Promise(($,j)=>{n=$,c=j});var C=Object.assign({},I),m="";typeof document<"u"&&document.currentScript&&(m=document.currentScript.src),e&&(m=e),m=m.indexOf("blob:")!==0?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var R,_,T=I.print||console.log.bind(console),b=I.printErr||console.error.bind(console);function J($){if($t($))return function(j){for(var RA=atob(j),ZA=new Uint8Array(RA.length),ne=0;ne$.startsWith(pt);function Pt($){return Promise.resolve().then(()=>function(j){if(j==ae&&R)return new Uint8Array(R);var RA=J(j);if(RA)return RA;throw"both async and sync fetching of the wasm failed"}($))}function ii($,j,RA,ZA){return function(ne,De,Ke){return Pt(ne).then(qe=>WebAssembly.instantiate(qe,De)).then(qe=>qe).then(Ke,qe=>{b(`failed to asynchronously prepare wasm: ${qe}`),Xe(qe)})}(j,RA,ZA)}$t(ae="data:application/octet-stream;base64,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IAEoAgA2AgAgAiABKAIENgIEIAIgASgCCDYCCCACIAEoAgw2AgwgAiABKAIQNgIQIAIgASgCFDYCFCACIAEoAhg2AhggAiABKAIcNgIcIAIgASgCIDYCICACIAEoAiQ2AiQgAiABKAIoNgIoIAIgASgCLDYCLCACIAEoAjA2AjAgAiABKAI0NgI0IAIgASgCODYCOCACIAEoAjw2AjwgAUFAayEBIAJBQGsiAiAFTQ0ACwsgAiAETw0BA0AgAiABKAIANgIAIAFBBGohASACQQRqIgIgBEkNAAsMAQsgA0EESQRAIAAhAgwBCyAAIANBBGsiBEsEQCAAIQIMAQsgACECA0AgAiABLQAAOgAAIAIgAS0AAToAASACIAEtAAI6AAIgAiABLQADOgADIAFBBGohASACQQRqIgIgBE0NAAsLIAIgA0kEQANAIAIgAS0AADoAACABQQFqIQEgAkEBaiICIANHDQALCyAACwsAIAEgAiAAEEIaCxIAIAFBAXRB8MoAakECIAAQQgv5AQEEfwJ/IAEQKiECIwBBEGsiBSQAAn8gAC0AC0EHdgRAIAAoAgQMAQsgAC0AC0H/AHELIgRBAE8EQAJAIAIgAC0AC0EHdgR/IAAoAghB/////wdxQQFrBUEKCyIDIARrTQRAIAJFDQECfyAALQALQQd2BEAgACgCAAwBCyAACyIDIAQEfyACIANqIAMgBBBFIAEgAkEAIAMgBGogAUsbQQAgASADTxtqBSABCyACEEUgACACIARqIgEQMSAFQQA6AA8gASADaiAFLQAPOgAADAELIAAgAyACIARqIANrIARBACACIAEQRAsgBUEQaiQAIAAMAQsQJwALC/ICAgJ/AX4CQCACRQ0AIAAgAToAACAAIAJqIgNBAWsgAToAACACQQNJDQAgACABOgACIAAgAToAASADQQNrIAE6AAAgA0ECayABOgAAIAJBB0kNACAAIAE6AAMgA0EEayABOgAAIAJBCUkNACAAQQAgAGtBA3EiBGoiAyABQf8BcUGBgoQIbCIBNgIAIAMgAiAEa0F8cSIEaiICQQRrIAE2AgAgBEEJSQ0AIAMgATYCCCADIAE2AgQgAkEIayABNgIAIAJBDGsgATYCACAEQRlJDQAgAyABNgIYIAMgATYCFCADIAE2AhAgAyABNgIMIAJBEGsgATYCACACQRRr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ACACQQA6AA8DQCABBEAgACACLQAPOgAAIAFBAWshASAAQQFqIQAMAQsLIAJBEGokAAsaACAALQALQQd2BEAgACgCCBogACgCABAZCwvmAQEFfyMAQRBrIgUkACMAQSBrIgMkACMAQRBrIgQkACAEIAA2AgwgBCAAIAFqNgIIIAMgBCgCDDYCGCADIAQoAgg2AhwgBEEQaiQAIAMoAhghBCADKAIcIQYjAEEQayIBJAAgASAGNgIMIAIgBCAGIARrIgQQQyABIAIgBGo2AgggAyABKAIMNgIQIAMgASgCCDYCFCABQRBqJAAgAyAAIAMoAhAgAGtqNgIMIAMgAiADKAIUIAJrajYCCCAFIAMoAgw2AgggBSADKAIINgIMIANBIGokACAFKAIMIQcgBUEQaiQAIAcLDwAgAgRAIAAgASACEDILC/UCAQV/IwBBEGsiByQAIAIgAUF/c0Hv////B2pNBEACfyAALQALQQd2BEAgACgCAAwBCyAACyEIIAdBBGoiCSAAIAFB5////wNJBH8gByABQQF0NgIMIAcgASACajYCBCMAQRBrIgIkACAJKAIAIAdBDGoiCigCAEkhCyACQRBqJAAgCiAJIAsbKAIAIgJBC08EfyACQRBqQXBxIgIgAkEBayICIAJBC0YbBUEKC0EBagVB7////wcLEDAgBygCBCECIAcoAggaIAQEQCACIAggBBAjCyAFBEAgAiAEaiAGIAUQIwsgAyAEayEGIAMgBEcEQCACIARqIAVqIAQgCGogBhAjCyABQQpHBEAgCBAZCyAAIAI2AgAgACAAKAIIQYCAgIB4cSAHKAIIQf////8HcXI2AgggACAAKAIIQYCAgIB4cjYCCCAAIAQgBWogBmoiADYCBCAHQQA6AAwgACACaiAHLQAMOgAAIAdBEGokAA8LECcACwoAIAAgASACEEMLuQEBBH8jAEEQayIEJAAgBCACNgIMIwBBoAFrIgMkACADIAAgA0GeAWogARsiBjYClAFBfyEFIAMgAUEBayIAQQAgACABTRs2ApgBIANBAEGQARAmIgBBfzYCTCAAQSA2AiQgAEF/NgJQIAAgAEGfAWo2AiwgACAAQZQBajYCVAJAIAFBAEgEQEHo3gBBPTYCAAwBCyAGQQA6AAAgAEH9CiACQR8QTSEFCyAAQaABaiQAIARBEGokACAFCwQA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KAIARQ0AIAIgBCgCGDYCAAsgAEEBRiEFDAELQQAhBQsgBEFAayQAIAULMQAgACABKAIIQQAQHgRAIAEgAiADED0PCyAAKAIIIgAgASACIAMgACgCACgCHBEGAAsYACAAIAEoAghBABAeBEAgASACIAMQPQsLnQEBAn8jAEFAaiIDJAACf0EBIAAgAUEAEB4NABpBACABRQ0AGkEAIAFBjM0AECAiAUUNABogA0EMakEAQTQQJhogA0EBNgI4IANBfzYCFCADIAA2AhAgAyABNgIIIAEgA0EIaiACKAIAQQEgASgCACgCHBEGACADKAIgIgBBAUYEQCACIAMoAhg2AgALIABBAUYLIQQgA0FAayQAIAQLCgAgACABQQAQHgtOAgF/AXwjAEEQayICJAAgAkEANgIMIAEoAgRB1M8AIAJBDGoQCSEDIAIoAgwiAQRAIAEQAQsgACADRAAAAAAAAAAAYjoAOCACQRBqJAALNwEBfyMAQRBrIgIkACACIAEtADg2AgggAEHUzwAgAkEIahAHNgIEIABB1NUANgIAIAJBEGokAAuoAQEFfyAAKAJUIgMoAgAhBSADKAIEIgQgACgCFCAAKAIcIgdrIgYgBCAGSRsiBgRAIAUgByAGECIaIAMgAygCACAGaiIFNgIAIAMgAygCBCAGayIENgIECyAEIAIgAiAESxsiBARAIAUgASAEECIaIAMgAygCACAEaiIFNgIAIAMgAygCBCAEazYCBAsgBUEAOgAAIAAgACgCLCIBNgIcIAAgATYCFCACC5wBAQJ/IwBBEGsiAiQAQcgAEBwhASAAKAIEIgAQAiACIAA2AgggAUHMLSACQQhqEAc2AgQgAUHU1QA2AgAgAUEBNgIcIAFB1NUANgIYIAFBATYCFCABQdTVADYCECABQQE2AgwgAUHU1QA2AgggAUEAOgAgIAFBADYCRCABQoCAgIAwNwI8IAFBADsANyABQQA7ACsgAkEQaiQAIAELigUCBn4CfyABIAEoAgBBB2pBeHEiAUEQajYCACAAIQkgASkDACEDIAEpAwghBSMAQSBrIgAkAAJAIAVC////////////AIMiBEKAgICAgIDAgDx9IARCgICAgICAwP/DAH1UBEAgBUIEhiADQjyIhCEEIANC//////////8PgyIDQoGAgICAgICACFoEQCAEQoGAgICAgICAwAB8IQIMAgsgBEKAgICAgICAgEB9IQIgA0KAgICAgICAgAhSDQEgAiAEQgGDfCECDAELIANQIARCgICAgICAwP//AFQgBEKAgICAgIDA//8AURtFBEAgBUIEhiADQjyIhEL/////////A4NCgICAgICAgPz/AIQhAgwBC0KAgICAgICA+P8AIQIgBEL///////+//8MAVg0AQgAhAiAEQjCIpyIBQZH3AEkNACADIQIgBUL///////8/g0KAgICAgIDAAIQiBCEGAkAgAUGB9wBrIghBwABxBEAgAyAIQUBqrYYhBkIAIQIMAQsgCEUNACAGIAitIgeGIAJBwAAgCGutiIQhBiACIAeGIQILIAAgAjcDECAAIAY3AxgCQEGB+AAgAWsiAUHAAHEEQCAEIAFBQGqtiCEDQgAhBAwBCyABRQ0AIARBwAAgAWuthiADIAGtIgKIhCEDIAQgAoghBAsgACADNwMAIAAgBDcDCCAAKQMIQgSGIAApAwAiA0I8iIQhAiAAKQMQIAApAxiEQgBSrSADQv//////////D4OEIgNCgYCAgICAgIAIWgRAIAJCAXwhAgwBCyADQoCAgICAgICACFINACACQgGDIAJ8IQILIABBIGokACAJIAIgBUKAgICAgICAgIB/g4S/OQMAC0ABAn8jAEEQayICJAAgAiABNgIMIAJB1NUANgIIIAJBCGogABEBACEDIAIoAgwiAQRAIAEQAwsgAkEQaiQAIAMLBABCAAsEAEEAC/YCAQh/IwBBIGsiAyQAIAMgACgCHCIENgIQIAAoAhQhBSADIAI2AhwgAyABNgIYIAMgBSAEayIBNgIUIAEgAmohBUECIQcCfwJAAkACQCAAKAI8IANBEGoiAUECIANBDGoQDSIEBH9B6N4AIAQ2AgBBfwVBAAsEQCABIQQMAQsDQCAFIAMoAgwiBkYNAiAGQQBIBEAgASEEDAQLIAEgBiABKAIEIghLIglBA3RqIgQgBiAIQQAgCRtrIgggBCgCAGo2AgAgAUEMQQQgCRtqIgEgASgCACAIazYCACAFIAZrIQUgACgCPCAEIgEgByAJayIHIANBDGoQDSIGBH9B6N4AIAY2AgBBfwVBAAtFDQALCyAFQX9HDQELIAAgACgCLCIBNgIcIAAgATYCFCAAIAEgACgCMGo2AhAgAgwBCyAAQQA2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EGokAAsiAQF+IAEgAq0gA61CIIaEIAQgABEMACIFQiCIpyQBIAWnCzcBAX8jAEEQayICJAAgAiABKAI8NgIIIABBnNAAIAJBCGoQBzYCBCAAQdTVADYCACACQRBqJAALC/NKFQBBgAgLhCZzZXRCZWF1dHkALSsgICAwWDB4AC0wWCswWCAwWC0weCsweCAweAB1bnNpZ25lZCBzaG9ydAB1bnNpZ25lZCBpbnQAaW5pdABmbG9hdAB1aW50NjRfdABibHVyUmFkaXVzAHZlY3RvcgBtaXJyb3IAYXR0YWNoU2hhZGVyAGRlbGV0ZVNoYWRlcgBjcmVhdGVTaGFkZXIAY29tcGlsZVNoYWRlcgB1bnNpZ25lZCBjaGFyAHN0ZDo6ZXhjZXB0aW9uAHJvdGF0aW9uAG5hbgBsaW5rUHJvZ3JhbQBkZWxldGVQcm9ncmFtAGNyZWF0ZVByb2dyYW0AYm9vbABlbXNjcmlwdGVuOjp2YWwAc2V0V2F0ZXJNYXJrAHN0b3BXYXRlck1hcmsAdW5zaWduZWQgbG9uZwBzdGQ6OndzdHJpbmcAYmFzaWNfc3RyaW5nAHN0ZDo6c3RyaW5nAHN0ZDo6dTE2c3RyaW5nAHN0ZDo6dTMyc3RyaW5nAGluZgAlZgBjbG9zZQBkb3VibGUAdmJNb2RlAHNoYWRlclNvdXJjZQB2b2lkAHNhbXBsZUNvbG9yICs9IHRleHR1cmUoZnJhbWUsIGJsdXJDb29yZGluYXRlc1sATkFOAElORgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxzaG9ydD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgc2hvcnQ+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGludD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgaW50PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxmbG9hdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dWludDhfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50OF90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1aW50MTZfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50MTZfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dWludDY0X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGludDY0X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PHVpbnQzMl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxpbnQzMl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxjaGFyPgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1bnNpZ25lZCBjaGFyPgBzdGQ6OmJhc2ljX3N0cmluZzx1bnNpZ25lZCBjaGFyPgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxzaWduZWQgY2hhcj4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8bG9uZz4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgbG9uZz4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8ZG91YmxlPgB2ZWMyIGMgPSB2X3RleENvb3JkOwB2ZWMyIGMgPSB2ZWMyKDEuMCAtIHZfdGV4Q29vcmQueCwgdl90ZXhDb29yZC55KTsAYyA9IHZlYzIoMS4wIC0gYy54LCAxLjAgLSBjLnkpOwBjID0gdmVjMihjLnksIDEuMCAtIGMueCk7AGMgPSB2ZWMyKDEuMCAtIGMueSwgYy54KTsAQWxsSW4xAC4ALjAsAC4wKSpvKSoAKG51bGwpACkqby55KTsgICAgdmVjMiBjb29yZDIgPSB2ZWMyKGZsb2F0KAAgICAgYyA9IHZlYzIodl90ZXhDb29yZC54LCAxLjAgLSB2X3RleENvb3JkLnkpOyAgICB2ZWMyIGNvb3JkMSA9IHZlYzIoZmxvYXQoACksIChjLnkgLWNvb3JkMS55KSAvIG8ueSAvIGZsb2F0KAApKm8ueSk7ICAgIGlmIChjLnggPiBjb29yZDEueCAmJiBjLnggPCBjb29yZDIueCAmJiBjLnkgPiBjb29yZDEueSAmJiBjLnkgPCBjb29yZDIueSkgeyAgICAgIHZlYzQgd2F0ZXJDb2xvciA9IHRleHR1cmUod2F0ZXJNYXJrLCB2ZWMyKChjLnggLSBjb29yZDEueCkgIC8gby54IC8gZmxvYXQoACkgKiBvLngsIGZsb2F0KABvdXRDb2xvci5yZ2IgKz0gdmVjMygAKTsgICAgICAgdmVjMyBzbW9vdGhDb2xvciA9IG91dENvbG9yLnJnYiArIChvdXRDb2xvci5yZ2ItdmVjMyhoaWdoUGFzcykpKmFscGhhKjAuMTsgICAgICAgc21vb3RoQ29sb3IgPSBtYXgoc21vb3RoQ29sb3IsIHZlYzMoMC4wKSk7ICAgICAgIHNtb290aENvbG9yID0gY2xhbXAocG93KHNtb290aENvbG9yLCB2ZWMzKABnKz1HKGMsdmVjMigAICAgICAgdmVjMiBvZmZzZXQgPSB2ZWMyKABdID0gdl90ZXhDb29yZC54eSArIG9mZnNldCAqIHZlYzIoADsgACkpLCB2ZWMzKDAuMCksIHZlYzMoMS4wKSk7ICAgICAgdmVjMyBzY3JlZW4gPSB2ZWMzKDEuMCkgLSAodmVjMygxLjApLXNtb290aENvbG9yKSAqICh2ZWMzKDEuMCktb3V0Q29sb3IucmdiKTsgICAgICAgdmVjMyBsaWdodGVuID0gbWF4KHNtb290aENvbG9yLCBvdXRDb2xvci5yZ2IpOyAgICAgICB2ZWMzIGJlYXV0eUNvbG9yID0gbWl4KG1peChvdXRDb2xvci5yZ2IsIHNjcmVlbiwgYWxwaGEpLCBsaWdodGVuLCBhbHBoYSk7ICAgICAgb3V0Q29sb3IucmdiID0gbWl4KG91dENvbG9yLnJnYiwgYmVhdXR5Q29sb3IsIAAKICAgICAgY29uc3QgbWF0MyBzYXR1cmF0ZU1hdHJpeCA9IG1hdDMoMS4xMTAyLC0wLjA1OTgsLTAuMDYxLC0wLjA3NzQsMS4wODI2LC0wLjExODYsLTAuMDIyOCwtMC4wMjI4LDEuMTc3Mik7CiAgICAgIHZlYzMgd2FybUNvbG9yID0gb3V0Q29sb3IucmdiICogc2F0dXJhdGVNYXRyaXg7CiAgICAgIG91dENvbG9yLnJnYiA9IG1peChvdXRDb2xvci5yZ2IsIHdhcm1Db2xvciwgACAgICAgIHNhbXBsZUNvbG9yID0gc2FtcGxlQ29sb3IgLyA2Mi4wOyAgICAgICBmbG9hdCBoaWdoUGFzcyA9IG91dENvbG9yLmcgLSBzYW1wbGVDb2xvciArIDAuNTsgICAgICAgY29uc3QgaGlnaHAgdmVjMyBXID0gdmVjMygwLjI5OSwwLjU4NywwLjExNCk7ICAgICAgZmxvYXQgbHVtaW5hbmNlID0gZG90KG91dENvbG9yLnJnYiwgVyk7ICAgICAgIGZsb2F0IGFscGhhID0gcG93KGx1bWluYW5jZSwgAF0pLmcgKiAAKSkpOyAgICAgIG91dENvbG9yID0gbWl4KG91dENvbG9yLHdhdGVyQ29sb3IsICB3YXRlckNvbG9yLmEpOyAgICB9ICAgIAApOyAgICAAKTsgICAgICB2ZWMyIGJsdXJDb29yZGluYXRlc1syNF07ICAgICAgACAgICAgIGZsb2F0IHNhbXBsZUNvbG9yID0gb3V0Q29sb3IuZyAqIDIyLjA7ICAgICAgIAAjdmVyc2lvbiAzMDAgZXMKICAgIHByZWNpc2lvbiBoaWdocCBmbG9hdDsKICAgIHVuaWZvcm0gc2FtcGxlcjJEIGZyYW1lOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgbWFzazsKICAgIHVuaWZvcm0gc2FtcGxlcjJEIGJnOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgd2F0ZXJNYXJrOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgbGFzdE1hc2s7CiAgICB1bmlmb3JtIG1hdDQgdV9vZmZzZXRNYXRyaXg7CiAgICB1bmlmb3JtIHZlYzMgdV9jb2xvcjsKICAgIGluIHZlYzIgdl90ZXhDb29yZDsKICAgIG91dCB2ZWM0IG91dENvbG9yOwogICAgdmVjNCBHKHZlYzIgYyx2ZWMyIHMpewogICAgICByZXR1cm4gdGV4dHVyZShmcmFtZSx0ZXh0dXJlKG1hc2ssYytzKS5yPjAuMz9jOmMrcyk7CiAgICB9CiAgICB2b2lkIG1haW4oKSB7CiAgICAgIAAKICAgICAgdmVjMiBvZmZzZXRNYXNrVVYgPSAodV9vZmZzZXRNYXRyaXggKiB2ZWM0KGMsIDAsIDEpKS54eTsKICAgICAgZmxvYXQgaXNJbnNpZGVYID0gKG9mZnNldE1hc2tVVi54ID49IDAuMCkgJiYgKG9mZnNldE1hc2tVVi54IDw9IDEuMCkgPyAxLjAgOiAwLjA7CiAgICAgIGZsb2F0IGlzSW5zaWRlWSA9IChvZmZzZXRNYXNrVVYueSA+PSAwLjApICYmIChvZmZzZXRNYXNrVVYueSA8PSAxLjApID8gMS4wIDogMC4wOwogICAgICBmbG9hdCBpc0luc2lkZSA9IGlzSW5zaWRlWCAqIGlzSW5zaWRlWTsKICAgICAgZmxvYXQgbWFza2VkQWxwaGEgPSB0ZXh0dXJlKG1hc2ssIG9mZnNldE1hc2tVVikuciAqIGlzSW5zaWRlOwogICAgICBtYXNrZWRBbHBoYSA9IG1hc2tlZEFscGhhPDAuNT8yLjAqbWFza2VkQWxwaGEqbWFza2VkQWxwaGE6MS4wLTIuMCooMS4wLW1hc2tlZEFscGhhKSooMS4wLW1hc2tlZEFscGhhKTsKICAgICAgc3JjX2NvbG9yID0gdGV4dHVyZShmcmFtZSwgb2Zmc2V0TWFza1VWICwgaXNJbnNpZGUpOwogICAgICBvdXRDb2xvciA9IG1peCh0ZXh0dXJlKGJnLCBjKSwgc3JjX2NvbG9yLCBtYXNrZWRBbHBoYSk7CiAgICAACiAgICB2ZWM0IGcgPSB2ZWM0KDAuMCk7CiAgICAACiAgICAgIGMueSA9IDEuMCAtIGMueTsKICAgICAgdmVjNCBzcmNfY29sb3IgPSB0ZXh0dXJlKGZyYW1lLCBjKTsKICAgICAgZmxvYXQgYSA9IHRleHR1cmUobWFzaywgYykucjsKICAgICAgYSA9IGE8MC41PzIuMCphKmE6MS4wLTIuMCooMS4wLWEpKigxLjAtYSk7CiAgICAgIC8vIGZsb2F0IGEyID0gdGV4dHVyZShsYXN0TWFzaywgYykuYTsKICAgICAgLy8gYTIgPSBhMjwwLjU/Mi4wKmEyKmEyOjEuMC0yLjAqKDEuMC1hMikqKDEuMC1hMik7CiAgICAgIC8vIGZsb2F0IGRlbHRhID0gYSAtIGEyOwogICAgICAvLyBpZiAoZGVsdGEgPCAwLjI1ICYmIGRlbHRhID4gLTAuMjUpCiAgICAgIC8vIHsKICAgICAgLy8gICAgIGEgPSBhICsgMC41KmRlbHRhOwogICAgICAvLyB9CiAgICAgIAogICAgICB2ZWMyIG8gPSAxLjAgLyB2ZWMyKHRleHR1cmVTaXplKGZyYW1lLCAwKSk7CiAgICAACiAgICAgIG91dENvbG9yID0gZzsKICAAI3ZlcnNpb24gMzAwIGVzCmluIHZlYzIgYV9wb3NpdGlvbjsKaW4gdmVjMiBhX3RleENvb3JkOwoKdW5pZm9ybSBtYXQ0IHVfdGV4dHVyZU1hdHJpeDsKCm91dCB2ZWMyIHZfdGV4Q29vcmQ7CnZvaWQgbWFpbigpIHsKICBnbF9Qb3NpdGlvbiA9IHZlYzQoYV9wb3NpdGlvbi54LCBhX3Bvc2l0aW9uLnksIDAsIDEpOwogIHZfdGV4Q29vcmQgPSh1X3RleHR1cmVNYXRyaXggKiB2ZWM0KGFfdGV4Q29vcmQsIDAsIDEpKS54eTsKfQoAc2V0QmVhdXR5ICVmICVmICVmICVmICVmCgBvdXRDb2xvciA9IHNyY19jb2xvcjsKAG91dENvbG9yID0gbWl4KHZlYzQodV9jb2xvciwxLjApLHNyY19jb2xvcixhKTsKADZBbGxJbjEAAIAoAABfFgAAUDZBbGxJbjEAAAAABCkAAHAWAAAAAAAAaBYAAFBLNkFsbEluMQAAAAQpAACMFgAAAQAAAGgWAABpaQB2AHZpAHwWAADMFgAATjEwZW1zY3JpcHRlbjN2YWxFAACAKAAAuBYAAGlpaQB2aWlpAAAAALwnAAB8FgAAcCgAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkZABBkC4LyAi8JwAAfBYAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkALwnAAB8FgAAdmlpALwnAADMFgAAzBYAAHwWAADMFgAAHCgAALwnAADMFgAAoBcAAE5TdDNfXzIxMmJhc2ljX3N0cmluZ0ljTlNfMTFjaGFyX3RyYWl0c0ljRUVOU185YWxsb2NhdG9ySWNFRUVFAACAKAAAYBcAAMwWAAC8JwAAzBYAAMwWAABOU3QzX18yMTJiYXNpY19zdHJpbmdJaE5TXzExY2hhcl90cmFpdHNJaEVFTlNfOWFsbG9jYXRvckloRUVFRQAAgCgAALgXAABOU3QzX18yMTJiYXNpY19zdHJpbmdJd05TXzExY2hhcl90cmFpdHNJd0VFTlNfOWFsbG9jYXRvckl3RUVFRQAAgCgAAAAYAABOU3QzX18yMTJiYXNpY19zdHJpbmdJRHNOU18xMWNoYXJfdHJhaXRzSURzRUVOU185YWxsb2NhdG9ySURzRUVFRQAAAIAoAABIGAAATlN0M19fMjEyYmFzaWNfc3RyaW5nSURpTlNfMTFj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")||(Je=ae,ae=I.locateFile?I.locateFile(Je,m):m+Je);var ki=$=>{for(;$.length>0;)$.shift()(I)};I.noExitRuntime;function ao($){this.excPtr=$,this.ptr=$-24,this.set_type=function(j){vA[this.ptr+4>>2]=j},this.get_type=function(){return vA[this.ptr+4>>2]},this.set_destructor=function(j){vA[this.ptr+8>>2]=j},this.get_destructor=function(){return vA[this.ptr+8>>2]},this.set_caught=function(j){j=j?1:0,gA[this.ptr+12|0]=j},this.get_caught=function(){return gA[this.ptr+12|0]!=0},this.set_rethrown=function(j){j=j?1:0,gA[this.ptr+13|0]=j},this.get_rethrown=function(){return gA[this.ptr+13|0]!=0},this.init=function(j,RA){this.set_adjusted_ptr(0),this.set_type(j),this.set_destructor(RA)},this.set_adjusted_ptr=function(j){vA[this.ptr+16>>2]=j},this.get_adjusted_ptr=function(){return vA[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Oa(this.get_type()))return vA[this.excPtr>>2];var j=this.get_adjusted_ptr();return j!==0?j:this.excPtr}}var Ji,Vi,wn,Fi=$=>{for(var j="",RA=$;eA[RA];)j+=Ji[eA[RA++]];return j},en={},Ro={},oo={},Ai=$=>{throw new Vi($)},no=$=>{throw new wn($)},Ri=($,j,RA)=>{function ZA(qe){var Et=RA(qe);Et.length!==$.length&&no("Mismatched type converter count");for(var ft=0;ft<$.length;++ft)pn($[ft],Et[ft])}$.forEach(function(qe){oo[qe]=j});var ne=new Array(j.length),De=[],Ke=0;j.forEach((qe,Et)=>{Ro.hasOwnProperty(qe)?ne[Et]=Ro[qe]:(De.push(qe),en.hasOwnProperty(qe)||(en[qe]=[]),en[qe].push(()=>{ne[Et]=Ro[qe],++Ke===De.length&&ZA(ne)}))}),De.length===0&&ZA(ne)};function pn($,j,RA={}){if(!("argPackAdvance"in j))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(ZA,ne,De={}){var Ke=ne.name;if(ZA||Ai(`type "${Ke}" must have a positive integer typeid pointer`),Ro.hasOwnProperty(ZA)){if(De.ignoreDuplicateRegistrations)return;Ai(`Cannot register type '${Ke}' twice`)}if(Ro[ZA]=ne,delete oo[ZA],en.hasOwnProperty(ZA)){var qe=en[ZA];delete en[ZA],qe.forEach(Et=>Et())}}($,j,RA)}var jA,ue=$=>{Ai($.$$.ptrType.registeredClass.name+" instance already deleted")},He=!1,Lt=$=>{},ct=$=>{$.count.value-=1,$.count.value===0&&(j=>{j.smartPtr?j.smartPtrType.rawDestructor(j.smartPtr):j.ptrType.registeredClass.rawDestructor(j.ptr)})($)},Ct=($,j,RA)=>{if(j===RA)return $;if(RA.baseClass===void 0)return null;var ZA=Ct($,j,RA.baseClass);return ZA===null?null:RA.downcast(ZA)},ei={},Ht=()=>Object.keys(Hi).length,Le=()=>{var $=[];for(var j in Hi)Hi.hasOwnProperty(j)&&$.push(Hi[j]);return $},it=[],Tt=()=>{for(;it.length;){var $=it.pop();$.$$.deleteScheduled=!1,$.delete()}},Gt=$=>{jA=$,it.length&&jA&&jA(Tt)},Hi={},po=($,j)=>(j=((RA,ZA)=>{for(ZA===void 0&&Ai("ptr should not be undefined");RA.baseClass;)ZA=RA.upcast(ZA),RA=RA.baseClass;return ZA})($,j),Hi[j]),To=($,j)=>(j.ptrType&&j.ptr||no("makeClassHandle requires ptr and ptrType"),!!j.smartPtrType!=!!j.smartPtr&&no("Both smartPtrType and smartPtr must be specified"),j.count={value:1},wo(Object.create($,{$$:{value:j}})));function Zi($){var j=this.getPointee($);if(!j)return this.destructor($),null;var RA=po(this.registeredClass,j);if(RA!==void 0){if(RA.$$.count.value===0)return RA.$$.ptr=j,RA.$$.smartPtr=$,RA.clone();var ZA=RA.clone();return this.destructor($),ZA}function ne(){return this.isSmartPointer?To(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:j,smartPtrType:this,smartPtr:$}):To(this.registeredClass.instancePrototype,{ptrType:this,ptr:$})}var De,Ke=this.registeredClass.getActualType(j),qe=ei[Ke];if(!qe)return ne.call(this);De=this.isConst?qe.constPointerType:qe.pointerType;var Et=Ct(j,this.registeredClass,De.registeredClass);return Et===null?ne.call(this):this.isSmartPointer?To(De.registeredClass.instancePrototype,{ptrType:De,ptr:Et,smartPtrType:this,smartPtr:$}):To(De.registeredClass.instancePrototype,{ptrType:De,ptr:Et})}var wo=$=>typeof FinalizationRegistry>"u"?(wo=j=>j,$):(He=new FinalizationRegistry(j=>{ct(j.$$)}),Lt=j=>He.unregister(j),(wo=j=>{var RA=j.$$;if(RA.smartPtr){var ZA={$$:RA};He.register(j,ZA,j)}return j})($));function Cn(){}var an=($,j)=>Object.defineProperty(j,"name",{value:$}),Vo=($,j,RA)=>{if($[j].overloadTable===void 0){var ZA=$[j];$[j]=function(){return $[j].overloadTable.hasOwnProperty(arguments.length)||Ai(`Function '${RA}' called with an invalid number of arguments (${arguments.length}) - expects one of (${$[j].overloadTable})!`),$[j].overloadTable[arguments.length].apply(this,arguments)},$[j].overloadTable=[],$[j].overloadTable[ZA.argCount]=ZA}};function jn($,j,RA,ZA,ne,De,Ke,qe){this.name=$,this.constructor=j,this.instancePrototype=RA,this.rawDestructor=ZA,this.baseClass=ne,this.getActualType=De,this.upcast=Ke,this.downcast=qe,this.pureVirtualFunctions=[]}var vo=($,j,RA)=>{for(;j!==RA;)j.upcast||Ai(`Expected null or instance of ${RA.name}, got an instance of ${j.name}`),$=j.upcast($),j=j.baseClass;return $};function mA($,j){if(j===null)return this.isReference&&Ai(`null is not a valid ${this.name}`),0;j.$$||Ai(`Cannot pass "${ce(j)}" as a ${this.name}`),j.$$.ptr||Ai(`Cannot pass deleted object as a pointer of type ${this.name}`);var RA=j.$$.ptrType.registeredClass;return vo(j.$$.ptr,RA,this.registeredClass)}function xs($,j){var RA;if(j===null)return this.isReference&&Ai(`null is not a valid ${this.name}`),this.isSmartPointer?(RA=this.rawConstructor(),$!==null&&$.push(this.rawDestructor,RA),RA):0;j.$$||Ai(`Cannot pass "${ce(j)}" as a ${this.name}`),j.$$.ptr||Ai(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&j.$$.ptrType.isConst&&Ai(`Cannot convert argument of type ${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type ${this.name}`);var ZA=j.$$.ptrType.registeredClass;if(RA=vo(j.$$.ptr,ZA,this.registeredClass),this.isSmartPointer)switch(j.$$.smartPtr===void 0&&Ai("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:j.$$.smartPtrType===this?RA=j.$$.smartPtr:Ai(`Cannot convert argument of type ${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:RA=j.$$.smartPtr;break;case 2:if(j.$$.smartPtrType===this)RA=j.$$.smartPtr;else{var ne=j.clone();RA=this.rawShare(RA,ts.toHandle(()=>ne.delete())),$!==null&&$.push(this.rawDestructor,RA)}break;default:Ai("Unsupporting sharing policy")}return RA}function Zs($,j){if(j===null)return this.isReference&&Ai(`null is not a valid ${this.name}`),0;j.$$||Ai(`Cannot pass "${ce(j)}" as a ${this.name}`),j.$$.ptr||Ai(`Cannot pass deleted object as a pointer of type ${this.name}`),j.$$.ptrType.isConst&&Ai(`Cannot convert argument of type ${j.$$.ptrType.name} to parameter type ${this.name}`);var RA=j.$$.ptrType.registeredClass;return vo(j.$$.ptr,RA,this.registeredClass)}function mn($){return this.fromWireType(vA[$>>2])}function Fr($,j,RA,ZA,ne,De,Ke,qe,Et,ft,Nt){this.name=$,this.registeredClass=j,this.isReference=RA,this.isConst=ZA,this.isSmartPointer=ne,this.pointeeType=De,this.sharingPolicy=Ke,this.rawGetPointee=qe,this.rawConstructor=Et,this.rawShare=ft,this.rawDestructor=Nt,ne||j.baseClass!==void 0?this.toWireType=xs:ZA?(this.toWireType=mA,this.destructorFunction=null):(this.toWireType=Zs,this.destructorFunction=null)}var qi,tn,Ks=[],_n=$=>{var j=Ks[$];return j||($>=Ks.length&&(Ks.length=$+1),Ks[$]=j=qi.get($)),j},Is=($,j,RA)=>$.includes("j")?((ZA,ne,De)=>{var Ke=I["dynCall_"+ZA];return De&&De.length?Ke.apply(null,[ne].concat(De)):Ke.call(null,ne)})($,j,RA):_n(j).apply(null,RA),qt=($,j)=>{var RA,ZA,ne,De=($=Fi($)).includes("j")?(RA=$,ZA=j,ne=[],function(){return ne.length=0,Object.assign(ne,arguments),Is(RA,ZA,ne)}):_n(j);return typeof De!="function"&&Ai(`unknown function pointer with signature ${$}: ${j}`),De},$a=$=>{var j=pa($),RA=Fi(j);return _s(j),RA},Ls=($,j)=>{var RA=[],ZA={};throw j.forEach(function ne(De){ZA[De]||Ro[De]||(oo[De]?oo[De].forEach(ne):(RA.push(De),ZA[De]=!0))}),new tn(`${$}: `+RA.map($a).join([", "]))},Bs=($,j)=>{for(var RA=[],ZA=0;ZA<$;ZA++)RA.push(vA[j+4*ZA>>2]);return RA},Un=$=>{for(;$.length;){var j=$.pop();$.pop()(j)}};function ur($,j,RA,ZA,ne,De){var Ke=j.length;Ke<2&&Ai("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var qe=j[1]!==null&&RA!==null,Et=!1,ft=1;ft($ instanceof Object||Ai(`${RA} with invalid "this": ${$}`),$ instanceof j.registeredClass.constructor||Ai(`${RA} incompatible with "this" of type ${$.constructor.name}`),$.$$.ptr||Ai(`cannot call emscripten binding method ${RA} on deleted object`),vo($.$$.ptr,$.$$.ptrType.registeredClass,j.registeredClass));function rr(){this.allocated=[void 0],this.freelist=[]}var fo=new rr,es=$=>{$>=fo.reserved&&--fo.get($).refcount===0&&fo.free($)},vc=()=>{for(var $=0,j=fo.reserved;j($||Ai("Cannot use deleted val. handle = "+$),fo.get($).value),toHandle:$=>{switch($){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return fo.allocate({refcount:1,value:$})}}};function Er($){return this.fromWireType(oA[$>>2])}var On,Mg,yn,ce=$=>{if($===null)return"null";var j=typeof $;return j==="object"||j==="array"||j==="function"?$.toString():""+$},ot=($,j)=>{switch(j){case 4:return function(RA){return this.fromWireType(qA[RA>>2])};case 8:return function(RA){return this.fromWireType(Ae[RA>>3])};default:throw new TypeError(`invalid float width (${j}): ${$}`)}},Zt=($,j,RA)=>{switch(j){case 1:return RA?ZA=>gA[ZA|0]:ZA=>eA[ZA|0];case 2:return RA?ZA=>CA[ZA>>1]:ZA=>IA[ZA>>1];case 4:return RA?ZA=>oA[ZA>>2]:ZA=>vA[ZA>>2];default:throw new TypeError(`invalid integer width (${j}): ${$}`)}},Ho=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ba=($,j,RA)=>{for(var ZA=j+RA,ne=j;$[ne]&&!(ne>=ZA);)++ne;if(ne-j>16&&$.buffer&&Ho)return Ho.decode($.subarray(j,ne));for(var De="";j>10,56320|1023&ft)}}else De+=String.fromCharCode((31&Ke)<<6|qe)}else De+=String.fromCharCode(Ke)}return De},WI=($,j)=>$?Ba(eA,$,j):"",gn=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,ro=($,j)=>{for(var RA=$,ZA=RA>>1,ne=ZA+j/2;!(ZA>=ne)&&IA[ZA];)++ZA;if((RA=ZA<<1)-$>32&&gn)return gn.decode(eA.subarray($,RA));for(var De="",Ke=0;!(Ke>=j/2);++Ke){var qe=CA[$+2*Ke>>1];if(qe==0)break;De+=String.fromCharCode(qe)}return De},Mc=($,j,RA)=>{if(RA===void 0&&(RA=2147483647),RA<2)return 0;for(var ZA=j,ne=(RA-=2)<2*$.length?RA/2:$.length,De=0;De>1]=Ke,j+=2}return CA[j>>1]=0,j-ZA},cg=$=>2*$.length,Rg=($,j)=>{for(var RA=0,ZA="";!(RA>=j/4);){var ne=oA[$+4*RA>>2];if(ne==0)break;if(++RA,ne>=65536){var De=ne-65536;ZA+=String.fromCharCode(55296|De>>10,56320|1023&De)}else ZA+=String.fromCharCode(ne)}return ZA},Qa=($,j,RA)=>{if(RA===void 0&&(RA=2147483647),RA<4)return 0;for(var ZA=j,ne=ZA+RA-4,De=0;De<$.length;++De){var Ke=$.charCodeAt(De);if(Ke>=55296&&Ke<=57343&&(Ke=65536+((1023&Ke)<<10)|1023&$.charCodeAt(++De)),oA[j>>2]=Ke,(j+=4)+4>ne)break}return oA[j>>2]=0,j-ZA},Fo=$=>{for(var j=0,RA=0;RA<$.length;++RA){var ZA=$.charCodeAt(RA);ZA>=55296&&ZA<=57343&&++RA,j+=4}return j},Aa=($,j)=>{var RA=Ro[$];return RA===void 0&&Ai(j+" has unknown type "+$a($)),RA},Uo=($,j,RA)=>{var ZA=[],ne=$.toWireType(ZA,RA);return ZA.length&&(vA[j>>2]=ts.toHandle(ZA)),ne},Zc={},Xs=[],is=Reflect.construct,wg=[null,[],[]],Rc=($,j)=>{var RA=wg[$];j===0||j===10?(($===1?T:b)(Ba(RA,0)),RA.length=0):RA.push(j)};(()=>{for(var $=new Array(256),j=0;j<256;++j)$[j]=String.fromCharCode(j);Ji=$})(),Vi=I.BindingError=class extends Error{constructor($){super($),this.name="BindingError"}},wn=I.InternalError=class extends Error{constructor($){super($),this.name="InternalError"}},Object.assign(Cn.prototype,{isAliasOf($){if(!(this instanceof Cn)||!($ instanceof Cn))return!1;var j=this.$$.ptrType.registeredClass,RA=this.$$.ptr;$.$$=$.$$;for(var ZA=$.$$.ptrType.registeredClass,ne=$.$$.ptr;j.baseClass;)RA=j.upcast(RA),j=j.baseClass;for(;ZA.baseClass;)ne=ZA.upcast(ne),ZA=ZA.baseClass;return j===ZA&&RA===ne},clone(){if(this.$$.ptr||ue(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var $,j=wo(Object.create(Object.getPrototypeOf(this),{$$:{value:($=this.$$,{count:$.count,deleteScheduled:$.deleteScheduled,preservePointerOnDelete:$.preservePointerOnDelete,ptr:$.ptr,ptrType:$.ptrType,smartPtr:$.smartPtr,smartPtrType:$.smartPtrType})}}));return j.$$.count.value+=1,j.$$.deleteScheduled=!1,j},delete(){this.$$.ptr||ue(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ai("Object already scheduled for deletion"),Lt(this),ct(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||ue(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ai("Object already scheduled for deletion"),it.push(this),it.length===1&&jA&&jA(Tt),this.$$.deleteScheduled=!0,this}}),I.getInheritedInstanceCount=Ht,I.getLiveInheritedInstances=Le,I.flushPendingDeletes=Tt,I.setDelayFunction=Gt,Object.assign(Fr.prototype,{getPointee($){return this.rawGetPointee&&($=this.rawGetPointee($)),$},destructor($){this.rawDestructor&&this.rawDestructor($)},argPackAdvance:8,readValueFromPointer:mn,deleteObject($){$!==null&&$.delete()},fromWireType:Zi}),tn=I.UnboundTypeError=(On=Error,(yn=an(Mg="UnboundTypeError",function($){this.name=Mg,this.message=$;var j=new Error($).stack;j!==void 0&&(this.stack=this.toString()+` +`+j.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(On.prototype),yn.prototype.constructor=yn,yn.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},yn),Object.assign(rr.prototype,{get($){return this.allocated[$]},has($){return this.allocated[$]!==void 0},allocate($){var j=this.freelist.pop()||this.allocated.length;return this.allocated[j]=$,j},free($){this.allocated[$]=void 0,this.freelist.push($)}}),fo.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),fo.reserved=fo.allocated.length,I.count_emval_handles=vc;var ws,Fa={w:($,j,RA)=>{throw new ao($).init(j,RA),$},q:($,j,RA,ZA,ne)=>{},u:($,j,RA,ZA)=>{pn($,{name:j=Fi(j),fromWireType:function(ne){return!!ne},toWireType:function(ne,De){return De?RA:ZA},argPackAdvance:8,readValueFromPointer:function(ne){return this.fromWireType(eA[ne])},destructorFunction:null})},y:($,j,RA,ZA,ne,De,Ke,qe,Et,ft,Nt,Kt,di)=>{Nt=Fi(Nt),De=qt(ne,De),qe&&(qe=qt(Ke,qe)),ft&&(ft=qt(Et,ft)),di=qt(Kt,di);var Bt=(Jt=>{if(Jt===void 0)return"_unknown";var $i=(Jt=Jt.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return $i>=48&&$i<=57?`_${Jt}`:Jt})(Nt);((Jt,$i,eo)=>{I.hasOwnProperty(Jt)?(Ai(`Cannot register public name '${Jt}' twice`),Vo(I,Jt,Jt),I.hasOwnProperty(eo)&&Ai(`Cannot register multiple overloads of a function with the same number of arguments (${eo})!`),I[Jt].overloadTable[eo]=$i):I[Jt]=$i})(Bt,function(){Ls(`Cannot construct ${Nt} due to unbound types`,[ZA])}),Ri([$,j,RA],ZA?[ZA]:[],function(Jt){var $i,eo;Jt=Jt[0],eo=ZA?($i=Jt.registeredClass).instancePrototype:Cn.prototype;var os=an(Nt,function(){if(Object.getPrototypeOf(this)!==Ti)throw new Vi("Use 'new' to construct "+Nt);if(on.constructor_body===void 0)throw new Vi(Nt+" has no accessible constructor");var js=on.constructor_body[arguments.length];if(js===void 0)throw new Vi(`Tried to invoke ctor of ${Nt} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(on.constructor_body).toString()}) parameters instead!`);return js.apply(this,arguments)}),Ti=Object.create(eo,{constructor:{value:os}});os.prototype=Ti;var on=new jn(Nt,os,Ti,di,$i,De,qe,ft);on.baseClass&&(on.baseClass.__derivedClasses===void 0&&(on.baseClass.__derivedClasses=[]),on.baseClass.__derivedClasses.push(on));var _g=new Fr(Nt,on,!0,!1,!1),dr=new Fr(Nt+"*",on,!1,!1,!1),Mr=new Fr(Nt+" const*",on,!1,!0,!1);return ei[$]={pointerType:dr,constPointerType:Mr},((js,Nl,ns)=>{I.hasOwnProperty(js)||no("Replacing nonexistant public symbol"),I[js].overloadTable!==void 0&&ns!==void 0?I[js].overloadTable[ns]=Nl:(I[js]=Nl,I[js].argCount=ns)})(Bt,os),[_g,dr,Mr]})},x:($,j,RA,ZA,ne,De)=>{var Ke=Bs(j,RA);ne=qt(ZA,ne),Ri([],[$],function(qe){var Et=`constructor ${(qe=qe[0]).name}`;if(qe.registeredClass.constructor_body===void 0&&(qe.registeredClass.constructor_body=[]),qe.registeredClass.constructor_body[j-1]!==void 0)throw new Vi(`Cannot register multiple constructors with identical number of parameters (${j-1}) for class '${qe.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return qe.registeredClass.constructor_body[j-1]=()=>{Ls(`Cannot construct ${qe.name} due to unbound types`,Ke)},Ri([],Ke,ft=>(ft.splice(1,0,null),qe.registeredClass.constructor_body[j-1]=ur(Et,ft,null,ne,De),[])),[]})},i:($,j,RA,ZA,ne,De,Ke,qe,Et)=>{var ft=Bs(RA,ZA);j=(Nt=>{const Kt=(Nt=Nt.trim()).indexOf("(");return Kt!==-1?Nt.substr(0,Kt):Nt})(j=Fi(j)),De=qt(ne,De),Ri([],[$],function(Nt){var Kt=`${(Nt=Nt[0]).name}.${j}`;function di(){Ls(`Cannot call ${Kt} due to unbound types`,ft)}j.startsWith("@@")&&(j=Symbol[j.substring(2)]),qe&&Nt.registeredClass.pureVirtualFunctions.push(j);var Bt=Nt.registeredClass.instancePrototype,Jt=Bt[j];return Jt===void 0||Jt.overloadTable===void 0&&Jt.className!==Nt.name&&Jt.argCount===RA-2?(di.argCount=RA-2,di.className=Nt.name,Bt[j]=di):(Vo(Bt,j,Kt),Bt[j].overloadTable[RA-2]=di),Ri([],ft,function($i){var eo=ur(Kt,$i,Nt,De,Ke);return Bt[j].overloadTable===void 0?(eo.argCount=RA-2,Bt[j]=eo):Bt[j].overloadTable[RA-2]=eo,[]}),[]})},k:($,j,RA,ZA,ne,De,Ke,qe,Et,ft)=>{j=Fi(j),ne=qt(ZA,ne),Ri([],[$],function(Nt){var Kt=`${(Nt=Nt[0]).name}.${j}`,di={get(){Ls(`Cannot access ${Kt} due to unbound types`,[RA,Ke])},enumerable:!0,configurable:!0};return di.set=Et?()=>Ls(`Cannot access ${Kt} due to unbound types`,[RA,Ke]):Bt=>Ai(Kt+" is a read-only property"),Object.defineProperty(Nt.registeredClass.instancePrototype,j,di),Ri([],Et?[RA,Ke]:[RA],function(Bt){var Jt=Bt[0],$i={get(){var os=Fn(this,Nt,Kt+" getter");return Jt.fromWireType(ne(De,os))},enumerable:!0};if(Et){Et=qt(qe,Et);var eo=Bt[1];$i.set=function(os){var Ti=Fn(this,Nt,Kt+" setter"),on=[];Et(ft,Ti,eo.toWireType(on,os)),Un(on)}}return Object.defineProperty(Nt.registeredClass.instancePrototype,j,$i),[]}),[]})},t:($,j)=>{pn($,{name:j=Fi(j),fromWireType:RA=>{var ZA=ts.toValue(RA);return es(RA),ZA},toWireType:(RA,ZA)=>ts.toHandle(ZA),argPackAdvance:8,readValueFromPointer:Er,destructorFunction:null})},p:($,j,RA)=>{pn($,{name:j=Fi(j),fromWireType:ZA=>ZA,toWireType:(ZA,ne)=>ne,argPackAdvance:8,readValueFromPointer:ot(j,RA),destructorFunction:null})},g:($,j,RA,ZA,ne)=>{j=Fi(j);var De=Et=>Et;if(ZA===0){var Ke=32-8*RA;De=Et=>Et<>>Ke}var qe=j.includes("unsigned");pn($,{name:j,fromWireType:De,toWireType:qe?function(Et,ft){return this.name,ft>>>0}:function(Et,ft){return this.name,ft},argPackAdvance:8,readValueFromPointer:Zt(j,RA,ZA!==0),destructorFunction:null})},a:($,j,RA)=>{var ZA=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][j];function ne(De){var Ke=vA[De>>2],qe=vA[De+4>>2];return new ZA(gA.buffer,qe,Ke)}pn($,{name:RA=Fi(RA),fromWireType:ne,argPackAdvance:8,readValueFromPointer:ne},{ignoreDuplicateRegistrations:!0})},o:($,j)=>{var RA=(j=Fi(j))==="std::string";pn($,{name:j,fromWireType(ZA){var ne,De=vA[ZA>>2],Ke=ZA+4;if(RA)for(var qe=Ke,Et=0;Et<=De;++Et){var ft=Ke+Et;if(Et==De||eA[ft]==0){var Nt=WI(qe,ft-qe);ne===void 0?ne=Nt:(ne+="\0",ne+=Nt),qe=ft+1}}else{var Kt=new Array(De);for(Et=0;Et{for(var di=0,Bt=0;Bt=55296&&Jt<=57343?(di+=4,++Bt):di+=3}return di})(ne):ne.length;var qe=Tn(4+De+1),Et=qe+4;if(vA[qe>>2]=De,RA&&Ke)((Kt,di,Bt,Jt)=>{if(!(Jt>0))return 0;for(var $i=Bt,eo=Bt+Jt-1,os=0;os=55296&&Ti<=57343&&(Ti=65536+((1023&Ti)<<10)|1023&Kt.charCodeAt(++os)),Ti<=127){if(Bt>=eo)break;di[Bt++]=Ti}else if(Ti<=2047){if(Bt+1>=eo)break;di[Bt++]=192|Ti>>6,di[Bt++]=128|63&Ti}else if(Ti<=65535){if(Bt+2>=eo)break;di[Bt++]=224|Ti>>12,di[Bt++]=128|Ti>>6&63,di[Bt++]=128|63&Ti}else{if(Bt+3>=eo)break;di[Bt++]=240|Ti>>18,di[Bt++]=128|Ti>>12&63,di[Bt++]=128|Ti>>6&63,di[Bt++]=128|63&Ti}}di[Bt]=0})(ne,eA,Et,De+1);else if(Ke)for(var ft=0;ft255&&(_s(Et),Ai("String has UTF-16 code units that do not fit in 8 bits")),eA[Et+ft]=Nt}else for(ft=0;ft{var ZA,ne,De,Ke,qe;RA=Fi(RA),j===2?(ZA=ro,ne=Mc,Ke=cg,De=()=>IA,qe=1):j===4&&(ZA=Rg,ne=Qa,Ke=Fo,De=()=>vA,qe=2),pn($,{name:RA,fromWireType:Et=>{for(var ft,Nt=vA[Et>>2],Kt=De(),di=Et+4,Bt=0;Bt<=Nt;++Bt){var Jt=Et+4+Bt*j;if(Bt==Nt||Kt[Jt>>qe]==0){var $i=ZA(di,Jt-di);ft===void 0?ft=$i:(ft+="\0",ft+=$i),di=Jt+j}}return _s(Et),ft},toWireType:(Et,ft)=>{typeof ft!="string"&&Ai(`Cannot pass non-string to C++ string type ${RA}`);var Nt=Ke(ft),Kt=Tn(4+Nt+j);return vA[Kt>>2]=Nt>>qe,ne(ft,Kt+4,Nt+j),Et!==null&&Et.push(_s,Kt),Kt},argPackAdvance:8,readValueFromPointer:Er,destructorFunction(Et){_s(Et)}})},v:($,j)=>{pn($,{isVoid:!0,name:j=Fi(j),argPackAdvance:0,fromWireType:()=>{},toWireType:(RA,ZA)=>{}})},j:($,j,RA)=>($=ts.toValue($),j=Aa(j,"emval::as"),Uo(j,RA,$)),e:($,j,RA,ZA,ne)=>{var De,Ke;return($=Xs[$])(j=ts.toValue(j),j[RA=(Ke=Zc[De=RA])===void 0?Fi(De):Ke],ZA,ne)},d:es,f:($,j,RA)=>{var ZA=((ft,Nt)=>{for(var Kt=new Array(ft),di=0;di>2],"parameter "+di);return Kt})($,j),ne=ZA.shift();$--;var De,Ke,qe=new Array($),Et=`methodCaller<(${ZA.map(ft=>ft.name).join(", ")}) => ${ne.name}>`;return De=an(Et,(ft,Nt,Kt,di)=>{for(var Bt=0,Jt=0;Jt<$;++Jt)qe[Jt]=ZA[Jt].readValueFromPointer(di+Bt),Bt+=ZA[Jt].argPackAdvance;var $i=RA===1?is(Nt,qe):Nt.apply(ft,qe);for(Jt=0;Jt<$;++Jt)ZA[Jt].deleteObject&&ZA[Jt].deleteObject(qe[Jt]);return Uo(ne,Kt,$i)}),Ke=Xs.length,Xs.push(De),Ke},c:$=>{$>4&&(fo.get($).refcount+=1)},b:$=>{var j=ts.toValue($);Un(j),es($)},h:($,j)=>{var RA=($=Aa($,"_emval_take_value")).readValueFromPointer(j);return ts.toHandle(RA)},m:()=>{Xe("")},s:($,j,RA)=>eA.copyWithin($,j,j+RA),r:$=>{eA.length,Xe("OOM")},n:($,j,RA,ZA)=>{for(var ne=0,De=0;De>2],qe=vA[j+4>>2];j+=8;for(var Et=0;Et>2]=ne,0}},Qs=function(){var $={a:Fa};function j(RA,ZA){var ne,De;return Qs=RA.exports,_=Qs.z,ne=_.buffer,I.HEAP8=gA=new Int8Array(ne),I.HEAP16=CA=new Int16Array(ne),I.HEAPU8=eA=new Uint8Array(ne),I.HEAPU16=IA=new Uint16Array(ne),I.HEAP32=oA=new Int32Array(ne),I.HEAPU32=vA=new Uint32Array(ne),I.HEAPF32=qA=new Float32Array(ne),I.HEAPF64=Ae=new Float64Array(ne),qi=Qs.C,De=Qs.A,WA.unshift(De),function(){if(we--,I.monitorRunDependencies&&I.monitorRunDependencies(we),we==0&&et){var Ke=et;et=null,Ke()}}(),Qs}if(we++,I.monitorRunDependencies&&I.monitorRunDependencies(we),I.instantiateWasm)try{return I.instantiateWasm($,j)}catch(RA){b(`Module.instantiateWasm callback failed with error: ${RA}`),c(RA)}return ii(0,ae,$,function(RA){j(RA.instance)}).catch(c),{}}(),Tn=$=>(Tn=Qs.B)($),pa=$=>(pa=Qs.D)($),_s=$=>(_s=Qs.E)($),Oa=$=>(Oa=Qs.F)($);I.dynCall_jiji=($,j,RA,ZA,ne)=>(I.dynCall_jiji=Qs.G)($,j,RA,ZA,ne),I._vertexShaderSource=10688;function Ta(){function $(){ws||(ws=!0,I.calledRun=!0,HA||(ki(WA),n(I),I.onRuntimeInitialized&&I.onRuntimeInitialized(),function(){if(I.postRun)for(typeof I.postRun=="function"&&(I.postRun=[I.postRun]);I.postRun.length;)Pe(I.postRun.shift());ki(Ye)}()))}we>0||(function(){if(I.preRun)for(typeof I.preRun=="function"&&(I.preRun=[I.preRun]);I.preRun.length;)We(I.preRun.shift());ki(se)}(),we>0||(I.setStatus?(I.setStatus("Running..."),setTimeout(function(){setTimeout(function(){I.setStatus("")},1),$()},1)):$()))}if(et=function $(){ws||Ta(),ws||(et=$)},I.preInit)for(typeof I.preInit=="function"&&(I.preInit=[I.preInit]);I.preInit.length>0;)I.preInit.pop()();return Ta(),i.ready}})(),BgA=hgA,Qm=typeof navigator>"u"?"":navigator.userAgent,$n=e=>new RegExp(e,"i").test(Qm),Dc=e=>{if($n(e)){const i=new RegExp(`${e}\\/([\\d.]+)`),n=Qm.match(i);if(n&&n[1])return n[1]}return""},OV=e=>{if($n(e)){const i=new RegExp(`${e}\\/(\\d+)`),n=Qm.match(i);if(n&&n[1])return parseFloat(n[1])}return NaN},FZ=/AppleWebKit\/([\d.]+)/i.exec(Qm);FZ&&parseFloat(FZ[1]);var bX=$n("iPad"),kX=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&$n("Macintosh"),LX=$n("iPhone")&&!bX,QgA=$n("iPod"),UX=LX||bX||QgA||kX,p4=$n("Android"),pgA=function(){if(p4){const e=Qm.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(e){const i=e[1]&&parseFloat(e[1]),n=e[2]&&parseFloat(e[2]);if(i&&n)return parseFloat(`${e[1]}.${e[2]}`);if(i)return i}}return NaN}();p4&&$n("webkit")&&pgA<2.3;var mgA=$n("Firefox"),fgA=Dc("Firefox");OV("Firefox");var FX=$n("Edge"),ygA=Dc("Edge"),OX=$n("Edg"),DgA=Dc("Edg");OV("Edg");var PX=$n("SogouMobileBrowser"),SgA=Dc("SogouMobileBrowser"),xX=$n("MetaSr\\s"),vgA=Dc("MetaSr\\s"),JM=$n("TBS"),MgA=Dc("TBS"),YX=$n("XWEB"),RgA=Dc("XWEB");$n("MSIE\\s8\\.0");var wgA=$n("MSIE\\/\\d+");(function(){if(wgA){const e=/MSIE\s(\d+)\.\d/.exec(Qm);let i=e&&parseFloat(e[1]);return!i&&/Trident\/7.0/i.test(Qm)&&/rv:11.0/.test(Qm)&&(i=11),i}return NaN})();var _gA=$n("(micromessenger|webbrowser)"),TgA=Dc("MicroMessenger"),m4=!JM&&$n("MQQBrowser")&&$n("COVC"),f4=!JM&&$n("MQQBrowser")&&!$n("COVC"),OZ=f4||m4?Dc("MQQBrowser"):"",VX=!JM&&$n(" QQBrowser"),NgA=Dc(" QQBrowser"),HX=!JM&&$n("QQBrowserLite"),GgA=Dc("QQBrowserLite"),JX=!JM&&$n("MQBHD"),bgA=Dc("MQBHD");$n("Windows");!UX&&$n("MAC OS X");!p4&&$n("Linux");$n("CrOS");$n("MicroMessenger");$n("UCBrowser");$n("Electron");var qX=$n("MiuiBrowser"),kgA=Dc("MiuiBrowser"),KX=$n("HuaweiBrowser");$n("Huawei")||$n("HUAWEI");$n("Honor")||$n("HONOR");var LgA=Dc("HuaweiBrowser"),jX=$n("SamsungBrowser"),UgA=Dc("SamsungBrowser"),WX=$n("HeyTapBrowser"),FgA=Dc("HeyTapBrowser"),zX=$n("VivoBrowser"),OgA=Dc("VivoBrowser");$n("OpenHarmony");Dc("OpenHarmony");var PgA=()=>OV("Chrome"),PZ=$n("CriOS"),ZX=$n("Chrome"),xgA=!FX&&!xX&&!PX&&!JM&&!YX&&!OX&&!VX&&!qX&&!KX&&!jX&&!WX&&!zX&&ZX;$n("HeadlessChrome");var YgA=PgA(),VgA=Dc("Chrome");OV("Electron");var HgA=!ZX&&!f4&&!m4&&!HX&&!JX&&$n("Safari"),XX=Dc("Version"),$X=(()=>{if(kX)return XX;if(UX){const e=Qm.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let i=e[1];return e[2]&&(i+=`.${e[2]}`),i}}return""})();Number($X.split(".")[0]);(()=>{const e=Number($X.split(".")[0]);return e===14||e===13})();JgA();function JgA(){const e=new Map([[mgA,["Firefox",fgA]],[OX,["Edg",DgA]],[xgA,["Chrome",VgA]],[PZ,["ChiOS",Dc("CriOS")]],[HgA&&!PZ,["Safari",XX]],[JM,["TBS",MgA]],[YX,["XWEB",RgA]],[_gA&&LX,["WeChat",TgA]],[VX,["QQ(Win)",NgA]],[f4,["QQ(Mobile)",OZ]],[m4,["QQ(Mobile X5)",OZ]],[HX,["QQ(Mac)",GgA]],[JX,["QQ(iPad)",bgA]],[qX,["MI",kgA]],[KX,["HW",LgA]],[jX,["Samsung",UgA]],[WX,["OPPO",FgA]],[zX,["VIVO",OgA]],[FX,["EDGE",ygA]],[PX,["SogouMobile",SgA]],[xX,["Sogou",vgA]]]);let i="unknown",n="unknown";return e.has(!0)&&([i,n]=e.get(!0)),{name:i,version:n}}var fc=1e-6,hT=typeof Float32Array<"u"?Float32Array:Array,A7={};function qgA(){var e=new hT(16);return hT!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0),e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function KgA(e){var i=new hT(16);return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=e[12],i[13]=e[13],i[14]=e[14],i[15]=e[15],i}function jgA(e,i){return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],e}function WgA(e,i,n,c,I,C,m,R,_,T,b,J,gA,eA,CA,IA){var oA=new hT(16);return oA[0]=e,oA[1]=i,oA[2]=n,oA[3]=c,oA[4]=I,oA[5]=C,oA[6]=m,oA[7]=R,oA[8]=_,oA[9]=T,oA[10]=b,oA[11]=J,oA[12]=gA,oA[13]=eA,oA[14]=CA,oA[15]=IA,oA}function zgA(e,i,n,c,I,C,m,R,_,T,b,J,gA,eA,CA,IA,oA){return e[0]=i,e[1]=n,e[2]=c,e[3]=I,e[4]=C,e[5]=m,e[6]=R,e[7]=_,e[8]=T,e[9]=b,e[10]=J,e[11]=gA,e[12]=eA,e[13]=CA,e[14]=IA,e[15]=oA,e}function e7(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function ZgA(e,i){if(e===i){var n=i[1],c=i[2],I=i[3],C=i[6],m=i[7],R=i[11];e[1]=i[4],e[2]=i[8],e[3]=i[12],e[4]=n,e[6]=i[9],e[7]=i[13],e[8]=c,e[9]=C,e[11]=i[14],e[12]=I,e[13]=m,e[14]=R}else e[0]=i[0],e[1]=i[4],e[2]=i[8],e[3]=i[12],e[4]=i[1],e[5]=i[5],e[6]=i[9],e[7]=i[13],e[8]=i[2],e[9]=i[6],e[10]=i[10],e[11]=i[14],e[12]=i[3],e[13]=i[7],e[14]=i[11],e[15]=i[15];return e}function XgA(e,i){var n=i[0],c=i[1],I=i[2],C=i[3],m=i[4],R=i[5],_=i[6],T=i[7],b=i[8],J=i[9],gA=i[10],eA=i[11],CA=i[12],IA=i[13],oA=i[14],vA=i[15],qA=n*R-c*m,Ae=n*_-I*m,HA=n*T-C*m,se=c*_-I*R,WA=c*T-C*R,Ye=I*T-C*_,We=b*IA-J*CA,Pe=b*oA-gA*CA,we=b*vA-eA*CA,et=J*oA-gA*IA,Xe=J*vA-eA*IA,ae=gA*vA-eA*oA,Je=qA*ae-Ae*Xe+HA*et+se*we-WA*Pe+Ye*We;return Je?(Je=1/Je,e[0]=(R*ae-_*Xe+T*et)*Je,e[1]=(I*Xe-c*ae-C*et)*Je,e[2]=(IA*Ye-oA*WA+vA*se)*Je,e[3]=(gA*WA-J*Ye-eA*se)*Je,e[4]=(_*we-m*ae-T*Pe)*Je,e[5]=(n*ae-I*we+C*Pe)*Je,e[6]=(oA*HA-CA*Ye-vA*Ae)*Je,e[7]=(b*Ye-gA*HA+eA*Ae)*Je,e[8]=(m*Xe-R*we+T*We)*Je,e[9]=(c*we-n*Xe-C*We)*Je,e[10]=(CA*WA-IA*HA+vA*qA)*Je,e[11]=(J*HA-b*WA-eA*qA)*Je,e[12]=(R*Pe-m*et-_*We)*Je,e[13]=(n*et-c*Pe+I*We)*Je,e[14]=(IA*Ae-CA*se-oA*qA)*Je,e[15]=(b*se-J*Ae+gA*qA)*Je,e):null}function $gA(e,i){var n=i[0],c=i[1],I=i[2],C=i[3],m=i[4],R=i[5],_=i[6],T=i[7],b=i[8],J=i[9],gA=i[10],eA=i[11],CA=i[12],IA=i[13],oA=i[14],vA=i[15],qA=n*R-c*m,Ae=n*_-I*m,HA=n*T-C*m,se=c*_-I*R,WA=c*T-C*R,Ye=I*T-C*_,We=b*IA-J*CA,Pe=b*oA-gA*CA,we=b*vA-eA*CA,et=J*oA-gA*IA,Xe=J*vA-eA*IA,ae=gA*vA-eA*oA;return e[0]=R*ae-_*Xe+T*et,e[1]=I*Xe-c*ae-C*et,e[2]=IA*Ye-oA*WA+vA*se,e[3]=gA*WA-J*Ye-eA*se,e[4]=_*we-m*ae-T*Pe,e[5]=n*ae-I*we+C*Pe,e[6]=oA*HA-CA*Ye-vA*Ae,e[7]=b*Ye-gA*HA+eA*Ae,e[8]=m*Xe-R*we+T*We,e[9]=c*we-n*Xe-C*We,e[10]=CA*WA-IA*HA+vA*qA,e[11]=J*HA-b*WA-eA*qA,e[12]=R*Pe-m*et-_*We,e[13]=n*et-c*Pe+I*We,e[14]=IA*Ae-CA*se-oA*qA,e[15]=b*se-J*Ae+gA*qA,e}function AcA(e){var i=e[0],n=e[1],c=e[2],I=e[3],C=e[4],m=e[5],R=e[6],_=e[7],T=e[8],b=e[9],J=e[10],gA=e[11],eA=e[12],CA=e[13],IA=e[14],oA=i*m-n*C,vA=i*R-c*C,qA=n*R-c*m,Ae=T*CA-b*eA,HA=T*IA-J*eA,se=b*IA-J*CA;return _*(i*se-n*HA+c*Ae)-I*(C*se-m*HA+R*Ae)+e[15]*(T*qA-b*vA+J*oA)-gA*(eA*qA-CA*vA+IA*oA)}function t7(e,i,n){var c=i[0],I=i[1],C=i[2],m=i[3],R=i[4],_=i[5],T=i[6],b=i[7],J=i[8],gA=i[9],eA=i[10],CA=i[11],IA=i[12],oA=i[13],vA=i[14],qA=i[15],Ae=n[0],HA=n[1],se=n[2],WA=n[3];return e[0]=Ae*c+HA*R+se*J+WA*IA,e[1]=Ae*I+HA*_+se*gA+WA*oA,e[2]=Ae*C+HA*T+se*eA+WA*vA,e[3]=Ae*m+HA*b+se*CA+WA*qA,Ae=n[4],HA=n[5],se=n[6],WA=n[7],e[4]=Ae*c+HA*R+se*J+WA*IA,e[5]=Ae*I+HA*_+se*gA+WA*oA,e[6]=Ae*C+HA*T+se*eA+WA*vA,e[7]=Ae*m+HA*b+se*CA+WA*qA,Ae=n[8],HA=n[9],se=n[10],WA=n[11],e[8]=Ae*c+HA*R+se*J+WA*IA,e[9]=Ae*I+HA*_+se*gA+WA*oA,e[10]=Ae*C+HA*T+se*eA+WA*vA,e[11]=Ae*m+HA*b+se*CA+WA*qA,Ae=n[12],HA=n[13],se=n[14],WA=n[15],e[12]=Ae*c+HA*R+se*J+WA*IA,e[13]=Ae*I+HA*_+se*gA+WA*oA,e[14]=Ae*C+HA*T+se*eA+WA*vA,e[15]=Ae*m+HA*b+se*CA+WA*qA,e}function ecA(e,i,n){var c,I,C,m,R,_,T,b,J,gA,eA,CA,IA=n[0],oA=n[1],vA=n[2];return i===e?(e[12]=i[0]*IA+i[4]*oA+i[8]*vA+i[12],e[13]=i[1]*IA+i[5]*oA+i[9]*vA+i[13],e[14]=i[2]*IA+i[6]*oA+i[10]*vA+i[14],e[15]=i[3]*IA+i[7]*oA+i[11]*vA+i[15]):(c=i[0],I=i[1],C=i[2],m=i[3],R=i[4],_=i[5],T=i[6],b=i[7],J=i[8],gA=i[9],eA=i[10],CA=i[11],e[0]=c,e[1]=I,e[2]=C,e[3]=m,e[4]=R,e[5]=_,e[6]=T,e[7]=b,e[8]=J,e[9]=gA,e[10]=eA,e[11]=CA,e[12]=c*IA+R*oA+J*vA+i[12],e[13]=I*IA+_*oA+gA*vA+i[13],e[14]=C*IA+T*oA+eA*vA+i[14],e[15]=m*IA+b*oA+CA*vA+i[15]),e}function tcA(e,i,n){var c=n[0],I=n[1],C=n[2];return e[0]=i[0]*c,e[1]=i[1]*c,e[2]=i[2]*c,e[3]=i[3]*c,e[4]=i[4]*I,e[5]=i[5]*I,e[6]=i[6]*I,e[7]=i[7]*I,e[8]=i[8]*C,e[9]=i[9]*C,e[10]=i[10]*C,e[11]=i[11]*C,e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],e}function icA(e,i,n,c){var I,C,m,R,_,T,b,J,gA,eA,CA,IA,oA,vA,qA,Ae,HA,se,WA,Ye,We,Pe,we,et,Xe=c[0],ae=c[1],Je=c[2],pt=Math.sqrt(Xe*Xe+ae*ae+Je*Je);return pt0?(n[0]=2*(R*m+b*c+_*C-T*I)/J,n[1]=2*(_*m+b*I+T*c-R*C)/J,n[2]=2*(T*m+b*C+R*I-_*c)/J):(n[0]=2*(R*m+b*c+_*C-T*I),n[1]=2*(_*m+b*I+T*c-R*C),n[2]=2*(T*m+b*C+R*I-_*c)),i7(e,i,n),e}function EcA(e,i){return e[0]=i[12],e[1]=i[13],e[2]=i[14],e}function o7(e,i){var n=i[0],c=i[1],I=i[2],C=i[4],m=i[5],R=i[6],_=i[8],T=i[9],b=i[10];return e[0]=Math.sqrt(n*n+c*c+I*I),e[1]=Math.sqrt(C*C+m*m+R*R),e[2]=Math.sqrt(_*_+T*T+b*b),e}function dcA(e,i){var n=new hT(3);o7(n,i);var c=1/n[0],I=1/n[1],C=1/n[2],m=i[0]*c,R=i[1]*I,_=i[2]*C,T=i[4]*c,b=i[5]*I,J=i[6]*C,gA=i[8]*c,eA=i[9]*I,CA=i[10]*C,IA=m+b+CA,oA=0;return IA>0?(oA=2*Math.sqrt(IA+1),e[3]=.25*oA,e[0]=(J-eA)/oA,e[1]=(gA-_)/oA,e[2]=(R-T)/oA):m>b&&m>CA?(oA=2*Math.sqrt(1+m-b-CA),e[3]=(J-eA)/oA,e[0]=.25*oA,e[1]=(R+T)/oA,e[2]=(gA+_)/oA):b>CA?(oA=2*Math.sqrt(1+b-m-CA),e[3]=(gA-_)/oA,e[0]=(R+T)/oA,e[1]=.25*oA,e[2]=(J+eA)/oA):(oA=2*Math.sqrt(1+CA-m-b),e[3]=(R-T)/oA,e[0]=(gA+_)/oA,e[1]=(J+eA)/oA,e[2]=.25*oA),e}function CcA(e,i,n,c){i[0]=c[12],i[1]=c[13],i[2]=c[14];var I=c[0],C=c[1],m=c[2],R=c[4],_=c[5],T=c[6],b=c[8],J=c[9],gA=c[10];n[0]=Math.sqrt(I*I+C*C+m*m),n[1]=Math.sqrt(R*R+_*_+T*T),n[2]=Math.sqrt(b*b+J*J+gA*gA);var eA=1/n[0],CA=1/n[1],IA=1/n[2],oA=I*eA,vA=C*CA,qA=m*IA,Ae=R*eA,HA=_*CA,se=T*IA,WA=b*eA,Ye=J*CA,We=gA*IA,Pe=oA+HA+We,we=0;return Pe>0?(we=2*Math.sqrt(Pe+1),e[3]=.25*we,e[0]=(se-Ye)/we,e[1]=(WA-qA)/we,e[2]=(vA-Ae)/we):oA>HA&&oA>We?(we=2*Math.sqrt(1+oA-HA-We),e[3]=(se-Ye)/we,e[0]=.25*we,e[1]=(vA+Ae)/we,e[2]=(WA+qA)/we):HA>We?(we=2*Math.sqrt(1+HA-oA-We),e[3]=(WA-qA)/we,e[0]=(vA+Ae)/we,e[1]=.25*we,e[2]=(se+Ye)/we):(we=2*Math.sqrt(1+We-oA-HA),e[3]=(vA-Ae)/we,e[0]=(WA+qA)/we,e[1]=(se+Ye)/we,e[2]=.25*we),e}function hcA(e,i,n,c){var I=i[0],C=i[1],m=i[2],R=i[3],_=I+I,T=C+C,b=m+m,J=I*_,gA=I*T,eA=I*b,CA=C*T,IA=C*b,oA=m*b,vA=R*_,qA=R*T,Ae=R*b,HA=c[0],se=c[1],WA=c[2];return e[0]=(1-(CA+oA))*HA,e[1]=(gA+Ae)*HA,e[2]=(eA-qA)*HA,e[3]=0,e[4]=(gA-Ae)*se,e[5]=(1-(J+oA))*se,e[6]=(IA+vA)*se,e[7]=0,e[8]=(eA+qA)*WA,e[9]=(IA-vA)*WA,e[10]=(1-(J+CA))*WA,e[11]=0,e[12]=n[0],e[13]=n[1],e[14]=n[2],e[15]=1,e}function BcA(e,i,n,c,I){var C=i[0],m=i[1],R=i[2],_=i[3],T=C+C,b=m+m,J=R+R,gA=C*T,eA=C*b,CA=C*J,IA=m*b,oA=m*J,vA=R*J,qA=_*T,Ae=_*b,HA=_*J,se=c[0],WA=c[1],Ye=c[2],We=I[0],Pe=I[1],we=I[2],et=(1-(IA+vA))*se,Xe=(eA+HA)*se,ae=(CA-Ae)*se,Je=(eA-HA)*WA,pt=(1-(gA+vA))*WA,$t=(oA+qA)*WA,Pt=(CA+Ae)*Ye,ii=(oA-qA)*Ye,ki=(1-(gA+IA))*Ye;return e[0]=et,e[1]=Xe,e[2]=ae,e[3]=0,e[4]=Je,e[5]=pt,e[6]=$t,e[7]=0,e[8]=Pt,e[9]=ii,e[10]=ki,e[11]=0,e[12]=n[0]+We-(et*We+Je*Pe+Pt*we),e[13]=n[1]+Pe-(Xe*We+pt*Pe+ii*we),e[14]=n[2]+we-(ae*We+$t*Pe+ki*we),e[15]=1,e}function QcA(e,i){var n=i[0],c=i[1],I=i[2],C=i[3],m=n+n,R=c+c,_=I+I,T=n*m,b=c*m,J=c*R,gA=I*m,eA=I*R,CA=I*_,IA=C*m,oA=C*R,vA=C*_;return e[0]=1-J-CA,e[1]=b+vA,e[2]=gA-oA,e[3]=0,e[4]=b-vA,e[5]=1-T-CA,e[6]=eA+IA,e[7]=0,e[8]=gA+oA,e[9]=eA-IA,e[10]=1-T-J,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function pcA(e,i,n,c,I,C,m){var R=1/(n-i),_=1/(I-c),T=1/(C-m);return e[0]=2*C*R,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=2*C*_,e[6]=0,e[7]=0,e[8]=(n+i)*R,e[9]=(I+c)*_,e[10]=(m+C)*T,e[11]=-1,e[12]=0,e[13]=0,e[14]=m*C*2*T,e[15]=0,e}function n7(e,i,n,c,I){var C=1/Math.tan(i/2);if(e[0]=C/n,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=C,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=-1,e[12]=0,e[13]=0,e[15]=0,I!=null&&I!==1/0){var m=1/(c-I);e[10]=(I+c)*m,e[14]=2*I*c*m}else e[10]=-1,e[14]=-2*c;return e}lgA(A7,{add:()=>_cA,adjoint:()=>$gA,clone:()=>KgA,copy:()=>jgA,create:()=>qgA,decompose:()=>CcA,determinant:()=>AcA,equals:()=>bcA,exactEquals:()=>GcA,frob:()=>wcA,fromQuat:()=>QcA,fromQuat2:()=>ucA,fromRotation:()=>gcA,fromRotationTranslation:()=>i7,fromRotationTranslationScale:()=>hcA,fromRotationTranslationScaleOrigin:()=>BcA,fromScaling:()=>acA,fromTranslation:()=>rcA,fromValues:()=>WgA,fromXRotation:()=>ccA,fromYRotation:()=>lcA,fromZRotation:()=>IcA,frustum:()=>pcA,getRotation:()=>dcA,getScaling:()=>o7,getTranslation:()=>EcA,identity:()=>e7,invert:()=>XgA,lookAt:()=>vcA,mul:()=>kcA,multiply:()=>t7,multiplyScalar:()=>TcA,multiplyScalarAndAdd:()=>NcA,ortho:()=>DcA,orthoNO:()=>s7,orthoZO:()=>ScA,perspective:()=>mcA,perspectiveFromFieldOfView:()=>ycA,perspectiveNO:()=>n7,perspectiveZO:()=>fcA,rotate:()=>icA,rotateX:()=>ocA,rotateY:()=>ncA,rotateZ:()=>scA,scale:()=>tcA,set:()=>zgA,str:()=>RcA,sub:()=>LcA,subtract:()=>r7,targetTo:()=>McA,translate:()=>ecA,transpose:()=>ZgA});var mcA=n7;function fcA(e,i,n,c,I){var C=1/Math.tan(i/2);if(e[0]=C/n,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=C,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=-1,e[12]=0,e[13]=0,e[15]=0,I!=null&&I!==1/0){var m=1/(c-I);e[10]=I*m,e[14]=I*c*m}else e[10]=-1,e[14]=-c;return e}function ycA(e,i,n,c){var I=Math.tan(i.upDegrees*Math.PI/180),C=Math.tan(i.downDegrees*Math.PI/180),m=Math.tan(i.leftDegrees*Math.PI/180),R=Math.tan(i.rightDegrees*Math.PI/180),_=2/(m+R),T=2/(I+C);return e[0]=_,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=T,e[6]=0,e[7]=0,e[8]=-(m-R)*_*.5,e[9]=(I-C)*T*.5,e[10]=c/(n-c),e[11]=-1,e[12]=0,e[13]=0,e[14]=c*n/(n-c),e[15]=0,e}function s7(e,i,n,c,I,C,m){var R=1/(i-n),_=1/(c-I),T=1/(C-m);return e[0]=-2*R,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=-2*_,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=2*T,e[11]=0,e[12]=(i+n)*R,e[13]=(I+c)*_,e[14]=(m+C)*T,e[15]=1,e}var DcA=s7;function ScA(e,i,n,c,I,C,m){var R=1/(i-n),_=1/(c-I),T=1/(C-m);return e[0]=-2*R,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=-2*_,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=T,e[11]=0,e[12]=(i+n)*R,e[13]=(I+c)*_,e[14]=C*T,e[15]=1,e}function vcA(e,i,n,c){var I,C,m,R,_,T,b,J,gA,eA,CA=i[0],IA=i[1],oA=i[2],vA=c[0],qA=c[1],Ae=c[2],HA=n[0],se=n[1],WA=n[2];return Math.abs(CA-HA)0&&(b*=eA=1/Math.sqrt(eA),J*=eA,gA*=eA);var CA=_*gA-T*J,IA=T*b-R*gA,oA=R*J-_*b;return(eA=CA*CA+IA*IA+oA*oA)>0&&(CA*=eA=1/Math.sqrt(eA),IA*=eA,oA*=eA),e[0]=CA,e[1]=IA,e[2]=oA,e[3]=0,e[4]=J*oA-gA*IA,e[5]=gA*CA-b*oA,e[6]=b*IA-J*CA,e[7]=0,e[8]=b,e[9]=J,e[10]=gA,e[11]=0,e[12]=I,e[13]=C,e[14]=m,e[15]=1,e}function RcA(e){return"mat4("+e[0]+", "+e[1]+", "+e[2]+", "+e[3]+", "+e[4]+", "+e[5]+", "+e[6]+", "+e[7]+", "+e[8]+", "+e[9]+", "+e[10]+", "+e[11]+", "+e[12]+", "+e[13]+", "+e[14]+", "+e[15]+")"}function wcA(e){return Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]+e[3]*e[3]+e[4]*e[4]+e[5]*e[5]+e[6]*e[6]+e[7]*e[7]+e[8]*e[8]+e[9]*e[9]+e[10]*e[10]+e[11]*e[11]+e[12]*e[12]+e[13]*e[13]+e[14]*e[14]+e[15]*e[15])}function _cA(e,i,n){return e[0]=i[0]+n[0],e[1]=i[1]+n[1],e[2]=i[2]+n[2],e[3]=i[3]+n[3],e[4]=i[4]+n[4],e[5]=i[5]+n[5],e[6]=i[6]+n[6],e[7]=i[7]+n[7],e[8]=i[8]+n[8],e[9]=i[9]+n[9],e[10]=i[10]+n[10],e[11]=i[11]+n[11],e[12]=i[12]+n[12],e[13]=i[13]+n[13],e[14]=i[14]+n[14],e[15]=i[15]+n[15],e}function r7(e,i,n){return e[0]=i[0]-n[0],e[1]=i[1]-n[1],e[2]=i[2]-n[2],e[3]=i[3]-n[3],e[4]=i[4]-n[4],e[5]=i[5]-n[5],e[6]=i[6]-n[6],e[7]=i[7]-n[7],e[8]=i[8]-n[8],e[9]=i[9]-n[9],e[10]=i[10]-n[10],e[11]=i[11]-n[11],e[12]=i[12]-n[12],e[13]=i[13]-n[13],e[14]=i[14]-n[14],e[15]=i[15]-n[15],e}function TcA(e,i,n){return e[0]=i[0]*n,e[1]=i[1]*n,e[2]=i[2]*n,e[3]=i[3]*n,e[4]=i[4]*n,e[5]=i[5]*n,e[6]=i[6]*n,e[7]=i[7]*n,e[8]=i[8]*n,e[9]=i[9]*n,e[10]=i[10]*n,e[11]=i[11]*n,e[12]=i[12]*n,e[13]=i[13]*n,e[14]=i[14]*n,e[15]=i[15]*n,e}function NcA(e,i,n,c){return e[0]=i[0]+n[0]*c,e[1]=i[1]+n[1]*c,e[2]=i[2]+n[2]*c,e[3]=i[3]+n[3]*c,e[4]=i[4]+n[4]*c,e[5]=i[5]+n[5]*c,e[6]=i[6]+n[6]*c,e[7]=i[7]+n[7]*c,e[8]=i[8]+n[8]*c,e[9]=i[9]+n[9]*c,e[10]=i[10]+n[10]*c,e[11]=i[11]+n[11]*c,e[12]=i[12]+n[12]*c,e[13]=i[13]+n[13]*c,e[14]=i[14]+n[14]*c,e[15]=i[15]+n[15]*c,e}function GcA(e,i){return e[0]===i[0]&&e[1]===i[1]&&e[2]===i[2]&&e[3]===i[3]&&e[4]===i[4]&&e[5]===i[5]&&e[6]===i[6]&&e[7]===i[7]&&e[8]===i[8]&&e[9]===i[9]&&e[10]===i[10]&&e[11]===i[11]&&e[12]===i[12]&&e[13]===i[13]&&e[14]===i[14]&&e[15]===i[15]}function bcA(e,i){var n=e[0],c=e[1],I=e[2],C=e[3],m=e[4],R=e[5],_=e[6],T=e[7],b=e[8],J=e[9],gA=e[10],eA=e[11],CA=e[12],IA=e[13],oA=e[14],vA=e[15],qA=i[0],Ae=i[1],HA=i[2],se=i[3],WA=i[4],Ye=i[5],We=i[6],Pe=i[7],we=i[8],et=i[9],Xe=i[10],ae=i[11],Je=i[12],pt=i[13],$t=i[14],Pt=i[15];return Math.abs(n-qA)<=fc*Math.max(1,Math.abs(n),Math.abs(qA))&&Math.abs(c-Ae)<=fc*Math.max(1,Math.abs(c),Math.abs(Ae))&&Math.abs(I-HA)<=fc*Math.max(1,Math.abs(I),Math.abs(HA))&&Math.abs(C-se)<=fc*Math.max(1,Math.abs(C),Math.abs(se))&&Math.abs(m-WA)<=fc*Math.max(1,Math.abs(m),Math.abs(WA))&&Math.abs(R-Ye)<=fc*Math.max(1,Math.abs(R),Math.abs(Ye))&&Math.abs(_-We)<=fc*Math.max(1,Math.abs(_),Math.abs(We))&&Math.abs(T-Pe)<=fc*Math.max(1,Math.abs(T),Math.abs(Pe))&&Math.abs(b-we)<=fc*Math.max(1,Math.abs(b),Math.abs(we))&&Math.abs(J-et)<=fc*Math.max(1,Math.abs(J),Math.abs(et))&&Math.abs(gA-Xe)<=fc*Math.max(1,Math.abs(gA),Math.abs(Xe))&&Math.abs(eA-ae)<=fc*Math.max(1,Math.abs(eA),Math.abs(ae))&&Math.abs(CA-Je)<=fc*Math.max(1,Math.abs(CA),Math.abs(Je))&&Math.abs(IA-pt)<=fc*Math.max(1,Math.abs(IA),Math.abs(pt))&&Math.abs(oA-$t)<=fc*Math.max(1,Math.abs(oA),Math.abs($t))&&Math.abs(vA-Pt)<=fc*Math.max(1,Math.abs(vA),Math.abs(Pt))}var kcA=t7,LcA=r7,bL=`#version 300 es in vec2 a_position; in vec2 a_texCoord; out vec2 v_texCoord; @@ -524,18 +524,18 @@ void main() { float edge = nmsEdge > 0.0 ? 1.0 : 0.0; outColor = vec4(edge, 0.0, 0.0, 1.0); } -`,YcA=class{constructor(){jg(this,"gl"),jg(this,"positionBuffer"),jg(this,"texCoordBuffer"),jg(this,"ratio"),jg(this,"_tdProgram"),jg(this,"_kcProgram"),jg(this,"_mdProgram"),jg(this,"_edgeProgram"),jg(this,"_borderProgram"),jg(this,"_lastMaskTexture")}init(e,i,n,c){this.initParams(e,i,n,c),this.initPrograms()}initParams(e,i,n,c){this.gl=e,this.positionBuffer=i,this.texCoordBuffer=n,this.ratio=c}initPrograms(){this._tdProgram=this.createProgram(bL,UcA,["mask","lastMask"]),this._mdProgram=this.createProgram(bL,FcA,["mask"]),this._kcProgram=this.createProgram(bL,OcA,["mask"]),this._borderProgram=this.createProgram(bL,PcA,["mask","maskEdge","originalMask"]),this._edgeProgram=this.createProgram(bL,xcA,["mask"])}setAttributes(...e){const{gl:i}=this;e.forEach((n,c)=>{i.enableVertexAttribArray(c),i.bindBuffer(i.ARRAY_BUFFER,n),i.vertexAttribPointer(c,2,i.FLOAT,!1,0,0)})}createShader(e,i){const{gl:n}=this,c=n.createShader(e);return n.shaderSource(c,i),n.compileShader(c),c}createProgram(e,i,n){const{gl:c}=this,I=this.createShader(c.FRAGMENT_SHADER,i),C=this.createShader(c.VERTEX_SHADER,e),m=c.createProgram();if(c.attachShader(m,C),c.attachShader(m,I),c.linkProgram(m),!c.getProgramParameter(m,c.LINK_STATUS))throw new Error(`${c.getProgramInfoLog(m)}`);return c.useProgram(m),this.setAttributes(this.positionBuffer,this.texCoordBuffer),n.forEach((R,_)=>{c.uniform1i(c.getUniformLocation(m,R),1+_)}),m}createFramebuffer(e){const{gl:i}=this,n=i.createFramebuffer();return i.bindFramebuffer(i.FRAMEBUFFER,n),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,e,0),n}getTempTexture(e,i,n=!0,c){const{gl:I}=this;let C,m;I.useProgram(e),this.ratio===16/9?(C=640,m=360):(C=640,m=480);const R=I.createTexture();I.activeTexture(I.TEXTURE0),I.bindTexture(I.TEXTURE_2D,R),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_MIN_FILTER,I.LINEAR),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_MAG_FILTER,I.LINEAR),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_WRAP_S,I.CLAMP_TO_EDGE),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_WRAP_T,I.CLAMP_TO_EDGE),I.pixelStorei(I.PACK_ALIGNMENT,1),I.pixelStorei(I.UNPACK_ALIGNMENT,1),I.texImage2D(I.TEXTURE_2D,0,I.RGBA,C,m,0,I.RGBA,I.UNSIGNED_BYTE,null);const _=this.createFramebuffer(R);return i.forEach((T,b)=>{T&&(I.activeTexture(I.TEXTURE1+b),I.bindTexture(I.TEXTURE_2D,T||null))}),this.setAttributes(this.positionBuffer,this.texCoordBuffer),I.viewport(0,0,C,m),I.drawArrays(I.TRIANGLE_STRIP,0,4),n&&i.forEach((T,b)=>{T&&c!==b&&I.deleteTexture(T)}),I.deleteFramebuffer(_),R}postProcessing(e){this._lastMaskTexture=this.getTempTexture(this._tdProgram,[e,this._lastMaskTexture]);let i=this.getTempTexture(this._kcProgram,[this._lastMaskTexture],!1);for(let n=0;n<3;n++){i=this.getTempTexture(this._mdProgram,[i]);const c=this.getTempTexture(this._edgeProgram,[i],!1);i=this.getTempTexture(this._borderProgram,[i,c,this._lastMaskTexture],!0,2)}return i}close(){const{gl:e}=this;this._borderProgram&&e.deleteProgram(this._borderProgram),this._edgeProgram&&e.deleteProgram(this._edgeProgram),this._kcProgram&&e.deleteProgram(this._kcProgram),this._mdProgram&&e.deleteProgram(this._mdProgram),this._tdProgram&&e.deleteProgram(this._tdProgram)}},VcA=new YcA,HcA=(e=>(e[e.TRACE=0]="TRACE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.NONE=5]="NONE",e))(HcA||{}),JcA={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},N_=570703,d3=0,a7=class g7{constructor(i){this.core=i,jg(this,"seq"),jg(this,"_core"),jg(this,"log"),jg(this,"preLoadPromise"),jg(this,"startResolve"),jg(this,"startReject"),jg(this,"mediaPipeSolutions"),jg(this,"assetsPath"),jg(this,"currentType"),jg(this,"onAbort"),jg(this,"isAborted",!1),d3+=1,this.seq=d3,this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${d3}`}),this.log.info("created"),i.assetsPath&&(this.preLoadPromise=this.preload(i.assetsPath))}static isSupported(){if(YgA<90)return!1;const i=document.createElement("canvas").getContext("webgl2",JcA);return!!(i&&i instanceof WebGL2RenderingContext)}async preload(i){try{this._core.room.videoManager.Wasm||(this._core.room.videoManager.Wasm=await BgA());const n=c=>{var I;this.core.kvStatManager.addEnum({key:N_,value:this.getKVTypeValue(!1,this.isAborted,"ABORT_IN_INFERENCE")}),this.isAborted=!0,this.log.error("mediaPipeSolutions abort",c),this.core.clearStarted(this,this.getGroup()),this.stop(),(I=this.onAbort)==null||I.call(this,c)};this._core.room.videoManager.initVirtualBackground(n,A7,VcA),await this._core.initVisionTaskRegistry(i,["ImageSegmenter"])}catch(n){const{RtcError:c,ErrorCode:I}=this._core.errorModule;throw new c({code:I.INVALID_OPERATION,message:`VirtualBackground preload error, please redeploy the assets of the npm package. detail: ${n}`})}}getName(){return g7.Name}getAlias(){return"vb"}getValidateRule(i){switch(i){case"start":return EgA(this._core);case"update":return dgA(this._core);case"stop":return CgA(this._core)}}getGroup(){return"vb"}getKVTypeValue(i=!1,n=!1,c="NONE"){let I=0;switch(this.currentType){case"blur":I|=0;break;case"image":I|=1;break;case"color":I|=2}switch(i&&(I|=256),n&&(I|=512),c){case"ABORT_IN_INFERENCE":I|=4096;break;case"ABORT_IN_VIDEO_MANAGER":I|=8192;break;case"OTHER":I|=61440}return I}hexToRgb(i){const n=i.replace("#","");return[parseInt(n.slice(0,2),16)/255,parseInt(n.slice(2,4),16)/255,parseInt(n.slice(4,6),16)/255]}async start(i){const{type:n="blur",src:c,blurLevel:I=3,onAbort:C}=i;this.currentType=n,this.onAbort=C,n==="color"&&typeof i.color=="string"&&(i.color=this.hexToRgb(i.color));const{auth:m}=await IgA({sdkAppId:i.sdkAppId,userId:i.userId,userSig:i.userSig,core:this._core}),{RtcError:R,ErrorCodeDictionary:_,ErrorCode:T}=this._core.errorModule;if(!m){const b=this._core.utils.isOverseaSdkAppId(i.sdkAppId)?"https://trtc.io/document/56025":"https://cloud.tencent.com/document/product/647/85386";throw new R({code:_.NEED_TO_BUY,messageParams:{value:"Virtual Background",url:b}})}if(!this.preLoadPromise){if(!this._core.assetsPath)throw new R({code:T.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});this.preLoadPromise=this.preload(this._core.assetsPath)}return await this.preLoadPromise,this.core.room.videoManager.setVirtualBackground({type:n,imageUrl:c,blurLevel:I,enableFaceCentering:i.enableFaceCentering,enableEffectOptimization:i.enableEffectOptimization,color:i.color,onAbort:b=>{var J;this.core.kvStatManager.addEnum({key:N_,value:this.getKVTypeValue(!0,this.isAborted,"ABORT_IN_VIDEO_MANAGER")}),this.isAborted=!0,this.core.clearStarted(this,this.getGroup()),this.stop(),delete this.preLoadPromise,(J=this.onAbort)==null||J.call(this,b)}}).then(()=>{this.core.kvStatManager.addEnum({key:N_,value:this.getKVTypeValue(!1,this.isAborted,"NONE")})}).catch(b=>{throw this.core.kvStatManager.addEnum({key:N_,value:this.getKVTypeValue(!0,this.isAborted,"OTHER")}),b})}async update(i){const{type:n,src:c}=i;return n!==this.currentType&&(this.currentType=n),n==="color"&&typeof i.color=="string"&&(i.color=this.hexToRgb(i.color)),this.core.room.videoManager.setVirtualBackground({type:n,imageUrl:c,blurLevel:i.blurLevel,enableFaceCentering:i.enableFaceCentering,enableEffectOptimization:i.enableEffectOptimization,color:i.color}).then(()=>{this.core.kvStatManager.addEnum({key:N_,value:this.getKVTypeValue(!1,!1,"NONE")})}).catch(()=>{this.core.kvStatManager.addEnum({key:N_,value:this.getKVTypeValue(!0,!1,"OTHER")})})}async stop(){return this.core.room.videoManager.setVirtualBackground()}};jg(a7,"Name","VirtualBackground");var c7=a7,qcA=c7;const KcA=Object.freeze(Object.defineProperty({__proto__:null,VirtualBackground:c7,default:qcA},Symbol.toStringTag,{value:"Module"})),jcA=$U(KcA);var WcA=Object.defineProperty,zcA=(e,i,n)=>i in e?WcA(e,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[i]=n,jL=(e,i,n)=>zcA(e,typeof i!="symbol"?i+"":i,n);function ZcA(e){return{name:"BasicBeautyOptions",type:"object",required:!0,allowEmpty:!1,properties:{beauty:{required:!1,type:"number"},brightness:{required:!1,type:"number"},ruddy:{required:!1,type:"number"}},validate(i,n,c,I){const{RtcError:C,ErrorCode:m,ErrorCodeDictionary:R}=e.errorModule;if(e.utils.isOverseaSdkAppId(i.sdkAppId))throw new C({code:m.INVALID_OPERATION,extraCode:R.INVALID_OPERATION,message:"This feature is not yet available in your country or region. If you have any questions, you can go to the community for consultation: https://zhiliao.qq.com/s/cWSPGIIM62CC/c3TPGIIM62CQ"})}}}function XcA(e){return{name:"StopBasicBeautyOptions",required:!1}}var $cA=(()=>{var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(i={}){var n,c,I=i;I.ready=new Promise(($,j)=>{n=$,c=j});var C=Object.assign({},I),m="";typeof document<"u"&&document.currentScript&&(m=document.currentScript.src),e&&(m=e),m=m.indexOf("blob:")!==0?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var R,_,T=I.print||console.log.bind(console),b=I.printErr||console.error.bind(console);function J($){if($t($))return function(j){for(var RA=atob(j),ZA=new Uint8Array(RA.length),ne=0;ne$.startsWith(pt);function Pt($){return Promise.resolve().then(()=>function(j){if(j==ae&&R)return new Uint8Array(R);var RA=J(j);if(RA)return RA;throw"both async and sync fetching of the wasm failed"}($))}function ii($,j,RA,ZA){return function(ne,De,Ke){return Pt(ne).then(qe=>WebAssembly.instantiate(qe,De)).then(qe=>qe).then(Ke,qe=>{b(`failed to asynchronously prepare wasm: ${qe}`),Xe(qe)})}(j,RA,ZA)}$t(ae="data:application/octet-stream;base64,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IAEoAgA2AgAgAiABKAIENgIEIAIgASgCCDYCCCACIAEoAgw2AgwgAiABKAIQNgIQIAIgASgCFDYCFCACIAEoAhg2AhggAiABKAIcNgIcIAIgASgCIDYCICACIAEoAiQ2AiQgAiABKAIoNgIoIAIgASgCLDYCLCACIAEoAjA2AjAgAiABKAI0NgI0IAIgASgCODYCOCACIAEoAjw2AjwgAUFAayEBIAJBQGsiAiAFTQ0ACwsgAiAETw0BA0AgAiABKAIANgIAIAFBBGohASACQQRqIgIgBEkNAAsMAQsgA0EESQRAIAAhAgwBCyAAIANBBGsiBEsEQCAAIQIMAQsgACECA0AgAiABLQAAOgAAIAIgAS0AAToAASACIAEtAAI6AAIgAiABLQADOgADIAFBBGohASACQQRqIgIgBE0NAAsLIAIgA0kEQANAIAIgAS0AADoAACABQQFqIQEgAkEBaiICIANHDQALCyAACwsAIAEgAiAAEEIaCxIAIAFBAXRB8MoAakECIAAQQgv5AQEEfwJ/IAEQKiECIwBBEGsiBSQAAn8gAC0AC0EHdgRAIAAoAgQMAQsgAC0AC0H/AHELIgRBAE8EQAJAIAIgAC0AC0EHdgR/IAAoAghB/////wdxQQFrBUEKCyIDIARrTQRAIAJFDQECfyAALQALQQd2BEAgACgCAAwBCyAACyIDIAQEfyACIANqIAMgBBBFIAEgAkEAIAMgBGogAUsbQQAgASADTxtqBSABCyACEEUgACACIARqIgEQMSAFQQA6AA8gASADaiAFLQAPOgAADAELIAAgAyACIARqIANrIARBACACIAEQRAsgBUEQaiQAIAAMAQsQJwALC/ICAgJ/AX4CQCACRQ0AIAAgAToAACAAIAJqIgNBAWsgAToAACACQQNJDQAgACABOgACIAAgAToAASADQQNrIAE6AAAgA0ECayABOgAAIAJBB0kNACAAIAE6AAMgA0EEayABOgAAIAJBCUkNACAAQQAgAGtBA3EiBGoiAyABQf8BcUGBgoQIbCIBNgIAIAMgAiAEa0F8cSIEaiICQQRrIAE2AgAgBEEJSQ0AIAMgATYCCCADIAE2AgQgAkEIayABNgIAIAJBDGsgATYCACAEQRlJDQAgAyABNgIYIAMgATYCFCADIAE2AhAgAyABNgIMIAJBEGsgATYCACACQRRrIAE2AgAgAkEYayABNgIAIAJBHGsgATYCACAEIANBBHFBGHIiBGsiAkEgSQ0AIAGtQoGAgIAQfiEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkEgayICQR9LDQALCyAACwUAEAwAC1IBAn9B2NQAKAIAIgEgAEEHakF4cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQEUUNAQtB2NQAIAA2AgAgAQ8LQejeAEEwNgIAQX8LgwECBX8BfgJAIABCgICAgBBUBEAgACEHDAELA0AgAUEBayIBIAAgAEIKgCIHQgp+fadBMHI6AAAgAEL/////nwFWIQUgByEAIAUNAAsLIAenIgIEQANAIAFBAWsiASACIAJBCm4iA0EKbGtBMHI6AAAgAkEJSyEGIAMhAiAGDQALCyABC3oBA38CQAJAIAAiAUEDcUUNACABLQAARQRAQQAPCwNAIAFBAWoiAUEDcUUNASABLQAADQALDAELA0AgASICQQRqIQEgAigCACIDQX9zIANBgYKECGtxQYCBgoR4cUUNAAsDQCACIgFBAWohAiABLQAADQALCyABIABrC78EAQl/AkACfyAALQALQQd2BEAgACgCBAwBCyAALQALQf8AcQsiAiABSQRAIwBBEGsiBiQAIAEgAmsiBQRAIAUgAC0AC0EHdgR/IAAoAghB/////wdxQQFrBUEKCyICAn8gAC0AC0EHdgRAIAAoAgQMAQsgAC0AC0H/AHELIgFrSwRAIwBBEGsiBCQAAkAgBSACayABaiIDQe////8HIAJrTQRAAn8gAC0AC0EHdgRAIAAoAgAMAQsgAAshByAEQQRqIgggACACQef///8DSQR/IAQgAkEBdDYCDCAEIAIgA2o2AgQjAEEQayIDJAAgCCgCACAEQQxqIgkoAgBJIQogA0EQaiQAIAkgCCAKGygCACIDQQtPBH8gA0EQakFwcSIDIANBAWsiAyADQQtGGwVBCgtBAWoFQe////8HCxAwIAQoAgQhAyAEKAIIGiABBEAgAyAHIAEQIwsgAkEKRwRAIAcQGQsgACADNgIAIAAgACgCCEGAgICAeHEgBCgCCEH/////B3FyNgIIIAAgACgCCEGAgICAeHI2AgggBEEQaiQADAELECcACyAAIAE2AgQLIAECfyAALQALQQd2BEAgACgCAAwBCyAACyICaiAFEEAgACABIAVqIgAQMSAGQQA6AA8gACACaiAGLQAPOgAACyAGQRBqJAAMAQsCfyAALQALQQd2BEAgACgCAAwBCyAACyEEIwBBEGsiAiQAIAAgARAxIAJBADoADyABIARqIAItAA86AAAgAkEQaiQACwsGACAAEBkL0igBDH8jAEEQayIKJAACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEHs3gAoAgAiBkEQIABBC2pBeHEgAEELSRsiBUEDdiIAdiIBQQNxBEACQCABQX9zQQFxIABqIgJBA3QiAUGU3wBqIgAgAUGc3wBqKAIAIgEoAggiA0YEQEHs3gAgBkF+IAJ3cTYCAAwBCyADIAA2AgwgACADNgIICyABQQhqIQAgASACQQN0IgJBA3I2AgQgASACaiIBIAEoAgRBAXI2AgQMCgsgBUH03gAoAgAiB00NASABBEACQEECIAB0IgJBACACa3IgASAAdHFoIgFBA3QiAEGU3wBqIgIgAEGc3wBqKAIAIgAoAggiA0YEQEHs3gAgBkF+IAF3cSIGNgIADAELIAMgAjYCDCACIAM2AggLIAAgBUEDcjYCBCAAIAVqIgQgAUEDdCIBIAVrIgNBAXI2AgQgACABaiADNgIAIAcEQCAHQXhxQZTfAGohAUGA3wAoAgAhAgJ/IAZBASAHQQN2dCIFcUUEQEHs3gAgBSAGcjYCACABDAELIAEoAggLIQUgASACNgIIIAUgAjYCDCACIAE2AgwgAiAFNgIICyAAQQhqIQBBgN8AIAQ2AgBB9N4AIAM2AgAMCgtB8N4AKAIAIgtFDQEgC2hBAnRBnOEAaigCACICKAIEQXhxIAVrIQQgAiEBA0ACQCABKAIQIgBFBEAgASgCFCIARQ0BCyAAKAIEQXhxIAVrIgEgBCABIARJIgEbIQQgACACIAEbIQIgACEBDAELCyACKAIYIQkgAiACKAIMIgNHBEBB/N4AKAIAGiACKAIIIgAgAzYCDCADIAA2AggMCQsgAkEUaiIBKAIAIgBFBEAgAigCECIARQ0DIAJBEGohAQsDQCABIQggACIDQRRqIgEoAgAiAA0AIANBEGohASADKAIQIgANAAsgCEEANgIADAgLQX8hBSAAQb9/Sw0AIABBC2oiAEF4cSEFQfDeACgCACIIRQ0AQQAgBWshBAJAAkACQAJ/QQAgBUGAAkkNABpBHyAFQf///wdLDQAaIAVBJiAAQQh2ZyIAa3ZBAXEgAEEBdGtBPmoLIgdBAnRBnOEAaigCACIBRQRAQQAhAAwBC0EAIQAgBUEZIAdBAXZrQQAgB0EfRxt0IQIDQAJAIAEoAgRBeHEgBWsiBiAETw0AIAEhAyAGIgQNAEEAIQQgASEADAMLIAAgASgCFCIGIAYgASACQR12QQRxaigCECIBRhsgACAGGyEAIAJBAXQhAiABDQALCyAAIANyRQRAQQAhA0ECIAd0IgBBACAAa3IgCHEiAEUNAyAAaEECdEGc4QBqKAIAIQALIABFDQELA0AgACgCBEF4cSAFayICIARJIQEgAiAEIAEbIQQgACADIAEbIQMgACgCECIBBH8gAQUgACgCFAsiAA0ACwsgA0UNACAEQfTeACgCACAFa08NACADKAIYIQcgAyADKAIMIgJHBEBB/N4AKAIAGiADKAIIIgAgAjYCDCACIAA2AggMBwsgA0EUaiIBKAIAIgBFBEAgAygCECIARQ0DIANBEGohAQsDQCABIQYgACICQRRqIgEoAgAiAA0AIAJBEGohASACKAIQIgANAAsgBkEANgIADAYLIAVB9N4AKAIAIgNNBEBBgN8AKAIAIQACQCADIAVrIgFBEE8EQCAAIAVqIgIgAUEBcjYCBCAAIANqIAE2AgAgACAFQQNyNgIEDAELIAAgA0EDcjYCBCAAIANqIgEgASgCBEEBcjYCBEEAIQJBACEBC0H03gAgATYCAEGA3wAgAjYCACAAQQhqIQAMCAsgBUH43gAoAgAiAkkEQEH43gAgAiAFayIBNgIAQYTfAEGE3wAoAgAiACAFaiICNgIAIAIgAUEBcjYCBCAAIAVBA3I2AgQgAEEIaiEADAgLQQAhACAFQS9qIgQCf0HE4gAoAgAEQEHM4gAoAgAMAQtB0OIAQn83AgBByOIAQoCggICAgAQ3AgBBxOIAIApBDGpBcHFB2KrVqgVzNgIAQdjiAEEANgIAQajiAEEANgIAQYAgCyIBaiIGQQAgAWsiCHEiASAFTQ0HQaTiACgCACIDBEBBnOIAKAIAIgcgAWoiCSAHTQ0IIAMgCUkNCAsCQEGo4gAtAABBBHFFBEACQAJAAkACQEGE3wAoAgAiAwRAQaziACEAA0AgAyAAKAIAIgdPBEAgByAAKAIEaiADSw0DCyAAKAIIIgANAAsLQQAQKCICQX9GDQMgASEGQcjiACgCACIAQQFrIgMgAnEEQCABIAJrIAIgA2pBACAAa3FqIQYLIAUgBk8NA0Gk4gAoAgAiAARAQZziACgCACIDIAZqIgggA00NBCAAIAhJDQQLIAYQKCIAIAJHDQEMBQsgBiACayAIcSIGECgiAiAAKAIAIAAoAgRqRg0BIAIhAAsgAEF/Rg0BIAVBMGogBk0EQCAAIQIMBAtBzOIAKAIAIgIgBCAGa2pBACACa3EiAhAoQX9GDQEgAiAGaiEGIAAhAgwDCyACQX9HDQILQajiAEGo4gAoAgBBBHI2AgALIAEQKCECQQAQKCEAIAJBf0YNBSAAQX9GDQUgACACTQ0FIAAgAmsiBiAFQShqTQ0FC0Gc4gBBnOIAKAIAIAZqIgA2AgBBoOIAKAIAIABJBEBBoOIAIAA2AgALAkBBhN8AKAIAIgQEQEGs4gAhAANAIAIgACgCACIBIAAoAgQiA2pGDQIgACgCCCIADQALDAQLQfzeACgCACIAQQAgACACTRtFBEBB/N4AIAI2AgALQQAhAEGw4gAgBjYCAEGs4gAgAjYCAEGM3wBBfzYCAEGQ3wBBxOIAKAIANgIAQbjiAEEANgIAA0AgAEEDdCIBQZzfAGogAUGU3wBqIgM2AgAgAUGg3wBqIAM2AgAgAEEBaiIAQSBHDQALQfjeACAGQShrIgBBeCACa0EHcSIBayIDNgIAQYTfACABIAJqIgE2AgAgASADQQFyNgIEIAAgAmpBKDYCBEGI3wBB1OIAKAIANgIADAQLIAIgBE0NAiABIARLDQIgACgCDEEIcQ0CIAAgAyAGajYCBEGE3wAgBEF4IARrQQdxIgBqIgE2AgBB+N4AQfjeACgCACAGaiICIABrIgA2AgAgASAAQQFyNgIEIAIgBGpBKDYCBEGI3wBB1OIAKAIANgIADAMLQQAhAwwFC0EAIQIMAwtB/N4AKAIAIAJLBEBB/N4AIAI2AgALIAIgBmohAUGs4gAhAAJAAkACQANAIAEgACgCAEcEQCAAKAIIIgANAQwCCwsgAC0ADEEIcUUNAQtBrOIAIQADQAJAIAQgACgCACIBTwRAIAEgACgCBGoiAyAESw0BCyAAKAIIIQAMAQsLQfjeACAGQShrIgBBeCACa0EHcSIBayIINgIAQYTfACABIAJqIgE2AgAgASAIQQFyNgIEIAAgAmpBKDYCBEGI3wBB1OIAKAIANgIAIAQgA0EnIANrQQdxakEvayIAIAAgBEEQakkbIgFBGzYCBCABQbTiACkCADcCECABQaziACkCADcCCEG04gAgAUEIajYCAEGw4gAgBjYCAEGs4gAgAjYCAEG44gBBADYCACABQRhqIQADQCAAQQc2AgQgAEEIaiEMIABBBGohACAMIANJDQALIAEgBEYNAiABIAEoAgRBfnE2AgQgBCABIARrIgJBAXI2AgQgASACNgIAIAJB/wFNBEAgAkF4cUGU3wBqIQACf0Hs3gAoAgAiAUEBIAJBA3Z0IgJxRQRAQezeACABIAJyNgIAIAAMAQsgACgCCAshASAAIAQ2AgggASAENgIMIAQgADYCDCAEIAE2AggMAwtBHyEAIAJB////B00EQCACQSYgAkEIdmciAGt2QQFxIABBAXRrQT5qIQALIAQgADYCHCAEQgA3AhAgAEECdEGc4QBqIQECQEHw3gAoAgAiA0EBIAB0IgZxRQRAQfDeACADIAZyNgIAIAEgBDYCAAwBCyACQRkgAEEBdmtBACAAQR9HG3QhACABKAIAIQMDQCADIgEoAgRBeHEgAkYNAyAAQR12IQMgAEEBdCEAIAEgA0EEcWoiBigCECIDDQALIAYgBDYCEAsgBCABNgIYIAQgBDYCDCAEIAQ2AggMAgsgACACNgIAIAAgACgCBCAGajYCBCACQXggAmtBB3FqIgcgBUEDcjYCBCABQXggAWtBB3FqIgQgBSAHaiIFayEGAkBBhN8AKAIAIARGBEBBhN8AIAU2AgBB+N4AQfjeACgCACAGaiIANgIAIAUgAEEBcjYCBAwBC0GA3wAoAgAgBEYEQEGA3wAgBTYCAEH03gBB9N4AKAIAIAZqIgA2AgAgBSAAQQFyNgIEIAAgBWogADYCAAwBCyAEKAIEIgJBA3FBAUYEQCACQXhxIQkCQCACQf8BTQRAIAQoAgwiACAEKAIIIgFGBEBB7N4AQezeACgCAEF+IAJBA3Z3cTYCAAwCCyABIAA2AgwgACABNgIIDAELIAQoAhghCAJAIAQgBCgCDCIARwRAQfzeACgCABogBCgCCCIBIAA2AgwgACABNgIIDAELAkAgBEEUaiIBKAIAIgJFBEAgBCgCECICRQ0BIARBEGohAQsDQCABIQMgAiIAQRRqIgEoAgAiAg0AIABBEGohASAAKAIQIgINAAsgA0EANgIADAELQQAhAAsgCEUNAAJAIAQoAhwiAUECdEGc4QBqIgIoAgAgBEYEQCACIAA2AgAgAA0BQfDeAEHw3gAoAgBBfiABd3E2AgAMAgsgCEEQQRQgCCgCECAERhtqIAA2AgAgAEUNAQsgACAINgIYIAQoAhAiAQRAIAAgATYCECABIAA2AhgLIAQoAhQiAUUNACAAIAE2AhQgASAANgIYCyAGIAlqIQYgBCAJaiIEKAIEIQILIAQgAkF+cTYCBCAFIAZBAXI2AgQgBSAGaiAGNgIAIAZB/wFNBEAgBkF4cUGU3wBqIQACf0Hs3gAoAgAiAUEBIAZBA3Z0IgJxRQRAQezeACABIAJyNgIAIAAMAQsgACgCCAshASAAIAU2AgggASAFNgIMIAUgADYCDCAFIAE2AggMAQtBHyECIAZB////B00EQCAGQSYgBkEIdmciAGt2QQFxIABBAXRrQT5qIQILIAUgAjYCHCAFQgA3AhAgAkECdEGc4QBqIQECQAJAQfDeACgCACIAQQEgAnQiA3FFBEBB8N4AIAAgA3I2AgAgASAFNgIADAELIAZBGSACQQF2a0EAIAJBH0cbdCECIAEoAgAhAANAIAAiASgCBEF4cSAGRg0CIAJBHXYhACACQQF0IQIgASAAQQRxaiIDKAIQIgANAAsgAyAFNgIQCyAFIAE2AhggBSAFNgIMIAUgBTYCCAwBCyABKAIIIgAgBTYCDCABIAU2AgggBUEANgIYIAUgATYCDCAFIAA2AggLIAdBCGohAAwFCyABKAIIIgAgBDYCDCABIAQ2AgggBEEANgIYIAQgATYCDCAEIAA2AggLQfjeACgCACIAIAVNDQBB+N4AIAAgBWsiATYCAEGE3wBBhN8AKAIAIgAgBWoiAjYCACACIAFBAXI2AgQgACAFQQNyNgIEIABBCGohAAwDC0Ho3gBBMDYCAEEAIQAMAgsCQCAHRQ0AAkAgAygCHCIAQQJ0QZzhAGoiASgCACADRgRAIAEgAjYCACACDQFB8N4AIAhBfiAAd3EiCDYCAAwCCyAHQRBBFCAHKAIQIANGG2ogAjYCACACRQ0BCyACIAc2AhggAygCECIABEAgAiAANgIQIAAgAjYCGAsgAygCFCIARQ0AIAIgADYCFCAAIAI2AhgLAkAgBEEPTQRAIAMgBCAFaiIAQQNyNgIEIAAgA2oiACAAKAIEQQFyNgIEDAELIAMgBUEDcjYCBCADIAVqIgIgBEEBcjYCBCACIARqIAQ2AgAgBEH/AU0EQCAEQXhxQZTfAGohAAJ/QezeACgCACIBQQEgBEEDdnQiBXFFBEBB7N4AIAEgBXI2AgAgAAwBCyAAKAIICyEBIAAgAjYCCCABIAI2AgwgAiAANgIMIAIgATYCCAwBC0EfIQAgBEH///8HTQRAIARBJiAEQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAAsgAiAANgIcIAJCADcCECAAQQJ0QZzhAGohAQJAAkAgCEEBIAB0IgVxRQRAQfDeACAFIAhyNgIAIAEgAjYCAAwBCyAEQRkgAEEBdmtBACAAQR9HG3QhACABKAIAIQUDQCAFIgEoAgRBeHEgBEYNAiAAQR12IQUgAEEBdCEAIAEgBUEEcWoiBigCECIFDQALIAYgAjYCEAsgAiABNgIYIAIgAjYCDCACIAI2AggMAQsgASgCCCIAIAI2AgwgASACNgIIIAJBADYCGCACIAE2AgwgAiAANgIICyADQQhqIQAMAQsCQCAJRQ0AAkAgAigCHCIAQQJ0QZzhAGoiASgCACACRgRAIAEgAzYCACADDQFB8N4AIAtBfiAAd3E2AgAMAgsgCUEQQRQgCSgCECACRhtqIAM2AgAgA0UNAQsgAyAJNgIYIAIoAhAiAARAIAMgADYCECAAIAM2AhgLIAIoAhQiAEUNACADIAA2AhQgACADNgIYCwJAIARBD00EQCACIAQgBWoiAEEDcjYCBCAAIAJqIgAgACgCBEEBcjYCBAwBCyACIAVBA3I2AgQgAiAFaiIDIARBAXI2AgQgAyAEaiAENgIAIAcEQCAHQXhxQZTfAGohAEGA3wAoAgAhAQJ/QQEgB0EDdnQiBSAGcUUEQEHs3gAgBSAGcjYCACAADAELIAAoAggLIQUgACABNgIIIAUgATYCDCABIAA2AgwgASAFNgIIC0GA3wAgAzYCAEH03gAgBDYCAAsgAkEIaiEACyAKQRBqJAAgAAvXAQIFfwF8IwBBEGsiBiQAIAZBBGoiAhA/IwBBEGsiBSQAIAG7IQcCfyACLQALQQd2BEAgAigCBAwBCyACLQALQf8AcQshBANAAkACfyACLQALQQd2BEAgAigCAAwBCyACCyEDIAUgBzkDACACAn8gAyAEQQFqIAUQRiIDQQBOBEAgAyAETQ0CIAMMAQsgBEEBdEEBcgsiBBArDAELCyACIAMQKyAAIAIpAgA3AgAgACACKAIINgIIIAJCADcCACACQQA2AgggBUEQaiQAIAIQQSAGQRBqJAAL9gUBCH8jAEEgayIHJAAgB0EMaiEEAkAgB0EVaiIGIgIgB0EgaiIJRg0AIAFBAE4NACACQS06AAAgAkEBaiECQQAgAWshAQsgBAJ/IAkiAyACayIFQQlMBEBBPSAFQSAgAUEBcmdrQdEJbEEMdSIIIAhBAnRBwMoAaigCACABTWpIDQEaCwJ/IAFBv4Q9TQRAIAFBj84ATQRAIAFB4wBNBEAgAUEJTQRAIAIgAUEwajoAACACQQFqDAQLIAIgARAkDAMLIAFB5wdNBEAgAiABQeQAbiIDQTBqOgAAIAJBAWogASADQeQAbGsQJAwDCyACIAEQNQwCCyABQZ+NBk0EQCACIAFBkM4AbiIDQTBqOgAAIAJBAWogASADQZDOAGxrEDUMAgsgAiABEDQMAQsgAUH/wdcvTQRAIAFB/6ziBE0EQCACIAFBwIQ9biIDQTBqOgAAIAJBAWogASADQcCEPWxrEDQMAgsgAiABEDMMAQsgAUH/k+vcA00EQCACIAFBgMLXL24iA0EwajoAACACQQFqIAEgA0GAwtcvbGsQMwwBCyACIAFBgMLXL24iAxAkIAEgA0GAwtcvbGsQMwshA0EACzYCBCAEIAM2AgAgBygCDCEIIwBBEGsiAyQAIwBBEGsiBSQAIAAhAQJAIAggBiIAayIGQe////8HTQRAAkAgBkELSQRAIAEgAS0AC0GAAXEgBkH/AHFyOgALIAEgAS0AC0H/AHE6AAsgASEEDAELIAVBCGogASAGQQtPBH8gBkEQakFwcSIEIARBAWsiBCAEQQtGGwVBCgtBAWoQMCAFKAIMGiABIAUoAggiBDYCACABIAEoAghBgICAgHhxIAUoAgxB/////wdxcjYCCCABIAEoAghBgICAgHhyNgIIIAEgBjYCBAsDQCAAIAhHBEAgBCAALQAAOgAAIARBAWohBCAAQQFqIQAMAQsLIAVBADoAByAEIAUtAAc6AAAgBUEQaiQADAELECcACyADQRBqJAAgCSQACxYAIAIQHCEBIAAgAjYCBCAAIAE2AgALOAAgAC0AC0EHdgRAIAAgATYCBA8LIAAgAC0AC0GAAXEgAUH/AHFyOgALIAAgAC0AC0H/AHE6AAsL1QIBAn8CQCAAIAFGDQAgASAAIAJqIgRrQQAgAkEBdGtNBEAgACABIAIQIhoPCyAAIAFzQQNxIQMCQAJAIAAgAUkEQCADDQIgAEEDcUUNAQNAIAJFDQQgACABLQAAOgAAIAFBAWohASACQQFrIQIgAEEBaiIAQQNxDQALDAELAkAgAw0AIARBA3EEQANAIAJFDQUgACACQQFrIgJqIgMgASACai0AADoAACADQQNxDQALCyACQQNNDQADQCAAIAJBBGsiAmogASACaigCADYCACACQQNLDQALCyACRQ0CA0AgACACQQFrIgJqIAEgAmotAAA6AAAgAg0ACwwCCyACQQNNDQADQCAAIAEoAgA2AgAgAUEEaiEBIABBBGohACACQQRrIgJBA0sNAAsLIAJFDQADQCAAIAEtAAA6AAAgAEEBaiEAIAFBAWohASACQQFrIgINAAsLCxsAIAAgAUHAhD1uIgAQJCABIABBwIQ9bGsQNAsbACAAIAFBkM4AbiIAECQgASAAQZDOAGxrEDULGQAgACABQeQAbiIAECQgASAAQeQAbGsQJAu9BAMDfAN/An4CfAJAIAC9QjSIp0H/D3EiBUHJB2tBP0kEQCAFIQQMAQsgBUHJB0kEQCAARAAAAAAAAPA/oA8LIAVBiQhJDQBEAAAAAAAAAAAgAL0iB0KAgICAgICAeFENARogBUH/D08EQCAARAAAAAAAAPA/oA8LIAdCAFMEQCMAQRBrIgREAAAAAAAAABA5AwggBCsDCEQAAAAAAAAAEKIPCyMAQRBrIgREAAAAAAAAAHA5AwggBCsDCEQAAAAAAAAAcKIPC0HoNSsDACAAokHwNSsDACIBoCICIAGhIgFBgDYrAwCiIAFB+DUrAwCiIACgoCIBIAGiIgAgAKIgAUGgNisDAKJBmDYrAwCgoiAAIAFBkDYrAwCiQYg2KwMAoKIgAr0iB6dBBHRB8A9xIgVB2DZqKwMAIAGgoKAhASAFQeA2aikDACAHQi2GfCEIIARFBEACfCAHQoCAgIAIg1AEQCAIQoCAgICAgICIP32/IgAgAaIgAKBEAAAAAAAAAH+iDAELIAhCgICAgICAgPA/fL8iAiABoiIBIAKgIgNEAAAAAAAA8D9jBHwjAEEQayIEIQYgBEKAgICAgICACDcDCCAGIAQrAwhEAAAAAAAAEACiOQMIRAAAAAAAAAAAIANEAAAAAAAA8D+gIgAgASACIAOhoCADRAAAAAAAAPA/IAChoKCgRAAAAAAAAPC/oCIAIABEAAAAAAAAAABhGwUgAwtEAAAAAAAAEACiCw8LIAi/IgAgAaIgAKALCwgAQcIKEFIAC3AAQeDUAEEZNgIAQeTUAEEANgIAEFVB5NQAQZDVACgCADYCAEGQ1QBB4NQANgIAQZTVAEEaNgIAQZjVAEEANgIAEFFBmNUAQZDVACgCADYCAEGQ1QBBlNUANgIAQbTWAEG81QA2AgBB7NUAQSo2AgALCwAgABA6GiAAEBkLMgECfyAAQczSADYCACAAKAIEQQxrIgEgASgCCEEBayICNgIIIAJBAEgEQCABEBkLIAALmgEAIABBAToANQJAIAAoAgQgAkcNACAAQQE6ADQCQCAAKAIQIgJFBEAgAEEBNgIkIAAgAzYCGCAAIAE2AhAgA0EBRw0CIAAoAjBBAUYNAQwCCyABIAJGBEAgACgCGCICQQJGBEAgACADNgIYIAMhAgsgACgCMEEBRw0CIAJBAUYNAQwCCyAAIAAoAiRBAWo2AiQLIABBAToANgsLTAEBfwJAIAFFDQAgAUHczgAQICIBRQ0AIAEoAgggACgCCEF/c3ENACAAKAIMIAEoAgxBABAeRQ0AIAAoAhAgASgCEEEAEB4hAgsgAgtdAQF/IAAoAhAiA0UEQCAAQQE2AiQgACACNgIYIAAgATYCEA8LAkAgASADRgRAIAAoAhhBAkcNASAAIAI2AhgPCyAAQQE6ADYgAEECNgIYIAAgACgCJEEBajYCJAsLYwECfyMAQRBrIgIkACABIAAoAgQiA0EBdWohASAAKAIAIQAgAkEIaiABIANBAXEEfyABKAIAIABqKAIABSAACxEAACACKAIMIgAQAiACKAIMIgEEQCABEAMLIAJBEGokACAAC0MBAX8jAEEQayIBJAAgAEIANwIAIABBADYCCCABQRBqJAAgACAALQALQQd2BH8gACgCCEH/////B3FBAWsFQQoLECsLPQEBfyMAQRBrIgIkACACQQA6AA8DQCABBEAgACACLQAPOgAAIAFBAWshASAAQQFqIQAMAQsLIAJBEGokAAsaACAALQALQQd2BEAgACgCCBogACgCABAZCwvmAQEFfyMAQRBrIgUkACMAQSBrIgMkACMAQRBrIgQkACAEIAA2AgwgBCAAIAFqNgIIIAMgBCgCDDYCGCADIAQoAgg2AhwgBEEQaiQAIAMoAhghBCADKAIcIQYjAEEQayIBJAAgASAGNgIMIAIgBCAGIARrIgQQQyABIAIgBGo2AgggAyABKAIMNgIQIAMgASgCCDYCFCABQRBqJAAgAyAAIAMoAhAgAGtqNgIMIAMgAiADKAIUIAJrajYCCCAFIAMoAgw2AgggBSADKAIINgIMIANBIGokACAFKAIMIQcgBUEQaiQAIAcLDwAgAgRAIAAgASACEDILC/UCAQV/IwBBEGsiByQAIAIgAUF/c0Hv////B2pNBEACfyAALQALQQd2BEAgACgCAAwBCyAACyEIIAdBBGoiCSAAIAFB5////wNJBH8gByABQQF0NgIMIAcgASACajYCBCMAQRBrIgIkACAJKAIAIAdBDGoiCigCAEkhCyACQRBqJAAgCiAJIAsbKAIAIgJBC08EfyACQRBqQXBxIgIgAkEBayICIAJBC0YbBUEKC0EBagVB7////wcLEDAgBygCBCECIAcoAggaIAQEQCACIAggBBAjCyAFBEAgAiAEaiAGIAUQIwsgAyAEayEGIAMgBEcEQCACIARqIAVqIAQgCGogBhAjCyABQQpHBEAgCBAZCyAAIAI2AgAgACAAKAIIQYCAgIB4cSAHKAIIQf////8HcXI2AgggACAAKAIIQYCAgIB4cjYCCCAAIAQgBWogBmoiADYCBCAHQQA6AAwgACACaiAHLQAMOgAAIAdBEGokAA8LECcACwoAIAAgASACEEMLuQEBBH8jAEEQayIEJAAgBCACNgIMIwBBoAFrIgMkACADIAAgA0GeAWogARsiBjYClAFBfyEFIAMgAUEBayIAQQAgACABTRs2ApgBIANBAEGQARAmIgBBfzYCTCAAQSA2AiQgAEF/NgJQIAAgAEGfAWo2AiwgACAAQZQBajYCVAJAIAFBAEgEQEHo3gBBPTYCAAwBCyAGQQA6AAAgAEH9CiACQR8QTSEFCyAAQaABaiQAIARBEGokACAFCwQA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KAIARQ0AIAIgBCgCGDYCAAsgAEEBRiEFDAELQQAhBQsgBEFAayQAIAULMQAgACABKAIIQQAQHgRAIAEgAiADED0PCyAAKAIIIgAgASACIAMgACgCACgCHBEGAAsYACAAIAEoAghBABAeBEAgASACIAMQPQsLnQEBAn8jAEFAaiIDJAACf0EBIAAgAUEAEB4NABpBACABRQ0AGkEAIAFBjM0AECAiAUUNABogA0EMakEAQTQQJhogA0EBNgI4IANBfzYCFCADIAA2AhAgAyABNgIIIAEgA0EIaiACKAIAQQEgASgCACgCHBEGACADKAIgIgBBAUYEQCACIAMoAhg2AgALIABBAUYLIQQgA0FAayQAIAQLCgAgACABQQAQHgtOAgF/AXwjAEEQayICJAAgAkEANgIMIAEoAgRB1M8AIAJBDGoQCSEDIAIoAgwiAQRAIAEQAQsgACADRAAAAAAAAAAAYjoAOCACQRBqJAALNwEBfyMAQRBrIgIkACACIAEtADg2AgggAEHUzwAgAkEIahAHNgIEIABB1NUANgIAIAJBEGokAAuoAQEFfyAAKAJUIgMoAgAhBSADKAIEIgQgACgCFCAAKAIcIgdrIgYgBCAGSRsiBgRAIAUgByAGECIaIAMgAygCACAGaiIFNgIAIAMgAygCBCAGayIENgIECyAEIAIgAiAESxsiBARAIAUgASAEECIaIAMgAygCACAEaiIFNgIAIAMgAygCBCAEazYCBAsgBUEAOgAAIAAgACgCLCIBNgIcIAAgATYCFCACC5wBAQJ/IwBBEGsiAiQAQcgAEBwhASAAKAIEIgAQAiACIAA2AgggAUHMLSACQQhqEAc2AgQgAUHU1QA2AgAgAUEBNgIcIAFB1NUANgIYIAFBATYCFCABQdTVADYCECABQQE2AgwgAUHU1QA2AgggAUEAOgAgIAFBADYCRCABQoCAgIAwNwI8IAFBADsANyABQQA7ACsgAkEQaiQAIAELigUCBn4CfyABIAEoAgBBB2pBeHEiAUEQajYCACAAIQkgASkDACEDIAEpAwghBSMAQSBrIgAkAAJAIAVC////////////AIMiBEKAgICAgIDAgDx9IARCgICAgICAwP/DAH1UBEAgBUIEhiADQjyIhCEEIANC//////////8PgyIDQoGAgICAgICACFoEQCAEQoGAgICAgICAwAB8IQIMAgsgBEKAgICAgICAgEB9IQIgA0KAgICAgICAgAhSDQEgAiAEQgGDfCECDAELIANQIARCgICAgICAwP//AFQgBEKAgICAgIDA//8AURtFBEAgBUIEhiADQjyIhEL/////////A4NCgICAgICAgPz/AIQhAgwBC0KAgICAgICA+P8AIQIgBEL///////+//8MAVg0AQgAhAiAEQjCIpyIBQZH3AEkNACADIQIgBUL///////8/g0KAgICAgIDAAIQiBCEGAkAgAUGB9wBrIghBwABxBEAgAyAIQUBqrYYhBkIAIQIMAQsgCEUNACAGIAitIgeGIAJBwAAgCGutiIQhBiACIAeGIQILIAAgAjcDECAAIAY3AxgCQEGB+AAgAWsiAUHAAHEEQCAEIAFBQGqtiCEDQgAhBAwBCyABRQ0AIARBwAAgAWuthiADIAGtIgKIhCEDIAQgAoghBAsgACADNwMAIAAgBDcDCCAAKQMIQgSGIAApAwAiA0I8iIQhAiAAKQMQIAApAxiEQgBSrSADQv//////////D4OEIgNCgYCAgICAgIAIWgRAIAJCAXwhAgwBCyADQoCAgICAgICACFINACACQgGDIAJ8IQILIABBIGokACAJIAIgBUKAgICAgICAgIB/g4S/OQMAC0ABAn8jAEEQayICJAAgAiABNgIMIAJB1NUANgIIIAJBCGogABEBACEDIAIoAgwiAQRAIAEQAwsgAkEQaiQAIAMLBABCAAsEAEEAC/YCAQh/IwBBIGsiAyQAIAMgACgCHCIENgIQIAAoAhQhBSADIAI2AhwgAyABNgIYIAMgBSAEayIBNgIUIAEgAmohBUECIQcCfwJAAkACQCAAKAI8IANBEGoiAUECIANBDGoQDSIEBH9B6N4AIAQ2AgBBfwVBAAsEQCABIQQMAQsDQCAFIAMoAgwiBkYNAiAGQQBIBEAgASEEDAQLIAEgBiABKAIEIghLIglBA3RqIgQgBiAIQQAgCRtrIgggBCgCAGo2AgAgAUEMQQQgCRtqIgEgASgCACAIazYCACAFIAZrIQUgACgCPCAEIgEgByAJayIHIANBDGoQDSIGBH9B6N4AIAY2AgBBfwVBAAtFDQALCyAFQX9HDQELIAAgACgCLCIBNgIcIAAgATYCFCAAIAEgACgCMGo2AhAgAgwBCyAAQQA2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EGokAAsiAQF+IAEgAq0gA61CIIaEIAQgABEMACIFQiCIpyQBIAWnCzcBAX8jAEEQayICJAAgAiABKAI8NgIIIABBnNAAIAJBCGoQBzYCBCAAQdTVADYCACACQRBqJAALC/NKFQBBgAgLhCZzZXRCZWF1dHkALSsgICAwWDB4AC0wWCswWCAwWC0weCsweCAweAB1bnNpZ25lZCBzaG9ydAB1bnNpZ25lZCBpbnQAaW5pdABmbG9hdAB1aW50NjRfdABibHVyUmFkaXVzAHZlY3RvcgBtaXJyb3IAYXR0YWNoU2hhZGVyAGRlbGV0ZVNoYWRlcgBjcmVhdGVTaGFkZXIAY29tcGlsZVNoYWRlcgB1bnNpZ25lZCBjaGFyAHN0ZDo6ZXhjZXB0aW9uAHJvdGF0aW9uAG5hbgBsaW5rUHJvZ3JhbQBkZWxldGVQcm9ncmFtAGNyZWF0ZVByb2dyYW0AYm9vbABlbXNjcmlwdGVuOjp2YWwAc2V0V2F0ZXJNYXJrAHN0b3BXYXRlck1hcmsAdW5zaWduZWQgbG9uZwBzdGQ6OndzdHJpbmcAYmFzaWNfc3RyaW5nAHN0ZDo6c3RyaW5nAHN0ZDo6dTE2c3RyaW5nAHN0ZDo6dTMyc3RyaW5nAGluZgAlZgBjbG9zZQBkb3VibGUAdmJNb2RlAHNoYWRlclNvdXJjZQB2b2lkAHNhbXBsZUNvbG9yICs9IHRleHR1cmUoZnJhbWUsIGJsdXJDb29yZGluYXRlc1sATkFOAElORgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxzaG9ydD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgc2hvcnQ+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGludD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgaW50PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxmbG9hdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dWludDhfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50OF90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1aW50MTZfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50MTZfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dWludDY0X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGludDY0X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PHVpbnQzMl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxpbnQzMl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxjaGFyPgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1bnNpZ25lZCBjaGFyPgBzdGQ6OmJhc2ljX3N0cmluZzx1bnNpZ25lZCBjaGFyPgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxzaWduZWQgY2hhcj4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8bG9uZz4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgbG9uZz4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8ZG91YmxlPgB2ZWMyIGMgPSB2X3RleENvb3JkOwB2ZWMyIGMgPSB2ZWMyKDEuMCAtIHZfdGV4Q29vcmQueCwgdl90ZXhDb29yZC55KTsAYyA9IHZlYzIoMS4wIC0gYy54LCAxLjAgLSBjLnkpOwBjID0gdmVjMihjLnksIDEuMCAtIGMueCk7AGMgPSB2ZWMyKDEuMCAtIGMueSwgYy54KTsAQWxsSW4xAC4ALjAsAC4wKSpvKSoAKG51bGwpACkqby55KTsgICAgdmVjMiBjb29yZDIgPSB2ZWMyKGZsb2F0KAAgICAgYyA9IHZlYzIodl90ZXhDb29yZC54LCAxLjAgLSB2X3RleENvb3JkLnkpOyAgICB2ZWMyIGNvb3JkMSA9IHZlYzIoZmxvYXQoACksIChjLnkgLWNvb3JkMS55KSAvIG8ueSAvIGZsb2F0KAApKm8ueSk7ICAgIGlmIChjLnggPiBjb29yZDEueCAmJiBjLnggPCBjb29yZDIueCAmJiBjLnkgPiBjb29yZDEueSAmJiBjLnkgPCBjb29yZDIueSkgeyAgICAgIHZlYzQgd2F0ZXJDb2xvciA9IHRleHR1cmUod2F0ZXJNYXJrLCB2ZWMyKChjLnggLSBjb29yZDEueCkgIC8gby54IC8gZmxvYXQoACkgKiBvLngsIGZsb2F0KABvdXRDb2xvci5yZ2IgKz0gdmVjMygAKTsgICAgICAgdmVjMyBzbW9vdGhDb2xvciA9IG91dENvbG9yLnJnYiArIChvdXRDb2xvci5yZ2ItdmVjMyhoaWdoUGFzcykpKmFscGhhKjAuMTsgICAgICAgc21vb3RoQ29sb3IgPSBtYXgoc21vb3RoQ29sb3IsIHZlYzMoMC4wKSk7ICAgICAgIHNtb290aENvbG9yID0gY2xhbXAocG93KHNtb290aENvbG9yLCB2ZWMzKABnKz1HKGMsdmVjMigAICAgICAgdmVjMiBvZmZzZXQgPSB2ZWMyKABdID0gdl90ZXhDb29yZC54eSArIG9mZnNldCAqIHZlYzIoADsgACkpLCB2ZWMzKDAuMCksIHZlYzMoMS4wKSk7ICAgICAgdmVjMyBzY3JlZW4gPSB2ZWMzKDEuMCkgLSAodmVjMygxLjApLXNtb290aENvbG9yKSAqICh2ZWMzKDEuMCktb3V0Q29sb3IucmdiKTsgICAgICAgdmVjMyBsaWdodGVuID0gbWF4KHNtb290aENvbG9yLCBvdXRDb2xvci5yZ2IpOyAgICAgICB2ZWMzIGJlYXV0eUNvbG9yID0gbWl4KG1peChvdXRDb2xvci5yZ2IsIHNjcmVlbiwgYWxwaGEpLCBsaWdodGVuLCBhbHBoYSk7ICAgICAgb3V0Q29sb3IucmdiID0gbWl4KG91dENvbG9yLnJnYiwgYmVhdXR5Q29sb3IsIAAKICAgICAgY29uc3QgbWF0MyBzYXR1cmF0ZU1hdHJpeCA9IG1hdDMoMS4xMTAyLC0wLjA1OTgsLTAuMDYxLC0wLjA3NzQsMS4wODI2LC0wLjExODYsLTAuMDIyOCwtMC4wMjI4LDEuMTc3Mik7CiAgICAgIHZlYzMgd2FybUNvbG9yID0gb3V0Q29sb3IucmdiICogc2F0dXJhdGVNYXRyaXg7CiAgICAgIG91dENvbG9yLnJnYiA9IG1peChvdXRDb2xvci5yZ2IsIHdhcm1Db2xvciwgACAgICAgIHNhbXBsZUNvbG9yID0gc2FtcGxlQ29sb3IgLyA2Mi4wOyAgICAgICBmbG9hdCBoaWdoUGFzcyA9IG91dENvbG9yLmcgLSBzYW1wbGVDb2xvciArIDAuNTsgICAgICAgY29uc3QgaGlnaHAgdmVjMyBXID0gdmVjMygwLjI5OSwwLjU4NywwLjExNCk7ICAgICAgZmxvYXQgbHVtaW5hbmNlID0gZG90KG91dENvbG9yLnJnYiwgVyk7ICAgICAgIGZsb2F0IGFscGhhID0gcG93KGx1bWluYW5jZSwgAF0pLmcgKiAAKSkpOyAgICAgIG91dENvbG9yID0gbWl4KG91dENvbG9yLHdhdGVyQ29sb3IsICB3YXRlckNvbG9yLmEpOyAgICB9ICAgIAApOyAgICAAKTsgICAgICB2ZWMyIGJsdXJDb29yZGluYXRlc1syNF07ICAgICAgACAgICAgIGZsb2F0IHNhbXBsZUNvbG9yID0gb3V0Q29sb3IuZyAqIDIyLjA7ICAgICAgIAAjdmVyc2lvbiAzMDAgZXMKICAgIHByZWNpc2lvbiBoaWdocCBmbG9hdDsKICAgIHVuaWZvcm0gc2FtcGxlcjJEIGZyYW1lOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgbWFzazsKICAgIHVuaWZvcm0gc2FtcGxlcjJEIGJnOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgd2F0ZXJNYXJrOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgbGFzdE1hc2s7CiAgICB1bmlmb3JtIG1hdDQgdV9vZmZzZXRNYXRyaXg7CiAgICB1bmlmb3JtIHZlYzMgdV9jb2xvcjsKICAgIGluIHZlYzIgdl90ZXhDb29yZDsKICAgIG91dCB2ZWM0IG91dENvbG9yOwogICAgdmVjNCBHKHZlYzIgYyx2ZWMyIHMpewogICAgICByZXR1cm4gdGV4dHVyZShmcmFtZSx0ZXh0dXJlKG1hc2ssYytzKS5yPjAuMz9jOmMrcyk7CiAgICB9CiAgICB2b2lkIG1haW4oKSB7CiAgICAgIAAKICAgICAgdmVjMiBvZmZzZXRNYXNrVVYgPSAodV9vZmZzZXRNYXRyaXggKiB2ZWM0KGMsIDAsIDEpKS54eTsKICAgICAgZmxvYXQgaXNJbnNpZGVYID0gKG9mZnNldE1hc2tVVi54ID49IDAuMCkgJiYgKG9mZnNldE1hc2tVVi54IDw9IDEuMCkgPyAxLjAgOiAwLjA7CiAgICAgIGZsb2F0IGlzSW5zaWRlWSA9IChvZmZzZXRNYXNrVVYueSA+PSAwLjApICYmIChvZmZzZXRNYXNrVVYueSA8PSAxLjApID8gMS4wIDogMC4wOwogICAgICBmbG9hdCBpc0luc2lkZSA9IGlzSW5zaWRlWCAqIGlzSW5zaWRlWTsKICAgICAgZmxvYXQgbWFza2VkQWxwaGEgPSB0ZXh0dXJlKG1hc2ssIG9mZnNldE1hc2tVVikuciAqIGlzSW5zaWRlOwogICAgICBtYXNrZWRBbHBoYSA9IG1hc2tlZEFscGhhPDAuNT8yLjAqbWFza2VkQWxwaGEqbWFza2VkQWxwaGE6MS4wLTIuMCooMS4wLW1hc2tlZEFscGhhKSooMS4wLW1hc2tlZEFscGhhKTsKICAgICAgc3JjX2NvbG9yID0gdGV4dHVyZShmcmFtZSwgb2Zmc2V0TWFza1VWICwgaXNJbnNpZGUpOwogICAgICBvdXRDb2xvciA9IG1peCh0ZXh0dXJlKGJnLCBjKSwgc3JjX2NvbG9yLCBtYXNrZWRBbHBoYSk7CiAgICAACiAgICB2ZWM0IGcgPSB2ZWM0KDAuMCk7CiAgICAACiAgICAgIGMueSA9IDEuMCAtIGMueTsKICAgICAgdmVjNCBzcmNfY29sb3IgPSB0ZXh0dXJlKGZyYW1lLCBjKTsKICAgICAgZmxvYXQgYSA9IHRleHR1cmUobWFzaywgYykucjsKICAgICAgYSA9IGE8MC41PzIuMCphKmE6MS4wLTIuMCooMS4wLWEpKigxLjAtYSk7CiAgICAgIC8vIGZsb2F0IGEyID0gdGV4dHVyZShsYXN0TWFzaywgYykuYTsKICAgICAgLy8gYTIgPSBhMjwwLjU/Mi4wKmEyKmEyOjEuMC0yLjAqKDEuMC1hMikqKDEuMC1hMik7CiAgICAgIC8vIGZsb2F0IGRlbHRhID0gYSAtIGEyOwogICAgICAvLyBpZiAoZGVsdGEgPCAwLjI1ICYmIGRlbHRhID4gLTAuMjUpCiAgICAgIC8vIHsKICAgICAgLy8gICAgIGEgPSBhICsgMC41KmRlbHRhOwogICAgICAvLyB9CiAgICAgIAogICAgICB2ZWMyIG8gPSAxLjAgLyB2ZWMyKHRleHR1cmVTaXplKGZyYW1lLCAwKSk7CiAgICAACiAgICAgIG91dENvbG9yID0gZzsKICAAI3ZlcnNpb24gMzAwIGVzCmluIHZlYzIgYV9wb3NpdGlvbjsKaW4gdmVjMiBhX3RleENvb3JkOwoKdW5pZm9ybSBtYXQ0IHVfdGV4dHVyZU1hdHJpeDsKCm91dCB2ZWMyIHZfdGV4Q29vcmQ7CnZvaWQgbWFpbigpIHsKICBnbF9Qb3NpdGlvbiA9IHZlYzQoYV9wb3NpdGlvbi54LCBhX3Bvc2l0aW9uLnksIDAsIDEpOwogIHZfdGV4Q29vcmQgPSh1X3RleHR1cmVNYXRyaXggKiB2ZWM0KGFfdGV4Q29vcmQsIDAsIDEpKS54eTsKfQoAc2V0QmVhdXR5ICVmICVmICVmICVmICVmCgBvdXRDb2xvciA9IHNyY19jb2xvcjsKAG91dENvbG9yID0gbWl4KHZlYzQodV9jb2xvciwxLjApLHNyY19jb2xvcixhKTsKADZBbGxJbjEAAIAoAABfFgAAUDZBbGxJbjEAAAAABCkAAHAWAAAAAAAAaBYAAFBLNkFsbEluMQAAAAQpAACMFgAAAQAAAGgWAABpaQB2AHZpAHwWAADMFgAATjEwZW1zY3JpcHRlbjN2YWxFAACAKAAAuBYAAGlpaQB2aWlpAAAAALwnAAB8FgAAcCgAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkZABBkC4LyAi8JwAAfBYAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkALwnAAB8FgAAdmlpALwnAADMFgAAzBYAAHwWAADMFgAAHCgAALwnAADMFgAAoBcAAE5TdDNfXzIxMmJhc2ljX3N0cmluZ0ljTlNfMTFjaGFyX3RyYWl0c0ljRUVOU185YWxsb2NhdG9ySWNFRUVFAACAKAAAYBcAAMwWAAC8JwAAzBYAAMwWAABOU3QzX18yMTJiYXNpY19zdHJpbmdJaE5TXzExY2hhcl90cmFpdHNJaEVFTlNfOWFsbG9jYXRvckloRUVFRQAAgCgAALgXAABOU3QzX18yMTJiYXNpY19zdHJpbmdJd05TXzExY2hhcl90cmFpdHNJd0VFTlNfOWFsbG9jYXRvckl3RUVFRQAAgCgAAAAYAABOU3QzX18yMTJiYXNpY19zdHJpbmdJRHNOU18xMWNoYXJfdHJhaXRzSURzRUVOU185YWxsb2NhdG9ySURzRUVFRQAAAIAoAABIGAAATlN0M19fMjEyYmFzaWNfc3RyaW5nSURpTlNfMTFj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")||(Je=ae,ae=I.locateFile?I.locateFile(Je,m):m+Je);var ki=$=>{for(;$.length>0;)$.shift()(I)};I.noExitRuntime;function ao($){this.excPtr=$,this.ptr=$-24,this.set_type=function(j){vA[this.ptr+4>>2]=j},this.get_type=function(){return vA[this.ptr+4>>2]},this.set_destructor=function(j){vA[this.ptr+8>>2]=j},this.get_destructor=function(){return vA[this.ptr+8>>2]},this.set_caught=function(j){j=j?1:0,cA[this.ptr+12|0]=j},this.get_caught=function(){return cA[this.ptr+12|0]!=0},this.set_rethrown=function(j){j=j?1:0,cA[this.ptr+13|0]=j},this.get_rethrown=function(){return cA[this.ptr+13|0]!=0},this.init=function(j,RA){this.set_adjusted_ptr(0),this.set_type(j),this.set_destructor(RA)},this.set_adjusted_ptr=function(j){vA[this.ptr+16>>2]=j},this.get_adjusted_ptr=function(){return vA[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Oa(this.get_type()))return vA[this.excPtr>>2];var j=this.get_adjusted_ptr();return j!==0?j:this.excPtr}}var Ji,Vi,wn,Fi=$=>{for(var j="",RA=$;eA[RA];)j+=Ji[eA[RA++]];return j},en={},Ro={},oo={},Ai=$=>{throw new Vi($)},no=$=>{throw new wn($)},Ri=($,j,RA)=>{function ZA(qe){var Et=RA(qe);Et.length!==$.length&&no("Mismatched type converter count");for(var ft=0;ft<$.length;++ft)pn($[ft],Et[ft])}$.forEach(function(qe){oo[qe]=j});var ne=new Array(j.length),De=[],Ke=0;j.forEach((qe,Et)=>{Ro.hasOwnProperty(qe)?ne[Et]=Ro[qe]:(De.push(qe),en.hasOwnProperty(qe)||(en[qe]=[]),en[qe].push(()=>{ne[Et]=Ro[qe],++Ke===De.length&&ZA(ne)}))}),De.length===0&&ZA(ne)};function pn($,j,RA={}){if(!("argPackAdvance"in j))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(ZA,ne,De={}){var Ke=ne.name;if(ZA||Ai(`type "${Ke}" must have a positive integer typeid pointer`),Ro.hasOwnProperty(ZA)){if(De.ignoreDuplicateRegistrations)return;Ai(`Cannot register type '${Ke}' twice`)}if(Ro[ZA]=ne,delete oo[ZA],en.hasOwnProperty(ZA)){var qe=en[ZA];delete en[ZA],qe.forEach(Et=>Et())}}($,j,RA)}var jA,ue=$=>{Ai($.$$.ptrType.registeredClass.name+" instance already deleted")},He=!1,Lt=$=>{},ct=$=>{$.count.value-=1,$.count.value===0&&(j=>{j.smartPtr?j.smartPtrType.rawDestructor(j.smartPtr):j.ptrType.registeredClass.rawDestructor(j.ptr)})($)},Ct=($,j,RA)=>{if(j===RA)return $;if(RA.baseClass===void 0)return null;var ZA=Ct($,j,RA.baseClass);return ZA===null?null:RA.downcast(ZA)},ei={},Ht=()=>Object.keys(Hi).length,Le=()=>{var $=[];for(var j in Hi)Hi.hasOwnProperty(j)&&$.push(Hi[j]);return $},it=[],Tt=()=>{for(;it.length;){var $=it.pop();$.$$.deleteScheduled=!1,$.delete()}},Gt=$=>{jA=$,it.length&&jA&&jA(Tt)},Hi={},po=($,j)=>(j=((RA,ZA)=>{for(ZA===void 0&&Ai("ptr should not be undefined");RA.baseClass;)ZA=RA.upcast(ZA),RA=RA.baseClass;return ZA})($,j),Hi[j]),To=($,j)=>(j.ptrType&&j.ptr||no("makeClassHandle requires ptr and ptrType"),!!j.smartPtrType!=!!j.smartPtr&&no("Both smartPtrType and smartPtr must be specified"),j.count={value:1},wo(Object.create($,{$$:{value:j}})));function Zi($){var j=this.getPointee($);if(!j)return this.destructor($),null;var RA=po(this.registeredClass,j);if(RA!==void 0){if(RA.$$.count.value===0)return RA.$$.ptr=j,RA.$$.smartPtr=$,RA.clone();var ZA=RA.clone();return this.destructor($),ZA}function ne(){return this.isSmartPointer?To(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:j,smartPtrType:this,smartPtr:$}):To(this.registeredClass.instancePrototype,{ptrType:this,ptr:$})}var De,Ke=this.registeredClass.getActualType(j),qe=ei[Ke];if(!qe)return ne.call(this);De=this.isConst?qe.constPointerType:qe.pointerType;var Et=Ct(j,this.registeredClass,De.registeredClass);return Et===null?ne.call(this):this.isSmartPointer?To(De.registeredClass.instancePrototype,{ptrType:De,ptr:Et,smartPtrType:this,smartPtr:$}):To(De.registeredClass.instancePrototype,{ptrType:De,ptr:Et})}var wo=$=>typeof FinalizationRegistry>"u"?(wo=j=>j,$):(He=new FinalizationRegistry(j=>{ct(j.$$)}),Lt=j=>He.unregister(j),(wo=j=>{var RA=j.$$;if(RA.smartPtr){var ZA={$$:RA};He.register(j,ZA,j)}return j})($));function Cn(){}var an=($,j)=>Object.defineProperty(j,"name",{value:$}),Vo=($,j,RA)=>{if($[j].overloadTable===void 0){var ZA=$[j];$[j]=function(){return $[j].overloadTable.hasOwnProperty(arguments.length)||Ai(`Function '${RA}' called with an invalid number of arguments (${arguments.length}) - expects one of (${$[j].overloadTable})!`),$[j].overloadTable[arguments.length].apply(this,arguments)},$[j].overloadTable=[],$[j].overloadTable[ZA.argCount]=ZA}};function jn($,j,RA,ZA,ne,De,Ke,qe){this.name=$,this.constructor=j,this.instancePrototype=RA,this.rawDestructor=ZA,this.baseClass=ne,this.getActualType=De,this.upcast=Ke,this.downcast=qe,this.pureVirtualFunctions=[]}var vo=($,j,RA)=>{for(;j!==RA;)j.upcast||Ai(`Expected null or instance of ${RA.name}, got an instance of ${j.name}`),$=j.upcast($),j=j.baseClass;return $};function mA($,j){if(j===null)return this.isReference&&Ai(`null is not a valid ${this.name}`),0;j.$$||Ai(`Cannot pass "${ce(j)}" as a ${this.name}`),j.$$.ptr||Ai(`Cannot pass deleted object as a pointer of type ${this.name}`);var RA=j.$$.ptrType.registeredClass;return vo(j.$$.ptr,RA,this.registeredClass)}function xs($,j){var RA;if(j===null)return this.isReference&&Ai(`null is not a valid ${this.name}`),this.isSmartPointer?(RA=this.rawConstructor(),$!==null&&$.push(this.rawDestructor,RA),RA):0;j.$$||Ai(`Cannot pass "${ce(j)}" as a ${this.name}`),j.$$.ptr||Ai(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&j.$$.ptrType.isConst&&Ai(`Cannot convert argument of type ${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type ${this.name}`);var ZA=j.$$.ptrType.registeredClass;if(RA=vo(j.$$.ptr,ZA,this.registeredClass),this.isSmartPointer)switch(j.$$.smartPtr===void 0&&Ai("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:j.$$.smartPtrType===this?RA=j.$$.smartPtr:Ai(`Cannot convert argument of type ${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:RA=j.$$.smartPtr;break;case 2:if(j.$$.smartPtrType===this)RA=j.$$.smartPtr;else{var ne=j.clone();RA=this.rawShare(RA,ts.toHandle(()=>ne.delete())),$!==null&&$.push(this.rawDestructor,RA)}break;default:Ai("Unsupporting sharing policy")}return RA}function Zs($,j){if(j===null)return this.isReference&&Ai(`null is not a valid ${this.name}`),0;j.$$||Ai(`Cannot pass "${ce(j)}" as a ${this.name}`),j.$$.ptr||Ai(`Cannot pass deleted object as a pointer of type ${this.name}`),j.$$.ptrType.isConst&&Ai(`Cannot convert argument of type ${j.$$.ptrType.name} to parameter type ${this.name}`);var RA=j.$$.ptrType.registeredClass;return vo(j.$$.ptr,RA,this.registeredClass)}function mn($){return this.fromWireType(vA[$>>2])}function Fr($,j,RA,ZA,ne,De,Ke,qe,Et,ft,Nt){this.name=$,this.registeredClass=j,this.isReference=RA,this.isConst=ZA,this.isSmartPointer=ne,this.pointeeType=De,this.sharingPolicy=Ke,this.rawGetPointee=qe,this.rawConstructor=Et,this.rawShare=ft,this.rawDestructor=Nt,ne||j.baseClass!==void 0?this.toWireType=xs:ZA?(this.toWireType=mA,this.destructorFunction=null):(this.toWireType=Zs,this.destructorFunction=null)}var qi,tn,Ks=[],_n=$=>{var j=Ks[$];return j||($>=Ks.length&&(Ks.length=$+1),Ks[$]=j=qi.get($)),j},Is=($,j,RA)=>$.includes("j")?((ZA,ne,De)=>{var Ke=I["dynCall_"+ZA];return De&&De.length?Ke.apply(null,[ne].concat(De)):Ke.call(null,ne)})($,j,RA):_n(j).apply(null,RA),qt=($,j)=>{var RA,ZA,ne,De=($=Fi($)).includes("j")?(RA=$,ZA=j,ne=[],function(){return ne.length=0,Object.assign(ne,arguments),Is(RA,ZA,ne)}):_n(j);return typeof De!="function"&&Ai(`unknown function pointer with signature ${$}: ${j}`),De},$a=$=>{var j=pa($),RA=Fi(j);return _s(j),RA},Ls=($,j)=>{var RA=[],ZA={};throw j.forEach(function ne(De){ZA[De]||Ro[De]||(oo[De]?oo[De].forEach(ne):(RA.push(De),ZA[De]=!0))}),new tn(`${$}: `+RA.map($a).join([", "]))},Bs=($,j)=>{for(var RA=[],ZA=0;ZA<$;ZA++)RA.push(vA[j+4*ZA>>2]);return RA},Un=$=>{for(;$.length;){var j=$.pop();$.pop()(j)}};function Ir($,j,RA,ZA,ne,De){var Ke=j.length;Ke<2&&Ai("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var qe=j[1]!==null&&RA!==null,Et=!1,ft=1;ft($ instanceof Object||Ai(`${RA} with invalid "this": ${$}`),$ instanceof j.registeredClass.constructor||Ai(`${RA} incompatible with "this" of type ${$.constructor.name}`),$.$$.ptr||Ai(`cannot call emscripten binding method ${RA} on deleted object`),vo($.$$.ptr,$.$$.ptrType.registeredClass,j.registeredClass));function rr(){this.allocated=[void 0],this.freelist=[]}var fo=new rr,es=$=>{$>=fo.reserved&&--fo.get($).refcount===0&&fo.free($)},vc=()=>{for(var $=0,j=fo.reserved;j($||Ai("Cannot use deleted val. handle = "+$),fo.get($).value),toHandle:$=>{switch($){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return fo.allocate({refcount:1,value:$})}}};function ur($){return this.fromWireType(oA[$>>2])}var On,vg,yn,ce=$=>{if($===null)return"null";var j=typeof $;return j==="object"||j==="array"||j==="function"?$.toString():""+$},ot=($,j)=>{switch(j){case 4:return function(RA){return this.fromWireType(qA[RA>>2])};case 8:return function(RA){return this.fromWireType(Ae[RA>>3])};default:throw new TypeError(`invalid float width (${j}): ${$}`)}},Zt=($,j,RA)=>{switch(j){case 1:return RA?ZA=>cA[ZA|0]:ZA=>eA[ZA|0];case 2:return RA?ZA=>CA[ZA>>1]:ZA=>IA[ZA>>1];case 4:return RA?ZA=>oA[ZA>>2]:ZA=>vA[ZA>>2];default:throw new TypeError(`invalid integer width (${j}): ${$}`)}},Ho=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ba=($,j,RA)=>{for(var ZA=j+RA,ne=j;$[ne]&&!(ne>=ZA);)++ne;if(ne-j>16&&$.buffer&&Ho)return Ho.decode($.subarray(j,ne));for(var De="";j>10,56320|1023&ft)}}else De+=String.fromCharCode((31&Ke)<<6|qe)}else De+=String.fromCharCode(Ke)}return De},WI=($,j)=>$?Ba(eA,$,j):"",gn=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,ro=($,j)=>{for(var RA=$,ZA=RA>>1,ne=ZA+j/2;!(ZA>=ne)&&IA[ZA];)++ZA;if((RA=ZA<<1)-$>32&&gn)return gn.decode(eA.subarray($,RA));for(var De="",Ke=0;!(Ke>=j/2);++Ke){var qe=CA[$+2*Ke>>1];if(qe==0)break;De+=String.fromCharCode(qe)}return De},Mc=($,j,RA)=>{if(RA===void 0&&(RA=2147483647),RA<2)return 0;for(var ZA=j,ne=(RA-=2)<2*$.length?RA/2:$.length,De=0;De>1]=Ke,j+=2}return CA[j>>1]=0,j-ZA},gg=$=>2*$.length,Mg=($,j)=>{for(var RA=0,ZA="";!(RA>=j/4);){var ne=oA[$+4*RA>>2];if(ne==0)break;if(++RA,ne>=65536){var De=ne-65536;ZA+=String.fromCharCode(55296|De>>10,56320|1023&De)}else ZA+=String.fromCharCode(ne)}return ZA},Qa=($,j,RA)=>{if(RA===void 0&&(RA=2147483647),RA<4)return 0;for(var ZA=j,ne=ZA+RA-4,De=0;De<$.length;++De){var Ke=$.charCodeAt(De);if(Ke>=55296&&Ke<=57343&&(Ke=65536+((1023&Ke)<<10)|1023&$.charCodeAt(++De)),oA[j>>2]=Ke,(j+=4)+4>ne)break}return oA[j>>2]=0,j-ZA},Fo=$=>{for(var j=0,RA=0;RA<$.length;++RA){var ZA=$.charCodeAt(RA);ZA>=55296&&ZA<=57343&&++RA,j+=4}return j},Aa=($,j)=>{var RA=Ro[$];return RA===void 0&&Ai(j+" has unknown type "+$a($)),RA},Uo=($,j,RA)=>{var ZA=[],ne=$.toWireType(ZA,RA);return ZA.length&&(vA[j>>2]=ts.toHandle(ZA)),ne},Zc={},Xs=[],is=Reflect.construct,Rg=[null,[],[]],Rc=($,j)=>{var RA=Rg[$];j===0||j===10?(($===1?T:b)(Ba(RA,0)),RA.length=0):RA.push(j)};(()=>{for(var $=new Array(256),j=0;j<256;++j)$[j]=String.fromCharCode(j);Ji=$})(),Vi=I.BindingError=class extends Error{constructor($){super($),this.name="BindingError"}},wn=I.InternalError=class extends Error{constructor($){super($),this.name="InternalError"}},Object.assign(Cn.prototype,{isAliasOf($){if(!(this instanceof Cn)||!($ instanceof Cn))return!1;var j=this.$$.ptrType.registeredClass,RA=this.$$.ptr;$.$$=$.$$;for(var ZA=$.$$.ptrType.registeredClass,ne=$.$$.ptr;j.baseClass;)RA=j.upcast(RA),j=j.baseClass;for(;ZA.baseClass;)ne=ZA.upcast(ne),ZA=ZA.baseClass;return j===ZA&&RA===ne},clone(){if(this.$$.ptr||ue(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var $,j=wo(Object.create(Object.getPrototypeOf(this),{$$:{value:($=this.$$,{count:$.count,deleteScheduled:$.deleteScheduled,preservePointerOnDelete:$.preservePointerOnDelete,ptr:$.ptr,ptrType:$.ptrType,smartPtr:$.smartPtr,smartPtrType:$.smartPtrType})}}));return j.$$.count.value+=1,j.$$.deleteScheduled=!1,j},delete(){this.$$.ptr||ue(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ai("Object already scheduled for deletion"),Lt(this),ct(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||ue(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ai("Object already scheduled for deletion"),it.push(this),it.length===1&&jA&&jA(Tt),this.$$.deleteScheduled=!0,this}}),I.getInheritedInstanceCount=Ht,I.getLiveInheritedInstances=Le,I.flushPendingDeletes=Tt,I.setDelayFunction=Gt,Object.assign(Fr.prototype,{getPointee($){return this.rawGetPointee&&($=this.rawGetPointee($)),$},destructor($){this.rawDestructor&&this.rawDestructor($)},argPackAdvance:8,readValueFromPointer:mn,deleteObject($){$!==null&&$.delete()},fromWireType:Zi}),tn=I.UnboundTypeError=(On=Error,(yn=an(vg="UnboundTypeError",function($){this.name=vg,this.message=$;var j=new Error($).stack;j!==void 0&&(this.stack=this.toString()+` -`+j.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(On.prototype),yn.prototype.constructor=yn,yn.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},yn),Object.assign(rr.prototype,{get($){return this.allocated[$]},has($){return this.allocated[$]!==void 0},allocate($){var j=this.freelist.pop()||this.allocated.length;return this.allocated[j]=$,j},free($){this.allocated[$]=void 0,this.freelist.push($)}}),fo.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),fo.reserved=fo.allocated.length,I.count_emval_handles=vc;var ws,Fa={w:($,j,RA)=>{throw new ao($).init(j,RA),$},q:($,j,RA,ZA,ne)=>{},u:($,j,RA,ZA)=>{pn($,{name:j=Fi(j),fromWireType:function(ne){return!!ne},toWireType:function(ne,De){return De?RA:ZA},argPackAdvance:8,readValueFromPointer:function(ne){return this.fromWireType(eA[ne])},destructorFunction:null})},y:($,j,RA,ZA,ne,De,Ke,qe,Et,ft,Nt,Kt,di)=>{Nt=Fi(Nt),De=qt(ne,De),qe&&(qe=qt(Ke,qe)),ft&&(ft=qt(Et,ft)),di=qt(Kt,di);var Bt=(Jt=>{if(Jt===void 0)return"_unknown";var $i=(Jt=Jt.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return $i>=48&&$i<=57?`_${Jt}`:Jt})(Nt);((Jt,$i,eo)=>{I.hasOwnProperty(Jt)?(Ai(`Cannot register public name '${Jt}' twice`),Vo(I,Jt,Jt),I.hasOwnProperty(eo)&&Ai(`Cannot register multiple overloads of a function with the same number of arguments (${eo})!`),I[Jt].overloadTable[eo]=$i):I[Jt]=$i})(Bt,function(){Ls(`Cannot construct ${Nt} due to unbound types`,[ZA])}),Ri([$,j,RA],ZA?[ZA]:[],function(Jt){var $i,eo;Jt=Jt[0],eo=ZA?($i=Jt.registeredClass).instancePrototype:Cn.prototype;var os=an(Nt,function(){if(Object.getPrototypeOf(this)!==Ti)throw new Vi("Use 'new' to construct "+Nt);if(on.constructor_body===void 0)throw new Vi(Nt+" has no accessible constructor");var js=on.constructor_body[arguments.length];if(js===void 0)throw new Vi(`Tried to invoke ctor of ${Nt} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(on.constructor_body).toString()}) parameters instead!`);return js.apply(this,arguments)}),Ti=Object.create(eo,{constructor:{value:os}});os.prototype=Ti;var on=new jn(Nt,os,Ti,di,$i,De,qe,ft);on.baseClass&&(on.baseClass.__derivedClasses===void 0&&(on.baseClass.__derivedClasses=[]),on.baseClass.__derivedClasses.push(on));var wg=new Fr(Nt,on,!0,!1,!1),Er=new Fr(Nt+"*",on,!1,!1,!1),Mr=new Fr(Nt+" const*",on,!1,!0,!1);return ei[$]={pointerType:Er,constPointerType:Mr},((js,Tl,ns)=>{I.hasOwnProperty(js)||no("Replacing nonexistant public symbol"),I[js].overloadTable!==void 0&&ns!==void 0?I[js].overloadTable[ns]=Tl:(I[js]=Tl,I[js].argCount=ns)})(Bt,os),[wg,Er,Mr]})},x:($,j,RA,ZA,ne,De)=>{var Ke=Bs(j,RA);ne=qt(ZA,ne),Ri([],[$],function(qe){var Et=`constructor ${(qe=qe[0]).name}`;if(qe.registeredClass.constructor_body===void 0&&(qe.registeredClass.constructor_body=[]),qe.registeredClass.constructor_body[j-1]!==void 0)throw new Vi(`Cannot register multiple constructors with identical number of parameters (${j-1}) for class '${qe.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return qe.registeredClass.constructor_body[j-1]=()=>{Ls(`Cannot construct ${qe.name} due to unbound types`,Ke)},Ri([],Ke,ft=>(ft.splice(1,0,null),qe.registeredClass.constructor_body[j-1]=Ir(Et,ft,null,ne,De),[])),[]})},i:($,j,RA,ZA,ne,De,Ke,qe,Et)=>{var ft=Bs(RA,ZA);j=(Nt=>{const Kt=(Nt=Nt.trim()).indexOf("(");return Kt!==-1?Nt.substr(0,Kt):Nt})(j=Fi(j)),De=qt(ne,De),Ri([],[$],function(Nt){var Kt=`${(Nt=Nt[0]).name}.${j}`;function di(){Ls(`Cannot call ${Kt} due to unbound types`,ft)}j.startsWith("@@")&&(j=Symbol[j.substring(2)]),qe&&Nt.registeredClass.pureVirtualFunctions.push(j);var Bt=Nt.registeredClass.instancePrototype,Jt=Bt[j];return Jt===void 0||Jt.overloadTable===void 0&&Jt.className!==Nt.name&&Jt.argCount===RA-2?(di.argCount=RA-2,di.className=Nt.name,Bt[j]=di):(Vo(Bt,j,Kt),Bt[j].overloadTable[RA-2]=di),Ri([],ft,function($i){var eo=Ir(Kt,$i,Nt,De,Ke);return Bt[j].overloadTable===void 0?(eo.argCount=RA-2,Bt[j]=eo):Bt[j].overloadTable[RA-2]=eo,[]}),[]})},k:($,j,RA,ZA,ne,De,Ke,qe,Et,ft)=>{j=Fi(j),ne=qt(ZA,ne),Ri([],[$],function(Nt){var Kt=`${(Nt=Nt[0]).name}.${j}`,di={get(){Ls(`Cannot access ${Kt} due to unbound types`,[RA,Ke])},enumerable:!0,configurable:!0};return di.set=Et?()=>Ls(`Cannot access ${Kt} due to unbound types`,[RA,Ke]):Bt=>Ai(Kt+" is a read-only property"),Object.defineProperty(Nt.registeredClass.instancePrototype,j,di),Ri([],Et?[RA,Ke]:[RA],function(Bt){var Jt=Bt[0],$i={get(){var os=Fn(this,Nt,Kt+" getter");return Jt.fromWireType(ne(De,os))},enumerable:!0};if(Et){Et=qt(qe,Et);var eo=Bt[1];$i.set=function(os){var Ti=Fn(this,Nt,Kt+" setter"),on=[];Et(ft,Ti,eo.toWireType(on,os)),Un(on)}}return Object.defineProperty(Nt.registeredClass.instancePrototype,j,$i),[]}),[]})},t:($,j)=>{pn($,{name:j=Fi(j),fromWireType:RA=>{var ZA=ts.toValue(RA);return es(RA),ZA},toWireType:(RA,ZA)=>ts.toHandle(ZA),argPackAdvance:8,readValueFromPointer:ur,destructorFunction:null})},p:($,j,RA)=>{pn($,{name:j=Fi(j),fromWireType:ZA=>ZA,toWireType:(ZA,ne)=>ne,argPackAdvance:8,readValueFromPointer:ot(j,RA),destructorFunction:null})},g:($,j,RA,ZA,ne)=>{j=Fi(j);var De=Et=>Et;if(ZA===0){var Ke=32-8*RA;De=Et=>Et<>>Ke}var qe=j.includes("unsigned");pn($,{name:j,fromWireType:De,toWireType:qe?function(Et,ft){return this.name,ft>>>0}:function(Et,ft){return this.name,ft},argPackAdvance:8,readValueFromPointer:Zt(j,RA,ZA!==0),destructorFunction:null})},a:($,j,RA)=>{var ZA=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][j];function ne(De){var Ke=vA[De>>2],qe=vA[De+4>>2];return new ZA(cA.buffer,qe,Ke)}pn($,{name:RA=Fi(RA),fromWireType:ne,argPackAdvance:8,readValueFromPointer:ne},{ignoreDuplicateRegistrations:!0})},o:($,j)=>{var RA=(j=Fi(j))==="std::string";pn($,{name:j,fromWireType(ZA){var ne,De=vA[ZA>>2],Ke=ZA+4;if(RA)for(var qe=Ke,Et=0;Et<=De;++Et){var ft=Ke+Et;if(Et==De||eA[ft]==0){var Nt=WI(qe,ft-qe);ne===void 0?ne=Nt:(ne+="\0",ne+=Nt),qe=ft+1}}else{var Kt=new Array(De);for(Et=0;Et{for(var di=0,Bt=0;Bt=55296&&Jt<=57343?(di+=4,++Bt):di+=3}return di})(ne):ne.length;var qe=Tn(4+De+1),Et=qe+4;if(vA[qe>>2]=De,RA&&Ke)((Kt,di,Bt,Jt)=>{if(!(Jt>0))return 0;for(var $i=Bt,eo=Bt+Jt-1,os=0;os=55296&&Ti<=57343&&(Ti=65536+((1023&Ti)<<10)|1023&Kt.charCodeAt(++os)),Ti<=127){if(Bt>=eo)break;di[Bt++]=Ti}else if(Ti<=2047){if(Bt+1>=eo)break;di[Bt++]=192|Ti>>6,di[Bt++]=128|63&Ti}else if(Ti<=65535){if(Bt+2>=eo)break;di[Bt++]=224|Ti>>12,di[Bt++]=128|Ti>>6&63,di[Bt++]=128|63&Ti}else{if(Bt+3>=eo)break;di[Bt++]=240|Ti>>18,di[Bt++]=128|Ti>>12&63,di[Bt++]=128|Ti>>6&63,di[Bt++]=128|63&Ti}}di[Bt]=0})(ne,eA,Et,De+1);else if(Ke)for(var ft=0;ft255&&(_s(Et),Ai("String has UTF-16 code units that do not fit in 8 bits")),eA[Et+ft]=Nt}else for(ft=0;ft{var ZA,ne,De,Ke,qe;RA=Fi(RA),j===2?(ZA=ro,ne=Mc,Ke=gg,De=()=>IA,qe=1):j===4&&(ZA=Mg,ne=Qa,Ke=Fo,De=()=>vA,qe=2),pn($,{name:RA,fromWireType:Et=>{for(var ft,Nt=vA[Et>>2],Kt=De(),di=Et+4,Bt=0;Bt<=Nt;++Bt){var Jt=Et+4+Bt*j;if(Bt==Nt||Kt[Jt>>qe]==0){var $i=ZA(di,Jt-di);ft===void 0?ft=$i:(ft+="\0",ft+=$i),di=Jt+j}}return _s(Et),ft},toWireType:(Et,ft)=>{typeof ft!="string"&&Ai(`Cannot pass non-string to C++ string type ${RA}`);var Nt=Ke(ft),Kt=Tn(4+Nt+j);return vA[Kt>>2]=Nt>>qe,ne(ft,Kt+4,Nt+j),Et!==null&&Et.push(_s,Kt),Kt},argPackAdvance:8,readValueFromPointer:ur,destructorFunction(Et){_s(Et)}})},v:($,j)=>{pn($,{isVoid:!0,name:j=Fi(j),argPackAdvance:0,fromWireType:()=>{},toWireType:(RA,ZA)=>{}})},j:($,j,RA)=>($=ts.toValue($),j=Aa(j,"emval::as"),Uo(j,RA,$)),e:($,j,RA,ZA,ne)=>{var De,Ke;return($=Xs[$])(j=ts.toValue(j),j[RA=(Ke=Zc[De=RA])===void 0?Fi(De):Ke],ZA,ne)},d:es,f:($,j,RA)=>{var ZA=((ft,Nt)=>{for(var Kt=new Array(ft),di=0;di>2],"parameter "+di);return Kt})($,j),ne=ZA.shift();$--;var De,Ke,qe=new Array($),Et=`methodCaller<(${ZA.map(ft=>ft.name).join(", ")}) => ${ne.name}>`;return De=an(Et,(ft,Nt,Kt,di)=>{for(var Bt=0,Jt=0;Jt<$;++Jt)qe[Jt]=ZA[Jt].readValueFromPointer(di+Bt),Bt+=ZA[Jt].argPackAdvance;var $i=RA===1?is(Nt,qe):Nt.apply(ft,qe);for(Jt=0;Jt<$;++Jt)ZA[Jt].deleteObject&&ZA[Jt].deleteObject(qe[Jt]);return Uo(ne,Kt,$i)}),Ke=Xs.length,Xs.push(De),Ke},c:$=>{$>4&&(fo.get($).refcount+=1)},b:$=>{var j=ts.toValue($);Un(j),es($)},h:($,j)=>{var RA=($=Aa($,"_emval_take_value")).readValueFromPointer(j);return ts.toHandle(RA)},m:()=>{Xe("")},s:($,j,RA)=>eA.copyWithin($,j,j+RA),r:$=>{eA.length,Xe("OOM")},n:($,j,RA,ZA)=>{for(var ne=0,De=0;De>2],qe=vA[j+4>>2];j+=8;for(var Et=0;Et>2]=ne,0}},Qs=function(){var $={a:Fa};function j(RA,ZA){var ne,De;return Qs=RA.exports,_=Qs.z,ne=_.buffer,I.HEAP8=cA=new Int8Array(ne),I.HEAP16=CA=new Int16Array(ne),I.HEAPU8=eA=new Uint8Array(ne),I.HEAPU16=IA=new Uint16Array(ne),I.HEAP32=oA=new Int32Array(ne),I.HEAPU32=vA=new Uint32Array(ne),I.HEAPF32=qA=new Float32Array(ne),I.HEAPF64=Ae=new Float64Array(ne),qi=Qs.C,De=Qs.A,WA.unshift(De),function(){if(we--,I.monitorRunDependencies&&I.monitorRunDependencies(we),we==0&&et){var Ke=et;et=null,Ke()}}(),Qs}if(we++,I.monitorRunDependencies&&I.monitorRunDependencies(we),I.instantiateWasm)try{return I.instantiateWasm($,j)}catch(RA){b(`Module.instantiateWasm callback failed with error: ${RA}`),c(RA)}return ii(0,ae,$,function(RA){j(RA.instance)}).catch(c),{}}(),Tn=$=>(Tn=Qs.B)($),pa=$=>(pa=Qs.D)($),_s=$=>(_s=Qs.E)($),Oa=$=>(Oa=Qs.F)($);I.dynCall_jiji=($,j,RA,ZA,ne)=>(I.dynCall_jiji=Qs.G)($,j,RA,ZA,ne),I._vertexShaderSource=10688;function Ta(){function $(){ws||(ws=!0,I.calledRun=!0,HA||(ki(WA),n(I),I.onRuntimeInitialized&&I.onRuntimeInitialized(),function(){if(I.postRun)for(typeof I.postRun=="function"&&(I.postRun=[I.postRun]);I.postRun.length;)Pe(I.postRun.shift());ki(Ye)}()))}we>0||(function(){if(I.preRun)for(typeof I.preRun=="function"&&(I.preRun=[I.preRun]);I.preRun.length;)We(I.preRun.shift());ki(se)}(),we>0||(I.setStatus?(I.setStatus("Running..."),setTimeout(function(){setTimeout(function(){I.setStatus("")},1),$()},1)):$()))}if(et=function $(){ws||Ta(),ws||(et=$)},I.preInit)for(typeof I.preInit=="function"&&(I.preInit=[I.preInit]);I.preInit.length>0;)I.preInit.pop()();return Ta(),i.ready}})(),AlA=$cA,C3=0,l7=class I7{constructor(i){this.core=i,jL(this,"seq"),jL(this,"_core"),jL(this,"log"),jL(this,"beautyParams"),C3+=1,this.seq=C3,this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${C3}`}),this.log.info("created")}getName(){return I7.Name}getAlias(){return"bb"}getValidateRule(i){switch(i){case"start":case"update":return ZcA(this._core);case"stop":return XcA(this._core)}}getGroup(){return"bb"}async start(i){this._core.room.videoManager.Wasm||(this._core.room.videoManager.Wasm=await AlA()),this._core.room.videoManager.renderMode="webgl";const n=this._core.utils.isUndefined(i.beauty)?.5:i.beauty,c=this._core.utils.isUndefined(i.brightness)?.5:i.brightness,I=this._core.utils.isUndefined(i.ruddy)?.5:i.ruddy;return this._core.room.videoManager.setBeautyParams({beauty:n,brightness:c,ruddy:I})}async update(i){const n=this._core.utils.isUndefined(i.beauty)?.5:i.beauty,c=this._core.utils.isUndefined(i.brightness)?.5:i.brightness,I=this._core.utils.isUndefined(i.ruddy)?.5:i.ruddy;return this._core.room.videoManager.setBeautyParams({beauty:n,brightness:c,ruddy:I})}async stop(){return this._core.room.videoManager.renderMode="auto",this._core.room.videoManager.stopBeauty()}destroy(){this._core.room.videoManager.renderMode="auto"}};jL(l7,"Name","BasicBeauty");var u7=l7,elA=u7;const tlA=Object.freeze(Object.defineProperty({__proto__:null,BasicBeauty:u7,default:elA},Symbol.toStringTag,{value:"Module"})),ilA=$U(tlA);var olA=Object.defineProperty,nlA=(e,i,n)=>i in e?olA(e,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[i]=n,MY=(e,i,n)=>nlA(e,typeof i!="symbol"?i+"":i,n),slA={name:"option",required:!0,properties:{sourceLanguage:{type:"string",required:!0},translationLanguages:{type:["string","array"],required:!1},userIdsToTranscribe:{type:["string","array"],required:!1},transcriberRobotId:{type:"string",required:!1}}},rlA={name:"option",required:!0,properties:{transcriberRobotId:{type:"string",required:!0}}},alA=new Set([2002,4003]),E7=class d7{constructor(i){this.core=i,MY(this,"disableRandomCall",!0),MY(this,"activeTranscriberMap",new Map),MY(this,"_log"),this._log=this.core.log.createChild({id:`${this.getAlias()}`})}getName(){return d7.Name}getAlias(){return"rt-trans"}getGroup(){return"*"}getValidateRule(i){switch(i){case"start":return slA;case"update":return{};case"stop":return rlA}}async start(i){var n;const{RtcError:c,ErrorCode:I}=this.core.errorModule;if(!this.core.room.sendSignalMessage)throw new c({code:I.ENV_NOT_SUPPORTED});const{sourceLanguage:C,translationLanguages:m,userIdsToTranscribe:R="all",transcriberRobotId:_}=i,T=_||`transcriber_${this.core.room.roomId}_robot_${this.core.room.userId}`,b={sdkappid:this.core.room.sdkAppId,roomid:String(this.core.room.roomId),roomType:this.core.room.useStringRoomId?1:0,agentParam:{cdnRobotUserid:T,lifecycleUserid:this.core.room.userId,maxIdletime:30},subscribeParams:{subUsers:[]},asrParams:{lang:C,vadSilenceTime:1e3},translationParams:{mode:1,targetLangs:[""]}};m&&m.length>0&&(b.translationParams.mode=1,b.translationParams.targetLangs=Array.isArray(m)?m:[m]),R==="all"?b.subscribeParams.subUsers=[]:Array.isArray(R)?b.subscribeParams.subUsers=R.map(J=>({userId:J,roomType:this.core.room.useStringRoomId?1:0,roomid:String(this.core.room.roomId)})):R&&(b.subscribeParams.subUsers=[{userId:R,roomType:this.core.room.useStringRoomId?1:0,roomid:String(this.core.room.roomId)}]);try{this._log.info(`start_cloud_transcription ${JSON.stringify(b)}`);const J=await this.core.room.sendSignalMessage({command:"start_cloud_transcription",responseCommand:String(8268),data:b,retries:0}),{code:cA,data:eA}=J.data;if(cA!==0){const IA=((n=J.data)==null?void 0:n.message)||"";throw this._log.error("start_cloud_transcription failed",{extraCode:cA,reason:IA,data:eA}),new c({code:I.SERVER_ERROR,extraCode:cA,message:IA})}const{taskId:CA}=eA;if(!CA)throw this._log.error("taskId is required",{data:J.data}),new c({code:I.SERVER_ERROR,message:"taskId is required"});return this.activeTranscriberMap.set(CA,i),this._log.info(`start_cloud_transcription success ${CA}, activeSize: ${this.activeTranscriberMap.size}`),CA}catch(J){throw this._log.error("start_cloud_transcription failed",{error:J}),J}}async update(){}async stop({transcriberRobotId:i}){var n;const{RtcError:c,ErrorCode:I}=this.core.errorModule;if(!this.core.room.sendSignalMessage)throw new c({code:I.ENV_NOT_SUPPORTED});try{const C=await this.core.room.sendSignalMessage({command:"stop_cloud_transcription",responseCommand:String(8270),data:{taskId:i},retries:3});if(C.data.code!==0){const m=C.data.code,R=((n=C.data)==null?void 0:n.message)||"";if(!alA.has(m))throw this._log.error("stop_cloud_transcription failed",{extraCode:m,reason:R,data:C.data.data}),new c({code:I.SERVER_ERROR,extraCode:m,message:R});this._log.warn("stop_cloud_transcription ignored error",{extraCode:m,reason:R,data:C.data.data})}this.activeTranscriberMap.delete(i)}catch(C){throw this._log.error("stop_cloud_transcription failed",{error:C}),C}}destroy(){this.activeTranscriberMap.clear()}};MY(E7,"Name","RealtimeTranscriber");var C7=E7,glA=C7;const clA=Object.freeze(Object.defineProperty({__proto__:null,RealtimeTranscriber:C7,default:glA},Symbol.toStringTag,{value:"Module"})),llA=$U(clA);var IlA=Object.create,tF=Object.defineProperty,ulA=Object.defineProperties,h7=Object.getOwnPropertyDescriptor,ElA=Object.getOwnPropertyDescriptors,B7=Object.getOwnPropertyNames,JY=Object.getOwnPropertySymbols,dlA=Object.getPrototypeOf,D4=Object.prototype.hasOwnProperty,Q7=Object.prototype.propertyIsEnumerable,CW=(e,i,n)=>i in e?tF(e,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[i]=n,ks=(e,i)=>{for(var n in i||(i={}))D4.call(i,n)&&CW(e,n,i[n]);if(JY)for(var n of JY(i))Q7.call(i,n)&&CW(e,n,i[n]);return e},cB=(e,i)=>ulA(e,ElA(i)),ClA=(e,i)=>{var n={};for(var c in e)D4.call(e,c)&&i.indexOf(c)<0&&(n[c]=e[c]);if(e!=null&&JY)for(var c of JY(e))i.indexOf(c)<0&&Q7.call(e,c)&&(n[c]=e[c]);return n},iF=(e,i)=>function(){return i||(0,e[B7(e)[0]])((i={exports:{}}).exports,i),i.exports},S4=(e,i)=>{for(var n in i)tF(e,n,{get:i[n],enumerable:!0})},hlA=(e,i,n,c)=>{if(i&&typeof i=="object"||typeof i=="function")for(let I of B7(i))D4.call(e,I)||I===n||tF(e,I,{get:()=>i[I],enumerable:!(c=h7(i,I))||c.enumerable});return e},MT=(e,i,n)=>(n=e!=null?IlA(dlA(e)):{},hlA(tF(n,"default",{value:e,enumerable:!0}),e)),yc=(e,i,n,c)=>{for(var I,C=h7(i,n),m=e.length-1;m>=0;m--)(I=e[m])&&(C=I(i,n,C)||C);return C&&tF(i,n,C),C},pe=(e,i,n)=>CW(e,typeof i!="symbol"?i+"":i,n),oF=iF({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(e,i){var n=Object.prototype.hasOwnProperty,c="~";function I(){}function C(T,b,J){this.fn=T,this.context=b,this.once=J||!1}function m(T,b,J,cA,eA){if(typeof J!="function")throw new TypeError("The listener must be a function");var CA=new C(J,cA||T,eA),IA=c?c+b:b;return T._events[IA]?T._events[IA].fn?T._events[IA]=[T._events[IA],CA]:T._events[IA].push(CA):(T._events[IA]=CA,T._eventsCount++),T}function R(T,b){--T._eventsCount===0?T._events=new I:delete T._events[b]}function _(){this._events=new I,this._eventsCount=0}Object.create&&(I.prototype=Object.create(null),new I().__proto__||(c=!1)),_.prototype.eventNames=function(){var T,b,J=[];if(this._eventsCount===0)return J;for(b in T=this._events)n.call(T,b)&&J.push(c?b.slice(1):b);return Object.getOwnPropertySymbols?J.concat(Object.getOwnPropertySymbols(T)):J},_.prototype.listeners=function(T){var b=c?c+T:T,J=this._events[b];if(!J)return[];if(J.fn)return[J.fn];for(var cA=0,eA=J.length,CA=new Array(eA);cA1&&(m[_[0]]=void 0),m};e.parseParams=function(m){return m.split(/;\s?/).reduce(C,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(m){return m.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(m){for(var R=[],_=m.split(" ").map(i),T=0;T<_.length;T+=3)R.push({component:_[T],ip:_[T+1],port:_[T+2]});return R},e.parseImageAttributes=function(m){return m.split(" ").map(function(R){return R.substring(1,R.length-1).split(",").reduce(C,{})})},e.parseSimulcastStreamList=function(m){return m.split(";").map(function(R){return R.split(",").map(function(_){var T,b=!1;return _[0]!=="~"?T=i(_):(T=i(_.substring(1,_.length)),b=!0),{scid:T,paused:b}})})}}}),QlA=iF({"../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/writer.js"(e,i){var n=v4(),c=/%[sdv%]/g,I=function(_){var T=1,b=arguments,J=b.length;return _.replace(c,function(cA){if(T>=J)return cA;var eA=b[T];switch(T+=1,cA){case"%%":return"%";case"%s":return String(eA);case"%d":return Number(eA);case"%v":return""}})},C=function(_,T,b){var J=[_+"="+(T.format instanceof Function?T.format(T.push?b:b[T.name]):T.format)];if(T.names)for(var cA=0;cA{i.enableVertexAttribArray(c),i.bindBuffer(i.ARRAY_BUFFER,n),i.vertexAttribPointer(c,2,i.FLOAT,!1,0,0)})}createShader(e,i){const{gl:n}=this,c=n.createShader(e);return n.shaderSource(c,i),n.compileShader(c),c}createProgram(e,i,n){const{gl:c}=this,I=this.createShader(c.FRAGMENT_SHADER,i),C=this.createShader(c.VERTEX_SHADER,e),m=c.createProgram();if(c.attachShader(m,C),c.attachShader(m,I),c.linkProgram(m),!c.getProgramParameter(m,c.LINK_STATUS))throw new Error(`${c.getProgramInfoLog(m)}`);return c.useProgram(m),this.setAttributes(this.positionBuffer,this.texCoordBuffer),n.forEach((R,_)=>{c.uniform1i(c.getUniformLocation(m,R),1+_)}),m}createFramebuffer(e){const{gl:i}=this,n=i.createFramebuffer();return i.bindFramebuffer(i.FRAMEBUFFER,n),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,e,0),n}getTempTexture(e,i,n=!0,c){const{gl:I}=this;let C,m;I.useProgram(e),this.ratio===16/9?(C=640,m=360):(C=640,m=480);const R=I.createTexture();I.activeTexture(I.TEXTURE0),I.bindTexture(I.TEXTURE_2D,R),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_MIN_FILTER,I.LINEAR),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_MAG_FILTER,I.LINEAR),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_WRAP_S,I.CLAMP_TO_EDGE),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_WRAP_T,I.CLAMP_TO_EDGE),I.pixelStorei(I.PACK_ALIGNMENT,1),I.pixelStorei(I.UNPACK_ALIGNMENT,1),I.texImage2D(I.TEXTURE_2D,0,I.RGBA,C,m,0,I.RGBA,I.UNSIGNED_BYTE,null);const _=this.createFramebuffer(R);return i.forEach((T,b)=>{T&&(I.activeTexture(I.TEXTURE1+b),I.bindTexture(I.TEXTURE_2D,T||null))}),this.setAttributes(this.positionBuffer,this.texCoordBuffer),I.viewport(0,0,C,m),I.drawArrays(I.TRIANGLE_STRIP,0,4),n&&i.forEach((T,b)=>{T&&c!==b&&I.deleteTexture(T)}),I.deleteFramebuffer(_),R}postProcessing(e){this._lastMaskTexture=this.getTempTexture(this._tdProgram,[e,this._lastMaskTexture]);let i=this.getTempTexture(this._kcProgram,[this._lastMaskTexture],!1);for(let n=0;n<3;n++){i=this.getTempTexture(this._mdProgram,[i]);const c=this.getTempTexture(this._edgeProgram,[i],!1);i=this.getTempTexture(this._borderProgram,[i,c,this._lastMaskTexture],!0,2)}return i}close(){const{gl:e}=this;this._borderProgram&&e.deleteProgram(this._borderProgram),this._edgeProgram&&e.deleteProgram(this._edgeProgram),this._kcProgram&&e.deleteProgram(this._kcProgram),this._mdProgram&&e.deleteProgram(this._mdProgram),this._tdProgram&&e.deleteProgram(this._tdProgram)}},VcA=new YcA,HcA=(e=>(e[e.TRACE=0]="TRACE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.NONE=5]="NONE",e))(HcA||{}),JcA={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},N_=570703,d3=0,a7=class g7{constructor(i){this.core=i,Wg(this,"seq"),Wg(this,"_core"),Wg(this,"log"),Wg(this,"preLoadPromise"),Wg(this,"startResolve"),Wg(this,"startReject"),Wg(this,"mediaPipeSolutions"),Wg(this,"assetsPath"),Wg(this,"currentType"),Wg(this,"onAbort"),Wg(this,"isAborted",!1),d3+=1,this.seq=d3,this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${d3}`}),this.log.info("created"),i.assetsPath&&(this.preLoadPromise=this.preload(i.assetsPath))}static isSupported(){if(YgA<90)return!1;const i=document.createElement("canvas").getContext("webgl2",JcA);return!!(i&&i instanceof WebGL2RenderingContext)}async preload(i){try{this._core.room.videoManager.Wasm||(this._core.room.videoManager.Wasm=await BgA());const n=c=>{var I;this.core.kvStatManager.addEnum({key:N_,value:this.getKVTypeValue(!1,this.isAborted,"ABORT_IN_INFERENCE")}),this.isAborted=!0,this.log.error("mediaPipeSolutions abort",c),this.core.clearStarted(this,this.getGroup()),this.stop(),(I=this.onAbort)==null||I.call(this,c)};this._core.room.videoManager.initVirtualBackground(n,A7,VcA),await this._core.initVisionTaskRegistry(i,["ImageSegmenter"])}catch(n){const{RtcError:c,ErrorCode:I}=this._core.errorModule;throw new c({code:I.INVALID_OPERATION,message:`VirtualBackground preload error, please redeploy the assets of the npm package. detail: ${n}`})}}getName(){return g7.Name}getAlias(){return"vb"}getValidateRule(i){switch(i){case"start":return EgA(this._core);case"update":return dgA(this._core);case"stop":return CgA(this._core)}}getGroup(){return"vb"}getKVTypeValue(i=!1,n=!1,c="NONE"){let I=0;switch(this.currentType){case"blur":I|=0;break;case"image":I|=1;break;case"color":I|=2}switch(i&&(I|=256),n&&(I|=512),c){case"ABORT_IN_INFERENCE":I|=4096;break;case"ABORT_IN_VIDEO_MANAGER":I|=8192;break;case"OTHER":I|=61440}return I}hexToRgb(i){const n=i.replace("#","");return[parseInt(n.slice(0,2),16)/255,parseInt(n.slice(2,4),16)/255,parseInt(n.slice(4,6),16)/255]}async start(i){const{type:n="blur",src:c,blurLevel:I=3,onAbort:C}=i;this.currentType=n,this.onAbort=C,n==="color"&&typeof i.color=="string"&&(i.color=this.hexToRgb(i.color));const{auth:m}=await IgA({sdkAppId:i.sdkAppId,userId:i.userId,userSig:i.userSig,core:this._core}),{RtcError:R,ErrorCodeDictionary:_,ErrorCode:T}=this._core.errorModule;if(!m){const b=this._core.utils.isOverseaSdkAppId(i.sdkAppId)?"https://trtc.io/document/56025":"https://cloud.tencent.com/document/product/647/85386";throw new R({code:_.NEED_TO_BUY,messageParams:{value:"Virtual Background",url:b}})}if(!this.preLoadPromise){if(!this._core.assetsPath)throw new R({code:T.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});this.preLoadPromise=this.preload(this._core.assetsPath)}return await this.preLoadPromise,this.core.room.videoManager.setVirtualBackground({type:n,imageUrl:c,blurLevel:I,enableFaceCentering:i.enableFaceCentering,enableEffectOptimization:i.enableEffectOptimization,color:i.color,onAbort:b=>{var J;this.core.kvStatManager.addEnum({key:N_,value:this.getKVTypeValue(!0,this.isAborted,"ABORT_IN_VIDEO_MANAGER")}),this.isAborted=!0,this.core.clearStarted(this,this.getGroup()),this.stop(),delete this.preLoadPromise,(J=this.onAbort)==null||J.call(this,b)}}).then(()=>{this.core.kvStatManager.addEnum({key:N_,value:this.getKVTypeValue(!1,this.isAborted,"NONE")})}).catch(b=>{throw this.core.kvStatManager.addEnum({key:N_,value:this.getKVTypeValue(!0,this.isAborted,"OTHER")}),b})}async update(i){const{type:n,src:c}=i;return n!==this.currentType&&(this.currentType=n),n==="color"&&typeof i.color=="string"&&(i.color=this.hexToRgb(i.color)),this.core.room.videoManager.setVirtualBackground({type:n,imageUrl:c,blurLevel:i.blurLevel,enableFaceCentering:i.enableFaceCentering,enableEffectOptimization:i.enableEffectOptimization,color:i.color}).then(()=>{this.core.kvStatManager.addEnum({key:N_,value:this.getKVTypeValue(!1,!1,"NONE")})}).catch(()=>{this.core.kvStatManager.addEnum({key:N_,value:this.getKVTypeValue(!0,!1,"OTHER")})})}async stop(){return this.core.room.videoManager.setVirtualBackground()}};Wg(a7,"Name","VirtualBackground");var c7=a7,qcA=c7;const KcA=Object.freeze(Object.defineProperty({__proto__:null,VirtualBackground:c7,default:qcA},Symbol.toStringTag,{value:"Module"})),jcA=$U(KcA);var WcA=Object.defineProperty,zcA=(e,i,n)=>i in e?WcA(e,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[i]=n,jL=(e,i,n)=>zcA(e,typeof i!="symbol"?i+"":i,n);function ZcA(e){return{name:"BasicBeautyOptions",type:"object",required:!0,allowEmpty:!1,properties:{beauty:{required:!1,type:"number"},brightness:{required:!1,type:"number"},ruddy:{required:!1,type:"number"}},validate(i,n,c,I){const{RtcError:C,ErrorCode:m,ErrorCodeDictionary:R}=e.errorModule;if(e.utils.isOverseaSdkAppId(i.sdkAppId))throw new C({code:m.INVALID_OPERATION,extraCode:R.INVALID_OPERATION,message:"This feature is not yet available in your country or region. If you have any questions, you can go to the community for consultation: https://zhiliao.qq.com/s/cWSPGIIM62CC/c3TPGIIM62CQ"})}}}function XcA(e){return{name:"StopBasicBeautyOptions",required:!1}}var $cA=(()=>{var e=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(i={}){var n,c,I=i;I.ready=new Promise(($,j)=>{n=$,c=j});var C=Object.assign({},I),m="";typeof document<"u"&&document.currentScript&&(m=document.currentScript.src),e&&(m=e),m=m.indexOf("blob:")!==0?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var R,_,T=I.print||console.log.bind(console),b=I.printErr||console.error.bind(console);function J($){if($t($))return function(j){for(var RA=atob(j),ZA=new Uint8Array(RA.length),ne=0;ne$.startsWith(pt);function Pt($){return Promise.resolve().then(()=>function(j){if(j==ae&&R)return new Uint8Array(R);var RA=J(j);if(RA)return RA;throw"both async and sync fetching of the wasm failed"}($))}function ii($,j,RA,ZA){return function(ne,De,Ke){return Pt(ne).then(qe=>WebAssembly.instantiate(qe,De)).then(qe=>qe).then(Ke,qe=>{b(`failed to asynchronously prepare wasm: ${qe}`),Xe(qe)})}(j,RA,ZA)}$t(ae="data:application/octet-stream;base64,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IAEoAgA2AgAgAiABKAIENgIEIAIgASgCCDYCCCACIAEoAgw2AgwgAiABKAIQNgIQIAIgASgCFDYCFCACIAEoAhg2AhggAiABKAIcNgIcIAIgASgCIDYCICACIAEoAiQ2AiQgAiABKAIoNgIoIAIgASgCLDYCLCACIAEoAjA2AjAgAiABKAI0NgI0IAIgASgCODYCOCACIAEoAjw2AjwgAUFAayEBIAJBQGsiAiAFTQ0ACwsgAiAETw0BA0AgAiABKAIANgIAIAFBBGohASACQQRqIgIgBEkNAAsMAQsgA0EESQRAIAAhAgwBCyAAIANBBGsiBEsEQCAAIQIMAQsgACECA0AgAiABLQAAOgAAIAIgAS0AAToAASACIAEtAAI6AAIgAiABLQADOgADIAFBBGohASACQQRqIgIgBE0NAAsLIAIgA0kEQANAIAIgAS0AADoAACABQQFqIQEgAkEBaiICIANHDQALCyAACwsAIAEgAiAAEEIaCxIAIAFBAXRB8MoAakECIAAQQgv5AQEEfwJ/IAEQKiECIwBBEGsiBSQAAn8gAC0AC0EHdgRAIAAoAgQMAQsgAC0AC0H/AHELIgRBAE8EQAJAIAIgAC0AC0EHdgR/IAAoAghB/////wdxQQFrBUEKCyIDIARrTQRAIAJFDQECfyAALQALQQd2BEAgACgCAAwBCyAACyIDIAQEfyACIANqIAMgBBBFIAEgAkEAIAMgBGogAUsbQQAgASADTxtqBSABCyACEEUgACACIARqIgEQMSAFQQA6AA8gASADaiAFLQAPOgAADAELIAAgAyACIARqIANrIARBACACIAEQRAsgBUEQaiQAIAAMAQsQJwALC/ICAgJ/AX4CQCACRQ0AIAAgAToAACAAIAJqIgNBAWsgAToAACACQQNJDQAgACABOgACIAAgAToAASADQQNrIAE6AAAgA0ECayABOgAAIAJBB0kNACAAIAE6AAMgA0EEayABOgAAIAJBCUkNACAAQQAgAGtBA3EiBGoiAyABQf8BcUGBgoQIbCIBNgIAIAMgAiAEa0F8cSIEaiICQQRrIAE2AgAgBEEJSQ0AIAMgATYCCCADIAE2AgQgAkEIayABNgIAIAJBDGsgATYCACAEQRlJDQAgAyABNgIYIAMgATYCFCADIAE2AhAgAyABNgIMIAJBEGsgATYCACACQRRr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ACACQQA6AA8DQCABBEAgACACLQAPOgAAIAFBAWshASAAQQFqIQAMAQsLIAJBEGokAAsaACAALQALQQd2BEAgACgCCBogACgCABAZCwvmAQEFfyMAQRBrIgUkACMAQSBrIgMkACMAQRBrIgQkACAEIAA2AgwgBCAAIAFqNgIIIAMgBCgCDDYCGCADIAQoAgg2AhwgBEEQaiQAIAMoAhghBCADKAIcIQYjAEEQayIBJAAgASAGNgIMIAIgBCAGIARrIgQQQyABIAIgBGo2AgggAyABKAIMNgIQIAMgASgCCDYCFCABQRBqJAAgAyAAIAMoAhAgAGtqNgIMIAMgAiADKAIUIAJrajYCCCAFIAMoAgw2AgggBSADKAIINgIMIANBIGokACAFKAIMIQcgBUEQaiQAIAcLDwAgAgRAIAAgASACEDILC/UCAQV/IwBBEGsiByQAIAIgAUF/c0Hv////B2pNBEACfyAALQALQQd2BEAgACgCAAwBCyAACyEIIAdBBGoiCSAAIAFB5////wNJBH8gByABQQF0NgIMIAcgASACajYCBCMAQRBrIgIkACAJKAIAIAdBDGoiCigCAEkhCyACQRBqJAAgCiAJIAsbKAIAIgJBC08EfyACQRBqQXBxIgIgAkEBayICIAJBC0YbBUEKC0EBagVB7////wcLEDAgBygCBCECIAcoAggaIAQEQCACIAggBBAjCyAFBEAgAiAEaiAGIAUQIwsgAyAEayEGIAMgBEcEQCACIARqIAVqIAQgCGogBhAjCyABQQpHBEAgCBAZCyAAIAI2AgAgACAAKAIIQYCAgIB4cSAHKAIIQf////8HcXI2AgggACAAKAIIQYCAgIB4cjYCCCAAIAQgBWogBmoiADYCBCAHQQA6AAwgACACaiAHLQAMOgAAIAdBEGokAA8LECcACwoAIAAgASACEEMLuQEBBH8jAEEQayIEJAAgBCACNgIMIwBBoAFrIgMkACADIAAgA0GeAWogARsiBjYClAFBfyEFIAMgAUEBayIAQQAgACABTRs2ApgBIANBAEGQARAmIgBBfzYCTCAAQSA2AiQgAEF/NgJQIAAgAEGfAWo2AiwgACAAQZQBajYCVAJAIAFBAEgEQEHo3gBBPTYCAAwBCyAGQQA6AAAgAEH9CiACQR8QTSEFCyAAQaABaiQAIARBEGokACAFCwQA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KAIARQ0AIAIgBCgCGDYCAAsgAEEBRiEFDAELQQAhBQsgBEFAayQAIAULMQAgACABKAIIQQAQHgRAIAEgAiADED0PCyAAKAIIIgAgASACIAMgACgCACgCHBEGAAsYACAAIAEoAghBABAeBEAgASACIAMQPQsLnQEBAn8jAEFAaiIDJAACf0EBIAAgAUEAEB4NABpBACABRQ0AGkEAIAFBjM0AECAiAUUNABogA0EMakEAQTQQJhogA0EBNgI4IANBfzYCFCADIAA2AhAgAyABNgIIIAEgA0EIaiACKAIAQQEgASgCACgCHBEGACADKAIgIgBBAUYEQCACIAMoAhg2AgALIABBAUYLIQQgA0FAayQAIAQLCgAgACABQQAQHgtOAgF/AXwjAEEQayICJAAgAkEANgIMIAEoAgRB1M8AIAJBDGoQCSEDIAIoAgwiAQRAIAEQAQsgACADRAAAAAAAAAAAYjoAOCACQRBqJAALNwEBfyMAQRBrIgIkACACIAEtADg2AgggAEHUzwAgAkEIahAHNgIEIABB1NUANgIAIAJBEGokAAuoAQEFfyAAKAJUIgMoAgAhBSADKAIEIgQgACgCFCAAKAIcIgdrIgYgBCAGSRsiBgRAIAUgByAGECIaIAMgAygCACAGaiIFNgIAIAMgAygCBCAGayIENgIECyAEIAIgAiAESxsiBARAIAUgASAEECIaIAMgAygCACAEaiIFNgIAIAMgAygCBCAEazYCBAsgBUEAOgAAIAAgACgCLCIBNgIcIAAgATYCFCACC5wBAQJ/IwBBEGsiAiQAQcgAEBwhASAAKAIEIgAQAiACIAA2AgggAUHMLSACQQhqEAc2AgQgAUHU1QA2AgAgAUEBNgIcIAFB1NUANgIYIAFBATYCFCABQdTVADYCECABQQE2AgwgAUHU1QA2AgggAUEAOgAgIAFBADYCRCABQoCAgIAwNwI8IAFBADsANyABQQA7ACsgAkEQaiQAIAELigUCBn4CfyABIAEoAgBBB2pBeHEiAUEQajYCACAAIQkgASkDACEDIAEpAwghBSMAQSBrIgAkAAJAIAVC////////////AIMiBEKAgICAgIDAgDx9IARCgICAgICAwP/DAH1UBEAgBUIEhiADQjyIhCEEIANC//////////8PgyIDQoGAgICAgICACFoEQCAEQoGAgICAgICAwAB8IQIMAgsgBEKAgICAgICAgEB9IQIgA0KAgICAgICAgAhSDQEgAiAEQgGDfCECDAELIANQIARCgICAgICAwP//AFQgBEKAgICAgIDA//8AURtFBEAgBUIEhiADQjyIhEL/////////A4NCgICAgICAgPz/AIQhAgwBC0KAgICAgICA+P8AIQIgBEL///////+//8MAVg0AQgAhAiAEQjCIpyIBQZH3AEkNACADIQIgBUL///////8/g0KAgICAgIDAAIQiBCEGAkAgAUGB9wBrIghBwABxBEAgAyAIQUBqrYYhBkIAIQIMAQsgCEUNACAGIAitIgeGIAJBwAAgCGutiIQhBiACIAeGIQILIAAgAjcDECAAIAY3AxgCQEGB+AAgAWsiAUHAAHEEQCAEIAFBQGqtiCEDQgAhBAwBCyABRQ0AIARBwAAgAWuthiADIAGtIgKIhCEDIAQgAoghBAsgACADNwMAIAAgBDcDCCAAKQMIQgSGIAApAwAiA0I8iIQhAiAAKQMQIAApAxiEQgBSrSADQv//////////D4OEIgNCgYCAgICAgIAIWgRAIAJCAXwhAgwBCyADQoCAgICAgICACFINACACQgGDIAJ8IQILIABBIGokACAJIAIgBUKAgICAgICAgIB/g4S/OQMAC0ABAn8jAEEQayICJAAgAiABNgIMIAJB1NUANgIIIAJBCGogABEBACEDIAIoAgwiAQRAIAEQAwsgAkEQaiQAIAMLBABCAAsEAEEAC/YCAQh/IwBBIGsiAyQAIAMgACgCHCIENgIQIAAoAhQhBSADIAI2AhwgAyABNgIYIAMgBSAEayIBNgIUIAEgAmohBUECIQcCfwJAAkACQCAAKAI8IANBEGoiAUECIANBDGoQDSIEBH9B6N4AIAQ2AgBBfwVBAAsEQCABIQQMAQsDQCAFIAMoAgwiBkYNAiAGQQBIBEAgASEEDAQLIAEgBiABKAIEIghLIglBA3RqIgQgBiAIQQAgCRtrIgggBCgCAGo2AgAgAUEMQQQgCRtqIgEgASgCACAIazYCACAFIAZrIQUgACgCPCAEIgEgByAJayIHIANBDGoQDSIGBH9B6N4AIAY2AgBBfwVBAAtFDQALCyAFQX9HDQELIAAgACgCLCIBNgIcIAAgATYCFCAAIAEgACgCMGo2AhAgAgwBCyAAQQA2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EGokAAsiAQF+IAEgAq0gA61CIIaEIAQgABEMACIFQiCIpyQBIAWnCzcBAX8jAEEQayICJAAgAiABKAI8NgIIIABBnNAAIAJBCGoQBzYCBCAAQdTVADYCACACQRBqJAALC/NKFQBBgAgLhCZzZXRCZWF1dHkALSsgICAwWDB4AC0wWCswWCAwWC0weCsweCAweAB1bnNpZ25lZCBzaG9ydAB1bnNpZ25lZCBpbnQAaW5pdABmbG9hdAB1aW50NjRfdABibHVyUmFkaXVzAHZlY3RvcgBtaXJyb3IAYXR0YWNoU2hhZGVyAGRlbGV0ZVNoYWRlcgBjcmVhdGVTaGFkZXIAY29tcGlsZVNoYWRlcgB1bnNpZ25lZCBjaGFyAHN0ZDo6ZXhjZXB0aW9uAHJvdGF0aW9uAG5hbgBsaW5rUHJvZ3JhbQBkZWxldGVQcm9ncmFtAGNyZWF0ZVByb2dyYW0AYm9vbABlbXNjcmlwdGVuOjp2YWwAc2V0V2F0ZXJNYXJrAHN0b3BXYXRlck1hcmsAdW5zaWduZWQgbG9uZwBzdGQ6OndzdHJpbmcAYmFzaWNfc3RyaW5nAHN0ZDo6c3RyaW5nAHN0ZDo6dTE2c3RyaW5nAHN0ZDo6dTMyc3RyaW5nAGluZgAlZgBjbG9zZQBkb3VibGUAdmJNb2RlAHNoYWRlclNvdXJjZQB2b2lkAHNhbXBsZUNvbG9yICs9IHRleHR1cmUoZnJhbWUsIGJsdXJDb29yZGluYXRlc1sATkFOAElORgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxzaG9ydD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgc2hvcnQ+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGludD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgaW50PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxmbG9hdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dWludDhfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50OF90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1aW50MTZfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50MTZfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dWludDY0X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGludDY0X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PHVpbnQzMl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxpbnQzMl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxjaGFyPgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1bnNpZ25lZCBjaGFyPgBzdGQ6OmJhc2ljX3N0cmluZzx1bnNpZ25lZCBjaGFyPgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxzaWduZWQgY2hhcj4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8bG9uZz4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgbG9uZz4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8ZG91YmxlPgB2ZWMyIGMgPSB2X3RleENvb3JkOwB2ZWMyIGMgPSB2ZWMyKDEuMCAtIHZfdGV4Q29vcmQueCwgdl90ZXhDb29yZC55KTsAYyA9IHZlYzIoMS4wIC0gYy54LCAxLjAgLSBjLnkpOwBjID0gdmVjMihjLnksIDEuMCAtIGMueCk7AGMgPSB2ZWMyKDEuMCAtIGMueSwgYy54KTsAQWxsSW4xAC4ALjAsAC4wKSpvKSoAKG51bGwpACkqby55KTsgICAgdmVjMiBjb29yZDIgPSB2ZWMyKGZsb2F0KAAgICAgYyA9IHZlYzIodl90ZXhDb29yZC54LCAxLjAgLSB2X3RleENvb3JkLnkpOyAgICB2ZWMyIGNvb3JkMSA9IHZlYzIoZmxvYXQoACksIChjLnkgLWNvb3JkMS55KSAvIG8ueSAvIGZsb2F0KAApKm8ueSk7ICAgIGlmIChjLnggPiBjb29yZDEueCAmJiBjLnggPCBjb29yZDIueCAmJiBjLnkgPiBjb29yZDEueSAmJiBjLnkgPCBjb29yZDIueSkgeyAgICAgIHZlYzQgd2F0ZXJDb2xvciA9IHRleHR1cmUod2F0ZXJNYXJrLCB2ZWMyKChjLnggLSBjb29yZDEueCkgIC8gby54IC8gZmxvYXQoACkgKiBvLngsIGZsb2F0KABvdXRDb2xvci5yZ2IgKz0gdmVjMygAKTsgICAgICAgdmVjMyBzbW9vdGhDb2xvciA9IG91dENvbG9yLnJnYiArIChvdXRDb2xvci5yZ2ItdmVjMyhoaWdoUGFzcykpKmFscGhhKjAuMTsgICAgICAgc21vb3RoQ29sb3IgPSBtYXgoc21vb3RoQ29sb3IsIHZlYzMoMC4wKSk7ICAgICAgIHNtb290aENvbG9yID0gY2xhbXAocG93KHNtb290aENvbG9yLCB2ZWMzKABnKz1HKGMsdmVjMigAICAgICAgdmVjMiBvZmZzZXQgPSB2ZWMyKABdID0gdl90ZXhDb29yZC54eSArIG9mZnNldCAqIHZlYzIoADsgACkpLCB2ZWMzKDAuMCksIHZlYzMoMS4wKSk7ICAgICAgdmVjMyBzY3JlZW4gPSB2ZWMzKDEuMCkgLSAodmVjMygxLjApLXNtb290aENvbG9yKSAqICh2ZWMzKDEuMCktb3V0Q29sb3IucmdiKTsgICAgICAgdmVjMyBsaWdodGVuID0gbWF4KHNtb290aENvbG9yLCBvdXRDb2xvci5yZ2IpOyAgICAgICB2ZWMzIGJlYXV0eUNvbG9yID0gbWl4KG1peChvdXRDb2xvci5yZ2IsIHNjcmVlbiwgYWxwaGEpLCBsaWdodGVuLCBhbHBoYSk7ICAgICAgb3V0Q29sb3IucmdiID0gbWl4KG91dENvbG9yLnJnYiwgYmVhdXR5Q29sb3IsIAAKICAgICAgY29uc3QgbWF0MyBzYXR1cmF0ZU1hdHJpeCA9IG1hdDMoMS4xMTAyLC0wLjA1OTgsLTAuMDYxLC0wLjA3NzQsMS4wODI2LC0wLjExODYsLTAuMDIyOCwtMC4wMjI4LDEuMTc3Mik7CiAgICAgIHZlYzMgd2FybUNvbG9yID0gb3V0Q29sb3IucmdiICogc2F0dXJhdGVNYXRyaXg7CiAgICAgIG91dENvbG9yLnJnYiA9IG1peChvdXRDb2xvci5yZ2IsIHdhcm1Db2xvciwgACAgICAgIHNhbXBsZUNvbG9yID0gc2FtcGxlQ29sb3IgLyA2Mi4wOyAgICAgICBmbG9hdCBoaWdoUGFzcyA9IG91dENvbG9yLmcgLSBzYW1wbGVDb2xvciArIDAuNTsgICAgICAgY29uc3QgaGlnaHAgdmVjMyBXID0gdmVjMygwLjI5OSwwLjU4NywwLjExNCk7ICAgICAgZmxvYXQgbHVtaW5hbmNlID0gZG90KG91dENvbG9yLnJnYiwgVyk7ICAgICAgIGZsb2F0IGFscGhhID0gcG93KGx1bWluYW5jZSwgAF0pLmcgKiAAKSkpOyAgICAgIG91dENvbG9yID0gbWl4KG91dENvbG9yLHdhdGVyQ29sb3IsICB3YXRlckNvbG9yLmEpOyAgICB9ICAgIAApOyAgICAAKTsgICAgICB2ZWMyIGJsdXJDb29yZGluYXRlc1syNF07ICAgICAgACAgICAgIGZsb2F0IHNhbXBsZUNvbG9yID0gb3V0Q29sb3IuZyAqIDIyLjA7ICAgICAgIAAjdmVyc2lvbiAzMDAgZXMKICAgIHByZWNpc2lvbiBoaWdocCBmbG9hdDsKICAgIHVuaWZvcm0gc2FtcGxlcjJEIGZyYW1lOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgbWFzazsKICAgIHVuaWZvcm0gc2FtcGxlcjJEIGJnOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgd2F0ZXJNYXJrOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgbGFzdE1hc2s7CiAgICB1bmlmb3JtIG1hdDQgdV9vZmZzZXRNYXRyaXg7CiAgICB1bmlmb3JtIHZlYzMgdV9jb2xvcjsKICAgIGluIHZlYzIgdl90ZXhDb29yZDsKICAgIG91dCB2ZWM0IG91dENvbG9yOwogICAgdmVjNCBHKHZlYzIgYyx2ZWMyIHMpewogICAgICByZXR1cm4gdGV4dHVyZShmcmFtZSx0ZXh0dXJlKG1hc2ssYytzKS5yPjAuMz9jOmMrcyk7CiAgICB9CiAgICB2b2lkIG1haW4oKSB7CiAgICAgIAAKICAgICAgdmVjMiBvZmZzZXRNYXNrVVYgPSAodV9vZmZzZXRNYXRyaXggKiB2ZWM0KGMsIDAsIDEpKS54eTsKICAgICAgZmxvYXQgaXNJbnNpZGVYID0gKG9mZnNldE1hc2tVVi54ID49IDAuMCkgJiYgKG9mZnNldE1hc2tVVi54IDw9IDEuMCkgPyAxLjAgOiAwLjA7CiAgICAgIGZsb2F0IGlzSW5zaWRlWSA9IChvZmZzZXRNYXNrVVYueSA+PSAwLjApICYmIChvZmZzZXRNYXNrVVYueSA8PSAxLjApID8gMS4wIDogMC4wOwogICAgICBmbG9hdCBpc0luc2lkZSA9IGlzSW5zaWRlWCAqIGlzSW5zaWRlWTsKICAgICAgZmxvYXQgbWFza2VkQWxwaGEgPSB0ZXh0dXJlKG1hc2ssIG9mZnNldE1hc2tVVikuciAqIGlzSW5zaWRlOwogICAgICBtYXNrZWRBbHBoYSA9IG1hc2tlZEFscGhhPDAuNT8yLjAqbWFza2VkQWxwaGEqbWFza2VkQWxwaGE6MS4wLTIuMCooMS4wLW1hc2tlZEFscGhhKSooMS4wLW1hc2tlZEFscGhhKTsKICAgICAgc3JjX2NvbG9yID0gdGV4dHVyZShmcmFtZSwgb2Zmc2V0TWFza1VWICwgaXNJbnNpZGUpOwogICAgICBvdXRDb2xvciA9IG1peCh0ZXh0dXJlKGJnLCBjKSwgc3JjX2NvbG9yLCBtYXNrZWRBbHBoYSk7CiAgICAACiAgICB2ZWM0IGcgPSB2ZWM0KDAuMCk7CiAgICAACiAgICAgIGMueSA9IDEuMCAtIGMueTsKICAgICAgdmVjNCBzcmNfY29sb3IgPSB0ZXh0dXJlKGZyYW1lLCBjKTsKICAgICAgZmxvYXQgYSA9IHRleHR1cmUobWFzaywgYykucjsKICAgICAgYSA9IGE8MC41PzIuMCphKmE6MS4wLTIuMCooMS4wLWEpKigxLjAtYSk7CiAgICAgIC8vIGZsb2F0IGEyID0gdGV4dHVyZShsYXN0TWFzaywgYykuYTsKICAgICAgLy8gYTIgPSBhMjwwLjU/Mi4wKmEyKmEyOjEuMC0yLjAqKDEuMC1hMikqKDEuMC1hMik7CiAgICAgIC8vIGZsb2F0IGRlbHRhID0gYSAtIGEyOwogICAgICAvLyBpZiAoZGVsdGEgPCAwLjI1ICYmIGRlbHRhID4gLTAuMjUpCiAgICAgIC8vIHsKICAgICAgLy8gICAgIGEgPSBhICsgMC41KmRlbHRhOwogICAgICAvLyB9CiAgICAgIAogICAgICB2ZWMyIG8gPSAxLjAgLyB2ZWMyKHRleHR1cmVTaXplKGZyYW1lLCAwKSk7CiAgICAACiAgICAgIG91dENvbG9yID0gZzsKICAAI3ZlcnNpb24gMzAwIGVzCmluIHZlYzIgYV9wb3NpdGlvbjsKaW4gdmVjMiBhX3RleENvb3JkOwoKdW5pZm9ybSBtYXQ0IHVfdGV4dHVyZU1hdHJpeDsKCm91dCB2ZWMyIHZfdGV4Q29vcmQ7CnZvaWQgbWFpbigpIHsKICBnbF9Qb3NpdGlvbiA9IHZlYzQoYV9wb3NpdGlvbi54LCBhX3Bvc2l0aW9uLnksIDAsIDEpOwogIHZfdGV4Q29vcmQgPSh1X3RleHR1cmVNYXRyaXggKiB2ZWM0KGFfdGV4Q29vcmQsIDAsIDEpKS54eTsKfQoAc2V0QmVhdXR5ICVmICVmICVmICVmICVmCgBvdXRDb2xvciA9IHNyY19jb2xvcjsKAG91dENvbG9yID0gbWl4KHZlYzQodV9jb2xvciwxLjApLHNyY19jb2xvcixhKTsKADZBbGxJbjEAAIAoAABfFgAAUDZBbGxJbjEAAAAABCkAAHAWAAAAAAAAaBYAAFBLNkFsbEluMQAAAAQpAACMFgAAAQAAAGgWAABpaQB2AHZpAHwWAADMFgAATjEwZW1zY3JpcHRlbjN2YWxFAACAKAAAuBYAAGlpaQB2aWlpAAAAALwnAAB8FgAAcCgAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkZABBkC4LyAi8JwAAfBYAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkALwnAAB8FgAAdmlpALwnAADMFgAAzBYAAHwWAADMFgAAHCgAALwnAADMFgAAoBcAAE5TdDNfXzIxMmJhc2ljX3N0cmluZ0ljTlNfMTFjaGFyX3RyYWl0c0ljRUVOU185YWxsb2NhdG9ySWNFRUVFAACAKAAAYBcAAMwWAAC8JwAAzBYAAMwWAABOU3QzX18yMTJiYXNpY19zdHJpbmdJaE5TXzExY2hhcl90cmFpdHNJaEVFTlNfOWFsbG9jYXRvckloRUVFRQAAgCgAALgXAABOU3QzX18yMTJiYXNpY19zdHJpbmdJd05TXzExY2hhcl90cmFpdHNJd0VFTlNfOWFsbG9jYXRvckl3RUVFRQAAgCgAAAAYAABOU3QzX18yMTJiYXNpY19zdHJpbmdJRHNOU18xMWNoYXJfdHJhaXRzSURzRUVOU185YWxsb2NhdG9ySURzRUVFRQAAAIAoAABIGAAATlN0M19fMjEyYmFzaWNfc3RyaW5nSURpTlNfMTFj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")||(Je=ae,ae=I.locateFile?I.locateFile(Je,m):m+Je);var ki=$=>{for(;$.length>0;)$.shift()(I)};I.noExitRuntime;function ao($){this.excPtr=$,this.ptr=$-24,this.set_type=function(j){vA[this.ptr+4>>2]=j},this.get_type=function(){return vA[this.ptr+4>>2]},this.set_destructor=function(j){vA[this.ptr+8>>2]=j},this.get_destructor=function(){return vA[this.ptr+8>>2]},this.set_caught=function(j){j=j?1:0,gA[this.ptr+12|0]=j},this.get_caught=function(){return gA[this.ptr+12|0]!=0},this.set_rethrown=function(j){j=j?1:0,gA[this.ptr+13|0]=j},this.get_rethrown=function(){return gA[this.ptr+13|0]!=0},this.init=function(j,RA){this.set_adjusted_ptr(0),this.set_type(j),this.set_destructor(RA)},this.set_adjusted_ptr=function(j){vA[this.ptr+16>>2]=j},this.get_adjusted_ptr=function(){return vA[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Oa(this.get_type()))return vA[this.excPtr>>2];var j=this.get_adjusted_ptr();return j!==0?j:this.excPtr}}var Ji,Vi,wn,Fi=$=>{for(var j="",RA=$;eA[RA];)j+=Ji[eA[RA++]];return j},en={},Ro={},oo={},Ai=$=>{throw new Vi($)},no=$=>{throw new wn($)},Ri=($,j,RA)=>{function ZA(qe){var Et=RA(qe);Et.length!==$.length&&no("Mismatched type converter count");for(var ft=0;ft<$.length;++ft)pn($[ft],Et[ft])}$.forEach(function(qe){oo[qe]=j});var ne=new Array(j.length),De=[],Ke=0;j.forEach((qe,Et)=>{Ro.hasOwnProperty(qe)?ne[Et]=Ro[qe]:(De.push(qe),en.hasOwnProperty(qe)||(en[qe]=[]),en[qe].push(()=>{ne[Et]=Ro[qe],++Ke===De.length&&ZA(ne)}))}),De.length===0&&ZA(ne)};function pn($,j,RA={}){if(!("argPackAdvance"in j))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(ZA,ne,De={}){var Ke=ne.name;if(ZA||Ai(`type "${Ke}" must have a positive integer typeid pointer`),Ro.hasOwnProperty(ZA)){if(De.ignoreDuplicateRegistrations)return;Ai(`Cannot register type '${Ke}' twice`)}if(Ro[ZA]=ne,delete oo[ZA],en.hasOwnProperty(ZA)){var qe=en[ZA];delete en[ZA],qe.forEach(Et=>Et())}}($,j,RA)}var jA,ue=$=>{Ai($.$$.ptrType.registeredClass.name+" instance already deleted")},He=!1,Lt=$=>{},ct=$=>{$.count.value-=1,$.count.value===0&&(j=>{j.smartPtr?j.smartPtrType.rawDestructor(j.smartPtr):j.ptrType.registeredClass.rawDestructor(j.ptr)})($)},Ct=($,j,RA)=>{if(j===RA)return $;if(RA.baseClass===void 0)return null;var ZA=Ct($,j,RA.baseClass);return ZA===null?null:RA.downcast(ZA)},ei={},Ht=()=>Object.keys(Hi).length,Le=()=>{var $=[];for(var j in Hi)Hi.hasOwnProperty(j)&&$.push(Hi[j]);return $},it=[],Tt=()=>{for(;it.length;){var $=it.pop();$.$$.deleteScheduled=!1,$.delete()}},Gt=$=>{jA=$,it.length&&jA&&jA(Tt)},Hi={},po=($,j)=>(j=((RA,ZA)=>{for(ZA===void 0&&Ai("ptr should not be undefined");RA.baseClass;)ZA=RA.upcast(ZA),RA=RA.baseClass;return ZA})($,j),Hi[j]),To=($,j)=>(j.ptrType&&j.ptr||no("makeClassHandle requires ptr and ptrType"),!!j.smartPtrType!=!!j.smartPtr&&no("Both smartPtrType and smartPtr must be specified"),j.count={value:1},wo(Object.create($,{$$:{value:j}})));function Zi($){var j=this.getPointee($);if(!j)return this.destructor($),null;var RA=po(this.registeredClass,j);if(RA!==void 0){if(RA.$$.count.value===0)return RA.$$.ptr=j,RA.$$.smartPtr=$,RA.clone();var ZA=RA.clone();return this.destructor($),ZA}function ne(){return this.isSmartPointer?To(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:j,smartPtrType:this,smartPtr:$}):To(this.registeredClass.instancePrototype,{ptrType:this,ptr:$})}var De,Ke=this.registeredClass.getActualType(j),qe=ei[Ke];if(!qe)return ne.call(this);De=this.isConst?qe.constPointerType:qe.pointerType;var Et=Ct(j,this.registeredClass,De.registeredClass);return Et===null?ne.call(this):this.isSmartPointer?To(De.registeredClass.instancePrototype,{ptrType:De,ptr:Et,smartPtrType:this,smartPtr:$}):To(De.registeredClass.instancePrototype,{ptrType:De,ptr:Et})}var wo=$=>typeof FinalizationRegistry>"u"?(wo=j=>j,$):(He=new FinalizationRegistry(j=>{ct(j.$$)}),Lt=j=>He.unregister(j),(wo=j=>{var RA=j.$$;if(RA.smartPtr){var ZA={$$:RA};He.register(j,ZA,j)}return j})($));function Cn(){}var an=($,j)=>Object.defineProperty(j,"name",{value:$}),Vo=($,j,RA)=>{if($[j].overloadTable===void 0){var ZA=$[j];$[j]=function(){return $[j].overloadTable.hasOwnProperty(arguments.length)||Ai(`Function '${RA}' called with an invalid number of arguments (${arguments.length}) - expects one of (${$[j].overloadTable})!`),$[j].overloadTable[arguments.length].apply(this,arguments)},$[j].overloadTable=[],$[j].overloadTable[ZA.argCount]=ZA}};function jn($,j,RA,ZA,ne,De,Ke,qe){this.name=$,this.constructor=j,this.instancePrototype=RA,this.rawDestructor=ZA,this.baseClass=ne,this.getActualType=De,this.upcast=Ke,this.downcast=qe,this.pureVirtualFunctions=[]}var vo=($,j,RA)=>{for(;j!==RA;)j.upcast||Ai(`Expected null or instance of ${RA.name}, got an instance of ${j.name}`),$=j.upcast($),j=j.baseClass;return $};function mA($,j){if(j===null)return this.isReference&&Ai(`null is not a valid ${this.name}`),0;j.$$||Ai(`Cannot pass "${ce(j)}" as a ${this.name}`),j.$$.ptr||Ai(`Cannot pass deleted object as a pointer of type ${this.name}`);var RA=j.$$.ptrType.registeredClass;return vo(j.$$.ptr,RA,this.registeredClass)}function xs($,j){var RA;if(j===null)return this.isReference&&Ai(`null is not a valid ${this.name}`),this.isSmartPointer?(RA=this.rawConstructor(),$!==null&&$.push(this.rawDestructor,RA),RA):0;j.$$||Ai(`Cannot pass "${ce(j)}" as a ${this.name}`),j.$$.ptr||Ai(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&j.$$.ptrType.isConst&&Ai(`Cannot convert argument of type ${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type ${this.name}`);var ZA=j.$$.ptrType.registeredClass;if(RA=vo(j.$$.ptr,ZA,this.registeredClass),this.isSmartPointer)switch(j.$$.smartPtr===void 0&&Ai("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:j.$$.smartPtrType===this?RA=j.$$.smartPtr:Ai(`Cannot convert argument of type ${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:RA=j.$$.smartPtr;break;case 2:if(j.$$.smartPtrType===this)RA=j.$$.smartPtr;else{var ne=j.clone();RA=this.rawShare(RA,ts.toHandle(()=>ne.delete())),$!==null&&$.push(this.rawDestructor,RA)}break;default:Ai("Unsupporting sharing policy")}return RA}function Zs($,j){if(j===null)return this.isReference&&Ai(`null is not a valid ${this.name}`),0;j.$$||Ai(`Cannot pass "${ce(j)}" as a ${this.name}`),j.$$.ptr||Ai(`Cannot pass deleted object as a pointer of type ${this.name}`),j.$$.ptrType.isConst&&Ai(`Cannot convert argument of type ${j.$$.ptrType.name} to parameter type ${this.name}`);var RA=j.$$.ptrType.registeredClass;return vo(j.$$.ptr,RA,this.registeredClass)}function mn($){return this.fromWireType(vA[$>>2])}function Fr($,j,RA,ZA,ne,De,Ke,qe,Et,ft,Nt){this.name=$,this.registeredClass=j,this.isReference=RA,this.isConst=ZA,this.isSmartPointer=ne,this.pointeeType=De,this.sharingPolicy=Ke,this.rawGetPointee=qe,this.rawConstructor=Et,this.rawShare=ft,this.rawDestructor=Nt,ne||j.baseClass!==void 0?this.toWireType=xs:ZA?(this.toWireType=mA,this.destructorFunction=null):(this.toWireType=Zs,this.destructorFunction=null)}var qi,tn,Ks=[],_n=$=>{var j=Ks[$];return j||($>=Ks.length&&(Ks.length=$+1),Ks[$]=j=qi.get($)),j},Is=($,j,RA)=>$.includes("j")?((ZA,ne,De)=>{var Ke=I["dynCall_"+ZA];return De&&De.length?Ke.apply(null,[ne].concat(De)):Ke.call(null,ne)})($,j,RA):_n(j).apply(null,RA),qt=($,j)=>{var RA,ZA,ne,De=($=Fi($)).includes("j")?(RA=$,ZA=j,ne=[],function(){return ne.length=0,Object.assign(ne,arguments),Is(RA,ZA,ne)}):_n(j);return typeof De!="function"&&Ai(`unknown function pointer with signature ${$}: ${j}`),De},$a=$=>{var j=pa($),RA=Fi(j);return _s(j),RA},Ls=($,j)=>{var RA=[],ZA={};throw j.forEach(function ne(De){ZA[De]||Ro[De]||(oo[De]?oo[De].forEach(ne):(RA.push(De),ZA[De]=!0))}),new tn(`${$}: `+RA.map($a).join([", "]))},Bs=($,j)=>{for(var RA=[],ZA=0;ZA<$;ZA++)RA.push(vA[j+4*ZA>>2]);return RA},Un=$=>{for(;$.length;){var j=$.pop();$.pop()(j)}};function ur($,j,RA,ZA,ne,De){var Ke=j.length;Ke<2&&Ai("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var qe=j[1]!==null&&RA!==null,Et=!1,ft=1;ft($ instanceof Object||Ai(`${RA} with invalid "this": ${$}`),$ instanceof j.registeredClass.constructor||Ai(`${RA} incompatible with "this" of type ${$.constructor.name}`),$.$$.ptr||Ai(`cannot call emscripten binding method ${RA} on deleted object`),vo($.$$.ptr,$.$$.ptrType.registeredClass,j.registeredClass));function rr(){this.allocated=[void 0],this.freelist=[]}var fo=new rr,es=$=>{$>=fo.reserved&&--fo.get($).refcount===0&&fo.free($)},vc=()=>{for(var $=0,j=fo.reserved;j($||Ai("Cannot use deleted val. handle = "+$),fo.get($).value),toHandle:$=>{switch($){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return fo.allocate({refcount:1,value:$})}}};function Er($){return this.fromWireType(oA[$>>2])}var On,Mg,yn,ce=$=>{if($===null)return"null";var j=typeof $;return j==="object"||j==="array"||j==="function"?$.toString():""+$},ot=($,j)=>{switch(j){case 4:return function(RA){return this.fromWireType(qA[RA>>2])};case 8:return function(RA){return this.fromWireType(Ae[RA>>3])};default:throw new TypeError(`invalid float width (${j}): ${$}`)}},Zt=($,j,RA)=>{switch(j){case 1:return RA?ZA=>gA[ZA|0]:ZA=>eA[ZA|0];case 2:return RA?ZA=>CA[ZA>>1]:ZA=>IA[ZA>>1];case 4:return RA?ZA=>oA[ZA>>2]:ZA=>vA[ZA>>2];default:throw new TypeError(`invalid integer width (${j}): ${$}`)}},Ho=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ba=($,j,RA)=>{for(var ZA=j+RA,ne=j;$[ne]&&!(ne>=ZA);)++ne;if(ne-j>16&&$.buffer&&Ho)return Ho.decode($.subarray(j,ne));for(var De="";j>10,56320|1023&ft)}}else De+=String.fromCharCode((31&Ke)<<6|qe)}else De+=String.fromCharCode(Ke)}return De},WI=($,j)=>$?Ba(eA,$,j):"",gn=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,ro=($,j)=>{for(var RA=$,ZA=RA>>1,ne=ZA+j/2;!(ZA>=ne)&&IA[ZA];)++ZA;if((RA=ZA<<1)-$>32&&gn)return gn.decode(eA.subarray($,RA));for(var De="",Ke=0;!(Ke>=j/2);++Ke){var qe=CA[$+2*Ke>>1];if(qe==0)break;De+=String.fromCharCode(qe)}return De},Mc=($,j,RA)=>{if(RA===void 0&&(RA=2147483647),RA<2)return 0;for(var ZA=j,ne=(RA-=2)<2*$.length?RA/2:$.length,De=0;De>1]=Ke,j+=2}return CA[j>>1]=0,j-ZA},cg=$=>2*$.length,Rg=($,j)=>{for(var RA=0,ZA="";!(RA>=j/4);){var ne=oA[$+4*RA>>2];if(ne==0)break;if(++RA,ne>=65536){var De=ne-65536;ZA+=String.fromCharCode(55296|De>>10,56320|1023&De)}else ZA+=String.fromCharCode(ne)}return ZA},Qa=($,j,RA)=>{if(RA===void 0&&(RA=2147483647),RA<4)return 0;for(var ZA=j,ne=ZA+RA-4,De=0;De<$.length;++De){var Ke=$.charCodeAt(De);if(Ke>=55296&&Ke<=57343&&(Ke=65536+((1023&Ke)<<10)|1023&$.charCodeAt(++De)),oA[j>>2]=Ke,(j+=4)+4>ne)break}return oA[j>>2]=0,j-ZA},Fo=$=>{for(var j=0,RA=0;RA<$.length;++RA){var ZA=$.charCodeAt(RA);ZA>=55296&&ZA<=57343&&++RA,j+=4}return j},Aa=($,j)=>{var RA=Ro[$];return RA===void 0&&Ai(j+" has unknown type "+$a($)),RA},Uo=($,j,RA)=>{var ZA=[],ne=$.toWireType(ZA,RA);return ZA.length&&(vA[j>>2]=ts.toHandle(ZA)),ne},Zc={},Xs=[],is=Reflect.construct,wg=[null,[],[]],Rc=($,j)=>{var RA=wg[$];j===0||j===10?(($===1?T:b)(Ba(RA,0)),RA.length=0):RA.push(j)};(()=>{for(var $=new Array(256),j=0;j<256;++j)$[j]=String.fromCharCode(j);Ji=$})(),Vi=I.BindingError=class extends Error{constructor($){super($),this.name="BindingError"}},wn=I.InternalError=class extends Error{constructor($){super($),this.name="InternalError"}},Object.assign(Cn.prototype,{isAliasOf($){if(!(this instanceof Cn)||!($ instanceof Cn))return!1;var j=this.$$.ptrType.registeredClass,RA=this.$$.ptr;$.$$=$.$$;for(var ZA=$.$$.ptrType.registeredClass,ne=$.$$.ptr;j.baseClass;)RA=j.upcast(RA),j=j.baseClass;for(;ZA.baseClass;)ne=ZA.upcast(ne),ZA=ZA.baseClass;return j===ZA&&RA===ne},clone(){if(this.$$.ptr||ue(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var $,j=wo(Object.create(Object.getPrototypeOf(this),{$$:{value:($=this.$$,{count:$.count,deleteScheduled:$.deleteScheduled,preservePointerOnDelete:$.preservePointerOnDelete,ptr:$.ptr,ptrType:$.ptrType,smartPtr:$.smartPtr,smartPtrType:$.smartPtrType})}}));return j.$$.count.value+=1,j.$$.deleteScheduled=!1,j},delete(){this.$$.ptr||ue(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ai("Object already scheduled for deletion"),Lt(this),ct(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||ue(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Ai("Object already scheduled for deletion"),it.push(this),it.length===1&&jA&&jA(Tt),this.$$.deleteScheduled=!0,this}}),I.getInheritedInstanceCount=Ht,I.getLiveInheritedInstances=Le,I.flushPendingDeletes=Tt,I.setDelayFunction=Gt,Object.assign(Fr.prototype,{getPointee($){return this.rawGetPointee&&($=this.rawGetPointee($)),$},destructor($){this.rawDestructor&&this.rawDestructor($)},argPackAdvance:8,readValueFromPointer:mn,deleteObject($){$!==null&&$.delete()},fromWireType:Zi}),tn=I.UnboundTypeError=(On=Error,(yn=an(Mg="UnboundTypeError",function($){this.name=Mg,this.message=$;var j=new Error($).stack;j!==void 0&&(this.stack=this.toString()+` +`+j.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(On.prototype),yn.prototype.constructor=yn,yn.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},yn),Object.assign(rr.prototype,{get($){return this.allocated[$]},has($){return this.allocated[$]!==void 0},allocate($){var j=this.freelist.pop()||this.allocated.length;return this.allocated[j]=$,j},free($){this.allocated[$]=void 0,this.freelist.push($)}}),fo.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),fo.reserved=fo.allocated.length,I.count_emval_handles=vc;var ws,Fa={w:($,j,RA)=>{throw new ao($).init(j,RA),$},q:($,j,RA,ZA,ne)=>{},u:($,j,RA,ZA)=>{pn($,{name:j=Fi(j),fromWireType:function(ne){return!!ne},toWireType:function(ne,De){return De?RA:ZA},argPackAdvance:8,readValueFromPointer:function(ne){return this.fromWireType(eA[ne])},destructorFunction:null})},y:($,j,RA,ZA,ne,De,Ke,qe,Et,ft,Nt,Kt,di)=>{Nt=Fi(Nt),De=qt(ne,De),qe&&(qe=qt(Ke,qe)),ft&&(ft=qt(Et,ft)),di=qt(Kt,di);var Bt=(Jt=>{if(Jt===void 0)return"_unknown";var $i=(Jt=Jt.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return $i>=48&&$i<=57?`_${Jt}`:Jt})(Nt);((Jt,$i,eo)=>{I.hasOwnProperty(Jt)?(Ai(`Cannot register public name '${Jt}' twice`),Vo(I,Jt,Jt),I.hasOwnProperty(eo)&&Ai(`Cannot register multiple overloads of a function with the same number of arguments (${eo})!`),I[Jt].overloadTable[eo]=$i):I[Jt]=$i})(Bt,function(){Ls(`Cannot construct ${Nt} due to unbound types`,[ZA])}),Ri([$,j,RA],ZA?[ZA]:[],function(Jt){var $i,eo;Jt=Jt[0],eo=ZA?($i=Jt.registeredClass).instancePrototype:Cn.prototype;var os=an(Nt,function(){if(Object.getPrototypeOf(this)!==Ti)throw new Vi("Use 'new' to construct "+Nt);if(on.constructor_body===void 0)throw new Vi(Nt+" has no accessible constructor");var js=on.constructor_body[arguments.length];if(js===void 0)throw new Vi(`Tried to invoke ctor of ${Nt} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(on.constructor_body).toString()}) parameters instead!`);return js.apply(this,arguments)}),Ti=Object.create(eo,{constructor:{value:os}});os.prototype=Ti;var on=new jn(Nt,os,Ti,di,$i,De,qe,ft);on.baseClass&&(on.baseClass.__derivedClasses===void 0&&(on.baseClass.__derivedClasses=[]),on.baseClass.__derivedClasses.push(on));var _g=new Fr(Nt,on,!0,!1,!1),dr=new Fr(Nt+"*",on,!1,!1,!1),Mr=new Fr(Nt+" const*",on,!1,!0,!1);return ei[$]={pointerType:dr,constPointerType:Mr},((js,Nl,ns)=>{I.hasOwnProperty(js)||no("Replacing nonexistant public symbol"),I[js].overloadTable!==void 0&&ns!==void 0?I[js].overloadTable[ns]=Nl:(I[js]=Nl,I[js].argCount=ns)})(Bt,os),[_g,dr,Mr]})},x:($,j,RA,ZA,ne,De)=>{var Ke=Bs(j,RA);ne=qt(ZA,ne),Ri([],[$],function(qe){var Et=`constructor ${(qe=qe[0]).name}`;if(qe.registeredClass.constructor_body===void 0&&(qe.registeredClass.constructor_body=[]),qe.registeredClass.constructor_body[j-1]!==void 0)throw new Vi(`Cannot register multiple constructors with identical number of parameters (${j-1}) for class '${qe.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return qe.registeredClass.constructor_body[j-1]=()=>{Ls(`Cannot construct ${qe.name} due to unbound types`,Ke)},Ri([],Ke,ft=>(ft.splice(1,0,null),qe.registeredClass.constructor_body[j-1]=ur(Et,ft,null,ne,De),[])),[]})},i:($,j,RA,ZA,ne,De,Ke,qe,Et)=>{var ft=Bs(RA,ZA);j=(Nt=>{const Kt=(Nt=Nt.trim()).indexOf("(");return Kt!==-1?Nt.substr(0,Kt):Nt})(j=Fi(j)),De=qt(ne,De),Ri([],[$],function(Nt){var Kt=`${(Nt=Nt[0]).name}.${j}`;function di(){Ls(`Cannot call ${Kt} due to unbound types`,ft)}j.startsWith("@@")&&(j=Symbol[j.substring(2)]),qe&&Nt.registeredClass.pureVirtualFunctions.push(j);var Bt=Nt.registeredClass.instancePrototype,Jt=Bt[j];return Jt===void 0||Jt.overloadTable===void 0&&Jt.className!==Nt.name&&Jt.argCount===RA-2?(di.argCount=RA-2,di.className=Nt.name,Bt[j]=di):(Vo(Bt,j,Kt),Bt[j].overloadTable[RA-2]=di),Ri([],ft,function($i){var eo=ur(Kt,$i,Nt,De,Ke);return Bt[j].overloadTable===void 0?(eo.argCount=RA-2,Bt[j]=eo):Bt[j].overloadTable[RA-2]=eo,[]}),[]})},k:($,j,RA,ZA,ne,De,Ke,qe,Et,ft)=>{j=Fi(j),ne=qt(ZA,ne),Ri([],[$],function(Nt){var Kt=`${(Nt=Nt[0]).name}.${j}`,di={get(){Ls(`Cannot access ${Kt} due to unbound types`,[RA,Ke])},enumerable:!0,configurable:!0};return di.set=Et?()=>Ls(`Cannot access ${Kt} due to unbound types`,[RA,Ke]):Bt=>Ai(Kt+" is a read-only property"),Object.defineProperty(Nt.registeredClass.instancePrototype,j,di),Ri([],Et?[RA,Ke]:[RA],function(Bt){var Jt=Bt[0],$i={get(){var os=Fn(this,Nt,Kt+" getter");return Jt.fromWireType(ne(De,os))},enumerable:!0};if(Et){Et=qt(qe,Et);var eo=Bt[1];$i.set=function(os){var Ti=Fn(this,Nt,Kt+" setter"),on=[];Et(ft,Ti,eo.toWireType(on,os)),Un(on)}}return Object.defineProperty(Nt.registeredClass.instancePrototype,j,$i),[]}),[]})},t:($,j)=>{pn($,{name:j=Fi(j),fromWireType:RA=>{var ZA=ts.toValue(RA);return es(RA),ZA},toWireType:(RA,ZA)=>ts.toHandle(ZA),argPackAdvance:8,readValueFromPointer:Er,destructorFunction:null})},p:($,j,RA)=>{pn($,{name:j=Fi(j),fromWireType:ZA=>ZA,toWireType:(ZA,ne)=>ne,argPackAdvance:8,readValueFromPointer:ot(j,RA),destructorFunction:null})},g:($,j,RA,ZA,ne)=>{j=Fi(j);var De=Et=>Et;if(ZA===0){var Ke=32-8*RA;De=Et=>Et<>>Ke}var qe=j.includes("unsigned");pn($,{name:j,fromWireType:De,toWireType:qe?function(Et,ft){return this.name,ft>>>0}:function(Et,ft){return this.name,ft},argPackAdvance:8,readValueFromPointer:Zt(j,RA,ZA!==0),destructorFunction:null})},a:($,j,RA)=>{var ZA=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][j];function ne(De){var Ke=vA[De>>2],qe=vA[De+4>>2];return new ZA(gA.buffer,qe,Ke)}pn($,{name:RA=Fi(RA),fromWireType:ne,argPackAdvance:8,readValueFromPointer:ne},{ignoreDuplicateRegistrations:!0})},o:($,j)=>{var RA=(j=Fi(j))==="std::string";pn($,{name:j,fromWireType(ZA){var ne,De=vA[ZA>>2],Ke=ZA+4;if(RA)for(var qe=Ke,Et=0;Et<=De;++Et){var ft=Ke+Et;if(Et==De||eA[ft]==0){var Nt=WI(qe,ft-qe);ne===void 0?ne=Nt:(ne+="\0",ne+=Nt),qe=ft+1}}else{var Kt=new Array(De);for(Et=0;Et{for(var di=0,Bt=0;Bt=55296&&Jt<=57343?(di+=4,++Bt):di+=3}return di})(ne):ne.length;var qe=Tn(4+De+1),Et=qe+4;if(vA[qe>>2]=De,RA&&Ke)((Kt,di,Bt,Jt)=>{if(!(Jt>0))return 0;for(var $i=Bt,eo=Bt+Jt-1,os=0;os=55296&&Ti<=57343&&(Ti=65536+((1023&Ti)<<10)|1023&Kt.charCodeAt(++os)),Ti<=127){if(Bt>=eo)break;di[Bt++]=Ti}else if(Ti<=2047){if(Bt+1>=eo)break;di[Bt++]=192|Ti>>6,di[Bt++]=128|63&Ti}else if(Ti<=65535){if(Bt+2>=eo)break;di[Bt++]=224|Ti>>12,di[Bt++]=128|Ti>>6&63,di[Bt++]=128|63&Ti}else{if(Bt+3>=eo)break;di[Bt++]=240|Ti>>18,di[Bt++]=128|Ti>>12&63,di[Bt++]=128|Ti>>6&63,di[Bt++]=128|63&Ti}}di[Bt]=0})(ne,eA,Et,De+1);else if(Ke)for(var ft=0;ft255&&(_s(Et),Ai("String has UTF-16 code units that do not fit in 8 bits")),eA[Et+ft]=Nt}else for(ft=0;ft{var ZA,ne,De,Ke,qe;RA=Fi(RA),j===2?(ZA=ro,ne=Mc,Ke=cg,De=()=>IA,qe=1):j===4&&(ZA=Rg,ne=Qa,Ke=Fo,De=()=>vA,qe=2),pn($,{name:RA,fromWireType:Et=>{for(var ft,Nt=vA[Et>>2],Kt=De(),di=Et+4,Bt=0;Bt<=Nt;++Bt){var Jt=Et+4+Bt*j;if(Bt==Nt||Kt[Jt>>qe]==0){var $i=ZA(di,Jt-di);ft===void 0?ft=$i:(ft+="\0",ft+=$i),di=Jt+j}}return _s(Et),ft},toWireType:(Et,ft)=>{typeof ft!="string"&&Ai(`Cannot pass non-string to C++ string type ${RA}`);var Nt=Ke(ft),Kt=Tn(4+Nt+j);return vA[Kt>>2]=Nt>>qe,ne(ft,Kt+4,Nt+j),Et!==null&&Et.push(_s,Kt),Kt},argPackAdvance:8,readValueFromPointer:Er,destructorFunction(Et){_s(Et)}})},v:($,j)=>{pn($,{isVoid:!0,name:j=Fi(j),argPackAdvance:0,fromWireType:()=>{},toWireType:(RA,ZA)=>{}})},j:($,j,RA)=>($=ts.toValue($),j=Aa(j,"emval::as"),Uo(j,RA,$)),e:($,j,RA,ZA,ne)=>{var De,Ke;return($=Xs[$])(j=ts.toValue(j),j[RA=(Ke=Zc[De=RA])===void 0?Fi(De):Ke],ZA,ne)},d:es,f:($,j,RA)=>{var ZA=((ft,Nt)=>{for(var Kt=new Array(ft),di=0;di>2],"parameter "+di);return Kt})($,j),ne=ZA.shift();$--;var De,Ke,qe=new Array($),Et=`methodCaller<(${ZA.map(ft=>ft.name).join(", ")}) => ${ne.name}>`;return De=an(Et,(ft,Nt,Kt,di)=>{for(var Bt=0,Jt=0;Jt<$;++Jt)qe[Jt]=ZA[Jt].readValueFromPointer(di+Bt),Bt+=ZA[Jt].argPackAdvance;var $i=RA===1?is(Nt,qe):Nt.apply(ft,qe);for(Jt=0;Jt<$;++Jt)ZA[Jt].deleteObject&&ZA[Jt].deleteObject(qe[Jt]);return Uo(ne,Kt,$i)}),Ke=Xs.length,Xs.push(De),Ke},c:$=>{$>4&&(fo.get($).refcount+=1)},b:$=>{var j=ts.toValue($);Un(j),es($)},h:($,j)=>{var RA=($=Aa($,"_emval_take_value")).readValueFromPointer(j);return ts.toHandle(RA)},m:()=>{Xe("")},s:($,j,RA)=>eA.copyWithin($,j,j+RA),r:$=>{eA.length,Xe("OOM")},n:($,j,RA,ZA)=>{for(var ne=0,De=0;De>2],qe=vA[j+4>>2];j+=8;for(var Et=0;Et>2]=ne,0}},Qs=function(){var $={a:Fa};function j(RA,ZA){var ne,De;return Qs=RA.exports,_=Qs.z,ne=_.buffer,I.HEAP8=gA=new Int8Array(ne),I.HEAP16=CA=new Int16Array(ne),I.HEAPU8=eA=new Uint8Array(ne),I.HEAPU16=IA=new Uint16Array(ne),I.HEAP32=oA=new Int32Array(ne),I.HEAPU32=vA=new Uint32Array(ne),I.HEAPF32=qA=new Float32Array(ne),I.HEAPF64=Ae=new Float64Array(ne),qi=Qs.C,De=Qs.A,WA.unshift(De),function(){if(we--,I.monitorRunDependencies&&I.monitorRunDependencies(we),we==0&&et){var Ke=et;et=null,Ke()}}(),Qs}if(we++,I.monitorRunDependencies&&I.monitorRunDependencies(we),I.instantiateWasm)try{return I.instantiateWasm($,j)}catch(RA){b(`Module.instantiateWasm callback failed with error: ${RA}`),c(RA)}return ii(0,ae,$,function(RA){j(RA.instance)}).catch(c),{}}(),Tn=$=>(Tn=Qs.B)($),pa=$=>(pa=Qs.D)($),_s=$=>(_s=Qs.E)($),Oa=$=>(Oa=Qs.F)($);I.dynCall_jiji=($,j,RA,ZA,ne)=>(I.dynCall_jiji=Qs.G)($,j,RA,ZA,ne),I._vertexShaderSource=10688;function Ta(){function $(){ws||(ws=!0,I.calledRun=!0,HA||(ki(WA),n(I),I.onRuntimeInitialized&&I.onRuntimeInitialized(),function(){if(I.postRun)for(typeof I.postRun=="function"&&(I.postRun=[I.postRun]);I.postRun.length;)Pe(I.postRun.shift());ki(Ye)}()))}we>0||(function(){if(I.preRun)for(typeof I.preRun=="function"&&(I.preRun=[I.preRun]);I.preRun.length;)We(I.preRun.shift());ki(se)}(),we>0||(I.setStatus?(I.setStatus("Running..."),setTimeout(function(){setTimeout(function(){I.setStatus("")},1),$()},1)):$()))}if(et=function $(){ws||Ta(),ws||(et=$)},I.preInit)for(typeof I.preInit=="function"&&(I.preInit=[I.preInit]);I.preInit.length>0;)I.preInit.pop()();return Ta(),i.ready}})(),AlA=$cA,C3=0,l7=class I7{constructor(i){this.core=i,jL(this,"seq"),jL(this,"_core"),jL(this,"log"),jL(this,"beautyParams"),C3+=1,this.seq=C3,this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${C3}`}),this.log.info("created")}getName(){return I7.Name}getAlias(){return"bb"}getValidateRule(i){switch(i){case"start":case"update":return ZcA(this._core);case"stop":return XcA(this._core)}}getGroup(){return"bb"}async start(i){this._core.room.videoManager.Wasm||(this._core.room.videoManager.Wasm=await AlA()),this._core.room.videoManager.renderMode="webgl";const n=this._core.utils.isUndefined(i.beauty)?.5:i.beauty,c=this._core.utils.isUndefined(i.brightness)?.5:i.brightness,I=this._core.utils.isUndefined(i.ruddy)?.5:i.ruddy;return this._core.room.videoManager.setBeautyParams({beauty:n,brightness:c,ruddy:I})}async update(i){const n=this._core.utils.isUndefined(i.beauty)?.5:i.beauty,c=this._core.utils.isUndefined(i.brightness)?.5:i.brightness,I=this._core.utils.isUndefined(i.ruddy)?.5:i.ruddy;return this._core.room.videoManager.setBeautyParams({beauty:n,brightness:c,ruddy:I})}async stop(){return this._core.room.videoManager.renderMode="auto",this._core.room.videoManager.stopBeauty()}destroy(){this._core.room.videoManager.renderMode="auto"}};jL(l7,"Name","BasicBeauty");var u7=l7,elA=u7;const tlA=Object.freeze(Object.defineProperty({__proto__:null,BasicBeauty:u7,default:elA},Symbol.toStringTag,{value:"Module"})),ilA=$U(tlA);var olA=Object.defineProperty,nlA=(e,i,n)=>i in e?olA(e,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[i]=n,MY=(e,i,n)=>nlA(e,typeof i!="symbol"?i+"":i,n),slA={name:"option",required:!0,properties:{sourceLanguage:{type:"string",required:!0},translationLanguages:{type:["string","array"],required:!1},userIdsToTranscribe:{type:["string","array"],required:!1},transcriberRobotId:{type:"string",required:!1}}},rlA={name:"option",required:!0,properties:{transcriberRobotId:{type:"string",required:!0}}},alA=new Set([2002,4003]),E7=class d7{constructor(i){this.core=i,MY(this,"disableRandomCall",!0),MY(this,"activeTranscriberMap",new Map),MY(this,"_log"),this._log=this.core.log.createChild({id:`${this.getAlias()}`})}getName(){return d7.Name}getAlias(){return"rt-trans"}getGroup(){return"*"}getValidateRule(i){switch(i){case"start":return slA;case"update":return{};case"stop":return rlA}}async start(i){var n;const{RtcError:c,ErrorCode:I}=this.core.errorModule;if(!this.core.room.sendSignalMessage)throw new c({code:I.ENV_NOT_SUPPORTED});const{sourceLanguage:C,translationLanguages:m,userIdsToTranscribe:R="all",transcriberRobotId:_}=i,T=_||`transcriber_${this.core.room.roomId}_robot_${this.core.room.userId}`,b={sdkappid:this.core.room.sdkAppId,roomid:String(this.core.room.roomId),roomType:this.core.room.useStringRoomId?1:0,agentParam:{cdnRobotUserid:T,lifecycleUserid:this.core.room.userId,maxIdletime:30},subscribeParams:{subUsers:[]},asrParams:{lang:C,vadSilenceTime:1e3},translationParams:{mode:1,targetLangs:[""]}};m&&m.length>0&&(b.translationParams.mode=1,b.translationParams.targetLangs=Array.isArray(m)?m:[m]),R==="all"?b.subscribeParams.subUsers=[]:Array.isArray(R)?b.subscribeParams.subUsers=R.map(J=>({userId:J,roomType:this.core.room.useStringRoomId?1:0,roomid:String(this.core.room.roomId)})):R&&(b.subscribeParams.subUsers=[{userId:R,roomType:this.core.room.useStringRoomId?1:0,roomid:String(this.core.room.roomId)}]);try{this._log.info(`start_cloud_transcription ${JSON.stringify(b)}`);const J=await this.core.room.sendSignalMessage({command:"start_cloud_transcription",responseCommand:String(8268),data:b,retries:0}),{code:gA,data:eA}=J.data;if(gA!==0){const IA=((n=J.data)==null?void 0:n.message)||"";throw this._log.error("start_cloud_transcription failed",{extraCode:gA,reason:IA,data:eA}),new c({code:I.SERVER_ERROR,extraCode:gA,message:IA})}const{taskId:CA}=eA;if(!CA)throw this._log.error("taskId is required",{data:J.data}),new c({code:I.SERVER_ERROR,message:"taskId is required"});return this.activeTranscriberMap.set(CA,i),this._log.info(`start_cloud_transcription success ${CA}, activeSize: ${this.activeTranscriberMap.size}`),CA}catch(J){throw this._log.error("start_cloud_transcription failed",{error:J}),J}}async update(){}async stop({transcriberRobotId:i}){var n;const{RtcError:c,ErrorCode:I}=this.core.errorModule;if(!this.core.room.sendSignalMessage)throw new c({code:I.ENV_NOT_SUPPORTED});try{const C=await this.core.room.sendSignalMessage({command:"stop_cloud_transcription",responseCommand:String(8270),data:{taskId:i},retries:3});if(C.data.code!==0){const m=C.data.code,R=((n=C.data)==null?void 0:n.message)||"";if(!alA.has(m))throw this._log.error("stop_cloud_transcription failed",{extraCode:m,reason:R,data:C.data.data}),new c({code:I.SERVER_ERROR,extraCode:m,message:R});this._log.warn("stop_cloud_transcription ignored error",{extraCode:m,reason:R,data:C.data.data})}this.activeTranscriberMap.delete(i)}catch(C){throw this._log.error("stop_cloud_transcription failed",{error:C}),C}}destroy(){this.activeTranscriberMap.clear()}};MY(E7,"Name","RealtimeTranscriber");var C7=E7,glA=C7;const clA=Object.freeze(Object.defineProperty({__proto__:null,RealtimeTranscriber:C7,default:glA},Symbol.toStringTag,{value:"Module"})),llA=$U(clA);var IlA=Object.create,tF=Object.defineProperty,ulA=Object.defineProperties,h7=Object.getOwnPropertyDescriptor,ElA=Object.getOwnPropertyDescriptors,B7=Object.getOwnPropertyNames,JY=Object.getOwnPropertySymbols,dlA=Object.getPrototypeOf,D4=Object.prototype.hasOwnProperty,Q7=Object.prototype.propertyIsEnumerable,CW=(e,i,n)=>i in e?tF(e,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[i]=n,ks=(e,i)=>{for(var n in i||(i={}))D4.call(i,n)&&CW(e,n,i[n]);if(JY)for(var n of JY(i))Q7.call(i,n)&&CW(e,n,i[n]);return e},cB=(e,i)=>ulA(e,ElA(i)),ClA=(e,i)=>{var n={};for(var c in e)D4.call(e,c)&&i.indexOf(c)<0&&(n[c]=e[c]);if(e!=null&&JY)for(var c of JY(e))i.indexOf(c)<0&&Q7.call(e,c)&&(n[c]=e[c]);return n},iF=(e,i)=>function(){return i||(0,e[B7(e)[0]])((i={exports:{}}).exports,i),i.exports},S4=(e,i)=>{for(var n in i)tF(e,n,{get:i[n],enumerable:!0})},hlA=(e,i,n,c)=>{if(i&&typeof i=="object"||typeof i=="function")for(let I of B7(i))D4.call(e,I)||I===n||tF(e,I,{get:()=>i[I],enumerable:!(c=h7(i,I))||c.enumerable});return e},MT=(e,i,n)=>(n=e!=null?IlA(dlA(e)):{},hlA(tF(n,"default",{value:e,enumerable:!0}),e)),yc=(e,i,n,c)=>{for(var I,C=h7(i,n),m=e.length-1;m>=0;m--)(I=e[m])&&(C=I(i,n,C)||C);return C&&tF(i,n,C),C},pe=(e,i,n)=>CW(e,typeof i!="symbol"?i+"":i,n),oF=iF({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(e,i){var n=Object.prototype.hasOwnProperty,c="~";function I(){}function C(T,b,J){this.fn=T,this.context=b,this.once=J||!1}function m(T,b,J,gA,eA){if(typeof J!="function")throw new TypeError("The listener must be a function");var CA=new C(J,gA||T,eA),IA=c?c+b:b;return T._events[IA]?T._events[IA].fn?T._events[IA]=[T._events[IA],CA]:T._events[IA].push(CA):(T._events[IA]=CA,T._eventsCount++),T}function R(T,b){--T._eventsCount===0?T._events=new I:delete T._events[b]}function _(){this._events=new I,this._eventsCount=0}Object.create&&(I.prototype=Object.create(null),new I().__proto__||(c=!1)),_.prototype.eventNames=function(){var T,b,J=[];if(this._eventsCount===0)return J;for(b in T=this._events)n.call(T,b)&&J.push(c?b.slice(1):b);return Object.getOwnPropertySymbols?J.concat(Object.getOwnPropertySymbols(T)):J},_.prototype.listeners=function(T){var b=c?c+T:T,J=this._events[b];if(!J)return[];if(J.fn)return[J.fn];for(var gA=0,eA=J.length,CA=new Array(eA);gA1&&(m[_[0]]=void 0),m};e.parseParams=function(m){return m.split(/;\s?/).reduce(C,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(m){return m.toString().split(" ").map(Number)},e.parseRemoteCandidates=function(m){for(var R=[],_=m.split(" ").map(i),T=0;T<_.length;T+=3)R.push({component:_[T],ip:_[T+1],port:_[T+2]});return R},e.parseImageAttributes=function(m){return m.split(" ").map(function(R){return R.substring(1,R.length-1).split(",").reduce(C,{})})},e.parseSimulcastStreamList=function(m){return m.split(";").map(function(R){return R.split(",").map(function(_){var T,b=!1;return _[0]!=="~"?T=i(_):(T=i(_.substring(1,_.length)),b=!0),{scid:T,paused:b}})})}}}),QlA=iF({"../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/writer.js"(e,i){var n=v4(),c=/%[sdv%]/g,I=function(_){var T=1,b=arguments,J=b.length;return _.replace(c,function(gA){if(T>=J)return gA;var eA=b[T];switch(T+=1,gA){case"%%":return"%";case"%s":return String(eA);case"%d":return Number(eA);case"%v":return""}})},C=function(_,T,b){var J=[_+"="+(T.format instanceof Function?T.format(T.push?b:b[T.name]):T.format)];if(T.names)for(var gA=0;gA({type:"object",required:i,properties:{canvasColor:{required:!1,type:["string",CanvasGradient,CanvasPattern]},width:{required:!0,type:"number",notLessThanZero:!0,min:1,max:3840},height:{required:!0,type:"number",notLessThanZero:!0,min:1,max:3840},frameRate:{required:!1,type:"number",notLessThanZero:!0,min:1,max:60}},validate(n,c,I){const{RtcError:C,ErrorCode:m,ErrorCodeDictionary:R}=e.errorModule;if(!n)return;const{width:_,height:T}=n;if(_&&T&&_*T>8294400)throw new C({code:m.INVALID_PARAMETER,message:"The mix resolution cannot be set higher than 3840 * 2160."})}}),m7=e=>({required:!1,type:["string",HTMLElement,null],validate(i,n,c){const{RtcError:I,ErrorCode:C,ErrorCodeDictionary:m}=e.errorModule;if(e.utils.isString(i)&&!document.getElementById(i))throw new I({code:C.INVALID_PARAMETER,extraCode:m.INVALID_ELEMENT_ID,fnName:c,messageParams:{key:n}})}}),nF=(e,i=!0)=>({type:"object",required:i,properties:ks({},mlA),validate(n,c,I){const{RtcError:C,ErrorCode:m,ErrorCodeDictionary:R}=e.errorModule;if(n){if(n.fillMode&&!["contain","cover","fill"].includes(n.fillMode))throw new C({code:m.INVALID_PARAMETER,extraCode:R.INVALID_PARAMETER_TYPE,message:"The fillMode parameter must be 'contain', 'cover' or 'fill'",fnName:I});if(n.rotation&&![0,90,180,270].includes(n.rotation))throw new C({code:m.INVALID_PARAMETER,extraCode:R.INVALID_PARAMETER_TYPE,message:"The rotation parameter must be 0, 90, 180 or 270",fnName:I})}}}),f7=e=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},cameraId:{required:!1,type:"string"},videoTrack:{required:!1,instanceof:MediaStreamTrack},profile:{required:!1,type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},layout:ks({},nF(e))}}}),y7=e=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},profile:{required:!1,type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},captureElement:{required:!1,type:HTMLElement},preferDisplaySurface:{required:!1,type:"string"},layout:ks({},nF(e))},validate(i,n,c){const{RtcError:I,ErrorCode:C,ErrorCodeDictionary:m}=e.errorModule;if(!e.rtcDectection.isScreenCaptureApiAvailable())throw new I({code:C.ENV_NOT_SUPPORTED,fnName:c,extraCode:m.NOT_SUPPORTED_SCREEN_SHARE})}}}),D7=e=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},content:{required:!0,type:"string"},font:{required:!1,type:"string"},color:{required:!1,type:["string",CanvasGradient,CanvasPattern]},layout:ks({},nF(e))}}}),S7=e=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},url:{required:!0,type:"string"},layout:ks({},nF(e))}}}),v7=e=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},url:{required:!0,type:"string"},layout:ks({},nF(e))}}});function flA(e){return{name:"VideoMixerOptions",type:"object",required:!0,allowEmpty:!1,properties:{view:ks({},m7(e)),canvasInfo:ks({},p7(e,!0)),camera:ks({},f7(e)),screen:ks({},y7(e)),text:ks({},D7(e)),image:ks({},S7(e)),video:ks({},v7(e))},validate(i,n,c,I){const{RtcError:C,ErrorCode:m,ErrorCodeDictionary:R}=e.errorModule;if(e.environment.isMobile())throw new C({code:m.ENV_NOT_SUPPORTED,message:"VideoMixer is not supported on mobile devices currently"});const{onScreenShareStop:_}=i;if(_&&!e.utils.isFunction(_))throw new C({code:m.INVALID_PARAMETER,extraCode:R.INVALID_PARAMETER_TYPE,fnName:c,messageParams:{key:"onScreenShareStop",value:typeof _,rule:{type:"Function"}}})}}}function ylA(e){return{name:"VideoMixerOptions",type:"object",required:!1,allowEmpty:!1,properties:{view:ks({},m7(e)),canvasInfo:ks({},p7(e)),camera:ks({},f7(e)),screen:ks({},y7(e)),text:ks({},D7(e)),image:ks({},S7(e)),video:ks({},v7(e))}}}function DlA(e){return{name:"StopVideoMixerOptions",required:!1}}var M7=(e=>(e[e.INVALID_PARAMETER=4096]="INVALID_PARAMETER",e[e.INVALID_OPERATION=4097]="INVALID_OPERATION",e[e.NOT_SUPPORTED=4098]="NOT_SUPPORTED",e[e.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",e[e.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",e[e.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",e[e.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",e[e.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",e[e.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",e[e.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",e[e.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",e[e.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",e[e.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",e[e.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",e[e.CLIENT_BANNED=16448]="CLIENT_BANNED",e[e.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",e[e.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",e[e.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",e[e.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",e[e.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",e[e.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",e[e.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",e[e.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",e[e.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",e[e.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",e[e.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",e[e.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",e[e.API_CALL_ABORTED=16461]="API_CALL_ABORTED",e[e.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",e[e.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",e[e.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",e[e.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",e[e.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",e[e.UNKNOWN=65535]="UNKNOWN",e))(M7||{}),Zg=M7,SlA=function(e){for(const i in Zg)if(Zg[i]===e)return i;return"UNKNOWN"},vlA=class extends Error{constructor({name:e="RtcError",message:i,code:n=Zg.UNKNOWN,extraCode:c=0,constraint:I}){const C=`<${SlA(n)} 0x${n.toString(16)}>`,m=`${i}${I?` constraint: ${I}`:""}${i?.includes(C)?"":` ${C}`}`;super(m),pe(this,"code"),pe(this,"extraCode"),pe(this,"message"),pe(this,"originMessage"),pe(this,"name"),pe(this,"constraint"),this.code=n,this.extraCode=c,this.name=e,this.message=m,this.constraint=I,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},vl=vlA,MlA=0,M4=function(){return Date.now()+MlA},R7=function(){const e=new Date;return e.setTime(M4()),e.toLocaleString()},RlA=function(e){let i=String(e.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`},wlA={};S4(wlA,{REPORT_TYPE:()=>W7,buildSSOPackage:()=>T4,bytes2ms:()=>iIA,calculateScaleResolutionDownNumber:()=>K7,concatArrayBuffers:()=>RIA,convertObjectNumberToInt:()=>J7,copyProperties:()=>tIA,deepClone:()=>jY,deepCloneBasic:()=>SW,deepMerge:()=>Y7,delay:()=>QT,fibonacci:()=>_4,formatedTime:()=>mIA,getConstructorName:()=>gIA,getContainerFromElement:()=>QIA,getEnv:()=>WlA,getFirst16Bits:()=>_IA,getInternalVersion:()=>uIA,getLast16Bits:()=>wIA,getLoggerUrl:()=>R4,getMediaStreamTrackInfo:()=>SIA,getMuteStateFromFlag:()=>x7,getNetworkType:()=>w4,getNumNetworkType:()=>eIA,getReconnectionTimeout:()=>sIA,getStringByteLength:()=>fIA,getTestSignalDomain:()=>ZlA,getTurnServer:()=>CIA,getUint32Version:()=>H7,getValueType:()=>xM,getViewListFromView:()=>BIA,glog:()=>nIA,ipv4ToUint32:()=>hIA,isArray:()=>oh,isAudioWorkletSupported:()=>cIA,isBoolean:()=>TM,isConstructor:()=>P7,isEmpty:()=>dIA,isFunction:()=>_M,isLangChinese:()=>iD,isMediaStreamTrack:()=>rIA,isNumber:()=>YM,isObject:()=>SM,isOverseaSdkAppId:()=>KY,isPlainObject:()=>BT,isPortrait:()=>V7,isPromise:()=>O7,isRemoteTrack:()=>aIA,isRotate90Or270:()=>j7,isSetSinkIdSupported:()=>lIA,isString:()=>rh,isUndefined:()=>sr,isVideoMixerOutputTrack:()=>N4,loadImage:()=>yIA,loadVideo:()=>vIA,ms2bytes:()=>oIA,ms2samples:()=>F7,normalizeUrl:()=>DIA,performanceNow:()=>Wc,promiseAny:()=>IIA,samples2ms:()=>U7,setNetworkTypeFromWebRTC:()=>AIA,stringify:()=>oD,stringifyIncludeValue:()=>DW,throttlePromise:()=>q7});var qY="5.0.0",w7=typeof importScripts<"u",_7=typeof registerProcessor<"u",_lA="web.sdk.qcloud.com",hW=`https://${_lA}/trtc/webrtc/doc`,xZ="https://cloud.tencent.com/document/product/647/85386",YZ="https://trtc.io/document/56025",TlA="https://yun.tim.qq.com",NlA="https://apisgp.my-imcloud.com",GlA="trtc_error_assistance",T7={LOG:"jssdk_log"},h3={QCLOUD:"qcloud"},Y_=(e=>(e[e.TRACE=0]="TRACE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.NONE=5]="NONE",e))(Y_||{}),N7={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},blA=6048e5,klA={"480p_2":{width:640,height:480,frameRate:15,bitrate:500}},LlA=klA["480p_2"],ni={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADSTART:"loadstart",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",FULLSCREEN_CHANGE:"fullscreenchange",RESIZE:"resize",TIME_UPDATE:"timeupdate"},VZ=1,UlA=2,FlA=4,HZ=8,JZ=64,qZ=16,OlA=256,CU={PLAYER_ERROR:"player-error",LOAD_WORKLET:"load-worklet",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},PlA="unified-plan",V_=5,G7="default",iY=2e3,b7=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],xlA={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},YlA=function(e,i,n,c){return new(n||(n=Promise))(function(I,C){function m(T){try{_(c.next(T))}catch(b){C(b)}}function R(T){try{_(c.throw(T))}catch(b){C(b)}}function _(T){var b;T.done?I(T.value):(b=T.value,b instanceof n?b:new n(function(J){J(b)})).then(m,R)}_((c=c.apply(e,[])).next())})},BW=Symbol(32),QW=Symbol(16),pW=Symbol(8),rT=class{constructor(e){this.g=e,this.consumed=0,e&&(this.need=e.next().value)}setG(e){this.g=e,this.demand(e.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(e,i){return i&&this.consume(),this.need=e,this.flush()}read(e){return YlA(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((i,n)=>{var c;this.reject=n,this.resolve=I=>{delete this.lastReadPromise,delete this.resolve,delete this.need,i(I)},this.demand(e,!0)||(c=this.pull)===null||c===void 0||c.call(this,e)})})}readU32(){return this.read(BW)}readU16(){return this.read(QW)}readU8(){return this.read(pW)}close(){var e;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(e=this.reject)===null||e===void 0||e.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let e=null;const i=this.buffer.subarray(this.consumed);let n=0;const c=I=>i.length<(n=I);if(typeof this.need=="number"){if(c(this.need))return;e=i.subarray(0,n)}else if(this.need===BW){if(c(4))return;e=i[0]<<24|i[1]<<16|i[2]<<8|i[3]}else if(this.need===QW){if(c(2))return;e=i[0]<<8|i[1]}else if(this.need===pW){if(c(1))return;e=i[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(c(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(i.subarray(0,n)),e=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(c(this.need.byteLength))return;new Uint8Array(this.need).set(i.subarray(0,n)),e=this.need}return this.consumed+=n,this.g?this.demand(this.g.next(e).value,!0):this.resolve&&this.resolve(e),e}write(e){if(e instanceof Uint8Array?this.malloc(e.length).set(e):"buffer"in e?this.malloc(e.byteLength).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):this.malloc(e.byteLength).set(new Uint8Array(e)),!this.g&&!this.resolve)return new Promise(i=>this.pull=i);this.flush()}writeU32(e){this.malloc(4).set([e>>24&255,e>>16&255,e>>8&255,255&e]),this.flush()}writeU16(e){this.malloc(2).set([e>>8&255,255&e]),this.flush()}writeU8(e){this.malloc(1)[0]=e,this.flush()}malloc(e){if(this.buffer){const i=this.buffer.length,n=i+e;if(n<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,n);else{const c=new Uint8Array(n);c.set(this.buffer),this.buffer=c}return this.buffer.subarray(i,n)}return this.buffer=new Uint8Array(e),this.buffer}};rT.U32=BW,rT.U16=QW,rT.U8=pW;var VlA=128;function B3(e){const i=new rT;for(;e>=128;)i.malloc(1)[0]=255&e|VlA,e>>>=7;return i.malloc(1)[0]=255&e,i.buffer||new Uint8Array(0)}function mW(e,i=0){const n=new rT,c=i<<3;switch(typeof e){case"boolean":const I=n.malloc(2);I[0]=c,I[1]=e?1:0;break;case"number":n.malloc(1)[0]=c,n.write(B3(e));break;case"string":n.malloc(1)[0]=2|c;const C=new TextEncoder().encode(e);n.write(B3(C.length));const m=n.malloc(C.length);for(let _=0;_>>24&255),this.buffer.push(e>>>16&255),this.buffer.push(e>>>8&255),this.buffer.push(255&e)}writeInt16(e){this.buffer.push(e>>>8&255),this.buffer.push(255&e)}writeByte(e){this.buffer.push(255&e)}writeBytes(e){for(let i=0;i>>24&255,e[n+1]=i>>>16&255,e[n+2]=i>>>8&255,e[n+3]=255&i}function ld(e,i){return e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]}function WZ(e,i){return e[i]}function kL(e,i,n){return new TextDecoder().decode(HlA(e,i,n))}function HlA(e,i,n){return e.slice(i,i+n)}var Q3=0,fW=2654435769,yW=16,zZ=4,hU=2,BU=7;function JlA(e,i,n,c="AVQualityReportSvc.C2S",I=2e3,C=2,m=30){return{version:I,encryption:C,d2:"",d2Len:0,uinType:m,uin:"",uinLen:0,reqHead:{seqNumber:n,appId:e,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:c,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:i}}function qlA(e,i){const n=new KZ,c=JlA(i,e,Q3);Q3=Q3+1&2147483647,n.writeInt32(0),n.writeInt32(c.version),n.writeByte(c.encryption);const I=new TextEncoder().encode(c.d2);n.writeInt32(I.length+4),I&&n.writeBytes(I),n.writeByte(c.uinType);const C=new TextEncoder().encode(c.uin);n.writeInt32(C.length+4),C.length&&n.writeBytes(C);const m=new KZ;m.writeInt32(0),m.writeInt32(c.reqHead.seqNumber),m.writeInt32(c.reqHead.appId),m.writeByte(c.reqHead.appId>>>24&255),m.writeByte(c.reqHead.appId>>>16&255),m.writeByte(c.reqHead.appId>>>8&255),m.writeByte(255&c.reqHead.appId);for(let qA=4;qA<16;qA++)m.writeByte(0);const R=new TextEncoder().encode(c.reqHead.a2);m.writeInt32(R.length+4),R.length&&m.writeBytes(R);const _=new TextEncoder().encode(c.reqHead.serviceCmd);m.writeInt32(_.length+4),_.length&&m.writeBytes(_);const T=new TextEncoder().encode(c.reqHead.cookie);m.writeInt32(T.length+4),T.length&&m.writeBytes(T);const b=new TextEncoder().encode(c.reqHead.imei);m.writeInt32(b.length+4),b.length&&m.writeBytes(b);const J=new TextEncoder().encode(c.reqHead.ksid);m.writeInt32(J.length+4),J.length&&m.writeBytes(J);const cA=new TextEncoder().encode(c.reqHead.clientVersionInfo);m.writeInt16(cA.length+2),cA.length&&m.writeBytes(cA);const eA=m.length;m.data[0]=eA>>>24&255,m.data[1]=eA>>>16&255,m.data[2]=eA>>>8&255,m.data[3]=255&eA,rh(e)&&(e=new TextEncoder().encode(e)),m.writeInt32(e.length+4),e.length&&m.writeBytes(e);let CA=new Uint8Array(m.data),IA=null;c.encryption===1?IA=new TextEncoder().encode(c.uin):c.encryption===2&&(IA=new Uint8Array(16)),IA&&(CA=KlA(CA,IA)),n.writeBytes(CA);const oA=new Uint8Array(n.data),vA=oA.length;return oA[0]=vA>>>24&255,oA[1]=vA>>>16&255,oA[2]=vA>>>8&255,oA[3]=255&vA,oA}function KlA(e,i){const n=e.length;let c=(n+1+hU+BU)%8;c&&(c=8-c);const I=new Uint8Array(n+1+hU+BU+c);let C=0;const m=new Uint8Array(8),R=new Uint8Array(8),_=new Uint8Array(8);let T=0;m[0]=248&Math.floor(256*Math.random())|c,T=1;for(let J=0;J>>=0,I+=(C<<4)+m[0]^C+R^(C>>>5)+m[1],I>>>=0,C+=(I<<4)+m[2]^I+R^(I>>>5)+m[3],C>>>=0;jZ(n,I,c),jZ(n,C,c+4)}var WlA=function(){return new URLSearchParams(location.search).get("trtc_env")||""},zlA=".rtc.qq.com",ZlA=function(e){return e.includes(".")?e:`${e}${zlA}`},KY=e=>Number(e)<14e8,R4=function(e,i){let n;return n=KY(e)?NlA:TlA,`${n}/v5/AVQualityReportSvc/C2S?random=${Math.floor(Math.random()*2**31)}&sdkappid=${e}&cmdtype=${i}`},k7="unknown";function w4(){$lA();const{userAgent:e,connection:i}=navigator;let n=(e.match(/NetType\/\S+/)||[])[0]||"";n=n.toLowerCase().replace("nettype/",""),n==="3gnet"&&(n="3g");const c=i&&i.type&&i.type.toLowerCase();let I=i&&i.effectiveType&&i.effectiveType.toLowerCase();return I==="slow-2"&&(I="2g"),c?L7(c,I):k7}function XlA(){An.warn("netType changed",w4())}var ZZ=!1;function $lA(){var e;ZZ||(ZZ=!0,(e=navigator.connection)==null||e.addEventListener("typechange",XlA))}function L7(e,i){if(N7[e])return e;switch(e){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";default:return"unknown"}}function AIA(e){k7=L7(e)}function eIA(){return N7[w4()]}function tIA(e,i){for(const n of Reflect.ownKeys(i))if(n!=="constructor"&&n!=="prototype"&&n!=="name"){const c=Object.getOwnPropertyDescriptor(i,n)||"";Object.defineProperty(e,n,c)}return e}function iIA(e,i=48e3){return U7(e/4,i)}function U7(e,i=48e3){return 1e3*e/i}function oIA(e,i=48e3){return 4*F7(e,i)}function F7(e,i=48e3){return e*i/1e3}var nIA=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},iD=()=>{let e=navigator.language;return e=e.substring(0,2),e==="zh"},BT=function(e){if(!e||typeof e!="object"||Object.prototype.toString.call(e)!="[object Object]")return!1;const i=Object.getPrototypeOf(e);if(i===null)return!0;const n=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof n=="function"&&n instanceof n&&Function.prototype.toString.call(n)===Function.prototype.toString.call(Object)};function _4(e,i=1,n=1){return e<=1?n:_4(e-1,n,i+n)}function sIA(e){return e>8?3e4:1e3*_4(e)}function xM(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var _M=e=>typeof e=="function",sr=e=>e===void 0,rh=e=>typeof e=="string",YM=e=>typeof e=="number",TM=e=>typeof e=="boolean",SM=e=>xM(e)==="object",oh=e=>xM(e)==="array",rIA=e=>xM(e)==="MediaStreamTrack".toLowerCase(),aIA=e=>e.isRemote,O7=e=>xM(e)==="promise",P7=e=>_M(e)&&e.prototype.constructor===e,gIA=e=>P7(e)?e.prototype.constructor.name:"",cIA=typeof AudioWorkletNode<"u",lIA=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype;function IIA(e){return new Promise((i,n)=>{const c=[];e.forEach(I=>{I.then(i).catch(C=>{c.push(C),c.length===e.length&&n(c)})})})}function Wc(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var XZ=e=>+e<10?`0${e}`:e,uIA=e=>{const i=e.match(/^\d+\.\d+\.\d+/)[0];if(!i)return e;const n=i.split("."),c=XZ(n[1])+XZ(n[2]);return n[1]-15>0&&(n[1]="15"),n[2]-15>0&&(n[2]="15"),`${n.join(".")}.${c}`},EIA=Object.prototype.hasOwnProperty;function dIA(e){if(e==null)return!0;if(typeof e=="boolean")return!1;if(typeof e=="number")return e===0;if(typeof e=="string"||typeof e=="function"||Array.isArray(e))return e.length===0;if(e instanceof Error)return e.message==="";if(BT(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return e.size===0;case"[object Object]":for(const i in e)if(EIA.call(e,i))return!1;return!0}return!1}function x7(e,i){return{userId:i,hasAudio:!!(e&HZ),hasVideo:!!(e&VZ),hasAuxiliary:!!(e&FlA),hasSmall:!!(e&UlA),audioMuted:!!(e&JZ),videoMuted:!!(e&qZ),audioAvailable:!(!(e&HZ)||e&JZ),videoAvailable:!(!(e&VZ)||e&qZ),hasDatachannel:!!(e&OlA)}}function CIA(e){const i={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:`turn:${e.url}`};return sr(e.username)||sr(e.credential)||(i.username=e.username,i.credential=e.credential,i.credentialType="password",sr(e.credentialType)||(i.credentialType=e.credentialType)),i}function hIA(e,i=!0){if(!rh(e))return 0;const n=e.split(".");return i?(Number(n[0])<<24|Number(n[1])<<16|Number(n[2])<<8|Number(n[3]))>>>0:(Number(n[3])<<24|Number(n[2])<<16|Number(n[1])<<8|Number(n[0]))>>>0}var Y7=function(e,i,n,c){if(!SM(e)||!SM(i))return 0;let I=0;const C=Object.keys(i);let m;for(let R=0,_=C.length;R<_;R++)if(m=C[R],!(sr(i[m])||n&&n.includes(m)))if(SM(e[m])&&SM(i[m]))I+=Y7(e[m],i[m],n,c);else{if(c&&c.includes(i[m]))continue;e[m]!==i[m]&&(e[m]=jY(i[m]),I+=1)}return I};function jY(e){if(oh(e)){const i=[];return e.forEach((n,c)=>{i[c]=jY(n)}),i}if(SM(e)){const i={};return Object.keys(e).forEach(n=>{i[n]=jY(e[n])}),i}return e}var BIA=e=>{let i=[];if(oh(e))i=[...e];else if(rh(e)){const n=document.getElementById(e);n&&i.push(n)}else e&&i.push(e);return i},QIA=e=>rh(e)?document.getElementById(e):e,pIA=e=>{const i=n=>n<10?`0${n}`:`${n}`;return`${e.getFullYear()}/${e.getMonth()+1}/${e.getDate()} ${i(e.getHours())}:${i(e.getMinutes())}:${i(e.getSeconds())}`},mIA=()=>pIA(new Date);function oD(e,{keysToInclude:i,keysToExclude:n}){try{if(oh(e))return`[${e.map(m=>oD(m,{keysToInclude:i,keysToExclude:n})).join(",")}]`;if(!BT(e)||!oh(i)&&!oh(n))return JSON.stringify(e);const c={},I=new Set(i),C=new Set(n);return Object.keys(e).forEach(m=>{(C.size===0&&I.has(m)||I.size===0&&!C.has(m))&&(c[m]=BT(e[m])||oh(e[m])?JSON.parse(oD(e[m],{keysToExclude:n,keysToInclude:i})):e[m])}),JSON.stringify(c)}catch{return"{}"}}function DW(e,i=!1){const n=[];return Object.keys(e).forEach(c=>{i===e[c]&&n.push(c)}),oD(e,{keysToInclude:n})}function fIA(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var V7=()=>{var e,i,n,c;return(e=window.screen)!=null&&e.orientation?!!((c=(n=(i=window.screen)==null?void 0:i.orientation)==null?void 0:n.type)!=null&&c.includes("portrait")):window.orientation===0||window.orientation===180},yIA=async e=>new Promise((i,n)=>{let c;if(rh(e))c=new Image,c.crossOrigin="anonymous",c.src=e;else if(c=e,c.complete)return void i(c);c.onload=()=>i(c),c.onerror=()=>{n(new vl({code:Zg.INVALID_PARAMETER,message:`load image failed, url: ${e}`}))}}),H7=e=>{const i=e.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]},J7=e=>(Object.keys(e).forEach(i=>{YM(e[i])&&(i.startsWith("uint")||i.startsWith("int"))?e[i]=Math.floor(e[i]):(BT(e[i])||oh(e[i]))&&J7(e[i])}),e);function QT(e,i){return new Promise(n=>{const c=setTimeout(n,e);i&&i(c)})}function q7(e,i){let n=null;return function(...c){return n||(n=e.apply(i||this,c),n.finally(()=>n=null),n)}}function DIA(e){return e.replace(/(^|[^:])\/{2,}/g,"$1/")}function SIA(e){var i;try{const{width:n,height:c,frameRate:I,sampleRate:C,sampleSize:m,channelCount:R}=(i=e.getSettings)==null?void 0:i.call(e),_=e.kind===ni.AUDIO?`${C}x${m}@${R}`:`${n}x${c}@${I}`,T=e.stats?` stats: ${JSON.stringify(e.stats).replaceAll('"',"")}`:"";return`${e.id} ${e.readyState} muted:${e.muted} ${e.kind} ${e.label} ${_}${T}`}catch{return""}}function K7(e,i){return e.width*e.height===i.width*i.height?1:V7()&&i.width>i.height&&e.height>i.width?Math.max(e.width/i.height,e.height/i.width,1):Math.max(e.width/i.width,e.height/i.height,1)}function j7(e){return e===90||e===270}async function vIA(e){return new Promise((i,n)=>{const c=document.createElement("video");c.crossOrigin="anonymous",c.src=e,c.muted=!0,c.loop=!0,c.playsInline=!0,c.play().then(()=>i(c)),c.onerror=()=>{n(c.error)}})}function SW(e,i=new WeakMap){if(typeof e!="object"||e===null)return e;if(i.has(e))return i.get(e);if(Array.isArray(e)){const n=[];return i.set(e,n),e.forEach((c,I)=>{n[I]=SW(c,i)}),n}if(Object.prototype.toString.call(e)==="[object Object]"){const n={};return i.set(e,n),Reflect.ownKeys(e).forEach(c=>{n[c]=SW(e[c],i)}),n}return e}var W7=(e=>(e[e.END_REPORT=2001]="END_REPORT",e[e.LOG=2002]="LOG",e[e.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",e))(W7||{});function MIA(e,i,n,c){let I={data:e,random:Math.floor(Math.random()*2147483648),sdkAppId:n};return sr(c)||(I=cB(ks({},I),{gzip:+c})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:i,bytes_report_data:JSON.stringify(I)}}}function T4(e,i,n,c){try{const I=MIA(e,i,n,c);return qlA(mW(I),n)}catch{return JSON.stringify(e)}}function RIA(e,i){const n=new Uint8Array(e.byteLength+i.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(i),e.byteLength),n.buffer}function wIA(e){return(65535&e)>>>0}function _IA(e){return(4294901760&e)>>>0}function N4(e){return!!(e&&e instanceof CanvasCaptureMediaStreamTrack&&e.canvas.id.includes("trtc_mix"))}function TIA(e){const i=NIA(e);return i?.busiBuff}function NIA(e){try{const i={};let n=0;i.totalLength=ld(e,n),n+=4,i.version=ld(e,n),n+=4,i.encryption=WZ(e,n),n+=1,i.uinType=WZ(e,n),n+=1,i.uinLength=ld(e,n),n+=4,i.uin=i.uinLength>4?kL(e,n,i.uinLength-4):"",n+=i.uinLength-4;const c=e.slice(n);if(i.encryption===2){const I=new Uint8Array(16).fill(0);e=GIA(c,I),i.decrypted=!0,n=0}else e=c,n=0;return i.rspHeadLength=ld(e,n),n+=4,i.seqNo=ld(e,n),n+=4,i.retCode=ld(e,n),n+=4,i.retStrLength=ld(e,n),n+=4,i.retStr=i.retStrLength?kL(e,n,i.retStrLength-4):"",n+=i.retStrLength-4,i.serviceCmdLength=ld(e,n),n+=4,i.serviceCmd=i.serviceCmdLength?kL(e,n,i.serviceCmdLength-4):"",n+=i.serviceCmdLength-4,i.cookieLength=ld(e,n),n+=4,i.cookie=i.cookieLength?kL(e,n,i.cookieLength-4):"",n+=i.cookieLength-4,i.flag=ld(e,n),n+=4,i.busiBuffLength=ld(e,n),n+=4,i.busiBuff=i.busiBuffLength?kL(e,n,i.busiBuffLength-4):"",n+=i.busiBuffLength-4,i}catch{}}function z7(e,i){let n=e[0]<<24|e[1]<<16|e[2]<<8|e[3],c=e[4]<<24|e[5]<<16|e[6]<<8|e[7];n>>>=0,c>>>=0;let I=fW*yW>>>0;for(let C=0;C>>5)+i[3],c>>>=0,n-=(c<>>5)+i[1],n>>>=0,I-=fW,I>>>=0;return new Uint8Array([n>>>24&255,n>>>16&255,n>>>8&255,255&n,c>>>24&255,c>>>16&255,c>>>8&255,255&c])}function GIA(e,i){let n=0;const c=new Uint8Array(8).fill(0);let I=z7(new Uint8Array(e.slice(0,8)),i);const C=7&I[0],m=e.length-1-C-hU-BU,R=new Uint8Array(m);let _=0,T=c,b=e.slice(0,8);n=8;let J=1;J+=C;for(let eA=1;eA<=hU;)if(J<8)J++,eA++;else if(J===8){const CA=m3(e,n,T,b,I,i);T=CA.ivPreCrypt,b=CA.ivCurCrypt,I=CA.debiBuf,n=CA.bufPos,J=0}let cA=m;for(;cA>0;)if(J<8)R[_++]=I[J]^T[J],J++,cA--;else if(J===8){const eA=m3(e,n,T,b,I,i);T=eA.ivPreCrypt,b=eA.ivCurCrypt,I=eA.debiBuf,n=eA.bufPos,J=0}for(let eA=1;eA<=BU;)if(J<8)I[J],T[J],J++,eA++;else if(J===8){if(n>=e.length)break;const CA=m3(e,n,T,b,I,i);if(!CA.success)break;T=CA.ivPreCrypt,b=CA.ivCurCrypt,I=CA.debiBuf,n=CA.bufPos,J=0}return R}function m3(e,i,n,c,I,C){if(i+8>e.length)return{success:!1};const m=new Uint8Array(c),R=e.slice(i,i+8),_=new Uint8Array(8);for(let T=0;T<8;T++)_[T]=I[T]^R[T];return{success:!0,ivPreCrypt:m,ivCurCrypt:R,debiBuf:z7(_,C),bufPos:i+8}}var $Z=typeof TextDecoder<"u"?new TextDecoder:void 0;function Z7({url:e,body:i,method:n="POST",timeout:c,priority:I}){return new Promise((C,m)=>{if("fetch"in window)return fetch(e,{method:n,body:i,priority:I}).then(_=>_.clone().json().then(T=>({data:T}),()=>_.arrayBuffer().then(T=>({data:TIA(new Uint8Array(T))||($Z?$Z.decode(T):T)})))).then(C,m);const R=new XMLHttpRequest;R.onreadystatechange=()=>{if(R.readyState===4)if(R.status>=200&&R.status<300)try{const _=JSON.parse(R.response);C({data:_})}catch{C({data:R.response})}else m({status:R.status,statusText:R.statusText||"request failed!"})},R.timeout=c||5e3,R.open(n,e,!0),R.send(i)})}var bIA=Object.prototype.hasOwnProperty,H_=e=>typeof e=="function",G_=e=>e===void 0,kIA=e=>typeof e=="boolean",f3=e=>e.isRemote,LIA=function(e){if(!e||typeof e!="object"||Object.prototype.toString.call(e)!="[object Object]")return!1;const i=Object.getPrototypeOf(e);if(i===null)return!0;const n=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof n=="function"&&n instanceof n&&Function.prototype.toString.call(n)===Function.prototype.toString.call(Object)};function UIA(e){if(e==null)return!0;if(typeof e=="boolean")return!1;if(typeof e=="number")return e===0;if(typeof e=="string"||typeof e=="function"||Array.isArray(e))return e.length===0;if(e instanceof Error)return e.message==="";if(LIA(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return e.size===0;case"[object Object]":for(const i in e)if(bIA.call(e,i))return!1;return!0}return!1}var FIA=0,OIA=1,A6=2;function PIA({retryFunction:e,settings:i,onError:n,onRetrying:c,onRetryFailed:I,onRetrySuccess:C,context:m}){return function(...R){const{retries:_=5,timeout:T=1e3}=i;let b=0,J=-1,cA=FIA;const eA=async(CA,IA)=>{const oA=m||this;try{const vA=await e.apply(oA,R);b>0&&C&&C.call(this,b),b=0,CA(vA)}catch(vA){const qA=()=>{clearTimeout(J),b=0,cA=A6,IA(vA)},Ae=()=>{cA!==A6&&b<(H_(_)?_():_)?(b++,cA=OIA,H_(c)&&c.call(this,b,qA),J=window.setTimeout(()=>{J=-1,eA(CA,IA)},H_(T)?T(b):T)):(qA(),H_(I)&&I.call(this,vA))};H_(n)?n.call(this,{error:vA,retry:Ae,reject:IA,retryFuncArgs:R,retriedCount:b}):Ae()}};return new Promise(eA)}}var G4=PIA,y3=class X7{constructor(i){pe(this,"_parentPath"),pe(this,"userId"),pe(this,"remoteUserId"),pe(this,"id"),pe(this,"sdkAppId"),pe(this,"type"),pe(this,"isLocal"),this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=!kIA(i.isLocal)||i.isLocal,this.type=this.isLocal?"":i.type}getFullId(){return this._parentPath&&this.id?`${this._parentPath}-${this.id}`:this._parentPath?this._parentPath:this.id}createChild(i){const n=new X7({id:i.id,userId:G_(i.userId)?this.userId:i.userId,sdkAppId:G_(i.sdkAppId)?this.sdkAppId:i.sdkAppId,type:G_(i.type)?this.type:i.type,isLocal:G_(i.isLocal)?this.isLocal:i.isLocal,remoteUserId:G_(i.remoteUserId)?this.remoteUserId:i.remoteUserId});return n.bindParent(this),n}bindParent(i){const n=i.getFullId();this._parentPath!==n&&(this.debug(`bind logger parent: ${i.id}`),this._parentPath=n,this.userId=i.userId||this.userId,this.sdkAppId=i.sdkAppId||this.sdkAppId)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,n){const c=this.isLocal?this.userId:this.remoteUserId,I=this.getFullId();n.unshift(`[${this.isLocal?"↑":"↓"}${this.type&&this.type!=="main"?"*":""}${I}${c?`|${c}`:""}]`),An.log(i,n,G_(this.userId)||UIA(this.userId),this.userId,this.sdkAppId)}info(...i){this.log(2,i)}debug(...i){this.log(1,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}},bQ=typeof navigator>"u"?"":navigator.userAgent,As=e=>new RegExp(e,"i").test(bQ),Sc=e=>{if(As(e)){const i=new RegExp(`${e}\\/([\\d.]+)`),n=bQ.match(i);if(n&&n[1])return n[1]}return""},PV=e=>{if(As(e)){const i=new RegExp(`${e}\\/(\\d+)`),n=bQ.match(i);if(n&&n[1])return parseFloat(n[1])}return NaN},e6=/AppleWebKit\/([\d.]+)/i.exec(bQ);e6&&parseFloat(e6[1]);var b4=As("iPad"),$7=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&As("Macintosh"),xV=As("iPhone")&&!b4,xIA=As("iPod"),_u=xV||b4||xIA||$7,WY=()=>{try{return _u&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch{return _u}},cC=As("Android"),A$=function(){if(cC){const e=bQ.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(e){const i=e[1]&&parseFloat(e[1]),n=e[2]&&parseFloat(e[2]);if(i&&n)return parseFloat(`${e[1]}.${e[2]}`);if(i)return i}}return NaN}();cC&&As("webkit")&&A$<2.3;var aC=As("Firefox"),e$=Sc("Firefox"),t$=PV("Firefox"),sF=As("Edge"),i$=Sc("Edge"),YV=As("Edg"),o$=Sc("Edg"),YIA=PV("Edg"),k4=As("SogouMobileBrowser"),n$=Sc("SogouMobileBrowser"),L4=As("MetaSr\\s"),s$=Sc("MetaSr\\s"),Sm=As("TBS"),r$=Sc("TBS"),RT=As("XWEB"),a$=Sc("XWEB");As("MSIE\\s8\\.0");var VIA=As("MSIE\\/\\d+");(function(){if(VIA){const e=/MSIE\s(\d+)\.\d/.exec(bQ);let i=e&&parseFloat(e[1]);return!i&&/Trident\/7.0/i.test(bQ)&&/rv:11.0/.test(bQ)&&(i=11),i}return NaN})();var rF=As("(micromessenger|webbrowser)"),g$=Sc("MicroMessenger"),VV=!Sm&&As("MQQBrowser")&&As("COVC"),HV=!Sm&&As("MQQBrowser")&&!As("COVC"),zY=HV||VV?Sc("MQQBrowser"):"",U4=!Sm&&As(" QQBrowser"),c$=Sc(" QQBrowser"),F4=!Sm&&As("QQBrowserLite"),l$=Sc("QQBrowserLite"),O4=!Sm&&As("MQBHD"),I$=Sc("MQBHD"),u$=As("Windows"),JV=!_u&&As("MAC OS X"),E$=!cC&&As("Linux"),d$=As("CrOS");As("MicroMessenger");var HIA=As("UCBrowser");As("Electron");var P4=As("MiuiBrowser"),C$=Sc("MiuiBrowser"),x4=As("HuaweiBrowser"),h$=As("Huawei")||As("HUAWEI"),JIA=As("Honor")||As("HONOR"),B$=Sc("HuaweiBrowser"),Y4=As("SamsungBrowser"),Q$=Sc("SamsungBrowser"),qV=As("HeyTapBrowser"),p$=Sc("HeyTapBrowser"),V4=As("VivoBrowser"),m$=Sc("VivoBrowser"),H4=As("OpenHarmony");Sc("OpenHarmony");var f$=()=>PV("Chrome"),ZY=As("CriOS"),lD=As("Chrome"),J4=!sF&&!L4&&!k4&&!Sm&&!RT&&!YV&&!U4&&!P4&&!x4&&!Y4&&!qV&&!V4&&lD,qIA=As("HeadlessChrome"),ID=f$(),D3=lD&&ID>=128&&ID<=143,y$=Sc("Chrome");PV("Electron");var ud=!lD&&!HV&&!VV&&!F4&&!O4&&As("Safari"),D$=ud||_u,aF=Sc("Version"),TQ=(()=>{if($7)return aF;if(_u){const e=bQ.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let i=e[1];return e[2]&&(i+=`.${e[2]}`),i}}return""})();function KIA(e,i){const n=e.split(".").map(I=>Number(I)),c=i.split(".").map(I=>Number(I));for(let I=0;Im)return!1}return!1}function S$(e,i,n=!1){const c=e.split(".").map(C=>Number(C)),I=i.split(".").map(C=>Number(C));for(let C=0;CR)return!0;if(m{const e=Number(TQ.split(".")[0]);return e===14||e===13})(),zIA=ZY&&aF==="11.1.1",XY=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),b_=(()=>{let e;return()=>{if(e===void 0)try{e=!!window.localStorage}catch{e=!1}return e}})(),NM=ZIA();function ZIA(){const e=new Map([[aC,["Firefox",e$]],[YV,["Edg",o$]],[J4,["Chrome",y$]],[ZY,["ChiOS",Sc("CriOS")]],[ud&&!ZY,["Safari",aF]],[Sm,["TBS",r$]],[RT,["XWEB",a$]],[rF&&xV,["WeChat",g$]],[U4,["QQ(Win)",c$]],[HV,["QQ(Mobile)",zY]],[VV,["QQ(Mobile X5)",zY]],[F4,["QQ(Mac)",l$]],[O4,["QQ(iPad)",I$]],[P4,["MI",C$]],[x4,["HW",B$]],[Y4,["Samsung",Q$]],[qV,["OPPO",p$]],[V4,["VIVO",m$]],[sF,["EDGE",i$]],[k4,["SogouMobile",n$]],[L4,["Sogou",s$]]]);let i="unknown",n="unknown";return e.has(!0)&&([i,n]=e.get(!0)),{name:i,version:n}}function XIA(){return cC||_u||xV||b4||H4}var $IA="";function v$(){return AuA()||""}function AuA(){const e=bQ.match(/;\s*([^;)]+)\s+Build\//);return e?.[1]?e[1].trim():null}var t6=new Map([[cC,"Android"],[_u,"iOS"],[u$,"Windows"],[JV,"MacOS"],[E$,"Linux"],[d$,"ChromeOS"]]),M$=function(){return t6.get(!0)?t6.get(!0):"unknown"};function q4(){return u$?1:cC?2:JV?3:_u?4:E$?5:d$?6:H4?7:0}function euA(){return rF||RT?4:lD?1:ud?2:aC?3:0}var R$=()=>{let e=M$();return _u?e+=`/${TQ}`:cC&&(e+=`/${A$}`),e+=`/${NM.name}/${ud&&!ZY?NM.version:NM.version.split(".")[0]}`,e},tuA=MT(oF()),iuA=new tuA.default,Rn=iuA,w$=(e=>(e.ROOM_DESTROY="1",e.JOIN_START="21",e.JOIN_SCHEDULE_SUCCESS="22",e.JOIN_SIGNAL_CONNECTION_START="23",e.JOIN_SIGNAL_CONNECTION_END="24",e.JOIN_SEND_CMD="25",e.JOIN_RECEIVED_CMD_RES="26",e.JOIN_SUCCESS="27",e.JOIN_FAILED="28",e.LEAVE_START="51",e.LEAVE_SEND_CMD="52",e.LEAVE_SUCCESS="53",e.PUBLISH_START="61",e.SEND_FIRST_VIDEO_FRAME="62",e.PUBLISH_FAILED="63",e.SUBSCRIBE_START="81",e.SUBSCRIBE_SUCCESS="82",e.SUBSCRIBE_FAILED="84",e.UNSUBSCRIBE_SUCCESS="83",e.LOCAL_TRACK_CAPTURE_START="101",e.LOCAL_TRACK_CAPTURE_SUCCESS="102",e.LOCAL_TRACK_CAPTURE_FAILED="103",e.LOCAL_TRACK_PUBLISHED="104",e.LOCAL_TRACK_UNPUBLISHED="105",e.LOCAL_TRACK_REPLACED="106",e.SWITCH_DEVICE_SUCCESS="107",e.TRACK_MUTED="108",e.TRACK_UNMUTED="109",e.REMOTE_TRACK_SUBSCRIBED="110",e.REMOTE_TRACK_UNSUBSCRIBED="111",e.LOCAL_TRACK_RECAPTURE="112",e.LOCAL_AUDIO_STARTED="113",e.LOCAL_AUDIO_STOPPED="114",e.REMOTE_AUDIO_STARTED="115",e.REMOTE_AUDIO_STOPPED="116",e.LOCAL_TRACK_STOPPED="117",e.LOCAL_VIDEO_TRACK_PREPROCESSED="118",e.PLAY_TRACK_START="151",e.PLAYER_STATE_CHANGED="152",e.VIDEO_LOADED_DATA="153",e.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",e.AUDIO_CONTEXT_LONG_SUSPENDED="155",e.REMOTE_VIDEO_PLAY_START="156",e.REMOTE_VIDEO_PLAY_FINISH="157",e.SIGNAL_CONNECTION_STATE_CHANGED="201",e.PEER_CONNECTION_STATE_CHANGED="202",e.SINGLE_CONNECTION_STAT="203",e.SPC_RECONNECTED="204",e.HEARTBEAT_REPORT="251",e.RECEIVED_PUBLISHED_USER_LIST="252",e.REMOTE_PUBLISH_STATE_CHANGED="253",e.AUDIO_LEVEL_INTERVAL="260",e.NETWORK_QUALITY="261",e.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",e.QUALITY_LIMITATION_CHANGED="263",e.LOG="264",e.AUDIO_PROCESSOR_DEBUG="265",e.SSO_SWITCH="266",e.SEI_MESSAGE="267",e.USER_PAUSE_IN_PIP="268",e.USER_RESUME_IN_PIP="269",e.ENTER_PICTURE_IN_PICTURE="270",e.LEAVE_PICTURE_IN_PICTURE="271",e.SWITCH_ROOM_START="401",e.SWITCH_ROOM_SUCCESS="407",e.SWITCH_ROOM_FAILED="408",e))(w$||{}),Rs=w$,ouA=class{constructor(){pe(this,"enable",!1),pe(this,"ssoFailCount",0),Rn.on("22",({schedule:e})=>{var i;(i=e?.config)!=null&&i.sso&&Rn.emit("266",{enable:!0})}),Rn.on("266",({enable:e})=>{this.enable=e})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&Rn.emit("266",{enable:!1})}},vW=new ouA,nuA="%cTRTC%c%s",suA="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",ruA="display: inline",_$=class T${constructor(){pe(this,"_isEnableUploadLog",!0),pe(this,"_localJoinedUser",new Map),pe(this,"_queue",[]),pe(this,"_timeoutId",-1),pe(this,"_logLevel",1),pe(this,"_logLevelToUpload",2),w7||_7||(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){Rn.on(Rs.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var n;(n=i?.config)!=null&&n.logLevelToUpload&&Y_[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),Rn.on(Rs.JOIN_START,({params:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),Rn.on(Rs.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){const i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let n=0;for(;n{i.map.has(I)?i.map.get(I).logs.push(c):i.map.set(I,{userId:I,sdkAppId:C,logs:[c]})});else if(rh(c.userId)&&YM(c.sdkAppId)){const{userId:I,sdkAppId:C}=c;i.map.has(I)?i.map.get(I).logs.push(c):i.map.set(I,{userId:I,sdkAppId:C,logs:[c]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,n)),i}async upload(){if(this._queue.length===0||!this._isEnableUploadLog)return;const{map:i,splicedQueue:n}=this.getLogsToUpload();if(i.size===0)return;try{const I=[...i.values()];for(let C=0;CcA.log).join(` -`)},b=JSON.stringify(T),J=vW.enable?T4(T,2002,R):b;await this.uploadLogWithRetry(J,R,J instanceof Uint8Array,b),_.forEach(cA=>cA.uploaded=!0)}}catch{}const c=n.filter(I=>!I.uploaded);c.length>0&&(this._queue=c.concat(this._queue))}uploadLogWithRetry(i,n,c,I){return G4({retryFunction:()=>Z7({url:R4(n,T7.LOG),body:i,timeout:5e3,priority:"low"}).then(C=>{c&&C.data!=="ok"&&(vW.handleUploadFailed(),this.uploadLogWithRetry(I,n,!1,I))}),settings:{retries:3,timeout:2e3},onError:({retry:C})=>{C()}})()}getPrefix(i){const n=new Date;return n.setTime(M4()),`[${RlA(n)}] <${Y_[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){sr(Y_[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(rh(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch{return""}}addLogToQueue(i,n,c=!0,I,C){const m={log:n.reduce((R,_)=>`${R} ${this.logChunkToString(_)}`.trim(),""),level:i,userId:I,sdkAppId:C,forAllJoinedClients:c};Rn.emit(Rs.LOG,{log:m}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(m)}log(i,n,c=!0,I,C){var m;if(n.unshift(this.getPrefix(i)),this.addLogToQueue(i,n,c,I,C),i{const i=16*Math.random()|0;return(e=="x"?i:3&i|8).toString(16)})},N$=guA,cuA=class{constructor(){pe(this,"_prefix","TRTC"),pe(this,"_queue",new Map)}getRealKey(e){return`${this._prefix}_${e}`}checkStorage(){b_()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(e=>{if(e.startsWith(this._prefix))try{const i=localStorage.getItem(e);if(!i)return!1;const n=JSON.parse(i);if(n&&n.expiresInlocalStorage.removeItem(e)))}doFlush(){if(b_())try{for(const[e,i]of this._queue)localStorage.setItem(e,JSON.stringify(i))}catch(e){An.warn(e)}}getItem(e){if(!b_())return null;try{const i=localStorage.getItem(this.getRealKey(e));if(!i)return null;const n=JSON.parse(i);return n&&n.expiresIn>=Date.now()?n.value:null}catch(i){An.warn(i)}}setItem(e,i){if(b_())try{const n={expiresIn:Date.now()+blA,value:i};this._queue.set(this.getRealKey(e),n)}catch(n){An.warn(n)}}deleteItem(e){if(!b_())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(i){return An.warn(i),!1}}clear(){if(b_())try{localStorage.clear()}catch(e){An.warn(e)}}},G$=new cuA,luA={};S4(luA,{HTTPS_API:()=>DuA,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>j$,IS_GET_CAPABILITIES_SUPPORTED:()=>K$,IS_GET_SETTINGS_SUPPORTED:()=>eV,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>GuA,IS_INSERTABLE_STREAM_SUPPORTED:()=>W$,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>OuA,IS_RTC_RTP_SENDER_SUPPORTED:()=>gF,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>z$,IS_SEI_SUPPORTED:()=>buA,IS_SPC_SUPPORTED:()=>wuA,basis:()=>LuA,capabilityCheck:()=>UuA,checkSystemRequirementsInternal:()=>U$,decodeSupportStatus:()=>L$,detectH264SupportedByFakeStreaming:()=>F$,detectVideoCodecCapabilities:()=>PuA,detectVideoDecoderCapabilities:()=>tAA,detectVideoEncoderCapabilities:()=>eAA,encodeSupportStatus:()=>z4,getBrowserInfo:()=>huA,getDisplayResolution:()=>O$,getH264ProfileLevelIds:()=>iAA,isAddTransceiverSupported:()=>jV,isBrowserSupported:()=>K4,isCanvasCaptureStreamAPISupported:()=>Y$,isCanvasSmallStreamSupported:()=>V$,isGetReceiversSupported:()=>MuA,isGetSendersSupported:()=>q$,isGetTransceiversSupported:()=>RuA,isGetUserMediaSupported:()=>P$,isMediaDevicesSupported:()=>W4,isMediaSessionSupported:()=>X$,isMediaStreamTrackGeneratorSupported:()=>QuA,isMediaStreamTrackProcessorSupported:()=>BuA,isReplaceTrackSupported:()=>TuA,isRequestVideoFrameCallbackSupported:()=>$4,isSIMDSupported:()=>kuA,isScaleResolutionDownBySupported:()=>H$,isScreenCaptureApiAvailable:()=>Z4,isSelectedCandidatePair:()=>SuA,isSetParametersSupported:()=>NuA,isSetSinkIdSupported:()=>fuA,isSmallStreamSupported:()=>J$,isStopTransceiverSupported:()=>_uA,isTRTCSupported:()=>muA,isUnifiedPlanDefault:()=>vuA,isUsedInHttpProtocol:()=>KV,isWebAudioSupported:()=>x$,isWebCodecSupported:()=>Z$,isWebCodecsSupported:()=>j4,isWebRTCSupported:()=>X4,isWebTransportSupported:()=>$$});var $Y={PLAY_FAILED:"PLAY_FAILED",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND"},Z_={AVOID_REPEATED_CALL:e=>`previous ${e.name}() is ongoing, please avoid repeated calls.`,INVALID_PARAMETER_REQUIRED:({key:e,rule:i,fnName:n,value:c})=>`'${e||i.name}' is a required param when calling ${n}(), received: ${c}.`,INVALID_PARAMETER_TYPE({key:e,rule:i,fnName:n,value:c}){const I=`${e||i.name}`;let C="";return C=Array.isArray(i.type)?i.type.join("|"):i.type,`'${I}' must be type of ${C} when calling ${n}(), received type: ${xM(c)}.`},INVALID_PARAMETER_EMPTY:({key:e,rule:i,fnName:n,value:c})=>`'${e||i.name}' cannot be '${c}' when calling ${n}().`,INVALID_PARAMETER_INSTANCE:({key:e,rule:i,fnName:n,value:c})=>`'${`${e||i.name}`}' must be instanceof ${`${i.instanceOf.name||i.instanceOf}`} when calling ${n}(), received type: ${xM(c)}.`,INVALID_PARAMETER_RANGE:({key:e,rule:i,fnName:n,value:c})=>`'${e||i.name}' must be one of ${i.values.join("|")} when calling ${n}(), received: ${c}.`,INVALID_PARAMETER_MIN:({key:e,rule:i,fnName:n,value:c})=>`the min value of ${e||i.name} is ${i.min}, received: ${c}.`,INVALID_PARAMETER_MAX:({key:e,rule:i,fnName:n,value:c})=>`the max value of ${e||i.name} is ${i.max}, received: ${c}.`,API_CALL_TIMEOUT:e=>`${e.commandDesc||e.command} timeout observed.`,SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:e=>`SignalChannel setup failure: (errorCode: ${e.errorCode}, errorMsg: ${e.errorMsg} }).`,ERROR_MESSAGE(e){let i=`${e.type} failed`;return e.message&&(i=`${i}: ${e.message}.`),i},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:e=>`exchange sdp failed ${e.errMsg}.`,UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:e=>`'${e}' must be validate string when useStringRoomId is true.`,INVALID_ROOMID_INTEGER:e=>`'${e}' must be an integer between [1, 4294967294] when useStringRoomId is false.`,INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED:({error:e,code:i})=>`Failed to join room - ${e} code: ${i}`,REJOIN_ROOM_FAILED:e=>`reJoin room: ${e.roomId} failed, please check your network.`,INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:e=>`duplicate ${e} stream publishing, please unpublish your prev ${e} stream and then re-publish.`,INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED:({message:e,userId:i,streamType:n})=>`failed to subscribe ${i} ${n} stream, reason: ${e}.`,INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:e=>`switchRole failed, errCode: ${e.code} errMsg: ${e.message}.`,CLIENT_BANNED:e=>`client was banned because of ${e.message}.`,INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:e=>`startPublishCDNStream failed, errMsg: ${e.message}.`,STOP_PUBLISH_CDN_FAILED:e=>`stopPublishCDNStream failed, errMsg: ${e.message}.`,INVALID_STREAM_ID:e=>`'${e}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`,START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:e=>`cannot replace ${e.kind} track because stream has not ${e.kind} track`,NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:e=>`startMixTranscode failed, errMsg: ${e.message}.`,STOP_MIX_TRANSCODE_FAILED:e=>`stopMixTranscode failed, errMsg: ${e.message}.`,MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO:({key:e,rule:i,fnName:n,value:c})=>`'${e||i.name}' cannot be less than 0 when calling ${n}().`,MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:e=>`'${e}' is required and must be between 1 and 15.`,MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:e,fnName:i})=>`'${e}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:e,fnName:i,type:n})=>`the element corresponding to '${e}' must be instanceof HTMLElement when calling ${i}(), received: ${n}.`,PLAY_FAILED:e=>`${e.media} play failed, browser exception: ${e.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:e=>`${e}Track is not supported on your browser.`,NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:e=>`${e.signalResponse} failed, response code is ${e.code} , errMsg: ${e.message}.`,CATCH_HANDLER_ERROR:({name:e,event:i})=>`an error was caught in ${e}.on('${i}', handler), please check your code in 'handler'.`,API_NOT_EXIST:({name:e})=>`experimental api ${e} does not exist.`,REPEAT_JOIN:e=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED:({funName:e})=>`failed to call ${e}() because client was destroyed.`,SEI_NOT_SUPPORT:e=>"not support to sendSEIMessage"+(e===!1?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:e,name:i,timesInSecond:n,maxSizeInSecond:c})=>`api ${i} call ${e?"size":"times"} is over ${e?`${c} bytes`:n} in a second.`,CONNECTION_ABORTED:e=>`connection aborted due to: ${e}`,API_CALL_ABORTED(e){let i;return i=e.message.includes("REMOTE_STREAM_NOT_EXIST")?`Subscribe ${e.userId} ${e.streamType} stream aborted, reason: remote user ${e.userId} unpublished stream.`:`API aborted, reason: ${e.message}`,i},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:e=>`'streamType' is required when 'userId' is not '*', calling ${e}()`,SWITCH_PLAYBACK_QUALITY_TIMEOUT:e=>`switchPlaybackQuality timeout: waiting for first frame of user ${e.userId}.`},i6=(e,i)=>i?`${hW}/${e}/${i}`:`${hW}/${e}/index.html`,IuA=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let e=localStorage==null?void 0:localStorage.getItem(GlA);if(e){e=JSON.parse(e);const i=document.createElement("script");i.type="text/javascript",i.text=e.message,document.body.appendChild(i);const n=window.TRTC_ERROR_INFO,c=window.TRTC_ERROR_LINK;return document.body.removeChild(i),{TRTC_ERROR_INFO:n,TRTC_ERROR_LINK:c}}return{}};function AV(e){const{key:i,data:n,link:c,addDocLink:I=!0}=e;let C="",m="",R="";_M(Z_[i])?C=Z_[i](n):rh(Z_[i])&&(C=Z_[i]);const{TRTC_ERROR_INFO:_,TRTC_ERROR_LINK:T}=IuA();c?R=`${c.className}.html#${c.fnName}`:T&&T[i]&&(_M(T[i])?R=T[i](n):rh(T[i])&&(R=T[i]));let b=C;return iD()&&(_&&_[i]&&(_M(_[i])?m=_[i](n):rh(_[i])&&(m=_[i])),m&&(b=I?`${m} +`}}}),plA=iF({"../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/index.js"(e){var i=BlA(),n=QlA(),c=v4();e.grammar=c,e.write=n,e.parse=i.parse,e.parseParams=i.parseParams,e.parseFmtpConfig=i.parseFmtpConfig,e.parsePayloads=i.parsePayloads,e.parseRemoteCandidates=i.parseRemoteCandidates,e.parseImageAttributes=i.parseImageAttributes,e.parseSimulcastStreamList=i.parseSimulcastStreamList}}),mlA={x:{required:!0,type:"number"},y:{required:!0,type:"number"},width:{required:!0,type:"number",notLessThanZero:!0,min:1,max:3840},height:{required:!0,type:"number",notLessThanZero:!0,min:1,max:3840},zIndex:{required:!0,type:"number"},fillMode:{required:!1,type:"string"},mirror:{required:!1,type:"boolean"},rotation:{required:!1,type:"number"},hidden:{required:!1,type:"boolean"}},p7=(e,i=!1)=>({type:"object",required:i,properties:{canvasColor:{required:!1,type:["string",CanvasGradient,CanvasPattern]},width:{required:!0,type:"number",notLessThanZero:!0,min:1,max:3840},height:{required:!0,type:"number",notLessThanZero:!0,min:1,max:3840},frameRate:{required:!1,type:"number",notLessThanZero:!0,min:1,max:60}},validate(n,c,I){const{RtcError:C,ErrorCode:m,ErrorCodeDictionary:R}=e.errorModule;if(!n)return;const{width:_,height:T}=n;if(_&&T&&_*T>8294400)throw new C({code:m.INVALID_PARAMETER,message:"The mix resolution cannot be set higher than 3840 * 2160."})}}),m7=e=>({required:!1,type:["string",HTMLElement,null],validate(i,n,c){const{RtcError:I,ErrorCode:C,ErrorCodeDictionary:m}=e.errorModule;if(e.utils.isString(i)&&!document.getElementById(i))throw new I({code:C.INVALID_PARAMETER,extraCode:m.INVALID_ELEMENT_ID,fnName:c,messageParams:{key:n}})}}),nF=(e,i=!0)=>({type:"object",required:i,properties:ks({},mlA),validate(n,c,I){const{RtcError:C,ErrorCode:m,ErrorCodeDictionary:R}=e.errorModule;if(n){if(n.fillMode&&!["contain","cover","fill"].includes(n.fillMode))throw new C({code:m.INVALID_PARAMETER,extraCode:R.INVALID_PARAMETER_TYPE,message:"The fillMode parameter must be 'contain', 'cover' or 'fill'",fnName:I});if(n.rotation&&![0,90,180,270].includes(n.rotation))throw new C({code:m.INVALID_PARAMETER,extraCode:R.INVALID_PARAMETER_TYPE,message:"The rotation parameter must be 0, 90, 180 or 270",fnName:I})}}}),f7=e=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},cameraId:{required:!1,type:"string"},videoTrack:{required:!1,instanceof:MediaStreamTrack},profile:{required:!1,type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},layout:ks({},nF(e))}}}),y7=e=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},profile:{required:!1,type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},captureElement:{required:!1,type:HTMLElement},preferDisplaySurface:{required:!1,type:"string"},layout:ks({},nF(e))},validate(i,n,c){const{RtcError:I,ErrorCode:C,ErrorCodeDictionary:m}=e.errorModule;if(!e.rtcDectection.isScreenCaptureApiAvailable())throw new I({code:C.ENV_NOT_SUPPORTED,fnName:c,extraCode:m.NOT_SUPPORTED_SCREEN_SHARE})}}}),D7=e=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},content:{required:!0,type:"string"},font:{required:!1,type:"string"},color:{required:!1,type:["string",CanvasGradient,CanvasPattern]},layout:ks({},nF(e))}}}),S7=e=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},url:{required:!0,type:"string"},layout:ks({},nF(e))}}}),v7=e=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},url:{required:!0,type:"string"},layout:ks({},nF(e))}}});function flA(e){return{name:"VideoMixerOptions",type:"object",required:!0,allowEmpty:!1,properties:{view:ks({},m7(e)),canvasInfo:ks({},p7(e,!0)),camera:ks({},f7(e)),screen:ks({},y7(e)),text:ks({},D7(e)),image:ks({},S7(e)),video:ks({},v7(e))},validate(i,n,c,I){const{RtcError:C,ErrorCode:m,ErrorCodeDictionary:R}=e.errorModule;if(e.environment.isMobile())throw new C({code:m.ENV_NOT_SUPPORTED,message:"VideoMixer is not supported on mobile devices currently"});const{onScreenShareStop:_}=i;if(_&&!e.utils.isFunction(_))throw new C({code:m.INVALID_PARAMETER,extraCode:R.INVALID_PARAMETER_TYPE,fnName:c,messageParams:{key:"onScreenShareStop",value:typeof _,rule:{type:"Function"}}})}}}function ylA(e){return{name:"VideoMixerOptions",type:"object",required:!1,allowEmpty:!1,properties:{view:ks({},m7(e)),canvasInfo:ks({},p7(e)),camera:ks({},f7(e)),screen:ks({},y7(e)),text:ks({},D7(e)),image:ks({},S7(e)),video:ks({},v7(e))}}}function DlA(e){return{name:"StopVideoMixerOptions",required:!1}}var M7=(e=>(e[e.INVALID_PARAMETER=4096]="INVALID_PARAMETER",e[e.INVALID_OPERATION=4097]="INVALID_OPERATION",e[e.NOT_SUPPORTED=4098]="NOT_SUPPORTED",e[e.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",e[e.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",e[e.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",e[e.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",e[e.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",e[e.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",e[e.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",e[e.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",e[e.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",e[e.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",e[e.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",e[e.CLIENT_BANNED=16448]="CLIENT_BANNED",e[e.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",e[e.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",e[e.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",e[e.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",e[e.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",e[e.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",e[e.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",e[e.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",e[e.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",e[e.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",e[e.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",e[e.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",e[e.API_CALL_ABORTED=16461]="API_CALL_ABORTED",e[e.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",e[e.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",e[e.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",e[e.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",e[e.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",e[e.UNKNOWN=65535]="UNKNOWN",e))(M7||{}),Zg=M7,SlA=function(e){for(const i in Zg)if(Zg[i]===e)return i;return"UNKNOWN"},vlA=class extends Error{constructor({name:e="RtcError",message:i,code:n=Zg.UNKNOWN,extraCode:c=0,constraint:I}){const C=`<${SlA(n)} 0x${n.toString(16)}>`,m=`${i}${I?` constraint: ${I}`:""}${i?.includes(C)?"":` ${C}`}`;super(m),pe(this,"code"),pe(this,"extraCode"),pe(this,"message"),pe(this,"originMessage"),pe(this,"name"),pe(this,"constraint"),this.code=n,this.extraCode=c,this.name=e,this.message=m,this.constraint=I,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},Ml=vlA,MlA=0,M4=function(){return Date.now()+MlA},R7=function(){const e=new Date;return e.setTime(M4()),e.toLocaleString()},RlA=function(e){let i=String(e.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${e.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`},wlA={};S4(wlA,{REPORT_TYPE:()=>W7,buildSSOPackage:()=>T4,bytes2ms:()=>iIA,calculateScaleResolutionDownNumber:()=>K7,concatArrayBuffers:()=>RIA,convertObjectNumberToInt:()=>J7,copyProperties:()=>tIA,deepClone:()=>jY,deepCloneBasic:()=>SW,deepMerge:()=>Y7,delay:()=>QT,fibonacci:()=>_4,formatedTime:()=>mIA,getConstructorName:()=>gIA,getContainerFromElement:()=>QIA,getEnv:()=>WlA,getFirst16Bits:()=>_IA,getInternalVersion:()=>uIA,getLast16Bits:()=>wIA,getLoggerUrl:()=>R4,getMediaStreamTrackInfo:()=>SIA,getMuteStateFromFlag:()=>x7,getNetworkType:()=>w4,getNumNetworkType:()=>eIA,getReconnectionTimeout:()=>sIA,getStringByteLength:()=>fIA,getTestSignalDomain:()=>ZlA,getTurnServer:()=>CIA,getUint32Version:()=>H7,getValueType:()=>xM,getViewListFromView:()=>BIA,glog:()=>nIA,ipv4ToUint32:()=>hIA,isArray:()=>oh,isAudioWorkletSupported:()=>cIA,isBoolean:()=>TM,isConstructor:()=>P7,isEmpty:()=>dIA,isFunction:()=>_M,isLangChinese:()=>iD,isMediaStreamTrack:()=>rIA,isNumber:()=>YM,isObject:()=>SM,isOverseaSdkAppId:()=>KY,isPlainObject:()=>BT,isPortrait:()=>V7,isPromise:()=>O7,isRemoteTrack:()=>aIA,isRotate90Or270:()=>j7,isSetSinkIdSupported:()=>lIA,isString:()=>rh,isUndefined:()=>sr,isVideoMixerOutputTrack:()=>N4,loadImage:()=>yIA,loadVideo:()=>vIA,ms2bytes:()=>oIA,ms2samples:()=>F7,normalizeUrl:()=>DIA,performanceNow:()=>Wc,promiseAny:()=>IIA,samples2ms:()=>U7,setNetworkTypeFromWebRTC:()=>AIA,stringify:()=>oD,stringifyIncludeValue:()=>DW,throttlePromise:()=>q7});var qY="5.0.0",w7=typeof importScripts<"u",_7=typeof registerProcessor<"u",_lA="web.sdk.qcloud.com",hW=`https://${_lA}/trtc/webrtc/doc`,xZ="https://cloud.tencent.com/document/product/647/85386",YZ="https://trtc.io/document/56025",TlA="https://yun.tim.qq.com",NlA="https://apisgp.my-imcloud.com",GlA="trtc_error_assistance",T7={LOG:"jssdk_log"},h3={QCLOUD:"qcloud"},Y_=(e=>(e[e.TRACE=0]="TRACE",e[e.DEBUG=1]="DEBUG",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.NONE=5]="NONE",e))(Y_||{}),N7={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},blA=6048e5,klA={"480p_2":{width:640,height:480,frameRate:15,bitrate:500}},LlA=klA["480p_2"],ni={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADSTART:"loadstart",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",FULLSCREEN_CHANGE:"fullscreenchange",RESIZE:"resize",TIME_UPDATE:"timeupdate"},VZ=1,UlA=2,FlA=4,HZ=8,JZ=64,qZ=16,OlA=256,CU={PLAYER_ERROR:"player-error",LOAD_WORKLET:"load-worklet",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},PlA="unified-plan",V_=5,G7="default",iY=2e3,b7=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],xlA={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},YlA=function(e,i,n,c){return new(n||(n=Promise))(function(I,C){function m(T){try{_(c.next(T))}catch(b){C(b)}}function R(T){try{_(c.throw(T))}catch(b){C(b)}}function _(T){var b;T.done?I(T.value):(b=T.value,b instanceof n?b:new n(function(J){J(b)})).then(m,R)}_((c=c.apply(e,[])).next())})},BW=Symbol(32),QW=Symbol(16),pW=Symbol(8),rT=class{constructor(e){this.g=e,this.consumed=0,e&&(this.need=e.next().value)}setG(e){this.g=e,this.demand(e.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(e,i){return i&&this.consume(),this.need=e,this.flush()}read(e){return YlA(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((i,n)=>{var c;this.reject=n,this.resolve=I=>{delete this.lastReadPromise,delete this.resolve,delete this.need,i(I)},this.demand(e,!0)||(c=this.pull)===null||c===void 0||c.call(this,e)})})}readU32(){return this.read(BW)}readU16(){return this.read(QW)}readU8(){return this.read(pW)}close(){var e;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(e=this.reject)===null||e===void 0||e.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let e=null;const i=this.buffer.subarray(this.consumed);let n=0;const c=I=>i.length<(n=I);if(typeof this.need=="number"){if(c(this.need))return;e=i.subarray(0,n)}else if(this.need===BW){if(c(4))return;e=i[0]<<24|i[1]<<16|i[2]<<8|i[3]}else if(this.need===QW){if(c(2))return;e=i[0]<<8|i[1]}else if(this.need===pW){if(c(1))return;e=i[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(c(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(i.subarray(0,n)),e=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(c(this.need.byteLength))return;new Uint8Array(this.need).set(i.subarray(0,n)),e=this.need}return this.consumed+=n,this.g?this.demand(this.g.next(e).value,!0):this.resolve&&this.resolve(e),e}write(e){if(e instanceof Uint8Array?this.malloc(e.length).set(e):"buffer"in e?this.malloc(e.byteLength).set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength)):this.malloc(e.byteLength).set(new Uint8Array(e)),!this.g&&!this.resolve)return new Promise(i=>this.pull=i);this.flush()}writeU32(e){this.malloc(4).set([e>>24&255,e>>16&255,e>>8&255,255&e]),this.flush()}writeU16(e){this.malloc(2).set([e>>8&255,255&e]),this.flush()}writeU8(e){this.malloc(1)[0]=e,this.flush()}malloc(e){if(this.buffer){const i=this.buffer.length,n=i+e;if(n<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,n);else{const c=new Uint8Array(n);c.set(this.buffer),this.buffer=c}return this.buffer.subarray(i,n)}return this.buffer=new Uint8Array(e),this.buffer}};rT.U32=BW,rT.U16=QW,rT.U8=pW;var VlA=128;function B3(e){const i=new rT;for(;e>=128;)i.malloc(1)[0]=255&e|VlA,e>>>=7;return i.malloc(1)[0]=255&e,i.buffer||new Uint8Array(0)}function mW(e,i=0){const n=new rT,c=i<<3;switch(typeof e){case"boolean":const I=n.malloc(2);I[0]=c,I[1]=e?1:0;break;case"number":n.malloc(1)[0]=c,n.write(B3(e));break;case"string":n.malloc(1)[0]=2|c;const C=new TextEncoder().encode(e);n.write(B3(C.length));const m=n.malloc(C.length);for(let _=0;_>>24&255),this.buffer.push(e>>>16&255),this.buffer.push(e>>>8&255),this.buffer.push(255&e)}writeInt16(e){this.buffer.push(e>>>8&255),this.buffer.push(255&e)}writeByte(e){this.buffer.push(255&e)}writeBytes(e){for(let i=0;i>>24&255,e[n+1]=i>>>16&255,e[n+2]=i>>>8&255,e[n+3]=255&i}function ld(e,i){return e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3]}function WZ(e,i){return e[i]}function kL(e,i,n){return new TextDecoder().decode(HlA(e,i,n))}function HlA(e,i,n){return e.slice(i,i+n)}var Q3=0,fW=2654435769,yW=16,zZ=4,hU=2,BU=7;function JlA(e,i,n,c="AVQualityReportSvc.C2S",I=2e3,C=2,m=30){return{version:I,encryption:C,d2:"",d2Len:0,uinType:m,uin:"",uinLen:0,reqHead:{seqNumber:n,appId:e,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:c,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:i}}function qlA(e,i){const n=new KZ,c=JlA(i,e,Q3);Q3=Q3+1&2147483647,n.writeInt32(0),n.writeInt32(c.version),n.writeByte(c.encryption);const I=new TextEncoder().encode(c.d2);n.writeInt32(I.length+4),I&&n.writeBytes(I),n.writeByte(c.uinType);const C=new TextEncoder().encode(c.uin);n.writeInt32(C.length+4),C.length&&n.writeBytes(C);const m=new KZ;m.writeInt32(0),m.writeInt32(c.reqHead.seqNumber),m.writeInt32(c.reqHead.appId),m.writeByte(c.reqHead.appId>>>24&255),m.writeByte(c.reqHead.appId>>>16&255),m.writeByte(c.reqHead.appId>>>8&255),m.writeByte(255&c.reqHead.appId);for(let qA=4;qA<16;qA++)m.writeByte(0);const R=new TextEncoder().encode(c.reqHead.a2);m.writeInt32(R.length+4),R.length&&m.writeBytes(R);const _=new TextEncoder().encode(c.reqHead.serviceCmd);m.writeInt32(_.length+4),_.length&&m.writeBytes(_);const T=new TextEncoder().encode(c.reqHead.cookie);m.writeInt32(T.length+4),T.length&&m.writeBytes(T);const b=new TextEncoder().encode(c.reqHead.imei);m.writeInt32(b.length+4),b.length&&m.writeBytes(b);const J=new TextEncoder().encode(c.reqHead.ksid);m.writeInt32(J.length+4),J.length&&m.writeBytes(J);const gA=new TextEncoder().encode(c.reqHead.clientVersionInfo);m.writeInt16(gA.length+2),gA.length&&m.writeBytes(gA);const eA=m.length;m.data[0]=eA>>>24&255,m.data[1]=eA>>>16&255,m.data[2]=eA>>>8&255,m.data[3]=255&eA,rh(e)&&(e=new TextEncoder().encode(e)),m.writeInt32(e.length+4),e.length&&m.writeBytes(e);let CA=new Uint8Array(m.data),IA=null;c.encryption===1?IA=new TextEncoder().encode(c.uin):c.encryption===2&&(IA=new Uint8Array(16)),IA&&(CA=KlA(CA,IA)),n.writeBytes(CA);const oA=new Uint8Array(n.data),vA=oA.length;return oA[0]=vA>>>24&255,oA[1]=vA>>>16&255,oA[2]=vA>>>8&255,oA[3]=255&vA,oA}function KlA(e,i){const n=e.length;let c=(n+1+hU+BU)%8;c&&(c=8-c);const I=new Uint8Array(n+1+hU+BU+c);let C=0;const m=new Uint8Array(8),R=new Uint8Array(8),_=new Uint8Array(8);let T=0;m[0]=248&Math.floor(256*Math.random())|c,T=1;for(let J=0;J>>=0,I+=(C<<4)+m[0]^C+R^(C>>>5)+m[1],I>>>=0,C+=(I<<4)+m[2]^I+R^(I>>>5)+m[3],C>>>=0;jZ(n,I,c),jZ(n,C,c+4)}var WlA=function(){return new URLSearchParams(location.search).get("trtc_env")||""},zlA=".rtc.qq.com",ZlA=function(e){return e.includes(".")?e:`${e}${zlA}`},KY=e=>Number(e)<14e8,R4=function(e,i){let n;return n=KY(e)?NlA:TlA,`${n}/v5/AVQualityReportSvc/C2S?random=${Math.floor(Math.random()*2**31)}&sdkappid=${e}&cmdtype=${i}`},k7="unknown";function w4(){$lA();const{userAgent:e,connection:i}=navigator;let n=(e.match(/NetType\/\S+/)||[])[0]||"";n=n.toLowerCase().replace("nettype/",""),n==="3gnet"&&(n="3g");const c=i&&i.type&&i.type.toLowerCase();let I=i&&i.effectiveType&&i.effectiveType.toLowerCase();return I==="slow-2"&&(I="2g"),c?L7(c,I):k7}function XlA(){An.warn("netType changed",w4())}var ZZ=!1;function $lA(){var e;ZZ||(ZZ=!0,(e=navigator.connection)==null||e.addEventListener("typechange",XlA))}function L7(e,i){if(N7[e])return e;switch(e){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";default:return"unknown"}}function AIA(e){k7=L7(e)}function eIA(){return N7[w4()]}function tIA(e,i){for(const n of Reflect.ownKeys(i))if(n!=="constructor"&&n!=="prototype"&&n!=="name"){const c=Object.getOwnPropertyDescriptor(i,n)||"";Object.defineProperty(e,n,c)}return e}function iIA(e,i=48e3){return U7(e/4,i)}function U7(e,i=48e3){return 1e3*e/i}function oIA(e,i=48e3){return 4*F7(e,i)}function F7(e,i=48e3){return e*i/1e3}var nIA=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},iD=()=>{let e=navigator.language;return e=e.substring(0,2),e==="zh"},BT=function(e){if(!e||typeof e!="object"||Object.prototype.toString.call(e)!="[object Object]")return!1;const i=Object.getPrototypeOf(e);if(i===null)return!0;const n=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof n=="function"&&n instanceof n&&Function.prototype.toString.call(n)===Function.prototype.toString.call(Object)};function _4(e,i=1,n=1){return e<=1?n:_4(e-1,n,i+n)}function sIA(e){return e>8?3e4:1e3*_4(e)}function xM(e){return Reflect.apply(Object.prototype.toString,e,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var _M=e=>typeof e=="function",sr=e=>e===void 0,rh=e=>typeof e=="string",YM=e=>typeof e=="number",TM=e=>typeof e=="boolean",SM=e=>xM(e)==="object",oh=e=>xM(e)==="array",rIA=e=>xM(e)==="MediaStreamTrack".toLowerCase(),aIA=e=>e.isRemote,O7=e=>xM(e)==="promise",P7=e=>_M(e)&&e.prototype.constructor===e,gIA=e=>P7(e)?e.prototype.constructor.name:"",cIA=typeof AudioWorkletNode<"u",lIA=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype;function IIA(e){return new Promise((i,n)=>{const c=[];e.forEach(I=>{I.then(i).catch(C=>{c.push(C),c.length===e.length&&n(c)})})})}function Wc(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var XZ=e=>+e<10?`0${e}`:e,uIA=e=>{const i=e.match(/^\d+\.\d+\.\d+/)[0];if(!i)return e;const n=i.split("."),c=XZ(n[1])+XZ(n[2]);return n[1]-15>0&&(n[1]="15"),n[2]-15>0&&(n[2]="15"),`${n.join(".")}.${c}`},EIA=Object.prototype.hasOwnProperty;function dIA(e){if(e==null)return!0;if(typeof e=="boolean")return!1;if(typeof e=="number")return e===0;if(typeof e=="string"||typeof e=="function"||Array.isArray(e))return e.length===0;if(e instanceof Error)return e.message==="";if(BT(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return e.size===0;case"[object Object]":for(const i in e)if(EIA.call(e,i))return!1;return!0}return!1}function x7(e,i){return{userId:i,hasAudio:!!(e&HZ),hasVideo:!!(e&VZ),hasAuxiliary:!!(e&FlA),hasSmall:!!(e&UlA),audioMuted:!!(e&JZ),videoMuted:!!(e&qZ),audioAvailable:!(!(e&HZ)||e&JZ),videoAvailable:!(!(e&VZ)||e&qZ),hasDatachannel:!!(e&OlA)}}function CIA(e){const i={urls:e.url.startsWith("turn:")||e.url.startsWith("turns:")?e.url:`turn:${e.url}`};return sr(e.username)||sr(e.credential)||(i.username=e.username,i.credential=e.credential,i.credentialType="password",sr(e.credentialType)||(i.credentialType=e.credentialType)),i}function hIA(e,i=!0){if(!rh(e))return 0;const n=e.split(".");return i?(Number(n[0])<<24|Number(n[1])<<16|Number(n[2])<<8|Number(n[3]))>>>0:(Number(n[3])<<24|Number(n[2])<<16|Number(n[1])<<8|Number(n[0]))>>>0}var Y7=function(e,i,n,c){if(!SM(e)||!SM(i))return 0;let I=0;const C=Object.keys(i);let m;for(let R=0,_=C.length;R<_;R++)if(m=C[R],!(sr(i[m])||n&&n.includes(m)))if(SM(e[m])&&SM(i[m]))I+=Y7(e[m],i[m],n,c);else{if(c&&c.includes(i[m]))continue;e[m]!==i[m]&&(e[m]=jY(i[m]),I+=1)}return I};function jY(e){if(oh(e)){const i=[];return e.forEach((n,c)=>{i[c]=jY(n)}),i}if(SM(e)){const i={};return Object.keys(e).forEach(n=>{i[n]=jY(e[n])}),i}return e}var BIA=e=>{let i=[];if(oh(e))i=[...e];else if(rh(e)){const n=document.getElementById(e);n&&i.push(n)}else e&&i.push(e);return i},QIA=e=>rh(e)?document.getElementById(e):e,pIA=e=>{const i=n=>n<10?`0${n}`:`${n}`;return`${e.getFullYear()}/${e.getMonth()+1}/${e.getDate()} ${i(e.getHours())}:${i(e.getMinutes())}:${i(e.getSeconds())}`},mIA=()=>pIA(new Date);function oD(e,{keysToInclude:i,keysToExclude:n}){try{if(oh(e))return`[${e.map(m=>oD(m,{keysToInclude:i,keysToExclude:n})).join(",")}]`;if(!BT(e)||!oh(i)&&!oh(n))return JSON.stringify(e);const c={},I=new Set(i),C=new Set(n);return Object.keys(e).forEach(m=>{(C.size===0&&I.has(m)||I.size===0&&!C.has(m))&&(c[m]=BT(e[m])||oh(e[m])?JSON.parse(oD(e[m],{keysToExclude:n,keysToInclude:i})):e[m])}),JSON.stringify(c)}catch{return"{}"}}function DW(e,i=!1){const n=[];return Object.keys(e).forEach(c=>{i===e[c]&&n.push(c)}),oD(e,{keysToInclude:n})}function fIA(e){return e.replace(/[\u4e00-\u9fa5]/g,"aa").length}var V7=()=>{var e,i,n,c;return(e=window.screen)!=null&&e.orientation?!!((c=(n=(i=window.screen)==null?void 0:i.orientation)==null?void 0:n.type)!=null&&c.includes("portrait")):window.orientation===0||window.orientation===180},yIA=async e=>new Promise((i,n)=>{let c;if(rh(e))c=new Image,c.crossOrigin="anonymous",c.src=e;else if(c=e,c.complete)return void i(c);c.onload=()=>i(c),c.onerror=()=>{n(new Ml({code:Zg.INVALID_PARAMETER,message:`load image failed, url: ${e}`}))}}),H7=e=>{const i=e.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]},J7=e=>(Object.keys(e).forEach(i=>{YM(e[i])&&(i.startsWith("uint")||i.startsWith("int"))?e[i]=Math.floor(e[i]):(BT(e[i])||oh(e[i]))&&J7(e[i])}),e);function QT(e,i){return new Promise(n=>{const c=setTimeout(n,e);i&&i(c)})}function q7(e,i){let n=null;return function(...c){return n||(n=e.apply(i||this,c),n.finally(()=>n=null),n)}}function DIA(e){return e.replace(/(^|[^:])\/{2,}/g,"$1/")}function SIA(e){var i;try{const{width:n,height:c,frameRate:I,sampleRate:C,sampleSize:m,channelCount:R}=(i=e.getSettings)==null?void 0:i.call(e),_=e.kind===ni.AUDIO?`${C}x${m}@${R}`:`${n}x${c}@${I}`,T=e.stats?` stats: ${JSON.stringify(e.stats).replaceAll('"',"")}`:"";return`${e.id} ${e.readyState} muted:${e.muted} ${e.kind} ${e.label} ${_}${T}`}catch{return""}}function K7(e,i){return e.width*e.height===i.width*i.height?1:V7()&&i.width>i.height&&e.height>i.width?Math.max(e.width/i.height,e.height/i.width,1):Math.max(e.width/i.width,e.height/i.height,1)}function j7(e){return e===90||e===270}async function vIA(e){return new Promise((i,n)=>{const c=document.createElement("video");c.crossOrigin="anonymous",c.src=e,c.muted=!0,c.loop=!0,c.playsInline=!0,c.play().then(()=>i(c)),c.onerror=()=>{n(c.error)}})}function SW(e,i=new WeakMap){if(typeof e!="object"||e===null)return e;if(i.has(e))return i.get(e);if(Array.isArray(e)){const n=[];return i.set(e,n),e.forEach((c,I)=>{n[I]=SW(c,i)}),n}if(Object.prototype.toString.call(e)==="[object Object]"){const n={};return i.set(e,n),Reflect.ownKeys(e).forEach(c=>{n[c]=SW(e[c],i)}),n}return e}var W7=(e=>(e[e.END_REPORT=2001]="END_REPORT",e[e.LOG=2002]="LOG",e[e.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",e))(W7||{});function MIA(e,i,n,c){let I={data:e,random:Math.floor(Math.random()*2147483648),sdkAppId:n};return sr(c)||(I=cB(ks({},I),{gzip:+c})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:i,bytes_report_data:JSON.stringify(I)}}}function T4(e,i,n,c){try{const I=MIA(e,i,n,c);return qlA(mW(I),n)}catch{return JSON.stringify(e)}}function RIA(e,i){const n=new Uint8Array(e.byteLength+i.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(i),e.byteLength),n.buffer}function wIA(e){return(65535&e)>>>0}function _IA(e){return(4294901760&e)>>>0}function N4(e){return!!(e&&e instanceof CanvasCaptureMediaStreamTrack&&e.canvas.id.includes("trtc_mix"))}function TIA(e){const i=NIA(e);return i?.busiBuff}function NIA(e){try{const i={};let n=0;i.totalLength=ld(e,n),n+=4,i.version=ld(e,n),n+=4,i.encryption=WZ(e,n),n+=1,i.uinType=WZ(e,n),n+=1,i.uinLength=ld(e,n),n+=4,i.uin=i.uinLength>4?kL(e,n,i.uinLength-4):"",n+=i.uinLength-4;const c=e.slice(n);if(i.encryption===2){const I=new Uint8Array(16).fill(0);e=GIA(c,I),i.decrypted=!0,n=0}else e=c,n=0;return i.rspHeadLength=ld(e,n),n+=4,i.seqNo=ld(e,n),n+=4,i.retCode=ld(e,n),n+=4,i.retStrLength=ld(e,n),n+=4,i.retStr=i.retStrLength?kL(e,n,i.retStrLength-4):"",n+=i.retStrLength-4,i.serviceCmdLength=ld(e,n),n+=4,i.serviceCmd=i.serviceCmdLength?kL(e,n,i.serviceCmdLength-4):"",n+=i.serviceCmdLength-4,i.cookieLength=ld(e,n),n+=4,i.cookie=i.cookieLength?kL(e,n,i.cookieLength-4):"",n+=i.cookieLength-4,i.flag=ld(e,n),n+=4,i.busiBuffLength=ld(e,n),n+=4,i.busiBuff=i.busiBuffLength?kL(e,n,i.busiBuffLength-4):"",n+=i.busiBuffLength-4,i}catch{}}function z7(e,i){let n=e[0]<<24|e[1]<<16|e[2]<<8|e[3],c=e[4]<<24|e[5]<<16|e[6]<<8|e[7];n>>>=0,c>>>=0;let I=fW*yW>>>0;for(let C=0;C>>5)+i[3],c>>>=0,n-=(c<>>5)+i[1],n>>>=0,I-=fW,I>>>=0;return new Uint8Array([n>>>24&255,n>>>16&255,n>>>8&255,255&n,c>>>24&255,c>>>16&255,c>>>8&255,255&c])}function GIA(e,i){let n=0;const c=new Uint8Array(8).fill(0);let I=z7(new Uint8Array(e.slice(0,8)),i);const C=7&I[0],m=e.length-1-C-hU-BU,R=new Uint8Array(m);let _=0,T=c,b=e.slice(0,8);n=8;let J=1;J+=C;for(let eA=1;eA<=hU;)if(J<8)J++,eA++;else if(J===8){const CA=m3(e,n,T,b,I,i);T=CA.ivPreCrypt,b=CA.ivCurCrypt,I=CA.debiBuf,n=CA.bufPos,J=0}let gA=m;for(;gA>0;)if(J<8)R[_++]=I[J]^T[J],J++,gA--;else if(J===8){const eA=m3(e,n,T,b,I,i);T=eA.ivPreCrypt,b=eA.ivCurCrypt,I=eA.debiBuf,n=eA.bufPos,J=0}for(let eA=1;eA<=BU;)if(J<8)I[J],T[J],J++,eA++;else if(J===8){if(n>=e.length)break;const CA=m3(e,n,T,b,I,i);if(!CA.success)break;T=CA.ivPreCrypt,b=CA.ivCurCrypt,I=CA.debiBuf,n=CA.bufPos,J=0}return R}function m3(e,i,n,c,I,C){if(i+8>e.length)return{success:!1};const m=new Uint8Array(c),R=e.slice(i,i+8),_=new Uint8Array(8);for(let T=0;T<8;T++)_[T]=I[T]^R[T];return{success:!0,ivPreCrypt:m,ivCurCrypt:R,debiBuf:z7(_,C),bufPos:i+8}}var $Z=typeof TextDecoder<"u"?new TextDecoder:void 0;function Z7({url:e,body:i,method:n="POST",timeout:c,priority:I}){return new Promise((C,m)=>{if("fetch"in window)return fetch(e,{method:n,body:i,priority:I}).then(_=>_.clone().json().then(T=>({data:T}),()=>_.arrayBuffer().then(T=>({data:TIA(new Uint8Array(T))||($Z?$Z.decode(T):T)})))).then(C,m);const R=new XMLHttpRequest;R.onreadystatechange=()=>{if(R.readyState===4)if(R.status>=200&&R.status<300)try{const _=JSON.parse(R.response);C({data:_})}catch{C({data:R.response})}else m({status:R.status,statusText:R.statusText||"request failed!"})},R.timeout=c||5e3,R.open(n,e,!0),R.send(i)})}var bIA=Object.prototype.hasOwnProperty,H_=e=>typeof e=="function",G_=e=>e===void 0,kIA=e=>typeof e=="boolean",f3=e=>e.isRemote,LIA=function(e){if(!e||typeof e!="object"||Object.prototype.toString.call(e)!="[object Object]")return!1;const i=Object.getPrototypeOf(e);if(i===null)return!0;const n=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof n=="function"&&n instanceof n&&Function.prototype.toString.call(n)===Function.prototype.toString.call(Object)};function UIA(e){if(e==null)return!0;if(typeof e=="boolean")return!1;if(typeof e=="number")return e===0;if(typeof e=="string"||typeof e=="function"||Array.isArray(e))return e.length===0;if(e instanceof Error)return e.message==="";if(LIA(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return e.size===0;case"[object Object]":for(const i in e)if(bIA.call(e,i))return!1;return!0}return!1}var FIA=0,OIA=1,A6=2;function PIA({retryFunction:e,settings:i,onError:n,onRetrying:c,onRetryFailed:I,onRetrySuccess:C,context:m}){return function(...R){const{retries:_=5,timeout:T=1e3}=i;let b=0,J=-1,gA=FIA;const eA=async(CA,IA)=>{const oA=m||this;try{const vA=await e.apply(oA,R);b>0&&C&&C.call(this,b),b=0,CA(vA)}catch(vA){const qA=()=>{clearTimeout(J),b=0,gA=A6,IA(vA)},Ae=()=>{gA!==A6&&b<(H_(_)?_():_)?(b++,gA=OIA,H_(c)&&c.call(this,b,qA),J=window.setTimeout(()=>{J=-1,eA(CA,IA)},H_(T)?T(b):T)):(qA(),H_(I)&&I.call(this,vA))};H_(n)?n.call(this,{error:vA,retry:Ae,reject:IA,retryFuncArgs:R,retriedCount:b}):Ae()}};return new Promise(eA)}}var G4=PIA,y3=class X7{constructor(i){pe(this,"_parentPath"),pe(this,"userId"),pe(this,"remoteUserId"),pe(this,"id"),pe(this,"sdkAppId"),pe(this,"type"),pe(this,"isLocal"),this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=!kIA(i.isLocal)||i.isLocal,this.type=this.isLocal?"":i.type}getFullId(){return this._parentPath&&this.id?`${this._parentPath}-${this.id}`:this._parentPath?this._parentPath:this.id}createChild(i){const n=new X7({id:i.id,userId:G_(i.userId)?this.userId:i.userId,sdkAppId:G_(i.sdkAppId)?this.sdkAppId:i.sdkAppId,type:G_(i.type)?this.type:i.type,isLocal:G_(i.isLocal)?this.isLocal:i.isLocal,remoteUserId:G_(i.remoteUserId)?this.remoteUserId:i.remoteUserId});return n.bindParent(this),n}bindParent(i){const n=i.getFullId();this._parentPath!==n&&(this.debug(`bind logger parent: ${i.id}`),this._parentPath=n,this.userId=i.userId||this.userId,this.sdkAppId=i.sdkAppId||this.sdkAppId)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,n){const c=this.isLocal?this.userId:this.remoteUserId,I=this.getFullId();n.unshift(`[${this.isLocal?"↑":"↓"}${this.type&&this.type!=="main"?"*":""}${I}${c?`|${c}`:""}]`),An.log(i,n,G_(this.userId)||UIA(this.userId),this.userId,this.sdkAppId)}info(...i){this.log(2,i)}debug(...i){this.log(1,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}},bQ=typeof navigator>"u"?"":navigator.userAgent,As=e=>new RegExp(e,"i").test(bQ),Sc=e=>{if(As(e)){const i=new RegExp(`${e}\\/([\\d.]+)`),n=bQ.match(i);if(n&&n[1])return n[1]}return""},PV=e=>{if(As(e)){const i=new RegExp(`${e}\\/(\\d+)`),n=bQ.match(i);if(n&&n[1])return parseFloat(n[1])}return NaN},e6=/AppleWebKit\/([\d.]+)/i.exec(bQ);e6&&parseFloat(e6[1]);var b4=As("iPad"),$7=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&As("Macintosh"),xV=As("iPhone")&&!b4,xIA=As("iPod"),_u=xV||b4||xIA||$7,WY=()=>{try{return _u&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch{return _u}},cC=As("Android"),A$=function(){if(cC){const e=bQ.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(e){const i=e[1]&&parseFloat(e[1]),n=e[2]&&parseFloat(e[2]);if(i&&n)return parseFloat(`${e[1]}.${e[2]}`);if(i)return i}}return NaN}();cC&&As("webkit")&&A$<2.3;var aC=As("Firefox"),e$=Sc("Firefox"),t$=PV("Firefox"),sF=As("Edge"),i$=Sc("Edge"),YV=As("Edg"),o$=Sc("Edg"),YIA=PV("Edg"),k4=As("SogouMobileBrowser"),n$=Sc("SogouMobileBrowser"),L4=As("MetaSr\\s"),s$=Sc("MetaSr\\s"),Sm=As("TBS"),r$=Sc("TBS"),RT=As("XWEB"),a$=Sc("XWEB");As("MSIE\\s8\\.0");var VIA=As("MSIE\\/\\d+");(function(){if(VIA){const e=/MSIE\s(\d+)\.\d/.exec(bQ);let i=e&&parseFloat(e[1]);return!i&&/Trident\/7.0/i.test(bQ)&&/rv:11.0/.test(bQ)&&(i=11),i}return NaN})();var rF=As("(micromessenger|webbrowser)"),g$=Sc("MicroMessenger"),VV=!Sm&&As("MQQBrowser")&&As("COVC"),HV=!Sm&&As("MQQBrowser")&&!As("COVC"),zY=HV||VV?Sc("MQQBrowser"):"",U4=!Sm&&As(" QQBrowser"),c$=Sc(" QQBrowser"),F4=!Sm&&As("QQBrowserLite"),l$=Sc("QQBrowserLite"),O4=!Sm&&As("MQBHD"),I$=Sc("MQBHD"),u$=As("Windows"),JV=!_u&&As("MAC OS X"),E$=!cC&&As("Linux"),d$=As("CrOS");As("MicroMessenger");var HIA=As("UCBrowser");As("Electron");var P4=As("MiuiBrowser"),C$=Sc("MiuiBrowser"),x4=As("HuaweiBrowser"),h$=As("Huawei")||As("HUAWEI"),JIA=As("Honor")||As("HONOR"),B$=Sc("HuaweiBrowser"),Y4=As("SamsungBrowser"),Q$=Sc("SamsungBrowser"),qV=As("HeyTapBrowser"),p$=Sc("HeyTapBrowser"),V4=As("VivoBrowser"),m$=Sc("VivoBrowser"),H4=As("OpenHarmony");Sc("OpenHarmony");var f$=()=>PV("Chrome"),ZY=As("CriOS"),lD=As("Chrome"),J4=!sF&&!L4&&!k4&&!Sm&&!RT&&!YV&&!U4&&!P4&&!x4&&!Y4&&!qV&&!V4&&lD,qIA=As("HeadlessChrome"),ID=f$(),D3=lD&&ID>=128&&ID<=143,y$=Sc("Chrome");PV("Electron");var ud=!lD&&!HV&&!VV&&!F4&&!O4&&As("Safari"),D$=ud||_u,aF=Sc("Version"),TQ=(()=>{if($7)return aF;if(_u){const e=bQ.match(/OS (\d+)_(\d+)/i);if(e&&e[1]){let i=e[1];return e[2]&&(i+=`.${e[2]}`),i}}return""})();function KIA(e,i){const n=e.split(".").map(I=>Number(I)),c=i.split(".").map(I=>Number(I));for(let I=0;Im)return!1}return!1}function S$(e,i,n=!1){const c=e.split(".").map(C=>Number(C)),I=i.split(".").map(C=>Number(C));for(let C=0;CR)return!0;if(m{const e=Number(TQ.split(".")[0]);return e===14||e===13})(),zIA=ZY&&aF==="11.1.1",XY=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),b_=(()=>{let e;return()=>{if(e===void 0)try{e=!!window.localStorage}catch{e=!1}return e}})(),NM=ZIA();function ZIA(){const e=new Map([[aC,["Firefox",e$]],[YV,["Edg",o$]],[J4,["Chrome",y$]],[ZY,["ChiOS",Sc("CriOS")]],[ud&&!ZY,["Safari",aF]],[Sm,["TBS",r$]],[RT,["XWEB",a$]],[rF&&xV,["WeChat",g$]],[U4,["QQ(Win)",c$]],[HV,["QQ(Mobile)",zY]],[VV,["QQ(Mobile X5)",zY]],[F4,["QQ(Mac)",l$]],[O4,["QQ(iPad)",I$]],[P4,["MI",C$]],[x4,["HW",B$]],[Y4,["Samsung",Q$]],[qV,["OPPO",p$]],[V4,["VIVO",m$]],[sF,["EDGE",i$]],[k4,["SogouMobile",n$]],[L4,["Sogou",s$]]]);let i="unknown",n="unknown";return e.has(!0)&&([i,n]=e.get(!0)),{name:i,version:n}}function XIA(){return cC||_u||xV||b4||H4}var $IA="";function v$(){return AuA()||""}function AuA(){const e=bQ.match(/;\s*([^;)]+)\s+Build\//);return e?.[1]?e[1].trim():null}var t6=new Map([[cC,"Android"],[_u,"iOS"],[u$,"Windows"],[JV,"MacOS"],[E$,"Linux"],[d$,"ChromeOS"]]),M$=function(){return t6.get(!0)?t6.get(!0):"unknown"};function q4(){return u$?1:cC?2:JV?3:_u?4:E$?5:d$?6:H4?7:0}function euA(){return rF||RT?4:lD?1:ud?2:aC?3:0}var R$=()=>{let e=M$();return _u?e+=`/${TQ}`:cC&&(e+=`/${A$}`),e+=`/${NM.name}/${ud&&!ZY?NM.version:NM.version.split(".")[0]}`,e},tuA=MT(oF()),iuA=new tuA.default,Rn=iuA,w$=(e=>(e.ROOM_DESTROY="1",e.JOIN_START="21",e.JOIN_SCHEDULE_SUCCESS="22",e.JOIN_SIGNAL_CONNECTION_START="23",e.JOIN_SIGNAL_CONNECTION_END="24",e.JOIN_SEND_CMD="25",e.JOIN_RECEIVED_CMD_RES="26",e.JOIN_SUCCESS="27",e.JOIN_FAILED="28",e.LEAVE_START="51",e.LEAVE_SEND_CMD="52",e.LEAVE_SUCCESS="53",e.PUBLISH_START="61",e.SEND_FIRST_VIDEO_FRAME="62",e.PUBLISH_FAILED="63",e.SUBSCRIBE_START="81",e.SUBSCRIBE_SUCCESS="82",e.SUBSCRIBE_FAILED="84",e.UNSUBSCRIBE_SUCCESS="83",e.LOCAL_TRACK_CAPTURE_START="101",e.LOCAL_TRACK_CAPTURE_SUCCESS="102",e.LOCAL_TRACK_CAPTURE_FAILED="103",e.LOCAL_TRACK_PUBLISHED="104",e.LOCAL_TRACK_UNPUBLISHED="105",e.LOCAL_TRACK_REPLACED="106",e.SWITCH_DEVICE_SUCCESS="107",e.TRACK_MUTED="108",e.TRACK_UNMUTED="109",e.REMOTE_TRACK_SUBSCRIBED="110",e.REMOTE_TRACK_UNSUBSCRIBED="111",e.LOCAL_TRACK_RECAPTURE="112",e.LOCAL_AUDIO_STARTED="113",e.LOCAL_AUDIO_STOPPED="114",e.REMOTE_AUDIO_STARTED="115",e.REMOTE_AUDIO_STOPPED="116",e.LOCAL_TRACK_STOPPED="117",e.LOCAL_VIDEO_TRACK_PREPROCESSED="118",e.PLAY_TRACK_START="151",e.PLAYER_STATE_CHANGED="152",e.VIDEO_LOADED_DATA="153",e.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",e.AUDIO_CONTEXT_LONG_SUSPENDED="155",e.REMOTE_VIDEO_PLAY_START="156",e.REMOTE_VIDEO_PLAY_FINISH="157",e.SIGNAL_CONNECTION_STATE_CHANGED="201",e.PEER_CONNECTION_STATE_CHANGED="202",e.SINGLE_CONNECTION_STAT="203",e.SPC_RECONNECTED="204",e.HEARTBEAT_REPORT="251",e.RECEIVED_PUBLISHED_USER_LIST="252",e.REMOTE_PUBLISH_STATE_CHANGED="253",e.AUDIO_LEVEL_INTERVAL="260",e.NETWORK_QUALITY="261",e.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",e.QUALITY_LIMITATION_CHANGED="263",e.LOG="264",e.AUDIO_PROCESSOR_DEBUG="265",e.SSO_SWITCH="266",e.SEI_MESSAGE="267",e.USER_PAUSE_IN_PIP="268",e.USER_RESUME_IN_PIP="269",e.ENTER_PICTURE_IN_PICTURE="270",e.LEAVE_PICTURE_IN_PICTURE="271",e.SWITCH_ROOM_START="401",e.SWITCH_ROOM_SUCCESS="407",e.SWITCH_ROOM_FAILED="408",e))(w$||{}),Rs=w$,ouA=class{constructor(){pe(this,"enable",!1),pe(this,"ssoFailCount",0),Rn.on("22",({schedule:e})=>{var i;(i=e?.config)!=null&&i.sso&&Rn.emit("266",{enable:!0})}),Rn.on("266",({enable:e})=>{this.enable=e})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&Rn.emit("266",{enable:!1})}},vW=new ouA,nuA="%cTRTC%c%s",suA="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",ruA="display: inline",_$=class T${constructor(){pe(this,"_isEnableUploadLog",!0),pe(this,"_localJoinedUser",new Map),pe(this,"_queue",[]),pe(this,"_timeoutId",-1),pe(this,"_logLevel",1),pe(this,"_logLevelToUpload",2),w7||_7||(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){Rn.on(Rs.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var n;(n=i?.config)!=null&&n.logLevelToUpload&&Y_[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),Rn.on(Rs.JOIN_START,({params:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),Rn.on(Rs.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){const i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let n=0;for(;n{i.map.has(I)?i.map.get(I).logs.push(c):i.map.set(I,{userId:I,sdkAppId:C,logs:[c]})});else if(rh(c.userId)&&YM(c.sdkAppId)){const{userId:I,sdkAppId:C}=c;i.map.has(I)?i.map.get(I).logs.push(c):i.map.set(I,{userId:I,sdkAppId:C,logs:[c]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,n)),i}async upload(){if(this._queue.length===0||!this._isEnableUploadLog)return;const{map:i,splicedQueue:n}=this.getLogsToUpload();if(i.size===0)return;try{const I=[...i.values()];for(let C=0;CgA.log).join(` +`)},b=JSON.stringify(T),J=vW.enable?T4(T,2002,R):b;await this.uploadLogWithRetry(J,R,J instanceof Uint8Array,b),_.forEach(gA=>gA.uploaded=!0)}}catch{}const c=n.filter(I=>!I.uploaded);c.length>0&&(this._queue=c.concat(this._queue))}uploadLogWithRetry(i,n,c,I){return G4({retryFunction:()=>Z7({url:R4(n,T7.LOG),body:i,timeout:5e3,priority:"low"}).then(C=>{c&&C.data!=="ok"&&(vW.handleUploadFailed(),this.uploadLogWithRetry(I,n,!1,I))}),settings:{retries:3,timeout:2e3},onError:({retry:C})=>{C()}})()}getPrefix(i){const n=new Date;return n.setTime(M4()),`[${RlA(n)}] <${Y_[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){sr(Y_[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(rh(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch{return""}}addLogToQueue(i,n,c=!0,I,C){const m={log:n.reduce((R,_)=>`${R} ${this.logChunkToString(_)}`.trim(),""),level:i,userId:I,sdkAppId:C,forAllJoinedClients:c};Rn.emit(Rs.LOG,{log:m}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(m)}log(i,n,c=!0,I,C){var m;if(n.unshift(this.getPrefix(i)),this.addLogToQueue(i,n,c,I,C),i{const i=16*Math.random()|0;return(e=="x"?i:3&i|8).toString(16)})},N$=guA,cuA=class{constructor(){pe(this,"_prefix","TRTC"),pe(this,"_queue",new Map)}getRealKey(e){return`${this._prefix}_${e}`}checkStorage(){b_()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(e=>{if(e.startsWith(this._prefix))try{const i=localStorage.getItem(e);if(!i)return!1;const n=JSON.parse(i);if(n&&n.expiresInlocalStorage.removeItem(e)))}doFlush(){if(b_())try{for(const[e,i]of this._queue)localStorage.setItem(e,JSON.stringify(i))}catch(e){An.warn(e)}}getItem(e){if(!b_())return null;try{const i=localStorage.getItem(this.getRealKey(e));if(!i)return null;const n=JSON.parse(i);return n&&n.expiresIn>=Date.now()?n.value:null}catch(i){An.warn(i)}}setItem(e,i){if(b_())try{const n={expiresIn:Date.now()+blA,value:i};this._queue.set(this.getRealKey(e),n)}catch(n){An.warn(n)}}deleteItem(e){if(!b_())return!1;try{return e=this.getRealKey(e),this._queue.delete(e),localStorage.removeItem(e),!0}catch(i){return An.warn(i),!1}}clear(){if(b_())try{localStorage.clear()}catch(e){An.warn(e)}}},G$=new cuA,luA={};S4(luA,{HTTPS_API:()=>DuA,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>j$,IS_GET_CAPABILITIES_SUPPORTED:()=>K$,IS_GET_SETTINGS_SUPPORTED:()=>eV,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>GuA,IS_INSERTABLE_STREAM_SUPPORTED:()=>W$,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>OuA,IS_RTC_RTP_SENDER_SUPPORTED:()=>gF,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>z$,IS_SEI_SUPPORTED:()=>buA,IS_SPC_SUPPORTED:()=>wuA,basis:()=>LuA,capabilityCheck:()=>UuA,checkSystemRequirementsInternal:()=>U$,decodeSupportStatus:()=>L$,detectH264SupportedByFakeStreaming:()=>F$,detectVideoCodecCapabilities:()=>PuA,detectVideoDecoderCapabilities:()=>tAA,detectVideoEncoderCapabilities:()=>eAA,encodeSupportStatus:()=>z4,getBrowserInfo:()=>huA,getDisplayResolution:()=>O$,getH264ProfileLevelIds:()=>iAA,isAddTransceiverSupported:()=>jV,isBrowserSupported:()=>K4,isCanvasCaptureStreamAPISupported:()=>Y$,isCanvasSmallStreamSupported:()=>V$,isGetReceiversSupported:()=>MuA,isGetSendersSupported:()=>q$,isGetTransceiversSupported:()=>RuA,isGetUserMediaSupported:()=>P$,isMediaDevicesSupported:()=>W4,isMediaSessionSupported:()=>X$,isMediaStreamTrackGeneratorSupported:()=>QuA,isMediaStreamTrackProcessorSupported:()=>BuA,isReplaceTrackSupported:()=>TuA,isRequestVideoFrameCallbackSupported:()=>$4,isSIMDSupported:()=>kuA,isScaleResolutionDownBySupported:()=>H$,isScreenCaptureApiAvailable:()=>Z4,isSelectedCandidatePair:()=>SuA,isSetParametersSupported:()=>NuA,isSetSinkIdSupported:()=>fuA,isSmallStreamSupported:()=>J$,isStopTransceiverSupported:()=>_uA,isTRTCSupported:()=>muA,isUnifiedPlanDefault:()=>vuA,isUsedInHttpProtocol:()=>KV,isWebAudioSupported:()=>x$,isWebCodecSupported:()=>Z$,isWebCodecsSupported:()=>j4,isWebRTCSupported:()=>X4,isWebTransportSupported:()=>$$});var $Y={PLAY_FAILED:"PLAY_FAILED",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND"},Z_={AVOID_REPEATED_CALL:e=>`previous ${e.name}() is ongoing, please avoid repeated calls.`,INVALID_PARAMETER_REQUIRED:({key:e,rule:i,fnName:n,value:c})=>`'${e||i.name}' is a required param when calling ${n}(), received: ${c}.`,INVALID_PARAMETER_TYPE({key:e,rule:i,fnName:n,value:c}){const I=`${e||i.name}`;let C="";return C=Array.isArray(i.type)?i.type.join("|"):i.type,`'${I}' must be type of ${C} when calling ${n}(), received type: ${xM(c)}.`},INVALID_PARAMETER_EMPTY:({key:e,rule:i,fnName:n,value:c})=>`'${e||i.name}' cannot be '${c}' when calling ${n}().`,INVALID_PARAMETER_INSTANCE:({key:e,rule:i,fnName:n,value:c})=>`'${`${e||i.name}`}' must be instanceof ${`${i.instanceOf.name||i.instanceOf}`} when calling ${n}(), received type: ${xM(c)}.`,INVALID_PARAMETER_RANGE:({key:e,rule:i,fnName:n,value:c})=>`'${e||i.name}' must be one of ${i.values.join("|")} when calling ${n}(), received: ${c}.`,INVALID_PARAMETER_MIN:({key:e,rule:i,fnName:n,value:c})=>`the min value of ${e||i.name} is ${i.min}, received: ${c}.`,INVALID_PARAMETER_MAX:({key:e,rule:i,fnName:n,value:c})=>`the max value of ${e||i.name} is ${i.max}, received: ${c}.`,API_CALL_TIMEOUT:e=>`${e.commandDesc||e.command} timeout observed.`,SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:e=>`SignalChannel setup failure: (errorCode: ${e.errorCode}, errorMsg: ${e.errorMsg} }).`,ERROR_MESSAGE(e){let i=`${e.type} failed`;return e.message&&(i=`${i}: ${e.message}.`),i},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:e=>`exchange sdp failed ${e.errMsg}.`,UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:e=>`'${e}' must be validate string when useStringRoomId is true.`,INVALID_ROOMID_INTEGER:e=>`'${e}' must be an integer between [1, 4294967294] when useStringRoomId is false.`,INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED:({error:e,code:i})=>`Failed to join room - ${e} code: ${i}`,REJOIN_ROOM_FAILED:e=>`reJoin room: ${e.roomId} failed, please check your network.`,INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:e=>`duplicate ${e} stream publishing, please unpublish your prev ${e} stream and then re-publish.`,INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED:({message:e,userId:i,streamType:n})=>`failed to subscribe ${i} ${n} stream, reason: ${e}.`,INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:e=>`switchRole failed, errCode: ${e.code} errMsg: ${e.message}.`,CLIENT_BANNED:e=>`client was banned because of ${e.message}.`,INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:e=>`startPublishCDNStream failed, errMsg: ${e.message}.`,STOP_PUBLISH_CDN_FAILED:e=>`stopPublishCDNStream failed, errMsg: ${e.message}.`,INVALID_STREAM_ID:e=>`'${e}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`,START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:e=>`cannot replace ${e.kind} track because stream has not ${e.kind} track`,NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:e=>`startMixTranscode failed, errMsg: ${e.message}.`,STOP_MIX_TRANSCODE_FAILED:e=>`stopMixTranscode failed, errMsg: ${e.message}.`,MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO:({key:e,rule:i,fnName:n,value:c})=>`'${e||i.name}' cannot be less than 0 when calling ${n}().`,MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:e=>`'${e}' is required and must be between 1 and 15.`,MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:e,fnName:i})=>`'${e}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:e,fnName:i,type:n})=>`the element corresponding to '${e}' must be instanceof HTMLElement when calling ${i}(), received: ${n}.`,PLAY_FAILED:e=>`${e.media} play failed, browser exception: ${e.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:e=>`${e}Track is not supported on your browser.`,NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:e=>`${e.signalResponse} failed, response code is ${e.code} , errMsg: ${e.message}.`,CATCH_HANDLER_ERROR:({name:e,event:i})=>`an error was caught in ${e}.on('${i}', handler), please check your code in 'handler'.`,API_NOT_EXIST:({name:e})=>`experimental api ${e} does not exist.`,REPEAT_JOIN:e=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED:({funName:e})=>`failed to call ${e}() because client was destroyed.`,SEI_NOT_SUPPORT:e=>"not support to sendSEIMessage"+(e===!1?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:e,name:i,timesInSecond:n,maxSizeInSecond:c})=>`api ${i} call ${e?"size":"times"} is over ${e?`${c} bytes`:n} in a second.`,CONNECTION_ABORTED:e=>`connection aborted due to: ${e}`,API_CALL_ABORTED(e){let i;return i=e.message.includes("REMOTE_STREAM_NOT_EXIST")?`Subscribe ${e.userId} ${e.streamType} stream aborted, reason: remote user ${e.userId} unpublished stream.`:`API aborted, reason: ${e.message}`,i},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:e=>`'streamType' is required when 'userId' is not '*', calling ${e}()`,SWITCH_PLAYBACK_QUALITY_TIMEOUT:e=>`switchPlaybackQuality timeout: waiting for first frame of user ${e.userId}.`},i6=(e,i)=>i?`${hW}/${e}/${i}`:`${hW}/${e}/index.html`,IuA=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let e=localStorage==null?void 0:localStorage.getItem(GlA);if(e){e=JSON.parse(e);const i=document.createElement("script");i.type="text/javascript",i.text=e.message,document.body.appendChild(i);const n=window.TRTC_ERROR_INFO,c=window.TRTC_ERROR_LINK;return document.body.removeChild(i),{TRTC_ERROR_INFO:n,TRTC_ERROR_LINK:c}}return{}};function AV(e){const{key:i,data:n,link:c,addDocLink:I=!0}=e;let C="",m="",R="";_M(Z_[i])?C=Z_[i](n):rh(Z_[i])&&(C=Z_[i]);const{TRTC_ERROR_INFO:_,TRTC_ERROR_LINK:T}=IuA();c?R=`${c.className}.html#${c.fnName}`:T&&T[i]&&(_M(T[i])?R=T[i](n):rh(T[i])&&(R=T[i]));let b=C;return iD()&&(_&&_[i]&&(_M(_[i])?m=_[i](n):rh(_[i])&&(m=_[i])),m&&(b=I?`${m} 请查看文档: ${i6("zh-cn",R)} `:`${m} `,b+=C)),I&&(b+=` Refer to: ${i6("en",R)} -`),b}var o6=MT(plA()),uuA=1,EuA=0,b$=class{constructor(e=!0){pe(this,"countMap",new Map),pe(this,"distributionMap",new Map),pe(this,"version"),pe(this,"log",An.createLogger({id:"kv"})),e&&(Rn.on("102",({track:i,cost:n})=>{this.addSuccessEvent({key:i.kind===ni.AUDIO?501700:511700,cost:n})}),Rn.on("103",({track:i,error:n})=>{this.addFailedEvent({key:i.kind===ni.AUDIO?501700:511700,error:n})}),Rn.on("266",({enable:i})=>{this.log.info((i?"enable":"disable")+" sso"),i?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(e,i){const n={msg_sdk_basic_info:{uint32_sdk_version:H7(this.version||qY),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([c,I])=>({uint32_key:c,uint32_count:I})),stats_distribution:[...this.distributionMap.entries()].map(([c,I])=>({uint32_key:c,distribution_items:[...I.entries()].map(([C,m])=>({uint32_item_key:C,uint32_item_value:m}))})),str_user_sig:e,bytes_report_token:i};return this.countMap.clear(),this.distributionMap.clear(),n}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(e){const i=+String(e).slice(-3);return i>=700&&i<799}isErrorCodeKey(e){const i=+String(e).slice(-3);return i>=600&&i<699}isCountKey(e){const i=+String(e).slice(-3);return i>=0&&i<599}isNumberKey(e){const i=+String(e).slice(-3);return i>=800&&i<899}addCount({key:e,useUV:i=!1}){this.isCountKey(e)?i&&this.countMap.has(e)||this.countMap.set(e,(this.countMap.get(e)||0)+1):this.log.debug(`${e} is not count key, last 3 number should be 0~599`)}addEnum({key:e,value:i,useUV:n=!0}){var c;if(!this.isEnumKey(e))return this.log.debug(`${e} is not enum key, last 3 number should be 700~799`);if(n&&this.countMap.has(e))return;this.countMap.set(e,(this.countMap.get(e)||0)+1);const I=((c=this.distributionMap)==null?void 0:c.get(e))||new Map;I.set(i,(I.get(i)||0)+1),this.distributionMap.set(e,I)}addNumber({key:e,value:i,split:n=100,useUV:c=!1,max:I=5e3}){var C;if(!this.isNumberKey(e))return this.log.debug(`${e} is not number key, last 3 number should be 800~899`);if(c&&this.countMap.has(e))return;i>I&&(i=I),this.countMap.set(e,(this.countMap.get(e)||0)+1);const m=((C=this.distributionMap)==null?void 0:C.get(e))||new Map;let R=0;if(YM(n))R=Math.floor(i/n);else for(let _=n.length-1;_>0;_--)if(i>n[_]){R=_;break}m.set(R,(m.get(R)||0)+1),this.distributionMap.set(e,m)}addSuccessEvent({key:e,cost:i,timeKey:n,split:c}){if(e&&(this.addEnum({key:e,value:uuA,useUV:!1}),i)){const I=+String(e).slice(-3);I<800&&I>=700?this.addNumber({key:n||e+100,value:i,split:c}):n||this.log.debug(`time stat ignored, ${e}`)}}addFailedEvent({key:e,error:i}){if(!e)return;let n=Zg.UNKNOWN;i&&(YM(i)?n=i:sr(i.extraCode)&&sr(i.code)||(n=i.extraCode||i.code)),this.addEnum({key:e,value:EuA,useUV:!1}),this.addEnum({key:e,value:Math.abs(n),useUV:!1})}},k$=(e=>(e[e.DECODER_TYPE=514700]="DECODER_TYPE",e[e.DECODER_HW_SW=514701]="DECODER_HW_SW",e[e.DECODE_RESULT=514702]="DECODE_RESULT",e[e.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",e[e.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",e[e.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",e[e.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",e[e.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",e[e.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",e[e.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",e[e.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",e[e.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",e[e.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",e[e.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",e[e.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",e[e.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",e[e.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",e[e.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",e[e.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",e))(k$||{}),duA=new b$(!0);new b$(!1);var mr=duA,cs={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},CuA=new Map([[aC,["Firefox",e$]],[YV,["Edg",o$]],[J4,["Chrome",y$]],[ud,["Safari",aF]],[Sm,["TBS",r$]],[RT,["XWEB",a$]],[rF&&xV,["WeChat",g$]],[U4,["QQ(Win)",c$]],[HV,["QQ(Mobile)",zY]],[VV,["QQ(Mobile X5)",zY]],[F4,["QQ(Mac)",l$]],[O4,["QQ(iPad)",I$]],[P4,["MI",C$]],[x4,["HW",B$]],[Y4,["Samsung",Q$]],[qV,["OPPO",p$]],[V4,["VIVO",m$]],[sF,["EDGE",i$]],[k4,["SogouMobile",n$]],[L4,["Sogou",s$]]]);function huA(){const e=CuA.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var K4=function(){return!HIA&&!sF&&!(YV&&YIA<80)&&!(aC&&t$<56)},j4=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(e=>e in window)},W4=function(){if(!navigator.mediaDevices)return KV()||An.error(Z_.NOT_SUPPORTED_MEDIA),!1;const e=["getUserMedia","enumerateDevices"];return e.filter(i=>i in navigator.mediaDevices).length===e.length},n6=!1;function KV(){return location.protocol==="http:"&&!XY&&(n6||An.error(AV({key:$Y.NOT_SUPPORTED_HTTP})),n6=!0,!0)}var BuA=function(){return window?.OffscreenCanvas&&window?.MediaStreamTrackProcessor&&window?.MediaStreamTrackGenerator},QuA=function(){return!!window?.MediaStreamTrackGenerator},z4=async function(){var e,i,n;if(cs.detail.isH264EncodeSupported&&cs.detail.isVp8EncodeSupported)return{isH264EncodeSupported:cs.detail.isH264EncodeSupported,isVp8EncodeSupported:cs.detail.isVp8EncodeSupported,isH265EncodeSupported:cs.detail.isH265EncodeSupported};let c,I=!1,C=!1,m=!1;try{const R=new RTCPeerConnection,_=document.createElement(ni.CANVAS);_.getContext("2d");const T=_.captureStream(0);return R.addTrack(T.getVideoTracks()[0],T),c=await R.createOffer(),I=((e=c.sdp)==null?void 0:e.toLowerCase().indexOf("h264"))!==-1,C=((i=c.sdp)==null?void 0:i.toLowerCase().indexOf("vp8"))!==-1,m=((n=c.sdp)==null?void 0:n.toLowerCase().indexOf("h265"))!==-1,R.close(),{isH264EncodeSupported:I,isVp8EncodeSupported:C,isH265EncodeSupported:m}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}},L$=async function(){var e;if(cs.detail.isH264DecodeSupported&&cs.detail.isVp8DecodeSupported)return{isH264DecodeSupported:cs.detail.isH264DecodeSupported,isVp8DecodeSupported:cs.detail.isVp8DecodeSupported,isH265DecodeSupported:cs.detail.isH265DecodeSupported};let i,n=!1,c=!1;try{const I=new RTCPeerConnection;jV()?(I.addTransceiver(ni.VIDEO,{direction:"recvonly"}),i=await I.createOffer()):i=await I.createOffer({offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(n=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(c=!0);const C=((e=i.sdp)==null?void 0:e.toLowerCase().indexOf("h265"))!==-1;return I.close(),{isH264DecodeSupported:n,isVp8DecodeSupported:c,isH265DecodeSupported:C}}catch{return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}};async function puA(){const[e,i]=await Promise.all([z4(),L$()]);return{encode:{h264:e.isH264EncodeSupported,vp8:e.isVp8EncodeSupported,h265:e.isH265EncodeSupported},decode:{h264:i.isH264DecodeSupported,vp8:i.isVp8DecodeSupported,h265:i.isH265DecodeSupported}}}var U$=q7(async e=>{const i=Date.now(),n=X4(),c=W4(),I=j4();if(cs.detail.isWebRTCSupported=n,cs.detail.isMediaDevicesSupported=c,cs.detail.isWebCodecsSupported=I,cs.detail.isScreenShareSupported=Z4(),cs.detail.isSmallStreamSupported=J$(),e===37)return Object.assign(cs.detail,await yuA()),cs.detail.isBrowserSupported=I,cs.result=c&&I,cs.result||An.error(`${navigator.userAgent} ${DW(cs.detail,!1)}`),a6(e),mr.addNumber({key:523800,value:Date.now()-i}),cs;if(cs.result&&cs.detail.isH264EncodeSupported&&cs.detail.isVp8EncodeSupported&&cs.detail.isH265EncodeSupported&&cs.detail.isH264DecodeSupported&&cs.detail.isVp8DecodeSupported&&cs.detail.isH265DecodeSupported)return cs;const C=K4(),{encode:m,decode:R}=await puA();let{h264:_,vp8:T}=m,{h264:b}=R;const{h265:J}=m,{vp8:cA,h265:eA}=R;if(!_||!T){const CA=await z4();An.warn(`detect encode again h264:${_} vp8:${T} result: ${JSON.stringify(CA)}`),_=CA.isH264EncodeSupported,T=CA.isVp8EncodeSupported}if(_&&b&&cC&&lD&&!RT&&!Sm&&(!qV||ID!==115)){const{encode:CA,decode:IA}=await F$();_=CA,b=IA}return cs.result=C&&n&&c&&(_||T)&&(b||cA),cs.detail.isBrowserSupported=C,cs.detail.isWebRTCSupported=n,cs.detail.isH264EncodeSupported=_,cs.detail.isVp8EncodeSupported=T,cs.detail.isH265EncodeSupported=J,cs.detail.isH264DecodeSupported=b,cs.detail.isVp8DecodeSupported=cA,cs.detail.isH265DecodeSupported=eA,cs.result||An.error(`${navigator.userAgent} ${DW(cs.detail,!1)}`),a6(),mr.addNumber({key:523800,value:Date.now()-i}),cs}),muA=function(){return cs.result},Z4=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},fuA=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype,s6=null;async function F$(e=2e3){return s6||(s6=new Promise(async i=>{const n={encode:!1,decode:!1};let c=()=>{};try{const I=document.createElement("canvas"),C=I.getContext("2d");I.width=640,I.height=480;const m=setInterval(()=>{C.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))},66);let R=-1,_=-1;c=()=>{clearInterval(R),clearInterval(m),clearTimeout(_),b.close(),J.close(),T.getTracks().forEach(oA=>oA.stop())},_=setTimeout(()=>{c(),i(n)},e);const T=I.captureStream(),b=new RTCPeerConnection({}),J=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});b.addEventListener("icecandidate",oA=>J.addIceCandidate(oA.candidate)),J.addEventListener("icecandidate",oA=>b.addIceCandidate(oA.candidate)),b.addTrack(T.getVideoTracks()[0],T);const cA=await b.createOffer();await b.setLocalDescription(cA),await J.setRemoteDescription(cA);const eA=await J.createAnswer(),CA=o6.default.parse(eA.sdp),IA=CA.media[0].rtp.findIndex(oA=>oA.codec==="H264");CA.media[0].rtp=[CA.media[0].rtp[IA]],CA.media[0].fmtp=CA.media[0].fmtp.filter(oA=>oA.payload===CA.media[0].rtp[0].payload),CA.media[0].rtcpFb&&(CA.media[0].rtcpFb=CA.media[0].rtcpFb.filter(oA=>oA.payload===CA.media[0].rtp[0].payload)),eA.sdp=o6.default.write(CA),await J.setLocalDescription(eA),await b.setRemoteDescription(eA),R=setInterval(async()=>{n.encode&&n.decode&&(c(),i(n));const[oA,vA]=await Promise.all([b.getSenders()[0].getStats(),J.getReceivers()[0].getStats()]);n.encode||oA.forEach(qA=>{qA.type==="outbound-rtp"&&(qA.mediaType===ni.VIDEO||qA.kind===ni.VIDEO)&&qA.bytesSent>0&&(n.encode=!0)}),n.decode||vA.forEach(qA=>{qA.type==="inbound-rtp"&&(qA.mediaType===ni.VIDEO||qA.kind===ni.VIDEO)&&qA.bytesReceived>0&&(n.decode=!0)})},100)}catch(I){c(),An.warn("detectH264Supported failed",I),i({encode:!0,decode:!0})}}).then(i=>(i.encode||(i.decode=!0),i.encode&&i.decode||An.warn(`detectH264Supported encode: ${i.encode} decode: ${i.decode} ${$IA}`),i)))}var r6=null;async function yuA(){return r6||(r6=new Promise(async e=>{const i={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!j4())return void e(i);let n=null,c=null,I=null;const C=()=>{I&&clearTimeout(I),n=null,c=null};try{n=document.createElement("canvas"),c=n.getContext("2d"),n.width=320,n.height=240;let m=0;const R=()=>{c&&n&&(c.fillStyle=`hsl(${m%360}, 50%, 50%)`,c.fillRect(0,0,n.width,n.height),c.fillStyle="white",c.font="20px Arial",c.fillText(`Frame ${m}`,10,30),m++)};I=setTimeout(()=>{C(),e(i)},5e3);const _=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(await Promise.all(_.map(async T=>{const b={type:T.type,encodeSupported:!1,decodeSupported:!1};let J;try{J=await new Promise(async(cA,eA)=>{try{const CA=new VideoEncoder({output:oA=>{cA(oA),b.encodeSupported=!0},error:eA});CA.configure(T.encodeConfig),R();const IA=new VideoFrame(n,{timestamp:0});CA.encode(IA,{keyFrame:!0}),IA.close(),await CA.flush(),CA.close()}catch(CA){eA(CA)}})}catch(cA){return An.warn(`${T.type} encoder error:`,cA),b}try{await new Promise(async(cA,eA)=>{try{const CA=new VideoDecoder({output:IA=>{b.decodeSupported=!0,cA(0),IA.close()},error:eA});CA.configure(T.decodeConfig),CA.decode(J),await CA.flush(),CA.close()}catch(CA){eA(CA)}})}catch(cA){An.warn(`${T.type} decoder error:`,cA)}return b}))).forEach(T=>{T.type==="h264"?(i.isH264EncodeSupported=T.encodeSupported,i.isH264DecodeSupported=T.decodeSupported):T.type==="vp8"&&(i.isVp8EncodeSupported=T.encodeSupported,i.isVp8DecodeSupported=T.decodeSupported)}),C(),e(i)}catch(m){C(),An.warn("detectWebCodecsSupported failed:",m),e(i)}}))}var DuA=(e,i,n)=>{location.protocol!=="http:"||XY||(e[i]=()=>{throw new vl({code:Zg.INVALID_OPERATION,message:Z_.NOT_SUPPORTED_HTTP})})},SuA=function(e){return!(e.type!=="candidate-pair"||!e.nominated||e.state!=="in-progress"&&e.state!=="succeeded")&&!(TM(e.selected)&&!e.selected)};function O$(){let e="";return screen.width&&(e+=`${screen.width?screen.width*window.devicePixelRatio:""} * ${screen.height?screen.height*window.devicePixelRatio:""}`),e}function P$(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function x$(){const e={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let n=0;n=86,z$="RTCRtpScriptTransform"in window,buA=gF&&(W$||z$),X4=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(e=>e in window).length>0};function Z$(){const e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return sr(window.AudioDecoder)||(e.AudioDecoder=!0),sr(window.AudioEncoder)||(e.AudioEncoder=!0),sr(window.VideoDecoder)||(e.VideoDecoder=!0),sr(window.VideoEncoder)||(e.VideoEncoder=!0),sr(window.ImageDecoder)||(e.ImageDecoder=!0),e}function X$(){return"mediaSession"in navigator&&!sr(navigator.mediaSession.setActionHandler)}function $$(){return!sr(window.WebTransport)}function kuA(){return typeof WebAssembly<"u"&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function LuA(){const e={browser:`${NM.name}/${NM.version}`,os:M$(),displayResolution:O$(),isScreenShareSupported:Z4(),isWebRTCSupported:X4(),isGetUserMediaSupported:P$(),isWebAudioSupported:x$(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Z$(),isMediaSessionSupported:X$(),isWebTransportSupported:$$()};return navigator.userAgent.includes("miniProgram")&&(e.browser=`mini/${e.browser}`),e}var AAA="checkResult";function a6(e=30){G$.setItem(AAA+e,{ua:navigator.userAgent,checkResult:cs})}function UuA(e){KV();const i=G$.getItem(AAA+e);i&&i.ua===navigator.userAgent&&i.checkResult&&FuA(i.checkResult.detail,cs.detail)&&(cs=i.checkResult),U$(e)}function FuA(e,i){return!!SM(e)&&Object.keys(i).every(n=>n in e)}function $4(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var OuA="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function g6(e){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[e]}var c6=!1;async function PuA(){var e;try{if(c6||!((e=navigator?.mediaCapabilities)!=null&&e.encodingInfo))return;const i=q4(),n=euA();if(i===0||n===0)return;c6=!0;const c=["H264","VP8","VP9","AV1","H265"],[I,C]=await Promise.all([eAA(c),tAA(c)]);I&&Object.keys(I).forEach(_=>{const T=g6(_.toLowerCase());mr.addEnum({key:513707,value:+`${T}${+I[_].supported}${+I[_].powerEfficient}${i}${n}`,useUV:!1})}),C&&Object.keys(C).forEach(_=>{const T=g6(_.toLowerCase());mr.addEnum({key:514713,value:+`${T}${+C[_].supported}${+C[_].powerEfficient}${i}${n}`,useUV:!1})});const{sender:m,receiver:R}=iAA();mr.addEnum({key:513708,value:+`${i}${n}${+m.high}`,useUV:!1}),mr.addEnum({key:513709,value:+`${i}${n}${+m.main}`,useUV:!1}),mr.addEnum({key:514714,value:+`${i}${n}${+R.high}`,useUV:!1}),mr.addEnum({key:514715,value:+`${i}${n}${+R.main}`,useUV:!1})}catch(i){An.info("detectVideoCodecCapabilities failed",i)}}async function eAA(e,i=1920,n=1080,c=30,I=3e3){const C={};try{for(const m of e){const R=await navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:`video/${m}`,width:i,height:n,bitrate:I,framerate:c}});C[m]=R}}catch{}return C}async function tAA(e,i=1920,n=1080,c=30,I=3e3){const C={};try{for(const m of e){const R=await navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:`video/${m}`,width:i,height:n,bitrate:I,framerate:c}});C[m]=R}}catch{}return C}function iAA(){const e={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){const i=RTCRtpSender.getCapabilities("video");i&&i.codecs&&i.codecs.filter(n=>n.mimeType.toLowerCase()==="video/h264").forEach(n=>{if(n.sdpFmtpLine){const c=n.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(c&&c[1])switch(c[1].slice(0,2)){case"42":e.sender.base=!0;break;case"4d":e.sender.main=!0;break;case"64":e.sender.high=!0}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){const i=RTCRtpReceiver.getCapabilities("video");i&&i.codecs&&i.codecs.filter(n=>n.mimeType.toLowerCase()==="video/h264").forEach(n=>{if(n.sdpFmtpLine){const c=n.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(c&&c[1])switch(c[1].slice(0,2)){case"42":e.receiver.base=!0;break;case"4d":e.receiver.main=!0;break;case"64":e.receiver.high=!0}}})}}catch(i){An.warn("get H264 profile levelId failed",i)}return e}var xuA=MT(oF()),l6=Symbol("instance"),oY=Symbol("cacheResult"),S3=class{constructor(e,i,n){this.oldState=e,this.newState=i,this.action=n,this.aborted=!1}abort(e){this.aborted=!0,pU.call(e,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},v3=class extends Error{constructor(e,i,n){super(i),this.state=e,this.message=i,this.cause=n}};function YuA(e){return typeof e=="object"&&e&&"then"in e}var QU=new Map;function Ru(e,i,n={}){return(c,I,C)=>{const m=n.action||I;if(!n.context){const _=QU.get(c)||[];QU.has(c)||QU.set(c,_),_.push({from:e,to:i,action:m})}const R=C.value;C.value=function(..._){let T=this;if(n.context&&(T=nr.get(typeof n.context=="function"?n.context.call(this,..._):n.context)),T.state===i)return n.sync?T[oY]:Promise.resolve(T[oY]);T.state instanceof S3&&T.state.action==n.abortAction&&T.state.abort(T);let b=null;Array.isArray(e)?e.length==0?T.state instanceof S3&&T.state.abort(T):typeof T.state=="string"&&e.includes(T.state)||(b=new v3(T._state,`${T.name} ${m} to ${i} failed: current state ${T._state} not from ${e.join("|")}`)):e!==T.state&&(b=new v3(T._state,`${T.name} ${m} to ${i} failed: current state ${T._state} not from ${e}`));const J=oA=>{if(n.fail&&n.fail.call(this,oA),n.sync){if(n.ignoreError)return oA;throw oA}return n.ignoreError?Promise.resolve(oA):Promise.reject(oA)};if(b)return J(b);const cA=T.state,eA=new S3(cA,i,m);pU.call(T,eA);const CA=oA=>{var vA;return T[oY]=oA,eA.aborted||(pU.call(T,i),(vA=n.success)===null||vA===void 0||vA.call(this,T[oY])),oA},IA=oA=>(pU.call(T,cA,oA),J(oA));try{const oA=R.apply(this,_);return YuA(oA)?oA.then(CA).catch(IA):n.sync?CA(oA):Promise.resolve(CA(oA))}catch(oA){return IA(new v3(T._state,`${T.name} ${m} from ${e} to ${i} failed: ${oA}`,oA instanceof Error?oA:new Error(String(oA))))}}}}var VuA=typeof window<"u"&&window.__AFSM__?(n,c)=>{window.dispatchEvent(new CustomEvent(n,{detail:c}))}:typeof importScripts<"u"?(n,c)=>{postMessage({type:n,payload:c})}:()=>{};function pU(e,i){const n=this._state;this._state=e;const c=e.toString();e&&this.emit(c,n),this.emit(nr.STATECHANGED,e,n,i),this.updateDevTools({value:e,old:n,err:i instanceof Error?i.message:String(i)})}var nr=class XC extends xuA.default{constructor(i,n,c){super(),this.name=i,this.groupName=n,this._state=XC.INIT,i||(i=Date.now().toString(36)),c?Object.setPrototypeOf(this,c):c=Object.getPrototypeOf(this),n||(this.groupName=this.constructor.name);const I=c[l6];I?this.name=I.name+"-"+I.count++:c[l6]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){const i=Object.getPrototypeOf(this),n=QU.get(i)||[];let c=new Set,I=[],C=[];const m=new Set,R=Object.getPrototypeOf(i);QU.has(R)&&(R.stateDiagram.forEach(T=>c.add(T)),R.allStates.forEach(T=>m.add(T))),n.forEach(({from:T,to:b,action:J})=>{typeof T=="string"?I.push({from:T,to:b,action:J}):T.length?T.forEach(cA=>{I.push({from:cA,to:b,action:J})}):C.push({to:b,action:J})}),I.forEach(({from:T,to:b,action:J})=>{m.add(T),m.add(b),m.add(J+"ing"),c.add(`${T} --> ${J}ing : ${J}`),c.add(`${J}ing --> ${b} : ${J} 🟢`),c.add(`${J}ing --> ${T} : ${J} 🔴`)}),C.forEach(({to:T,action:b})=>{c.add(`${b}ing --> ${T} : ${b} 🟢`),m.forEach(J=>{J!==T&&c.add(`${J} --> ${b}ing : ${b}`)})});const _=[...c];return Object.defineProperties(i,{stateDiagram:{value:_},allStates:{value:m}}),_}static get(i){let n;return typeof i=="string"?(n=XC.instances.get(i),n||XC.instances.set(i,n=new XC(i,void 0,Object.create(XC.prototype)))):(n=XC.instances2.get(i),n||XC.instances2.set(i,n=new XC(i.constructor.name,void 0,Object.create(XC.prototype)))),n}static getState(i){var n;return(n=XC.get(i))===null||n===void 0?void 0:n.state}updateDevTools(i={}){VuA(XC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){pU.call(this,i)}};nr.STATECHANGED="stateChanged",nr.UPDATEAFSM="updateAFSM",nr.INIT="[*]",nr.ON="on",nr.OFF="off",nr.instances=new Map,nr.instances2=new WeakMap;var A5=typeof window<"u",I6=A5&&window.requestIdleCallback||function(e){const i=Date.now();return setTimeout(()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-i))})},1e3)},HuA=A5&&window.cancelIdleCallback||function(e){clearTimeout(e)},u6=A5&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),WL=class QE{static generateTaskID(){return this.currentTaskID++}static run(i,n,c){c?.fps&&(c.delay=c.delay||Number((1e3/c.fps).toFixed(2))),c=ks(ks({},i==="interval"?{delay:2e3,count:0,backgroundTask:!0}:i==="ric"?{delay:1e4,count:0}:i==="raf"?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0}),c);const I=cB(ks({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:n},c),{delay:c.delay});return this.taskMap.set(I.taskID,I),this[i](I),I.taskID}static interval(i){return i.intervalID=setInterval(()=>{i.callback(),i.loopCount+=1,QE.isBreakLoop(i)},i.delay)}static intervalInWorker(i){QE.sharedWorker||(QE.sharedWorker=new Worker(URL.createObjectURL(new Blob([` +`),b}var o6=MT(plA()),uuA=1,EuA=0,b$=class{constructor(e=!0){pe(this,"countMap",new Map),pe(this,"distributionMap",new Map),pe(this,"version"),pe(this,"log",An.createLogger({id:"kv"})),e&&(Rn.on("102",({track:i,cost:n})=>{this.addSuccessEvent({key:i.kind===ni.AUDIO?501700:511700,cost:n})}),Rn.on("103",({track:i,error:n})=>{this.addFailedEvent({key:i.kind===ni.AUDIO?501700:511700,error:n})}),Rn.on("266",({enable:i})=>{this.log.info((i?"enable":"disable")+" sso"),i?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(e,i){const n={msg_sdk_basic_info:{uint32_sdk_version:H7(this.version||qY),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([c,I])=>({uint32_key:c,uint32_count:I})),stats_distribution:[...this.distributionMap.entries()].map(([c,I])=>({uint32_key:c,distribution_items:[...I.entries()].map(([C,m])=>({uint32_item_key:C,uint32_item_value:m}))})),str_user_sig:e,bytes_report_token:i};return this.countMap.clear(),this.distributionMap.clear(),n}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(e){const i=+String(e).slice(-3);return i>=700&&i<799}isErrorCodeKey(e){const i=+String(e).slice(-3);return i>=600&&i<699}isCountKey(e){const i=+String(e).slice(-3);return i>=0&&i<599}isNumberKey(e){const i=+String(e).slice(-3);return i>=800&&i<899}addCount({key:e,useUV:i=!1}){this.isCountKey(e)?i&&this.countMap.has(e)||this.countMap.set(e,(this.countMap.get(e)||0)+1):this.log.debug(`${e} is not count key, last 3 number should be 0~599`)}addEnum({key:e,value:i,useUV:n=!0}){var c;if(!this.isEnumKey(e))return this.log.debug(`${e} is not enum key, last 3 number should be 700~799`);if(n&&this.countMap.has(e))return;this.countMap.set(e,(this.countMap.get(e)||0)+1);const I=((c=this.distributionMap)==null?void 0:c.get(e))||new Map;I.set(i,(I.get(i)||0)+1),this.distributionMap.set(e,I)}addNumber({key:e,value:i,split:n=100,useUV:c=!1,max:I=5e3}){var C;if(!this.isNumberKey(e))return this.log.debug(`${e} is not number key, last 3 number should be 800~899`);if(c&&this.countMap.has(e))return;i>I&&(i=I),this.countMap.set(e,(this.countMap.get(e)||0)+1);const m=((C=this.distributionMap)==null?void 0:C.get(e))||new Map;let R=0;if(YM(n))R=Math.floor(i/n);else for(let _=n.length-1;_>0;_--)if(i>n[_]){R=_;break}m.set(R,(m.get(R)||0)+1),this.distributionMap.set(e,m)}addSuccessEvent({key:e,cost:i,timeKey:n,split:c}){if(e&&(this.addEnum({key:e,value:uuA,useUV:!1}),i)){const I=+String(e).slice(-3);I<800&&I>=700?this.addNumber({key:n||e+100,value:i,split:c}):n||this.log.debug(`time stat ignored, ${e}`)}}addFailedEvent({key:e,error:i}){if(!e)return;let n=Zg.UNKNOWN;i&&(YM(i)?n=i:sr(i.extraCode)&&sr(i.code)||(n=i.extraCode||i.code)),this.addEnum({key:e,value:EuA,useUV:!1}),this.addEnum({key:e,value:Math.abs(n),useUV:!1})}},k$=(e=>(e[e.DECODER_TYPE=514700]="DECODER_TYPE",e[e.DECODER_HW_SW=514701]="DECODER_HW_SW",e[e.DECODE_RESULT=514702]="DECODE_RESULT",e[e.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",e[e.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",e[e.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",e[e.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",e[e.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",e[e.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",e[e.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",e[e.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",e[e.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",e[e.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",e[e.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",e[e.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",e[e.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",e[e.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",e[e.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",e[e.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",e))(k$||{}),duA=new b$(!0);new b$(!1);var fr=duA,cs={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},CuA=new Map([[aC,["Firefox",e$]],[YV,["Edg",o$]],[J4,["Chrome",y$]],[ud,["Safari",aF]],[Sm,["TBS",r$]],[RT,["XWEB",a$]],[rF&&xV,["WeChat",g$]],[U4,["QQ(Win)",c$]],[HV,["QQ(Mobile)",zY]],[VV,["QQ(Mobile X5)",zY]],[F4,["QQ(Mac)",l$]],[O4,["QQ(iPad)",I$]],[P4,["MI",C$]],[x4,["HW",B$]],[Y4,["Samsung",Q$]],[qV,["OPPO",p$]],[V4,["VIVO",m$]],[sF,["EDGE",i$]],[k4,["SogouMobile",n$]],[L4,["Sogou",s$]]]);function huA(){const e=CuA.get(!0);return{browserName:e?e[0]:"unknown",browserVersion:e?e[1]:"unknown"}}var K4=function(){return!HIA&&!sF&&!(YV&&YIA<80)&&!(aC&&t$<56)},j4=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(e=>e in window)},W4=function(){if(!navigator.mediaDevices)return KV()||An.error(Z_.NOT_SUPPORTED_MEDIA),!1;const e=["getUserMedia","enumerateDevices"];return e.filter(i=>i in navigator.mediaDevices).length===e.length},n6=!1;function KV(){return location.protocol==="http:"&&!XY&&(n6||An.error(AV({key:$Y.NOT_SUPPORTED_HTTP})),n6=!0,!0)}var BuA=function(){return window?.OffscreenCanvas&&window?.MediaStreamTrackProcessor&&window?.MediaStreamTrackGenerator},QuA=function(){return!!window?.MediaStreamTrackGenerator},z4=async function(){var e,i,n;if(cs.detail.isH264EncodeSupported&&cs.detail.isVp8EncodeSupported)return{isH264EncodeSupported:cs.detail.isH264EncodeSupported,isVp8EncodeSupported:cs.detail.isVp8EncodeSupported,isH265EncodeSupported:cs.detail.isH265EncodeSupported};let c,I=!1,C=!1,m=!1;try{const R=new RTCPeerConnection,_=document.createElement(ni.CANVAS);_.getContext("2d");const T=_.captureStream(0);return R.addTrack(T.getVideoTracks()[0],T),c=await R.createOffer(),I=((e=c.sdp)==null?void 0:e.toLowerCase().indexOf("h264"))!==-1,C=((i=c.sdp)==null?void 0:i.toLowerCase().indexOf("vp8"))!==-1,m=((n=c.sdp)==null?void 0:n.toLowerCase().indexOf("h265"))!==-1,R.close(),{isH264EncodeSupported:I,isVp8EncodeSupported:C,isH265EncodeSupported:m}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}},L$=async function(){var e;if(cs.detail.isH264DecodeSupported&&cs.detail.isVp8DecodeSupported)return{isH264DecodeSupported:cs.detail.isH264DecodeSupported,isVp8DecodeSupported:cs.detail.isVp8DecodeSupported,isH265DecodeSupported:cs.detail.isH265DecodeSupported};let i,n=!1,c=!1;try{const I=new RTCPeerConnection;jV()?(I.addTransceiver(ni.VIDEO,{direction:"recvonly"}),i=await I.createOffer()):i=await I.createOffer({offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(n=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(c=!0);const C=((e=i.sdp)==null?void 0:e.toLowerCase().indexOf("h265"))!==-1;return I.close(),{isH264DecodeSupported:n,isVp8DecodeSupported:c,isH265DecodeSupported:C}}catch{return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}};async function puA(){const[e,i]=await Promise.all([z4(),L$()]);return{encode:{h264:e.isH264EncodeSupported,vp8:e.isVp8EncodeSupported,h265:e.isH265EncodeSupported},decode:{h264:i.isH264DecodeSupported,vp8:i.isVp8DecodeSupported,h265:i.isH265DecodeSupported}}}var U$=q7(async e=>{const i=Date.now(),n=X4(),c=W4(),I=j4();if(cs.detail.isWebRTCSupported=n,cs.detail.isMediaDevicesSupported=c,cs.detail.isWebCodecsSupported=I,cs.detail.isScreenShareSupported=Z4(),cs.detail.isSmallStreamSupported=J$(),e===37)return Object.assign(cs.detail,await yuA()),cs.detail.isBrowserSupported=I,cs.result=c&&I,cs.result||An.error(`${navigator.userAgent} ${DW(cs.detail,!1)}`),a6(e),fr.addNumber({key:523800,value:Date.now()-i}),cs;if(cs.result&&cs.detail.isH264EncodeSupported&&cs.detail.isVp8EncodeSupported&&cs.detail.isH265EncodeSupported&&cs.detail.isH264DecodeSupported&&cs.detail.isVp8DecodeSupported&&cs.detail.isH265DecodeSupported)return cs;const C=K4(),{encode:m,decode:R}=await puA();let{h264:_,vp8:T}=m,{h264:b}=R;const{h265:J}=m,{vp8:gA,h265:eA}=R;if(!_||!T){const CA=await z4();An.warn(`detect encode again h264:${_} vp8:${T} result: ${JSON.stringify(CA)}`),_=CA.isH264EncodeSupported,T=CA.isVp8EncodeSupported}if(_&&b&&cC&&lD&&!RT&&!Sm&&(!qV||ID!==115)){const{encode:CA,decode:IA}=await F$();_=CA,b=IA}return cs.result=C&&n&&c&&(_||T)&&(b||gA),cs.detail.isBrowserSupported=C,cs.detail.isWebRTCSupported=n,cs.detail.isH264EncodeSupported=_,cs.detail.isVp8EncodeSupported=T,cs.detail.isH265EncodeSupported=J,cs.detail.isH264DecodeSupported=b,cs.detail.isVp8DecodeSupported=gA,cs.detail.isH265DecodeSupported=eA,cs.result||An.error(`${navigator.userAgent} ${DW(cs.detail,!1)}`),a6(),fr.addNumber({key:523800,value:Date.now()-i}),cs}),muA=function(){return cs.result},Z4=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},fuA=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype,s6=null;async function F$(e=2e3){return s6||(s6=new Promise(async i=>{const n={encode:!1,decode:!1};let c=()=>{};try{const I=document.createElement("canvas"),C=I.getContext("2d");I.width=640,I.height=480;const m=setInterval(()=>{C.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))},66);let R=-1,_=-1;c=()=>{clearInterval(R),clearInterval(m),clearTimeout(_),b.close(),J.close(),T.getTracks().forEach(oA=>oA.stop())},_=setTimeout(()=>{c(),i(n)},e);const T=I.captureStream(),b=new RTCPeerConnection({}),J=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});b.addEventListener("icecandidate",oA=>J.addIceCandidate(oA.candidate)),J.addEventListener("icecandidate",oA=>b.addIceCandidate(oA.candidate)),b.addTrack(T.getVideoTracks()[0],T);const gA=await b.createOffer();await b.setLocalDescription(gA),await J.setRemoteDescription(gA);const eA=await J.createAnswer(),CA=o6.default.parse(eA.sdp),IA=CA.media[0].rtp.findIndex(oA=>oA.codec==="H264");CA.media[0].rtp=[CA.media[0].rtp[IA]],CA.media[0].fmtp=CA.media[0].fmtp.filter(oA=>oA.payload===CA.media[0].rtp[0].payload),CA.media[0].rtcpFb&&(CA.media[0].rtcpFb=CA.media[0].rtcpFb.filter(oA=>oA.payload===CA.media[0].rtp[0].payload)),eA.sdp=o6.default.write(CA),await J.setLocalDescription(eA),await b.setRemoteDescription(eA),R=setInterval(async()=>{n.encode&&n.decode&&(c(),i(n));const[oA,vA]=await Promise.all([b.getSenders()[0].getStats(),J.getReceivers()[0].getStats()]);n.encode||oA.forEach(qA=>{qA.type==="outbound-rtp"&&(qA.mediaType===ni.VIDEO||qA.kind===ni.VIDEO)&&qA.bytesSent>0&&(n.encode=!0)}),n.decode||vA.forEach(qA=>{qA.type==="inbound-rtp"&&(qA.mediaType===ni.VIDEO||qA.kind===ni.VIDEO)&&qA.bytesReceived>0&&(n.decode=!0)})},100)}catch(I){c(),An.warn("detectH264Supported failed",I),i({encode:!0,decode:!0})}}).then(i=>(i.encode||(i.decode=!0),i.encode&&i.decode||An.warn(`detectH264Supported encode: ${i.encode} decode: ${i.decode} ${$IA}`),i)))}var r6=null;async function yuA(){return r6||(r6=new Promise(async e=>{const i={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!j4())return void e(i);let n=null,c=null,I=null;const C=()=>{I&&clearTimeout(I),n=null,c=null};try{n=document.createElement("canvas"),c=n.getContext("2d"),n.width=320,n.height=240;let m=0;const R=()=>{c&&n&&(c.fillStyle=`hsl(${m%360}, 50%, 50%)`,c.fillRect(0,0,n.width,n.height),c.fillStyle="white",c.font="20px Arial",c.fillText(`Frame ${m}`,10,30),m++)};I=setTimeout(()=>{C(),e(i)},5e3);const _=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(await Promise.all(_.map(async T=>{const b={type:T.type,encodeSupported:!1,decodeSupported:!1};let J;try{J=await new Promise(async(gA,eA)=>{try{const CA=new VideoEncoder({output:oA=>{gA(oA),b.encodeSupported=!0},error:eA});CA.configure(T.encodeConfig),R();const IA=new VideoFrame(n,{timestamp:0});CA.encode(IA,{keyFrame:!0}),IA.close(),await CA.flush(),CA.close()}catch(CA){eA(CA)}})}catch(gA){return An.warn(`${T.type} encoder error:`,gA),b}try{await new Promise(async(gA,eA)=>{try{const CA=new VideoDecoder({output:IA=>{b.decodeSupported=!0,gA(0),IA.close()},error:eA});CA.configure(T.decodeConfig),CA.decode(J),await CA.flush(),CA.close()}catch(CA){eA(CA)}})}catch(gA){An.warn(`${T.type} decoder error:`,gA)}return b}))).forEach(T=>{T.type==="h264"?(i.isH264EncodeSupported=T.encodeSupported,i.isH264DecodeSupported=T.decodeSupported):T.type==="vp8"&&(i.isVp8EncodeSupported=T.encodeSupported,i.isVp8DecodeSupported=T.decodeSupported)}),C(),e(i)}catch(m){C(),An.warn("detectWebCodecsSupported failed:",m),e(i)}}))}var DuA=(e,i,n)=>{location.protocol!=="http:"||XY||(e[i]=()=>{throw new Ml({code:Zg.INVALID_OPERATION,message:Z_.NOT_SUPPORTED_HTTP})})},SuA=function(e){return!(e.type!=="candidate-pair"||!e.nominated||e.state!=="in-progress"&&e.state!=="succeeded")&&!(TM(e.selected)&&!e.selected)};function O$(){let e="";return screen.width&&(e+=`${screen.width?screen.width*window.devicePixelRatio:""} * ${screen.height?screen.height*window.devicePixelRatio:""}`),e}function P$(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function x$(){const e={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let n=0;n=86,z$="RTCRtpScriptTransform"in window,buA=gF&&(W$||z$),X4=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(e=>e in window).length>0};function Z$(){const e={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return sr(window.AudioDecoder)||(e.AudioDecoder=!0),sr(window.AudioEncoder)||(e.AudioEncoder=!0),sr(window.VideoDecoder)||(e.VideoDecoder=!0),sr(window.VideoEncoder)||(e.VideoEncoder=!0),sr(window.ImageDecoder)||(e.ImageDecoder=!0),e}function X$(){return"mediaSession"in navigator&&!sr(navigator.mediaSession.setActionHandler)}function $$(){return!sr(window.WebTransport)}function kuA(){return typeof WebAssembly<"u"&&WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]))}function LuA(){const e={browser:`${NM.name}/${NM.version}`,os:M$(),displayResolution:O$(),isScreenShareSupported:Z4(),isWebRTCSupported:X4(),isGetUserMediaSupported:P$(),isWebAudioSupported:x$(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:Z$(),isMediaSessionSupported:X$(),isWebTransportSupported:$$()};return navigator.userAgent.includes("miniProgram")&&(e.browser=`mini/${e.browser}`),e}var AAA="checkResult";function a6(e=30){G$.setItem(AAA+e,{ua:navigator.userAgent,checkResult:cs})}function UuA(e){KV();const i=G$.getItem(AAA+e);i&&i.ua===navigator.userAgent&&i.checkResult&&FuA(i.checkResult.detail,cs.detail)&&(cs=i.checkResult),U$(e)}function FuA(e,i){return!!SM(e)&&Object.keys(i).every(n=>n in e)}function $4(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var OuA="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function g6(e){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[e]}var c6=!1;async function PuA(){var e;try{if(c6||!((e=navigator?.mediaCapabilities)!=null&&e.encodingInfo))return;const i=q4(),n=euA();if(i===0||n===0)return;c6=!0;const c=["H264","VP8","VP9","AV1","H265"],[I,C]=await Promise.all([eAA(c),tAA(c)]);I&&Object.keys(I).forEach(_=>{const T=g6(_.toLowerCase());fr.addEnum({key:513707,value:+`${T}${+I[_].supported}${+I[_].powerEfficient}${i}${n}`,useUV:!1})}),C&&Object.keys(C).forEach(_=>{const T=g6(_.toLowerCase());fr.addEnum({key:514713,value:+`${T}${+C[_].supported}${+C[_].powerEfficient}${i}${n}`,useUV:!1})});const{sender:m,receiver:R}=iAA();fr.addEnum({key:513708,value:+`${i}${n}${+m.high}`,useUV:!1}),fr.addEnum({key:513709,value:+`${i}${n}${+m.main}`,useUV:!1}),fr.addEnum({key:514714,value:+`${i}${n}${+R.high}`,useUV:!1}),fr.addEnum({key:514715,value:+`${i}${n}${+R.main}`,useUV:!1})}catch(i){An.info("detectVideoCodecCapabilities failed",i)}}async function eAA(e,i=1920,n=1080,c=30,I=3e3){const C={};try{for(const m of e){const R=await navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:`video/${m}`,width:i,height:n,bitrate:I,framerate:c}});C[m]=R}}catch{}return C}async function tAA(e,i=1920,n=1080,c=30,I=3e3){const C={};try{for(const m of e){const R=await navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:`video/${m}`,width:i,height:n,bitrate:I,framerate:c}});C[m]=R}}catch{}return C}function iAA(){const e={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){const i=RTCRtpSender.getCapabilities("video");i&&i.codecs&&i.codecs.filter(n=>n.mimeType.toLowerCase()==="video/h264").forEach(n=>{if(n.sdpFmtpLine){const c=n.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(c&&c[1])switch(c[1].slice(0,2)){case"42":e.sender.base=!0;break;case"4d":e.sender.main=!0;break;case"64":e.sender.high=!0}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){const i=RTCRtpReceiver.getCapabilities("video");i&&i.codecs&&i.codecs.filter(n=>n.mimeType.toLowerCase()==="video/h264").forEach(n=>{if(n.sdpFmtpLine){const c=n.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(c&&c[1])switch(c[1].slice(0,2)){case"42":e.receiver.base=!0;break;case"4d":e.receiver.main=!0;break;case"64":e.receiver.high=!0}}})}}catch(i){An.warn("get H264 profile levelId failed",i)}return e}var xuA=MT(oF()),l6=Symbol("instance"),oY=Symbol("cacheResult"),S3=class{constructor(e,i,n){this.oldState=e,this.newState=i,this.action=n,this.aborted=!1}abort(e){this.aborted=!0,pU.call(e,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},v3=class extends Error{constructor(e,i,n){super(i),this.state=e,this.message=i,this.cause=n}};function YuA(e){return typeof e=="object"&&e&&"then"in e}var QU=new Map;function Ru(e,i,n={}){return(c,I,C)=>{const m=n.action||I;if(!n.context){const _=QU.get(c)||[];QU.has(c)||QU.set(c,_),_.push({from:e,to:i,action:m})}const R=C.value;C.value=function(..._){let T=this;if(n.context&&(T=nr.get(typeof n.context=="function"?n.context.call(this,..._):n.context)),T.state===i)return n.sync?T[oY]:Promise.resolve(T[oY]);T.state instanceof S3&&T.state.action==n.abortAction&&T.state.abort(T);let b=null;Array.isArray(e)?e.length==0?T.state instanceof S3&&T.state.abort(T):typeof T.state=="string"&&e.includes(T.state)||(b=new v3(T._state,`${T.name} ${m} to ${i} failed: current state ${T._state} not from ${e.join("|")}`)):e!==T.state&&(b=new v3(T._state,`${T.name} ${m} to ${i} failed: current state ${T._state} not from ${e}`));const J=oA=>{if(n.fail&&n.fail.call(this,oA),n.sync){if(n.ignoreError)return oA;throw oA}return n.ignoreError?Promise.resolve(oA):Promise.reject(oA)};if(b)return J(b);const gA=T.state,eA=new S3(gA,i,m);pU.call(T,eA);const CA=oA=>{var vA;return T[oY]=oA,eA.aborted||(pU.call(T,i),(vA=n.success)===null||vA===void 0||vA.call(this,T[oY])),oA},IA=oA=>(pU.call(T,gA,oA),J(oA));try{const oA=R.apply(this,_);return YuA(oA)?oA.then(CA).catch(IA):n.sync?CA(oA):Promise.resolve(CA(oA))}catch(oA){return IA(new v3(T._state,`${T.name} ${m} from ${e} to ${i} failed: ${oA}`,oA instanceof Error?oA:new Error(String(oA))))}}}}var VuA=typeof window<"u"&&window.__AFSM__?(n,c)=>{window.dispatchEvent(new CustomEvent(n,{detail:c}))}:typeof importScripts<"u"?(n,c)=>{postMessage({type:n,payload:c})}:()=>{};function pU(e,i){const n=this._state;this._state=e;const c=e.toString();e&&this.emit(c,n),this.emit(nr.STATECHANGED,e,n,i),this.updateDevTools({value:e,old:n,err:i instanceof Error?i.message:String(i)})}var nr=class XC extends xuA.default{constructor(i,n,c){super(),this.name=i,this.groupName=n,this._state=XC.INIT,i||(i=Date.now().toString(36)),c?Object.setPrototypeOf(this,c):c=Object.getPrototypeOf(this),n||(this.groupName=this.constructor.name);const I=c[l6];I?this.name=I.name+"-"+I.count++:c[l6]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){const i=Object.getPrototypeOf(this),n=QU.get(i)||[];let c=new Set,I=[],C=[];const m=new Set,R=Object.getPrototypeOf(i);QU.has(R)&&(R.stateDiagram.forEach(T=>c.add(T)),R.allStates.forEach(T=>m.add(T))),n.forEach(({from:T,to:b,action:J})=>{typeof T=="string"?I.push({from:T,to:b,action:J}):T.length?T.forEach(gA=>{I.push({from:gA,to:b,action:J})}):C.push({to:b,action:J})}),I.forEach(({from:T,to:b,action:J})=>{m.add(T),m.add(b),m.add(J+"ing"),c.add(`${T} --> ${J}ing : ${J}`),c.add(`${J}ing --> ${b} : ${J} 🟢`),c.add(`${J}ing --> ${T} : ${J} 🔴`)}),C.forEach(({to:T,action:b})=>{c.add(`${b}ing --> ${T} : ${b} 🟢`),m.forEach(J=>{J!==T&&c.add(`${J} --> ${b}ing : ${b}`)})});const _=[...c];return Object.defineProperties(i,{stateDiagram:{value:_},allStates:{value:m}}),_}static get(i){let n;return typeof i=="string"?(n=XC.instances.get(i),n||XC.instances.set(i,n=new XC(i,void 0,Object.create(XC.prototype)))):(n=XC.instances2.get(i),n||XC.instances2.set(i,n=new XC(i.constructor.name,void 0,Object.create(XC.prototype)))),n}static getState(i){var n;return(n=XC.get(i))===null||n===void 0?void 0:n.state}updateDevTools(i={}){VuA(XC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){pU.call(this,i)}};nr.STATECHANGED="stateChanged",nr.UPDATEAFSM="updateAFSM",nr.INIT="[*]",nr.ON="on",nr.OFF="off",nr.instances=new Map,nr.instances2=new WeakMap;var A5=typeof window<"u",I6=A5&&window.requestIdleCallback||function(e){const i=Date.now();return setTimeout(()=>{e({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-i))})},1e3)},HuA=A5&&window.cancelIdleCallback||function(e){clearTimeout(e)},u6=A5&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),WL=class QE{static generateTaskID(){return this.currentTaskID++}static run(i,n,c){c?.fps&&(c.delay=c.delay||Number((1e3/c.fps).toFixed(2))),c=ks(ks({},i==="interval"?{delay:2e3,count:0,backgroundTask:!0}:i==="ric"?{delay:1e4,count:0}:i==="raf"?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0}),c);const I=cB(ks({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:n},c),{delay:c.delay});return this.taskMap.set(I.taskID,I),this[i](I),I.taskID}static interval(i){return i.intervalID=setInterval(()=>{i.callback(),i.loopCount+=1,QE.isBreakLoop(i)},i.delay)}static intervalInWorker(i){QE.sharedWorker||(QE.sharedWorker=new Worker(URL.createObjectURL(new Blob([` const timers = new Map(); self.onmessage = function(e) { const { taskId, delay, type } = e.data; @@ -549,13 +549,13 @@ Refer to: ${i6("en",R)} } }; `],{type:"application/javascript"}))),QE.sharedWorker.onmessage=n=>{var c;if(n.data.type==="tick"){const I=QE.workerTasks.get(n.data.taskId);I&&(QE.isBreakLoop(I)?((c=QE.sharedWorker)==null||c.postMessage({type:"stop",taskId:I.taskID}),QE.workerTasks.delete(I.taskID)):(I.callback(),I.loopCount+=1))}}),QE.workerTasks.set(i.taskID,i),QE.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){const n=()=>{if(i.callback(),i.loopCount+=1,!QE.isBreakLoop(i))return i.timeoutID=setTimeout(n,i.delay)};return i.timeoutID=setTimeout(n,i.delay)}static ric(i){let n,c=Wc();const I=()=>{if(n=Wc()-c,n>=i.delay&&(c=Wc()-Math.floor(n%i.delay),i.callback(),i.loopCount+=1),!QE.isBreakLoop(i))return i.ricID=I6(I,{timeout:i.delay})};return i.ricID=I6(I,{timeout:i.delay})}static raf(i){let n,c=Wc();const I=()=>{if(document.hidden&&i.backgroundTask)return n=Wc()-c,c=Wc(),i.callback(),i.loopCount+=1,QE.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(I,i.delay-Math.floor(n%i.delay));if(n=Wc()-c,n>=i.delay&&(c=Wc()-Math.floor(n%i.delay),i.callback(),i.loopCount+=1),!QE.isBreakLoop(i))return i.rafID=requestAnimationFrame(I)};if(i.rafID=requestAnimationFrame(I),i.backgroundTask){const C=()=>{if(document.hidden){const m=Wc()-c;m>=i.delay?I():i.timeoutID=setTimeout(I,i.delay-m)}};document.addEventListener("visibilitychange",C),i.onVisibilitychange=C,document.hidden&&C()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;const{intervalID:n,timeoutID:c,rafID:I,ricID:C,onVisibilitychange:m}=this.taskMap.get(i);return n&&clearInterval(n),c&&clearTimeout(c),I&&u6&&u6(I),C&&HuA(C),m&&document.removeEventListener("visibilitychange",m),this.taskMap.delete(i),!0}static isBreakLoop(i){return!this.hasTask(i.taskID)||i.count!==0&&i.loopCount>=i.count&&(this.clearTask(i.taskID),!0)}};pe(WL,"taskMap",new Map),pe(WL,"currentTaskID",1),pe(WL,"sharedWorker",null),pe(WL,"workerTasks",new Map);var JuA=WL,RQ=JuA,zs={LOAD_START:ni.LOADSTART,LOADED_DATA:ni.LOADEDDATA,LOADED_META_DATA:ni.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:ni.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:ni.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:ni.ENTER_PICTURE_IN_PICTURE,USER_RESUME_IN_PIP_OR_FULL_SCREEN:"user-resume-in-pip-or-full-screen",USER_PAUSE_IN_PIP_OR_FULL_SCREEN:"user-pause-in-pip-or-full-screen",ENTER_FULL_SCREEN:"enter-full-screen",LEAVE_FULL_SCREEN:"leave-full-screen",VOLUME_CHANGE:"volume-change",FIRST_FRAME_RENDER:"first-frame-render"},MW={};S4(MW,{create:()=>e5,remove:()=>FU});var mU=new WeakMap;function e5(e,i){mU.has(e)||mU.set(e,[]);const n=mU.get(e),c={add:(I,C)=>("addEventListener"in i?(n.push(i.removeEventListener.bind(i,I,C)),i.addEventListener(I,C)):(n.push(i.off.bind(i,I,C)),i.on(I,C)),c)};return c}function FU(e){const i=mU.get(e);i&&(i.forEach(n=>n()),mU.delete(e))}var quA=class{constructor(){pe(this,"_roomIdMap",new Map),pe(this,"_configs"),typeof registerProcessor>"u"&&(this._configs={sdkAppId:"",userId:"",version:qY,env:h3.QCLOUD,browserVersion:NM.name+NM.version,ua:navigator.userAgent})}setConfig({sdkAppId:e,env:i,userId:n,roomId:c}){e!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(e)),this._configs.env=i,this._configs.userId=n,this._roomIdMap.set(n,String(c))}logSuccessEvent(e){!XY&&An.isAbleToUpload&&this._configs.env===h3.QCLOUD&&this.uploadEventToKibana(cB(ks({},e),{result:"success"}))}logFailedEvent(e){if(XY||!An.isAbleToUpload)return;const{eventType:i,code:n,error:c,userId:I}=e,C={roomId:this._roomIdMap.get(I||this._configs.userId),userId:I,eventType:i,result:"failed",code:n||c?.extraCode||c?.code||Zg.UNKNOWN};this._configs.env===h3.QCLOUD&&this.uploadEventToKibana(cB(ks({},C),{error:c}))}uploadEventToKibana(e){let i=`stat-${e.eventType}-${e.result}`;e.eventType!=="delta-join"&&e.eventType!=="delta-leave"&&e.eventType!=="delta-publish"||(i=`${e.eventType}:${e.delta}`),this.uploadEvent({log:i,userId:e.userId}),e.result==="failed"&&(i=`stat-${e.eventType}-${e.result}-${e.code}`,this.uploadEvent({log:i,userId:e.userId,error:e.error}))}uploadEvent({log:e,userId:i,error:n}){const c={timestamp:R7(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:qY,log:e};n&&(c.errorInfo=n.message,n.stack&&(c.errorInfo+=` -${n.stack}`));const I=vW.enable?T4(c,2002,Number(this._configs.sdkAppId)):JSON.stringify(c);this.sendRequest(R4(this._configs.sdkAppId,T7.LOG),I)}sendRequest(e,i){setTimeout(()=>Z7({url:e,body:i,priority:"low"}).catch(()=>{}),2e3)}},ah=new quA,EM=new WeakMap;function KuA({settings:e={retries:5,timeout:2e3},onError:i,onRetrying:n,onRetryFailed:c}){return function(I,C,m){const R=G4({retryFunction:m.value,settings:e,onError({error:_,retry:T,reject:b,retryFuncArgs:J}){var cA;i?i.call(this,_,()=>{var eA;(eA=EM.get(I))!=null&&eA.has(C)?T():b(_)},b,J):(cA=EM.get(I))!=null&&cA.has(C)?T():b(_)},onRetrying(_,T){var b;H_(n)&&n.call(this,_,T),(b=EM.get(I))!=null&&b.has(C)&&(EM.get(I).get(C).stopRetry=T)},onRetryFailed:c});return m.value=function(..._){const T=EM.get(I);return T?T.set(C,{args:_}):EM.set(I,new Map([[C,{args:_}]])),R.apply(this,_).finally(()=>{var b;return(b=EM.get(I))==null?void 0:b.delete(C)})},m}}var pM=class extends nr{constructor(e,i){super(e.id,`${i}-player`),this.options=e,this.kind=i,pe(this,"id"),pe(this,"element",null),pe(this,"track"),pe(this,"url"),pe(this,"attr"),pe(this,"mode"),pe(this,"muted"),pe(this,"_log"),pe(this,"isPausedByUserCall",!1),pe(this,"_pausedRetryCount"),pe(this,"_isElementPlayingFired",!1),pe(this,"_interval"),pe(this,"_delayDestroyTimeoutId",0),pe(this,"_playSuccessResolve"),pe(this,"_isReplayByRecreateMediaStreamCalled",!1),pe(this,"isPlayCalled",!1),pe(this,"isInAutoPlayFailedState",!1),pe(this,"isBindAutoPlayEvent",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=V_,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${i}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isPaused(){var e;return this._state==="PAUSED"||((e=this.element)==null?void 0:e.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}async play(){if(!this.isPlaying)try{this.isPlayCalled=!0,this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),await new Promise((e,i)=>{this._playSuccessResolve=e,this.element.play().then(e,i)})}catch(e){const i=AV({key:$Y.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),i.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new vl({code:Zg.PLAY_NOT_ALLOWED,message:i})}}stop(e=0){var i;this.isPlayCalled=!1,this.isPausedByUserCall=!1,this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!D$?this._delayDestroyTimeoutId||((i=this.element)==null||i.remove(),this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(ni.ENDED),this._interval>0&&RQ.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){this._log.info("pause"),this.isPausedByUserCall=!0,this.doPause()}doPause(){var e;(e=this.element)==null||e.pause()}resume(e=!1){return this.isPausedByUserCall=!1,this.doResume(e)}doResume(e=!1){return this._log.info("resume"),this.isPausedByUserCall||this.isPlaying?Promise.resolve():jIA?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){const e=this.handleElementEvent.bind(this);return e5(this.element,this.element).add(ni.PLAYING,e).add(ni.ENDED,e).add(ni.PAUSE,e).add(ni.ERROR,e).add(ni.LOADSTART,e).add(ni.LOADEDDATA,e).add(ni.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){const i=this.handleTrackEvent.bind(this);MW?.create(e,e).add(ni.ENDED,i).add(ni.MUTE,i).add(ni.UNMUTE,i),e.readyState===ni.ENDED&&this.handleTrackEvent({type:ni.ENDED}),e.muted&&this.handleTrackEvent({type:ni.MUTE})}}bindAutoPlayEvent(){this.isBindAutoPlayEvent||(this._log.warn("bindAutoPlayEvent"),Rn.on(Rs.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!0)}unbindTrackEvents(e=this.track){e&&FU(e)}unbindEvents(){this.element&&FU(this.element),this.unbindTrackEvents(),Rn.off(Rs.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!1}handleElementEvent(e){switch(e.type){case ni.PLAYING:OU()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(ni.PLAYING),this._interval&&(RQ.clearTask(this._interval),this._interval=-1);break;case ni.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(ni.ENDED);break;case ni.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(ni.PAUSE);break;case ni.ERROR:if(this.element&&this.element.error){this.handlePaused(ni.ERROR);const{code:i,message:n}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${i} message: ${n} userAgent: ${navigator.userAgent}`),ah.uploadEvent({log:`stat-${this.kind}-${CU.PLAYER_ERROR}-${i}-${navigator.userAgent}`,error:this.element.error}),JIA||h$?this.emit(zs.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case ni.LOADEDDATA:this.kind===ni.VIDEO&&this.emit(zs.LOADED_DATA);break;case ni.LOADEDMETADATA:this.kind===ni.VIDEO&&this.emit(zs.LOADED_META_DATA);break;case ni.LOADSTART:this.emit(zs.LOAD_START)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),ah.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),mr.addSuccessEvent({key:this.kind===ni.AUDIO?506700:516700})}).catch(()=>{var i;this._log.error("replayByRecreateMediaStream failed"),ah.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),mr.addFailedEvent({key:this.kind===ni.AUDIO?506700:516700,error:(i=this.element)==null?void 0:i.error}),this.emit(zs.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((i,n)=>{QT(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var c,I,C;this._log.warn(`element onerror ${(I=(c=this.element)==null?void 0:c.error)==null?void 0:I.code} fired after recreated mediaStream`),n((C=this.element)==null?void 0:C.error)}),QT(5e3).then(()=>{var c,I;this.isPlaying&&!((c=this.element)!=null&&c.error)||n((I=this.element)==null?void 0:I.error),i()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}async handleTrackEvent(e){const i=e.type;switch(this.options.enableLogTrackState&&this._log[i===ni.UNMUTE?"info":"warn"](`track ${i}`),i){case ni.ENDED:this.handleStopped(ni.ENDED);break;case ni.MUTE:this.handlePaused(ni.MUTE);break;case ni.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&!this.isPausedByUserCall&&(this._log.warn("track unmuted and element is paused, resume"),await this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(ni.UNMUTE))}}handlePlaying(e){var i;return this._log.debug("handlePlaying",e),(i=this._playSuccessResolve)==null||i.call(this,e),e}handlePaused(e){return this._log.debug("handlePaused",e),e}handleStopped(e){return this._log.debug("handleStopped",e),e}getElement(){return this.element}};pe(pM,"PlayerEvent",zs),yc([KuA({settings:{retries:2,timeout:0},onError(e,i,n,c){c[0]=(c[0]||1e3)+1e3,i()}})],pM.prototype,"doReplayByRecreateMediaStream"),yc([Ru([],"PLAYING",{sync:!0,success(e){this.emit(zs.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],pM.prototype,"handlePlaying"),yc([Ru("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(zs.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],pM.prototype,"handlePaused"),yc([Ru([],"STOPPED",{sync:!0,success(e){this.emit(zs.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],pM.prototype,"handleStopped");var vm="trtc_autoplay",M3=`${vm}_mask`,LL=`${vm}_wrapper`,E6=`${vm}_header`,R3=`${vm}_content`,nY=`${vm}_action_wrapper`,w3=`${vm}_question`,_3=`${vm}_collapse`,sY=`${vm}_action_confirm`,d6=`${vm}_detail`,C6="#2473E8",t5="dialog",juA=`${t5}-show`,WuA=`${t5}-1`,zuA=`${t5}-2`,h6=!1,RW=!1,OU=()=>RW,oAA=`${hW}/${iD()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,B6=`
${iD()?"其他方案?":"Any other solution?"}`,ZuA=iD()?`浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。${B6}`:`Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ${B6}`,XuA=class{constructor(){if(pe(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),pe(this,"_dialogNode",null),pe(this,"_bodyPosition",""),pe(this,"_showDetail",!1),pe(this,"_isCollapseClicked",!1),pe(this,"_isQuestionClicked",!1),iD()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!h6){const e=document.createElement("style");e.innerHTML=`.${M3}{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.${M3} div:not(.${nY}){display:block !important;}.${LL}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${LL} a{color:${C6};}.${E6}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${R3}{margin:8px 0;}.${nY}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${_3}{margin-right:auto;cursor:pointer}.${w3}{height:100%;line-height:16px;cursor:pointer;}.${sY}{margin-left:8px;color:#fff;background:${C6};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${sY}:hover{opacity:0.9;}.${_3},.${sY},.${R3},.${w3}{font-size:14px;}@media screen and (max-width:750px){.${LL}{width:80vw;}}`,document.head.appendChild(e),h6=!0}this.addDiaLog()}createDiaLog(){const e=document.createElement("template");e.innerHTML=`
${location.host}
${this.content}
`.trim();const i=document.createElement("button");i.className=sY,i.innerText=iD()?"恢复播放":"Resume",i.onclick=this.onConfirm.bind(this);const n=document.createElement("div");n.className=w3,n.innerHTML=` +${n.stack}`));const I=vW.enable?T4(c,2002,Number(this._configs.sdkAppId)):JSON.stringify(c);this.sendRequest(R4(this._configs.sdkAppId,T7.LOG),I)}sendRequest(e,i){setTimeout(()=>Z7({url:e,body:i,priority:"low"}).catch(()=>{}),2e3)}},ah=new quA,EM=new WeakMap;function KuA({settings:e={retries:5,timeout:2e3},onError:i,onRetrying:n,onRetryFailed:c}){return function(I,C,m){const R=G4({retryFunction:m.value,settings:e,onError({error:_,retry:T,reject:b,retryFuncArgs:J}){var gA;i?i.call(this,_,()=>{var eA;(eA=EM.get(I))!=null&&eA.has(C)?T():b(_)},b,J):(gA=EM.get(I))!=null&&gA.has(C)?T():b(_)},onRetrying(_,T){var b;H_(n)&&n.call(this,_,T),(b=EM.get(I))!=null&&b.has(C)&&(EM.get(I).get(C).stopRetry=T)},onRetryFailed:c});return m.value=function(..._){const T=EM.get(I);return T?T.set(C,{args:_}):EM.set(I,new Map([[C,{args:_}]])),R.apply(this,_).finally(()=>{var b;return(b=EM.get(I))==null?void 0:b.delete(C)})},m}}var pM=class extends nr{constructor(e,i){super(e.id,`${i}-player`),this.options=e,this.kind=i,pe(this,"id"),pe(this,"element",null),pe(this,"track"),pe(this,"url"),pe(this,"attr"),pe(this,"mode"),pe(this,"muted"),pe(this,"_log"),pe(this,"isPausedByUserCall",!1),pe(this,"_pausedRetryCount"),pe(this,"_isElementPlayingFired",!1),pe(this,"_interval"),pe(this,"_delayDestroyTimeoutId",0),pe(this,"_playSuccessResolve"),pe(this,"_isReplayByRecreateMediaStreamCalled",!1),pe(this,"isPlayCalled",!1),pe(this,"isInAutoPlayFailedState",!1),pe(this,"isBindAutoPlayEvent",!1),this.id=e.id,this._log=e.log,this.track=e.track,this.muted=e.muted,this._pausedRetryCount=V_,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${i}-player ${this.id}`)}get isPlaying(){var e;return this._state==="PLAYING"&&((e=this.element)==null?void 0:e.paused)===!1}get isPaused(){var e;return this._state==="PAUSED"||((e=this.element)==null?void 0:e.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(e){this.attr=e}setUrl(e){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),e!==this.url&&(this.url=e,e!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=e))}async play(){if(!this.isPlaying)try{this.isPlayCalled=!0,this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),await new Promise((e,i)=>{this._playSuccessResolve=e,this.element.play().then(e,i)})}catch(e){const i=AV({key:$Y.PLAY_FAILED,data:{media:this.kind,error:e}});if(this._log.warn(e),i.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new Ml({code:Zg.PLAY_NOT_ALLOWED,message:i})}}stop(e=0){var i;this.isPlayCalled=!1,this.isPausedByUserCall=!1,this._isElementPlayingFired=!1,this.unbindEvents(),e>0&&!D$?this._delayDestroyTimeoutId||((i=this.element)==null||i.remove(),this._log.info(`destroy element after 3 * ${e}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*e)):this.destroyElement(),this.handleStopped(ni.ENDED),this._interval>0&&RQ.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){this._log.info("pause"),this.isPausedByUserCall=!0,this.doPause()}doPause(){var e;(e=this.element)==null||e.pause()}resume(e=!1){return this.isPausedByUserCall=!1,this.doResume(e)}doResume(e=!1){return this._log.info("resume"),this.isPausedByUserCall||this.isPlaying?Promise.resolve():jIA?this.replay():this.play().catch(()=>{})}setMuted(e){this.element&&(this.element.muted=e),this.muted=e}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){const e=this.handleElementEvent.bind(this);return e5(this.element,this.element).add(ni.PLAYING,e).add(ni.ENDED,e).add(ni.PAUSE,e).add(ni.ERROR,e).add(ni.LOADSTART,e).add(ni.LOADEDDATA,e).add(ni.LOADEDMETADATA,e)}}bindTrackEvents(e=this.track){if(e){const i=this.handleTrackEvent.bind(this);MW?.create(e,e).add(ni.ENDED,i).add(ni.MUTE,i).add(ni.UNMUTE,i),e.readyState===ni.ENDED&&this.handleTrackEvent({type:ni.ENDED}),e.muted&&this.handleTrackEvent({type:ni.MUTE})}}bindAutoPlayEvent(){this.isBindAutoPlayEvent||(this._log.warn("bindAutoPlayEvent"),Rn.on(Rs.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!0)}unbindTrackEvents(e=this.track){e&&FU(e)}unbindEvents(){this.element&&FU(this.element),this.unbindTrackEvents(),Rn.off(Rs.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!1}handleElementEvent(e){switch(e.type){case ni.PLAYING:OU()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(ni.PLAYING),this._interval&&(RQ.clearTask(this._interval),this._interval=-1);break;case ni.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(ni.ENDED);break;case ni.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(ni.PAUSE);break;case ni.ERROR:if(this.element&&this.element.error){this.handlePaused(ni.ERROR);const{code:i,message:n}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${i} message: ${n} userAgent: ${navigator.userAgent}`),ah.uploadEvent({log:`stat-${this.kind}-${CU.PLAYER_ERROR}-${i}-${navigator.userAgent}`,error:this.element.error}),JIA||h$?this.emit(zs.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case ni.LOADEDDATA:this.kind===ni.VIDEO&&this.emit(zs.LOADED_DATA);break;case ni.LOADEDMETADATA:this.kind===ni.VIDEO&&this.emit(zs.LOADED_META_DATA);break;case ni.LOADSTART:this.emit(zs.LOAD_START)}}replayByRecreateMediaStream(e){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),ah.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),fr.addSuccessEvent({key:this.kind===ni.AUDIO?506700:516700})}).catch(()=>{var i;this._log.error("replayByRecreateMediaStream failed"),ah.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),fr.addFailedEvent({key:this.kind===ni.AUDIO?506700:516700,error:(i=this.element)==null?void 0:i.error}),this.emit(zs.ERROR,e)})}doReplayByRecreateMediaStream(e){return this._log.warn(`delay ${e}ms to recreate mediaStream`),new Promise((i,n)=>{QT(e).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var c,I,C;this._log.warn(`element onerror ${(I=(c=this.element)==null?void 0:c.error)==null?void 0:I.code} fired after recreated mediaStream`),n((C=this.element)==null?void 0:C.error)}),QT(5e3).then(()=>{var c,I;this.isPlaying&&!((c=this.element)!=null&&c.error)||n((I=this.element)==null?void 0:I.error),i()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}async handleTrackEvent(e){const i=e.type;switch(this.options.enableLogTrackState&&this._log[i===ni.UNMUTE?"info":"warn"](`track ${i}`),i){case ni.ENDED:this.handleStopped(ni.ENDED);break;case ni.MUTE:this.handlePaused(ni.MUTE);break;case ni.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&!this.isPausedByUserCall&&(this._log.warn("track unmuted and element is paused, resume"),await this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(ni.UNMUTE))}}handlePlaying(e){var i;return this._log.debug("handlePlaying",e),(i=this._playSuccessResolve)==null||i.call(this,e),e}handlePaused(e){return this._log.debug("handlePaused",e),e}handleStopped(e){return this._log.debug("handleStopped",e),e}getElement(){return this.element}};pe(pM,"PlayerEvent",zs),yc([KuA({settings:{retries:2,timeout:0},onError(e,i,n,c){c[0]=(c[0]||1e3)+1e3,i()}})],pM.prototype,"doReplayByRecreateMediaStream"),yc([Ru([],"PLAYING",{sync:!0,success(e){this.emit(zs.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:e})}})],pM.prototype,"handlePlaying"),yc([Ru("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(e){this.emit(zs.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:e})}})],pM.prototype,"handlePaused"),yc([Ru([],"STOPPED",{sync:!0,success(e){this.emit(zs.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:e})}})],pM.prototype,"handleStopped");var vm="trtc_autoplay",M3=`${vm}_mask`,LL=`${vm}_wrapper`,E6=`${vm}_header`,R3=`${vm}_content`,nY=`${vm}_action_wrapper`,w3=`${vm}_question`,_3=`${vm}_collapse`,sY=`${vm}_action_confirm`,d6=`${vm}_detail`,C6="#2473E8",t5="dialog",juA=`${t5}-show`,WuA=`${t5}-1`,zuA=`${t5}-2`,h6=!1,RW=!1,OU=()=>RW,oAA=`${hW}/${iD()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,B6=`
${iD()?"其他方案?":"Any other solution?"}`,ZuA=iD()?`浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。${B6}`:`Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ${B6}`,XuA=class{constructor(){if(pe(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),pe(this,"_dialogNode",null),pe(this,"_bodyPosition",""),pe(this,"_showDetail",!1),pe(this,"_isCollapseClicked",!1),pe(this,"_isQuestionClicked",!1),iD()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!h6){const e=document.createElement("style");e.innerHTML=`.${M3}{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.${M3} div:not(.${nY}){display:block !important;}.${LL}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${LL} a{color:${C6};}.${E6}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${R3}{margin:8px 0;}.${nY}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${_3}{margin-right:auto;cursor:pointer}.${w3}{height:100%;line-height:16px;cursor:pointer;}.${sY}{margin-left:8px;color:#fff;background:${C6};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${sY}:hover{opacity:0.9;}.${_3},.${sY},.${R3},.${w3}{font-size:14px;}@media screen and (max-width:750px){.${LL}{width:80vw;}}`,document.head.appendChild(e),h6=!0}this.addDiaLog()}createDiaLog(){const e=document.createElement("template");e.innerHTML=`
${location.host}
${this.content}
`.trim();const i=document.createElement("button");i.className=sY,i.innerText=iD()?"恢复播放":"Resume",i.onclick=this.onConfirm.bind(this);const n=document.createElement("div");n.className=w3,n.innerHTML=` - `,n.onclick=this.onQuestionClick.bind(this);const c=document.createElement("div");c.className=_3,c.innerText=iD()?"详情 >":"Detail >",c.onclick=this.onCollapseClick.bind(this);const I=e.content.firstChild,C=I.querySelector(`.${nY}`);return C.appendChild(c),C.appendChild(n),C.appendChild(i),I}addDiaLog(){OU()||(RW=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${LL}`).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",An.info("show autoplay dialog"),ah.uploadEvent({log:juA}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,RW=!1),PU=null}onConfirm(){An.warn("confirm clicked, try resume stream"),Rn.emit(Rs.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){const e=this._dialogNode.querySelector(`.${d6}`);e.style.visibility=this._showDetail?"hidden":"visible",e.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||ah.uploadEvent({log:WuA}),this._isCollapseClicked=!0}onQuestionClick(){window.open(oAA,"_blank"),this._isQuestionClicked||ah.uploadEvent({log:zuA}),this._isQuestionClicked=!0}},PU=null;function $uA(){PU||(PU=new XuA)}function AEA(){PU&&PU.deleteDialog()}var fU,Ky=class extends pM{constructor(e){super(e,ni.VIDEO),pe(this,"stat",{}),pe(this,"_calculateTimeout",-1),pe(this,"viewMirror",!1),pe(this,"objectFit","cover"),pe(this,"container"),pe(this,"canvas"),pe(this,"shouldRenderAlpha",!1),pe(this,"_preSize",{width:0,height:0}),pe(this,"posterImg"),pe(this,"pipWindow"),pe(this,"enterPIPPromise"),pe(this,"_originContainerPosition"),pe(this,"_isResettingSrcObject",!1),pe(this,"_wrapper",null),pe(this,"_useWrapper",!1),pe(this,"_isFirstFrameRenderEmitted",!1),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,sr(e.viewMirror)||(this.viewMirror=e.viewMirror),sr(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state==="PLAYING"&&(!this.element||!this.element.paused)&&((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){const e=document.createElement(ni.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,cC&&(e.poster="data:,"),this._appendToWrapper(),this.bindElementEvents(),this.calculateStat(),this._bindFirstFrameRenderEvent(e)}_bindFirstFrameRenderEvent(e){const i=()=>{if(this._isFirstFrameRenderEmitted)return;this._isFirstFrameRenderEmitted=!0;const n=e.videoWidth||0,c=e.videoHeight||0;this._log.info(`first frame render: ${n}x${c}`),this.emit(zs.FIRST_FRAME_RENDER,{width:n,height:c})};typeof e.requestVideoFrameCallback=="function"?e.requestVideoFrameCallback(i):e.addEventListener("loadeddata",i,{once:!0})}get styleAttribute(){let e=this._useWrapper?`grid-area:1/1;width:100%;height:100%;object-fit:${this.objectFit};${this.shouldRenderAlpha?"":"background-color:black"};`:`width:100%;height:100%;object-fit:${this.objectFit};${this.shouldRenderAlpha?"":"background-color:black"};`;return this.viewMirror&&(e+="transform:scaleX(-1);"),e}setLiveMode(e){if(this._useWrapper!==e&&(this._useWrapper=e,this.elementToRender&&this.elementToRender.setAttribute("style",this.styleAttribute),this.container&&this.elementToRender))if(e){const i=this._getOrCreateWrapper();i.insertBefore(this.elementToRender,i.firstChild)}else this.container.appendChild(this.elementToRender),this._cleanupWrapper()}setContainer(e){if(this.container===e)return;const i=this._wrapper,n=this.container;this.container=e,this._pausedRetryCount=V_,this.track&&this.elementToRender&&this._appendToWrapper(),i&&n&&n!==this.container&&i.isConnected&&i.children.length===0&&i.remove()}_getOrCreateWrapper(){if(!this.container)throw new Error("[VideoPlayer] container is required");let e=this.container.querySelector("[data-trtc-video-wrapper]");return e||(e=document.createElement("div"),e.setAttribute("data-trtc-video-wrapper","true"),e.style.cssText="display:grid;width:100%;height:100%;",this.container.appendChild(e)),this._wrapper=e,e}_appendToWrapper(e){const i=e??this.elementToRender;if(this.container&&i)if(this._useWrapper){const n=this._getOrCreateWrapper();n.insertBefore(i,n.firstChild)}else this.container.appendChild(i)}bindElementEvents(){const e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),this.handleFullscreenChange=this.handleFullscreenChange.bind(this),this.handleVolumeChange=this.handleVolumeChange.bind(this),e&&e.add(ni.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(ni.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(ni.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener(ni.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.addEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.addEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.addEventListener("volumechange",this.handleVolumeChange))}handleTrackEvent(e){var i;return e.type===ni.MUTE&&((i=this.stat)!=null&&i.fps&&(this.stat.fps=0),this.isFullscreen()&&this.resetSrcObjectToReplay()),super.handleTrackEvent(e)}handleFullscreenChange(){this.isFullscreen()?(this._log.info("enter fullscreen"),this.emit(zs.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(zs.LEAVE_FULL_SCREEN))}handleVolumeChange(){var e;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(zs.VOLUME_CHANGE,{muted:(e=this.element)==null?void 0:e.muted})}handleElementEvent(e){var i,n,c,I,C,m;if(this.mode===2)return;super.handleElementEvent(e);const R=e.type,_=this.isPictureInPicture(),T=this.isFullscreen(),b=e.isTrusted&&(_&&ud||T);if(R===ni.PLAYING&&b&&!this._isResettingSrcObject&&(this._log.warn("user resume in "+(T?"fullscreen":"pip")),this.emit(zs.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),R===ni.PAUSE&&(b&&(this._log.warn("user pause in "+(T?"fullscreen":"pip")),this.emit(zs.USER_PAUSE_IN_PIP_OR_FULL_SCREEN)),this.container&&!this.container.isConnected&&(this._log.warn(`${this.kind} player has been remove, element ID: ${this.container.id}`),QT(500).then(()=>{var J;(J=this.container)!=null&&J.isConnected&&(this._pausedRetryCount=V_,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!OU()&&!this.isPausedByUserCall&&!b&&(this._log.info(`[${V_-this._pausedRetryCount+1}/${V_}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),_u&&!b&&(this._interval=RQ.run("timeout",()=>{this.element&&this._state==="PAUSED"&&!this.isPausedByUserCall&&this.doResume()},{delay:3e3})),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){const J=this.element.style.transform;R===ni.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=J.replace("scaleX(-1)",""):R!==ni.LEAVE_PICTURE_IN_PICTURE||J.includes("scaleX")||(this.element.style.transform=`${J} scaleX(-1)`)}R===ni.RESIZE&&(this._preSize.height===((i=this.element)==null?void 0:i.videoHeight)&&this._preSize.width===((n=this.element)==null?void 0:n.videoWidth)||(this._log.info(`video size changed to ${(c=this.element)==null?void 0:c.videoWidth}x${(I=this.element)==null?void 0:I.videoHeight}`),this._preSize.height=((C=this.element)==null?void 0:C.videoHeight)||0,this._preSize.width=((m=this.element)==null?void 0:m.videoWidth)||0,this.emit(zs.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))),R===ni.LEAVE_PICTURE_IN_PICTURE&&(this._log.warn("exit pip"),this.isPaused&&!this.isPausedByUserCall&&(this._log.warn("resume after exit pip"),this.doResume()),this.resetSrcObjectToReplay(),this.emit(zs.LEAVE_PICTURE_IN_PICTURE)),R===ni.ENTER_PICTURE_IN_PICTURE&&this.emit(zs.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){cC&&D3&&this.isPlayCalled&&this.element&&this.track&&!this.isPausedByUserCall&&(this._log.warn("reset srcObject to replay for android chromium"),this._isResettingSrcObject=!0,this.element.srcObject=new MediaStream([this.track]),this.element.play().catch(e=>{this._log.warn("play failed after reset srcObject",e)}).finally(()=>{this._isResettingSrcObject=!1}))}setCanvas(e,i=1){var n,c;this.canvas!==e&&((n=this.canvas)==null||n.remove(),e?.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?i:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((c=this.element)==null||c.remove(),this._appendToWrapper(e)):this.element&&this._appendToWrapper(this.element))}setAttr(e){const i=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);i.style=Object.assign({width:"100%",height:"100%"},i.style),super.setAttr(i)}get mirror(){return this.viewMirror}setRect(e,i){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${i}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e,i=!1){return new Promise(n=>{if(!this.element||(this._log.info("setPoster",e.slice(0,10)),e===""?this.element.removeAttribute("poster"):this.element.poster=e,!(i&&(ud||aC))))return n();if(e==="")return this.removePosterImg(),n();if(this.posterImg)return n();const c=document.createElement("img");c.src=e;const I=window.getComputedStyle(this.element),C=I.objectFit||this.objectFit;let m=1;if(this._useWrapper){const R=parseInt(I.zIndex,10);isNaN(R)||(m=R+1)}c.style.cssText=this._useWrapper?`grid-area:1/1;z-index:${m};width:100%;height:100%;object-fit:${C};`:`position:absolute;top:0;left:0;width:100%;height:100%;object-fit:${C};`,c.onload=async()=>{try{c.decode&&await c.decode(),this.container&&!this._useWrapper&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=c;const R=this._useWrapper?this._wrapper:this.container;R?.appendChild(c),WY()&&VM<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(R){this._log.warn("decode poster image error",R)}return n()},c.onerror=()=>(this._log.warn("load poster image error"),n())})}removePosterImg(){this.posterImg&&(WY()&&VM<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),this._useWrapper||!this.container||sr(this._originContainerPosition)||this.container.style.position!=="relative"||(this.container.style.position=this._originContainerPosition),delete this.posterImg)}get hasPoster(){var e;return!!this.posterImg||!!((e=this.element)!=null&&e.getAttribute("poster"))}async pause(e=!0){super.pause(),this.isPictureInPicture()||this.hasPoster||!(D3||e&&(aC||ud))||await this.setPoster(this.getVideoFrame(),!0)}resume(e=!1){return super.resume(e).then(()=>{var i;(this.posterImg||(i=this.element)!=null&&i.poster)&&this.setPoster("",!0)})}doResume(e=!1){return this.isPaused&&e&&this.element&&this.track&&D3&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(e=0){var i;this.isPictureInPicture()&&this.exitPictureInPicture().catch(n=>{}),this.isFullscreen()&&this.exitFullscreen().catch(n=>{}),this.element&&(this.element.removeEventListener(ni.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.removeEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.removeEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.removeEventListener("volumechange",this.handleVolumeChange)),this._isFirstFrameRenderEmitted=!1,super.stop(e),(i=this.canvas)==null||i.remove(),this.removePosterImg(),this._useWrapper&&this._cleanupWrapper()}_cleanupWrapper(){this._wrapper&&this._wrapper.children.length===0&&this._wrapper.remove(),this._wrapper=null}play(e){if(sr(e?.isLiveStream)||this.setLiveMode(e.isLiveStream),this.element){if(this.elementToRender&&this.container)if(this._useWrapper){const i=this._getOrCreateWrapper();this.elementToRender.parentElement!==i&&i.insertBefore(this.elementToRender,i.firstChild)}else this.elementToRender.parentElement!==this.container&&this.container.append(this.elementToRender)}else this.initializeElement();return this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(zs.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this._appendToWrapper()))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";const e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if($4()&&this.element&&this._calculateTimeout<0){let e=0,i=null;const n=(c,I)=>{this.stat.width=I.width,this.stat.height=I.height,i&&(this.stat.fps=Math.round((I.presentedFrames-i.presentedFrames)/(c-e)*1e3)),e=c,i=I,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var C;return(C=this.element)==null?void 0:C.requestVideoFrameCallback(n)},2e3))};this.element.requestVideoFrameCallback(n)}}catch(e){this._log.warn("init stat failed",e)}}async enterFullscreen(){const e=this.elementToRender;if(!e)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");if(_u&&this.isPictureInPicture()){this._log.info("exit pip before entering fullscreen");try{await this.exitPictureInPicture()}catch(i){this._log.warn("exit pip failed before fullscreen:",i)}}try{if(e.requestFullscreen)await e.requestFullscreen();else if(e.webkitRequestFullscreen)await e.webkitRequestFullscreen();else if(e.webkitEnterFullscreen)await e.webkitEnterFullscreen();else if(e.mozRequestFullScreen)await e.mozRequestFullScreen();else{if(!e.msRequestFullscreen)throw new Error("Fullscreen API not supported");await e.msRequestFullscreen()}this._log.info("entered fullscreen mode")}catch(i){throw this._log.error("failed to enter fullscreen:",i),i}}async exitFullscreen(){try{if(!this.isFullscreen())return;if(document.exitFullscreen)await document.exitFullscreen();else if(document.webkitExitFullscreen)await document.webkitExitFullscreen();else if(document.mozCancelFullScreen)await document.mozCancelFullScreen();else{if(!document.msExitFullscreen)throw new Error("Exit fullscreen API not supported");await document.msExitFullscreen()}this._log.info("exited fullscreen mode")}catch(e){throw this._log.error("failed to exit fullscreen:",e),e}}isFullscreen(){const e=this.elementToRender;return e?this.element&&this.element.webkitDisplayingFullscreen?!this.isPictureInPicture():(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===e:!1}async toggleFullscreen(){this.isFullscreen()?await this.exitFullscreen():await this.enterFullscreen()}async enterPictureInPicture(){this.enterPIPPromise=this._enterPictureInPicture();try{return await this.enterPIPPromise}finally{delete this.enterPIPPromise}}async _enterPictureInPicture(){try{if(!this.element)throw new Error("No video element available for pip");if(this.canvas&&this.mode!==1)throw new Error("pip is not supported for canvas-only mode");const{element:e}=this;if(e.requestPictureInPicture){this._log.info("requestPictureInPicture");const i=await e.requestPictureInPicture();return this.pipWindow=i,this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),this._appendToWrapper(this.element)),i}if(e.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),await e.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered pip mode (webkit)"),{};throw new Error("pip API not supported")}catch(e){throw this._log.error("failed to enter pip:",e.name,e.message),e}}async exitPictureInPicture(){var e;try{if(!this.isPictureInPicture())return;if(delete this.pipWindow,document.pictureInPictureElement&&document.exitPictureInPicture)await document.exitPictureInPicture(),this.elementToRender===this.canvas&&((e=this.element)==null||e.remove(),this._pausedRetryCount=V_,this._appendToWrapper(this.canvas)),this._log.info("exited pip mode");else{if(!this.element||!this.element.webkitSetPresentationMode)throw new Error("Exit pip API not supported or not in PiP mode");await this.element.webkitSetPresentationMode("inline"),this._log.info("exited pip mode (webkit)")}}catch(i){throw this._log.error("failed to exit pip:",i),i}}isPictureInPicture(){if(!this.element)return!1;const{element:e}=this;return document.pictureInPictureElement?document.pictureInPictureElement===e:!!e.webkitPresentationMode&&e.webkitPresentationMode==="picture-in-picture"}async togglePictureInPicture(){this.isPictureInPicture()?await this.exitPictureInPicture():await this.enterPictureInPicture()}};async function eEA(e,i){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{await e.audioWorklet.addModule(i),An.info("worklet addModule success")}catch(n){throw An.info(`worklet addModule catch error. ${n.message}`),n}}typeof AudioContext<"u"?fU=AudioContext:typeof webkitAudioContext<"u"?fU=webkitAudioContext:typeof mozAudioContext<"u"&&(fU=mozAudioContext);var Mu,tEA=1500,Q6=-1,rY=0,yU=-1,wW=!1,p6=0,m6=-1,f6=-1;function nAA(){try{if(Mu)return;(Mu=new fU({sampleRate:48e3})).onstatechange=()=>{An.info(`context state: ${Mu.state}${Mu.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),aT()},clearTimeout(Q6)}catch(e){An.error(`initAudioContext failed: ${e} typeof AudioContextClass: ${typeof fU}`),Q6=setTimeout(nAA,1e3)}}nAA();var aT=()=>{Mu.state==="suspended"?(rY=Wc(),iEA(),tV(),document.addEventListener("click",aT)):Mu.state==="interrupted"?tV():(rY&&(mr.addNumber({key:507800,value:Wc()-rY,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),rY=0),oEA(),document.removeEventListener("visibilitychange",aT),document.removeEventListener("click",aT))},T3=0,N3=-1;function tV(){return new Promise((e,i)=>{if(Mu.state==="running")return e();Date.now()-T3<1e3?(clearTimeout(N3),N3=setTimeout(()=>{T3=Date.now(),Mu.resume().then(e,i)},1e3)):(clearTimeout(N3),T3=Date.now(),Mu.resume().then(e,i))}).catch(e=>{An.warn(`context resume failed: ${e}`),document.addEventListener("visibilitychange",aT)})}function iEA(){yU===-1&&(yU=setTimeout(()=>{Mu.state==="suspended"&&(wW=!0,Rn.emit("155",{isSuspended:!0}))},tEA))}function oEA(){yU!==-1&&(clearTimeout(yU),yU=-1,wW&&(wW=!1,Rn.emit("155",{isSuspended:!1})))}function nEA(){if(!_u||f6!==-1)return;const e=()=>{Wc()-p6<500||(Mu&&Mu.state==="running"&&Mu.currentTime===m6&&(An.warn("context is fake running, auto resume"),Mu.suspend().catch(i=>{An.warn(`context suspend failed: ${i}`)})),m6=Mu.currentTime,p6=Wc())};f6=setInterval(()=>{e()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&e()})}document.addEventListener("click",aT);var uD=e=>Mu,GM=class{constructor(e){this.name=e,pe(this,"node"),pe(this,"node2"),pe(this,"pre",new Set),pe(this,"next",new Set),pe(this,"context"),pe(this,"connectedNodes",new Set),pe(this,"nextInputChannelMap",new Map),pe(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(e){this._channelCount=e,this.setChannelCount(this.node,e),this.setChannelCount(this.node2,e),this.next.forEach(i=>i.channelCount=e)}setChannelCount(e,i){!e||e instanceof ScriptProcessorNode||(e.channelCountMode="explicit",e.channelCount=i||this.channelCount||1)}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&((e=this.context)==null||e.reduceMixWeight()),delete this.context}replaceNode(e){var i;if(e!==this.node)try{this.node?this._disconnect():(i=this.context)==null||i.addMixWeight(),this.node=e,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(n){An.error(n)}}setNode(e,i){var n;if(!this.node)try{(n=this.context)==null||n.addMixWeight(),this.node=e,this.setChannelCount(this.node),i&&(this.node2=i,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),mr.addSuccessEvent({key:502701})}catch(c){An.error(c),mr.addFailedEvent({key:502701,error:c})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(e=this.context)==null||e.reduceMixWeight(),this.preNodeReconnect(),mr.addSuccessEvent({key:502702})}catch(i){An.error(i),mr.addFailedEvent({key:502702,error:i})}}preNodeReconnect(){this.pre.forEach(e=>{e.node?e.reconnect():e.preNodeReconnect()})}connectNext(e){this.next.forEach(i=>{const n=this.nextInputChannelMap.get(i);e._connect(i.node,n)||i.connectNext(e)})}_connect(e,i=0){return!(!this.node||!e)&&((this.node2||this.node).connect(e,0,i),this.connectedNodes.add(e),!0)}_disconnect(){this.connectedNodes.forEach(e=>{var i;return(i=this.node2||this.node)==null?void 0:i.disconnect(e)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(e,i=0){return this.next.add(e),e.pre.add(this),this.nextInputChannelMap.set(e,i),e}},sEA=class extends GM{constructor(e=256){super(),this.fftSize=e,pe(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){const e=this.getByteTimeDomainData();let i=0,n=0,c=`M${i},${n}`;for(let I=0;Ithis.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(um.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=n=>{um.lastMessageTime=Date.now(),this._volume=n.data.volume||0,this._volumeDb=n.data.volumeDb||0,!i&&n.data.cacheLen&&n.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),ah.logFailedEvent({userId:this._log.userId,eventType:CU.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=uD("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{um.lastMessageTime=Date.now();const n=i.inputBuffer.getChannelData(0);let c=0;for(let I=0;I>2);e.copyTo(n,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:n},[n.buffer]),e.close()}}},cEA=MT(oF()),S6=e=>i=>i.deviceId===e,G3=class{constructor(e,i){pe(this,"kind"),pe(this,"type"),pe(this,"devices",[]),this.kind=e,this.type=i}update(e,i){const n=e.filter(c=>c.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);this.devices.length===1&&sAA(this.devices[0])||i&&(n.forEach(c=>{if(c.deviceId&&!this.devices.find(S6(c.deviceId))){const I=`${this.kind}${this.type}Added`;An.warn(`${I}: ${JSON.stringify(c)}`),i.emit(I,c)}}),this.devices.forEach(c=>{if(c.deviceId&&!n.find(S6(c.deviceId))){const I=`${this.kind}${this.type}Removed`;An.warn(`${I}: ${JSON.stringify(c)}`),i.emit(I,c)}})),this.devices=n}hasDevice(e){return!!this.devices.find(i=>i.deviceId===e)}},lEA=class extends cEA.EventEmitter{constructor(){super(),pe(this,"audioInputs",new G3(ni.AUDIO,"Input")),pe(this,"videoInputs",new G3(ni.VIDEO,"Input")),pe(this,"audioOutputs",new G3(ni.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||RQ.run("interval",()=>{this.update()},{delay:1e4}))}init(){_W().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}async update(e=0){const i=await _W(e);return this.audioInputs.update(i,this),this.videoInputs.update(i,this),this.audioOutputs.update(i,this),this}hasBlueTooth(){var e;if(1e3*((e=uD())==null?void 0:e.outputLatency)>150)return!0;const i=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(n=>i.some(c=>n.label.toLowerCase().includes(c)))||this.audioInputs.devices.some(n=>i.some(c=>n.label.toLowerCase().includes(c)))}},SQ=_7||w7?null:new lEA;function sAA(e){return e.deviceId===e.groupId&&e.groupId===""}async function _W(e=0){if(KV()||!W4())return[];let i=await navigator.mediaDevices.enumerateDevices();if(e!==0){const n={audio:!1,video:!1};if(i.forEach(c=>{sAA(c)&&(c.kind===ni.AUDIO_INPUT?n.audio=!0:c.kind===ni.VIDEO_INPUT&&(n.video=!0))}),e===2&&(n.audio=!1),e===1&&(n.video=!1),n.audio||n.video){let c;try{c=await navigator.mediaDevices.getUserMedia(n),n.audio&&tV()}catch(I){An.debug("capture before getDevices failed: ",I)}i=await navigator.mediaDevices.enumerateDevices(),c?.getTracks().forEach(I=>I.stop())}}return i.map((n,c)=>{const I={kind:n.kind,deviceId:n.deviceId,groupId:n.groupId,label:n.label||`${n.kind}_${c}`};return n.deviceId.length>0&&i5.add(`${n.deviceId}_${n.kind}`),n.getCapabilities&&(I.getCapabilities=()=>n.getCapabilities()),I})}function xU(e=!1){return SQ.update(e?1:0).then(i=>i.audioInputs.devices)}function bM(e=!1){return SQ.update(e?2:0).then(i=>i.videoInputs.devices)}var v6=!1;async function IEA(){try{v6||(v6=!0,An.info(`speakers:${(await uEA()).map(e=>` ${e.deviceId.slice(0,8)}: ${e.label}`)}`))}catch{}}async function uEA(e=!1){return(_u||ud)&&(e=!1),SQ.update(e?1:0).then(i=>i.audioOutputs.devices)}var wY,i5=new Set;function EEA(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;const i=e.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;const n=`${(e?.getSettings()||{}).deviceId}_${ni.VIDEO_INPUT}`;return!!i5.has(n)}function dEA(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;const i=e.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("麦克风"))return!0;const n=`${(e?.getSettings()||{}).deviceId}_${ni.AUDIO_INPUT}`;return!!i5.has(n)}async function CEA(e,i){const n=(await xU()).find(c=>c.deviceId===G7);return!i&&n?.groupId===e||n?.groupId===e&&n.label===i}async function hEA({newDeviceId:e,oldDeviceId:i,oldGroupId:n,oldLabel:c,kind:I}){return e===i&&(I!==ni.AUDIO||e!==G7||await CEA(n,c))}var BEA=class extends rEA{constructor(e){super(),this.log=e,pe(this,"volumeMeter"),pe(this,"volumeMeterAfter3A"),pe(this,"volumeDestination"),pe(this,"analyser",new sEA),this.volumeMeter=new D6({log:this.log}),this.volumeMeterAfter3A=new D6({log:this.log}),this.volumeDestination=new GM,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},QEA=class extends pM{constructor(e){super(e,ni.AUDIO),pe(this,"_outputDeviceId"),pe(this,"_floatVolume",1),pe(this,"_destination"),pe(this,"pipeline"),pe(this,"volumeMeterMode","worklet"),pe(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new BEA(this._log)}setTrack(e){}get duration(){var e;return Math.floor(1e3*(((e=this.element)==null?void 0:e.duration)||0))}get currentTime(){var e;return Math.floor(1e3*(((e=this.element)==null?void 0:e.currentTime)||0))}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((TQ==="15.2"||TQ==="15.3"||TQ==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");this._log.info("audio player initializeElement");const i=wY||new Audio;i.setAttribute("autoplay","autoplay"),i.srcObject=this.getMediaStream(),i.muted=this.muted,this.url&&(i.crossOrigin="anonymous",i.src=this.url),this.element=i,this.setVolume(YM(e)?e/100:this._floatVolume),i===wY&&(wY=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(zs.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}async play(e){if(this.track||this.url){try{!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e?.volume),this._outputDeviceId&&await this.setSinkId(this._outputDeviceId),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(uD("player").createAnalyser()),IEA()}catch(i){throw this._log.warn(`audio play error: ${i}`),S$(TQ,"18.7",!0)&&this.bindAutoPlayEvent(),i}return super.play()}}stop(e=0){this.pipeline.destroy(),super.stop(e)}setVolume(e){this._floatVolume=e,this.element&&(this.element.volume=e)}async setSinkId(e){var i,n;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&await((n=(i=this.element).setSinkId)==null?void 0:n.call(i,e))}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},pEA=class extends QEA{constructor(e){super(e),pe(this,"_sourceElement"),pe(this,"_output",new GM),this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(uD().destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var i,n,c;((n=(i=this.element)==null?void 0:i.error)==null?void 0:n.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(zs.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((c=e.getSettings())==null?void 0:c.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){var i;const n=e<=1&&!WY();if(!(this._floatVolume===e&&(n&&((i=this.element)==null?void 0:i.volume)===e||!n&&this.pipeline.volume===e)))if(this._floatVolume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`);else if(n)this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element");else{if(WY()){if(!this.enableVolumeControlInIOS)return;nEA()}if(aC&&!this.pipeline.source.node)return void this._log.warn("set pipeline volume failed: no source node");this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this._destination||(this._destination=uD().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),FU(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(c=>{this.emit(zs.AUTOPLAY_FAILED,c)}))}}stop(e=0){this.pipeline.destroy();const i=this._sourceElement||this.element;i&&D$&&(wY=i),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},o5=class extends nr{constructor({userId:e,sdkAppId:i,mediaType:n,room:c,PlayerClass:I=n===1?pEA:Ky}){var C;super(),pe(this,"id",N$()),pe(this,"userId",""),pe(this,"isRemote"),pe(this,"mediaType"),pe(this,"room"),pe(this,"user"),pe(this,"_log"),pe(this,"_inputTrack"),pe(this,"_outputTrack"),pe(this,"isPlayCalled"),pe(this,"container",null),pe(this,"player"),pe(this,"subVideoPlayerMap"),pe(this,"muted",!1),pe(this,"abortCtrl"),pe(this,"objectFit","cover"),pe(this,"mirror"),pe(this,"rotation"),pe(this,"isScreen",!1),pe(this,"manager"),pe(this,"trackSettings"),pe(this,"isFirstVideoFrameEmitted",!1),this.userId=e||"",this.mediaType=n,this._log=An.createLogger({parent:c?.getLogger(),id:`${this.kind[0]}t`,userId:(C=c||this.room)==null?void 0:C.userId,remoteUserId:this instanceof vM?void 0:this.userId,sdkAppId:i,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof vM}),this.player=new I({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:c?.enableVolumeControlInIOS}),this.player.on(zs.PLAYER_STATE_CHANGED,m=>{if(Rn.emit(Rs.PLAYER_STATE_CHANGED,ks({track:this},m)),this.emit("player-state-changed",m),m.state==="PLAYING"&&this.room){let R=!0;for(const{remoteAudioTrack:_,remoteVideoTrack:T,remoteAuxiliaryTrack:b}of[...this.room.remotePublishedUserMap.values()])if(_.isAvailable&&!_.player.isPlaying||T.isAvailable&&!T.player.isPlaying||b.isAvailable&&!b.player.isPlaying){R=!1;break}R&&OU()&&AEA()}}),this.kind===ni.VIDEO&&(this.player.on(zs.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(zs.LOADED_DATA),Rn.emit(Rs.VIDEO_LOADED_DATA,{track:this})}),this.player.on(zs.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(zs.LOADED_META_DATA)}),this.player.on(zs.MEDIA_TRACK_CHANGED,m=>{var R;(R=this.subVideoPlayerMap)==null||R.forEach(_=>_.setTrack(m))}),this.player.on(zs.RESIZE,m=>{this.emitFirstVideoFrameEvent(zs.RESIZE),this.emit("video-size-changed",ks({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},m))}),this.player.on(zs.FIRST_FRAME_RENDER,m=>{this.emit("first-frame-render",cB(ks({},m),{streamType:this.streamType,userId:this.isRemote?this.userId:""}))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(zs.ERROR,this.onPlayerError.bind(this)),this.player.on(zs.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||An}get kind(){return this.mediaType===1?ni.AUDIO:ni.VIDEO}get isAudio(){return this.kind===ni.AUDIO}get strMediaType(){return this.mediaType===4?ni.VIDEO:this.mediaType===2?ni.SCREEN:ni.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}async play(e,i){const n=oh(e)?e[0]:e;if(this.isPlayCalled)return this.log.info(`play update options: ${JSON.stringify(i)}`),i&&!sr(i.muted)&&this.setPlayerMute(i.muted),i&&!sr(i.objectFit)&&(this.objectFit=i.objectFit),void(this.player instanceof Ky&&(this.player.setObjectFit(this.objectFit),this.container!==n&&n&&(oh(e)&&e.length>=1&&this.container&&e.includes(this.container)&&this.container.contains(this.player.elementToRender)?(e.splice(e.indexOf(this.container),1),e.unshift(this.container)):(this.container=n,this.player.setContainer(n))),oh(e)&&e.length>=1&&await this.playSubContainer(e.slice(1),i)));if(i&&!sr(i.muted)?this.setPlayerMute(i.muted):this.isRemote&&this.kind!==ni.VIDEO||this.setPlayerMute(!0),i&&!sr(i.objectFit)&&(this.objectFit=i.objectFit),this.player instanceof Ky&&(sr(i?.isLiveStream)||this.player.setLiveMode(i.isLiveStream),this.player.setObjectFit(this.objectFit),i&&!sr(i.poster)&&this.player.setPoster(i.poster)),this.isPlayCalled=!0,n&&(this.container=n,this.player instanceof Ky&&this.player.setContainer(n)),Rn.emit(Rs.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info(`play with options: ${JSON.stringify(i)}`);try{this.player.setTrack(this.playerMediaTrack),await this.player.play(i),oh(e)&&e.length>1&&await this.playSubContainer(e.slice(1),i)}catch(c){throw this.handleAutoPlayFailed(c),c}}else this.log.info("play has not mediaTrack, abort")}setMirror(e,i){if(this.isScreen||this.kind!==ni.VIDEO||sr(e)||e===this.mirror)return;this.mirror=e;let n=this.player;i&&(n=i);const c=this.manager;if(TM(this.mirror))return n.setViewMirror(this.mirror),void(!this.isRemote&&c&&(c.mirror=!1));switch(this.mirror){case"view":c&&(c.mirror=!1),n.setViewMirror(!0);break;case"publish":c&&(c.mirror=!0),n.setViewMirror(!0);break;case"both":c&&(c.mirror=!0),n.setViewMirror(!1)}}async playSubContainer(e,i){if(!this._outputTrack||this.kind===ni.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((c,I)=>{var C;e.find(m=>I===m)||(c.stop(),(C=this.subVideoPlayerMap)==null||C.delete(I))});for(const[c,I]of e.entries()){const C=this.subVideoPlayerMap.get(I);C?i&&(sr(i.objectFit)||C.setObjectFit(i.objectFit)):this.subVideoPlayerMap.set(I,new Ky({id:this.userId||this.id,track:this.playerMediaTrack,container:I,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${c+1}`})}))}const n=[...this.subVideoPlayerMap.values()];for(const c of n)c.setViewMirror(this.player.mirror),await c.play()}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(f3(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(i=>{i.stop()}),this.container=null)}async resume(){var e;this.isPlayCalled&&await((e=this.player)==null?void 0:e.resume())}close(){this._toInitState(),this.log.info("close"),this.isPlayCalled&&this.stop(!0)}_toInitState(){}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),Rn.emit(e?Rs.TRACK_MUTED:Rs.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){e5(e,e).add(ni.MUTE,this.onTrackMuted).add(ni.UNMUTE,this.onTrackUnmuted).add(ni.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===ni.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){FU(e)}setInputMediaStreamTrack(e){var i;const n=this._inputTrack;if(e!==n)return this._inputTrack=e,this.trackSettings=(i=e.getSettings)==null?void 0:i.call(e),e.enabled=!this.muted,n&&this.uninstallTrackEvent(n),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,n||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var i;const n=this._outputTrack;this instanceof zV&&N4(n)||e!==n&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(i=e.getSettings)==null?void 0:i.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){var i,n;if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch(c=>this.handleAutoPlayFailed(c)),void this.log.info(`playing state updated, play ${this.kind}`)}else if(!this.player.isStopped)return f3(this)&&this.isAudio&&((i=this.user)!=null&&i.muteState.hasAudio)&&((n=this.user)!=null&&n.muteState.audioMuted)?void 0:(this.player.stop(f3(this)?this.jitterBufferDelay:0),void this.log.info(`playing state updated, stop ${this.kind}`))}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}async handleAutoPlayFailed(e){var i;this.log.warn("handleAutoPlayFailed",e);const n=()=>{this.resume().then(()=>{document.removeEventListener("click",n,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((RT||rF)&&(await QT(100),(i=this.player)==null?void 0:i.isPlaying))return;$uA()}else document.addEventListener("click",n,!0);Rn.once(Rs.LOCAL_TRACK_CAPTURE_SUCCESS,({track:c})=>{c.kind==="audio"&&OU()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&n()}),this.emit("error",e)}getVideoFrame(){return this.player instanceof Ky?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var i,n,c;if(this.isFirstVideoFrameEmitted)return;const I=(i=this.mediaTrack)==null?void 0:i.getSettings();let C=I?.width||((n=this.player.element)==null?void 0:n.videoWidth)||0,m=I?.height||((c=this.player.element)==null?void 0:c.videoHeight)||0;(e!==zs.RESIZE||C||m)&&(e!==zs.LOADED_META_DATA||C||m)&&(e!==zs.LOADED_DATA||C||m||this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,j7(this.rotation)&&([C,m]=[m,C]),this.emit("first-video-frame",{width:C,height:m,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};yc([Ru([],nr.INIT,{sync:!0})],o5.prototype,"_toInitState");var mEA=Object.prototype.hasOwnProperty;function fEA(e){if(e==null)return!0;if(typeof e=="boolean")return!1;if(typeof e=="number")return e===0;if(typeof e=="string"||typeof e=="function"||Array.isArray(e))return e.length===0;if(e instanceof Error)return e.message==="";if(BT(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return e.size===0;case"[object Object]":for(const i in e)if(mEA.call(e,i))return!1;return!0}return!1}var iV=fEA,yEA=async function(e){const i=SEA(e);An.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let n=[],c=[];const I=["label","deviceId","groupId"];if(i.audio&&(n=await xU(),An.info(`microphones: ${oD(n.map(C=>cB(ks({},C),{groupId:C.groupId.substring(0,8)})),{keysToInclude:I})}`)),i.video&&(c=await bM(),An.info(`cameras: ${oD(c,{keysToInclude:I})}`),!TM(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){const C=c.filter(m=>!m.label.includes("infrared")).find(m=>m.label.includes("facing front"));C&&(i.video.deviceId=C.deviceId,An.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{const C=await navigator.mediaDevices.getUserMedia(i);return K$&&C.getTracks().forEach(m=>{var R;const _=m.getCapabilities();An.info(`${m.kind} capabilities: ${oD(_,{keysToInclude:b7})}`),sr(e.echoCancellation)||((R=_.echoCancellation)==null?void 0:R.indexOf(e.echoCancellation))!==-1||An.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(_.echoCancellation)}], but received '${e.echoCancellation}'`)}),i.audio&&tV(),C}catch(C){let{message:m}=C;throw C.name==="NotFoundError"&&(e.video&&c&&c.length===0&&(m=AV({key:$Y.CAMERA_NOT_FOUND})),e.audio&&n&&n.length===0&&(m=AV({key:$Y.MICROPHONE_NOT_FOUND}))),new vl({code:Zg.INITIALIZE_FAILED,name:C.name,message:m,constraint:C.constraint})}},DEA=G4({retryFunction:yEA,settings:{retries:3,timeout:500},onError:({error:e,retry:i,reject:n,retryFuncArgs:c,retriedCount:I})=>{const C=I+1;e.name==="NotReadableError"||e.name==="OverconstrainedError"||e.name==="AbortError"?(C===1?(c[0].video&&(c[0].maxResolution=!1,(!ud||c[0].width*c[0].height<=2073600)&&c[0].frameRate&&(c[0].frameRate=c[0].frameRate>10?10:5)),c[0].retryWhenExactFailed&&c[0].useExactDeviceId&&(c[0].useExactDeviceId=!1)):C===2?c[0].useDeviceIdOnly=!0:C!==3||c[0].useExactDeviceId||(c[0].useTrueAsConstraint=!0),i()):n(e),c[0].microphoneId&&M6(c[0].microphoneId,!1),c[0].cameraId&&M6(c[0].cameraId,!0)},onRetrying:e=>{An.warn(`getUserMedia NotReadableError observed, retrying [${e}/3]`)},onRetryFailed:e=>{ah.logFailedEvent({eventType:CU.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{ah.logSuccessEvent({eventType:CU.GET_USER_MEDIA_RETRY}),ah.uploadEvent({log:`stat-${CU.GET_USER_MEDIA_RETRY}-success-${e}`})}});async function M6(e,i){const n=(i?await bM():await xU()).find(c=>c.deviceId===e);n&&_M(n.getCapabilities)&&An.warn(oD(n.getCapabilities(),{keysToInclude:b7}))}function SEA(e){return{audio:vEA(e),video:MEA(e)}}function vEA(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;const i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!iV(e.microphoneId)&&(i.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?i:(YM(e.channelCount)&&(i.channelCount=e.channelCount),(TM(e.echoCancellation)||e.echoCancellation==="remote-only"||e.echoCancellation==="all")&&(i.echoCancellation=e.echoCancellation),TM(e.noiseSuppression)&&!e.noiseSuppression&&(i.noiseSuppression=!1),TM(e.autoGainControl)&&!e.autoGainControl&&(i.autoGainControl=!1),!!iV(i)||i)}function MEA(e){if(!e.video)return!1;if(e.useTrueAsConstraint)return!0;const{maxResolution:i=!0}=e,n={};return e.cameraId?n.deviceId=e.useExactDeviceId?{exact:e.cameraId}:e.cameraId:e.facingMode&&(n.facingMode=e.facingMode),e.useDeviceIdOnly&&!iV(n)?n:(e.width&&(n.width={ideal:e.width},i&&!aC&&(n.width.max=e.width)),e.height&&(n.height={ideal:e.height},i&&!aC&&(n.height.max=e.height)),aC&&JV&&e.width&&e.height&&e.width*e.height<101376&&(n.width=e.width,n.height=e.height),e.frameRate&&(n.frameRate=e.frameRate),!!iV(n)||n)}var REA=DEA;function rAA(e){return WV((i,n)=>async function(...c){const I=await i.apply(this,c);return await e.call(this,...c),I})}function WV(e){return function(i,n,c){return c.value=e(c.value,n),c}}var wEA=(()=>{let e=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&An.info(`visibility change: ${document.visibilityState}`),e||(document.addEventListener("visibilitychange",()=>{An.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),e=!0)}})(),_EA=0,TEA=class{constructor(e){pe(this,"log"),pe(this,"isRunning",!1),pe(this,"queue",[]);let i="fq"+ ++_EA;e&&(i+=`|${e}`),this.log=An.createLogger({id:i})}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(e,i=!1){var n,c;const I=ks({},e),C=new Promise((m,R)=>{I.resolve=m,I.reject=R});return I.promise=C,i?this.length<=1?this.queue.push(I):(c=(n=this.lastQueueItem)==null?void 0:n.promise)==null||c.then(I.resolve,I.reject):this.queue.push(I),this.log.debug(`push ${this.length}`,e.funcName,e.args),this.isRunning||this.callNext(),C}shift(){const e=this.queue.shift();return this.log.debug(`shift ${this.length}`,e?.funcName,e?.args),e}callNext(){if(this.isRunning||this.length===0)return;const{fn:e,args:i,context:n,resolve:c,reject:I,funcName:C}=this.queue[0];this.log.debug("callNext",this.length,C,i),this.isRunning=!0,e.apply(n,i).then(c,I).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},R6=new WeakMap;function NEA(e=!1){return function(i,n,c){const I=c.value;return c.value=function(...C){const m=R6.get(this)||new TEA;return R6.set(this,m),m.push({fn:I,args:C,context:this,funcName:n},e)},c}}function aAA(e,i){return WV((n,c)=>function(...I){const C=e;try{const m=n.apply(this,I),R=Wc();return O7(m)?m.then(_=>(i?mr.addSuccessEvent({key:C,cost:Wc()-R}):mr.addSuccessEvent({key:C}),_)).catch(_=>{throw mr.addFailedEvent({key:C,error:_}),_}):(mr.addSuccessEvent({key:C}),m)}catch(m){throw mr.addFailedEvent({key:C,error:m}),m}})}function oI(...e){}var GEA=e=>e();function bEA(){this.dispose()}var kEA=()=>typeof __FASTRX_DEVTOOLS__<"u",LEA=1,pT=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(e){const i=new FEA(e,this,this.streamId++);return Sl.subscribe({id:this.id,end:!1},{nodeId:i.sourceId,streamId:i.id}),this(i),i}},n5=class{constructor(){this.defers=new Set,this.disposed=!1}next(e){}complete(){this.dispose()}error(e){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=oI,this.error=oI,this.next=oI,this.dispose=oI,this.subscribe=oI,this.doDefer()}subscribe(e){return e instanceof pT?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(GEA),this.defers.clear()}defer(e){this.defers.add(e)}removeDefer(e){this.defers.delete(e)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},IB=class extends n5{constructor(e){super(),this.sink=e,e.defer(this.bindDispose)}next(e){this.sink.next(e)}complete(){this.sink.complete()}error(e){this.sink.error(e)}},UEA=class extends n5{constructor(e,i=oI,n=oI,c=oI){if(super(),this._next=i,this._error=n,this._complete=c,this.then=oI,e instanceof pT){const I={toString:()=>"subscribe",id:0,source:e};this.defer(()=>{Sl.defer(I,0)}),Sl.create(I),Sl.pipe(I),this.sourceId=I.id,this.subscribe(e),Sl.subscribe({id:I.id,end:!0}),i==oI?this._next=C=>Sl.next(I,0,C):this.next=C=>{Sl.next(I,0,C),i(C)},c==oI?this._complete=()=>Sl.complete(I,0):this.complete=()=>{this.dispose(),Sl.complete(I,0),c()},n==oI?this._error=C=>Sl.complete(I,0,C):this.error=C=>{this.dispose(),Sl.complete(I,0,C),n(C)}}else this.subscribe(e)}next(e){this._next(e)}complete(){this.dispose(),this._complete()}error(e){this.dispose(),this._error(e)}};function ih(e,...i){return i.reduce((n,c)=>c(n),e)}function gC(e,i,n){if(kEA()){const c=Object.defineProperties(Object.setPrototypeOf(e,pT.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:n,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Sl.create(c);for(let I=0;I{if(c instanceof pT){const I=gC(C=>{const m=new e(C,...n);m.sourceId=I.id,m.subscribe(c)},i,arguments);return I.source=c,Sl.pipe(I),I}return I=>c(new e(I,...n))}}}function Fy(e,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:i}})}var FEA=class extends IB{constructor(e,i,n){super(e),this.source=i,this.id=n,this.sourceId=e.sourceId,this.defer(()=>{Sl.defer(this.source,this.id)})}next(e){Sl.next(this.source,this.id,e),this.sink.next(e)}complete(){Sl.complete(this.source,this.id),this.sink.complete()}error(e){Sl.complete(this.source,this.id,e),this.sink.error(e)}},Sl={addSource(e,i){Fy("addSource",{id:e.id,name:e.toString(),source:{id:i.id,name:i.toString()}})},next(e,i,n){Fy("next",{id:e.id,streamId:i,data:n&&n.toString()})},subscribe({id:e,end:i},n){Fy("subscribe",{id:e,end:i,sink:{nodeId:n&&n.nodeId,streamId:n&&n.streamId}})},complete(e,i,n){Fy("complete",{id:e.id,streamId:i,err:n?n.toString():null})},defer(e,i){Fy("defer",{id:e.id,streamId:i})},pipe(e){Fy("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){Fy("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=LEA++),Fy("create",{name:e.toString(),id:e.id})}},OEA=class extends n5{constructor(e){super(),this.source=e,this.sinks=new Set}add(e){e.defer(()=>this.remove(e)),this.sinks.add(e).size===1&&(this.reset(),this.subscribe(this.source))}remove(e){this.sinks.delete(e),this.sinks.size===0&&this.dispose()}next(e){this.sinks.forEach(i=>i.next(e))}complete(){this.sinks.forEach(e=>e.complete()),this.sinks.clear()}error(e){this.sinks.forEach(i=>i.error(e)),this.sinks.clear()}};function gAA(){return e=>{const i=new OEA(e);if(e instanceof pT){const n=gC(c=>{i.add(c)},"share",arguments);return i.sourceId=n.id,n.source=e,Sl.pipe(n),n}return gC(i.add.bind(i),"share",arguments)}}function cAA(...e){return gC(i=>{const n=new IB(i);let c=e.length;n.complete=()=>{--c===0&&i.complete()},e.forEach(n.bindSubscribe)},"merge",arguments)}function PEA(...e){return gC(i=>{const n=new Map;e.forEach(c=>{const I=new IB(i);n.set(c,I),I.complete=()=>{n.delete(c),n.size===0?i.complete():I.dispose()},I.next=C=>{n.delete(c),n.forEach(m=>m.dispose()),I.resetNext(),I.resetComplete(),I.next(C)}}),e.forEach(c=>n.get(c).subscribe(c))},"race",arguments)}function xEA(...e){return i=>gC((n,c=0,I=e.length)=>{for(;c{n.next=I=>c.next(I),n.complete=()=>c.complete(),n.error=I=>c.error(I),e&&c.subscribe(e)},"subject",i));return n.next=oI,n.complete=oI,n.error=oI,n}function YEA(e){return gC(i=>{let n=0;const c=setInterval(()=>i.next(n++),e);return i.defer(()=>{clearInterval(c)}),"interval"},"interval",arguments)}function VEA(e,i){return gC(n=>{let c=0;const I=setTimeout(()=>{n.removeDefer(C),n.next(c++),i||n.complete()},e),C=()=>clearTimeout(I);n.defer(C)},"timer",arguments)}function b3(e,i){return n=>{const c=I=>n.next(I);n.defer(()=>i(c)),e(c)}}function DE(e,i){if("on"in e&&"off"in e)return gC(b3(n=>e.on(i,n),n=>e.off(i,n)),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return gC(b3(n=>e.addListener(i,n),n=>e.removeListener(i,n)),"fromEvent",arguments);if("addEventListener"in e)return gC(b3(n=>e.addEventListener(i,n),n=>e.removeEventListener(i,n)),"fromEvent",arguments);throw"target is not a EventDispachter"}function HEA(){return gC(e=>e.complete(),"empty",arguments)}var JEA=class extends IB{constructor(e,i,n){super(e),this.filter=i,this.thisArg=n}next(e){this.filter.call(this.thisArg,e)&&this.sink.next(e)}},gT=qM(JEA,"filter"),qEA=class extends IB{constructor(e,i){super(e),this.count=i}next(e){this.sink.next(e),--this.count===0&&(this.doDefer(),this.complete())}},KEA=qM(qEA,"take"),jEA=class extends IB{constructor(e,i){super(e);const n=new IB(e);n.next=()=>{n.doDefer(),e.complete()},n.complete=bEA,n.subscribe(i)}},mT=qM(jEA,"takeUntil"),WEA=class extends IB{constructor(e,i){super(e),this.f=i}next(e){this.f(e)||(this.next=super.next,this.next(e))}},zEA=qM(WEA,"skipWhile"),ZEA=class extends IB{constructor(e,i,n){super(e),this.mapper=i,this.thisArg=n}next(e){super.next(this.mapper.call(this.thisArg,e))}},IAA=qM(ZEA,"map"),XEA=class extends IB{constructor(e,i,n){super(e),this.data=i,this.context=n}next(e){const i=this.context.combineResults;i?this.sink.next(i(this.data,e)):this.sink.next(e)}tryComplete(){this.context.resetComplete(),this.dispose()}},$EA=class uAA extends IB{constructor(i,n,c){super(i),this.makeSource=n,this.combineResults=c,this.index=0}subInner(i,n){const c=this.currentSink=new n(this.sink,i,this);this.complete===uAA.prototype.complete&&(this.complete=this.tryComplete),c.complete=c.tryComplete,c.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},w6=class extends XEA{},EAA=class extends $EA{next(e){this.subInner(e,w6),this.next=i=>{this.currentSink.dispose(),this.subInner(i,w6)}}},AdA=qM(EAA,"switchMap");function edA(e){return(i,n)=>e(()=>i,n)}var dAA=edA(qM(EAA,"switchMapTo")),HM=(e=oI,i=oI,n=oI)=>c=>new UEA(c,e,i,n),CAA=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(CAA||{}),vM=class extends o5{constructor(e,i){super({mediaType:e,PlayerClass:i}),pe(this,"isRemote",!1),pe(this,"deviceId"),pe(this,"groupId",""),pe(this,"label",""),pe(this,"sourceTrack"),pe(this,"enableAutoSwitchWhenRecapturing",!0),pe(this,"_isRecapturing",!1),pe(this,"_lastRecaptureTime",0),pe(this,"_onMuteTimeoutId",-1),pe(this,"_encodeCheckTimeoutId",-1),pe(this,"recaptureMode",0),pe(this,"profile"),pe(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return!(!this.mediaTrack||this.sourceTrack===this.mediaTrack)}encodeFrame(e,i){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(ni.MUTE,this.onTrackMuted),e.addEventListener(ni.UNMUTE,this.onTrackUnmuted),e.addEventListener(ni.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===ni.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(ni.MUTE,this.onTrackMuted),e.removeEventListener(ni.UNMUTE,this.onTrackUnmuted),e.removeEventListener(ni.ENDED,this.onTrackEnded)}setStateToReady(){}async capture(e,i=!1){var n,c;const I=this.sourceTrack;try{const C=Wc();let m;Rn.emit(Rs.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(m=new MediaStream,m.addTrack(e.customSource)):(i||(n=this.sourceTrack)==null||n.stop(),m=await REA(e));const R=m.getTracks()[0];return await this.setInputMediaStreamTrack(R),e.customSource||(this.sourceTrack=R,this.updateDeviceIdInUse(),this.listenDeviceChange()),Rn.emit(Rs.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Wc()-C,profile:this.profile,room:(c=this.manager)==null?void 0:c.room}),m}catch(C){throw Rn.emit(Rs.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:C}),this.log.error(`getUserMedia error observed ${C}`),C}finally{i&&I?.stop()}}setOutputMediaStreamTrack(e){var i;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(i=this.room)==null?void 0:i.replaceTrack(this)}get hasFlag(){var e,i;const n=x7(((e=this.room)==null?void 0:e.localPublishFlag)||0,((i=this.room)==null?void 0:i.userId)||"");return this.mediaType===4&&n.hasVideo||this.mediaType===1&&n.hasAudio||this.mediaType===2&&n.hasAuxiliary}async publish(e,i){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),await i,this._checkPublishFlag(e)}_checkPublishFlag(e){return new Promise(async(i,n)=>{var c,I,C,m,R;const _=()=>n(new vl({code:Zg.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?i():(this.state!==nr.INIT&&this.state!=="ready"||_(),ih(DE(e,"local-publish-flag-changed"),gT(()=>this.hasFlag),mT(cAA(DE(this,nr.INIT),DE(this,"ready"))),HM(i,n,_))),(C=(I=(c=this.room)==null?void 0:c.networkQuality)==null?void 0:I.hadRecentBadUplink)==null?void 0:C.call(I,2))return i();const T=e.heartbeatCount,b=((R=(m=this.mediaTrack)==null?void 0:m.stats)==null?void 0:R.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(async()=>{var J,cA,eA,CA,IA,oA,vA,qA;if((eA=(cA=(J=this.room)==null?void 0:J.networkQuality)==null?void 0:cA.hadRecentBadUplink)!=null&&eA.call(cA,2)||e.heartbeatCount-T<3)return i();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((CA=this.mediaTrack)!=null&&CA.stats){const se=this.mediaTrack.stats.totalFrames||0;se-b===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",se)}const Ae=this.kind===ni.AUDIO,HA=this.stat.bytesSent>0;if(mr[HA?"addSuccessEvent":"addFailedEvent"]({key:Ae?503700:513702}),!Ae){const se={H264:513704,H265:513705,VP8:513706}[((oA=(IA=this.room)==null?void 0:IA.videoCodec)==null?void 0:oA.toUpperCase())||"H264"];se&&mr[HA?"addSuccessEvent":"addFailedEvent"]({key:se})}if(!HA){if(mr.addEnum({key:Ae?503701:513703,value:q4()}),ah.uploadEvent({log:`stat-encode-failed-${this.kind}-${v$()||R$()}`,userId:this.userId}),this.log.warn(Ae?"encode failed":`${(qA=(vA=this.room)==null?void 0:vA.videoCodec)==null?void 0:qA.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),await this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(await QT(5e3),this.stat.bytesSent>0||this.hasFlag)))return i();this.emit("6",this),n(new vl({message:`${this.strMediaType} encode failed`,code:Ae?Zg.AUDIO_ENCODE_FAILED:Zg.VIDEO_ENCODE_FAILED}))}}},1e4)})}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),Rn.emit(Rs.LOCAL_TRACK_UNPUBLISHED,{track:this})}async updateDeviceIdInUse(){if(this.sourceTrack&&eV){const{deviceId:e,groupId:i}=this.sourceTrack.getSettings(),{label:n}=this.sourceTrack;await hEA({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind})||(this.deviceId=e,this.label=n,i&&(this.groupId=i),_W().then(c=>{const I=c.find(C=>{let m=C.deviceId===e;return i&&(m=m&&C.groupId===i),m});I&&this.emit("2",I)}))}}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===ni.AUDIO&&!dEA(this.sourceTrack)||this.kind===ni.VIDEO&&!EEA(this.sourceTrack)||this._isRecapturing||e&&JV&&ud)}onTrackMuted(){super.onTrackMuted(),wEA(),this.isNeedToRecapture(!0)&&(Date.now()-this._lastRecaptureTimethis.onTrackMuted(),iY):this._onMuteTimeoutId=setTimeout(async()=>{var e;if((e=this.sourceTrack)!=null&&e.muted){if((_u||cC)&&document.visibilityState!=="visible")return;this.recapture(await this.getRecoverCaptureDeviceId())}},5e3))}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}async onTrackEnded(){if(super.onTrackEnded(),this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTimethis.onTrackEnded(),iY);this.emit("7"),this.recapture(await this.getRecoverCaptureDeviceId())}}async recapture(e,i=!1){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");const c=this.sourceTrack;i||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();const I={useExactDeviceId:!0};if(e==="user"||e==="environment")I.facingMode=e;else{let C;(this.kind==="audio"?await xU():await bM()).find(m=>m.deviceId===e)&&(C=e),I.deviceId=C}return this.capture(I,i).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),Rn.emit(Rs.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(C=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${C.message}`),this.emit("5",C),Rn.emit(Rs.LOCAL_TRACK_RECAPTURE,{track:this,error:C})}).finally(()=>{i&&c?.stop()})}async getRecoverCaptureDeviceId(){const e=this instanceof zV;if(e&&this.facingMode)return this.facingMode;let{deviceId:i}=this;if(i){const n=(zL.get(i)||0)+1;if(zL.set(i,n),n>=3&&this.enableAutoSwitchWhenRecapturing){const c=e?(await bM()).find(I=>!zL.has(I.deviceId)):(await xU()).find(I=>!zL.has(I.deviceId));c&&(this.log.warn(`${i} capture fail ${n} times, change new ${c.deviceId}`),i=c.deviceId)}}return i}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),Rn.emit(Rs.LOCAL_TRACK_STOPPED,{track:this}),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(e=this.manager)==null||e.removeInput(this),this._onMuteTimeoutId&&clearTimeout(this._onMuteTimeoutId)}close(){super.close(),this.stopCapture()}};yc([Ru(nr.INIT,"ready",{ignoreError:!0,sync:!0})],vM.prototype,"setStateToReady"),yc([NEA()],vM.prototype,"capture"),yc([Ru("ready","publish",{ignoreError:!0,success(){Rn.emit(Rs.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var i;(i=this.room)==null||i.localTracks.delete(this);let n="error";const c=e instanceof vl?e:e.cause instanceof vl?e.cause:e;let I=!1;c instanceof vl&&(c.message.includes("timeout")?n="timeout":c.code===Zg.API_CALL_ABORTED&&(I=!0,n="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:n,error:c}),this.log[I?"info":"error"]("publish failed",c)}}),aAA(521714,!1)],vM.prototype,"publish"),yc([WV(e=>async function(){const i=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)}),Ru([],"ready",{sync:!0})],vM.prototype,"unpublish");var zL=new Map;Rn.on(Rs.SWITCH_DEVICE_SUCCESS,e=>{e.track.deviceId&&zL.delete(e.track.deviceId)});var tdA=class{constructor(e,i=!1){this.dataView=e,this.isSEI&&(i?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){const{seiPayloadStartIndex:e}=this,i=this.dataView.byteLength-2,n=[];let c=0;for(let C=e;C<=i;C++){const m=this.dataView.getInt8(C);switch(m){case 0:case 1:case 2:case 3:c===2&&(n.push(3),c=0),m===0?c+=1:c=0,n.push(m);break;default:c=0,n.push(m)}}n.push(this.dataView.getInt8(this.dataView.byteLength-1));const I=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...n]).buffer);this.dataView=I}removePreventionByte(){const{seiPayloadStartIndex:e}=this,i=this.dataView.byteLength-1,n=[];let c=0;for(let C=e;C<=i;C++)switch(this.dataView.getInt8(C)){case 0:c++,n.push(this.dataView.getInt8(C));break;case 3:c!==2&&n.push(this.dataView.getInt8(C)),c=0;break;default:n.push(this.dataView.getInt8(C)),c=0}const I=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...n]).buffer);this.dataView=I}get seiPayloadStartIndex(){let e=6;for(let i=6;i=this.dataView.byteLength?0:31&this.dataView.getUint8(e)}getStartCodeLength(){return this.dataView.byteLength>=4&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===0&&this.dataView.getUint8(3)===1?4:this.dataView.byteLength>=3&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===1?3:0}get isIDR(){return this.naluType===5}get isSPS(){return this.naluType===7}get isPPS(){return this.naluType===8}get isSEI(){return this.naluType===6}},idA=class{constructor(){pe(this,"_seiMessageList",[]),pe(this,"_smallSeiMessageList",[]),pe(this,"_seiPayloadType",243)}encodeSEINalu(e){const i=e.byteLength,n=parseInt(String(i/255),10),c=i%255,I=[];I.push(0,0,0,1,6,this._seiPayloadType);for(let m=0;m0&&e.data.byteLength>0){const c=9-this.getNaluCount(e.data);if(c<=0)return 0;const I=n.splice(0,c).reverse().map(this.encodeSEINalu.bind(this)),C=I.reduce((b,J)=>b+J.dataView.byteLength,0),m=new ArrayBuffer(C+e.data.byteLength),R=new DataView(m),_=new DataView(e.data);let T=0;for(let b=0;b{var c;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{const I=KY(((c=this.room)==null?void 0:c.sdkAppId)||0)?YZ:xZ;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${I}`),this.setProfile(cB(ks({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",n),this.on("publish",n),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(eV&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}get hasSmall(){var e;return!!((e=this.manager)!=null&&e.hasSmall)}async setMute(e){var i,n,c;if(rh(e)){if(this.muteImage===e)return;await((i=this.manager)==null?void 0:i.deleteWatermark("mute")),await((n=this.manager)==null?void 0:n.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e,fillVideo:!0})),this.muteImage=e,super.setMute(!1)}else this.muteImage&&(await((c=this.manager)==null?void 0:c.deleteWatermark("mute")),this.muteImage=void 0),super.setMute(e)}async capture({deviceId:e,facingMode:i,useExactDeviceId:n=!0,customSource:c,retryWhenExactFailed:I=!0}){const C={audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:n,retryWhenExactFailed:I,customSource:c};if(C.facingMode==="environment"){const m=await this.getDeviceIdWhenUsingBackCamera();m&&(C.cameraId=m)}return super.capture(C)}setProfile(e){var i;const n=this.fallbackProfile(e);if(n.bitrate&&(this.isNeedToSetBandwidth=n.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(n);else{const c=KY(((i=this.room)==null?void 0:i.sdkAppId)||0)?YZ:xZ;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${c}`),super.setProfile(cB(ks({},this.profile),{width:1920,height:1080}))}}async applyProfile(){var e,i;if(!this.mediaTrack)return;const{width:n=0,height:c=0}=(this.sourceTrack||this.mediaTrack).getSettings(),I=n*c,C=this.settings,m=C.height!==this.profile.height||C.width!==this.profile.width||C.frameRate!==this.profile.frameRate;if(m&&(VM===16&&this.deviceId?await this.recapture(this.deviceId):(N4(this.outMediaTrack)?await((e=this.outMediaTrack)==null?void 0:e.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate})):await((i=this.sourceTrack||this.mediaTrack)==null?void 0:i.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate})),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;const{width:R=0,height:_=0}=(this.sourceTrack||this.mediaTrack).getSettings(),T=R*_;return m&&T&&I&&T===I?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:ni.VIDEO,videoType:ni.BIG})}}get settings(){const e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},i=this.sourceTrack||this.mediaTrack;return eV&&i&&Object.assign(e,i.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:K7(this.settings,this.profile)}isAllowed2k4k(e){var i;return!this.room||!this.room.scheduleResult||!!this.isScreen||e.height*e.width<3686400||((i=this.room.scheduleResult.trtcAutoConf)==null?void 0:i["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}async switchDevice(e){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;const i={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?i.facingMode=e:i.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),await this.capture(i),Rn.emit(Rs.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(i){throw this.log.error(`switch camera failed ${i}`),this.deviceId&&this.recapture(this.deviceId),i}}async getDeviceIdWhenUsingBackCamera(){let e;try{if(h$&&!H4&&j$){const i=(await bM(!0)).map(c=>{var I;return cB(ks({},c),{capabilities:(I=c.getCapabilities)==null?void 0:I.call(c)})}).filter(c=>{var I,C;return(C=(I=c.capabilities)==null?void 0:I.facingMode)==null?void 0:C.includes("environment")});let n=i[0];i.forEach(c=>{var I,C,m,R;const{capabilities:_}=c;((I=_.width)!=null&&I.max&&((C=_.height)!=null&&C.max)?_.width.max*_.height.max:0)>((m=n.capabilities.width)!=null&&m.max&&((R=n.capabilities.height)!=null&&R.max)?n.capabilities.width.max*n.capabilities.height.max:0)&&(n=c)}),n?.capabilities&&(this._log.info("use max resolution back camera",n),e=n.deviceId)}}catch(i){this._log.warn("get max res camera failed",i)}return e}async updateSmallConfig(e){var i,n;this._log.info(`update small stream config: ${JSON.stringify(e)}`);const c=!this.small;this.small=this.fallbackProfile(e,!0),await((i=this.manager)==null?void 0:i.update()),c&&await((n=this.room)==null?void 0:n.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,i=!1){const n=e.width>e.height,c=ks({},e);return e.width*e.height<=19200&&cC&&lD&&(this.log.warn(`${i?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),c.width=n?240:180,c.height=n?180:240,c.bitrate=Math.max(e.bitrate,150)),e.width*e.height>921600&&WIA&&(c.width=n?1280:720,c.height=n?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),KIA(TQ,"14.3")&&S$(TQ,"14.0",!0)&&this.on("7",()=>{const I=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=I?640:480,this.profile.height=I?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>230400&&(this.profile.width=I?640:360,this.profile.height=I?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!i&&this.avoidCropping&&(lD||aC)&&!XIA()&&e.width*e.height<=230400&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,c.width=1280,c.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),c}stopSmall(){var e,i;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(i=this.room)==null||i.enableSmall(!1))}listenDeviceChange(){SQ&&!SQ.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&SQ.on("videoInputRemoved",this.handleCameraRemoved,this)}async handleCameraRemoved(e){if(e.deviceId===this.deviceId){let i=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${CAA[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){pc(this.userId,{eventId:2003,param1:7,streamType:2});const n=await bM();n[0]?this.recapture(n[0].deviceId):i=!0}i&&SQ.on("videoInputAdded",this.handleCameraAdded,this)}}async handleCameraAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(SQ.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))}encodeFrame(e,i){if(!this.manager)return e;const n=i?8:this.mediaType;return this.manager.encodePipeline.reduceRight((c,I)=>I?I({frame:c,mediaType:n}):c,e)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(e=>e)}play(e,i){return sr(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,i)}close(){SQ.off("videoInputAdded",this.handleCameraAdded,this),SQ.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}async recapture(e){try{await super.recapture(e)}catch(i){const n=(await bM()).find(c=>c.deviceId!==e);if(!n)throw i;await super.recapture(n.deviceId)}}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||sr(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};yc([rAA(function(e){this.setContentHint(e.contentHint||"motion")})],zV.prototype,"capture");var odA=[-1,-1,1,-1,-1,1,1,1],ndA=[0,0,1,0,0,1,1,1],ZL=class TW extends nr{constructor(i,n){if(super(),this.context=i,pe(this,"name"),pe(this,"input"),pe(this,"output"),pe(this,"texture"),pe(this,"ctx2d",null),pe(this,"fbo"),pe(this,"width",0),pe(this,"height",0),pe(this,"x",0),pe(this,"y",0),pe(this,"program"),pe(this,"vertexShader"),pe(this,"fragmentShader"),pe(this,"totalFrames",0),pe(this,"dropFrames",0),pe(this,"matchInputSize",!0),pe(this,"texCoordBuffer"),pe(this,"positionBuffer"),pe(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),pe(this,"cost",0),pe(this,"_canvas",null),pe(this,"_image"),pe(this,"log"),this.context.on("disconnect",this.close,this),this.name=n.name,this.log=n.logger,this.matchInputSize=n.matchInputSize!==!1,this.width=n.width||i.width,this.height=n.height||i.height,this._image=n.image,i instanceof VU)i.ctx&&n.create2d&&(typeof OffscreenCanvas=="function"&&VM!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);else try{const c=i.ctx;this.texCoordBuffer=this.createBuffer(ndA),this.positionBuffer=this.createBuffer(odA),n.createTexture!==!1&&(this.texture=c.createTexture(),this.useTexture(),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,c.LINEAR),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MAG_FILTER,c.LINEAR),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),c.pixelStorei(c.UNPACK_ALIGNMENT,1)),n.useFbo&&(this.fbo=c.createFramebuffer(),this.useBufferFrame(),this.useTexture(),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,this.width,this.height,0,c.RGBA,c.UNSIGNED_BYTE,null),c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,this.texture,0)),n.useDefaultProgram?this.program=i.defaultProgam:(n.vertexShaderSource||n.fragmentShaderSource)&&(this.vertexShader=n.vertexShaderSource?i.createShader(c.VERTEX_SHADER,n.vertexShaderSource):i.defaultVShader,this.fragmentShader=n.fragmentShaderSource?i.createShader(c.FRAGMENT_SHADER,n.fragmentShaderSource):i.defaultFShader,this.program=i.createProgram(this.vertexShader,this.fragmentShader))}catch(c){this.context.destroy(new vl({code:Zg.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${c.message||c}`}))}}get image(){return this._image}set image(i){this._image=i}createFramebuffer(i){const n=this.context.ctx,c=n.createFramebuffer();return n.bindFramebuffer(n.FRAMEBUFFER,c),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,i,0),c}connect(i,...n){return i.addInput(this,...n),this.output=i,i}addInput(i,...n){this.input=i,this.matchInputSize&&i.width&&i.height&&this.resize(i.width,i.height)}requestFrame(i){const n=Date.now();return!!(this.context instanceof NW&&this.render(i)||this.context instanceof VU&&this.render2d(i))&&(this.totalFrames++,this.cost=Date.now()-n,!0)}render2d(i){var n;return!!((n=this.input)!=null&&n.requestFrame(i))&&this.draw2d(this.input.image,0,0,this.width,this.height)}update(i=0){var n;(n=this.output)==null||n.update(i)}disconnect(...i){var n;(n=this.output)==null||n.removeInput(this,...i),delete this.output}removeInput(i,...n){delete this.input}close(){var i,n;if(this.context.off("disconnect",this.close,this),(i=this.output)==null||i.removeInput(this),delete this.output,(n=this.input)==null||n.disconnect(),this.context instanceof NW){const c=this.context.ctx;c.deleteBuffer(this.texCoordBuffer),c.deleteBuffer(this.positionBuffer),this.fbo&&c.deleteFramebuffer(this.fbo),this.texture&&c.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&c.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&c.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&c.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var i;this.useTextures((i=this.input)==null?void 0:i.texture)}useTextures(...i){const n=this.context.ctx;i.forEach((c,I)=>{c&&(n.activeTexture(n.TEXTURE0+I),n.bindTexture(n.TEXTURE_2D,c))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){const i=this.context.ctx;i.bindFramebuffer(i.FRAMEBUFFER,this.fbo||null)}createBuffer(i){const n=this.context.ctx,c=n.createBuffer();return n.bindBuffer(n.ARRAY_BUFFER,c),n.bufferData(n.ARRAY_BUFFER,new Float32Array(i),n.STATIC_DRAW),c}setTexBuffer(i){const n=this.context.ctx;n.bindBuffer(n.ARRAY_BUFFER,this.texCoordBuffer),n.bufferData(n.ARRAY_BUFFER,new Float32Array(i),n.STATIC_DRAW)}setPosBuffer(i){const n=this.context.ctx;n.bindBuffer(n.ARRAY_BUFFER,this.positionBuffer),n.bufferData(n.ARRAY_BUFFER,new Float32Array(i),n.STATIC_DRAW)}changeBufferData(i,n){const c=this.context.ctx;c.bindBuffer(c.ARRAY_BUFFER,i),c.bufferData(c.ARRAY_BUFFER,new Float32Array(n),c.STATIC_DRAW)}setAttributes(...i){const n=this.context.ctx;i.forEach((c,I)=>{n.enableVertexAttribArray(I),n.bindBuffer(n.ARRAY_BUFFER,c),n.vertexAttribPointer(I,2,n.FLOAT,!1,0,0)})}getVertexPoint(i,n){return[i/this.width*2-1,n/this.height*2-1]}layout2texCoords(i){return[...this.getVertexPoint(i.x,i.y),...this.getVertexPoint(i.x+i.width,i.y),...this.getVertexPoint(i.x,i.y+i.height),...this.getVertexPoint(i.x+i.width,i.y+i.height)]}resize(i,n){if(this.width!==i||this.height!==n){if(this.width=i,this.height=n,this._canvas&&(this._canvas.width=i,this._canvas.height=n),this.texture&&this.fbo){this.useTexture();const c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,i,n,0,c.RGBA,c.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(i,n)}}draw(i,n){this.setAttributes(i||this.positionBuffer,n||this.texCoordBuffer);const c=this.context.ctx;c.drawArrays(c.TRIANGLE_STRIP,0,4)}draw2d(i,n,c,I,C,m,R,_,T){const b=!(sr(m)||sr(R)||sr(_)||sr(T));return!(!this.ctx2d||!i)&&(i instanceof ImageData?(b?this.ctx2d.putImageData(i,n,c,m,R,_,T):this.ctx2d.putImageData(i,n,c),this.emit(TW.RENDER,this.ctx2d.canvas)):(b?this.ctx2d.drawImage(i,m,R,_,T,n,c,I,C):this.ctx2d.drawImage(i,n,c,I,C),this.emit(TW.RENDER,i)),typeof VideoFrame<"u"&&i instanceof VideoFrame&&i.close(),!0)}drawBackGround2d(i){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=i,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var i;const{totalFrames:n,x:c,y:I,width:C,height:m,name:R,cost:_}=this,T=Date.now(),b=(n-this.lastInfo.totalFrames)/((T-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:n,x:c,y:I,width:C,height:m,timestamp:T,fps:b,name:R,cost:_},ks({parent:(i=this.input)==null?void 0:i.getInfo()},this.lastInfo)}createTexture(i){const n=this.context.ctx,c=n.createTexture();return this.useTextures(c),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.pixelStorei(n.UNPACK_ALIGNMENT,1),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,i),c}};pe(ZL,"RENDER","render"),yc([Ru(nr.INIT,"connected",{sync:!0})],ZL.prototype,"connect"),yc([Ru("connected",nr.INIT,{ignoreError:!0,sync:!0})],ZL.prototype,"disconnect"),yc([Ru([],"closed",{sync:!0})],ZL.prototype,"close");var oV=ZL,sdA=ih(YEA(250),IAA(()=>performance.now()),gAA()),rdA=e=>i=>{const n=performance.now();ih(sdA,zEA(c=>c-n{if(e!==this.context.frameRate&&(RQ.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof NW){const i=this.context.ctx.getError();i&&this.context.destroy(new vl({code:Zg.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${i}`}))}},{fps:this.context.frameRate})}render(e){var i;return!!((i=this.input)!=null&&i.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(oV.RENDER,this.context._canvas),!0)}addInput(e,...i){super.addInput(e,...i),this.start(this.context.frameRate)}update(e=0){this.state!=="closed"&&(this._intervalId&&(RQ.clearTask(this._intervalId),this._intervalId=0,e===1&&(this.log.info(`${this.name} use requestVideoFrameCallback`),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(e){super.removeInput(e),RQ.clearTask(this._intervalId)}resize(e,i){super.resize(e,i),this.context.setSize(e,i)}close(){super.close(),RQ.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},cdA=class extends gdA{constructor(e,i){super(e,i),pe(this,"_videoTrack"),pe(this,"_muteOb"),pe(this,"_closedOb",DE(this,"closed")),pe(this,"_subscription"),pe(this,"_canvasContainer"),Number(aF)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=DE(this._videoTrack,"mute"),ih(DE(this._videoTrack,"ended"),mT(this._closedOb),HM(()=>{this.context.destroy(new vl({code:Zg.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=ih(this._muteOb,mT(this._closedOb),dAA(rdA(5e3)),gT(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),HM(()=>{this.context.destroy(new vl({code:Zg.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){this.context._canvas&&this._canvasContainer&&(document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas)))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,i;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(i=this._canvasContainer)==null||i.remove()}},hAA=class extends oV{constructor(e,i){super(e,ks({name:"imageSource"},i)),pe(this,"_lastImage"),pe(this,"_totalFrames",0),pe(this,"_autoResize",!1),pe(this,"_canvasRendered"),pe(this,"videoCallbackId",0),pe(this,"waitingFirstFrame",!0),pe(this,"shouldUpdate",!0),this._autoResize=i?.autoResize!==!1,VM===16&&(this._canvasRendered=lAA(),ih(this._canvasRendered,xEA(this._image),AdA(n=>n instanceof HTMLCanvasElement?DE(n,"rendered"):HEA()),mT(DE(this,"closed")),HM(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;const e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),$4()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback((i,n)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=n.presentedFrames,this.update(1))}))}_render(e,i){var n;let{width:c,height:I}=this;const{image:C}=this;if(C instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:c,videoHeight:I}=C,!c||!I)return!1;C.width=c,C.height=I}else if(C instanceof HTMLImageElement||C instanceof ImageData||C instanceof ImageBitmap){if({width:c,height:I}=C,C!==this._lastImage)this._lastImage=C;else if(c===this.width&&I===this.height)return!0}else C instanceof HTMLCanvasElement||C instanceof OffscreenCanvas?({width:c,height:I}=C,this._lastImage=C):typeof VideoFrame<"u"&&C instanceof VideoFrame&&({displayWidth:c,displayHeight:I}=C,(n=this._lastImage)==null||n.close(),this._lastImage=C);if(!this._autoResize)return!0;if(this.width===c&&this.height===I&&this.totalFrames){if(i){this.useTexture();const m=this.context.ctx;m.texSubImage2D(m.TEXTURE_2D,0,0,0,m.RGBA,m.UNSIGNED_BYTE,C)}}else{if(i){this.useTexture();const m=this.context.ctx;m.texImage2D(m.TEXTURE_2D,0,m.RGBA,m.RGBA,m.UNSIGNED_BYTE,C)}this.resize(c,I)}return!0}get image(){return this._image}set image(e){var i;(i=this._canvasRendered)==null||i.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},BAA=class extends hAA{constructor(e,i,n){super(e,n),this._player=i,this.name="videoPlayerSource",ih(DE(this._player,zs.PLAYER_STATE_CHANGED),mT(DE(this,"closed")),gT(({state:c})=>c==="PLAYING"),HM(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},ldA=class extends BAA{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(e,i,n){super(e,new Ky({id:n.name,track:i,muted:!0,container:null,objectFit:"contain",log:n.logger}),n),this.name="videoTrackSource",this._player.play()}replaceTrack(e){this.waitingFirstFrame=!0,this._player.setTrack(e),this._player.play()}close(){super.close(),this._player.stop()}},IdA=class extends oV{constructor(e,i,n){super(e,cB(ks({name:"textSource"},n),{create2d:!0})),pe(this,"hasChange",!0),pe(this,"content",""),this.ctx2d.textBaseline="top",this.content=i.content||"",i.font&&(this.font=i.font),i.color&&(this.color=i.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return((e=this.ctx2d)==null?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return((e=this.ctx2d)==null?void 0:e.fillStyle)||""}render2d(e){return!(!this.ctx2d||!this.hasChange)&&(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0)}render(e){return!1}resize(e,i){if(!this.ctx2d)return;const{color:n,font:c}=this;super.resize(e,i),this.color=n,this.font=c}drawMultilineText(e=0,i=0,n=1.2){if(!this.ctx2d)return;const c=this.ctx2d.measureText(this.content);i+=c.fontBoundingBoxAscent||c.actualBoundingBoxAscent||0;const I=this.font.match(/(\d+)px/),C=(I?parseInt(I[1],10):16)*n,m=this.content.split(` + `,n.onclick=this.onQuestionClick.bind(this);const c=document.createElement("div");c.className=_3,c.innerText=iD()?"详情 >":"Detail >",c.onclick=this.onCollapseClick.bind(this);const I=e.content.firstChild,C=I.querySelector(`.${nY}`);return C.appendChild(c),C.appendChild(n),C.appendChild(i),I}addDiaLog(){OU()||(RW=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${LL}`).onclick=e=>e.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",An.info("show autoplay dialog"),ah.uploadEvent({log:juA}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,RW=!1),PU=null}onConfirm(){An.warn("confirm clicked, try resume stream"),Rn.emit(Rs.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){const e=this._dialogNode.querySelector(`.${d6}`);e.style.visibility=this._showDetail?"hidden":"visible",e.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||ah.uploadEvent({log:WuA}),this._isCollapseClicked=!0}onQuestionClick(){window.open(oAA,"_blank"),this._isQuestionClicked||ah.uploadEvent({log:zuA}),this._isQuestionClicked=!0}},PU=null;function $uA(){PU||(PU=new XuA)}function AEA(){PU&&PU.deleteDialog()}var fU,Ky=class extends pM{constructor(e){super(e,ni.VIDEO),pe(this,"stat",{}),pe(this,"_calculateTimeout",-1),pe(this,"viewMirror",!1),pe(this,"objectFit","cover"),pe(this,"container"),pe(this,"canvas"),pe(this,"shouldRenderAlpha",!1),pe(this,"_preSize",{width:0,height:0}),pe(this,"posterImg"),pe(this,"pipWindow"),pe(this,"enterPIPPromise"),pe(this,"_originContainerPosition"),pe(this,"_isResettingSrcObject",!1),pe(this,"_wrapper",null),pe(this,"_useWrapper",!1),pe(this,"_isFirstFrameRenderEmitted",!1),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,sr(e.viewMirror)||(this.viewMirror=e.viewMirror),sr(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return this._state==="PLAYING"&&(!this.element||!this.element.paused)&&((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){const e=document.createElement(ni.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id",`video_${this.id}`),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,cC&&(e.poster="data:,"),this._appendToWrapper(),this.bindElementEvents(),this.calculateStat(),this._bindFirstFrameRenderEvent(e)}_bindFirstFrameRenderEvent(e){const i=()=>{if(this._isFirstFrameRenderEmitted)return;this._isFirstFrameRenderEmitted=!0;const n=e.videoWidth||0,c=e.videoHeight||0;this._log.info(`first frame render: ${n}x${c}`),this.emit(zs.FIRST_FRAME_RENDER,{width:n,height:c})};typeof e.requestVideoFrameCallback=="function"?e.requestVideoFrameCallback(i):e.addEventListener("loadeddata",i,{once:!0})}get styleAttribute(){let e=this._useWrapper?`grid-area:1/1;width:100%;height:100%;object-fit:${this.objectFit};${this.shouldRenderAlpha?"":"background-color:black"};`:`width:100%;height:100%;object-fit:${this.objectFit};${this.shouldRenderAlpha?"":"background-color:black"};`;return this.viewMirror&&(e+="transform:scaleX(-1);"),e}setLiveMode(e){if(this._useWrapper!==e&&(this._useWrapper=e,this.elementToRender&&this.elementToRender.setAttribute("style",this.styleAttribute),this.container&&this.elementToRender))if(e){const i=this._getOrCreateWrapper();i.insertBefore(this.elementToRender,i.firstChild)}else this.container.appendChild(this.elementToRender),this._cleanupWrapper()}setContainer(e){if(this.container===e)return;const i=this._wrapper,n=this.container;this.container=e,this._pausedRetryCount=V_,this.track&&this.elementToRender&&this._appendToWrapper(),i&&n&&n!==this.container&&i.isConnected&&i.children.length===0&&i.remove()}_getOrCreateWrapper(){if(!this.container)throw new Error("[VideoPlayer] container is required");let e=this.container.querySelector("[data-trtc-video-wrapper]");return e||(e=document.createElement("div"),e.setAttribute("data-trtc-video-wrapper","true"),e.style.cssText="display:grid;width:100%;height:100%;",this.container.appendChild(e)),this._wrapper=e,e}_appendToWrapper(e){const i=e??this.elementToRender;if(this.container&&i)if(this._useWrapper){const n=this._getOrCreateWrapper();n.insertBefore(i,n.firstChild)}else this.container.appendChild(i)}bindElementEvents(){const e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),this.handleFullscreenChange=this.handleFullscreenChange.bind(this),this.handleVolumeChange=this.handleVolumeChange.bind(this),e&&e.add(ni.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(ni.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(ni.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener(ni.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.addEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.addEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.addEventListener("volumechange",this.handleVolumeChange))}handleTrackEvent(e){var i;return e.type===ni.MUTE&&((i=this.stat)!=null&&i.fps&&(this.stat.fps=0),this.isFullscreen()&&this.resetSrcObjectToReplay()),super.handleTrackEvent(e)}handleFullscreenChange(){this.isFullscreen()?(this._log.info("enter fullscreen"),this.emit(zs.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(zs.LEAVE_FULL_SCREEN))}handleVolumeChange(){var e;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(zs.VOLUME_CHANGE,{muted:(e=this.element)==null?void 0:e.muted})}handleElementEvent(e){var i,n,c,I,C,m;if(this.mode===2)return;super.handleElementEvent(e);const R=e.type,_=this.isPictureInPicture(),T=this.isFullscreen(),b=e.isTrusted&&(_&&ud||T);if(R===ni.PLAYING&&b&&!this._isResettingSrcObject&&(this._log.warn("user resume in "+(T?"fullscreen":"pip")),this.emit(zs.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),R===ni.PAUSE&&(b&&(this._log.warn("user pause in "+(T?"fullscreen":"pip")),this.emit(zs.USER_PAUSE_IN_PIP_OR_FULL_SCREEN)),this.container&&!this.container.isConnected&&(this._log.warn(`${this.kind} player has been remove, element ID: ${this.container.id}`),QT(500).then(()=>{var J;(J=this.container)!=null&&J.isConnected&&(this._pausedRetryCount=V_,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!OU()&&!this.isPausedByUserCall&&!b&&(this._log.info(`[${V_-this._pausedRetryCount+1}/${V_}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),_u&&!b&&(this._interval=RQ.run("timeout",()=>{this.element&&this._state==="PAUSED"&&!this.isPausedByUserCall&&this.doResume()},{delay:3e3})),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){const J=this.element.style.transform;R===ni.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=J.replace("scaleX(-1)",""):R!==ni.LEAVE_PICTURE_IN_PICTURE||J.includes("scaleX")||(this.element.style.transform=`${J} scaleX(-1)`)}R===ni.RESIZE&&(this._preSize.height===((i=this.element)==null?void 0:i.videoHeight)&&this._preSize.width===((n=this.element)==null?void 0:n.videoWidth)||(this._log.info(`video size changed to ${(c=this.element)==null?void 0:c.videoWidth}x${(I=this.element)==null?void 0:I.videoHeight}`),this._preSize.height=((C=this.element)==null?void 0:C.videoHeight)||0,this._preSize.width=((m=this.element)==null?void 0:m.videoWidth)||0,this.emit(zs.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))),R===ni.LEAVE_PICTURE_IN_PICTURE&&(this._log.warn("exit pip"),this.isPaused&&!this.isPausedByUserCall&&(this._log.warn("resume after exit pip"),this.doResume()),this.resetSrcObjectToReplay(),this.emit(zs.LEAVE_PICTURE_IN_PICTURE)),R===ni.ENTER_PICTURE_IN_PICTURE&&this.emit(zs.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){cC&&D3&&this.isPlayCalled&&this.element&&this.track&&!this.isPausedByUserCall&&(this._log.warn("reset srcObject to replay for android chromium"),this._isResettingSrcObject=!0,this.element.srcObject=new MediaStream([this.track]),this.element.play().catch(e=>{this._log.warn("play failed after reset srcObject",e)}).finally(()=>{this._isResettingSrcObject=!1}))}setCanvas(e,i=1){var n,c;this.canvas!==e&&((n=this.canvas)==null||n.remove(),e?.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?i:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((c=this.element)==null||c.remove(),this._appendToWrapper(e)):this.element&&this._appendToWrapper(this.element))}setAttr(e){const i=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);i.style=Object.assign({width:"100%",height:"100%"},i.style),super.setAttr(i)}get mirror(){return this.viewMirror}setRect(e,i){this.elementToRender&&(this.elementToRender.style.width=`${e}px`,this.elementToRender.style.height=`${i}px`)}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit=`${e}`),this.objectFit=e}setPoster(e,i=!1){return new Promise(n=>{if(!this.element||(this._log.info("setPoster",e.slice(0,10)),e===""?this.element.removeAttribute("poster"):this.element.poster=e,!(i&&(ud||aC))))return n();if(e==="")return this.removePosterImg(),n();if(this.posterImg)return n();const c=document.createElement("img");c.src=e;const I=window.getComputedStyle(this.element),C=I.objectFit||this.objectFit;let m=1;if(this._useWrapper){const R=parseInt(I.zIndex,10);isNaN(R)||(m=R+1)}c.style.cssText=this._useWrapper?`grid-area:1/1;z-index:${m};width:100%;height:100%;object-fit:${C};`:`position:absolute;top:0;left:0;width:100%;height:100%;object-fit:${C};`,c.onload=async()=>{try{c.decode&&await c.decode(),this.container&&!this._useWrapper&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=c;const R=this._useWrapper?this._wrapper:this.container;R?.appendChild(c),WY()&&VM<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(R){this._log.warn("decode poster image error",R)}return n()},c.onerror=()=>(this._log.warn("load poster image error"),n())})}removePosterImg(){this.posterImg&&(WY()&&VM<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),this._useWrapper||!this.container||sr(this._originContainerPosition)||this.container.style.position!=="relative"||(this.container.style.position=this._originContainerPosition),delete this.posterImg)}get hasPoster(){var e;return!!this.posterImg||!!((e=this.element)!=null&&e.getAttribute("poster"))}async pause(e=!0){super.pause(),this.isPictureInPicture()||this.hasPoster||!(D3||e&&(aC||ud))||await this.setPoster(this.getVideoFrame(),!0)}resume(e=!1){return super.resume(e).then(()=>{var i;(this.posterImg||(i=this.element)!=null&&i.poster)&&this.setPoster("",!0)})}doResume(e=!1){return this.isPaused&&e&&this.element&&this.track&&D3&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(e=0){var i;this.isPictureInPicture()&&this.exitPictureInPicture().catch(n=>{}),this.isFullscreen()&&this.exitFullscreen().catch(n=>{}),this.element&&(this.element.removeEventListener(ni.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.removeEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.removeEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.removeEventListener("volumechange",this.handleVolumeChange)),this._isFirstFrameRenderEmitted=!1,super.stop(e),(i=this.canvas)==null||i.remove(),this.removePosterImg(),this._useWrapper&&this._cleanupWrapper()}_cleanupWrapper(){this._wrapper&&this._wrapper.children.length===0&&this._wrapper.remove(),this._wrapper=null}play(e){if(sr(e?.isLiveStream)||this.setLiveMode(e.isLiveStream),this.element){if(this.elementToRender&&this.container)if(this._useWrapper){const i=this._getOrCreateWrapper();this.elementToRender.parentElement!==i&&i.insertBefore(this.elementToRender,i.firstChild)}else this.elementToRender.parentElement!==this.container&&this.container.append(this.elementToRender)}else this.initializeElement();return this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(zs.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this._appendToWrapper()))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";const e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if($4()&&this.element&&this._calculateTimeout<0){let e=0,i=null;const n=(c,I)=>{this.stat.width=I.width,this.stat.height=I.height,i&&(this.stat.fps=Math.round((I.presentedFrames-i.presentedFrames)/(c-e)*1e3)),e=c,i=I,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var C;return(C=this.element)==null?void 0:C.requestVideoFrameCallback(n)},2e3))};this.element.requestVideoFrameCallback(n)}}catch(e){this._log.warn("init stat failed",e)}}async enterFullscreen(){const e=this.elementToRender;if(!e)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");if(_u&&this.isPictureInPicture()){this._log.info("exit pip before entering fullscreen");try{await this.exitPictureInPicture()}catch(i){this._log.warn("exit pip failed before fullscreen:",i)}}try{if(e.requestFullscreen)await e.requestFullscreen();else if(e.webkitRequestFullscreen)await e.webkitRequestFullscreen();else if(e.webkitEnterFullscreen)await e.webkitEnterFullscreen();else if(e.mozRequestFullScreen)await e.mozRequestFullScreen();else{if(!e.msRequestFullscreen)throw new Error("Fullscreen API not supported");await e.msRequestFullscreen()}this._log.info("entered fullscreen mode")}catch(i){throw this._log.error("failed to enter fullscreen:",i),i}}async exitFullscreen(){try{if(!this.isFullscreen())return;if(document.exitFullscreen)await document.exitFullscreen();else if(document.webkitExitFullscreen)await document.webkitExitFullscreen();else if(document.mozCancelFullScreen)await document.mozCancelFullScreen();else{if(!document.msExitFullscreen)throw new Error("Exit fullscreen API not supported");await document.msExitFullscreen()}this._log.info("exited fullscreen mode")}catch(e){throw this._log.error("failed to exit fullscreen:",e),e}}isFullscreen(){const e=this.elementToRender;return e?this.element&&this.element.webkitDisplayingFullscreen?!this.isPictureInPicture():(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===e:!1}async toggleFullscreen(){this.isFullscreen()?await this.exitFullscreen():await this.enterFullscreen()}async enterPictureInPicture(){this.enterPIPPromise=this._enterPictureInPicture();try{return await this.enterPIPPromise}finally{delete this.enterPIPPromise}}async _enterPictureInPicture(){try{if(!this.element)throw new Error("No video element available for pip");if(this.canvas&&this.mode!==1)throw new Error("pip is not supported for canvas-only mode");const{element:e}=this;if(e.requestPictureInPicture){this._log.info("requestPictureInPicture");const i=await e.requestPictureInPicture();return this.pipWindow=i,this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),this._appendToWrapper(this.element)),i}if(e.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),await e.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered pip mode (webkit)"),{};throw new Error("pip API not supported")}catch(e){throw this._log.error("failed to enter pip:",e.name,e.message),e}}async exitPictureInPicture(){var e;try{if(!this.isPictureInPicture())return;if(delete this.pipWindow,document.pictureInPictureElement&&document.exitPictureInPicture)await document.exitPictureInPicture(),this.elementToRender===this.canvas&&((e=this.element)==null||e.remove(),this._pausedRetryCount=V_,this._appendToWrapper(this.canvas)),this._log.info("exited pip mode");else{if(!this.element||!this.element.webkitSetPresentationMode)throw new Error("Exit pip API not supported or not in PiP mode");await this.element.webkitSetPresentationMode("inline"),this._log.info("exited pip mode (webkit)")}}catch(i){throw this._log.error("failed to exit pip:",i),i}}isPictureInPicture(){if(!this.element)return!1;const{element:e}=this;return document.pictureInPictureElement?document.pictureInPictureElement===e:!!e.webkitPresentationMode&&e.webkitPresentationMode==="picture-in-picture"}async togglePictureInPicture(){this.isPictureInPicture()?await this.exitPictureInPicture():await this.enterPictureInPicture()}};async function eEA(e,i){if(!e.audioWorklet)return Promise.reject("audioWorklet is not supported");try{await e.audioWorklet.addModule(i),An.info("worklet addModule success")}catch(n){throw An.info(`worklet addModule catch error. ${n.message}`),n}}typeof AudioContext<"u"?fU=AudioContext:typeof webkitAudioContext<"u"?fU=webkitAudioContext:typeof mozAudioContext<"u"&&(fU=mozAudioContext);var Mu,tEA=1500,Q6=-1,rY=0,yU=-1,wW=!1,p6=0,m6=-1,f6=-1;function nAA(){try{if(Mu)return;(Mu=new fU({sampleRate:48e3})).onstatechange=()=>{An.info(`context state: ${Mu.state}${Mu.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),aT()},clearTimeout(Q6)}catch(e){An.error(`initAudioContext failed: ${e} typeof AudioContextClass: ${typeof fU}`),Q6=setTimeout(nAA,1e3)}}nAA();var aT=()=>{Mu.state==="suspended"?(rY=Wc(),iEA(),tV(),document.addEventListener("click",aT)):Mu.state==="interrupted"?tV():(rY&&(fr.addNumber({key:507800,value:Wc()-rY,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),rY=0),oEA(),document.removeEventListener("visibilitychange",aT),document.removeEventListener("click",aT))},T3=0,N3=-1;function tV(){return new Promise((e,i)=>{if(Mu.state==="running")return e();Date.now()-T3<1e3?(clearTimeout(N3),N3=setTimeout(()=>{T3=Date.now(),Mu.resume().then(e,i)},1e3)):(clearTimeout(N3),T3=Date.now(),Mu.resume().then(e,i))}).catch(e=>{An.warn(`context resume failed: ${e}`),document.addEventListener("visibilitychange",aT)})}function iEA(){yU===-1&&(yU=setTimeout(()=>{Mu.state==="suspended"&&(wW=!0,Rn.emit("155",{isSuspended:!0}))},tEA))}function oEA(){yU!==-1&&(clearTimeout(yU),yU=-1,wW&&(wW=!1,Rn.emit("155",{isSuspended:!1})))}function nEA(){if(!_u||f6!==-1)return;const e=()=>{Wc()-p6<500||(Mu&&Mu.state==="running"&&Mu.currentTime===m6&&(An.warn("context is fake running, auto resume"),Mu.suspend().catch(i=>{An.warn(`context suspend failed: ${i}`)})),m6=Mu.currentTime,p6=Wc())};f6=setInterval(()=>{e()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&e()})}document.addEventListener("click",aT);var uD=e=>Mu,GM=class{constructor(e){this.name=e,pe(this,"node"),pe(this,"node2"),pe(this,"pre",new Set),pe(this,"next",new Set),pe(this,"context"),pe(this,"connectedNodes",new Set),pe(this,"nextInputChannelMap",new Map),pe(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(e){this._channelCount=e,this.setChannelCount(this.node,e),this.setChannelCount(this.node2,e),this.next.forEach(i=>i.channelCount=e)}setChannelCount(e,i){!e||e instanceof ScriptProcessorNode||(e.channelCountMode="explicit",e.channelCount=i||this.channelCount||1)}setContext(e){this.context=e,this.node&&e.addMixWeight()}removeContext(){var e;this.node&&((e=this.context)==null||e.reduceMixWeight()),delete this.context}replaceNode(e){var i;if(e!==this.node)try{this.node?this._disconnect():(i=this.context)==null||i.addMixWeight(),this.node=e,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(n){An.error(n)}}setNode(e,i){var n;if(!this.node)try{(n=this.context)==null||n.addMixWeight(),this.node=e,this.setChannelCount(this.node),i&&(this.node2=i,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),fr.addSuccessEvent({key:502701})}catch(c){An.error(c),fr.addFailedEvent({key:502701,error:c})}}deleteNode(){var e;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(e=this.context)==null||e.reduceMixWeight(),this.preNodeReconnect(),fr.addSuccessEvent({key:502702})}catch(i){An.error(i),fr.addFailedEvent({key:502702,error:i})}}preNodeReconnect(){this.pre.forEach(e=>{e.node?e.reconnect():e.preNodeReconnect()})}connectNext(e){this.next.forEach(i=>{const n=this.nextInputChannelMap.get(i);e._connect(i.node,n)||i.connectNext(e)})}_connect(e,i=0){return!(!this.node||!e)&&((this.node2||this.node).connect(e,0,i),this.connectedNodes.add(e),!0)}_disconnect(){this.connectedNodes.forEach(e=>{var i;return(i=this.node2||this.node)==null?void 0:i.disconnect(e)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(e,i=0){return this.next.add(e),e.pre.add(this),this.nextInputChannelMap.set(e,i),e}},sEA=class extends GM{constructor(e=256){super(),this.fftSize=e,pe(this,"dataArray",new Uint8Array(0))}setNode(e){e.fftSize=this.fftSize,this.dataArray=new Uint8Array(e.frequencyBinCount),super.setNode(e)}getByteTimeDomainData(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var e;return(e=this.node)==null||e.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){const e=this.getByteTimeDomainData();let i=0,n=0,c=`M${i},${n}`;for(let I=0;Ithis.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(um.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=n=>{um.lastMessageTime=Date.now(),this._volume=n.data.volume||0,this._volumeDb=n.data.volumeDb||0,!i&&n.data.cacheLen&&n.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),ah.logFailedEvent({userId:this._log.userId,eventType:CU.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=uD("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{um.lastMessageTime=Date.now();const n=i.inputBuffer.getChannelData(0);let c=0;for(let I=0;I>2);e.copyTo(n,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:n},[n.buffer]),e.close()}}},cEA=MT(oF()),S6=e=>i=>i.deviceId===e,G3=class{constructor(e,i){pe(this,"kind"),pe(this,"type"),pe(this,"devices",[]),this.kind=e,this.type=i}update(e,i){const n=e.filter(c=>c.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);this.devices.length===1&&sAA(this.devices[0])||i&&(n.forEach(c=>{if(c.deviceId&&!this.devices.find(S6(c.deviceId))){const I=`${this.kind}${this.type}Added`;An.warn(`${I}: ${JSON.stringify(c)}`),i.emit(I,c)}}),this.devices.forEach(c=>{if(c.deviceId&&!n.find(S6(c.deviceId))){const I=`${this.kind}${this.type}Removed`;An.warn(`${I}: ${JSON.stringify(c)}`),i.emit(I,c)}})),this.devices=n}hasDevice(e){return!!this.devices.find(i=>i.deviceId===e)}},lEA=class extends cEA.EventEmitter{constructor(){super(),pe(this,"audioInputs",new G3(ni.AUDIO,"Input")),pe(this,"videoInputs",new G3(ni.VIDEO,"Input")),pe(this,"audioOutputs",new G3(ni.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||RQ.run("interval",()=>{this.update()},{delay:1e4}))}init(){_W().then(e=>{this.audioInputs.update(e),this.videoInputs.update(e),this.audioOutputs.update(e)})}async update(e=0){const i=await _W(e);return this.audioInputs.update(i,this),this.videoInputs.update(i,this),this.audioOutputs.update(i,this),this}hasBlueTooth(){var e;if(1e3*((e=uD())==null?void 0:e.outputLatency)>150)return!0;const i=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(n=>i.some(c=>n.label.toLowerCase().includes(c)))||this.audioInputs.devices.some(n=>i.some(c=>n.label.toLowerCase().includes(c)))}},SQ=_7||w7?null:new lEA;function sAA(e){return e.deviceId===e.groupId&&e.groupId===""}async function _W(e=0){if(KV()||!W4())return[];let i=await navigator.mediaDevices.enumerateDevices();if(e!==0){const n={audio:!1,video:!1};if(i.forEach(c=>{sAA(c)&&(c.kind===ni.AUDIO_INPUT?n.audio=!0:c.kind===ni.VIDEO_INPUT&&(n.video=!0))}),e===2&&(n.audio=!1),e===1&&(n.video=!1),n.audio||n.video){let c;try{c=await navigator.mediaDevices.getUserMedia(n),n.audio&&tV()}catch(I){An.debug("capture before getDevices failed: ",I)}i=await navigator.mediaDevices.enumerateDevices(),c?.getTracks().forEach(I=>I.stop())}}return i.map((n,c)=>{const I={kind:n.kind,deviceId:n.deviceId,groupId:n.groupId,label:n.label||`${n.kind}_${c}`};return n.deviceId.length>0&&i5.add(`${n.deviceId}_${n.kind}`),n.getCapabilities&&(I.getCapabilities=()=>n.getCapabilities()),I})}function xU(e=!1){return SQ.update(e?1:0).then(i=>i.audioInputs.devices)}function bM(e=!1){return SQ.update(e?2:0).then(i=>i.videoInputs.devices)}var v6=!1;async function IEA(){try{v6||(v6=!0,An.info(`speakers:${(await uEA()).map(e=>` ${e.deviceId.slice(0,8)}: ${e.label}`)}`))}catch{}}async function uEA(e=!1){return(_u||ud)&&(e=!1),SQ.update(e?1:0).then(i=>i.audioOutputs.devices)}var wY,i5=new Set;function EEA(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;const i=e.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;const n=`${(e?.getSettings()||{}).deviceId}_${ni.VIDEO_INPUT}`;return!!i5.has(n)}function dEA(e){if(e instanceof CanvasCaptureMediaStreamTrack||!(e instanceof MediaStreamTrack))return!1;const i=e.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("麦克风"))return!0;const n=`${(e?.getSettings()||{}).deviceId}_${ni.AUDIO_INPUT}`;return!!i5.has(n)}async function CEA(e,i){const n=(await xU()).find(c=>c.deviceId===G7);return!i&&n?.groupId===e||n?.groupId===e&&n.label===i}async function hEA({newDeviceId:e,oldDeviceId:i,oldGroupId:n,oldLabel:c,kind:I}){return e===i&&(I!==ni.AUDIO||e!==G7||await CEA(n,c))}var BEA=class extends rEA{constructor(e){super(),this.log=e,pe(this,"volumeMeter"),pe(this,"volumeMeterAfter3A"),pe(this,"volumeDestination"),pe(this,"analyser",new sEA),this.volumeMeter=new D6({log:this.log}),this.volumeMeterAfter3A=new D6({log:this.log}),this.volumeDestination=new GM,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},QEA=class extends pM{constructor(e){super(e,ni.AUDIO),pe(this,"_outputDeviceId"),pe(this,"_floatVolume",1),pe(this,"_destination"),pe(this,"pipeline"),pe(this,"volumeMeterMode","worklet"),pe(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new BEA(this._log)}setTrack(e){}get duration(){var e;return Math.floor(1e3*(((e=this.element)==null?void 0:e.duration)||0))}get currentTime(){var e;return Math.floor(1e3*(((e=this.element)==null?void 0:e.currentTime)||0))}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((TQ==="15.2"||TQ==="15.3"||TQ==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");this._log.info("audio player initializeElement");const i=wY||new Audio;i.setAttribute("autoplay","autoplay"),i.srcObject=this.getMediaStream(),i.muted=this.muted,this.url&&(i.crossOrigin="anonymous",i.src=this.url),this.element=i,this.setVolume(YM(e)?e/100:this._floatVolume),i===wY&&(wY=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(zs.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}async play(e){if(this.track||this.url){try{!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e?.volume),this._outputDeviceId&&await this.setSinkId(this._outputDeviceId),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(uD("player").createAnalyser()),IEA()}catch(i){throw this._log.warn(`audio play error: ${i}`),S$(TQ,"18.7",!0)&&this.bindAutoPlayEvent(),i}return super.play()}}stop(e=0){this.pipeline.destroy(),super.stop(e)}setVolume(e){this._floatVolume=e,this.element&&(this.element.volume=e)}async setSinkId(e){var i,n;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&await((n=(i=this.element).setSinkId)==null?void 0:n.call(i,e))}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},pEA=class extends QEA{constructor(e){super(e),pe(this,"_sourceElement"),pe(this,"_output",new GM),this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(uD().destination)}write(e){this.pipeline.volumeMeter.write(e)}setTrack(e){var i,n,c;((n=(i=this.element)==null?void 0:i.error)==null?void 0:n.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==e&&(this.unbindTrackEvents(),this.track=e,this.emit(zs.MEDIA_TRACK_CHANGED,e),e?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([e]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([e])),this.pipeline.source.channelCount=((c=e.getSettings())==null?void 0:c.channelCount)||1,this.pipeline.replaceSource(e)):this.pipeline.source.deleteNode())}setVolume(e){var i;const n=e<=1&&!WY();if(!(this._floatVolume===e&&(n&&((i=this.element)==null?void 0:i.volume)===e||!n&&this.pipeline.volume===e)))if(this._floatVolume=e,this.useDestination)this.pipeline.setVolume(e),this._log.info(`set pipeline volume: ${e}`);else if(n)this.element?(this._log.info(`set element volume: ${e}`),this.element.volume=e):this._log.info("set element volume: no element");else{if(WY()){if(!this.enableVolumeControlInIOS)return;nEA()}if(aC&&!this.pipeline.source.node)return void this._log.warn("set pipeline volume failed: no source node");this._log.info(`start set pipeline volume: ${e}`),this.pipeline.setVolume(e),this.element&&!this._sourceElement&&(this._destination||(this._destination=uD().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),FU(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(c=>{this.emit(zs.AUTOPLAY_FAILED,c)}))}}stop(e=0){this.pipeline.destroy();const i=this._sourceElement||this.element;i&&D$&&(wY=i),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(e)}},o5=class extends nr{constructor({userId:e,sdkAppId:i,mediaType:n,room:c,PlayerClass:I=n===1?pEA:Ky}){var C;super(),pe(this,"id",N$()),pe(this,"userId",""),pe(this,"isRemote"),pe(this,"mediaType"),pe(this,"room"),pe(this,"user"),pe(this,"_log"),pe(this,"_inputTrack"),pe(this,"_outputTrack"),pe(this,"isPlayCalled"),pe(this,"container",null),pe(this,"player"),pe(this,"subVideoPlayerMap"),pe(this,"muted",!1),pe(this,"abortCtrl"),pe(this,"objectFit","cover"),pe(this,"mirror"),pe(this,"rotation"),pe(this,"isScreen",!1),pe(this,"manager"),pe(this,"trackSettings"),pe(this,"isFirstVideoFrameEmitted",!1),this.userId=e||"",this.mediaType=n,this._log=An.createLogger({parent:c?.getLogger(),id:`${this.kind[0]}t`,userId:(C=c||this.room)==null?void 0:C.userId,remoteUserId:this instanceof vM?void 0:this.userId,sdkAppId:i,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof vM}),this.player=new I({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:c?.enableVolumeControlInIOS}),this.player.on(zs.PLAYER_STATE_CHANGED,m=>{if(Rn.emit(Rs.PLAYER_STATE_CHANGED,ks({track:this},m)),this.emit("player-state-changed",m),m.state==="PLAYING"&&this.room){let R=!0;for(const{remoteAudioTrack:_,remoteVideoTrack:T,remoteAuxiliaryTrack:b}of[...this.room.remotePublishedUserMap.values()])if(_.isAvailable&&!_.player.isPlaying||T.isAvailable&&!T.player.isPlaying||b.isAvailable&&!b.player.isPlaying){R=!1;break}R&&OU()&&AEA()}}),this.kind===ni.VIDEO&&(this.player.on(zs.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(zs.LOADED_DATA),Rn.emit(Rs.VIDEO_LOADED_DATA,{track:this})}),this.player.on(zs.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(zs.LOADED_META_DATA)}),this.player.on(zs.MEDIA_TRACK_CHANGED,m=>{var R;(R=this.subVideoPlayerMap)==null||R.forEach(_=>_.setTrack(m))}),this.player.on(zs.RESIZE,m=>{this.emitFirstVideoFrameEvent(zs.RESIZE),this.emit("video-size-changed",ks({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},m))}),this.player.on(zs.FIRST_FRAME_RENDER,m=>{this.emit("first-frame-render",cB(ks({},m),{streamType:this.streamType,userId:this.isRemote?this.userId:""}))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(zs.ERROR,this.onPlayerError.bind(this)),this.player.on(zs.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||An}get kind(){return this.mediaType===1?ni.AUDIO:ni.VIDEO}get isAudio(){return this.kind===ni.AUDIO}get strMediaType(){return this.mediaType===4?ni.VIDEO:this.mediaType===2?ni.SCREEN:ni.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}async play(e,i){const n=oh(e)?e[0]:e;if(this.isPlayCalled)return this.log.info(`play update options: ${JSON.stringify(i)}`),i&&!sr(i.muted)&&this.setPlayerMute(i.muted),i&&!sr(i.objectFit)&&(this.objectFit=i.objectFit),void(this.player instanceof Ky&&(this.player.setObjectFit(this.objectFit),this.container!==n&&n&&(oh(e)&&e.length>=1&&this.container&&e.includes(this.container)&&this.container.contains(this.player.elementToRender)?(e.splice(e.indexOf(this.container),1),e.unshift(this.container)):(this.container=n,this.player.setContainer(n))),oh(e)&&e.length>=1&&await this.playSubContainer(e.slice(1),i)));if(i&&!sr(i.muted)?this.setPlayerMute(i.muted):this.isRemote&&this.kind!==ni.VIDEO||this.setPlayerMute(!0),i&&!sr(i.objectFit)&&(this.objectFit=i.objectFit),this.player instanceof Ky&&(sr(i?.isLiveStream)||this.player.setLiveMode(i.isLiveStream),this.player.setObjectFit(this.objectFit),i&&!sr(i.poster)&&this.player.setPoster(i.poster)),this.isPlayCalled=!0,n&&(this.container=n,this.player instanceof Ky&&this.player.setContainer(n)),Rn.emit(Rs.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info(`play with options: ${JSON.stringify(i)}`);try{this.player.setTrack(this.playerMediaTrack),await this.player.play(i),oh(e)&&e.length>1&&await this.playSubContainer(e.slice(1),i)}catch(c){throw this.handleAutoPlayFailed(c),c}}else this.log.info("play has not mediaTrack, abort")}setMirror(e,i){if(this.isScreen||this.kind!==ni.VIDEO||sr(e)||e===this.mirror)return;this.mirror=e;let n=this.player;i&&(n=i);const c=this.manager;if(TM(this.mirror))return n.setViewMirror(this.mirror),void(!this.isRemote&&c&&(c.mirror=!1));switch(this.mirror){case"view":c&&(c.mirror=!1),n.setViewMirror(!0);break;case"publish":c&&(c.mirror=!0),n.setViewMirror(!0);break;case"both":c&&(c.mirror=!0),n.setViewMirror(!1)}}async playSubContainer(e,i){if(!this._outputTrack||this.kind===ni.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((c,I)=>{var C;e.find(m=>I===m)||(c.stop(),(C=this.subVideoPlayerMap)==null||C.delete(I))});for(const[c,I]of e.entries()){const C=this.subVideoPlayerMap.get(I);C?i&&(sr(i.objectFit)||C.setObjectFit(i.objectFit)):this.subVideoPlayerMap.set(I,new Ky({id:this.userId||this.id,track:this.playerMediaTrack,container:I,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${c+1}`})}))}const n=[...this.subVideoPlayerMap.values()];for(const c of n)c.setViewMirror(this.player.mirror),await c.play()}setAudioOutput(e){return this.player.setSinkId(e)}setAudioVolume(e){this.player.setVolume(e)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var e;return((e=this.player)==null?void 0:e.getInternalAudioLevel())||0}stop(e=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(f3(this)&&!e?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(i=>{i.stop()}),this.container=null)}async resume(){var e;this.isPlayCalled&&await((e=this.player)==null?void 0:e.resume())}close(){this._toInitState(),this.log.info("close"),this.isPlayCalled&&this.stop(!0)}_toInitState(){}setMute(e){this.muted=e,this._inputTrack&&(this._inputTrack.enabled=!e),this._outputTrack&&(this._outputTrack.enabled=!e),this.emit(e?"mute":"unmute",this),Rn.emit(e?Rs.TRACK_MUTED:Rs.TRACK_UNMUTED,{track:this})}setPlayerMute(e){this.player.setMuted(e)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(e){e5(e,e).add(ni.MUTE,this.onTrackMuted).add(ni.UNMUTE,this.onTrackUnmuted).add(ni.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===ni.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){FU(e)}setInputMediaStreamTrack(e){var i;const n=this._inputTrack;if(e!==n)return this._inputTrack=e,this.trackSettings=(i=e.getSettings)==null?void 0:i.call(e),e.enabled=!this.muted,n&&this.uninstallTrackEvent(n),this.installTrackEvent(e),this.emit("input-media-track-changed",e||null,n||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(e)}setOutputMediaStreamTrack(e){var i;const n=this._outputTrack;this instanceof zV&&N4(n)||e!==n&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",e.label):this.log.info("setOutputMediaStreamTrack",(i=e.getSettings)==null?void 0:i.call(e).deviceId,e.label),this._outputTrack=e,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!e),this.emit("output-media-track-changed",e))}setMediaType(e){this.mediaType=e}updatePlayingState(e){var i,n;if(this.isPlayCalled){if(e){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch(c=>this.handleAutoPlayFailed(c)),void this.log.info(`playing state updated, play ${this.kind}`)}else if(!this.player.isStopped)return f3(this)&&this.isAudio&&((i=this.user)!=null&&i.muteState.hasAudio)&&((n=this.user)!=null&&n.muteState.audioMuted)?void 0:(this.player.stop(f3(this)?this.jitterBufferDelay:0),void this.log.info(`playing state updated, stop ${this.kind}`))}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${e} ${this.player.isStopped}`)}async handleAutoPlayFailed(e){var i;this.log.warn("handleAutoPlayFailed",e);const n=()=>{this.resume().then(()=>{document.removeEventListener("click",n,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((RT||rF)&&(await QT(100),(i=this.player)==null?void 0:i.isPlaying))return;$uA()}else document.addEventListener("click",n,!0);Rn.once(Rs.LOCAL_TRACK_CAPTURE_SUCCESS,({track:c})=>{c.kind==="audio"&&OU()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&n()}),this.emit("error",e)}getVideoFrame(){return this.player instanceof Ky?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(e){var i,n,c;if(this.isFirstVideoFrameEmitted)return;const I=(i=this.mediaTrack)==null?void 0:i.getSettings();let C=I?.width||((n=this.player.element)==null?void 0:n.videoWidth)||0,m=I?.height||((c=this.player.element)==null?void 0:c.videoHeight)||0;(e!==zs.RESIZE||C||m)&&(e!==zs.LOADED_META_DATA||C||m)&&(e!==zs.LOADED_DATA||C||m||this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,j7(this.rotation)&&([C,m]=[m,C]),this.emit("first-video-frame",{width:C,height:m,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};yc([Ru([],nr.INIT,{sync:!0})],o5.prototype,"_toInitState");var mEA=Object.prototype.hasOwnProperty;function fEA(e){if(e==null)return!0;if(typeof e=="boolean")return!1;if(typeof e=="number")return e===0;if(typeof e=="string"||typeof e=="function"||Array.isArray(e))return e.length===0;if(e instanceof Error)return e.message==="";if(BT(e))switch(Object.prototype.toString.call(e)){case"[object File]":case"[object Map]":case"[object Set]":return e.size===0;case"[object Object]":for(const i in e)if(mEA.call(e,i))return!1;return!0}return!1}var iV=fEA,yEA=async function(e){const i=SEA(e);An.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let n=[],c=[];const I=["label","deviceId","groupId"];if(i.audio&&(n=await xU(),An.info(`microphones: ${oD(n.map(C=>cB(ks({},C),{groupId:C.groupId.substring(0,8)})),{keysToInclude:I})}`)),i.video&&(c=await bM(),An.info(`cameras: ${oD(c,{keysToInclude:I})}`),!TM(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){const C=c.filter(m=>!m.label.includes("infrared")).find(m=>m.label.includes("facing front"));C&&(i.video.deviceId=C.deviceId,An.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{const C=await navigator.mediaDevices.getUserMedia(i);return K$&&C.getTracks().forEach(m=>{var R;const _=m.getCapabilities();An.info(`${m.kind} capabilities: ${oD(_,{keysToInclude:b7})}`),sr(e.echoCancellation)||((R=_.echoCancellation)==null?void 0:R.indexOf(e.echoCancellation))!==-1||An.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(_.echoCancellation)}], but received '${e.echoCancellation}'`)}),i.audio&&tV(),C}catch(C){let{message:m}=C;throw C.name==="NotFoundError"&&(e.video&&c&&c.length===0&&(m=AV({key:$Y.CAMERA_NOT_FOUND})),e.audio&&n&&n.length===0&&(m=AV({key:$Y.MICROPHONE_NOT_FOUND}))),new Ml({code:Zg.INITIALIZE_FAILED,name:C.name,message:m,constraint:C.constraint})}},DEA=G4({retryFunction:yEA,settings:{retries:3,timeout:500},onError:({error:e,retry:i,reject:n,retryFuncArgs:c,retriedCount:I})=>{const C=I+1;e.name==="NotReadableError"||e.name==="OverconstrainedError"||e.name==="AbortError"?(C===1?(c[0].video&&(c[0].maxResolution=!1,(!ud||c[0].width*c[0].height<=2073600)&&c[0].frameRate&&(c[0].frameRate=c[0].frameRate>10?10:5)),c[0].retryWhenExactFailed&&c[0].useExactDeviceId&&(c[0].useExactDeviceId=!1)):C===2?c[0].useDeviceIdOnly=!0:C!==3||c[0].useExactDeviceId||(c[0].useTrueAsConstraint=!0),i()):n(e),c[0].microphoneId&&M6(c[0].microphoneId,!1),c[0].cameraId&&M6(c[0].cameraId,!0)},onRetrying:e=>{An.warn(`getUserMedia NotReadableError observed, retrying [${e}/3]`)},onRetryFailed:e=>{ah.logFailedEvent({eventType:CU.GET_USER_MEDIA_RETRY,error:e})},onRetrySuccess:e=>{ah.logSuccessEvent({eventType:CU.GET_USER_MEDIA_RETRY}),ah.uploadEvent({log:`stat-${CU.GET_USER_MEDIA_RETRY}-success-${e}`})}});async function M6(e,i){const n=(i?await bM():await xU()).find(c=>c.deviceId===e);n&&_M(n.getCapabilities)&&An.warn(oD(n.getCapabilities(),{keysToInclude:b7}))}function SEA(e){return{audio:vEA(e),video:MEA(e)}}function vEA(e){if(!e.audio)return!1;if(e.useTrueAsConstraint)return!0;const i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:e.sampleRate};return!iV(e.microphoneId)&&(i.deviceId=e.useExactDeviceId?{exact:e.microphoneId}:e.microphoneId,e.useDeviceIdOnly)?i:(YM(e.channelCount)&&(i.channelCount=e.channelCount),(TM(e.echoCancellation)||e.echoCancellation==="remote-only"||e.echoCancellation==="all")&&(i.echoCancellation=e.echoCancellation),TM(e.noiseSuppression)&&!e.noiseSuppression&&(i.noiseSuppression=!1),TM(e.autoGainControl)&&!e.autoGainControl&&(i.autoGainControl=!1),!!iV(i)||i)}function MEA(e){if(!e.video)return!1;if(e.useTrueAsConstraint)return!0;const{maxResolution:i=!0}=e,n={};return e.cameraId?n.deviceId=e.useExactDeviceId?{exact:e.cameraId}:e.cameraId:e.facingMode&&(n.facingMode=e.facingMode),e.useDeviceIdOnly&&!iV(n)?n:(e.width&&(n.width={ideal:e.width},i&&!aC&&(n.width.max=e.width)),e.height&&(n.height={ideal:e.height},i&&!aC&&(n.height.max=e.height)),aC&&JV&&e.width&&e.height&&e.width*e.height<101376&&(n.width=e.width,n.height=e.height),e.frameRate&&(n.frameRate=e.frameRate),!!iV(n)||n)}var REA=DEA;function rAA(e){return WV((i,n)=>async function(...c){const I=await i.apply(this,c);return await e.call(this,...c),I})}function WV(e){return function(i,n,c){return c.value=e(c.value,n),c}}var wEA=(()=>{let e=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&An.info(`visibility change: ${document.visibilityState}`),e||(document.addEventListener("visibilitychange",()=>{An.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),e=!0)}})(),_EA=0,TEA=class{constructor(e){pe(this,"log"),pe(this,"isRunning",!1),pe(this,"queue",[]);let i="fq"+ ++_EA;e&&(i+=`|${e}`),this.log=An.createLogger({id:i})}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(e,i=!1){var n,c;const I=ks({},e),C=new Promise((m,R)=>{I.resolve=m,I.reject=R});return I.promise=C,i?this.length<=1?this.queue.push(I):(c=(n=this.lastQueueItem)==null?void 0:n.promise)==null||c.then(I.resolve,I.reject):this.queue.push(I),this.log.debug(`push ${this.length}`,e.funcName,e.args),this.isRunning||this.callNext(),C}shift(){const e=this.queue.shift();return this.log.debug(`shift ${this.length}`,e?.funcName,e?.args),e}callNext(){if(this.isRunning||this.length===0)return;const{fn:e,args:i,context:n,resolve:c,reject:I,funcName:C}=this.queue[0];this.log.debug("callNext",this.length,C,i),this.isRunning=!0,e.apply(n,i).then(c,I).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},R6=new WeakMap;function NEA(e=!1){return function(i,n,c){const I=c.value;return c.value=function(...C){const m=R6.get(this)||new TEA;return R6.set(this,m),m.push({fn:I,args:C,context:this,funcName:n},e)},c}}function aAA(e,i){return WV((n,c)=>function(...I){const C=e;try{const m=n.apply(this,I),R=Wc();return O7(m)?m.then(_=>(i?fr.addSuccessEvent({key:C,cost:Wc()-R}):fr.addSuccessEvent({key:C}),_)).catch(_=>{throw fr.addFailedEvent({key:C,error:_}),_}):(fr.addSuccessEvent({key:C}),m)}catch(m){throw fr.addFailedEvent({key:C,error:m}),m}})}function nI(...e){}var GEA=e=>e();function bEA(){this.dispose()}var kEA=()=>typeof __FASTRX_DEVTOOLS__<"u",LEA=1,pT=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(e){const i=new FEA(e,this,this.streamId++);return Sl.subscribe({id:this.id,end:!1},{nodeId:i.sourceId,streamId:i.id}),this(i),i}},n5=class{constructor(){this.defers=new Set,this.disposed=!1}next(e){}complete(){this.dispose()}error(e){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=nI,this.error=nI,this.next=nI,this.dispose=nI,this.subscribe=nI,this.doDefer()}subscribe(e){return e instanceof pT?e.subscribe(this):e(this),this}get bindSubscribe(){return e=>this.subscribe(e)}doDefer(){this.defers.forEach(GEA),this.defers.clear()}defer(e){this.defers.add(e)}removeDefer(e){this.defers.delete(e)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},IB=class extends n5{constructor(e){super(),this.sink=e,e.defer(this.bindDispose)}next(e){this.sink.next(e)}complete(){this.sink.complete()}error(e){this.sink.error(e)}},UEA=class extends n5{constructor(e,i=nI,n=nI,c=nI){if(super(),this._next=i,this._error=n,this._complete=c,this.then=nI,e instanceof pT){const I={toString:()=>"subscribe",id:0,source:e};this.defer(()=>{Sl.defer(I,0)}),Sl.create(I),Sl.pipe(I),this.sourceId=I.id,this.subscribe(e),Sl.subscribe({id:I.id,end:!0}),i==nI?this._next=C=>Sl.next(I,0,C):this.next=C=>{Sl.next(I,0,C),i(C)},c==nI?this._complete=()=>Sl.complete(I,0):this.complete=()=>{this.dispose(),Sl.complete(I,0),c()},n==nI?this._error=C=>Sl.complete(I,0,C):this.error=C=>{this.dispose(),Sl.complete(I,0,C),n(C)}}else this.subscribe(e)}next(e){this._next(e)}complete(){this.dispose(),this._complete()}error(e){this.dispose(),this._error(e)}};function ih(e,...i){return i.reduce((n,c)=>c(n),e)}function gC(e,i,n){if(kEA()){const c=Object.defineProperties(Object.setPrototypeOf(e,pT.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:n,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Sl.create(c);for(let I=0;I{if(c instanceof pT){const I=gC(C=>{const m=new e(C,...n);m.sourceId=I.id,m.subscribe(c)},i,arguments);return I.source=c,Sl.pipe(I),I}return I=>c(new e(I,...n))}}}function Fy(e,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:e,payload:i}})}var FEA=class extends IB{constructor(e,i,n){super(e),this.source=i,this.id=n,this.sourceId=e.sourceId,this.defer(()=>{Sl.defer(this.source,this.id)})}next(e){Sl.next(this.source,this.id,e),this.sink.next(e)}complete(){Sl.complete(this.source,this.id),this.sink.complete()}error(e){Sl.complete(this.source,this.id,e),this.sink.error(e)}},Sl={addSource(e,i){Fy("addSource",{id:e.id,name:e.toString(),source:{id:i.id,name:i.toString()}})},next(e,i,n){Fy("next",{id:e.id,streamId:i,data:n&&n.toString()})},subscribe({id:e,end:i},n){Fy("subscribe",{id:e,end:i,sink:{nodeId:n&&n.nodeId,streamId:n&&n.streamId}})},complete(e,i,n){Fy("complete",{id:e.id,streamId:i,err:n?n.toString():null})},defer(e,i){Fy("defer",{id:e.id,streamId:i})},pipe(e){Fy("pipe",{name:e.toString(),id:e.id,source:{id:e.source.id,name:e.source.toString()}})},update(e){Fy("update",{id:e.id,name:e.toString()})},create(e){e.id||(e.id=LEA++),Fy("create",{name:e.toString(),id:e.id})}},OEA=class extends n5{constructor(e){super(),this.source=e,this.sinks=new Set}add(e){e.defer(()=>this.remove(e)),this.sinks.add(e).size===1&&(this.reset(),this.subscribe(this.source))}remove(e){this.sinks.delete(e),this.sinks.size===0&&this.dispose()}next(e){this.sinks.forEach(i=>i.next(e))}complete(){this.sinks.forEach(e=>e.complete()),this.sinks.clear()}error(e){this.sinks.forEach(i=>i.error(e)),this.sinks.clear()}};function gAA(){return e=>{const i=new OEA(e);if(e instanceof pT){const n=gC(c=>{i.add(c)},"share",arguments);return i.sourceId=n.id,n.source=e,Sl.pipe(n),n}return gC(i.add.bind(i),"share",arguments)}}function cAA(...e){return gC(i=>{const n=new IB(i);let c=e.length;n.complete=()=>{--c===0&&i.complete()},e.forEach(n.bindSubscribe)},"merge",arguments)}function PEA(...e){return gC(i=>{const n=new Map;e.forEach(c=>{const I=new IB(i);n.set(c,I),I.complete=()=>{n.delete(c),n.size===0?i.complete():I.dispose()},I.next=C=>{n.delete(c),n.forEach(m=>m.dispose()),I.resetNext(),I.resetComplete(),I.next(C)}}),e.forEach(c=>n.get(c).subscribe(c))},"race",arguments)}function xEA(...e){return i=>gC((n,c=0,I=e.length)=>{for(;c{n.next=I=>c.next(I),n.complete=()=>c.complete(),n.error=I=>c.error(I),e&&c.subscribe(e)},"subject",i));return n.next=nI,n.complete=nI,n.error=nI,n}function YEA(e){return gC(i=>{let n=0;const c=setInterval(()=>i.next(n++),e);return i.defer(()=>{clearInterval(c)}),"interval"},"interval",arguments)}function VEA(e,i){return gC(n=>{let c=0;const I=setTimeout(()=>{n.removeDefer(C),n.next(c++),i||n.complete()},e),C=()=>clearTimeout(I);n.defer(C)},"timer",arguments)}function b3(e,i){return n=>{const c=I=>n.next(I);n.defer(()=>i(c)),e(c)}}function DE(e,i){if("on"in e&&"off"in e)return gC(b3(n=>e.on(i,n),n=>e.off(i,n)),"fromEvent",arguments);if("addListener"in e&&"removeListener"in e)return gC(b3(n=>e.addListener(i,n),n=>e.removeListener(i,n)),"fromEvent",arguments);if("addEventListener"in e)return gC(b3(n=>e.addEventListener(i,n),n=>e.removeEventListener(i,n)),"fromEvent",arguments);throw"target is not a EventDispachter"}function HEA(){return gC(e=>e.complete(),"empty",arguments)}var JEA=class extends IB{constructor(e,i,n){super(e),this.filter=i,this.thisArg=n}next(e){this.filter.call(this.thisArg,e)&&this.sink.next(e)}},gT=qM(JEA,"filter"),qEA=class extends IB{constructor(e,i){super(e),this.count=i}next(e){this.sink.next(e),--this.count===0&&(this.doDefer(),this.complete())}},KEA=qM(qEA,"take"),jEA=class extends IB{constructor(e,i){super(e);const n=new IB(e);n.next=()=>{n.doDefer(),e.complete()},n.complete=bEA,n.subscribe(i)}},mT=qM(jEA,"takeUntil"),WEA=class extends IB{constructor(e,i){super(e),this.f=i}next(e){this.f(e)||(this.next=super.next,this.next(e))}},zEA=qM(WEA,"skipWhile"),ZEA=class extends IB{constructor(e,i,n){super(e),this.mapper=i,this.thisArg=n}next(e){super.next(this.mapper.call(this.thisArg,e))}},IAA=qM(ZEA,"map"),XEA=class extends IB{constructor(e,i,n){super(e),this.data=i,this.context=n}next(e){const i=this.context.combineResults;i?this.sink.next(i(this.data,e)):this.sink.next(e)}tryComplete(){this.context.resetComplete(),this.dispose()}},$EA=class uAA extends IB{constructor(i,n,c){super(i),this.makeSource=n,this.combineResults=c,this.index=0}subInner(i,n){const c=this.currentSink=new n(this.sink,i,this);this.complete===uAA.prototype.complete&&(this.complete=this.tryComplete),c.complete=c.tryComplete,c.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},w6=class extends XEA{},EAA=class extends $EA{next(e){this.subInner(e,w6),this.next=i=>{this.currentSink.dispose(),this.subInner(i,w6)}}},AdA=qM(EAA,"switchMap");function edA(e){return(i,n)=>e(()=>i,n)}var dAA=edA(qM(EAA,"switchMapTo")),HM=(e=nI,i=nI,n=nI)=>c=>new UEA(c,e,i,n),CAA=(e=>(e[e.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",e[e.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",e))(CAA||{}),vM=class extends o5{constructor(e,i){super({mediaType:e,PlayerClass:i}),pe(this,"isRemote",!1),pe(this,"deviceId"),pe(this,"groupId",""),pe(this,"label",""),pe(this,"sourceTrack"),pe(this,"enableAutoSwitchWhenRecapturing",!0),pe(this,"_isRecapturing",!1),pe(this,"_lastRecaptureTime",0),pe(this,"_onMuteTimeoutId",-1),pe(this,"_encodeCheckTimeoutId",-1),pe(this,"recaptureMode",0),pe(this,"profile"),pe(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return!(!this.mediaTrack||this.sourceTrack===this.mediaTrack)}encodeFrame(e,i){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(ni.MUTE,this.onTrackMuted),e.addEventListener(ni.UNMUTE,this.onTrackUnmuted),e.addEventListener(ni.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===ni.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(ni.MUTE,this.onTrackMuted),e.removeEventListener(ni.UNMUTE,this.onTrackUnmuted),e.removeEventListener(ni.ENDED,this.onTrackEnded)}setStateToReady(){}async capture(e,i=!1){var n,c;const I=this.sourceTrack;try{const C=Wc();let m;Rn.emit(Rs.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(m=new MediaStream,m.addTrack(e.customSource)):(i||(n=this.sourceTrack)==null||n.stop(),m=await REA(e));const R=m.getTracks()[0];return await this.setInputMediaStreamTrack(R),e.customSource||(this.sourceTrack=R,this.updateDeviceIdInUse(),this.listenDeviceChange()),Rn.emit(Rs.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Wc()-C,profile:this.profile,room:(c=this.manager)==null?void 0:c.room}),m}catch(C){throw Rn.emit(Rs.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:C}),this.log.error(`getUserMedia error observed ${C}`),C}finally{i&&I?.stop()}}setOutputMediaStreamTrack(e){var i;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(i=this.room)==null?void 0:i.replaceTrack(this)}get hasFlag(){var e,i;const n=x7(((e=this.room)==null?void 0:e.localPublishFlag)||0,((i=this.room)==null?void 0:i.userId)||"");return this.mediaType===4&&n.hasVideo||this.mediaType===1&&n.hasAudio||this.mediaType===2&&n.hasAuxiliary}async publish(e,i){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),await i,this._checkPublishFlag(e)}_checkPublishFlag(e){return new Promise(async(i,n)=>{var c,I,C,m,R;const _=()=>n(new Ml({code:Zg.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?i():(this.state!==nr.INIT&&this.state!=="ready"||_(),ih(DE(e,"local-publish-flag-changed"),gT(()=>this.hasFlag),mT(cAA(DE(this,nr.INIT),DE(this,"ready"))),HM(i,n,_))),(C=(I=(c=this.room)==null?void 0:c.networkQuality)==null?void 0:I.hadRecentBadUplink)==null?void 0:C.call(I,2))return i();const T=e.heartbeatCount,b=((R=(m=this.mediaTrack)==null?void 0:m.stats)==null?void 0:R.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(async()=>{var J,gA,eA,CA,IA,oA,vA,qA;if((eA=(gA=(J=this.room)==null?void 0:J.networkQuality)==null?void 0:gA.hadRecentBadUplink)!=null&&eA.call(gA,2)||e.heartbeatCount-T<3)return i();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((CA=this.mediaTrack)!=null&&CA.stats){const se=this.mediaTrack.stats.totalFrames||0;se-b===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",se)}const Ae=this.kind===ni.AUDIO,HA=this.stat.bytesSent>0;if(fr[HA?"addSuccessEvent":"addFailedEvent"]({key:Ae?503700:513702}),!Ae){const se={H264:513704,H265:513705,VP8:513706}[((oA=(IA=this.room)==null?void 0:IA.videoCodec)==null?void 0:oA.toUpperCase())||"H264"];se&&fr[HA?"addSuccessEvent":"addFailedEvent"]({key:se})}if(!HA){if(fr.addEnum({key:Ae?503701:513703,value:q4()}),ah.uploadEvent({log:`stat-encode-failed-${this.kind}-${v$()||R$()}`,userId:this.userId}),this.log.warn(Ae?"encode failed":`${(qA=(vA=this.room)==null?void 0:vA.videoCodec)==null?void 0:qA.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),await this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(await QT(5e3),this.stat.bytesSent>0||this.hasFlag)))return i();this.emit("6",this),n(new Ml({message:`${this.strMediaType} encode failed`,code:Ae?Zg.AUDIO_ENCODE_FAILED:Zg.VIDEO_ENCODE_FAILED}))}}},1e4)})}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),Rn.emit(Rs.LOCAL_TRACK_UNPUBLISHED,{track:this})}async updateDeviceIdInUse(){if(this.sourceTrack&&eV){const{deviceId:e,groupId:i}=this.sourceTrack.getSettings(),{label:n}=this.sourceTrack;await hEA({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind})||(this.deviceId=e,this.label=n,i&&(this.groupId=i),_W().then(c=>{const I=c.find(C=>{let m=C.deviceId===e;return i&&(m=m&&C.groupId===i),m});I&&this.emit("2",I)}))}}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(e=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===ni.AUDIO&&!dEA(this.sourceTrack)||this.kind===ni.VIDEO&&!EEA(this.sourceTrack)||this._isRecapturing||e&&JV&&ud)}onTrackMuted(){super.onTrackMuted(),wEA(),this.isNeedToRecapture(!0)&&(Date.now()-this._lastRecaptureTimethis.onTrackMuted(),iY):this._onMuteTimeoutId=setTimeout(async()=>{var e;if((e=this.sourceTrack)!=null&&e.muted){if((_u||cC)&&document.visibilityState!=="visible")return;this.recapture(await this.getRecoverCaptureDeviceId())}},5e3))}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}async onTrackEnded(){if(super.onTrackEnded(),this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTimethis.onTrackEnded(),iY);this.emit("7"),this.recapture(await this.getRecoverCaptureDeviceId())}}async recapture(e,i=!1){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");const c=this.sourceTrack;i||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();const I={useExactDeviceId:!0};if(e==="user"||e==="environment")I.facingMode=e;else{let C;(this.kind==="audio"?await xU():await bM()).find(m=>m.deviceId===e)&&(C=e),I.deviceId=C}return this.capture(I,i).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),Rn.emit(Rs.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(C=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${C.message}`),this.emit("5",C),Rn.emit(Rs.LOCAL_TRACK_RECAPTURE,{track:this,error:C})}).finally(()=>{i&&c?.stop()})}async getRecoverCaptureDeviceId(){const e=this instanceof zV;if(e&&this.facingMode)return this.facingMode;let{deviceId:i}=this;if(i){const n=(zL.get(i)||0)+1;if(zL.set(i,n),n>=3&&this.enableAutoSwitchWhenRecapturing){const c=e?(await bM()).find(I=>!zL.has(I.deviceId)):(await xU()).find(I=>!zL.has(I.deviceId));c&&(this.log.warn(`${i} capture fail ${n} times, change new ${c.deviceId}`),i=c.deviceId)}}return i}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),Rn.emit(Rs.LOCAL_TRACK_STOPPED,{track:this}),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(e=this.manager)==null||e.removeInput(this),this._onMuteTimeoutId&&clearTimeout(this._onMuteTimeoutId)}close(){super.close(),this.stopCapture()}};yc([Ru(nr.INIT,"ready",{ignoreError:!0,sync:!0})],vM.prototype,"setStateToReady"),yc([NEA()],vM.prototype,"capture"),yc([Ru("ready","publish",{ignoreError:!0,success(){Rn.emit(Rs.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(e){var i;(i=this.room)==null||i.localTracks.delete(this);let n="error";const c=e instanceof Ml?e:e.cause instanceof Ml?e.cause:e;let I=!1;c instanceof Ml&&(c.message.includes("timeout")?n="timeout":c.code===Zg.API_CALL_ABORTED&&(I=!0,n="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:n,error:c}),this.log[I?"info":"error"]("publish failed",c)}}),aAA(521714,!1)],vM.prototype,"publish"),yc([WV(e=>async function(){const i=this.state==="publish"?"started":"starting";e.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)}),Ru([],"ready",{sync:!0})],vM.prototype,"unpublish");var zL=new Map;Rn.on(Rs.SWITCH_DEVICE_SUCCESS,e=>{e.track.deviceId&&zL.delete(e.track.deviceId)});var tdA=class{constructor(e,i=!1){this.dataView=e,this.isSEI&&(i?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){const{seiPayloadStartIndex:e}=this,i=this.dataView.byteLength-2,n=[];let c=0;for(let C=e;C<=i;C++){const m=this.dataView.getInt8(C);switch(m){case 0:case 1:case 2:case 3:c===2&&(n.push(3),c=0),m===0?c+=1:c=0,n.push(m);break;default:c=0,n.push(m)}}n.push(this.dataView.getInt8(this.dataView.byteLength-1));const I=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...n]).buffer);this.dataView=I}removePreventionByte(){const{seiPayloadStartIndex:e}=this,i=this.dataView.byteLength-1,n=[];let c=0;for(let C=e;C<=i;C++)switch(this.dataView.getInt8(C)){case 0:c++,n.push(this.dataView.getInt8(C));break;case 3:c!==2&&n.push(this.dataView.getInt8(C)),c=0;break;default:n.push(this.dataView.getInt8(C)),c=0}const I=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,e),...n]).buffer);this.dataView=I}get seiPayloadStartIndex(){let e=6;for(let i=6;i=this.dataView.byteLength?0:31&this.dataView.getUint8(e)}getStartCodeLength(){return this.dataView.byteLength>=4&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===0&&this.dataView.getUint8(3)===1?4:this.dataView.byteLength>=3&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===1?3:0}get isIDR(){return this.naluType===5}get isSPS(){return this.naluType===7}get isPPS(){return this.naluType===8}get isSEI(){return this.naluType===6}},idA=class{constructor(){pe(this,"_seiMessageList",[]),pe(this,"_smallSeiMessageList",[]),pe(this,"_seiPayloadType",243)}encodeSEINalu(e){const i=e.byteLength,n=parseInt(String(i/255),10),c=i%255,I=[];I.push(0,0,0,1,6,this._seiPayloadType);for(let m=0;m0&&e.data.byteLength>0){const c=9-this.getNaluCount(e.data);if(c<=0)return 0;const I=n.splice(0,c).reverse().map(this.encodeSEINalu.bind(this)),C=I.reduce((b,J)=>b+J.dataView.byteLength,0),m=new ArrayBuffer(C+e.data.byteLength),R=new DataView(m),_=new DataView(e.data);let T=0;for(let b=0;b{var c;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{const I=KY(((c=this.room)==null?void 0:c.sdkAppId)||0)?YZ:xZ;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${I}`),this.setProfile(cB(ks({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",n),this.on("publish",n),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(eV&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}get hasSmall(){var e;return!!((e=this.manager)!=null&&e.hasSmall)}async setMute(e){var i,n,c;if(rh(e)){if(this.muteImage===e)return;await((i=this.manager)==null?void 0:i.deleteWatermark("mute")),await((n=this.manager)==null?void 0:n.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e,fillVideo:!0})),this.muteImage=e,super.setMute(!1)}else this.muteImage&&(await((c=this.manager)==null?void 0:c.deleteWatermark("mute")),this.muteImage=void 0),super.setMute(e)}async capture({deviceId:e,facingMode:i,useExactDeviceId:n=!0,customSource:c,retryWhenExactFailed:I=!0}){const C={audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:n,retryWhenExactFailed:I,customSource:c};if(C.facingMode==="environment"){const m=await this.getDeviceIdWhenUsingBackCamera();m&&(C.cameraId=m)}return super.capture(C)}setProfile(e){var i;const n=this.fallbackProfile(e);if(n.bitrate&&(this.isNeedToSetBandwidth=n.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(n);else{const c=KY(((i=this.room)==null?void 0:i.sdkAppId)||0)?YZ:xZ;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${c}`),super.setProfile(cB(ks({},this.profile),{width:1920,height:1080}))}}async applyProfile(){var e,i;if(!this.mediaTrack)return;const{width:n=0,height:c=0}=(this.sourceTrack||this.mediaTrack).getSettings(),I=n*c,C=this.settings,m=C.height!==this.profile.height||C.width!==this.profile.width||C.frameRate!==this.profile.frameRate;if(m&&(VM===16&&this.deviceId?await this.recapture(this.deviceId):(N4(this.outMediaTrack)?await((e=this.outMediaTrack)==null?void 0:e.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate})):await((i=this.sourceTrack||this.mediaTrack)==null?void 0:i.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate})),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;const{width:R=0,height:_=0}=(this.sourceTrack||this.mediaTrack).getSettings(),T=R*_;return m&&T&&I&&T===I?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:ni.VIDEO,videoType:ni.BIG})}}get settings(){const e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},i=this.sourceTrack||this.mediaTrack;return eV&&i&&Object.assign(e,i.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:K7(this.settings,this.profile)}isAllowed2k4k(e){var i;return!this.room||!this.room.scheduleResult||!!this.isScreen||e.height*e.width<3686400||((i=this.room.scheduleResult.trtcAutoConf)==null?void 0:i["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}async switchDevice(e){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;const i={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?i.facingMode=e:i.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),await this.capture(i),Rn.emit(Rs.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(i){throw this.log.error(`switch camera failed ${i}`),this.deviceId&&this.recapture(this.deviceId),i}}async getDeviceIdWhenUsingBackCamera(){let e;try{if(h$&&!H4&&j$){const i=(await bM(!0)).map(c=>{var I;return cB(ks({},c),{capabilities:(I=c.getCapabilities)==null?void 0:I.call(c)})}).filter(c=>{var I,C;return(C=(I=c.capabilities)==null?void 0:I.facingMode)==null?void 0:C.includes("environment")});let n=i[0];i.forEach(c=>{var I,C,m,R;const{capabilities:_}=c;((I=_.width)!=null&&I.max&&((C=_.height)!=null&&C.max)?_.width.max*_.height.max:0)>((m=n.capabilities.width)!=null&&m.max&&((R=n.capabilities.height)!=null&&R.max)?n.capabilities.width.max*n.capabilities.height.max:0)&&(n=c)}),n?.capabilities&&(this._log.info("use max resolution back camera",n),e=n.deviceId)}}catch(i){this._log.warn("get max res camera failed",i)}return e}async updateSmallConfig(e){var i,n;this._log.info(`update small stream config: ${JSON.stringify(e)}`);const c=!this.small;this.small=this.fallbackProfile(e,!0),await((i=this.manager)==null?void 0:i.update()),c&&await((n=this.room)==null?void 0:n.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(e,i=!1){const n=e.width>e.height,c=ks({},e);return e.width*e.height<=19200&&cC&&lD&&(this.log.warn(`${i?"small ":""}resolution is ${e.width}*${e.height}, fallback to 240*180 for android chrome`),c.width=n?240:180,c.height=n?180:240,c.bitrate=Math.max(e.bitrate,150)),e.width*e.height>921600&&WIA&&(c.width=n?1280:720,c.height=n?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),KIA(TQ,"14.3")&&S$(TQ,"14.0",!0)&&this.on("7",()=>{const I=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=I?640:480,this.profile.height=I?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>230400&&(this.profile.width=I?640:360,this.profile.height=I?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!i&&this.avoidCropping&&(lD||aC)&&!XIA()&&e.width*e.height<=230400&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,c.width=1280,c.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),c}stopSmall(){var e,i;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(i=this.room)==null||i.enableSmall(!1))}listenDeviceChange(){SQ&&!SQ.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&SQ.on("videoInputRemoved",this.handleCameraRemoved,this)}async handleCameraRemoved(e){if(e.deviceId===this.deviceId){let i=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${CAA[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(e)}`),this.recaptureMode===0){pc(this.userId,{eventId:2003,param1:7,streamType:2});const n=await bM();n[0]?this.recapture(n[0].deviceId):i=!0}i&&SQ.on("videoInputAdded",this.handleCameraAdded,this)}}async handleCameraAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(SQ.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(e)}`),this.recapture(e.deviceId))}encodeFrame(e,i){if(!this.manager)return e;const n=i?8:this.mediaType;return this.manager.encodePipeline.reduceRight((c,I)=>I?I({frame:c,mediaType:n}):c,e)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(e=>e)}play(e,i){return sr(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,i)}close(){SQ.off("videoInputAdded",this.handleCameraAdded,this),SQ.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}async recapture(e){try{await super.recapture(e)}catch(i){const n=(await bM()).find(c=>c.deviceId!==e);if(!n)throw i;await super.recapture(n.deviceId)}}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info(`setContentHint ${e}`),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||sr(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};yc([rAA(function(e){this.setContentHint(e.contentHint||"motion")})],zV.prototype,"capture");var odA=[-1,-1,1,-1,-1,1,1,1],ndA=[0,0,1,0,0,1,1,1],ZL=class TW extends nr{constructor(i,n){if(super(),this.context=i,pe(this,"name"),pe(this,"input"),pe(this,"output"),pe(this,"texture"),pe(this,"ctx2d",null),pe(this,"fbo"),pe(this,"width",0),pe(this,"height",0),pe(this,"x",0),pe(this,"y",0),pe(this,"program"),pe(this,"vertexShader"),pe(this,"fragmentShader"),pe(this,"totalFrames",0),pe(this,"dropFrames",0),pe(this,"matchInputSize",!0),pe(this,"texCoordBuffer"),pe(this,"positionBuffer"),pe(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),pe(this,"cost",0),pe(this,"_canvas",null),pe(this,"_image"),pe(this,"log"),this.context.on("disconnect",this.close,this),this.name=n.name,this.log=n.logger,this.matchInputSize=n.matchInputSize!==!1,this.width=n.width||i.width,this.height=n.height||i.height,this._image=n.image,i instanceof VU)i.ctx&&n.create2d&&(typeof OffscreenCanvas=="function"&&VM!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);else try{const c=i.ctx;this.texCoordBuffer=this.createBuffer(ndA),this.positionBuffer=this.createBuffer(odA),n.createTexture!==!1&&(this.texture=c.createTexture(),this.useTexture(),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,c.LINEAR),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MAG_FILTER,c.LINEAR),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),c.pixelStorei(c.UNPACK_ALIGNMENT,1)),n.useFbo&&(this.fbo=c.createFramebuffer(),this.useBufferFrame(),this.useTexture(),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,this.width,this.height,0,c.RGBA,c.UNSIGNED_BYTE,null),c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,this.texture,0)),n.useDefaultProgram?this.program=i.defaultProgam:(n.vertexShaderSource||n.fragmentShaderSource)&&(this.vertexShader=n.vertexShaderSource?i.createShader(c.VERTEX_SHADER,n.vertexShaderSource):i.defaultVShader,this.fragmentShader=n.fragmentShaderSource?i.createShader(c.FRAGMENT_SHADER,n.fragmentShaderSource):i.defaultFShader,this.program=i.createProgram(this.vertexShader,this.fragmentShader))}catch(c){this.context.destroy(new Ml({code:Zg.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${c.message||c}`}))}}get image(){return this._image}set image(i){this._image=i}createFramebuffer(i){const n=this.context.ctx,c=n.createFramebuffer();return n.bindFramebuffer(n.FRAMEBUFFER,c),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,i,0),c}connect(i,...n){return i.addInput(this,...n),this.output=i,i}addInput(i,...n){this.input=i,this.matchInputSize&&i.width&&i.height&&this.resize(i.width,i.height)}requestFrame(i){const n=Date.now();return!!(this.context instanceof NW&&this.render(i)||this.context instanceof VU&&this.render2d(i))&&(this.totalFrames++,this.cost=Date.now()-n,!0)}render2d(i){var n;return!!((n=this.input)!=null&&n.requestFrame(i))&&this.draw2d(this.input.image,0,0,this.width,this.height)}update(i=0){var n;(n=this.output)==null||n.update(i)}disconnect(...i){var n;(n=this.output)==null||n.removeInput(this,...i),delete this.output}removeInput(i,...n){delete this.input}close(){var i,n;if(this.context.off("disconnect",this.close,this),(i=this.output)==null||i.removeInput(this),delete this.output,(n=this.input)==null||n.disconnect(),this.context instanceof NW){const c=this.context.ctx;c.deleteBuffer(this.texCoordBuffer),c.deleteBuffer(this.positionBuffer),this.fbo&&c.deleteFramebuffer(this.fbo),this.texture&&c.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&c.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&c.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&c.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var i;this.useTextures((i=this.input)==null?void 0:i.texture)}useTextures(...i){const n=this.context.ctx;i.forEach((c,I)=>{c&&(n.activeTexture(n.TEXTURE0+I),n.bindTexture(n.TEXTURE_2D,c))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){const i=this.context.ctx;i.bindFramebuffer(i.FRAMEBUFFER,this.fbo||null)}createBuffer(i){const n=this.context.ctx,c=n.createBuffer();return n.bindBuffer(n.ARRAY_BUFFER,c),n.bufferData(n.ARRAY_BUFFER,new Float32Array(i),n.STATIC_DRAW),c}setTexBuffer(i){const n=this.context.ctx;n.bindBuffer(n.ARRAY_BUFFER,this.texCoordBuffer),n.bufferData(n.ARRAY_BUFFER,new Float32Array(i),n.STATIC_DRAW)}setPosBuffer(i){const n=this.context.ctx;n.bindBuffer(n.ARRAY_BUFFER,this.positionBuffer),n.bufferData(n.ARRAY_BUFFER,new Float32Array(i),n.STATIC_DRAW)}changeBufferData(i,n){const c=this.context.ctx;c.bindBuffer(c.ARRAY_BUFFER,i),c.bufferData(c.ARRAY_BUFFER,new Float32Array(n),c.STATIC_DRAW)}setAttributes(...i){const n=this.context.ctx;i.forEach((c,I)=>{n.enableVertexAttribArray(I),n.bindBuffer(n.ARRAY_BUFFER,c),n.vertexAttribPointer(I,2,n.FLOAT,!1,0,0)})}getVertexPoint(i,n){return[i/this.width*2-1,n/this.height*2-1]}layout2texCoords(i){return[...this.getVertexPoint(i.x,i.y),...this.getVertexPoint(i.x+i.width,i.y),...this.getVertexPoint(i.x,i.y+i.height),...this.getVertexPoint(i.x+i.width,i.y+i.height)]}resize(i,n){if(this.width!==i||this.height!==n){if(this.width=i,this.height=n,this._canvas&&(this._canvas.width=i,this._canvas.height=n),this.texture&&this.fbo){this.useTexture();const c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,i,n,0,c.RGBA,c.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(i,n)}}draw(i,n){this.setAttributes(i||this.positionBuffer,n||this.texCoordBuffer);const c=this.context.ctx;c.drawArrays(c.TRIANGLE_STRIP,0,4)}draw2d(i,n,c,I,C,m,R,_,T){const b=!(sr(m)||sr(R)||sr(_)||sr(T));return!(!this.ctx2d||!i)&&(i instanceof ImageData?(b?this.ctx2d.putImageData(i,n,c,m,R,_,T):this.ctx2d.putImageData(i,n,c),this.emit(TW.RENDER,this.ctx2d.canvas)):(b?this.ctx2d.drawImage(i,m,R,_,T,n,c,I,C):this.ctx2d.drawImage(i,n,c,I,C),this.emit(TW.RENDER,i)),typeof VideoFrame<"u"&&i instanceof VideoFrame&&i.close(),!0)}drawBackGround2d(i){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=i,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var i;const{totalFrames:n,x:c,y:I,width:C,height:m,name:R,cost:_}=this,T=Date.now(),b=(n-this.lastInfo.totalFrames)/((T-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:n,x:c,y:I,width:C,height:m,timestamp:T,fps:b,name:R,cost:_},ks({parent:(i=this.input)==null?void 0:i.getInfo()},this.lastInfo)}createTexture(i){const n=this.context.ctx,c=n.createTexture();return this.useTextures(c),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.pixelStorei(n.UNPACK_ALIGNMENT,1),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,i),c}};pe(ZL,"RENDER","render"),yc([Ru(nr.INIT,"connected",{sync:!0})],ZL.prototype,"connect"),yc([Ru("connected",nr.INIT,{ignoreError:!0,sync:!0})],ZL.prototype,"disconnect"),yc([Ru([],"closed",{sync:!0})],ZL.prototype,"close");var oV=ZL,sdA=ih(YEA(250),IAA(()=>performance.now()),gAA()),rdA=e=>i=>{const n=performance.now();ih(sdA,zEA(c=>c-n{if(e!==this.context.frameRate&&(RQ.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof NW){const i=this.context.ctx.getError();i&&this.context.destroy(new Ml({code:Zg.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${i}`}))}},{fps:this.context.frameRate})}render(e){var i;return!!((i=this.input)!=null&&i.requestFrame(e))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(oV.RENDER,this.context._canvas),!0)}addInput(e,...i){super.addInput(e,...i),this.start(this.context.frameRate)}update(e=0){this.state!=="closed"&&(this._intervalId&&(RQ.clearTask(this._intervalId),this._intervalId=0,e===1&&(this.log.info(`${this.name} use requestVideoFrameCallback`),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(e){super.removeInput(e),RQ.clearTask(this._intervalId)}resize(e,i){super.resize(e,i),this.context.setSize(e,i)}close(){super.close(),RQ.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},cdA=class extends gdA{constructor(e,i){super(e,i),pe(this,"_videoTrack"),pe(this,"_muteOb"),pe(this,"_closedOb",DE(this,"closed")),pe(this,"_subscription"),pe(this,"_canvasContainer"),Number(aF)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=e.canvas.captureStream().getVideoTracks(),this._muteOb=DE(this._videoTrack,"mute"),ih(DE(this._videoTrack,"ended"),mT(this._closedOb),HM(()=>{this.context.destroy(new Ml({code:Zg.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=ih(this._muteOb,mT(this._closedOb),dAA(rdA(5e3)),gT(()=>{var e;return!!((e=this._videoTrack)!=null&&e.muted)&&!document.hidden}),HM(()=>{this.context.destroy(new Ml({code:Zg.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var e;(e=this._subscription)==null||e.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){this.context._canvas&&this._canvasContainer&&(document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas)))}render(e){return this.putCanvasIntoDom(),super.render(e)}render2d(e){return this.putCanvasIntoDom(),super.render2d(e)}close(){var e,i;super.close(),(e=this._videoTrack)==null||e.stop(),delete this._videoTrack,(i=this._canvasContainer)==null||i.remove()}},hAA=class extends oV{constructor(e,i){super(e,ks({name:"imageSource"},i)),pe(this,"_lastImage"),pe(this,"_totalFrames",0),pe(this,"_autoResize",!1),pe(this,"_canvasRendered"),pe(this,"videoCallbackId",0),pe(this,"waitingFirstFrame",!0),pe(this,"shouldUpdate",!0),this._autoResize=i?.autoResize!==!1,VM===16&&(this._canvasRendered=lAA(),ih(this._canvasRendered,xEA(this._image),AdA(n=>n instanceof HTMLCanvasElement?DE(n,"rendered"):HEA()),mT(DE(this,"closed")),HM(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;const e=this.image;this.videoCallbackId&&e.cancelVideoFrameCallback(this.videoCallbackId),$4()&&!document.hidden&&(this.videoCallbackId=e.requestVideoFrameCallback((i,n)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=n.presentedFrames,this.update(1))}))}_render(e,i){var n;let{width:c,height:I}=this;const{image:C}=this;if(C instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:c,videoHeight:I}=C,!c||!I)return!1;C.width=c,C.height=I}else if(C instanceof HTMLImageElement||C instanceof ImageData||C instanceof ImageBitmap){if({width:c,height:I}=C,C!==this._lastImage)this._lastImage=C;else if(c===this.width&&I===this.height)return!0}else C instanceof HTMLCanvasElement||C instanceof OffscreenCanvas?({width:c,height:I}=C,this._lastImage=C):typeof VideoFrame<"u"&&C instanceof VideoFrame&&({displayWidth:c,displayHeight:I}=C,(n=this._lastImage)==null||n.close(),this._lastImage=C);if(!this._autoResize)return!0;if(this.width===c&&this.height===I&&this.totalFrames){if(i){this.useTexture();const m=this.context.ctx;m.texSubImage2D(m.TEXTURE_2D,0,0,0,m.RGBA,m.UNSIGNED_BYTE,C)}}else{if(i){this.useTexture();const m=this.context.ctx;m.texImage2D(m.TEXTURE_2D,0,m.RGBA,m.RGBA,m.UNSIGNED_BYTE,C)}this.resize(c,I)}return!0}get image(){return this._image}set image(e){var i;(i=this._canvasRendered)==null||i.next(e),this._image=e}render(e){return this._render(e,!0)}render2d(e){return this._render(e,!1)}},BAA=class extends hAA{constructor(e,i,n){super(e,n),this._player=i,this.name="videoPlayerSource",ih(DE(this._player,zs.PLAYER_STATE_CHANGED),mT(DE(this,"closed")),gT(({state:c})=>c==="PLAYING"),HM(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},ldA=class extends BAA{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(e,i,n){super(e,new Ky({id:n.name,track:i,muted:!0,container:null,objectFit:"contain",log:n.logger}),n),this.name="videoTrackSource",this._player.play()}replaceTrack(e){this.waitingFirstFrame=!0,this._player.setTrack(e),this._player.play()}close(){super.close(),this._player.stop()}},IdA=class extends oV{constructor(e,i,n){super(e,cB(ks({name:"textSource"},n),{create2d:!0})),pe(this,"hasChange",!0),pe(this,"content",""),this.ctx2d.textBaseline="top",this.content=i.content||"",i.font&&(this.font=i.font),i.color&&(this.color=i.color)}set font(e){this.ctx2d&&(this.ctx2d.font=e,this.hasChange=!0)}get font(){var e;return((e=this.ctx2d)==null?void 0:e.font)||""}set color(e){this.ctx2d&&(this.ctx2d.fillStyle=e,this.hasChange=!0)}get color(){var e;return((e=this.ctx2d)==null?void 0:e.fillStyle)||""}render2d(e){return!(!this.ctx2d||!this.hasChange)&&(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0)}render(e){return!1}resize(e,i){if(!this.ctx2d)return;const{color:n,font:c}=this;super.resize(e,i),this.color=n,this.font=c}drawMultilineText(e=0,i=0,n=1.2){if(!this.ctx2d)return;const c=this.ctx2d.measureText(this.content);i+=c.fontBoundingBoxAscent||c.actualBoundingBoxAscent||0;const I=this.font.match(/(\d+)px/),C=(I?parseInt(I[1],10):16)*n,m=this.content.split(` `);for(let R=0;R{this.destroy(new vl({code:Zg.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(e){let i="";return e&&(i=e.message,this.error=e,mr.addFailedEvent({key:512702,error:e})),this.disconnect(),this.log.info(`video context destroy${i}`?`: ${i}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),e}set width(e){var i;(i=this.ctx)==null||i.viewport(0,0,e,this.height),super.width=e,this._canvas2d&&(this._canvas2d.width=e)}set height(e){var i;(i=this.ctx)==null||i.viewport(0,0,this.width,e),super.height=e,this._canvas2d&&(this._canvas2d.height=e)}setSize(e,i){var n;(n=this.ctx)==null||n.viewport(0,0,e,i),super.setSize(e,i),this._canvas2d&&(this._canvas2d.width=e,this._canvas2d.height=i)}createShader(e,i){const n=this.ctx,c=n.createShader(e);return n.shaderSource(c,i),n.compileShader(c),c}createProgram(e,i){const n=this.ctx,c=n.createProgram();return n.attachShader(c,e),n.attachShader(c,i),n.linkProgram(c),n.getProgramParameter(c,n.LINK_STATUS)||this.log.error(n.getProgramInfoLog(c)),c}};pe(XL,"UNAVAILABLE","unavailable"),yc([Ru(nr.INIT,"created",{sync:!0,fail(e){this.log.error("video gl context create failed",e.cause),mr.addFailedEvent({key:512700,error:e.cause||e})},success(){this.log.info("video context created use webgl"),mr.addSuccessEvent({key:512700})}})],XL.prototype,"create"),yc([Ru("created",nr.INIT,{ignoreError:!0,sync:!0,success(e){e&&this.emit(XL.UNAVAILABLE,e),this.removeAllListeners()}})],XL.prototype,"destroy");var NW=XL,VU=class extends YU{constructor(){super(...arguments),pe(this,"ctx")}create(e){if(this.hasAlpha=e.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${YU._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:e.alpha,willReadFrequently:e.willReadFrequently}),!this.ctx)throw new vl({code:Zg.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(e){let i="";e&&(i=e.message,this.error=e,mr.addFailedEvent({key:512703,error:e})),this.disconnect(),this.log.info("video context destroy "+(i?`: ${i}`:"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),mr.addSuccessEvent({key:512703})}};yc([Ru(nr.INIT,"created",{sync:!0,fail(e){this.log.error("video 2d context create failed",e.cause),mr.addFailedEvent({key:512701,error:e.cause||e})},success(){this.log.info("video context created use 2d"),mr.addSuccessEvent({key:512701})}})],VU.prototype,"create"),yc([Ru("created",nr.INIT,{ignoreError:!0,sync:!0})],VU.prototype,"destroy");var s5=N$();if(typeof navigator<"u"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:s5,exposeOrigin:!0,permittedOrigins:["*"]})}catch{}var ddA=async function(e){let i=null;const n=BdA(e);An.info(`getDisplayMedia with constraints: ${JSON.stringify(n)}`);const c=await navigator.mediaDevices.getDisplayMedia(n);e.systemAudio&&c.getAudioTracks().length===0&&(J4&&ID<74||ud||aC)&&An.warn("Your browser not support capture system audio");const I=c.getVideoTracks()[0];if(I){if(e.frameRate)try{await I.applyConstraints({frameRate:{min:e.frameRate,ideal:e.frameRate},width:e.width,height:e.height})}catch(C){An.warn(`screen applyConstraints failed: ${C}`)}e.captureElement&&await CdA(I,e.captureElement)}if(e.audio){const C=hdA(e);An.info(`getUserMedia with constraints: ${JSON.stringify(C)}`),i=await navigator.mediaDevices.getUserMedia(C),c.addTrack(i.getAudioTracks()[0])}return c};async function CdA(e,i){var n;if("CropTarget"in window&&"fromElement"in CropTarget&&_M(e.cropTo))try{if(((n=e.getCaptureHandle())==null?void 0:n.handle)!==s5)return;const c=await CropTarget.fromElement(i);await e.cropTo(c)}catch(c){An.warn(`cropTo target failed ${c}`)}}function hdA(e){const i={echoCancellation:e.echoCancellation,autoGainControl:e.autoGainControl,noiseSuppression:e.noiseSuppression,sampleRate:e.sampleRate,channelCount:e.channelCount};return sr(e.microphoneId)||(i.deviceId=e.microphoneId),{audio:i,video:!1}}function BdA(e){const i={preferCurrentTab:e.preferDisplaySurface==="current-tab"||!!e.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},n={width:ud?{max:e.width}:{ideal:e.width,max:e.width},height:ud?{max:e.height}:{ideal:e.height,max:e.height},frameRate:e.frameRate,displaySurface:e.preferDisplaySurface||"monitor"};if(i.video=n,e.systemAudio){const{echoCancellation:c=!0,noiseSuppression:I=!1,autoGainControl:C=!1}=e;i.audio={echoCancellation:c,noiseSuppression:I,autoGainControl:C,sampleRate:48e3}}return i}var QdA=ddA,pdA=class extends zV{constructor(e){super(e,2),pe(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),pe(this,"objectFit","contain"),pe(this,"isScreen",!0),this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var e,i;try{return s5===((i=(e=this.mediaTrack)==null?void 0:e.getCaptureHandle())==null?void 0:i.handle)}catch{return}}async capture({systemAudio:e=!1,autoGainControl:i,echoCancellation:n,noiseSuppression:c,audioTrack:I,videoTrack:C,captureElement:m,preferDisplaySurface:R}){var _;try{const T=Wc();let b;return C||I?(b=new MediaStream,C&&b.addTrack(C),I&&b.addTrack(I)):(b=await QdA({audio:!1,systemAudio:e,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:i,echoCancellation:n,noiseSuppression:c,captureElement:m,preferDisplaySurface:R}),this.sourceTrack=b.getVideoTracks()[0]),await this.setInputMediaStreamTrack(b.getVideoTracks()[0]),Rn.emit(Rs.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Wc()-T,profile:this.profile,room:(_=this.manager)==null?void 0:_.room}),b}catch(T){throw this.log.error(`getDisplayMedia error observed ${T}`),T instanceof vl?T:new vl({code:Zg.INITIALIZE_FAILED,name:T.name,message:T.message})}}async switchDevice(e){throw new Error("Method not implemented.")}};function mdA(e=30,i=2){return WV((n,c)=>function(...I){return new Promise((C,m)=>{const R=setTimeout(()=>{const _=new vl({code:Zg.API_CALL_TIMEOUT,message:`checkPendingPromise ${c}() timeout ${e}s`});(this.log||this._log||An).warn(_),i===2?m(_):i===1&&C()},1e3*e);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(R),n.apply(this,I).then(C,m).finally(()=>{clearTimeout(R),this._checkPendingPromiseSet&&R&&this._checkPendingPromiseSet.delete(R)})})})}yc([rAA(function(e){this.setContentHint(e.contentHint||"detail")})],pdA.prototype,"capture");var k_=class GW extends o5{constructor(i,n,c){super({userId:n.userId,sdkAppId:i.sdkAppId,mediaType:c,room:i}),this.room=i,this.user=n,pe(this,"tinyId"),pe(this,"isRemote",!0),pe(this,"jitterBufferDelay",0),pe(this,"availableState"),pe(this,"remotePublishState"),pe(this,"_triggerCheckDecodeSubject",lAA(DE(this,GW.STATE_SUBSCRIBE))),pe(this,"ignoreUpdatePlayingState"),this.tinyId=n.tinyId,this.availableState=new nr(`${n.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new nr(`${n.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),ih(cAA(DE(this,nr.STATECHANGED),DE(this.remotePublishState,nr.STATECHANGED)),IAA(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),HM(R=>{this.availableState.state!==(R?nr.ON:nr.OFF)&&(this.availableState.state=R?nr.ON:nr.OFF),this.isRemotePublished&&this.ignoreUpdatePlayingState||this.updatePlayingState(R)}));const I=ih(DE(this.player,zs.ERROR),gT(R=>R.code===MediaError.MEDIA_ERR_DECODE)),C=ih(VEA(5e3),gT(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived||!this.isRemotePublished?!1:!(this.player.isPlaying||(this.kind===ni.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0))||(this.reportDecodeResult(!0),!1))),m=ih(PEA(I,C),mT(DE(this,nr.INIT)));ih(this._triggerCheckDecodeSubject,gT(()=>!this.ignoreDecodeError),dAA(m),HM(R=>{this.reportDecodeResult(!1,R)}))}setMute(i){this.isRemotePublished&&super.setMute(i)}setInputMediaStreamTrack(i){super.setInputMediaStreamTrack(i),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(i=>{this.mediaTrack?i():this.once("input-media-track-changed",i)})}get ignoreDecodeError(){var i,n,c,I;return(I=(c=(n=(i=this.room)==null?void 0:i.networkQuality)==null?void 0:n.hadRecentBadDownlink)==null?void 0:c.call(n,2))!=null&&I||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===GW.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===nr.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(i){return i}unsubscribe(){this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(i,n){var c,I;const C=this.kind===ni.AUDIO;if(mr[i?"addSuccessEvent":"addFailedEvent"]({key:C?504700:514702}),!C){const m=((c=this.room)==null?void 0:c.downlinkVideoCodec.toUpperCase())||"H264";mr[i?"addSuccessEvent":"addFailedEvent"]({key:k$[`DECODE_${m}_RESULT`]}),i||this.log.warn(`${(I=this.room)==null?void 0:I.downlinkVideoCodec} decode failed`)}i||(mr.addEnum({key:C?504701:514703,value:q4()}),ah.uploadEvent({log:`stat-decode-failed-${this.kind}-${v$()||R$()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===ni.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:n}))}updatePlayingState(i){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===i){if(i&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack))return void this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);super.updatePlayingState(i)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?nr.ON:nr.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};pe(k_,"STATE_SUBSCRIBE","subscribe"),yc([mdA(5,1)],k_.prototype,"waitHasMediaTrack"),yc([Ru(nr.INIT,k_.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),Rn.emit(Rs.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),aAA(521716,!1)],k_.prototype,"subscribe"),yc([Ru(k_.STATE_SUBSCRIBE,nr.INIT,{sync:!0,success(){this.log.info("unsubscribed"),Rn.emit(Rs.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],k_.prototype,"unsubscribe");var k3=new Map;function pc(e,i){const n=cB(ks({},i),{timestamp:M4()});k3.has(e)?k3.get(e).push(n):k3.set(e,[n])}Rn.on(Rs.JOIN_SUCCESS,({room:e})=>{pc(e.userId,{eventId:32788})}),Rn.on(Rs.LEAVE_START,({room:e})=>{pc(e.userId,{eventId:32789})}),Rn.on(Rs.LOCAL_TRACK_PUBLISHED,({track:e})=>{if(e.room){let i=32769;e.mediaType===4?i=32768:e.mediaType===2&&(i=32805),pc(e.room.userId,{eventId:i})}}),Rn.on(Rs.LOCAL_TRACK_UNPUBLISHED,({track:e})=>{if(e.room){let i=32771;e.mediaType===4?i=32770:e.mediaType===2&&(i=32806),pc(e.room.userId,{eventId:i})}}),Rn.on(Rs.TRACK_MUTED,({track:e})=>{e.room&&(e.kind===ni.AUDIO?pc(e.room.userId,{eventId:e.isRemote?32785:32772,remoteUserId:e.isRemote?e.userId:void 0}):pc(e.room.userId,{eventId:e.isRemote?32784:32773,remoteUserId:e.isRemote?e.userId:void 0}))}),Rn.on(Rs.TRACK_UNMUTED,({track:e})=>{e.room&&(e.kind===ni.AUDIO?pc(e.room.userId,{eventId:e.isRemote?32787:32774,remoteUserId:e.isRemote?e.userId:void 0}):pc(e.room.userId,{eventId:e.isRemote?32786:32775,remoteUserId:e.isRemote?e.userId:void 0}))}),Rn.on(Rs.REMOTE_TRACK_SUBSCRIBED,({track:e})=>{e.room&&(e.mediaType===1&&pc(e.room.userId,{eventId:32777,remoteUserId:e.userId}),e.mediaType===4&&pc(e.room.userId,{eventId:32776,remoteUserId:e.userId}),e.mediaType===8&&pc(e.room.userId,{eventId:32803,remoteUserId:e.userId}))}),Rn.on(Rs.REMOTE_TRACK_UNSUBSCRIBED,({track:e})=>{e.room&&(e.mediaType===1&&pc(e.room.userId,{eventId:32779,remoteUserId:e.userId}),e.mediaType===4&&pc(e.room.userId,{eventId:32778,remoteUserId:e.userId}),e.mediaType===8&&pc(e.room.userId,{eventId:32804,remoteUserId:e.userId}))}),Rn.on(Rs.SWITCH_DEVICE_SUCCESS,({track:e})=>{e.room&&pc(e.room.userId,{eventId:e.kind===ni.VIDEO?32780:32781})}),Rn.on(Rs.LOCAL_TRACK_REPLACED,({track:e})=>{e.room&&pc(e.room.userId,{eventId:e.kind===ni.VIDEO?32782:32783})}),Rn.on(Rs.SIGNAL_CONNECTION_STATE_CHANGED,({room:e,prevState:i,state:n})=>{let c;switch(n){case"CONNECTED":c=i==="RECONNECTING"?32795:32791;break;case"DISCONNECTED":c=i==="RECONNECTING"?32796:32790;break;case"RECONNECTING":c=32794}c&&pc(e.userId,{eventId:c})}),Rn.on(Rs.PEER_CONNECTION_STATE_CHANGED,({room:e,prevState:i,state:n,remoteUserId:c})=>{const I=!!c;let C;switch(n){case"CONNECTED":C=i==="RECONNECTING"?I?32801:32798:I?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(C=I?32802:32799);break;case"RECONNECTING":C=I?32800:32797}C&&pc(e.userId,{eventId:C,remoteUserId:c})}),Rn.on(Rs.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:e,userId:i,remoteUserId:n,codec:c,isHWCodec:I,prevImplementation:C,streamType:m})=>{let R=I?1:0;C||(R=I?3:2);const _={H264:0,H265:1,VP8:2}[c.toUpperCase()],T={eventId:4004,param1:R,param2:_,streamType:m||2};n&&(T.remoteUserId=n,T.eventId=4005),pc(i,T),mr.addEnum({key:n?514701:513701,value:R}),mr.addEnum({key:n?514700:513700,value:_})}),Rn.on(Rs.LOCAL_TRACK_RECAPTURE,({track:e,error:i})=>{if(e.userId){const n={eventId:2003,param1:0};e.kind===ni.AUDIO?(n.streamType=1,i&&(n.param1=2)):(n.streamType=e.streamType==="auxiliary"?7:2,i&&(n.param1=8)),pc(e.userId,n)}});MT(oF());MT(oF());var L3=0,QAA=class pAA{constructor(i){this.core=i,pe(this,"seq"),pe(this,"log"),pe(this,"localMixVideoTrack",null),pe(this,"systemAudioTrackList",{}),pe(this,"_mixVideoConfig"),pe(this,"onScreenShareStop"),pe(this,"eventListeners",new Map),L3+=1,this.seq=L3,this.log=i.log.createChild({id:`${this.getAlias()}${L3}`}),this.log.info("created")}getName(){return pAA.Name}getAlias(){return"vmix"}getValidateRule(i){switch(i){case"start":return flA(this.core);case"update":return ylA(this.core);case"stop":return DlA(this.core)}}getGroup(){return"vmix"}async start(i){this.localMixVideoTrack||(this.localMixVideoTrack=new this.core.LocalMixVideoTrack(this.core.room.videoManager)),this._mixVideoConfig={canvasInfo:{width:1920,height:1080}},i=this.core.utils.deepCloneBasic(i);const{view:n,onScreenShareStop:c}=i,I=await this.parseMixOptions(i);return c&&(this.onScreenShareStop=c,this._mixVideoConfig.onScreenShareStop=c),this._updatePreview({view:n,track:this.localMixVideoTrack}),this.core.utils.isUndefined(n)||(this._mixVideoConfig.view=n),await this.localMixVideoTrack.startMix(),{track:this.localMixVideoTrack.outMediaTrack,systemAudioTrackList:this.systemAudioTrackList,result:I}}async update(i){const{RtcError:n,ErrorCode:c}=this.core.errorModule;if(!this.localMixVideoTrack)throw new n({code:c.INVALID_OPERATION,message:"mixTrack doesn't initialize!"});i=this.core.utils.deepCloneBasic(i);const{view:I}=i,C=await this.parseMixOptions(i);return await this._updatePreview({view:I,track:this.localMixVideoTrack,prevConfig:this._mixVideoConfig}),this.core.utils.isUndefined(I)||(this._mixVideoConfig.view=I),{track:this.localMixVideoTrack.outMediaTrack,systemAudioTrackList:this.systemAudioTrackList,result:C}}stop(){var i;this.eventListeners.forEach((n,c)=>{this.removeEventListeners(c)}),this.eventListeners.clear(),(i=this.localMixVideoTrack)==null||i.close(),this.localMixVideoTrack=null,Object.values(this.systemAudioTrackList).forEach(n=>n.stop()),this.systemAudioTrackList={},delete this.onScreenShareStop,delete this._mixVideoConfig}async parseMixOptions(i){const{RtcError:n,ErrorCode:c}=this.core.errorModule;if(!this.localMixVideoTrack||!this._mixVideoConfig)return{successOptions:{},failedDetails:[]};const I=[],C=ks({},i),{canvasInfo:m,camera:R,screen:_,text:T,image:b,video:J}=i;m&&this.parseCanvasOptions(m);let cA=0,eA=0;const CA=[{key:"camera",options:R,parser:this.parseCameraOptions.bind(this)},{key:"screen",options:_,parser:this.parseScreenOptions.bind(this)},{key:"text",options:T,parser:this.parseTextOptions.bind(this)},{key:"image",options:b,parser:this.parseImageOptions.bind(this)},{key:"video",options:J,parser:this.parseVideoOptions.bind(this)}];for(const{key:IA,options:oA,parser:vA}of CA)if(oA){cA++;const qA=await vA(this.localMixVideoTrack,oA,this._mixVideoConfig[IA]||[]);this._mixVideoConfig[IA]=qA.finalOptions,C[IA]=qA.finalOptions,qA.errors.length>0&&(I.push(...qA.errors),qA.errors.length===oA.length&&eA++)}if(eA>0&&eA===cA)throw new n({code:c.INVALID_PARAMETER,message:"all sources mix failed",data:{failedDetails:I}});return{successOptions:C,failedDetails:I}}parseCanvasOptions(i){if(!this.localMixVideoTrack||!this._mixVideoConfig)return;const{canvasColor:n,width:c,height:I,frameRate:C}=i;n&&this.localMixVideoTrack.setMixBackground(n),C&&this.localMixVideoTrack.setFps(C),this.localMixVideoTrack.resizeMixCanvas(c,I),this._mixVideoConfig.canvasInfo=i}prepareSourceOptions(i,n){const c=new Set(i.map(I=>I.id));return{removeIdList:n.filter(I=>!c.has(I.id)).map(I=>I.id),preOptionsMap:new Map(n.map(I=>[I.id,I]))}}recordSourceError(i,n,c,I,C){C.push({id:i,error:n}),c.has(i)&&I.push(c.get(i))}async parseCameraOptions(i,n,c=[]){const{removeIdList:I,preOptionsMap:C}=this.prepareSourceOptions(n,c);this.log.debug("videomixer removeIdList",n,I,C);for(const _ of I)i.removeCameraSource(_),this.removeEventListeners(_);const m=[],R=[];for(const _ of n)try{await this.processSingleCameraSource(i,_),m.push(_)}catch(T){this.recordSourceError(_.id,T,C,m,R)}return{finalOptions:m,errors:R}}async processSingleCameraSource(i,n){const{id:c}=n;this.resolveCameraInternalTrack(i,n),i.inputLocalVideoTracks.has(c)?await this.updateExistingCameraSource(i,n):await this.addNewCameraSource(i,n)}async updateExistingCameraSource(i,n){var c,I;const{id:C,layout:m,profile:R}=n,_=(c=i.inputLocalVideoTracks.get(C))==null?void 0:c.mediaTrack;await this.updateCameraProfile(n);const T=(I=i.inputLocalVideoTracks.get(C))==null?void 0:I.mediaTrack,b=this.resolveVideoProfile(R);T!==_?i.updateCameraSource(C,m,T,b):i.updateCameraSource(C,m,null,b)}resolveCameraInternalTrack(i,n){var c;const{id:I,layout:C,profile:m,useInternalTrack:R}=n;if(R){if(i.inputLocalVideoTracks.get(I))return n;this.log.debug("resolve camera internal track",n,n.id,n.videoTrack),(c=this.core.trtc.localVideoTrack)!=null&&c.sourceTrack?(this.log.debug("resolve camera internal track outMediaTrack:",this.core.trtc.localVideoTrack.outMediaTrack,"sourceTrack:",this.core.trtc.localVideoTrack.sourceTrack),n.videoTrack=this.core.trtc.localVideoTrack.outMediaTrack,n.profile=this.core.trtc.localVideoTrack.profile):n.videoTrack=this.createPlaceholderVideoTrack(),this.removeEventListeners(I);const _=b=>{var J,cA;const eA=i.inputLocalVideoTracks.get(I);this.log.debug(`camera internal track preprocessed event from ${(J=b.room)==null?void 0:J.userId} to ${this.core.room.userId}, is same instance:${b.room===this.core.room} ,new track:`,b.mediaTrack,eA?.mediaTrack,i.outMediaTrack),((cA=b.mediaTrack)==null?void 0:cA.kind)!==ni.AUDIO&&eA?.mediaTrack!==b.mediaTrack&&i.outMediaTrack!==b.mediaTrack&&b.room===this.core.room?eA&&b.mediaTrack&&i.updateCameraSource(I,C,b.mediaTrack):this.log.debug("camera internal track preprocessed event return")},T=b=>{var J,cA,eA,CA,IA,oA,vA,qA;const Ae=i.inputLocalVideoTracks.get(I);this.log.debug(`camera internal track stopped ${((J=b.track)==null?void 0:J.mediaTrack)===Ae?.mediaTrack||((cA=b.track)==null?void 0:cA.outMediaTrack)===Ae?.mediaTrack||((eA=b.track)==null?void 0:eA.outMediaTrack)===i.outMediaTrack}`,(CA=b.track)==null?void 0:CA.mediaTrack,(IA=b.track)==null?void 0:IA.outMediaTrack,Ae?.mediaTrack,i.outMediaTrack),!Ae||((oA=b.track)==null?void 0:oA.mediaTrack)!==Ae?.mediaTrack&&((vA=b.track)==null?void 0:vA.outMediaTrack)!==Ae?.mediaTrack&&((qA=b.track)==null?void 0:qA.outMediaTrack)!==i.outMediaTrack||i.updateCameraSource(I,C,this.createPlaceholderVideoTrack())};this.core.innerEmitter.on("118",_),this.core.innerEmitter.on("117",T),this.eventListeners.has(I)||this.eventListeners.set(I,{}),this.eventListeners.get(I).captureSuccess=()=>{this.core.innerEmitter.off("118",_)},this.eventListeners.get(I).trackStop=()=>{this.core.innerEmitter.off("117",T)}}return n}async addNewCameraSource(i,n){const{id:c,layout:I,useInternalTrack:C}=n,m=await this.captureCamera(n);try{i.addCameraSource(c,m,I)}catch(R){throw m.close(),R}}resolveVideoProfile(i){if(!this.core.utils.isUndefined(i))return this.core.utils.isString(i)?this.core.constants.videoProfileMap[i]:i}async parseScreenOptions(i,n,c=[]){const{removeIdList:I,preOptionsMap:C}=this.prepareSourceOptions(n,c);for(const _ of I)i.removeScreenSource(_),this.removeSystemAudioTrack(_),this.removeEventListeners(_);const m=[],R=[];for(const _ of n)try{await this.processSingleScreenSource(i,_,C),m.push(_)}catch(T){this.recordSourceError(_.id,T,C,m,R)}return{finalOptions:m,errors:R}}async processSingleScreenSource(i,n,c){const{id:I,layout:C,useInternalTrack:m}=n;this.resolveScreenInternalTrack(i,n);const R=c.get(I),_=i.inputLocalScreenTracks.has(I),T=!R?.systemAudio&&n.systemAudio;_&&!T?this.updateExistingScreenSource(i,I,C,R,n):await this.addNewScreenSource(i,n,R)}updateExistingScreenSource(i,n,c,I,C){i.updateScreenSource(n,c),I?.systemAudio&&!C.systemAudio&&this.removeSystemAudioTrack(n)}resolveScreenInternalTrack(i,n){var c,I;const{id:C,layout:m,useInternalTrack:R}=n;if(R){if(i.inputLocalScreenTracks.get(C))return n;this.log.debug("resolve screen internal track",n,n.id,n.videoTrack),(c=this.core.trtc.localScreenTrack)!=null&&c.sourceTrack?(n.videoTrack=this.core.trtc.localScreenTrack.sourceTrack,n.profile=this.core.trtc.localScreenTrack.profile,(I=this.core.trtc.localScreenAudioTrack)!=null&&I.mediaTrack&&(n.audioTrack=this.core.trtc.localScreenAudioTrack.mediaTrack),delete n.captureElement,delete n.preferDisplaySurface,delete n.systemAudio):n.videoTrack=this.createPlaceholderVideoTrack(),this.removeEventListeners(C);const _=b=>{var J,cA,eA,CA,IA,oA,vA;const qA=i.inputLocalScreenTracks.get(C);this.log.debug(`screen internal track capture success event from ${(J=b.room)==null?void 0:J.userId} to ${this.core.room.userId}, is same instance:${b.room===this.core.room}, isScreen:${(cA=b.track)==null?void 0:cA.isScreen} kind:${(eA=b.track)==null?void 0:eA.kind}`,qA,b.track.sourceTrack),(CA=b.track)!=null&&CA.isScreen&&((IA=b.track)==null?void 0:IA.kind)!==ni.AUDIO&&qA&&(this.log.debug("screen internal track capture success event ",(oA=b.track)==null?void 0:oA.sourceTrack),(vA=b.track)!=null&&vA.sourceTrack&&i.updateScreenSource(C,m,b.track.sourceTrack))},T=b=>{var J,cA;const eA=i.inputLocalScreenTracks.get(C);this.log.debug(`screen internal track stopped, is same track:${((J=b.track)==null?void 0:J.sourceTrack)===eA?.mediaTrack}, isScreen:${b.track.isScreen}`),b.track.isScreen&&((cA=b.track)==null?void 0:cA.sourceTrack)===eA?.mediaTrack&&i.updateScreenSource(C,m,this.createPlaceholderVideoTrack())};this.core.innerEmitter.on("102",_),this.core.innerEmitter.on("117",T),this.eventListeners.has(C)||this.eventListeners.set(C,{}),this.eventListeners.get(C).captureSuccess=()=>{this.core.innerEmitter.off("102",_)},this.eventListeners.get(C).trackStop=()=>{this.core.innerEmitter.off("117",T)}}return n}async addNewScreenSource(i,n,c){const{id:I,layout:C}=n,m=await this.captureScreen(n);!c?.systemAudio&&n.systemAudio&&i.inputLocalScreenTracks.has(I)&&i.removeScreenSource(I);try{i.addScreenSource(I,m,C)}catch(R){throw m.close(),R}}async parseTextOptions(i,n,c=[]){const{removeIdList:I,preOptionsMap:C}=this.prepareSourceOptions(n,c);for(const _ of I)i.removeTextSource(_);const m=[],R=[];for(const _ of n)try{C.has(_.id)?i.updateTextSource(_):i.addTextSource(_),m.push(_)}catch(T){this.recordSourceError(_.id,T,C,m,R)}return{finalOptions:m,errors:R}}async parseImageOptions(i,n,c=[]){const{removeIdList:I,preOptionsMap:C}=this.prepareSourceOptions(n,c);for(const _ of I)i.removeImageSource(_);const m=[],R=[];for(const _ of n)try{await this.processSingleImageSource(i,_,C),m.push(_)}catch(T){this.recordSourceError(_.id,T,C,m,R)}return{finalOptions:m,errors:R}}async processSingleImageSource(i,n,c){const{id:I,url:C,layout:m}=n,R=c.get(I);if(R){let _;R.url!==C&&(_=await this.core.utils.loadImage(C)),i.updateImageSource(I,m,_)}else{const _=await this.core.utils.loadImage(C);i.addImageSource(I,_,m)}}async parseVideoOptions(i,n,c=[]){const{removeIdList:I,preOptionsMap:C}=this.prepareSourceOptions(n,c);for(const _ of I)i.removeVideoSource(_);const m=[],R=[];for(const _ of n)try{await this.processSingleVideoSource(i,_,C),m.push(_)}catch(T){this.recordSourceError(_.id,T,C,m,R)}return{finalOptions:m,errors:R}}async processSingleVideoSource(i,n,c){const{id:I,url:C,layout:m}=n,R=c.get(I);if(R){let _;R.url!==C&&(_=await this.core.utils.loadVideo(C)),i.updateVideoSource(I,m,_)}else{const _=await this.core.utils.loadVideo(C);i.addVideoSource(I,_,m)}}createPlaceholderVideoTrack(){const i=document.createElement("canvas");i.width=1,i.height=1;const n=i.getContext("2d");if(!n)return i.captureStream(30).getVideoTracks()[0];let c=null;const I=1e3/30,C=i.captureStream(30).getVideoTracks()[0],m=()=>{n.fillStyle="rgba(255, 255, 255, 0)",n.fillRect(0,0,i.width,i.height),C.readyState==="live"&&(c=setTimeout(m,I))};m();const R=C.stop.bind(C);return C.stop=()=>{c&&(clearTimeout(c),c=null),R()},C}removeEventListeners(i){const n=this.eventListeners.get(i);n&&(n.captureSuccess&&n.captureSuccess(),n.trackStop&&n.trackStop(),this.eventListeners.delete(i))}async captureCamera(i){const{id:n,cameraId:c,videoTrack:I,profile:C}=i,m=new this.core.LocalVideoTrack;m.log.id+=`-${n}`;const R={};if(c?R.deviceId=c:this.core.utils.isUndefined(I)||(R.customSource=I),!this.core.utils.isUndefined(C)){const _=this.resolveVideoProfile(C);_&&m.setProfile(_)}return await m.capture(R),m}async updateCameraProfile(i){var n;const{id:c,cameraId:I,videoTrack:C,profile:m}=i,R=(n=this.localMixVideoTrack)==null?void 0:n.inputLocalVideoTracks.get(c);if(R&&(I?await R.switchDevice(I):this.core.utils.isUndefined(C)||await R.setInputMediaStreamTrack(C),!this.core.utils.isUndefined(m))){const _=this.resolveVideoProfile(m);_&&R.setProfile(_),I&&R.isNeedToSwitchDevice(I)||await R.applyProfile()}}async captureScreen(i){const{id:n,profile:c,captureElement:I,preferDisplaySurface:C,systemAudio:m,videoTrack:R,audioTrack:_}=i,T=new this.core.LocalScreenTrack;T.log.id+=`-${n}`;const b={captureElement:I,preferDisplaySurface:C,systemAudio:m,videoTrack:R,audioTrack:_};if(!this.core.utils.isUndefined(c))if(this.core.utils.isString(c)){const cA=this.core.constants.screenProfileMap[c];cA&&T.setProfile(cA)}else T.setProfile(c);const J=await T.capture(b);return m&&J.getAudioTracks().length>0?(this.systemAudioTrackList[n]=J.getAudioTracks()[0],this.log.info(`${n} system audio track captured`)):this.removeSystemAudioTrack(n),T.mediaTrack.addEventListener(this.core.constants.NAME.ENDED,()=>{this.handleScreenShareEnded(n)}),T}handleScreenShareEnded(i){var n,c,I;(n=this.localMixVideoTrack)==null||n.removeScreenSource(i),(c=this._mixVideoConfig)!=null&&c.screen&&(this._mixVideoConfig.screen=this._mixVideoConfig.screen.filter(C=>C.id!==i)),(I=this.onScreenShareStop)==null||I.call(this,i)}async _updatePreview({view:i,track:n,prevConfig:c}){if(this.core.utils.isUndefined(i)&&c?.view){const I=this.core.utils.getViewListFromView(c.view);return void(I.length>0&&await n.play(I))}if(!this.core.utils.isUndefined(i)){const I=this.core.utils.getViewListFromView(i);I.length>0?await n.play(I):n.stop()}}removeSystemAudioTrack(i){const n=this.systemAudioTrackList[i];n&&(n.stop(),this.log.info(`${i} system audio track stop`),delete this.systemAudioTrackList[i])}};pe(QAA,"Name","VideoMixer");var mAA=QAA,fdA=mAA;const ydA=Object.freeze(Object.defineProperty({__proto__:null,VideoMixer:mAA,default:fdA},Symbol.toStringTag,{value:"Module"})),DdA=$U(ydA);var SdA=YL.exports,_6;function vdA(){return _6||(_6=1,function(e,i){(function(n,c){c(i,NaA(),ogA,jcA,ilA,llA,DdA)})(SdA,function(n,c,I,C,m,R,_){function T(K){return K&&typeof K=="object"&&"default"in K?K:{default:K}}var b=T(c),J=T(_),cA=function(K,U){return cA=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(sA,k){sA.__proto__=k}||function(sA,k){for(var x in k)Object.prototype.hasOwnProperty.call(k,x)&&(sA[x]=k[x])},cA(K,U)},eA=function(){return eA=Object.assign||function(K){for(var U,sA=1,k=arguments.length;sA=0;_A--)(x=K[_A])&&(uA=(iA<3?x(uA):iA>3?x(U,sA,uA):x(U,sA))||uA);return iA>3&&uA&&Object.defineProperty(U,sA,uA),uA}function IA(K,U,sA,k){return new(sA||(sA=Promise))(function(x,iA){function uA(ye){try{ie(k.next(ye))}catch(p){iA(p)}}function _A(ye){try{ie(k.throw(ye))}catch(p){iA(p)}}function ie(ye){var p;ye.done?x(ye.value):(p=ye.value,p instanceof sA?p:new sA(function(B){B(p)})).then(uA,_A)}ie((k=k.apply(K,[])).next())})}function oA(K,U){var sA,k,x,iA,uA={label:0,sent:function(){if(1&x[0])throw x[1];return x[1]},trys:[],ops:[]};return iA={next:_A(0),throw:_A(1),return:_A(2)},typeof Symbol=="function"&&(iA[Symbol.iterator]=function(){return this}),iA;function _A(ie){return function(ye){return function(p){if(sA)throw new TypeError("Generator is already executing.");for(;iA&&(iA=0,p[0]&&(uA=0)),uA;)try{if(sA=1,k&&(x=2&p[0]?k.return:p[0]?k.throw||((x=k.return)&&x.call(k),0):k.next)&&!(x=x.call(k,p[1])).done)return x;switch(k=0,x&&(p=[2&p[0],x.value]),p[0]){case 0:case 1:x=p;break;case 4:return uA.label++,{value:p[1],done:!1};case 5:uA.label++,k=p[1],p=[0];continue;case 7:p=uA.ops.pop(),uA.trys.pop();continue;default:if(x=uA.trys,!((x=x.length>0&&x[x.length-1])||p[0]!==6&&p[0]!==2)){uA=0;continue}if(p[0]===3&&(!x||p[1]>x[0]&&p[1]=K.length&&(K=void 0),{value:K&&K[k++],done:!K}}};throw new TypeError(U?"Object is not iterable.":"Symbol.iterator is not defined.")}function qA(K,U,sA){if(sA||arguments.length===2)for(var k,x=0,iA=U.length;x0&&qt[0]<4?1:+(qt[0]+qt[1])),!$a&&Rc&&(!(qt=Rc.match(/Edge\/(\d+)/))||qt[1]>=74)&&(qt=Rc.match(/Chrome\/(\d+)/))&&($a=+qt[1]);var pa=$a,_s=Bs.String,Oa=!!Object.getOwnPropertySymbols&&!Un(function(){var K=Symbol("symbol detection");return!_s(K)||!(Object(K)instanceof Symbol)||!Symbol.sham&&pa&&pa<41}),Ta=Oa&&!Symbol.sham&&typeof Symbol.iterator=="symbol",$=Object,j=Ta?function(K){return typeof K=="symbol"}:function(K){var U=is("Symbol");return Uo(U)&&Rg(U.prototype,$(K))},RA=String,ZA=TypeError,ne=function(K){if(Uo(K))return K;throw ZA(function(U){try{return RA(U)}catch{return"Object"}}(K)+" is not a function")},De=function(K,U){var sA=K[U];return ro(sA)?void 0:ne(sA)},Ke=TypeError,qe=Object.defineProperty,Et=function(K,U){try{qe(Bs,K,{value:U,configurable:!0,writable:!0})}catch{Bs[K]=U}return U},ft="__core-js_shared__",Nt=Bs[ft]||Et(ft,{}),Kt=se(function(K){(K.exports=function(U,sA){return Nt[U]||(Nt[U]=sA!==void 0?sA:{})})("versions",[]).push({version:"3.32.1",mode:"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.32.1/LICENSE",source:"https://github.com/zloirock/core-js"})}),di=Object,Bt=function(K){return di(gg(K))},Jt=ce({}.hasOwnProperty),$i=Object.hasOwn||function(K,U){return Jt(Bt(K),U)},eo=0,os=Math.random(),Ti=ce(1 .toString),on=function(K){return"Symbol("+(K===void 0?"":K)+")_"+Ti(++eo+os,36)},wg=Bs.Symbol,Er=Kt("wks"),Mr=Ta?wg.for||wg:wg&&wg.withoutSetter||on,js=function(K){return $i(Er,K)||(Er[K]=Oa&&$i(wg,K)?wg[K]:Mr("Symbol."+K)),Er[K]},Tl=TypeError,ns=js("toPrimitive"),uI=function(K,U){if(!Xs(K)||j(K))return K;var sA,k=De(K,ns);if(k){if(sA=fo(k,K,U),!Xs(sA)||j(sA))return sA;throw Tl("Can't convert object to primitive value")}return function(x,iA){var uA,_A;if(Uo(uA=x.toString)&&!Xs(_A=fo(uA,x))||Uo(uA=x.valueOf)&&!Xs(_A=fo(uA,x)))return _A;throw Ke("Can't convert object to primitive value")}(K)},ec=function(K){var U=uI(K,"string");return j(U)?U:U+""},wc=Bs.document,Tu=Xs(wc)&&Xs(wc.createElement),Na=function(K){return Tu?wc.createElement(K):{}},Nl=!Ir&&!Un(function(){return Object.defineProperty(Na("div"),"a",{get:function(){return 7}}).a!==7}),ve=Object.getOwnPropertyDescriptor,Se={f:Ir?ve:function(K,U){if(K=Mg(K),U=ec(U),Nl)try{return ve(K,U)}catch{}if($i(K,U))return ur(!fo(ts.f,K,U),K[U])}},_g=Ir&&Un(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),cg=String,Tg=TypeError,Ts=function(K){if(Xs(K))return K;throw Tg(cg(K)+" is not an object")},Rr=TypeError,Ci=Object.defineProperty,lo=Object.getOwnPropertyDescriptor,Xc="enumerable",tc="configurable",Ng="writable",qr={f:Ir?_g?function(K,U,sA){if(Ts(K),U=ec(U),Ts(sA),typeof K=="function"&&U==="prototype"&&"value"in sA&&Ng in sA&&!sA[Ng]){var k=lo(K,U);k&&k[Ng]&&(K[U]=sA.value,sA={configurable:tc in sA?sA[tc]:k[tc],enumerable:Xc in sA?sA[Xc]:k[Xc],writable:!1})}return Ci(K,U,sA)}:Ci:function(K,U,sA){if(Ts(K),U=ec(U),Ts(sA),Nl)try{return Ci(K,U,sA)}catch{}if("get"in sA||"set"in sA)throw Rr("Accessors not supported");return"value"in sA&&(K[U]=sA.value),K}},_c=Ir?function(K,U,sA){return qr.f(K,U,ur(1,sA))}:function(K,U,sA){return K[U]=sA,K},$c=Function.prototype,lg=Ir&&Object.getOwnPropertyDescriptor,Nu=$i($c,"name"),ME={CONFIGURABLE:Nu&&(!Ir||Ir&&lg($c,"name").configurable)},Gg=ce(Function.toString);Uo(Nt.inspectSource)||(Nt.inspectSource=function(K){return Gg(K)});var Pa,Tc,RE,xa=Nt.inspectSource,ga=Bs.WeakMap,bg=Uo(ga)&&/native code/.test(String(ga)),EI=Kt("keys"),Sn=function(K){return EI[K]||(EI[K]=on(K))},Po={},ma="Object already initialized",dr=Bs.TypeError,jt=Bs.WeakMap;if(bg||Nt.state){var Xt=Nt.state||(Nt.state=new jt);Xt.get=Xt.get,Xt.has=Xt.has,Xt.set=Xt.set,Pa=function(K,U){if(Xt.has(K))throw dr(ma);return U.facade=K,Xt.set(K,U),U},Tc=function(K){return Xt.get(K)||{}},RE=function(K){return Xt.has(K)}}else{var kg=Sn("state");Po[kg]=!0,Pa=function(K,U){if($i(K,kg))throw dr(ma);return U.facade=K,_c(K,kg,U),U},Tc=function(K){return $i(K,kg)?K[kg]:{}},RE=function(K){return $i(K,kg)}}var dI={get:Tc,enforce:function(K){return RE(K)?Tc(K):Pa(K,{})}},Cr=se(function(K){var U=ME.CONFIGURABLE,sA=dI.enforce,k=dI.get,x=String,iA=Object.defineProperty,uA=ce("".slice),_A=ce("".replace),ie=ce([].join),ye=Ir&&!Un(function(){return iA(function(){},"length",{value:8}).length!==8}),p=String(String).split("String"),B=K.exports=function(M,G,O){uA(x(G),0,7)==="Symbol("&&(G="["+_A(x(G),/^Symbol\(([^)]*)\)/,"$1")+"]"),O&&O.getter&&(G="get "+G),O&&O.setter&&(G="set "+G),(!$i(M,"name")||U&&M.name!==G)&&(Ir?iA(M,"name",{value:G,configurable:!0}):M.name=G),ye&&O&&$i(O,"arity")&&M.length!==O.arity&&iA(M,"length",{value:O.arity});try{O&&$i(O,"constructor")&&O.constructor?Ir&&iA(M,"prototype",{writable:!1}):M.prototype&&(M.prototype=void 0)}catch{}var z=sA(M);return $i(z,"source")||(z.source=ie(p,typeof G=="string"?G:"")),M};Function.prototype.toString=B(function(){return Uo(this)&&k(this).source||xa(this)},"toString")}),zI=function(K,U,sA,k){k||(k={});var x=k.enumerable,iA=k.name!==void 0?k.name:U;if(Uo(sA)&&Cr(sA,iA,k),k.global)x?K[U]=sA:Et(U,sA);else{try{k.unsafe?K[U]&&(x=!0):delete K[U]}catch{}x?K[U]=sA:qr.f(K,U,{value:sA,enumerable:!1,configurable:!k.nonConfigurable,writable:!k.nonWritable})}return K},Ag=Math.ceil,ca=Math.floor,ps=Math.trunc||function(K){var U=+K;return(U>0?ca:Ag)(U)},Ns=function(K){var U=+K;return U!=U||U===0?0:ps(U)},Gu=Math.max,Lg=Math.min,Ya=Math.min,Al=function(K){return K>0?Ya(Ns(K),9007199254740991):0},ZI=function(K){return Al(K.length)},wE=function(K){return function(U,sA,k){var x,iA=Mg(U),uA=ZI(iA),_A=function(ie,ye){var p=Ns(ie);return p<0?Gu(p+ye,0):Lg(p,ye)}(k,uA);if(K&&sA!=sA){for(;uA>_A;)if((x=iA[_A++])!=x)return!0}else for(;uA>_A;_A++)if((K||_A in iA)&&iA[_A]===sA)return K||_A||0;return!K&&-1}},CI={indexOf:wE(!1)}.indexOf,bu=ce([].push),Gl=function(K,U){var sA,k=Mg(K),x=0,iA=[];for(sA in k)!$i(Po,sA)&&$i(k,sA)&&bu(iA,sA);for(;U.length>x;)$i(k,sA=U[x++])&&(~CI(iA,sA)||bu(iA,sA));return iA},Nc=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ku=Nc.concat("length","prototype"),Lu={f:Object.getOwnPropertyNames||function(K){return Gl(K,ku)}},bl={f:Object.getOwnPropertySymbols},dn=ce([].concat),hn=is("Reflect","ownKeys")||function(K){var U=Lu.f(Ts(K)),sA=bl.f;return sA?dn(U,sA(K)):U},dd=function(K,U,sA){for(var k=hn(U),x=qr.f,iA=Se.f,uA=0;uAuA;)qr.f(K,sA=x[uA++],k[sA]);return K},XI={f:Uu},il=is("document","documentElement"),ol="prototype",$I="script",QI=Sn("IE_PROTO"),nl=function(){},sl=function(K){return"<"+$I+">"+K+""},Ga=function(K){K.write(sl("")),K.close();var U=K.parentWindow.Object;return K=null,U},Ug=function(){try{fa=new ActiveXObject("htmlfile")}catch{}var K,U,sA;Ug=typeof document<"u"?document.domain&&fa?Ga(fa):(U=Na("iframe"),sA="java"+$I+":",U.style.display="none",il.appendChild(U),U.src=String(sA),(K=U.contentWindow.document).open(),K.write(sl("document.F=Object")),K.close(),K.F):Ga(fa);for(var k=Nc.length;k--;)delete Ug[ol][Nc[k]];return Ug()};Po[QI]=!0;var Nn,Ar,bc=Object.create||function(K,U){var sA;return K!==null?(nl[ol]=Ts(K),sA=new nl,nl[ol]=null,sA[QI]=K):sA=Ug(),U===void 0?sA:XI.f(sA,U)},Au=Bs.RegExp,eu=Un(function(){var K=Au(".","s");return!(K.dotAll&&K.exec(` -`)&&K.flags==="s")}),NE=Bs.RegExp,lh=Un(function(){var K=NE("(?b)","g");return K.exec("b").groups.a!=="b"||"b".replace(K,"$c")!=="bc"}),dC=dI.get,Ih=Kt("native-string-replace",String.prototype.replace),rl=RegExp.prototype.exec,Fg=rl,Io=ce("".charAt),CC=ce("".indexOf),GE=ce("".replace),bE=ce("".slice),Qd=(Ar=/b*/g,fo(rl,Nn=/a/,"a"),fo(rl,Ar,"a"),Nn.lastIndex!==0||Ar.lastIndex!==0),kE=Bd.BROKEN_CARET,al=/()??/.exec("")[1]!==void 0;(Qd||al||kE||eu||lh)&&(Fg=function(K){var U,sA,k,x,iA,uA,_A,ie=this,ye=dC(ie),p=oc(K),B=ye.raw;if(B)return B.lastIndex=ie.lastIndex,U=fo(Fg,B,p),ie.lastIndex=B.lastIndex,U;var M=ye.groups,G=kE&&ie.sticky,O=fo($s,ie),z=ie.source,X=0,gA=p;if(G&&(O=GE(O,"y",""),CC(O,"g")===-1&&(O+="g"),gA=bE(p,ie.lastIndex),ie.lastIndex>0&&(!ie.multiline||ie.multiline&&Io(p,ie.lastIndex-1)!==` -`)&&(z="(?: "+z+")",gA=" "+gA,X++),sA=new RegExp("^(?:"+z+")",O)),al&&(sA=new RegExp("^"+z+"$(?!\\s)",O)),Qd&&(k=ie.lastIndex),x=fo(rl,G?sA:ie,gA),G?x?(x.input=bE(x.input,X),x[0]=bE(x[0],X),x.index=ie.lastIndex,ie.lastIndex+=x[0].length):ie.lastIndex=0:Qd&&x&&(ie.lastIndex=ie.global?x.index+x[0].length:k),al&&x&&x.length>1&&fo(Ih,x[0],sA,function(){for(iA=1;iA=_A?K?"":void 0:(k=fI(iA,uA))<55296||k>56319||uA+1===_A||(x=fI(iA,uA+1))<56320||x>57343?K?md(iA,uA):k:K?Ha(iA,uA,uA+2):x-56320+(k-55296<<10)+65536}},Ja={charAt:QC(!0)}.charAt,fr=function(K,U,sA){return U+(sA?Ja(K,U).length:1)},fd=TypeError,xu=function(K,U){var sA=K.exec;if(Uo(sA)){var k=fo(sA,K,U);return k!==null&&Ts(k),k}if(Ho(K)==="RegExp")return fo(pI,K,U);throw fd("RegExp#exec called on incompatible receiver")};(function(K,U,sA,k){var x=js(K),iA=!Un(function(){var ye={};return ye[x]=function(){return 7},""[K](ye)!==7}),uA=iA&&!Un(function(){var ye=!1,p=/a/;return K==="split"&&((p={}).constructor={},p.constructor[BC]=function(){return p},p.flags="",p[x]=/./[x]),p.exec=function(){return ye=!0,null},p[x](""),!ye});if(!iA||!uA||sA){var _A=Us(/./[x]),ie=U(x,""[K],function(ye,p,B,M,G){var O=Us(ye),z=p.exec;return z===pI||z===gl.exec?iA&&!G?{done:!0,value:_A(p,B,M)}:{done:!0,value:O(B,p,M)}:{done:!1}});zI(String.prototype,K,ie[0]),zI(gl,x,ie[1])}})("match",function(K,U,sA){return[function(k){var x=gg(this),iA=ro(k)?void 0:De(k,K);return iA?fo(iA,k,x):new RegExp(k)[K](oc(x))},function(k){var x=Ts(this),iA=oc(k),uA=sA(U,x,iA);if(uA.done)return uA.value;if(!x.global)return xu(x,iA);var _A=x.unicode;x.lastIndex=0;for(var ie,ye=[],p=0;(ie=xu(x,iA))!==null;){var B=oc(ie[0]);ye[p]=B,B===""&&(x.lastIndex=fr(iA,Al(x.lastIndex),_A)),p++}return p===0?null:ye}]});var yr=Array.isArray||function(K){return Ho(K)==="Array"},Lc=TypeError,cl=function(K){if(K>9007199254740991)throw Lc("Maximum allowed index exceeded");return K},Og=function(K,U,sA){var k=ec(U);k in K?qr.f(K,k,ur(0,sA)):K[k]=sA},Jo=function(){},nc=[],eg=is("Reflect","construct"),Ul=/^\s*(?:class|function)\b/,ia=ce(Ul.exec),uh=!Ul.exec(Jo),ss=function(K){if(!Uo(K))return!1;try{return eg(Jo,nc,K),!0}catch{return!1}},tu=function(K){if(!Uo(K))return!1;switch(Ig(K)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return uh||!!ia(Ul,xa(K))}catch{return!0}};tu.sham=!0;var Wn,Uc=!eg||Un(function(){var K;return ss(ss.call)||!ss(Object)||!ss(function(){K=!0})||K})?tu:ss,sc=js("species"),Dr=Array,Kr=function(K,U){return new(function(sA){var k;return yr(sA)&&(k=sA.constructor,(Uc(k)&&(k===Dr||yr(k.prototype))||Xs(k)&&(k=k[sc])===null)&&(k=void 0)),k===void 0?Dr:k}(K))(0)},tg=js("species"),LE=js("isConcatSpreadable"),pC=pa>=51||!Un(function(){var K=[];return K[LE]=!1,K.concat()[0]!==K}),Eh=function(K){if(!Xs(K))return!1;var U=K[LE];return U!==void 0?!!U:yr(K)};us({target:"Array",proto:!0,arity:1,forced:!(pC&&(Wn="concat",pa>=51||!Un(function(){var K=[];return(K.constructor={})[tg]=function(){return{foo:1}},K[Wn](Boolean).foo!==1})))},{concat:function(K){var U,sA,k,x,iA,uA=Bt(this),_A=Kr(uA),ie=0;for(U=-1,k=arguments.length;U=5||Math.abs(k)>=5?(document.removeEventListener("mousemove",this.onMouseMove5px,!1),document.removeEventListener("mouseup",this.onMouseUp5px,!1),document.addEventListener("mousemove",this.onMouseMove,!1),document.addEventListener("mouseup",this.onMouseUp,!1)):Eg.debug("".concat(this.logPrefix,"on Movable mouse move less than 5px"))},K.prototype.onMouseUp5px=function(){document.removeEventListener("mousemove",this.onMouseMove5px,!1),document.removeEventListener("mouseup",this.onMouseUp5px,!1)},K.prototype.onMouseMove=function(U){if(this.movable&&this.container){var sA=U.screenX-this.moveStartOfLeft,k=U.screenY-this.moveStartOfTop,x=this.originLeft+sA,iA=this.originTop+k,uA=this.movable.offsetWidth,_A=this.movable.offsetHeight,ie=this.container.offsetWidth,ye=this.container.offsetHeight;this.options.canExceedContainer||(x<0?x=0:x>ie-uA&&(x=ie-uA),iA<0?iA=0:iA>ye-_A&&(iA=ye-_A)),!this.options.calcPositionOnly&&this.movable&&(this.movable.style.left="".concat(x,"px"),this.movable.style.top="".concat(iA,"px")),this.emit("move",x,iA)}else Eg.debug("".concat(this.logPrefix,"onMouseMove error:No 'movable' and 'container'."))},K.prototype.onMouseUp=function(){document.removeEventListener("mousemove",this.onMouseMove,!1),document.removeEventListener("mouseup",this.onMouseUp,!1),this.originLeft=0,this.originTop=0,this.moveStartOfLeft=0,this.moveStartOfTop=0},K.prototype.on=function(U,sA){var k=this.callbacksMap.get(U);k?k.push(sA):this.callbacksMap.set(U,[sA])},K.prototype.off=function(U,sA){var k=this.callbacksMap.get(U);k&&(k=k.filter(function(x){return x!=sA}),this.callbacksMap.set(U,k))},K.prototype.emit=function(U){for(var sA=[],k=1;k ").concat(U)),this.enabled=U,this.movable&&(this.movable.style.cursor=U?"move":"default",Eg.debug("".concat(this.logPrefix,"setEnabled: cursor updated to '").concat(U?"move":"default","'")))},K.prototype.isEnabled=function(){return this.enabled},K}();(function(K){K[K.Both=0]="Both",K[K.Corner=1]="Corner",K[K.Edge=2]="Edge"})(Ia||(Ia={}));var YE="trtc-resizable-top-left-anchor",Ju="trtc-resizable-top-anchor",qu="trtc-resizable-top-right-anchor",RI="trtc-resizable-left-anchor",dl="trtc-resizable-right-anchor",Pr="trtc-resizable-bottom-left-anchor",xr="trtc-resizable-bottom-anchor",dg="trtc-resizable-bottom-right-anchor",hr={resizeAnchor:{position:"absolute",width:"".concat(8,"px"),height:"".concat(8,"px"),border:"1px solid #3D7EFD",backgroundColor:"#FFFFFF"},topLeftAnchor:{top:"-".concat(4,"px"),left:"-".concat(4,"px"),cursor:"nw-resize"},topAnchor:{top:"-".concat(4,"px"),left:"calc(50% - ".concat(4,"px)"),cursor:"n-resize"},topRightAnchor:{top:"-".concat(4,"px"),right:"-".concat(4,"px"),cursor:"ne-resize"},leftAnchor:{top:"calc(50% - ".concat(4,"px)"),left:"-".concat(4,"px"),cursor:"w-resize"},rightAnchor:{top:"calc(50% - ".concat(4,"px)"),right:"-".concat(4,"px"),cursor:"e-resize"},bottomLeftAnchor:{bottom:"-".concat(4,"px"),left:"-".concat(4,"px"),cursor:"sw-resize"},bottomAnchor:{bottom:"-".concat(4,"px"),left:"calc(50% - ".concat(4,"px)"),cursor:"s-resize"},bottomRightAnchor:{bottom:"-".concat(4,"px"),right:"-".concat(4,"px"),cursor:"se-resize"}};function Nr(K,U){for(var sA in U)K.style[sA]=U[sA]}var gc=function(){function K(U,sA,k){k===void 0&&(k={keepRatio:!1,stopPropagation:!1,anchorMode:Ia.Both,canExceedContainer:!1}),this.logPrefix="[Resizable]",this.container=null,this.options={keepRatio:!1,stopPropagation:!1,anchorMode:Ia.Both,canExceedContainer:!1},this.callbacksMap=new Map,this.topLeftAnchor=null,this.topAnchor=null,this.topRightAnchor=null,this.leftAnchor=null,this.rightAnchor=null,this.bottomLeftAnchor=null,this.bottomAnchor=null,this.bottomRightAnchor=null,this.currentAnchor=null,this.resizeStartLeft=0,this.resizeStartTop=0,this.originLeft=0,this.originTop=0,this.originWidth=0,this.originHeight=0,this.resizeTarget=U,this.container=sA||document.body,this.options={keepRatio:!!k.keepRatio||!1,stopPropagation:!!k.stopPropagation||!1,anchorMode:k.anchorMode||Ia.Both,canExceedContainer:!!k.canExceedContainer||!1},this.mousedown=this.mousedown.bind(this),this.mousemove=this.mousemove.bind(this),this.mouseup=this.mouseup.bind(this),this.currentAnchor=null,this.createResizeAnchor(),this.resizeTarget.classList.add("trtc-resizable"),this.resizeTarget.style.position="absolute",this.resizeTarget.style.border="1px solid #3D7EFD",this.resizeTarget.style.boxSizing="border-box",this.initResizeEvent()}return K.prototype.createResizeAnchor=function(){var U,sA,k,x,iA,uA,_A,ie,ye=document.createElement("div");ye.className="trtc-resizable-resize-anchor ".concat(YE),Nr(ye,Object.assign({},hr.resizeAnchor,hr.topLeftAnchor)),this.topLeftAnchor=ye;var p=document.createElement("div");p.className="trtc-resizable-resize-anchor ".concat(Ju),Nr(p,Object.assign({},hr.resizeAnchor,hr.topAnchor)),this.topAnchor=p;var B=document.createElement("div");B.className="trtc-resizable-resize-anchor ".concat(qu),Nr(B,Object.assign({},hr.resizeAnchor,hr.topRightAnchor)),this.topRightAnchor=B;var M=document.createElement("div");M.className="trtc-resizable-resize-anchor ".concat(RI),Nr(M,Object.assign({},hr.resizeAnchor,hr.leftAnchor)),this.leftAnchor=M;var G=document.createElement("div");G.className="trtc-resizable-resize-anchor ".concat(dl),Nr(G,Object.assign({},hr.resizeAnchor,hr.rightAnchor)),this.rightAnchor=G;var O=document.createElement("div");O.className="trtc-resizable-resize-anchor ".concat(Pr),Nr(O,Object.assign({},hr.resizeAnchor,hr.bottomLeftAnchor)),this.bottomLeftAnchor=O;var z=document.createElement("div");z.className="trtc-resizable-resize-anchor ".concat(xr),Nr(z,Object.assign({},hr.resizeAnchor,hr.bottomAnchor)),this.bottomAnchor=z;var X=document.createElement("div");X.className="trtc-resizable-resize-anchor ".concat(dg),Nr(X,Object.assign({},hr.resizeAnchor,hr.bottomRightAnchor)),this.bottomRightAnchor=X,this.options.anchorMode!==Ia.Both&&this.options.anchorMode!==Ia.Edge||((U=this.resizeTarget)===null||U===void 0||U.appendChild(p),(sA=this.resizeTarget)===null||sA===void 0||sA.appendChild(M),(k=this.resizeTarget)===null||k===void 0||k.appendChild(G),(x=this.resizeTarget)===null||x===void 0||x.appendChild(z)),this.options.anchorMode!==Ia.Both&&this.options.anchorMode!==Ia.Corner||((iA=this.resizeTarget)===null||iA===void 0||iA.appendChild(ye),(uA=this.resizeTarget)===null||uA===void 0||uA.appendChild(B),(_A=this.resizeTarget)===null||_A===void 0||_A.appendChild(O),(ie=this.resizeTarget)===null||ie===void 0||ie.appendChild(X))},K.prototype.initResizeEvent=function(){var U,sA,k,x,iA,uA,_A,ie;(U=this.topLeftAnchor)===null||U===void 0||U.addEventListener("mousedown",this.mousedown,!1),(sA=this.topAnchor)===null||sA===void 0||sA.addEventListener("mousedown",this.mousedown,!1),(k=this.topRightAnchor)===null||k===void 0||k.addEventListener("mousedown",this.mousedown,!1),(x=this.leftAnchor)===null||x===void 0||x.addEventListener("mousedown",this.mousedown,!1),(iA=this.rightAnchor)===null||iA===void 0||iA.addEventListener("mousedown",this.mousedown,!1),(uA=this.bottomLeftAnchor)===null||uA===void 0||uA.addEventListener("mousedown",this.mousedown,!1),(_A=this.bottomAnchor)===null||_A===void 0||_A.addEventListener("mousedown",this.mousedown,!1),(ie=this.bottomRightAnchor)===null||ie===void 0||ie.addEventListener("mousedown",this.mousedown,!1)},K.prototype.mousedown=function(U){if(U.button===0){if(U.preventDefault(),this.options.stopPropagation&&U.stopPropagation(),this.currentAnchor=U.target,this.resizeStartLeft=U.screenX,this.resizeStartTop=U.screenY,document.defaultView&&this.resizeTarget){var sA=document.defaultView.getComputedStyle(this.resizeTarget);this.originTop=window.parseInt(sA.top),this.originLeft=window.parseInt(sA.left),this.originWidth=this.resizeTarget.offsetWidth,this.originHeight=this.resizeTarget.offsetHeight,Eg.debug("resize origin:",this.originTop,this.originLeft,this.originWidth,this.originHeight)}else Eg.debug("".concat(this.logPrefix,"mouseDown 'resizeTarget' is null"));document.addEventListener("mousemove",this.mousemove,!1),document.addEventListener("mouseup",this.mouseup,!1)}},K.prototype.mousemove=function(U){if(this.container&&this.resizeTarget&&this.currentAnchor){var sA,k=this.currentAnchor.classList[1],x=this.originLeft,iA=this.originTop,uA=this.originWidth,_A=this.originHeight;switch(k){case YE:iA=(sA=this._resizeTop(U)).top,_A=sA.height,x=(sA=this._resizeLeft(U)).left,uA=sA.width,this.options.keepRatio&&(uA/this.originWidth<_A/this.originHeight?(_A=uA*this.originHeight/this.originWidth,iA=this.originTop+this.originHeight-_A):(uA=_A*this.originWidth/this.originHeight,x=this.originLeft+this.originWidth-uA));break;case Ju:iA=(sA=this._resizeTop(U)).top,_A=sA.height,this.options.keepRatio&&((uA=this.originWidth*_A/this.originHeight)<20?(uA=20,_A=this.originHeight*uA/this.originWidth,iA=this.originTop+this.originHeight-_A):!this.options.canExceedContainer&&uA>this.container.offsetWidth-this.originLeft&&(uA=this.container.offsetWidth-this.originLeft,_A=this.originHeight*uA/this.originWidth,iA=this.originTop+this.originHeight-_A));break;case qu:iA=(sA=this._resizeTop(U)).top,_A=sA.height,uA=this._resizeRight(U),this.options.keepRatio&&(uA/this.originWidth<_A/this.originHeight?(_A=uA*this.originHeight/this.originWidth,iA=this.originTop+this.originHeight-_A):uA=_A*this.originWidth/this.originHeight);break;case RI:x=(sA=this._resizeLeft(U)).left,uA=sA.width,this.options.keepRatio&&((_A=this.originHeight*uA/this.originWidth)<20?(_A=20,uA=this.originWidth*_A/this.originHeight,x=this.originLeft+this.originWidth-uA):!this.options.canExceedContainer&&_A>this.container.offsetHeight-this.originTop&&(_A=this.container.offsetHeight-this.originTop,uA=this.originWidth*_A/this.originHeight,x=this.originLeft+this.originWidth-uA));break;case dl:uA=this._resizeRight(U),this.options.keepRatio&&((_A=uA*this.originHeight/this.originWidth)<20?uA=(_A=20)*this.originWidth/this.originHeight:!this.options.canExceedContainer&&_A>this.container.offsetHeight-this.originTop&&(uA=(_A=this.container.offsetHeight-this.originTop)*this.originWidth/this.originHeight));break;case Pr:_A=this._resizeBottom(U),x=(sA=this._resizeLeft(U)).left,uA=sA.width,this.options.keepRatio&&(uA/this.originWidth<_A/this.originHeight?_A=uA*this.originHeight/this.originWidth:(uA=_A*this.originWidth/this.originHeight,x=this.originLeft+this.originWidth-uA));break;case xr:_A=this._resizeBottom(U),this.options.keepRatio&&((uA=_A*this.originWidth/this.originHeight)<20?_A=(uA=20)*this.originHeight/this.originWidth:!this.options.canExceedContainer&&uA>this.container.offsetWidth-this.originLeft&&(_A=(uA=this.container.offsetWidth-this.originLeft)*this.originHeight/this.originWidth));break;case dg:_A=this._resizeBottom(U),uA=this._resizeRight(U),this.options.keepRatio&&(uA/this.originWidth<_A/this.originHeight?_A=uA*this.originHeight/this.originWidth:uA=_A*this.originWidth/this.originHeight)}this.resizeTarget.style.left="".concat(x,"px"),this.resizeTarget.style.top="".concat(iA,"px"),this.resizeTarget.style.height="".concat(_A,"px"),this.resizeTarget.style.width="".concat(uA,"px"),this.emit("resize",x,iA,uA,_A)}else Eg.debug("".concat(this.logPrefix,"mouseMove error. No valid inner info:"),this.container,this.resizeTarget,this.currentAnchor)},K.prototype._resizeLeft=function(U){var sA=U.screenX-this.resizeStartLeft,k=this.originLeft+sA,x=this.originWidth-sA;return!this.options.canExceedContainer&&k<0?(k=0,x=this.originWidth+this.originLeft):k>this.originLeft+this.originWidth-20&&(k=this.originLeft+this.originWidth-20,x=20),{left:k,width:x}},K.prototype._resizeTop=function(U){var sA=U.screenY-this.resizeStartTop,k=this.originTop+sA,x=this.originHeight-sA;return!this.options.canExceedContainer&&k<0?(k=0,x=this.originHeight+this.originTop):k>this.originTop+this.originHeight-20&&(k=this.originTop+this.originHeight-20,x=20),{top:k,height:x}},K.prototype._resizeRight=function(U){if(!this.container)return Eg.debug("".concat(this.logPrefix,"_resizeRight error. No container:"),this.container),0;var sA=U.screenX-this.resizeStartLeft,k=this.originWidth+sA;return k<20?k=20:!this.options.canExceedContainer&&k>this.container.offsetWidth-this.originLeft&&(k=this.container.offsetWidth-this.originLeft),k},K.prototype._resizeBottom=function(U){if(!this.container)return Eg.debug("".concat(this.logPrefix,"_resizeBottom error. No container:"),this.container),0;var sA=U.screenY-this.resizeStartTop,k=this.originHeight+sA;return k<20?k=20:!this.options.canExceedContainer&&k>this.container.offsetHeight-this.originTop&&(k=this.container.offsetHeight-this.originTop),k},K.prototype.mouseup=function(){document.removeEventListener("mousemove",this.mousemove,!1),document.removeEventListener("mouseup",this.mouseup,!1),this.currentAnchor=null,this.resizeStartLeft=0,this.resizeStartTop=0,this.originLeft=0,this.originTop=0,this.originWidth=0,this.originHeight=0},K.prototype.on=function(U,sA){var k=this.callbacksMap.get(U);k?k.push(sA):this.callbacksMap.set(U,[sA])},K.prototype.off=function(U,sA){var k=this.callbacksMap.get(U);k&&(k=k.filter(function(x){return x!=sA}),this.callbacksMap.set(U,k))},K.prototype.emit=function(U){for(var sA=[],k=1;kx?k:x,this.previewWidth=this.mixingVideoWidth*this.previewScale,this.previewHeight=this.mixingVideoHeight*this.previewScale,this.previewLeft=(U-this.previewWidth)/2,this.previewTop=(sA-this.previewHeight)/2}else console.debug("".concat(this.logPrefix,"calcPreviewScale failed, no HTML element to display"))},K.prototype.updateOverlay=function(){if(this.moveAndResizeOverlay){var U=void 0,sA=void 0,k=void 0,x=void 0;if(this.selectedMediaIndex>=0){var iA=this.mediaList[this.selectedMediaIndex],uA={left:iA.rect.left*this.previewScale,top:iA.rect.top*this.previewScale,right:iA.rect.right*this.previewScale,bottom:iA.rect.bottom*this.previewScale};U="".concat(uA.left+this.previewLeft,"px"),sA="".concat(uA.top+this.previewTop,"px"),k="".concat(uA.right-uA.left,"px"),x="".concat(uA.bottom-uA.top,"px");var _A=iA.interaction||{},ie=_A.showBorder!==!1,ye=_A.showResizeAnchors!==!1,p=_A.draggable!==!1,B=_A.canExceedCanvas!==!1;this.logger.debug("".concat(this.logPrefix,"updateOverlay: interaction config -"),{showBorder:ie,showResizeAnchors:ye,draggable:p,canExceedCanvas:B}),this.updateCanExceedContainer(B),this.moveAndResizeOverlay.style.display="block",this.moveAndResizeOverlay.style.border=ie?"1px solid #3D7EFD":"none",this.resizableHandler&&this.resizableHandler.setVisible(ye),this.movableHandler&&(this.logger.debug("".concat(this.logPrefix,"updateOverlay: setting movableHandler.setEnabled(").concat(p,")")),this.movableHandler.setEnabled(p))}else U="".concat(this.previewLeft,"px"),sA="".concat(this.previewTop,"px"),k="0px",x="0px",this.moveAndResizeOverlay.style.display="none";this.moveAndResizeOverlay.style.left=U,this.moveAndResizeOverlay.style.top=sA,this.moveAndResizeOverlay.style.width=k,this.moveAndResizeOverlay.style.height=x}},K.prototype.onMove=function(U,sA){var k;console.debug("".concat(this.logPrefix,"onMove: ").concat(U," ").concat(sA));var x=this.mediaList[this.selectedMediaIndex];if(x&&this.moveAndResizeOverlay){var iA={left:U-this.previewLeft,top:sA-this.previewTop,right:U-this.previewLeft+this.moveAndResizeOverlay.offsetWidth,bottom:sA-this.previewTop+this.moveAndResizeOverlay.offsetHeight};this.doAdsorption(iA);var uA={left:Math.round(iA.left/this.previewScale),top:Math.round(iA.top/this.previewScale),right:Math.round(iA.right/this.previewScale),bottom:Math.round(iA.bottom/this.previewScale)};(k=this.eventEmitter)===null||k===void 0||k.emit("onSourceMoved",eA({},x),uA)}else console.debug("".concat(this.logPrefix,"onMove no selected media"))},K.prototype.doAdsorption=function(U){var sA=this.BOUNDARY_ADSORPTION_THRESHOLD;Math.abs(U.left)ye&&(ye=B,ie=U[p])}return ie},K.prototype.emitOnSelect=function(U){var sA;if(U){for(var k=this.mediaList.length,x=0;x=p.rect.left&&_A<=p.rect.right&&ie>=p.rect.top&&ie<=p.rect.bottom&&((sA=p.interaction)===null||sA===void 0?void 0:sA.selectable)!==!1&&(this.clickedMediaSources.push(p),this.mediaList[this.selectedMediaIndex]&&p.id===this.mediaList[this.selectedMediaIndex].id&&(this.oldSelectedIndex=this.clickedMediaSources.length-1))}this.mousedownLeft=U.screenX,this.mousedownTop=U.screenY}this.clickedMediaSources.length>0?this.eventButton===2&&this.oldSelectedIndex===-1?(this.newSelected=this.getMaxZOrderMedia(this.clickedMediaSources),console.debug("".concat(this.logPrefix,"onContainerMousedown find clicked media source:"),this.newSelected),this.emitOnSelect(this.newSelected),this.clickedMediaSources.splice(0,this.clickedMediaSources.length)):(document.addEventListener("mousemove",this.onContainerMousemove,!1),document.addEventListener("mouseup",this.onContainerMouseup,!1)):(this.newSelected=null,console.debug("".concat(this.logPrefix,"onContainerMousedown find clicked media source:"),this.newSelected),this.emitOnSelect(null),this.mousedownLeft=null,this.mousedownTop=null,this.eventButton=null)}},K.prototype.onContainerMousemove=function(U){var sA;if(U.target&&this.container&&this.mousedownLeft!==null&&this.mousedownTop!==null){var k=U.screenX-this.mousedownLeft,x=U.screenY-this.mousedownTop;(Math.abs(k)>=5||Math.abs(x)>=5)&&(this.oldSelectedIndex>=0?(console.debug("".concat(this.logPrefix,"onContainerMousemove move or resize old selected media source, clear data:"),this.clickedMediaSources,this.oldSelectedIndex),this.clickedMediaSources.splice(0,this.clickedMediaSources.length),this.oldSelectedIndex=-1):this.clickedMediaSources.length>0&&(this.newSelected=this.getMaxZOrderMedia(this.clickedMediaSources),console.debug("".concat(this.logPrefix,"onContainerMousemove find clicked media source:"),this.newSelected),this.emitOnSelect(this.newSelected),this.clickedMediaSources.splice(0,this.clickedMediaSources.length),(sA=this.moveAndResizeOverlay)===null||sA===void 0||sA.dispatchEvent(new MouseEvent("mousedown",{screenX:this.mousedownLeft,screenY:this.mousedownTop,button:this.eventButton}))))}},K.prototype.onContainerMouseup=function(U){if(document.removeEventListener("mousemove",this.onContainerMousemove,!1),document.removeEventListener("mouseup",this.onContainerMouseup,!1),console.debug("".concat(this.logPrefix,"onContainerMouseup data:"),this.clickedMediaSources,this.oldSelectedIndex),U.target&&this.container){if(this.clickedMediaSources.length>0)if(this.oldSelectedIndex>=0){if(this.eventButton===0){var sA=(this.oldSelectedIndex+1)%this.clickedMediaSources.length;this.newSelected=this.clickedMediaSources[sA],console.debug("".concat(this.logPrefix,"onContainerMouseup find clicked media source:"),this.newSelected),this.emitOnSelect(this.newSelected)}}else this.newSelected=this.getMaxZOrderMedia(this.clickedMediaSources),console.debug("".concat(this.logPrefix,"onContainerMouseup find clicked media source:"),this.newSelected),this.emitOnSelect(this.newSelected)}else console.debug("".concat(this.logPrefix,"onContainerMouseup click outside of mixing video image")),this.emitOnSelect(null);this.mousedownLeft=null,this.mousedownTop=null,this.clickedMediaSources.splice(0,this.clickedMediaSources.length),this.oldSelectedIndex=-1,this.newSelected=null,this.eventButton=null},K.prototype.onRightButtonClicked=function(U){var sA;console.debug("".concat(this.logPrefix,"onRightButtonClicked:"),U.target,U.currentTarget,U.buttons),U.preventDefault(),(sA=this.eventEmitter)===null||sA===void 0||sA.emit("onRightButtonClicked",eA({},this.mediaList[this.selectedMediaIndex]))},K}(),Vl=function(){function K(U){if(this.logPrefix="[TRTCMediaMixingManager]",this.eventEmitter=new Je,this.publishParams={videoEncoderParams:{videoResolution:n.TRTCVideoResolution.TRTCVideoResolution_1280_720,resMode:n.TRTCVideoResolutionMode.TRTCVideoResolutionModeLandscape,videoFps:15,videoBitrate:1800},canvasColor:0},this.mediaMixingDesigner=null,this.sourceList=[],this.trtcSourceMap=new Map,this.mixVideoTrack=null,this.selectedSource=null,this.view=null,this.screensWithSystemAudio=new Set,K.mediaMixingManager)return K.mediaMixingManager;K.mediaMixingManager=this,this.logger=U.logger,this.trtc=U.trtc,this.trtcCloud=U.trtcCloud,this.onSourceSelected=this.onSourceSelected.bind(this),this.onSourceMoved=this.onSourceMoved.bind(this),this.onSourceResized=this.onSourceResized.bind(this),this.onRightButtonClicked=this.onRightButtonClicked.bind(this)}return K.prototype.destroy=function(){return IA(this,void 0,Promise,function(){var U,sA,k,x,iA;return oA(this,function(uA){switch(uA.label){case 0:this.view=null,uA.label=1;case 1:return uA.trys.push([1,3,,4]),[4,this.trtc.stopPlugin("VideoMixer")];case 2:return uA.sent(),[3,4];case 3:return U=uA.sent(),this.logger.error("".concat(this.logPrefix," destroy and stopPlugin error:"),U),[3,4];case 4:if(!(this.screensWithSystemAudio.size>0))return[3,12];uA.label=5;case 5:uA.trys.push([5,10,,11]),sA=0,k=Array.from(this.screensWithSystemAudio),uA.label=6;case 6:return sA1){var ye=[];this.queue=this.queue.filter(function(p,B){return B===0||p.functionName!==x||(ye.push(p),!1)}),ye.forEach(function(p){p.reject(new Error("aborted by newer task"))})}this.queue.push(_A)}return this.isRunning||this.callNext(),ie},K.prototype.shift=function(){return this.queue.shift()},K.prototype.callNext=function(){var U=this;if(!this.isRunning&&this.length!==0){var sA=this.queue[0],k=sA.fn,x=sA.args,iA=sA.context,uA=sA.resolve,_A=sA.reject;this.isRunning=!0,k.apply(iA,x).then(uA,_A).finally(function(){U.isRunning=!1,U.shift(),U.callNext()})}},K}(),wI=new WeakMap,ru=new WeakMap,Da=new WeakMap;function Cl(K,U){return U===void 0&&(U={}),function(sA,k,x){var iA=x.value,uA=U.deduplicate,_A=uA!==void 0&&uA;return x.value=function(){for(var ie=[],ye=0;ye0;if(U&&!this.isMessageListenerRegistered)return this.trtc.on(b.default.EVENT.REALTIME_TRANSCRIBER_MESSAGE,this.handleMessageEvent),void(this.isMessageListenerRegistered=!0);!U&&this.isMessageListenerRegistered&&(this.trtc.off(b.default.EVENT.REALTIME_TRANSCRIBER_MESSAGE,this.handleMessageEvent),this.isMessageListenerRegistered=!1)},K.prototype.log=function(){for(var U,sA,k=[],x=0;x0&&clearTimeout(gu),gu=window.setTimeout(function(){HE.apply(K,U),gu=-1},jr)}));var ju=new Map,SC=function(K){function U(k){k===void 0&&(k={});var x=K.call(this)||this;x._version="",x._frameWorkType=30,x._component=0,x._language=0,x._networkProxy={},x._localView=null,x._autoRecvAudio=!0,x._autoRecvVideo=!1,x._localTestView=null,x._isVideoPublish=!0,x._localRenderParams={rotation:n.TRTCVideoRotation.TRTCVideoRotation0,fillMode:n.TRTCVideoFillMode.TRTCVideoFillMode_Fill,mirrorType:n.TRTCVideoMirrorType.TRTCVideoMirrorType_Auto},x._encoderMirror=void 0,x._videoProfile={},x._isAudioPublish=!0,x._audioMuteType=!1,x._audioProfile=b.default.TYPE.AUDIO_PROFILE_STANDARD,x._captureVolume=100,x._playoutVolume=100,x._isSharingScreen=!1,x._remoteStreamConfig=new Map,x._remoteStreamMap=new Map,x._cameraList=[],x._microphoneList=[],x._speakerList=[],x._currentCamera={},x._currentMicrophone={},x._currentSpeaker={},x._currentCameraId="",x._currentMicrophoneId="",x._currentSpeakerId="",x._screenShareParams={option:{}},x._isMobile=iu,x._isFrontCamera=!0,x._cameraVideoTrack=null,x._smallStreamVideoProfile=void 0,x._qosPreference=void 0,x._defaultVideoProfile={width:640,height:480,frameRate:15,bitrate:900},x._defaultScreenProfile={width:1920,height:1080,frameRate:15,bitrate:1500},x._defaultSmallVideoProfile={width:160,height:120,frameRate:15,bitrate:200},x._isVirtualBackground=!1,x._isTestVirtualBackground=!1,x._isBeautyEnabled=!1,x._isTestBeautyEnabled=!1,x._remoteStatisticsUserIdList=[],x._hasJoinedRoom=!1,x._isExitingRoom=!1,x._version=DC;var iA=k.frameWorkType,uA=iA===void 0?30:iA,_A=k.component,ie=_A===void 0?0:_A,ye=k.language,p=ye===void 0?0:ye;return x._frameWorkType=uA,x._component=ie,x._language=p,x._trtc=b.default.create({enableSEI:U.enableSEI,assetsPath:U.assetsPath,enableVolumeControlInIOS:!0,plugins:[J.default,I.LEBPlayer,R.RealtimeTranscriber]}),x._testTrtc=b.default.create(),x._log=b.default._loggerManager,x.logger=new ac(au,{seq:Ku++}),x._echoCancellation=void 0,x._noiseSuppression=void 0,x._autoGainControl=void 0,x._addTRTCEvents(),x.handleDeviceChange=x.handleDeviceChange.bind(x),ju.set(x,{fn:x.handleDeviceChange,self:x}),x}var sA;return function(k,x){if(typeof x!="function"&&x!==null)throw new TypeError("Class extends value "+String(x)+" is not a constructor or null");function iA(){this.constructor=k}cA(k,x),k.prototype=x===null?Object.create(x):(iA.prototype=x.prototype,new iA)}(U,K),U.getPlugin=function(k){return k==="VirtualBackground"?C.VirtualBackground:k==="BasicBeauty"?m.BasicBeauty:k==="VideoMixer"?J.default:null},U.getTRTCShareInstance=function(k){return U.shareInstance||(U.shareInstance=new U(k)),U.shareInstance},U.setLogLevel=function(k,x){var iA,uA=((iA={})[n.TRTCLogLevel.TRTCLogLevelVerbose]=0,iA[n.TRTCLogLevel.TRTCLogLevelDebug]=1,iA[n.TRTCLogLevel.TRTCLogLevelInfo]=2,iA[n.TRTCLogLevel.TRTCLogLevelWarn]=3,iA[n.TRTCLogLevel.TRTCLogLevelError]=4,iA[n.TRTCLogLevel.TRTCLogLevelFatal]=4,iA[n.TRTCLogLevel.TRTCLogLevelNone]=5,iA),_A=uA[k];mn(_A)&&(_A=uA[n.TRTCLogLevel.TRTCLogLevelInfo]);var ie=!qi(x)||x;b.default.setLogLevel(_A,ie)},U.destroyTRTCShareInstance=function(){U.shareInstance&&(U.shareInstance._destroy(),U.shareInstance=null),Array.from(U.subCloudMap.keys()).forEach(function(k){return k._destroy()})},U.callExperimentalAPI=function(k){console.log("static ".concat(Vt,".callExperimentalAPI"),k);var x=tn(k);if(x!==k){var iA=x.api,uA=x.params;if(iA&&uA)try{switch(iA){case"enableSEI":U.enableSEI=uA.enable;break;case"setAssetsPath":U.assetsPath=uA.assetsPath}}catch(_A){throw _A}}},U.prototype.createSubCloud=function(){if(this!==U.shareInstance)return null;var k=new U;return this._inheritPropertiesToSubCloud(k),this._inheritEventsToSubCloud(k),U.subCloudMap.set(k,k),k},U.prototype.destroy=function(){this!==U.shareInstance?(U.subCloudMap.get(this)&&U.subCloudMap.delete(this),this._destroy()):U.destroyTRTCShareInstance()},U.prototype._destroy=function(){ju.delete(this),this.removeAllListeners(),this._trtc.off("*"),this._trtc.destroy(),this._trtc=null,this._testTrtc.off("*"),this._testTrtc.destroy(),this._testTrtc=null},U.prototype.getSDKVersion=function(){return this._version||""},U.prototype.enterRoom=function(k,x){return IA(this,void 0,Promise,function(){var iA,uA,_A,ie,ye,p,B,M,G,O,z,X,gA,DA,GA,KA,re,Qe;return oA(this,function(At){switch(At.label){case 0:if(iA=k.sdkAppId,uA=k.userId,_A=k.userSig,ie=k.roomId,ye=k.strRoomId,p=k.role,B=k.privateMapKey,M=k.businessInfo,G=k.enableAutoPlayDialog,O=k.proxy,z=k.streamId,X=k.userDefineRecordId,this.logger.update({sdkAppId:iA,userId:uA}),this.logger.info("".concat(Vt,".enterRoom with params: "),k,x),O&&(this._networkProxy=O),!(iA&&uA&&_A))return[3,5];At.label=1;case 1:return At.trys.push([1,3,,4]),gA={sdkAppId:iA,userId:uA,userSig:_A,roomId:ie,strRoomId:ye,role:vo[p],scene:mA[x],autoReceiveAudio:this._autoRecvAudio,autoReceiveVideo:this._autoRecvVideo,frameWorkType:this._frameWorkType,component:this._component,language:this._language},gA=B?eA(eA({},gA),{privateMapKey:B}):gA,gA=M?eA(eA({},gA),{businessInfo:M}):gA,DA=G||this._enableAutoPlayDialog,gA=qi(DA)?eA(eA({},gA),{enableAutoPlayDialog:DA}):gA,gA=this._networkProxy?eA(eA({},gA),{proxy:this._networkProxy}):gA,gA=z?eA(eA({},gA),{streamId:z}):gA,gA=X?eA(eA({},gA),{userDefineRecordId:X}):gA,gA=this._latencyLevel!==void 0?eA(eA({},gA),{latencyLevel:this._latencyLevel}):gA,GA=Zs(),[4,this._trtc.enterRoom(gA)];case 2:return At.sent(),this._hasJoinedRoom=!0,KA=Zs()-GA,this.emit("onEnterRoom",KA),[3,4];case 3:return re=At.sent(),Qe=(Qe=this._transformTRTCErrorCode(re,"enterRoom"))<0?Qe:-1,this.emit("onEnterRoom",Qe),this._callFunctionErrorManage(re,"enterRoom"),[3,4];case 4:return[3,6];case 5:this._emitError(vI),At.label=6;case 6:return[2]}})})},U.prototype.exitRoom=function(){return IA(this,void 0,Promise,function(){var k;return oA(this,function(x){switch(x.label){case 0:return x.trys.push([0,2,,3]),this.logger.info("".concat(Vt,".exitRoom")),this._isExitingRoom=!0,this._isSharingScreen&&this.stopScreenShare(),this.resetTRTCCloud(),this.stopLocalPreview(),this.stopLocalAudio(),[4,this._trtc.exitRoom()];case 1:return x.sent(),this._hasJoinedRoom=!1,this._isExitingRoom=!1,this._isVideoPublish=!0,this._isAudioPublish=!0,this.emit("onExitRoom",Il.exitRoom),[3,3];case 2:return k=x.sent(),this._callFunctionErrorManage(k,"exitRoom"),[3,3];case 3:return[2]}})})},U.prototype.switchRole=function(k){return IA(this,void 0,void 0,function(){var x;return oA(this,function(iA){switch(iA.label){case 0:this.logger.info("".concat(Vt,".switchRole with param: "),k),iA.label=1;case 1:return iA.trys.push([1,3,,4]),[4,this._trtc.switchRole(vo[k])];case 2:return iA.sent(),this.emit("onSwitchRole",0,"switch role success, role = ".concat(k,", ").concat(vo[k])),[3,4];case 3:return x=iA.sent(),this.emit("onSwitchRole",x?.getCode(),x.message),[3,4];case 4:return[2]}})})},U.prototype.setDefaultStreamRecvMode=function(k,x){return IA(this,void 0,void 0,function(){return oA(this,function(iA){return this.logger.info("".concat(Vt,".setDefaultStreamRecvMode with param: "),{autoRecvAudio:k,autoRecvVideo:x}),qi(k)&&(this._autoRecvAudio=k),qi(x)&&(this._autoRecvVideo=x),[2]})})},U.prototype.resetTRTCCloud=function(){this._setIsAudioPublish(!0),this._setAudioMuteType(!1),this._echoCancellation=void 0,this._noiseSuppression=void 0,this._autoGainControl=void 0,this._isVirtualBackground=!1,this._isTestVirtualBackground=!1,this._remoteStatisticsUserIdList=[],this._resetBeautyStyle()},U.prototype._updateLocalVideo=function(){return IA(this,void 0,void 0,function(){var k;return oA(this,function(x){switch(x.label){case 0:return x.trys.push([0,2,,3]),[4,this._trtc.updateLocalVideo(this._generateLocalVideoData())];case 1:return x.sent(),[3,3];case 2:if((k=x.sent()).code!==b.default.ERROR_CODE.OPERATION_ABORT)throw k;return[3,3];case 3:return[2]}})})},U.prototype._updateLocalTestVideo=function(){return IA(this,void 0,void 0,function(){var k;return oA(this,function(x){switch(x.label){case 0:return x.trys.push([0,2,,3]),[4,this._testTrtc.updateLocalVideo(this._generateLocalTestVideoData())];case 1:return x.sent(),[3,3];case 2:if((k=x.sent()).code!==b.default.ERROR_CODE.OPERATION_ABORT)throw k;return[3,3];case 3:return[2]}})})},U.prototype._updateLocalScreen=function(){return IA(this,void 0,void 0,function(){var k;return oA(this,function(x){switch(x.label){case 0:return x.trys.push([0,2,,3]),[4,this._trtc.updateScreenShare(this._getScreenShareParams())];case 1:return x.sent(),[3,3];case 2:if((k=x.sent()).code!==b.default.ERROR_CODE.OPERATION_ABORT)throw k;return[3,3];case 3:return[2]}})})},U.prototype._updateRemoteVideo=function(k,x){return IA(this,void 0,void 0,function(){var iA;return oA(this,function(uA){switch(uA.label){case 0:if(!this._hasJoinedRoom||this._isExitingRoom)return[2];uA.label=1;case 1:return uA.trys.push([1,3,,4]),[4,this._trtc.updateRemoteVideo(this._generateRemoteVideoData(k,x))];case 2:return uA.sent(),[3,4];case 3:if((iA=uA.sent()).code!==b.default.ERROR_CODE.OPERATION_ABORT)throw iA;return[3,4];case 4:return[2]}})})},U.prototype.startLocalPreview=function(){for(var k=[],x=0;x9)throw new Error("beautyLevel must be between 0 and 9");if(_A<0||_A>9)throw new Error("whitenessLevel must be between 0 and 9");if(ie<0||ie>9)throw new Error("ruddinessLevel must be between 0 and 9");z.label=1;case 1:return z.trys.push([1,8,,9]),B=_A/9,M=ie/9,(p=uA/9)===0&&B===0&&M===0?[4,k.stopPlugin(an)]:[3,3];case 2:return z.sent(),ye?this._isTestBeautyEnabled=!1:this._isBeautyEnabled=!1,[3,7];case 3:return G={beauty:p,brightness:B,ruddy:M},x?[3,5]:[4,k.startPlugin(an,G)];case 4:return z.sent(),ye?this._isTestBeautyEnabled=!0:this._isBeautyEnabled=!0,[3,7];case 5:return[4,k.updatePlugin(an,G)];case 6:z.sent(),z.label=7;case 7:return[3,9];case 8:throw O=z.sent(),ye?this.logger.error("".concat(Vt,".").concat("setTestBeautyStyle"," fail: "),O):this.logger.error("".concat(Vt,".").concat("setBeautyStyle"," fail: "),O),O;case 9:return[2]}})})},U.prototype._resetBeautyStyle=function(){return IA(this,void 0,void 0,function(){return oA(this,function(k){switch(k.label){case 0:return this._isBeautyEnabled?[4,this._trtc.stopPlugin(an)]:[3,2];case 1:k.sent(),this._isBeautyEnabled=!1,k.label=2;case 2:return this._isTestBeautyEnabled?[4,this._testTrtc.stopPlugin(an)]:[3,4];case 3:k.sent(),this._isTestBeautyEnabled=!1,k.label=4;case 4:return[2]}})})},U.prototype.getMicDevicesList=function(){return IA(this,void 0,Promise,function(){var k,x,iA;return oA(this,function(uA){switch(uA.label){case 0:this.logger.info("".concat(Vt,".getMicDevicesList")),uA.label=1;case 1:return uA.trys.push([1,5,,6]),[4,b.default.getMicrophoneList()];case 2:return k=uA.sent(),x=k.map(function(_A){return eA(eA({},_A),{deviceName:_A.label})}),this._microphoneList=k,JSON.stringify(this._currentMicrophone)!=="{}"?[3,4]:(this._currentMicrophone=this.getDefaultDeviceInfo(k),this._currentMicrophoneId=this._currentMicrophone.deviceId,[4,this.setCurrentMicDevice(this._currentMicrophoneId)]);case 3:uA.sent(),uA.label=4;case 4:return[2,Promise.resolve(x)];case 5:return iA=uA.sent(),this._callFunctionErrorManage(iA,"getMicDevicesList"),[2,Promise.resolve([])];case 6:return[2]}})})},U.prototype.setCurrentMicDevice=function(k){var x;return IA(this,void 0,Promise,function(){var iA;return oA(this,function(uA){switch(uA.label){case 0:this.logger.info("".concat(Vt,".setCurrentMicDevice with params: "),{micId:k}),uA.label=1;case 1:return uA.trys.push([1,4,,5]),k?(this._setCurrentMicrophoneId(k),[4,this._updateLocalAudio()]):[2,!1];case 2:return uA.sent(),[4,this._updateLocalTestAudio()];case 3:return uA.sent(),this._currentMicrophone=this._microphoneList.find(function(_A){return _A.deviceId===k})||{},[3,5];case 4:throw iA=uA.sent(),this._setCurrentMicrophoneId((x=this._currentMicrophone)===null||x===void 0?void 0:x.deviceId),this._callFunctionErrorManage(iA,"setCurrentMicDevice"),iA;case 5:return[2]}})})},U.prototype.getCurrentMicDevice=function(){this.logger.info("".concat(Vt,".getCurrentMicDevice"));var k=this._currentMicrophone,x=k.deviceId,iA=k.label,uA=k.kind,_A=k.groupId;return new Pt(x,iA,uA,iA,_A)},U.prototype.getSpeakerDevicesList=function(){return IA(this,void 0,Promise,function(){var k,x,iA;return oA(this,function(uA){switch(uA.label){case 0:this.logger.info("".concat(Vt,".getSpeakerDevicesList")),uA.label=1;case 1:return uA.trys.push([1,5,,6]),[4,b.default.getSpeakerList()];case 2:return k=uA.sent(),x=k.map(function(_A){return eA(eA({},_A),{deviceName:_A.label})}),this._speakerList=k,JSON.stringify(this._currentSpeaker)!=="{}"?[3,4]:(this._currentSpeaker=this.getDefaultDeviceInfo(k),this._currentSpeakerId=this._currentSpeaker.deviceId,[4,this.setCurrentSpeakerDevice(this._currentSpeakerId)]);case 3:uA.sent(),uA.label=4;case 4:return[2,Promise.resolve(x)];case 5:return iA=uA.sent(),this._callFunctionErrorManage(iA,"getSpeakerDevicesList"),[2,Promise.resolve([])];case 6:return[2]}})})},U.prototype.setCurrentSpeakerDevice=function(k){return IA(this,void 0,Promise,function(){var x;return oA(this,function(iA){switch(iA.label){case 0:this.logger.info("".concat(Vt,".setCurrentSpeakerDevice with params: "),{speakerId:k}),iA.label=1;case 1:return iA.trys.push([1,3,,4]),k?[4,b.default.setCurrentSpeaker(k)]:[2,!1];case 2:return iA.sent(),this._setCurrentSpeakerId(k),this._currentSpeaker=this._speakerList.find(function(uA){return uA.deviceId===k})||{},[3,4];case 3:throw x=iA.sent(),this._callFunctionErrorManage(x,"setCurrentSpeakerDevice"),x;case 4:return[2]}})})},U.prototype.getCurrentSpeakerDevice=function(){this.logger.info("".concat(Vt,".getCurrentSpeakerDevice"));var k=this._currentSpeaker,x=k.deviceId,iA=k.label,uA=k.kind,_A=k.groupId;return new Pt(x,iA,uA,iA,_A)},U.prototype.startCameraDeviceTest=function(k){return IA(this,void 0,void 0,function(){var x;return oA(this,function(iA){switch(iA.label){case 0:if(this.logger.info("".concat(Vt,".startCameraDeviceTest with params: "),k),!k)return[2];this._setLocalTestView(k),iA.label=1;case 1:return iA.trys.push([1,3,,7]),[4,this._testTrtc.startLocalVideo(this._generateLocalTestVideoData())];case 2:return iA.sent(),[3,7];case 3:return(x=iA.sent()).code!==b.default.ERROR_CODE.OPERATION_ABORT?[3,5]:[4,this._updateLocalTestVideo()];case 4:return iA.sent(),[3,6];case 5:throw this._callFunctionErrorManage(x,"startCameraDeviceTest"),x;case 6:return[3,7];case 7:return[2]}})})},U.prototype.stopCameraDeviceTest=function(){return IA(this,void 0,void 0,function(){return oA(this,function(k){switch(k.label){case 0:return this.logger.info("".concat(Vt,".stopCameraDeviceTest")),this._setLocalTestView(null),[4,this._testTrtc.stopLocalVideo()];case 1:return k.sent(),[2]}})})},U.prototype.startMicDeviceTest=function(k){return IA(this,void 0,void 0,function(){var x,iA=this;return oA(this,function(uA){switch(uA.label){case 0:this.logger.info("".concat(Vt,".startMicDeviceTest with params: "),k),uA.label=1;case 1:return uA.trys.push([1,3,,7]),[4,this._testTrtc.startLocalAudio(this._generateLocalTestAudioData())];case 2:return uA.sent(),[3,7];case 3:return(x=uA.sent()).code!==b.default.ERROR_CODE.OPERATION_ABORT?[3,5]:[4,this._updateLocalTestAudio()];case 4:return uA.sent(),[3,6];case 5:throw this._callFunctionErrorManage(x,"startMicDeviceTest"),x;case 6:return[3,7];case 7:return this._testTrtc.on(b.default.EVENT.AUDIO_VOLUME,function(_A){_A?.result.forEach(function(ie){var ye=ie.userId,p=ie.volume;ye===""&&iA.emit("onTestMicVolume",p)})}),[4,this._testTrtc.enableAudioVolumeEvaluation(k)];case 8:return uA.sent(),[2]}})})},U.prototype.stopMicDeviceTest=function(){return IA(this,void 0,void 0,function(){return oA(this,function(k){switch(k.label){case 0:return this.logger.info("".concat(Vt,".stopMicDeviceTest")),[4,this._testTrtc.stopLocalAudio()];case 1:return k.sent(),[2]}})})},U.prototype.callExperimentalAPI=function(k){return IA(this,void 0,void 0,function(){var x,iA,uA;return oA(this,function(_A){switch(_A.label){case 0:if(this.logger.info("".concat(Vt,".callExperimentalAPI"),k),(x=tn(k))===k)return[2];if(iA=x.api,uA=x.params,!iA||!uA)return[2];_A.label=1;case 1:switch(_A.trys.push([1,25,,26]),iA){case"setFramework":return[3,2];case"enableAudioAEC":return[3,3];case"enableAudioANS":return[3,4];case"enableAudioAGC":return[3,5];case"KeyMetricsStats":return[3,6];case"setNetworkProxy":return[3,7];case"enableVirtualBackground":return[3,8];case"enableTestVirtualBackground":return[3,10];case"enableTestBeautyStyle":return[3,12];case"setVideoEncodeParamEx":return[3,14];case"enableAutoPlayDialog":return[3,15];case"setAudienceLatencyLevel":return[3,16];case"switchPlaybackQuality":return[3,17];case"requestPictureInPicture":return[3,19];case"exitPictureInPicture":return[3,21]}return[3,23];case 2:return this._handleSetFrameWork(uA),[3,24];case 3:return this._echoCancellation=!!uA.enable,[3,24];case 4:return this._noiseSuppression=!!uA.enable,[3,24];case 5:return this._autoGainControl=!!uA.enable,[3,24];case 6:return this._handleKeyMetricsStats(uA),[3,24];case 7:return this._networkProxy=uA,[3,24];case 8:return[4,this.setVirtualBackground(uA)];case 9:return _A.sent(),[3,24];case 10:return[4,this.setTestVirtualBackground(uA)];case 11:return _A.sent(),[3,24];case 12:return[4,this.setTestBeautyStyle(uA.style,uA.beautyLevel,uA.whitenessLevel,uA.ruddinessLevel)];case 13:return _A.sent(),[3,24];case 14:return this._setVideoEncodeParamEx(uA),[3,24];case 15:return this._enableAutoPlayDialog=!!uA.enable,[3,24];case 16:return this._latencyLevel=uA.latencyLevel,[3,24];case 17:return[4,this._switchPlaybackQuality(uA)];case 18:return _A.sent(),[3,24];case 19:return[4,this._requestPictureInPicture()];case 20:return _A.sent(),[3,24];case 21:return[4,this._exitPictureInPicture()];case 22:return _A.sent(),[3,24];case 23:return[3,24];case 24:return[3,26];case 25:throw _A.sent();case 26:return[2]}})})},U.prototype._handleSetFrameWork=function(k){var x=k.frameWork,iA=k.component,uA=k.language;Fr(x)&&(this._frameWorkType=x),Fr(iA)&&(this._component=iA),Fr(uA)&&(this._language=uA)},U.prototype._handleKeyMetricsStats=function(k){var x=k.key,iA=k.opt,uA=k.value,_A=k.version,ie=iA===xs;b.default._addKVStat({type:iA,key:x,value:uA,version:_A,useUV:ie,base:100})},U.prototype._setVideoEncodeParamEx=function(k){return IA(this,void 0,void 0,function(){return oA(this,function(x){switch(x.label){case 0:switch(k.streamType){case n.TRTCVideoStreamType.TRTCVideoStreamTypeBig:return[3,1];case n.TRTCVideoStreamType.TRTCVideoStreamTypeSub:return[3,3]}return[3,5];case 1:return[4,this.setVideoEncoderParam(k)];case 2:case 4:return x.sent(),[3,6];case 3:return[4,this.setSubStreamEncoderParam(k)];case 5:return[3,6];case 6:return[2]}})})},U.prototype._switchPlaybackQuality=function(k){return IA(this,void 0,void 0,function(){var x,iA,uA,_A,ie,ye,p,B;return oA(this,function(M){switch(M.label){case 0:if(iA=(x=k||{}).quality,uA=x.stream_list,_A=uA===void 0?[]:uA,!iA||_A.length===0)return[2];for(ie=null,ye=0,p=_A;ye1&&x[1]),height:+(x.length>2&&x[2])}},U.prototype._getTRTCVideoProfile=function(k,x){x===void 0&&(x={});var iA=x.videoWidth,uA=x.videoHeight,_A=x.videoResolution,ie=x.videoFps,ye=x.videoBitrate,p=x.resMode,B=x.resolutionMode,M={};switch(k){case n.TRTCVideoStreamType.TRTCVideoStreamTypeSub:M=this._defaultScreenProfile;break;case n.TRTCVideoStreamType.TRTCVideoStreamTypeSmall:M=this._defaultSmallVideoProfile;break;case n.TRTCVideoStreamType.TRTCVideoStreamTypeBig:default:M=this._defaultVideoProfile}if(mn(_A))mn(iA)||(M.width=iA),mn(uA)||(M.height=uA);else{var G=this._getTRTCResolution(_A);M.width=G.width,M.height=G.height}if(!mn(p)&&p===n.TRTCVideoResolutionMode.TRTCVideoResolutionModePortrait||!mn(B)&&B===n.TRTCVideoResolutionMode.TRTCVideoResolutionModePortrait){var O=M.height,z=M.width;M.width=O,M.height=z}return ie&&(M.frameRate=ie),ye&&(M.bitrate=ye),M},U.prototype._getTRTCStreamType=function(k){var x;return((x={})[n.TRTCVideoStreamType.TRTCVideoStreamTypeBig]=b.default.TYPE.STREAM_TYPE_MAIN,x[n.TRTCVideoStreamType.TRTCVideoStreamTypeSmall]=b.default.TYPE.STREAM_TYPE_MAIN,x[n.TRTCVideoStreamType.TRTCVideoStreamTypeSub]=b.default.TYPE.STREAM_TYPE_SUB,x)[k]},U.prototype._getTRTCFillMode=function(k){var x;return((x={})[n.TRTCVideoFillMode.TRTCVideoFillMode_Fill]=ll.COVER,x[n.TRTCVideoFillMode.TRTCVideoFillMode_Fit]=ll.CONTAIN,x)[k]},U.prototype._getTRTCCloudVideoFillMode=function(k){var x;return((x={})[ll.COVER]=n.TRTCVideoFillMode.TRTCVideoFillMode_Fill,x[ll.CONTAIN]=n.TRTCVideoFillMode.TRTCVideoFillMode_Fit,x)[k]},U.prototype._getTRTCCloudMirrorType=function(k){return k===!0?n.TRTCVideoMirrorType.TRTCVideoMirrorType_Enable:n.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable},U.prototype._getLocalRenderMirror=function(k){var x;return k===n.TRTCVideoMirrorType.TRTCVideoMirrorType_Auto?!this._getIsMobile()||this._getIsFrontCamera():((x={})[n.TRTCVideoMirrorType.TRTCVideoMirrorType_Enable]=!0,x[n.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable]=!1,x)[k]},U.prototype._getTRTCLocalMirror=function(k,x){var iA=this._getLocalRenderMirror(k);return mn(x)?!!iA&&"both":iA&&x?"both":iA&&!x?"view":!iA&&x?"publish":!(!iA&&!x)&&"view"},U.prototype._getTRTCRemoteMirror=function(k){var x;return((x={})[n.TRTCVideoMirrorType.TRTCVideoMirrorType_Auto]=!1,x[n.TRTCVideoMirrorType.TRTCVideoMirrorType_Enable]=!0,x[n.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable]=!1,x)[k]},U.prototype._getTRTCQosPreference=function(k){var x;return((x={})[n.TRTCVideoQosPreference.TRTCVideoQosPreferenceSmooth]=b.default.TYPE.QOS_PREFERENCE_SMOOTH,x[n.TRTCVideoQosPreference.TRTCVideoQosPreferenceClear]=b.default.TYPE.QOS_PREFERENCE_CLEAR,x)[k]},U.prototype._getTRTCAudioQuality=function(k){var x;return((x={})[n.TRTCAudioQuality.TRTCAudioQualitySpeech]=b.default.TYPE.AUDIO_PROFILE_STANDARD,x[n.TRTCAudioQuality.TRTCAudioQualityDefault]=b.default.TYPE.AUDIO_PROFILE_STANDARD,x[n.TRTCAudioQuality.TRTCAudioQualityMusic]=b.default.TYPE.AUDIO_PROFILE_HIGH_STEREO,x)[k]},U.prototype._getTRTCCloudDeviceType=function(k){return{camera:n.TRTCDeviceType.TRTCDeviceTypeCamera,microphone:n.TRTCDeviceType.TRTCDeviceTypeMic,speaker:n.TRTCDeviceType.TRTCDeviceTypeSpeaker}[k]},U.prototype._getTRTCCloudDeviceState=function(k){return{add:n.TRTCDeviceState.TRTCDeviceStateAdd,remove:n.TRTCDeviceState.TRTCDeviceStateRemove,active:n.TRTCDeviceState.TRTCDeviceStateActive}[k]},U.prototype._getTRTCCloudQuality=function(k){return[n.TRTCQuality.TRTCQuality_Unknown,n.TRTCQuality.TRTCQuality_Excellent,n.TRTCQuality.TRTCQuality_Good,n.TRTCQuality.TRTCQuality_Poor,n.TRTCQuality.TRTCQuality_Bad,n.TRTCQuality.TRTCQuality_Vbad,n.TRTCQuality.TRTCQuality_Down][k]},U.prototype._generateLocalVideoData=function(){var k={view:this._getLocalView(),publish:this._getIsVideoPublish(),option:{profile:this._getVideoProfile(),small:this._getSmallStreamVideoProfile()||!1,mirror:this._getTRTCLocalMirror(this._localRenderParams.mirrorType,this._encoderMirror),fillMode:this._getTRTCFillMode(this._localRenderParams.fillMode)}};return this._cameraVideoTrack?k&&Object.assign(k.option,{videoTrack:this._cameraVideoTrack}):this._getIsMobile()?k&&Object.assign(k.option,{useFrontCamera:this._getIsFrontCamera()}):k&&Object.assign(k.option,{cameraId:this._getCurrentCameraId()}),this._getQosPreference()&&k&&Object.assign(k.option,{qosPreference:this._getQosPreference()}),k},U.prototype._generateLocalTestVideoData=function(){var k={view:this._getLocalTestView(),publish:!1,option:{profile:this._getVideoProfile(),mirror:this._getTRTCLocalMirror(this._localRenderParams.mirrorType,this._encoderMirror),fillMode:this._getTRTCFillMode(this._localRenderParams.fillMode)}};return this._getIsMobile()?k&&Object.assign(k.option,{useFrontCamera:this._getIsFrontCamera()}):k&&Object.assign(k.option,{cameraId:this._getCurrentCameraId()}),k},U.prototype._generateLocalAudioData=function(){var k={publish:this._getIsAudioPublish(),mute:this._getAudioMuteType(),muteKeepVolumeDetection:!0,option:{microphoneId:this._getCurrentMicrophoneId(),profile:this._getAudioProfile(),captureVolume:this._getCaptureVolume()}};return qi(this._echoCancellation)&&(k.option.echoCancellation=this._echoCancellation),qi(this._autoGainControl)&&(k.option.autoGainControl=this._autoGainControl),qi(this._noiseSuppression)&&(k.option.noiseSuppression=this._noiseSuppression),k},U.prototype._generateLocalTestAudioData=function(){return{publish:!1,option:{microphoneId:this._getCurrentMicrophoneId(),profile:this._getAudioProfile()}}},U.prototype._generateRemoteVideoData=function(k,x){return Is(this._remoteStreamConfig.get("".concat(k,"_").concat(this._getTRTCStreamType(x))))},U.prototype._addTRTCEvents=function(){var k=this;this._trtc.on(b.default.EVENT.ERROR,function(x){x&&k.emit("onError",x.code,x.message)}),this._trtc.on(b.default.EVENT.REMOTE_USER_ENTER,function(x){x?.userId&&k.emit("onRemoteUserEnterRoom",x.userId)}),this._trtc.on(b.default.EVENT.REMOTE_USER_EXIT,function(x){x?.userId&&k.emit("onRemoteUserLeaveRoom",x.userId)}),this._trtc.on(b.default.EVENT.REMOTE_AUDIO_AVAILABLE,function(x){x?.userId&&k.emit("onUserAudioAvailable",x.userId,!0)}),this._trtc.on(b.default.EVENT.REMOTE_AUDIO_UNAVAILABLE,function(x){x?.userId&&k.emit("onUserAudioAvailable",x.userId,!1)}),this._trtc.on(b.default.EVENT.REMOTE_VIDEO_AVAILABLE,function(x){k._emitVideoAvailable(x,!0)}),this._trtc.on(b.default.EVENT.REMOTE_VIDEO_UNAVAILABLE,function(x){k._emitVideoAvailable(x,!1)}),this._trtc.on(b.default.EVENT.AUDIO_VOLUME,function(x){x?.result&&k.emit("onUserVoiceVolume",x?.result,(x?.result||[]).length)}),this._trtc.on(b.default.EVENT.KICKED_OUT,function(x){var iA={banned:Il.banned,room_disband:Il.roomDisband};Fr(iA[x.reason])&&k.emit("onExitRoom",iA[x.reason])}),this._trtc.on(b.default.EVENT.NETWORK_QUALITY,function(x){var iA=x.uplinkNetworkQuality,uA=x.downlinkNetworkQuality,_A=new Ro("",k._getTRTCCloudQuality(iA)),ie=[];k._remoteStatisticsUserIdList.length>0&&(ie=k._remoteStatisticsUserIdList.map(function(ye){return new Ro(ye,k._getTRTCCloudQuality(uA))})),k.emit("onNetworkQuality",_A,ie)}),this._trtc.on(b.default.EVENT.AUTOPLAY_FAILED,function(x){k.emit("onAutoPlayFailed",x)}),this._trtc.on(b.default.EVENT.SEI_MESSAGE,function(x){if(x.data&&typeof x.data=="object"&&x.data instanceof ArrayBuffer){for(var iA=new Uint8Array(x.data),uA="",_A=0;_A0?B.video.map(function(DA){var GA=new no;return GA.width=DA.width,GA.height=DA.height,GA.frameRate=DA.frameRate,GA.videoBitrate=DA.bitrate,GA.audioBitrate=B.audio.bitrate||0,GA.streamType=G[DA.videoType],GA}):[];if(O.length===0&&B.audio.bitrate>0){var z=new no;z.audioBitrate=B.audio.bitrate||0,O.push(z)}var X=[];M.forEach(function(DA){var GA=[],KA=DA.userId,re=DA.audio.bitrate;if(DA.video&&DA.video.forEach(function(At){var lt=new Ri;lt.userId=KA,lt.width=At.width,lt.height=At.height,lt.frameRate=At.frameRate,lt.videoBitrate=At.bitrate,lt.audioBitrate=re||0,lt.streamType=G[At.videoType],GA.push(lt)}),GA.length===0){var Qe=new Ri;Qe.userId=KA,Qe.audioBitrate=re||0,GA.push(Qe)}X.push.apply(X,GA)});var gA=new pn;gA.upLoss=_A,gA.downLoss=ie,gA.rtt=uA,gA.sentBytes=ye,gA.receivedBytes=p,gA.localStatisticsArray=O,gA.localStatisticsArraySize=O.length,gA.remoteStatisticsArray=X,gA.remoteStatisticsArraySize=X.length,k.emit("onStatistics",gA)}),this._trtc.on(b.default.EVENT.SCREEN_SHARE_STOPPED,function(){k.emit("onScreenCaptureStopped",0),k._clearScreenShareParams(),k._isSharingScreen=!1}),this._trtc.on(b.default.EVENT.PUBLISH_STATE_CHANGED,function(x){var iA=x.mediaType;x.state==="started"&&(iA==="audio"?k.emit("onSendFirstLocalAudioFrame"):iA==="video"?k.emit("onSendFirstLocalVideoFrame",n.TRTCVideoStreamType.TRTCVideoStreamTypeBig):iA==="screen"&&k.emit("onSendFirstLocalVideoFrame",n.TRTCVideoStreamType.TRTCVideoStreamTypeSub))}),this._trtc.on(b.default.EVENT.FIRST_VIDEO_FRAME,function(x){var iA=x.userId,uA=x.streamType,_A=x.width,ie=x.height;k.emit("onFirstVideoFrame",iA,uA,_A,ie)}),this._trtc.on(b.default.EVENT.AUDIO_PLAY_STATE_CHANGED,function(x){var iA=x.userId;x.state==="PLAYING"&&k.emit("onFirstAudioFrame",iA)}),this._trtc.on(b.default.EVENT.DEVICE_CHANGED,function(x){var iA=x.type,uA=x.device,_A=x.action,ie=uA.deviceId;if(_A==="active"){switch(iA){case"camera":k._currentCameraId=ie,k._currentCamera=uA;break;case"microphone":k._currentMicrophoneId=ie,k._currentMicrophone=uA;break;case"speaker":k._currentSpeakerId=ie,k._currentSpeaker=uA}k.emitOnDeviceChange(ie,k._getTRTCCloudDeviceType(iA),k._getTRTCCloudDeviceState(_A))}}),this._trtc.on(b.default.EVENT.CUSTOM_MESSAGE,function(x){x&&k.emit("onRecvCustomCmdMsg",x.userId,x.cmdId,x.seq,x?.data)}),this._trtc.on(b.default.EVENT.CONNECTION_STATE_CHANGED,function(x){k._hasJoinedRoom&&!k._isExitingRoom&&(x.prevState==="CONNECTED"&&x.state==="DISCONNECTED"?k.emit("onConnectionLost"):x.prevState==="DISCONNECTED"&&x.state==="CONNECTING"?k.emit("onTryToReconnect"):x.prevState==="CONNECTING"&&x.state==="CONNECTED"&&k.emit("onConnectionRecovery"))}),this._trtc.on(b.default.EVENT.PICTURE_IN_PICTURE_STATE_CHANGED,function(x){k.emit("onPictureInPictureStateChanged",x)})},U.prototype._removeTRTCEvents=function(){this._trtc.off("*")},U.prototype._emitVideoAvailable=function(k,x){var iA=k.userId,uA=k.streamType;x?this._remoteStreamMap.set("".concat(iA,"_").concat(uA),!0):this._remoteStreamMap.delete("".concat(iA,"_").concat(uA)),uA===b.default.TYPE.STREAM_TYPE_SUB?iA&&this.emit("onUserSubStreamAvailable",iA,x):iA&&this.emit("onUserVideoAvailable",iA,x)},U.prototype._setLocalView=function(k){this._localView=k},U.prototype._getLocalView=function(){return this._localView},U.prototype._setIsMobile=function(k){this._isMobile=k},U.prototype._getIsMobile=function(){return this._isMobile},U.prototype._setIsFrontCamera=function(k){this._isFrontCamera=k},U.prototype._getIsFrontCamera=function(){return this._isFrontCamera},U.prototype._getSmallStreamVideoProfile=function(){return this._smallStreamVideoProfile},U.prototype._setSmallStreamVideoProfile=function(k){this._smallStreamVideoProfile=k},U.prototype._setIsVideoPublish=function(k){this._isVideoPublish=k},U.prototype._getIsVideoPublish=function(){return this._isVideoPublish},U.prototype._setVideoProfile=function(k){this._videoProfile=k},U.prototype._getVideoProfile=function(){return this._videoProfile},U.prototype._setQosPreference=function(k){this._qosPreference=k},U.prototype._getQosPreference=function(){return this._qosPreference},U.prototype._setLocalTestView=function(k){this._localTestView=k},U.prototype._getLocalTestView=function(){return this._localTestView},U.prototype._setScreenShareParams=function(k){var x=k.view,iA=k.systemAudio,uA=k.fillMode,_A=k.profile,ie=k.videoTrack,ye=k.qosPreference;mn(x)||(this._screenShareParams.view=x),mn(iA)||(this._screenShareParams.option.systemAudio=iA),mn(uA)||(this._screenShareParams.option.fillMode=uA),mn(_A)||(this._screenShareParams.option.profile=_A),mn(ie)||(this._screenShareParams.option.videoTrack=ie),mn(ye)||(this._screenShareParams.option.qosPreference=ye),mn(k.streamType)||(this._screenShareParams.streamType=this._getTRTCStreamType(k.streamType))},U.prototype._clearScreenShareParams=function(){var k,x,iA,uA,_A;!((k=this._screenShareParams)===null||k===void 0)&&k.view&&delete this._screenShareParams.view,!((iA=(x=this._screenShareParams)===null||x===void 0?void 0:x.option)===null||iA===void 0)&&iA.systemAudio&&delete this._screenShareParams.option.systemAudio,!((_A=(uA=this._screenShareParams)===null||uA===void 0?void 0:uA.option)===null||_A===void 0)&&_A.videoTrack&&delete this._screenShareParams.option.videoTrack},U.prototype._getScreenShareParams=function(){return this._screenShareParams},U.prototype._setIsAudioPublish=function(k){this._isAudioPublish=k},U.prototype._getIsAudioPublish=function(){return this._isAudioPublish},U.prototype._setAudioMuteType=function(k){this._audioMuteType=k},U.prototype._getAudioMuteType=function(){return this._audioMuteType},U.prototype._setAudioProfile=function(k){this._audioProfile=k},U.prototype._getAudioProfile=function(){return this._audioProfile},U.prototype._getCaptureVolume=function(){return this._captureVolume},U.prototype._setCaptureVolume=function(k){this._captureVolume=k},U.prototype._setCurrentCameraId=function(k){this._currentCameraId=k},U.prototype._getCurrentCameraId=function(){return this._currentCameraId},U.prototype._setCurrentMicrophoneId=function(k){this._currentMicrophoneId=k},U.prototype._getCurrentMicrophoneId=function(){return this._currentMicrophoneId},U.prototype._setCurrentSpeakerId=function(k){this._currentSpeakerId=k},U.prototype._getCurrentSpeakerId=function(){return this._currentSpeakerId},U.prototype._setRemoteStreamConfig=function(k,x,iA){var uA=this._remoteStreamConfig.get("".concat(k,"_").concat(this._getTRTCStreamType(x)));uA||(uA={userId:k,streamType:this._getTRTCStreamType(x),option:{mirror:this._getTRTCRemoteMirror(n.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable),fillMode:this._getTRTCFillMode(n.TRTCVideoFillMode.TRTCVideoFillMode_Fit)}});var _A=iA.view,ie=iA.mirrorType,ye=iA.fillMode,p=iA.small;mn(_A)||(uA.view=_A),mn(ie)||(uA.option.mirror=this._getTRTCRemoteMirror(ie)),mn(ye)||(uA.option.fillMode=this._getTRTCFillMode(ye)),mn(p)||(uA.option.small=p),this._remoteStreamConfig.set("".concat(k,"_").concat(this._getTRTCStreamType(x)),uA)},U.prototype._inheritPropertiesToSubCloud=function(k){k._frameWorkType=this._frameWorkType,k._component=this._component,k._language=this._language,k._networkProxy=eA({},this._networkProxy),k._latencyLevel=this._latencyLevel,k._enableAutoPlayDialog=this._enableAutoPlayDialog},U.prototype._inheritEventsToSubCloud=function(k){var x=this;k._trtc.on(b.default.EVENT.AUTOPLAY_FAILED,function(iA){x.emit("onAutoPlayFailed",iA)}),k._trtc.on(b.default.EVENT.PICTURE_IN_PICTURE_STATE_CHANGED,function(iA){x.emit("onPictureInPictureStateChanged",iA)})},U.prototype.handleDeviceChange=function(){return IA(this,void 0,void 0,function(){var k=this;return oA(this,function(x){return b.default.getCameraList().then(function(iA){return IA(k,void 0,void 0,function(){return oA(this,function(uA){switch(uA.label){case 0:return this._cameraList.length===iA.length?[2]:[4,this.deviceChangeManage(this._cameraList,iA,n.TRTCDeviceType.TRTCDeviceTypeCamera)];case 1:return uA.sent(),this._cameraList=iA,[2]}})})}),b.default.getMicrophoneList().then(function(iA){return IA(k,void 0,void 0,function(){return oA(this,function(uA){switch(uA.label){case 0:return[4,this.deviceChangeManage(this._microphoneList,iA,n.TRTCDeviceType.TRTCDeviceTypeMic)];case 1:return uA.sent(),this._microphoneList=iA,[2]}})})}),b.default.getSpeakerList().then(function(iA){return IA(k,void 0,void 0,function(){return oA(this,function(uA){switch(uA.label){case 0:return[4,this.deviceChangeManage(this._speakerList,iA,n.TRTCDeviceType.TRTCDeviceTypeSpeaker)];case 1:return uA.sent(),this._speakerList=iA,[2]}})})}),[2]})})},U.prototype.isSameDevice=function(k,x){var iA=k&&k.deviceId&&k.groupId&&k.label,uA=x&&x.deviceId&&x.groupId&&x.label;return!(!iA||!uA)&&k.deviceId===x.deviceId&&k.groupId===x.groupId&&k.label===x.label},U.prototype.deviceChangeManage=function(k,x,iA){return IA(this,void 0,void 0,function(){var uA,_A,ie,ye,p;return oA(this,function(B){switch(B.label){case 0:return uA=void 0,k.length!==x.length&&(_A=(x||[]).map(function(M){return M.deviceId}),ie=new Pt,k.length>x.length?(ie=k.filter(function(M){return!_A.includes(M.deviceId)})[0]||{},uA=n.TRTCDeviceState.TRTCDeviceStateRemove):(_A=(k||[]).map(function(M){return M.deviceId}),ie=x.filter(function(M){return!_A.includes(M.deviceId)})[0]||{},uA=n.TRTCDeviceState.TRTCDeviceStateAdd),ye=ie.deviceId,this.emitOnDeviceChange(ye,iA,uA)),p=this.getDefaultDeviceInfo(x),iA!==n.TRTCDeviceType.TRTCDeviceTypeCamera||uA!==n.TRTCDeviceState.TRTCDeviceStateRemove?[3,3]:this.isSameDevice(this._currentCamera,p)?[2]:p.deviceId?[4,this.autoChangeDevice(iA,p)]:[3,2];case 1:B.sent(),B.label=2;case 2:B.label=3;case 3:return iA!==n.TRTCDeviceType.TRTCDeviceTypeMic?[3,6]:this.isSameDevice(this._currentMicrophone,p)?[2]:p.deviceId?[4,this.autoChangeDevice(iA,p)]:[3,5];case 4:B.sent(),B.label=5;case 5:B.label=6;case 6:return iA!==n.TRTCDeviceType.TRTCDeviceTypeSpeaker?[3,9]:this.isSameDevice(this._currentSpeaker,p)?[2]:p.deviceId?[4,this.autoChangeDevice(iA,p)]:[3,8];case 7:B.sent(),B.label=8;case 8:B.label=9;case 9:return[2]}})})},U.prototype.getDefaultDeviceInfo=function(k){var x=new Pt;if(k.length===0)return x;var iA=k.filter(function(uA){return uA.deviceId==="default"});return x=iA.length>0?iA[0]:k[0]},U.prototype.autoChangeDevice=function(k,x){return IA(this,void 0,void 0,function(){var iA,uA,_A;return oA(this,function(ie){switch(ie.label){case 0:return iA=x.deviceId,k!==n.TRTCDeviceType.TRTCDeviceTypeCamera?[3,6]:(this._setCurrentCameraId(iA),[4,this._updateLocalVideo()]);case 1:ie.sent(),ie.label=2;case 2:return ie.trys.push([2,4,,5]),[4,this._testTrtc.updateLocalVideo({option:{cameraId:iA}})];case 3:return ie.sent(),[3,5];case 4:return uA=ie.sent(),console.log("testTRTC error",JSON.stringify(uA)),uA.code,b.default.ERROR_CODE.OPERATION_ABORT,[3,5];case 5:this._currentCameraId=iA,this._currentCamera=x,this.emitOnDeviceChange(iA,k,n.TRTCDeviceState.TRTCDeviceStateActive),ie.label=6;case 6:return k!==n.TRTCDeviceType.TRTCDeviceTypeMic?[3,12]:(this._setCurrentMicrophoneId(iA),[4,this._updateLocalAudio()]);case 7:ie.sent(),ie.label=8;case 8:return ie.trys.push([8,10,,11]),[4,this._testTrtc.updateLocalAudio({option:{microphoneId:iA}})];case 9:return ie.sent(),[3,11];case 10:return _A=ie.sent(),console.log("testTRTC error",JSON.stringify(_A)),_A.code,b.default.ERROR_CODE.OPERATION_ABORT,[3,11];case 11:this._currentMicrophoneId=iA,this._currentMicrophone=x,this.emitOnDeviceChange(iA,k,n.TRTCDeviceState.TRTCDeviceStateActive),ie.label=12;case 12:return k!==n.TRTCDeviceType.TRTCDeviceTypeSpeaker?[3,14]:[4,b.default.setCurrentSpeaker(iA)];case 13:ie.sent(),this._currentSpeakerId=iA,this._currentSpeaker=x,this.emitOnDeviceChange(iA,k,n.TRTCDeviceState.TRTCDeviceStateActive),ie.label=14;case 14:return[2]}})})},U.prototype.emitOnDeviceChange=function(k,x,iA){this.emit("onDeviceChange",k,x,iA)},U.prototype.getMediaMixingManager=function(){return new Vl({logger:this.logger,trtc:this._trtc,trtcCloud:this})},U.prototype.getAITranscriberManager=function(){return new VE({logger:this.logger,trtc:this._trtc})},U.shareInstance=null,U.subCloudMap=new Map,U.enableSEI=!1,U.assetsPath="",CA([(sA="exitRoom",function(k,x,iA){var uA=iA.value;return iA.value=function(){for(var _A,ie,ye,p,B=[],M=0;Mq.length)&&(QA=q.length);for(var yA=0,NA=new Array(QA);yA=0;--Es){var un=this.tryEntries[Es],hg=un.completion;if(un.tryLoc==="root")return _o("end");if(un.tryLoc<=this.prev){var Hl=ee.call(un,"catchLoc"),Dd=ee.call(un,"finallyLoc");if(Hl&&Dd){if(this.prev=0;--_o){var Es=this.tryEntries[_o];if(Es.tryLoc<=this.prev&&ee.call(Es,"finallyLoc")&&this.prev=0;--gi){var _o=this.tryEntries[gi];if(_o.finallyLoc===Gi)return this.complete(_o.completion,_o.afterLoc),zr(_o),ui}},catch:function(Gi){for(var gi=this.tryEntries.length-1;gi>=0;--gi){var _o=this.tryEntries[gi];if(_o.tryLoc===Gi){var Es=_o.completion;if(Es.type==="throw"){var un=Es.arg;zr(_o)}return un}}throw new Error("illegal catch attempt")},delegateYield:function(Gi,gi,_o){return this.delegate={iterator:Wu(Gi),resultName:gi,nextLoc:_o},this.method==="next"&&(this.arg=void 0),ui}},yA}(q.exports);try{regeneratorRuntime=QA}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=QA:Function("r","regeneratorRuntime = r")(QA)}});var eA,CA,IA=function(q){return q&&q.Math==Math&&q},oA=IA(typeof globalThis=="object"&&globalThis)||IA(typeof window=="object"&&window)||IA(typeof self=="object"&&self)||IA(typeof J=="object"&&J)||function(){return this}()||Function("return this")(),vA=function(q){try{return!!q()}catch{return!0}},qA=!vA(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Ae={}.propertyIsEnumerable,HA=Object.getOwnPropertyDescriptor,se={f:HA&&!Ae.call({1:2},1)?function(q){var QA=HA(this,q);return!!QA&&QA.enumerable}:Ae},WA=function(q,QA){return{enumerable:!(1&q),configurable:!(2&q),writable:!(4&q),value:QA}},Ye={}.toString,We=function(q){return Ye.call(q).slice(8,-1)},Pe="".split,we=vA(function(){return!Object("z").propertyIsEnumerable(0)})?function(q){return We(q)=="String"?Pe.call(q,""):Object(q)}:Object,et=function(q){if(q==null)throw TypeError("Can't call method on "+q);return q},Xe=function(q){return we(et(q))},ae=function(q){return typeof q=="function"},Je=function(q){return typeof q=="object"?q!==null:ae(q)},pt=function(q){return ae(q)?q:void 0},$t=function(q,QA){return arguments.length<2?pt(oA[q]):oA[q]&&oA[q][QA]},Pt=$t("navigator","userAgent")||"",ii=oA.process,ki=oA.Deno,ao=ii&&ii.versions||ki&&ki.version,Ji=ao&&ao.v8;Ji?CA=(eA=Ji.split("."))[0]<4?1:eA[0]+eA[1]:Pt&&(!(eA=Pt.match(/Edge\/(\d+)/))||eA[1]>=74)&&(eA=Pt.match(/Chrome\/(\d+)/))&&(CA=eA[1]);var Vi=CA&&+CA,wn=!!Object.getOwnPropertySymbols&&!vA(function(){var q=Symbol();return!String(q)||!(Object(q)instanceof Symbol)||!Symbol.sham&&Vi&&Vi<41}),Fi=wn&&!Symbol.sham&&typeof Symbol.iterator=="symbol",en=Fi?function(q){return typeof q=="symbol"}:function(q){var QA=$t("Symbol");return ae(QA)&&Object(q)instanceof QA},Ro=function(q){try{return String(q)}catch{return"Object"}},oo=function(q){if(ae(q))return q;throw TypeError(Ro(q)+" is not a function")},Ai=function(q,QA){var yA=q[QA];return yA==null?void 0:oo(yA)},no=function(q,QA){try{Object.defineProperty(oA,q,{value:QA,configurable:!0,writable:!0})}catch{oA[q]=QA}return QA},Ri=oA["__core-js_shared__"]||no("__core-js_shared__",{}),pn=cA(function(q){(q.exports=function(QA,yA){return Ri[QA]||(Ri[QA]=yA!==void 0?yA:{})})("versions",[]).push({version:"3.18.2",mode:"global",copyright:"© 2021 Denis Pushkarev (zloirock.ru)"})}),jA=function(q){return Object(et(q))},ue={}.hasOwnProperty,He=Object.hasOwn||function(q,QA){return ue.call(jA(q),QA)},Lt=0,ct=Math.random(),Ct=function(q){return"Symbol("+String(q===void 0?"":q)+")_"+(++Lt+ct).toString(36)},ei=pn("wks"),Ht=oA.Symbol,Le=Fi?Ht:Ht&&Ht.withoutSetter||Ct,it=function(q){return He(ei,q)&&(wn||typeof ei[q]=="string")||(wn&&He(Ht,q)?ei[q]=Ht[q]:ei[q]=Le("Symbol."+q)),ei[q]},Tt=it("toPrimitive"),Gt=function(q,QA){if(!Je(q)||en(q))return q;var yA,NA=Ai(q,Tt);if(NA){if(yA=NA.call(q,QA),!Je(yA)||en(yA))return yA;throw TypeError("Can't convert object to primitive value")}return function(ee,Ne){var he,Ue;if(ae(he=ee.toString)&&!Je(Ue=he.call(ee))||ae(he=ee.valueOf)&&!Je(Ue=he.call(ee)))return Ue;throw TypeError("Can't convert object to primitive value")}(q)},Hi=function(q){var QA=Gt(q,"string");return en(QA)?QA:String(QA)},po=oA.document,To=Je(po)&&Je(po.createElement),Zi=function(q){return To?po.createElement(q):{}},wo=!qA&&!vA(function(){return Object.defineProperty(Zi("div"),"a",{get:function(){return 7}}).a!=7}),Cn=Object.getOwnPropertyDescriptor,an={f:qA?Cn:function(q,QA){if(q=Xe(q),QA=Hi(QA),wo)try{return Cn(q,QA)}catch{}if(He(q,QA))return WA(!se.f.call(q,QA),q[QA])}},Vo=function(q){if(Je(q))return q;throw TypeError(String(q)+" is not an object")},jn=Object.defineProperty,vo={f:qA?jn:function(q,QA,yA){if(Vo(q),QA=Hi(QA),Vo(yA),wo)try{return jn(q,QA,yA)}catch{}if("get"in yA||"set"in yA)throw TypeError("Accessors not supported");return"value"in yA&&(q[QA]=yA.value),q}},mA=qA?function(q,QA,yA){return vo.f(q,QA,WA(1,yA))}:function(q,QA,yA){return q[QA]=yA,q},xs=Function.toString;ae(Ri.inspectSource)||(Ri.inspectSource=function(q){return xs.call(q)});var Zs,mn,Fr,qi=Ri.inspectSource,tn=oA.WeakMap,Ks=ae(tn)&&/native code/.test(qi(tn)),_n=pn("keys"),Is=function(q){return _n[q]||(_n[q]=Ct(q))},qt={},$a=oA.WeakMap;if(Ks||Ri.state){var Ls=Ri.state||(Ri.state=new $a),Bs=Ls.get,Un=Ls.has,Ir=Ls.set;Zs=function(q,QA){if(Un.call(Ls,q))throw new TypeError("Object already initialized");return QA.facade=q,Ir.call(Ls,q,QA),QA},mn=function(q){return Bs.call(Ls,q)||{}},Fr=function(q){return Un.call(Ls,q)}}else{var Fn=Is("state");qt[Fn]=!0,Zs=function(q,QA){if(He(q,Fn))throw new TypeError("Object already initialized");return QA.facade=q,mA(q,Fn,QA),QA},mn=function(q){return He(q,Fn)?q[Fn]:{}},Fr=function(q){return He(q,Fn)}}var rr={set:Zs,get:mn,has:Fr,enforce:function(q){return Fr(q)?mn(q):Zs(q,{})},getterFor:function(q){return function(QA){var yA;if(!Je(QA)||(yA=mn(QA)).type!==q)throw TypeError("Incompatible receiver, "+q+" required");return yA}}},fo=Function.prototype,es=qA&&Object.getOwnPropertyDescriptor,vc=He(fo,"name"),ts={PROPER:vc&&function(){}.name==="something",CONFIGURABLE:vc&&(!qA||qA&&es(fo,"name").configurable)},ur=cA(function(q){var QA=ts.CONFIGURABLE,yA=rr.get,NA=rr.enforce,ee=String(String).split("String");(q.exports=function(Ne,he,Ue,de){var Ve,_t=!!de&&!!de.unsafe,ti=!!de&&!!de.enumerable,ui=!!de&&!!de.noTargetGet,Rt=de&&de.name!==void 0?de.name:he;ae(Ue)&&(String(Rt).slice(0,7)==="Symbol("&&(Rt="["+String(Rt).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),(!He(Ue,"name")||QA&&Ue.name!==Rt)&&mA(Ue,"name",Rt),(Ve=NA(Ue)).source||(Ve.source=ee.join(typeof Rt=="string"?Rt:""))),Ne!==oA?(_t?!ui&&Ne[he]&&(ti=!0):delete Ne[he],ti?Ne[he]=Ue:mA(Ne,he,Ue)):ti?Ne[he]=Ue:no(he,Ue)})(Function.prototype,"toString",function(){return ae(this)&&yA(this).source||qi(this)})}),On=Math.ceil,vg=Math.floor,yn=function(q){var QA=+q;return QA!=QA||QA===0?0:(QA>0?vg:On)(QA)},ce=Math.max,ot=Math.min,Zt=Math.min,Ho=function(q){return q>0?Zt(yn(q),9007199254740991):0},Ba=function(q){return Ho(q.length)},WI=function(q){return function(QA,yA,NA){var ee,Ne=Xe(QA),he=Ba(Ne),Ue=function(de,Ve){var _t=yn(de);return _t<0?ce(_t+Ve,0):ot(_t,Ve)}(NA,he);if(q&&yA!=yA){for(;he>Ue;)if((ee=Ne[Ue++])!=ee)return!0}else for(;he>Ue;Ue++)if((q||Ue in Ne)&&Ne[Ue]===yA)return q||Ue||0;return!q&&-1}},gn={indexOf:WI(!1)},ro=gn.indexOf,Mc=function(q,QA){var yA,NA=Xe(q),ee=0,Ne=[];for(yA in NA)!He(qt,yA)&&He(NA,yA)&&Ne.push(yA);for(;QA.length>ee;)He(NA,yA=QA[ee++])&&(~ro(Ne,yA)||Ne.push(yA));return Ne},gg=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Mg=gg.concat("length","prototype"),Qa={f:Object.getOwnPropertyNames||function(q){return Mc(q,Mg)}},Fo={f:Object.getOwnPropertySymbols},Aa=$t("Reflect","ownKeys")||function(q){var QA=Qa.f(Vo(q)),yA=Fo.f;return yA?QA.concat(yA(q)):QA},Uo=function(q,QA){for(var yA=Aa(QA),NA=vo.f,ee=an.f,Ne=0;Ne=51||!vA(function(){var QA=[];return(QA.constructor={})[di]=function(){return{foo:1}},QA[q](Boolean).foo!==1})},Jt=it("isConcatSpreadable"),$i=Vi>=51||!vA(function(){var q=[];return q[Jt]=!1,q.concat()[0]!==q}),eo=Bt("concat"),os=function(q){if(!Je(q))return!1;var QA=q[Jt];return QA!==void 0?!!QA:pa(q)};Tn({target:"Array",proto:!0,forced:!$i||!eo},{concat:function(q){var QA,yA,NA,ee,Ne,he=jA(this),Ue=Kt(he,0),de=0;for(QA=-1,NA=arguments.length;QA9007199254740991)throw TypeError("Maximum allowed index exceeded");for(yA=0;yA=9007199254740991)throw TypeError("Maximum allowed index exceeded");_s(Ue,de++,Ne)}return Ue.length=de,Ue}});var Ti,on=Object.keys||function(q){return Mc(q,gg)},wg=qA?Object.defineProperties:function(q,QA){Vo(q);for(var yA,NA=on(QA),ee=NA.length,Ne=0;ee>Ne;)vo.f(q,yA=NA[Ne++],QA[yA]);return q},Er=$t("document","documentElement"),Mr=Is("IE_PROTO"),js=function(){},Tl=function(q){return" + diff --git a/app/video_companion/src/main.ts b/app/video_companion/src/main.ts index 04a223a58..80b8b94e7 100644 --- a/app/video_companion/src/main.ts +++ b/app/video_companion/src/main.ts @@ -1699,10 +1699,26 @@ async function stopTranscription( return } const finalStatus = sdkStopped && segmentsComplete && !transcriptionHadInterruption ? status : 'partial' - transcriptionFinalized = true - const persisted = await requestTranscriptionStop(sessionId, finalStatus) + let persisted = false + for (let attempt = 0; attempt < 3; attempt += 1) { + if (sessionId !== transcriptionSessionId) return + if (attempt > 0) { + await new Promise((resolve) => window.setTimeout(resolve, attempt * 500)) + if (sessionId !== transcriptionSessionId) return + } + persisted = await requestTranscriptionStop(sessionId, finalStatus) + if (persisted) break + } if (sessionId !== transcriptionSessionId) return - transcriptionState.value = persisted && !transcriptionError.value ? 'idle' : 'error' + if (!persisted) { + transcriptionState.value = 'error' + notice.value = '本次面诊对话文字归档失败,请在通话记录中核实' + // Keep the session and unsaved snapshots available; a failed ACK is not + // proof that the server finalized them. The native end fallback retries. + throw new Error(notice.value) + } + transcriptionFinalized = true + transcriptionState.value = !transcriptionError.value ? 'idle' : 'error' notice.value = transcriptionError.value || (persisted && finalStatus === 'completed' ? '本次面诊对话文字已保存到视频记录' : '本次转写可能不完整,请在通话记录中核实') diff --git a/app/video_companion/tests/cloud-transcription-lifecycle.test.cjs b/app/video_companion/tests/cloud-transcription-lifecycle.test.cjs index df937ec84..3f68070ff 100644 --- a/app/video_companion/tests/cloud-transcription-lifecycle.test.cjs +++ b/app/video_companion/tests/cloud-transcription-lifecycle.test.cjs @@ -42,7 +42,9 @@ function harness(options = {}) { if(!native.session)native.session=event.sessionId; if(native.session!==event.sessionId||native.sealed)native.violations.push(event); } else if(event.event==='transcription-stop'){ - if(native.session!==event.sessionId||native.sealed)native.violations.push(event); + // Capture is sealed immediately, but the same finish may retry after + // a negative or missing ACK; it does not create a second session. + if(native.session!==event.sessionId)native.violations.push(event); native.sealed=true; } else if(['transcription-segment','transcription-ready'].includes(event.event)){ if(!native.ready||native.session!==event.sessionId||native.sealed)native.violations.push(event); @@ -305,3 +307,53 @@ test('cloud capture status remains accurate and partial post-call text can be re assert.equal(status('error','partial',true),'partial') assert.equal(status('stopping','partial',true),'stopping') }) + + +test('finish retries negative ACKs in the same session and finalizes only after success', async () => { + const h=harness();await start(h) + const stopped=h.stop();await settle();await h.advance(600) + const session=h.state().session + assert.equal(h.state().finalized,false) + h.stopAck(false);await settle();await h.advance(500) + assert.equal(h.state().finalized,false) + assert.equal(h.state().ready,true) + h.stopAck(false);await settle();await h.advance(1000) + const finishes=h.events.filter(e=>e.event==='transcription-stop') + assert.equal(finishes.length,3) + assert.deepEqual(finishes.map(e=>e.sessionId),[session,session,session]) + h.stopAck();await stopped + assert.equal(h.state().finalized,true) + assert.equal(h.state().state,'idle') + assert.equal(h.state().ready,false) + assert.deepEqual(h.native.violations,[]) +}) + +test('exhausted finish ACK failures retain pending text and surface failure without false completion', async () => { + const h=harness();await start(h);h.segment(raw('unsaved')) + const stopped=h.stop() + const rejected=assert.rejects(stopped,/归档失败/) + await settle();await h.advance(15000) + h.stopAck(false);await settle();await h.advance(500) + h.stopAck(false);await settle();await h.advance(1000) + h.stopAck(false);await rejected + assert.equal(h.events.filter(e=>e.event==='transcription-stop').length,3) + assert.equal(h.state().pending,1) + assert.equal(h.state().ready,true) + assert.equal(h.state().finalized,false) + assert.equal(h.state().state,'error') + assert.equal(h.state().session,'tr-test-1') + assert.deepEqual(h.native.violations,[]) +}) + +test('a missing finish ACK times out and retries without clearing the current session', async () => { + const h=harness();await start(h) + const stopped=h.stop();await settle();await h.advance(600) + await h.advance(15500) + assert.equal(h.events.filter(e=>e.event==='transcription-stop').length,2) + assert.equal(h.state().finalized,false) + assert.equal(h.state().ready,true) + h.stopAck();await stopped + assert.equal(h.state().finalized,true) + assert.equal(h.state().state,'idle') + assert.deepEqual(h.native.violations,[]) +}) diff --git a/server/app/adminapi/controller/tcm/DiagnosisController.php b/server/app/adminapi/controller/tcm/DiagnosisController.php index 2a220256e..26d892314 100755 --- a/server/app/adminapi/controller/tcm/DiagnosisController.php +++ b/server/app/adminapi/controller/tcm/DiagnosisController.php @@ -393,6 +393,21 @@ class DiagnosisController extends BaseAdminController return $this->data($result); } + /** @notes 将本机保留录音补转写的完整文字保存到已结束的通话 */ + public function saveLocalAudioTranscript() + { + if (!$this->request->isPost()) { + return $this->fail('请求方式错误'); + } + $params = $this->request->post('', null, null); + $params['admin_id'] = (int)$this->adminId; + $result = DiagnosisLogic::saveLocalAudioTranscript($params); + if ($result === false) { + return $this->fail(DiagnosisLogic::getError()); + } + return $this->data($result); + } + /** @notes 完成当前通话转写并固化对话文字 */ public function finishCallTranscription() { diff --git a/server/app/adminapi/controller/tcm/MobileRecordingController.php b/server/app/adminapi/controller/tcm/MobileRecordingController.php new file mode 100644 index 000000000..4818d8a9f --- /dev/null +++ b/server/app/adminapi/controller/tcm/MobileRecordingController.php @@ -0,0 +1,54 @@ +handle(true, fn (array $params): array => MobileRecordingLogic::bind($params, $this->adminId)); + } + + public function unbind() + { + return $this->handle(true, fn (array $params): array => MobileRecordingLogic::unbind($params, $this->adminId)); + } + + public function deviceLists() + { + return $this->handle(false, fn (array $params): array => MobileRecordingLogic::deviceLists($params, $this->adminId)); + } + + public function patientLists() + { + return $this->handle(false, fn (array $params): array => MobileRecordingLogic::patientLists($params, $this->adminId)); + } + + private function handle(bool $post, callable $operation) + { + if ($post ? !$this->request->isPost() : !$this->request->isGet()) { + return $this->fail('请求方式错误'); + } + try { + // Explicit current page permission, including before any row lookup. + MobileRecordingLogic::actor((int) $this->adminId); + if ($this->request->file()) { + throw new DomainException('手机录音关联不接受文件上传'); + } + $params = $post ? $this->request->post('', null, null) : $this->request->get(); + return $this->data($operation($params)); + } catch (DomainException $e) { + return $this->fail($e->getMessage()); + } catch (\Throwable $e) { + // Do not expose SQL, identifiers, paths or server configuration on schema/deployment errors. + return $this->fail('手机录音关联服务暂不可用,请稍后重试或联系管理员'); + } + } +} diff --git a/server/app/adminapi/http/middleware/AuthMiddleware.php b/server/app/adminapi/http/middleware/AuthMiddleware.php index ebfd576e7..b7f7a2aee 100755 --- a/server/app/adminapi/http/middleware/AuthMiddleware.php +++ b/server/app/adminapi/http/middleware/AuthMiddleware.php @@ -109,6 +109,16 @@ class AuthMiddleware return JsonService::fail('权限不足,无法查看面诊记录'); } + // Full-audio recovery exercises all three realtime write capabilities. + // Protect it explicitly before the unregistered-route compatibility branch. + if ($accessUri === 'tcm.diagnosis/savelocalaudiotranscript') { + $uris = $this->formatUrl($adminAuthCache->getAdminUri() ?? []); + $required = ['tcm.diagnosis/startcalltranscription', + 'tcm.diagnosis/upsertcalltranscriptsegments', 'tcm.diagnosis/finishcalltranscription']; + return array_diff($required, $uris) === [] + ? $next($request) : JsonService::fail('权限不足,无法保存录音补转写'); + } + // This group must never use the legacy unregistered-route bypass. if (str_starts_with($accessUri, 'tcm.followupaudio/')) { $allowed = ['capabilities', 'uploadsession', 'uploadchunk', 'uploadcomplete', @@ -135,6 +145,16 @@ class AuthMiddleware return JsonService::fail('权限不足,无法访问或操作'); } + // Metadata-only mobile links always share the patient page grant, even before menu registration. + if (str_starts_with($accessUri, 'tcm.mobilerecording/')) { + $action = substr($accessUri, strlen('tcm.mobilerecording/')); + $uris = $this->formatUrl($adminAuthCache->getAdminUri() ?? []); + if (in_array($action, ['bind', 'unbind', 'devicelists', 'patientlists'], true) + && in_array('firstvisit.mypatient/lists', $uris, true)) { + return $next($request); // Controller re-reads grants; logic enforces the current patient scope. + } + return JsonService::fail('权限不足,无法访问我的患者录音关联'); + } // 全部路由 $allUri = $this->formatUrl($adminAuthCache->getAllUri()); diff --git a/server/app/adminapi/logic/tcm/DiagnosisLogic.php b/server/app/adminapi/logic/tcm/DiagnosisLogic.php index 84ca63398..cf5c78ecf 100755 --- a/server/app/adminapi/logic/tcm/DiagnosisLogic.php +++ b/server/app/adminapi/logic/tcm/DiagnosisLogic.php @@ -2023,6 +2023,20 @@ class DiagnosisLogic extends BaseLogic } } + /** @notes 本机完整录音补转写;不重新打开实时转写会话 */ + public static function saveLocalAudioTranscript(array $params) + { + try { + return \app\adminapi\service\LocalAudioTranscriptRecovery::save($params); + } catch (\DomainException $e) { + self::setError($e->getMessage()); + return false; + } catch (\Throwable $e) { + self::setError('录音补转写保存失败,请稍后重试'); + return false; + } + } + /** * @notes 完成实时转写并将最终文字固化在通话记录上 * @return array|false @@ -2068,10 +2082,9 @@ class DiagnosisLogic extends BaseLogic $callRecordId = (int)$record['id']; $snapshot = self::buildCallTranscriptSnapshot($callRecordId, $sessionId); $actualCount = (int)$snapshot['segment_count']; - $finalStatus = $requestedStatus; - if ($requestedStatus === 'completed' && $actualCount < $expectedCount) { - $finalStatus = 'partial'; - } + $finalStatus = \app\adminapi\service\LocalAudioTranscriptRecovery::completionStatus( + $requestedStatus, $actualCount, $expectedCount, $snapshot['transcript_text'] + ); $now = time(); $record->save([ 'transcription_status' => $finalStatus, diff --git a/server/app/adminapi/logic/tcm/MobileRecordingLogic.php b/server/app/adminapi/logic/tcm/MobileRecordingLogic.php new file mode 100644 index 000000000..d29518479 --- /dev/null +++ b/server/app/adminapi/logic/tcm/MobileRecordingLogic.php @@ -0,0 +1,230 @@ +where('id', $adminId)->whereNull('delete_time') + ->where('disable', 0)->lock($lock)->find(); + if ($adminId <= 0 || !$row) { + throw new DomainException('账号已停用或登录状态失效'); + } + $roles = Db::name('admin_role')->where('admin_id', $adminId)->column('role_id'); + $info = ['admin_id' => $adminId, 'id' => $adminId, 'root' => (int) $row['root'], 'role_id' => $roles]; + if ($info['root'] !== 1) { + $menuIds = $roles ? Db::name('system_role_menu')->whereIn('role_id', $roles)->column('menu_id') : []; + $allowed = $menuIds && Db::name('system_menu')->whereIn('id', $menuIds) + ->where('is_disable', 0)->where('perms', self::PAGE_PERMISSION)->count() > 0; + if (!$allowed) { + throw new DomainException('权限不足,无法访问我的患者录音关联'); + } + } + return $info; + } + + public static function bind(array $params, int $adminId): array + { + $p = self::bindingInput($params); + return Db::transaction(static function () use ($p, $adminId): array { + // Serialize mutations for this actor, including the first INSERT for an absent key. + $info = self::actor($adminId, true); + $existing = self::ownedQuery($adminId, $p)->lock(true)->find(); + $ids = array_unique([$p['diagnosis_id'], (int) ($existing['diagnosis_id'] ?? $p['diagnosis_id'])]); + sort($ids); + $patients = []; + foreach ($ids as $id) { + $patients[$id] = self::diagnosis($id, $adminId, $info, true); + } + $now = time(); + if ($existing) { + $id = (int) $existing['id']; + self::ownedQuery($adminId, $p)->where('id', $id)->update($p + ['updated_at' => $now]); + $row = array_merge($existing, $p, ['updated_at' => $now]); + } else { + $row = $p + ['admin_id' => $adminId, 'created_at' => $now, 'updated_at' => $now]; + $row['id'] = (int) Db::name('mobile_recording_binding')->insertGetId($row); + } + return ['binding' => self::deviceRow($row, $patients[$p['diagnosis_id']])]; + }); + } + + public static function unbind(array $params, int $adminId): array + { + self::only($params, ['installation_id', 'recording_key']); + $identity = self::identity($params); + return Db::transaction(static function () use ($identity, $adminId): array { + $info = self::actor($adminId, true); + $row = self::ownedQuery($adminId, $identity)->lock(true)->find(); + if ($row) { + self::diagnosis((int) $row['diagnosis_id'], $adminId, $info, true); + self::ownedQuery($adminId, $identity)->where('id', (int) $row['id'])->delete(); + } + return ['unbound' => true]; + }); + } + + public static function deviceLists(array $params, int $adminId): array + { + self::only($params, ['installation_id', 'page_no', 'page_size']); + $installationId = self::installation($params['installation_id'] ?? null); + [$page, $size] = self::pagination($params, 50); + $info = self::actor($adminId); + $query = Db::name('mobile_recording_binding')->alias('b') + ->join([(new Diagnosis())->getTable() => 'd'], 'd.id = b.diagnosis_id') + ->where('b.admin_id', $adminId)->where('b.installation_id', $installationId) + ->where('d.status', 1)->whereNull('d.delete_time'); + MyPatientLogic::applyScope($query, $adminId, $info); + $count = (int) (clone $query)->count('b.id'); + $rows = $query->field('b.*,d.patient_id AS source_patient_id,d.patient_name,d.phone AS patient_phone') + ->order('b.id', 'desc')->page($page, $size)->select()->toArray(); + $items = array_map(static fn (array $row): array => self::deviceRow($row, [ + 'id' => $row['diagnosis_id'], 'patient_id' => $row['source_patient_id'], + 'patient_name' => $row['patient_name'], 'phone' => $row['patient_phone'], + ]), $rows); + return ['lists' => $items, 'count' => $count, 'page_no' => $page, 'page_size' => $size]; + } + + public static function patientLists(array $params, int $adminId): array + { + self::only($params, ['diagnosis_id', 'page_no', 'page_size']); + $diagnosisId = self::integer($params['diagnosis_id'] ?? null, 1, 4294967295, '诊单标识'); + [$page, $size] = self::pagination($params, 20); + $info = self::actor($adminId); + self::diagnosis($diagnosisId, $adminId, $info); + $query = Db::name('mobile_recording_binding')->alias('b')->where('b.diagnosis_id', $diagnosisId); + $count = (int) (clone $query)->count(); + $adminTable = Db::name('admin')->getTable(); + $rows = $query->leftJoin([$adminTable => 'a'], 'a.id = b.admin_id') + ->field('b.id,b.diagnosis_id,b.source_platform,b.recorded_at,b.duration_ms,b.created_at,b.updated_at,a.name AS bound_by') + ->order('b.recorded_at', 'desc')->order('b.id', 'desc')->page($page, $size)->select()->toArray(); + $items = array_map(static function (array $row): array { + $dto = self::metadata($row); + $dto['bound_by'] = trim((string) ($row['bound_by'] ?? '')) ?: '已停用账号'; + $dto['playback_location'] = 'original_device'; + return $dto; + }, $rows); + return ['lists' => $items, 'count' => $count, 'page_no' => $page, 'page_size' => $size]; + } + + /** Public for the controller and executable input-contract tests. */ + public static function bindingInput(array $params): array + { + self::only($params, ['installation_id', 'recording_key', 'diagnosis_id', 'source_platform', 'recorded_at', 'duration_ms']); + if (($params['source_platform'] ?? null) !== 'android_bcr') { + throw new DomainException('录音来源无效'); + } + return self::identity($params) + [ + 'diagnosis_id' => self::integer($params['diagnosis_id'] ?? null, 1, 4294967295, '诊单标识'), + 'source_platform' => 'android_bcr', + 'recorded_at' => self::integer($params['recorded_at'] ?? null, 0, (time() + 300) * 1000, '录音时间'), + 'duration_ms' => self::integer($params['duration_ms'] ?? null, 0, 604800000, '录音时长'), + ]; + } + + private static function ownedQuery(int $adminId, array $identity): Query + { + return Db::name('mobile_recording_binding')->where('admin_id', $adminId) + ->where('installation_id', $identity['installation_id'])->where('recording_key', $identity['recording_key']); + } + + private static function diagnosis(int $id, int $adminId, array $info, bool $lock = false): array + { + $row = Db::name('tcm_diagnosis')->where('id', $id)->whereNull('delete_time')->where('status', 1) + ->lock($lock)->find(); + if (!$row || !MyPatientLogic::canAccessDiagnosis($id, $adminId, $info)) { + throw new DomainException('患者不存在或无权操作'); + } + return $row; + } + + private static function deviceRow(array $row, array $patient): array + { + return self::metadata($row) + [ + 'installation_id' => (string) $row['installation_id'], + 'recording_key' => (string) $row['recording_key'], + 'patient' => [ + 'diagnosis_id' => (int) $patient['id'], + 'source_patient_id' => (int) ($patient['patient_id'] ?? 0), + 'patient_name' => (string) ($patient['patient_name'] ?? ''), + 'phone_masked' => self::maskPhone((string) ($patient['phone'] ?? '')), + ], + ]; + } + + private static function metadata(array $row): array + { + $result = ['source_platform' => (string) $row['source_platform']]; + foreach (['id', 'diagnosis_id', 'recorded_at', 'duration_ms', 'created_at', 'updated_at'] as $field) { + $result[$field] = (int) $row[$field]; + } + return $result; + } + + private static function maskPhone(string $phone): string + { + $digits = preg_replace('/\D+/', '', $phone) ?? ''; + $length = strlen($digits); + if ($length <= 4) { + return str_repeat('*', $length); + } + if ($length < 8) { + return substr($digits, 0, 1) . str_repeat('*', $length - 2) . substr($digits, -1); + } + return substr($digits, 0, 3) . str_repeat('*', $length - 7) . substr($digits, -4); + } + + private static function identity(array $params): array + { + $key = $params['recording_key'] ?? null; + if (!is_string($key) || !preg_match('/^[0-9a-f]{64}$/D', $key)) { + throw new DomainException('录音标识无效'); + } + return ['installation_id' => self::installation($params['installation_id'] ?? null), 'recording_key' => $key]; + } + + private static function installation($value): string + { + if (!is_string($value) || !preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/D', $value)) { + throw new DomainException('设备标识无效'); + } + return $value; + } + + private static function pagination(array $params, int $defaultSize): array + { + return [ + self::integer($params['page_no'] ?? 1, 1, 1000000, '页码'), + self::integer($params['page_size'] ?? $defaultSize, 1, 100, '每页数量'), + ]; + } + + private static function integer($value, int $min, int $max, string $label): int + { + if (!(is_int($value) || is_string($value)) || !preg_match('/^(0|[1-9][0-9]{0,14})$/D', (string) $value) + || (int) $value < $min || (int) $value > $max) { + throw new DomainException($label . '无效'); + } + return (int) $value; + } + + private static function only(array $params, array $allowed): void + { + if (array_diff(array_keys($params), $allowed) !== []) { + throw new DomainException('请求包含不支持的字段'); + } + } +} diff --git a/server/app/adminapi/service/LocalAudioTranscriptRecovery.php b/server/app/adminapi/service/LocalAudioTranscriptRecovery.php new file mode 100644 index 000000000..fff39eb66 --- /dev/null +++ b/server/app/adminapi/service/LocalAudioTranscriptRecovery.php @@ -0,0 +1,104 @@ + ['min_range' => 1]]) === false) { + throw new DomainException('录音补转写身份参数无效'); + } + } + foreach (['recovery_id', 'expected_session_id', 'expected_status', 'audio_url', 'transcript_text'] as $key) { + if (!isset($params[$key]) || !is_string($params[$key])) { + throw new DomainException('录音补转写参数无效'); + } + } + if (!preg_match('/\Aaudio-[a-f0-9]{32}\z/D', $params['recovery_id']) + || mb_strlen($params['expected_session_id']) > 128 + || !in_array($params['expected_status'], ['', 'pending', 'running', 'partial', 'failed', 'completed'], true) + || trim($params['audio_url']) === '' || strlen($params['audio_url']) > 8192) { + throw new DomainException('录音补转写会话参数无效'); + } + $text = trim($params['transcript_text']); + if ($text === '' || mb_strlen($params['transcript_text']) > 100000) { + throw new DomainException('录音补转写文字必须为1到100000个字符'); + } + + return Db::transaction(static function () use ($params, $text): array { + // The realtime upsert/finish endpoints lock the same row, so a late + // old-session write cannot run after this session switch succeeds. + $record = CallRecord::where('id', (int) $params['call_record_id']) + ->where('diagnosis_id', (int) $params['diagnosis_id']) + ->where('caller_id', (int) $params['admin_id']) + ->where('caller_type', 'doctor')->lock(true)->find(); + if (!$record) { throw new DomainException('通话记录不存在或无权操作'); } + if ((int) $record['status'] !== 2) { throw new DomainException('通话结束后才能补转写'); } + $urls = json_decode((string) ($record['local_audio_urls'] ?? ''), true); + if ((int) ($record['local_audio_status'] ?? 0) !== 2 || !is_array($urls) + || !in_array($params['audio_url'], $urls, true)) { + throw new DomainException('录音尚未上传或不属于当前通话'); + } + $result = ['call_record_id' => (int) $record['id'], 'transcription_status' => 'completed']; + $session = (string) ($record['transcription_session_id'] ?? ''); + $status = (string) ($record['transcription_status'] ?? ''); + if ($status === 'completed' && trim((string) ($record['transcript_text'] ?? '')) !== '') { + // Lost response retries succeed even with the original CAS values; + // a different completed session always wins without being changed. + return $session === $params['recovery_id'] + ? $result + ['saved' => true] + : $result + ['saved' => false, 'already_complete' => true]; + } + if ($session !== $params['expected_session_id'] || $status !== $params['expected_status']) { + throw new DomainException('通话转写状态已变化,请刷新后重试'); + } + + $now = time(); + $segments = []; + $lines = []; + // Recognition supplied no diarization or alignment. Do not invent + // doctor/patient attribution or timestamps; preserve source order by id. + for ($offset = 0, $index = 0, $length = mb_strlen($text); $offset < $length; $offset += 4000, $index++) { + $part = mb_substr($text, $offset, 4000); + $segments[] = [ + 'call_record_id' => (int) $record['id'], + 'transcription_session_id' => $params['recovery_id'], + 'segment_id' => $params['recovery_id'] . '-' . $index, + 'speaker_user_id' => '', 'speaker_role' => 'unknown', 'timestamp_ms' => 0, + 'text' => $part, 'create_time' => $now, 'update_time' => $now, + ]; + $lines[] = '未知说话人:' . $part; + } + // Keep all old-session segments for audit; the current session is the + // only one consumed by transcript readers and clinical context builders. + Db::name('tcm_call_transcript_segment')->insertAll($segments); + $record->save([ + 'transcription_session_id' => $params['recovery_id'], + 'transcription_status' => 'completed', + 'transcription_segment_count' => count($segments), + 'transcript_text' => implode("\n", $lines), + 'transcription_started_at' => $now, 'transcription_finished_at' => $now, + 'update_time' => $now, + ]); + return $result + ['saved' => true]; + }); + } + + public static function completionStatus(string $requested, int $actual, int $expected, string $text): string + { + if ($requested !== 'completed') { return $requested; } + if ($actual === 0 || trim($text) === '') { return 'failed'; } + return $actual < $expected ? 'partial' : 'completed'; + } +} diff --git a/server/database/migrations/2026_11_06_mobile_recording_binding.sql b/server/database/migrations/2026_11_06_mobile_recording_binding.sql new file mode 100644 index 000000000..3243ed750 --- /dev/null +++ b/server/database/migrations/2026_11_06_mobile_recording_binding.sql @@ -0,0 +1,18 @@ +-- Metadata-only mobile recording links. Default prefix: zyt_. +-- No audio, transcript, original filename, contact label or device filesystem path is stored. +-- Permissions intentionally reuse firstvisit.myPatient/lists in BOTH middleware and controller. +CREATE TABLE IF NOT EXISTS `zyt_mobile_recording_binding` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT, + `admin_id` int unsigned NOT NULL, + `installation_id` char(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT 'Random per-install UUID v4', + `recording_key` char(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL COMMENT 'SHA256 of opaque stable local identifier, not audio content', + `diagnosis_id` int unsigned NOT NULL, + `source_platform` varchar(24) NOT NULL DEFAULT 'android_bcr', + `recorded_at` bigint unsigned NOT NULL COMMENT 'UTC Unix milliseconds; zero means unknown', + `duration_ms` bigint unsigned NOT NULL DEFAULT 0, + `created_at` int unsigned NOT NULL, + `updated_at` int unsigned NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `uq_actor_device_recording` (`admin_id`, `installation_id`, `recording_key`), + KEY `idx_diagnosis_recorded` (`diagnosis_id`, `recorded_at`, `id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Phone-local recording metadata links'; diff --git a/server/tests/ConsultationTranscriptAuthorizationTest.php b/server/tests/ConsultationTranscriptAuthorizationTest.php index 06853c043..107168948 100644 --- a/server/tests/ConsultationTranscriptAuthorizationTest.php +++ b/server/tests/ConsultationTranscriptAuthorizationTest.php @@ -55,6 +55,11 @@ namespace app\adminapi\logic\tcm { self::$events[] = ['read', $params]; return self::$records; } + public static function saveLocalAudioTranscript(array $params): array + { + self::$events[] = ['recover', $params]; + return ['call_record_id' => 1102, 'transcription_status' => 'completed', 'saved' => true]; + } public static function getError(): string { return self::$error; } } } @@ -79,6 +84,7 @@ namespace { public object $controllerObject; public string $actionName = 'getCallRecords'; public string $controllerName = 'tcm.Diagnosis'; + public bool $postRequest = false; public function __construct(public array $query = [], bool $root = false) { $this->adminInfo = ['admin_id' => 91, 'root' => $root ? 1 : 0, @@ -92,6 +98,8 @@ namespace { return $name === null ? $this->query : ($this->query[$name] ?? $default); } public function param(string $name, $default = null) { return $default; } + public function post($name = '', $default = null, $filter = '') { return $this->query; } + public function isPost(): bool { return $this->postRequest; } public function controller(): string { return $this->controllerName; } public function action(): string { return $this->actionName; } public function ip(): string { return '192.0.2.91'; } @@ -207,5 +215,45 @@ namespace { $empty = transcriptAuthorizationInvoke(['diagnosis_id' => 701], ['tcm.diagnosis/getCallRecords']); transcriptAuthorizationExpect($empty['code'] === 1 && $empty['data'] === [], 'authorized empty history retains the original array response'); + $recoveryGrants = ['tcm.diagnosis/startCallTranscription', 'tcm.diagnosis/upsertCallTranscriptSegments', + 'tcm.diagnosis/finishCallTranscription']; + foreach ([[], ['tcm.diagnosis/huifang'], ['tcm.diagnosis/edit'], ['tcm.diagnosis/video-call'], + ['tcm.diagnosis/saveLocalAudioTranscript'], [$recoveryGrants[0]], array_slice($recoveryGrants, 0, 2), + [$recoveryGrants[0], $recoveryGrants[1], $recoveryGrants[2] . 'Other']] as $permissions) { + $request = new ConsultationTranscriptRequest(); + $request->actionName = 'SaVeLoCaLaUdIoTrAnScRiPt'; + $GLOBALS['consultation_transcript_request'] = $request; + AdminAuthCache::$permissions = $permissions; + AdminAuthCache::$allUriReads = 0; + $continued = false; + $denied = (new AuthMiddleware())->handle($request, static function () use (&$continued): array { + $continued = true; return ['code' => 1]; + }); + transcriptAuthorizationExpect($denied['code'] === 0 && !$continued, 'recovery requires all exact realtime grants'); + transcriptAuthorizationExpect(AdminAuthCache::$allUriReads === 0, 'recovery never uses unregistered route bypass'); + } + foreach ([false, true] as $root) { + $payload = ['diagnosis_id' => 701, 'call_record_id' => 1102, 'admin_id' => 9999, + 'recovery_id' => 'audio-' . str_repeat('a', 32), 'expected_session_id' => 'session', + 'expected_status' => 'partial', 'audio_url' => 'https://audio.invalid/test.webm', + 'transcript_text' => "原文 &\n结尾"]; + $request = new ConsultationTranscriptRequest($payload, $root); + $request->actionName = 'saveLocalAudioTranscript'; + $request->postRequest = true; + $GLOBALS['consultation_transcript_request'] = $request; + $controller = new ConsultationTranscriptController($request); + $request->controllerObject = $controller; + AdminAuthCache::$permissions = $root ? [] : array_map('strtoupper', $recoveryGrants); + DiagnosisLogic::$events = []; + $saved = (new AuthMiddleware())->handle($request, static fn () => $controller->saveLocalAudioTranscript()); + transcriptAuthorizationExpect($saved['code'] === 1 && $saved['data']['saved'] === true, 'granted actor can invoke recovery'); + $payload['admin_id'] = 91; + transcriptAuthorizationExpect(DiagnosisLogic::$events === [['recover', $payload]], 'controller uses login actor and preserves transcript text'); + $request->postRequest = false; + DiagnosisLogic::$events = []; + transcriptAuthorizationExpect($controller->saveLocalAudioTranscript()['code'] === 0 && DiagnosisLogic::$events === [], + 'recovery rejects GET before persistence'); + } + echo "Consultation transcript authorization: {$assertions} assertions passed (no DB or network)\n"; } diff --git a/server/tests/LocalAudioTranscriptRecoveryTest.php b/server/tests/LocalAudioTranscriptRecoveryTest.php new file mode 100644 index 000000000..5fd75bc79 --- /dev/null +++ b/server/tests/LocalAudioTranscriptRecoveryTest.php @@ -0,0 +1,204 @@ + $value) { $this[$key] = $value; } + } + } + + final class RecordQuery + { + private array $filters = []; + private bool $locked = false; + public function where(string $key, $value): self { $this->filters[$key] = $value; return $this; } + public function lock(bool $locked): self { $this->locked = $locked; return $this; } + public function find(): ?Record + { + if (!$this->locked || !\think\facade\Db::$transaction) { throw new \RuntimeException('Missing transaction row lock'); } + foreach (\app\common\model\tcm\CallRecord::$rows as $row) { + foreach ($this->filters as $key => $value) { if (($row[$key] ?? null) !== $value) { continue 2; } } + return $row; + } + return null; + } + } + + final class SegmentQuery + { + private array $filters = []; + public function where(string $key, $value): self { $this->filters[$key] = $value; return $this; } + public function order(string $order): self { return $this; } + public function select(): self { return $this; } + public function toArray(): array + { + return array_values(array_filter(\think\facade\Db::$segments, function (array $row): bool { + foreach ($this->filters as $key => $value) { if ($row[$key] !== $value) { return false; } } + return true; + })); + } + public function insertAll(array $rows): void + { + if (!\think\facade\Db::$transaction) { throw new \RuntimeException('Segment write outside transaction'); } + foreach ($rows as $row) { + foreach (\think\facade\Db::$segments as $existing) { + if ($row['call_record_id'] === $existing['call_record_id'] + && $row['transcription_session_id'] === $existing['transcription_session_id'] + && $row['segment_id'] === $existing['segment_id']) { throw new \RuntimeException('Duplicate segment'); } + } + \think\facade\Db::$segments[] = $row; + } + } + } +} + +namespace app\common\model\tcm { + final class CallRecord + { + public static array $rows = []; + public static function where(string $key, $value): \recovery_test\RecordQuery + { + return (new \recovery_test\RecordQuery())->where($key, $value); + } + } +} + +namespace think\facade { + final class Db + { + public static bool $transaction = false; + public static bool $failSave = false; + public static array $segments = []; + public static function transaction(callable $callback) + { + $rows = array_map(static fn ($row) => clone $row, \app\common\model\tcm\CallRecord::$rows); + $segments = self::$segments; + self::$transaction = true; + try { return $callback(); } + catch (\Throwable $e) { + \app\common\model\tcm\CallRecord::$rows = $rows; + self::$segments = $segments; + throw $e; + } finally { self::$transaction = false; } + } + public static function name(string $name): \recovery_test\SegmentQuery + { + if ($name !== 'tcm_call_transcript_segment') { throw new \RuntimeException('Unexpected table'); } + return new \recovery_test\SegmentQuery(); + } + } +} + +namespace { + require dirname(__DIR__) . '/vendor/autoload.php'; + + use app\adminapi\logic\tcm\DiagnosisLogic as Logic; + use app\common\model\tcm\CallRecord; + use think\facade\Db; + + $assertions = 0; + function check(bool $condition, string $message): void + { + global $assertions; + if (!$condition) { throw new RuntimeException($message); } + $assertions++; + } + function fixture(array $changes = []): array + { + CallRecord::$rows = [new recovery_test\Record(array_replace([ + 'id' => 17, 'diagnosis_id' => 23, 'caller_id' => 91, 'caller_type' => 'doctor', + 'status' => 2, 'local_audio_status' => 2, 'local_audio_urls' => '["https://audio.invalid/synthetic.webm"]', + 'transcription_session_id' => 'original-session', 'transcription_status' => 'partial', + 'transcription_segment_count' => 1, 'transcript_text' => '未知说话人:片段', + ], $changes))]; + Db::$segments = [['call_record_id' => 17, 'transcription_session_id' => 'original-session', + 'segment_id' => 'old-1', 'text' => '片段', 'speaker_role' => 'unknown', 'timestamp_ms' => 10]]; + Db::$failSave = false; + return ['diagnosis_id' => 23, 'call_record_id' => 17, 'admin_id' => 91, + 'recovery_id' => 'audio-' . str_repeat('a', 32), 'expected_session_id' => 'original-session', + 'expected_status' => 'partial', 'audio_url' => 'https://audio.invalid/synthetic.webm', + 'transcript_text' => "完整的合成录音。\n保留结尾及否定:没有服药。"]; + } + function rejects(array $params, string $label): void + { + $before = serialize([CallRecord::$rows, Db::$segments]); + check(Logic::saveLocalAudioTranscript($params) === false, $label . ' rejects'); + check(serialize([CallRecord::$rows, Db::$segments]) === $before, $label . ' does not mutate'); + } + + $params = fixture(); + $result = Logic::saveLocalAudioTranscript($params); + check($result === ['call_record_id' => 17, 'transcription_status' => 'completed', 'saved' => true], 'recovery saves'); + check(CallRecord::$rows[0]['transcription_session_id'] === $params['recovery_id'], 'new session is active'); + check(CallRecord::$rows[0]['transcript_text'] === '未知说话人:' . $params['transcript_text'], 'complete text retained without claiming a speaker'); + check(count(Db::$segments) === 2 && Db::$segments[0]['text'] === '片段', 'old session retained'); + check(Db::$segments[1]['speaker_role'] === 'unknown' && Db::$segments[1]['timestamp_ms'] === 0, 'no invented attribution or timing'); + $before = serialize([CallRecord::$rows, Db::$segments]); + check(Logic::saveLocalAudioTranscript($params) === $result, 'lost response retry is idempotent despite stale CAS'); + check(serialize([CallRecord::$rows, Db::$segments]) === $before, 'retry writes no duplicate segments'); + $late = Logic::upsertCallTranscriptSegments(['diagnosis_id' => 23, 'call_record_id' => 17, 'admin_id' => 91, + 'transcription_session_id' => 'original-session', 'segments' => [['segment_id' => 'late', 'text' => '迟到分段']]]); + check($late === false, 'old realtime writer cannot overwrite replacement session'); + $lateFinish = Logic::finishCallTranscription(['diagnosis_id' => 23, 'call_record_id' => 17, 'admin_id' => 91, + 'transcription_session_id' => 'original-session', 'status' => 'completed', 'expected_segment_count' => 1]); + check($lateFinish === false && serialize([CallRecord::$rows, Db::$segments]) === $before, 'late finish cannot overwrite replacement'); + + $params = fixture(['transcription_status' => 'completed']); + $before = serialize([CallRecord::$rows, Db::$segments]); + check(Logic::saveLocalAudioTranscript($params) === ['call_record_id' => 17, 'transcription_status' => 'completed', + 'saved' => false, 'already_complete' => true], 'another complete session wins even with stale CAS'); + check(serialize([CallRecord::$rows, Db::$segments]) === $before, 'completed transcript never overwritten'); + foreach (['', 'pending', 'running', 'partial', 'failed', 'completed'] as $status) { + $params = fixture(['transcription_status' => $status, 'transcript_text' => '']); + $params['expected_status'] = $status; + check(Logic::saveLocalAudioTranscript($params)['saved'] === true, 'recover empty/nonterminal session ' . $status); + } + $params = fixture(['transcription_session_id' => '', 'transcription_status' => '', 'transcript_text' => '']); + $params['expected_session_id'] = $params['expected_status'] = ''; + check(Logic::saveLocalAudioTranscript($params)['saved'] === true, 'record without prior session can recover'); + + foreach (['expected_session_id' => 'changed-session', 'expected_status' => 'running', + 'audio_url' => 'https://audio.invalid/different.webm', 'admin_id' => 92, 'diagnosis_id' => 24, + 'call_record_id' => 18, 'recovery_id' => 'invalid', 'transcript_text' => ' '] as $key => $value) { + $params = fixture(); $params[$key] = $value; rejects($params, 'invalid ' . $key); + } + foreach ([['status' => 1], ['status' => 3], ['caller_type' => 'patient'], ['local_audio_status' => 0], + ['local_audio_urls' => 'invalid'], ['local_audio_urls' => '[]']] as $changes) { + rejects(fixture($changes), 'invalid record ' . json_encode($changes)); + } + foreach ([null, [], false, 23] as $value) { + $params = fixture(); $params['transcript_text'] = $value; rejects($params, 'non-string text'); + } + $params = fixture(); $params['transcript_text'] = str_repeat('字', 100001); rejects($params, 'oversize text'); + $params = fixture(); $params['transcript_text'] = str_repeat('字', 100000); + check(Logic::saveLocalAudioTranscript($params)['saved'] === true, 'Unicode limit counts characters'); + $newSegments = array_slice(Db::$segments, 1); + check(count($newSegments) === 25 && implode('', array_column($newSegments, 'text')) === $params['transcript_text'], + 'bounded segments preserve all 100000 characters in order'); + check(max(array_map(static fn ($row) => mb_strlen($row['text']), $newSegments)) <= 4000, 'segment schema limit respected'); + + $params = fixture(); Db::$failSave = true; + rejects($params, 'transaction rollback after segment insertion'); + check(!str_contains(Logic::getError(), 'Synthetic'), 'internal failure detail is not exposed'); + + fixture(['transcription_status' => 'running', 'transcript_text' => '', 'transcription_segment_count' => 0]); + Db::$segments = []; + $finish = ['diagnosis_id' => 23, 'call_record_id' => 17, 'admin_id' => 91, + 'transcription_session_id' => 'original-session', 'status' => 'completed', 'expected_segment_count' => 0]; + check(Logic::finishCallTranscription($finish)['status'] === 'failed', 'zero-segment completion is failed'); + fixture(['transcription_status' => 'running']); + $finish['expected_segment_count'] = 2; + check(Logic::finishCallTranscription($finish)['status'] === 'partial', 'missing requested segments stays partial'); + fixture(['transcription_status' => 'running']); + $finish['expected_segment_count'] = 1; + check(Logic::finishCallTranscription($finish)['status'] === 'completed', 'nonempty complete realtime session still completes'); + + echo "Local audio transcript recovery: {$assertions} assertions passed (no DB or network)\n"; +} diff --git a/server/tests/MobileRecordingBindingTest.php b/server/tests/MobileRecordingBindingTest.php new file mode 100644 index 000000000..d2ded137f --- /dev/null +++ b/server/tests/MobileRecordingBindingTest.php @@ -0,0 +1,157 @@ +setConfig(['default' => 'sqlite', 'auto_timestamp' => false, 'datetime_format' => false, + 'connections' => ['sqlite' => ['type' => 'sqlite', 'database' => ':memory:', 'prefix' => 'zyt_']]]); +Container::getInstance()->instance('think\DbManager', $manager); +$config = new think\Config(); +$config->set(['data_scope' => ['enabled' => false]], 'project'); +Container::getInstance()->instance('config', $config); + +foreach ([ + 'CREATE TABLE zyt_admin (id INTEGER PRIMARY KEY, root INT, name TEXT, disable INT, delete_time INT)', + 'CREATE TABLE zyt_admin_role (admin_id INT, role_id INT)', + 'CREATE TABLE zyt_system_role_menu (role_id INT, menu_id INT)', + 'CREATE TABLE zyt_system_menu (id INTEGER PRIMARY KEY, perms TEXT, is_disable INT)', + 'CREATE TABLE zyt_tcm_diagnosis (id INTEGER PRIMARY KEY, patient_id INT, patient_name TEXT, phone TEXT, assistant_id INT, status INT, delete_time INT)', + 'CREATE TABLE zyt_doctor_appointment (id INTEGER PRIMARY KEY, patient_id INT, doctor_id INT, status INT)', + 'CREATE TABLE zyt_mobile_recording_binding (id INTEGER PRIMARY KEY AUTOINCREMENT, admin_id INT NOT NULL, + installation_id TEXT NOT NULL, recording_key TEXT NOT NULL, diagnosis_id INT NOT NULL, source_platform TEXT NOT NULL, + recorded_at INT NOT NULL, duration_ms INT NOT NULL, created_at INT NOT NULL, updated_at INT NOT NULL, + UNIQUE(admin_id, installation_id, recording_key))', +] as $ddl) { + Db::execute($ddl); +} +Db::name('admin')->insertAll([ + ['id' => 1, 'root' => 1, 'name' => '合成管理员', 'disable' => 0], + ['id' => 11, 'root' => 0, 'name' => '合成助理甲', 'disable' => 0], + ['id' => 12, 'root' => 0, 'name' => '合成助理乙', 'disable' => 0], + ['id' => 13, 'root' => 0, 'name' => '合成医生', 'disable' => 0], + ['id' => 14, 'root' => 0, 'name' => '合成停用账号', 'disable' => 1], + ['id' => 15, 'root' => 0, 'name' => '合成无权限账号', 'disable' => 0], +]); +Db::name('admin_role')->insertAll([ + ['admin_id' => 11, 'role_id' => 2], ['admin_id' => 12, 'role_id' => 2], + ['admin_id' => 13, 'role_id' => 1], ['admin_id' => 14, 'role_id' => 2], +]); +Db::name('system_menu')->insert(['id' => 1, 'perms' => Logic::PAGE_PERMISSION, 'is_disable' => 0]); +Db::name('system_role_menu')->insertAll([['role_id' => 1, 'menu_id' => 1], ['role_id' => 2, 'menu_id' => 1]]); +Db::name('tcm_diagnosis')->insertAll([ + ['id' => 101, 'patient_id' => 501, 'patient_name' => '合成患者甲', 'phone' => '13800000001', 'assistant_id' => 11, 'status' => 1, 'delete_time' => null], + ['id' => 102, 'patient_id' => 502, 'patient_name' => '合成患者乙', 'phone' => '13800000002', 'assistant_id' => 11, 'status' => 1, 'delete_time' => null], + ['id' => 103, 'patient_id' => 503, 'patient_name' => '合成患者丙', 'phone' => '13800000003', 'assistant_id' => 12, 'status' => 1, 'delete_time' => null], + ['id' => 104, 'patient_id' => 504, 'patient_name' => '合成停用患者', 'phone' => '', 'assistant_id' => 11, 'status' => 0, 'delete_time' => null], + ['id' => 105, 'patient_id' => 505, 'patient_name' => '合成已删患者', 'phone' => '', 'assistant_id' => 11, 'status' => 1, 'delete_time' => 1], + ['id' => 106, 'patient_id' => 506, 'patient_name' => '合成接诊患者', 'phone' => '', 'assistant_id' => 12, 'status' => 1, 'delete_time' => null], +]); +Db::name('doctor_appointment')->insert(['id' => 1, 'patient_id' => 106, 'doctor_id' => 13, 'status' => 3]); + +$checks = 0; +$expect = static function (bool $ok, string $why) use (&$checks): void { + if (!$ok) { throw new RuntimeException($why); } + $checks++; +}; +$denied = static function (callable $call, string $why) use ($expect): void { + try { $call(); } catch (DomainException $e) { $expect(true, $why); return; } + throw new RuntimeException('Expected denial: ' . $why); +}; +$input = [ + 'installation_id' => '12345678-1234-4123-8123-123456789abc', + 'recording_key' => str_repeat('a', 64), 'diagnosis_id' => 101, + 'source_platform' => 'android_bcr', 'recorded_at' => 1700000000000, 'duration_ms' => 65000, +]; +$identity = array_intersect_key($input, array_flip(['installation_id', 'recording_key'])); +foreach ([ + ['admin_id' => 1], ['phone' => '13800000000'], ['file_name' => 'secret.wav'], + ['audio_path' => '/private/audio'], ['transcript_text' => 'content'], +] as $extra) { + $denied(fn () => Logic::bindingInput($input + $extra), 'unexpected private or actor field rejected'); +} +foreach ([ + ['installation_id' => 'not-a-uuid'], ['recording_key' => '../path'], ['diagnosis_id' => true], + ['duration_ms' => 1.5], ['duration_ms' => -1], ['duration_ms' => 604800001], + ['recorded_at' => (time() + 3600) * 1000], ['recorded_at' => '1e10'], ['source_platform' => 'other'], +] as $invalid) { + $denied(fn () => Logic::bindingInput(array_replace($input, $invalid)), 'invalid typed field rejected'); +} +$denied(fn () => Logic::bind($input, 15), 'missing page permission'); +$denied(fn () => Logic::bind($input, 14), 'disabled actor'); +$denied(fn () => Logic::bind($input, 0), 'missing actor'); +$denied(fn () => Logic::bind(array_replace($input, ['diagnosis_id' => 103]), 11), 'other assistant patient'); +$denied(fn () => Logic::bind(array_replace($input, ['diagnosis_id' => 104]), 11), 'disabled patient'); +$denied(fn () => Logic::bind(array_replace($input, ['diagnosis_id' => 105]), 11), 'deleted patient'); +$created = Logic::bind($input, 11)['binding']; +$again = Logic::bind($input, 11)['binding']; +$expect($created['id'] === $again['id'] && Db::name('mobile_recording_binding')->count() === 1, 'repeat bind is idempotent'); +$expect($created['patient']['diagnosis_id'] === 101 && $created['patient']['source_patient_id'] === 501, 'separate diagnosis/source patient identities'); +$expect($created['patient']['phone_masked'] === '138****0001', 'masked phone only'); +$expect(!str_contains(json_encode($created), '13800000001') && !isset($created['admin_id']), 'private data and actor ID omitted'); + +$other = Logic::bind(array_replace($input, ['diagnosis_id' => 103]), 12)['binding']; +$expect($other['id'] !== $created['id'], 'unique key includes current actor'); +Logic::unbind($identity, 12); +Logic::unbind($identity, 12); +$expect(Db::name('mobile_recording_binding')->where('id', $created['id'])->count() === 1, 'another actor unbind cannot touch original row'); +$denied(fn () => Logic::bind(array_replace($input, ['diagnosis_id' => 103]), 11), 'replacement target is checked'); +$replaced = Logic::bind(array_replace($input, ['diagnosis_id' => 102]), 11)['binding']; +$expect($replaced['id'] === $created['id'] && $replaced['diagnosis_id'] === 102, 'replacement updates existing identity'); + +$second = array_replace($input, ['recording_key' => str_repeat('b', 64)]); +Logic::bind($second, 11); +$device = ['installation_id' => $input['installation_id']]; +$page = Logic::deviceLists($device + ['page_no' => 1, 'page_size' => 1], 11); +$expect($page['count'] === 2 && count($page['lists']) === 1 && $page['page_size'] === 1, 'bounded device pagination'); +$expect(Logic::deviceLists(['installation_id' => '22345678-1234-4123-8123-123456789abc'], 11)['count'] === 0, 'device isolation'); +$expect(Logic::deviceLists($device, 12)['count'] === 0, 'account isolation'); +$denied(fn () => Logic::patientLists(['diagnosis_id' => 102], 12), 'patient listing scope'); +$records = Logic::patientLists(['diagnosis_id' => 102], 11); +$record = $records['lists'][0]; +$expect($record['bound_by'] === '合成助理甲' && $record['playback_location'] === 'original_device', 'archive playback and actor metadata'); +$expect(!isset($record['installation_id'], $record['recording_key']) && !isset($record['patient_name']), 'archive omits device keys and unnecessary patient names'); +$denied(fn () => Logic::deviceLists($device + ['page_size' => 101], 11), 'page limit'); + +$doctor = Logic::bind(array_replace($input, ['diagnosis_id' => 106]), 13); +$expect($doctor['binding']['diagnosis_id'] === 106, 'doctor uses own effective appointment'); +$denied(fn () => Logic::bind($input, 13), 'doctor cannot use unrelated patient'); +Logic::bind(array_replace($input, ['diagnosis_id' => 103]), 1); +$expect(Logic::patientLists(['diagnosis_id' => 103], 1)['count'] === 1, 'root uses same metadata contract'); + +Db::name('tcm_diagnosis')->where('id', 102)->update(['assistant_id' => 12]); +$denied(fn () => Logic::bind($input, 11), 'old patient checked on reassignment after scope loss'); +$denied(fn () => Logic::unbind($identity, 11), 'old patient checked on unlink after scope loss'); +$afterTransfer = Logic::deviceLists($device, 11); +$expect($afterTransfer['count'] === 1 && !str_contains(json_encode($afterTransfer, JSON_UNESCAPED_UNICODE), '合成患者乙'), 'lost-scope row and patient name hidden'); +Db::name('tcm_diagnosis')->where('id', 101)->update(['delete_time' => 2]); +$expect(Logic::deviceLists($device, 11)['count'] === 0, 'deleted diagnosis hidden on restore'); +$denied(fn () => Logic::patientLists(['diagnosis_id' => 101], 11), 'deleted patient archive denied'); +Db::name('tcm_diagnosis')->where('id', 101)->update(['delete_time' => null]); +Logic::unbind(array_replace($identity, ['recording_key' => str_repeat('b', 64)]), 11); +$expect(Logic::deviceLists($device, 11)['count'] === 0, 'authorized unbind removes association'); +Db::name('system_menu')->where('id', 1)->update(['is_disable' => 1]); +$denied(fn () => Logic::deviceLists($device, 11), 'revoked page permission is re-read'); +Db::name('admin')->where('id', 1)->update(['root' => 0]); +$denied(fn () => Logic::deviceLists($device, 1), 'revoked root is re-read'); + +// Guard the integration boundary which runtime service tests cannot exercise without an HTTP app. +$controller = file_get_contents(dirname(__DIR__) . '/app/adminapi/controller/tcm/MobileRecordingController.php'); +$middleware = file_get_contents(dirname(__DIR__) . '/app/adminapi/http/middleware/AuthMiddleware.php'); +$expect(str_contains($controller, 'MobileRecordingLogic::actor((int) $this->adminId)'), 'controller explicitly checks page grant'); +$expect(str_contains($controller, '$this->request->file()'), 'controller refuses binary upload'); +$expect(str_contains($middleware, "'tcm.mobilerecording/'") + && strpos($middleware, "'tcm.mobilerecording/'") < strpos($middleware, '$allUri ='), 'middleware guards before legacy unregistered-route bypass'); +echo "Mobile recording binding: {$checks} checks passed (synthetic in-memory SQLite).\n";