From de990a921bd16646610100bd95cd8b91ff6ecf4e Mon Sep 17 00:00:00 2001 From: Your Name Date: Tue, 11 Aug 2026 10:02:40 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/src/doctor_workstation/app.py | 211 ++++++++++++++--- app/src/doctor_workstation/core/models.py | 19 +- .../services/mock_repository.py | 26 ++- .../doctor_workstation/services/repository.py | 67 +++++- .../ui/diagnosis_index_widgets.py | 49 +++- .../ui/pages/consultations.py | 131 ++++++++--- app/src/doctor_workstation/ui/shell.py | 3 + app/src/doctor_workstation/video/__init__.py | 8 + app/src/doctor_workstation/video/launcher.py | 173 ++++++++++++++ app/src/doctor_workstation/video/window.py | 138 ++++++++++- app/tests/test_consultations_parity_ui.py | 168 +++++++++++++- app/tests/test_diagnosis_index_visual.py | 11 +- app/tests/test_repository_parity.py | 76 ++++++ app/tests/test_video_contract.py | 54 +++++ .../dist/assets/index-BuO_uDya.css | 1 - .../dist/assets/index-CG-V4g-D.css | 1 + .../{index-le5ZH3pL.js => index-DluArHub.js} | 168 +++++++------- app/video_companion/dist/index.html | 4 +- app/video_companion/package-lock.json | 1 + app/video_companion/package.json | 1 + app/video_companion/src/App.vue | 6 +- app/video_companion/src/env.d.ts | 18 ++ app/video_companion/src/main.ts | 217 +++++++++++++++++- app/video_companion/src/style.css | 35 +++ .../src/views/tcm/follow => follow}/index.vue | 0 25 files changed, 1412 insertions(+), 174 deletions(-) delete mode 100644 app/video_companion/dist/assets/index-BuO_uDya.css create mode 100644 app/video_companion/dist/assets/index-CG-V4g-D.css rename app/video_companion/dist/assets/{index-le5ZH3pL.js => index-DluArHub.js} (73%) rename {admin/src/views/tcm/follow => follow}/index.vue (100%) diff --git a/app/src/doctor_workstation/app.py b/app/src/doctor_workstation/app.py index d6c656c3e..4cdc27ecc 100644 --- a/app/src/doctor_workstation/app.py +++ b/app/src/doctor_workstation/app.py @@ -40,7 +40,7 @@ from doctor_workstation.ui.widgets import ( set_authentication_expired_handler, show_toast, ) -from doctor_workstation.video import BackendMode, launch_video_call +from doctor_workstation.video import BackendMode, launch_video_call, launch_video_watch from doctor_workstation.video.window import WEBENGINE_AVAILABLE LOGGER = logging.getLogger(__name__) @@ -66,10 +66,17 @@ class _UnconfiguredRepository: class DemoVideoDialog(QDialog): """Non-network video-room preview used only by the explicit demo mode.""" - def __init__(self, patient_name: str, parent: QWidget | None = None) -> None: + def __init__( + self, + patient_name: str, + parent: QWidget | None = None, + *, + watch_only: bool = False, + ) -> None: super().__init__(parent) self._seconds = 0 - self.setWindowTitle("视频面诊 · 演示模式") + self.watch_only = watch_only + self.setWindowTitle("旁观视频通话 · 演示模式" if watch_only else "视频面诊 · 演示模式") self.setMinimumSize(760, 520) self.resize(980, 660) self.setModal(False) @@ -88,7 +95,11 @@ class DemoVideoDialog(QDialog): root.setContentsMargins(22, 18, 22, 22) root.setSpacing(14) header = QHBoxLayout() - title = QLabel(f"与 {patient_name or '患者'} 的视频面诊") + title = QLabel( + f"旁观 {patient_name or '患者'} 的视频通话" + if watch_only + else f"与 {patient_name or '患者'} 的视频面诊" + ) title.setStyleSheet("font-size:18px;font-weight:700;") header.addWidget(title) header.addStretch(1) @@ -112,41 +123,47 @@ class DemoVideoDialog(QDialog): "background:#DDF1EC;color:#0F6D64;border-radius:52px;font-size:42px;font-weight:700;" ) stage_layout.addWidget(avatar, 0, Qt.AlignmentFlag.AlignHCenter) - waiting = QLabel("等待患者接听…") + waiting = QLabel("旁观演示画面" if watch_only else "等待患者接听…") waiting.setAlignment(Qt.AlignmentFlag.AlignCenter) waiting.setStyleSheet("font-size:17px;font-weight:600;") stage_layout.addWidget(waiting) - hint = QLabel("生产模式将通过后端短时 UserSig 初始化腾讯 TUICallKit") + hint = QLabel( + "仅观看,不会开启摄像头与麦克风" + if watch_only + else "生产模式将通过后端短时 UserSig 初始化腾讯 TUICallKit" + ) hint.setAlignment(Qt.AlignmentFlag.AlignCenter) hint.setStyleSheet("color:#80948D;font-size:12px;") stage_layout.addWidget(hint) stage_layout.addStretch(1) - local = QFrame(stage) - local.setObjectName("LocalStage") - local.setGeometry(24, 24, 178, 112) - local_layout = QVBoxLayout(local) - local_label = QLabel("医生画面") - local_label.setAlignment(Qt.AlignmentFlag.AlignCenter) - local_label.setStyleSheet("color:#A9BDB6;font-weight:600;") - local_layout.addWidget(local_label) + if not watch_only: + local = QFrame(stage) + local.setObjectName("LocalStage") + local.setGeometry(24, 24, 178, 112) + local_layout = QVBoxLayout(local) + local_label = QLabel("医生画面") + local_label.setAlignment(Qt.AlignmentFlag.AlignCenter) + local_label.setStyleSheet("color:#A9BDB6;font-weight:600;") + local_layout.addWidget(local_label) root.addWidget(stage, 1) controls = QHBoxLayout() controls.addStretch(1) - self.mic_button = QPushButton("麦克风 开") - self.mic_button.setCheckable(True) - self.mic_button.toggled.connect( - lambda muted: self.mic_button.setText("麦克风 关" if muted else "麦克风 开") - ) - controls.addWidget(self.mic_button) - self.camera_button = QPushButton("摄像头 开") - self.camera_button.setCheckable(True) - self.camera_button.toggled.connect( - lambda off: self.camera_button.setText("摄像头 关" if off else "摄像头 开") - ) - controls.addWidget(self.camera_button) - hangup = QPushButton("结束面诊") + if not watch_only: + self.mic_button = QPushButton("麦克风 开") + self.mic_button.setCheckable(True) + self.mic_button.toggled.connect( + lambda muted: self.mic_button.setText("麦克风 关" if muted else "麦克风 开") + ) + controls.addWidget(self.mic_button) + self.camera_button = QPushButton("摄像头 开") + self.camera_button.setCheckable(True) + self.camera_button.toggled.connect( + lambda off: self.camera_button.setText("摄像头 关" if off else "摄像头 开") + ) + controls.addWidget(self.camera_button) + hangup = QPushButton("离开旁观" if watch_only else "结束面诊") hangup.setObjectName("Hangup") hangup.clicked.connect(self.close) controls.addWidget(hangup) @@ -179,6 +196,8 @@ class ApplicationController(QObject): self.current_demo_mode = config.demo_mode self.video_calls: dict[str, Any] = {} self.video_pending: dict[str, object] = {} + self.video_watches: dict[str, Any] = {} + self.watch_pending: dict[str, object] = {} self.demo_video_dialogs: dict[str, DemoVideoDialog] = {} self._restore_generation = 0 self._restore_in_progress = False @@ -441,6 +460,7 @@ class ApplicationController(QObject): self.shell_window = ShellWindow(repository, payload, session.permissions) self.shell_window.logout_requested.connect(self._logout) self.shell_window.video_requested.connect(self._request_video) + self.shell_window.watch_requested.connect(self._request_watch) self._apply_window_icon(self.shell_window) if self.login_window is not None: self.login_window.hide() @@ -478,6 +498,11 @@ class ApplicationController(QObject): self._wait_for_video_lifecycle(calls, timeout=1.25) self.video_calls.clear() self.video_pending.clear() + for watch in self.video_watches.values(): + with suppress(Exception): + watch.close() + self.video_watches.clear() + self.watch_pending.clear() for dialog in self.demo_video_dialogs.values(): dialog.close() self.demo_video_dialogs.clear() @@ -508,7 +533,10 @@ class ApplicationController(QObject): if ( call_key in self.video_pending or call_key in self.video_calls + or call_key in self.watch_pending + or call_key in self.video_watches or call_key in self.demo_video_dialogs + or f"watch:{call_key}" in self.demo_video_dialogs ): show_toast(parent, "该问诊的视频正在准备或通话中。", "info", 3600) return @@ -630,6 +658,130 @@ class ApplicationController(QObject): if self.video_calls.get(call_key) is call: self.video_calls.pop(call_key, None) + def _request_watch(self, payload: dict[str, Any]) -> None: + """Fetch a server-authorized receive-only room ticket for one diagnosis.""" + + parent = self.shell_window + repository = self.current_repository + if parent is None or repository is None: + return + diagnosis_id = payload.get("diagnosis_id") + patient_name = str(payload.get("patient_name") or "患者") + try: + diagnosis_value = int(diagnosis_id) + except (TypeError, ValueError): + diagnosis_value = 0 + if diagnosis_value <= 0: + show_toast(parent, "诊单信息不完整,无法进入旁观。", "danger", 4200) + return + watch_key = str(diagnosis_value) + if ( + watch_key in self.watch_pending + or watch_key in self.video_watches + or watch_key in self.video_pending + or watch_key in self.video_calls + or f"watch:{watch_key}" in self.demo_video_dialogs + ): + show_toast(parent, "该诊单的视频会话正在准备或进行中。", "info", 3600) + return + if self.current_demo_mode: + demo_key = f"watch:{watch_key}" + dialog = DemoVideoDialog(patient_name, parent, watch_only=True) + dialog.finished.connect( + lambda _result, key=demo_key, item=dialog: self._forget_demo_dialog(key, item) + ) + self.demo_video_dialogs[demo_key] = dialog + dialog.show() + return + + show_toast(parent, "正在获取旁观房间凭证…", "info") + marker = object() + self.watch_pending[watch_key] = marker + run_async( + lambda: repository.get_assistant_watch_ticket(diagnosis_value), + on_success=lambda ticket: self._launch_watch( + ticket, + diagnosis_id=diagnosis_value, + repository=repository, + watch_key=watch_key, + marker=marker, + ), + on_error=lambda error: self._watch_ticket_error( + watch_key, + marker, + parent, + error, + ), + ) + + def _watch_ticket_error( + self, + watch_key: str, + marker: object, + parent: QWidget, + error: Exception, + ) -> None: + if self.watch_pending.get(watch_key) is not marker: + return + self.watch_pending.pop(watch_key, None) + if self.shell_window is parent: + show_toast(parent, f"旁观准备失败:{friendly_error(error)}", "danger", 5200) + + def _launch_watch( + self, + ticket: Any, + *, + diagnosis_id: int, + repository: Any, + watch_key: str, + marker: object, + ) -> None: + if self.watch_pending.get(watch_key) is not marker: + return + self.watch_pending.pop(watch_key, None) + if ( + self.shell_window is None + or self.current_repository is not repository + or watch_key in self.video_watches + ): + return + try: + mode = BackendMode.parse(self.config.video_mode) + if mode is BackendMode.BROWSER: + raise ValueError("浏览器旁观模式未启用,请使用嵌入式视频组件。") + if not WEBENGINE_AVAILABLE: + raise ValueError("当前安装缺少 QtWebEngine,无法打开旁观窗口。") + watch = launch_video_watch( + ticket, + diagnosis_id=diagnosis_id, + backend_mode=mode, + local_dist=video_dist_path(), + remote_url=self.config.video_web_url or None, + logger=logging.getLogger("doctor_workstation.video.watch"), + ) + except Exception as error: + LOGGER.exception("assistant watch could not be launched") + show_toast( + self.shell_window, + f"旁观启动失败:{friendly_error(error)}", + "danger", + 5600, + ) + return + self.video_watches[watch_key] = watch + qt_window = getattr(watch, "qt_window", None) + if qt_window is not None: + qt_window.destroyed.connect( + lambda _obj=None, key=watch_key, expected=watch: self._release_video_watch( + key, + expected, + ) + ) + + def _release_video_watch(self, watch_key: str, watch: Any) -> None: + if self.video_watches.get(watch_key) is watch: + self.video_watches.pop(watch_key, None) + def _forget_demo_dialog(self, call_key: str, dialog: DemoVideoDialog) -> None: if self.demo_video_dialogs.get(call_key) is dialog: self.demo_video_dialogs.pop(call_key, None) @@ -672,6 +824,11 @@ class ApplicationController(QObject): with suppress(Exception): call.close() self._wait_for_video_lifecycle(calls, timeout=1.25) + for watch in tuple(self.video_watches.values()): + with suppress(Exception): + watch.close() + self.video_watches.clear() + self.watch_pending.clear() if self.remote_repository is not None: with suppress(Exception): self.remote_repository.client.close() diff --git a/app/src/doctor_workstation/core/models.py b/app/src/doctor_workstation/core/models.py index 038253365..a329335ad 100644 --- a/app/src/doctor_workstation/core/models.py +++ b/app/src/doctor_workstation/core/models.py @@ -395,6 +395,7 @@ class Consultation: has_prescription: bool = False unserved_days: int | None = None video_hint: str = "" + video_call_hint: JSONDict = field(default_factory=dict) source: int | str | None = None source_text: str = "" remark: str = "" @@ -429,6 +430,12 @@ class Consultation: appointment_status_value = source.get("appointment_status") if appointment_status_value in (None, ""): appointment_status_value = appointment.get("status") + gender_value = source.get("gender", source.get("gender_desc")) + gender_description = _text(source.get("gender_desc")) + if not gender_description: + gender_number = _integer(gender_value, None) + gender_description = {0: "女", 1: "男"}.get(gender_number, "") + video_call_hint = _mapping(source.get("video_call_hint")) return cls( id=_integer(source.get("id", source.get("diagnosis_id")), 0) or 0, patient_id=_integer(source.get("patient_id", source.get("source_patient_id")), None), @@ -437,8 +444,8 @@ class Consultation: patient_phone=_text(source.get("patient_phone", source.get("phone"))), phone_masked=_text(source.get("phone_masked")), id_card=_text(source.get("id_card")), - gender=source.get("gender", source.get("gender_desc")), - gender_desc=_text(source.get("gender_desc")), + gender=gender_value, + gender_desc=gender_description, age=_integer(source.get("age"), None), doctor_id=_integer(source.get("doctor_id", appointment.get("doctor_id")), None), doctor_name=_text(source.get("doctor_name", appointment.get("doctor_name"))), @@ -504,7 +511,13 @@ class Consultation: unserved_days=_integer( source.get("unserved_days", source.get("unserved_day_count")), None ), - video_hint=_text(source.get("video_hint", source.get("call_hint"))), + video_hint=_text( + source.get( + "video_hint", + source.get("call_hint", video_call_hint.get("label")), + ) + ), + video_call_hint=dict(video_call_hint), source=source.get("source", source.get("diagnosis_source")), source_text=_text(source.get("source_text", source.get("source_name"))), remark=_text(source.get("remark")), diff --git a/app/src/doctor_workstation/services/mock_repository.py b/app/src/doctor_workstation/services/mock_repository.py index 7a259a54e..97c4f1b4d 100644 --- a/app/src/doctor_workstation/services/mock_repository.py +++ b/app/src/doctor_workstation/services/mock_repository.py @@ -29,6 +29,7 @@ from .repository import ( _audit_action, _body, _daily_record_body, + _diagnosis_create_body, _identified_body, _material_kind, _prescription_payload, @@ -62,6 +63,7 @@ DEMO_PERMISSIONS: tuple[str, ...] = ( "tcm.diagnosis/setRevisitSlotStartOffset", "tcm.diagnosis/guahaoLogList", "tcm.diagnosis/guahao", + "tcm.diagnosis/watchCall", "tcm.diagnosis/order", "tcm.diagnosis/qrcode", "tcm.diagnosis/videoQr", @@ -1455,6 +1457,13 @@ class DemoDoctorRepository: consultation.appointment_time = appointment.appointment_time return deepcopy(_appointment_dict(appointment)) + def create_diagnosis_appointment( + self, payload: Mapping[str, Any] | None = None, **fields: Any + ) -> dict[str, Any]: + """Create a demo appointment through the diagnosis workspace contract.""" + + return self.book_patient_appointment(payload, **fields) + def cancel_patient_appointment(self, appointment_id: int) -> dict[str, Any]: """Persist cancellation status 2 across all demo workspaces.""" @@ -1484,6 +1493,21 @@ class DemoDoctorRepository: raise ValueError("appointment_id must be positive") return self.cancel_patient_appointment(appointment_id) + def get_assistant_watch_ticket(self, diagnosis_id: int) -> dict[str, Any]: + """Return a non-production receive-only room ticket for UI demonstration.""" + + with self._lock: + consultation = self._find_consultation(diagnosis_id) + hint = consultation.raw.get("video_call_hint") + room_id = hint.get("room_id") if isinstance(hint, Mapping) else None + return { + "sdkAppId": 1400000000, + "userId": f"doctor_{consultation.assistant_id or 2001}", + "userSig": "DEMO_ONLY_NOT_A_REAL_SIGNATURE", + "roomId": int(room_id or 900001), + "patientName": consultation.patient_name, + } + def patient_detail(self, diagnosis_id: int) -> dict[str, Any]: """Return the complete readonly diagnosis aggregate.""" @@ -1645,7 +1669,7 @@ class DemoDoctorRepository: ) -> dict[str, Any]: """Create a new mutable demo diagnosis and matching patient row.""" - body = _body(diagnosis, fields) + body = _diagnosis_create_body(diagnosis, fields) with self._lock: diagnosis_id = max((row.id for row in self._consultations), default=500) + 1 body["id"] = diagnosis_id diff --git a/app/src/doctor_workstation/services/repository.py b/app/src/doctor_workstation/services/repository.py index 6ded7fd3c..3b0272e5a 100644 --- a/app/src/doctor_workstation/services/repository.py +++ b/app/src/doctor_workstation/services/repository.py @@ -223,12 +223,20 @@ class DoctorRepository(Protocol): ) -> Any: """Create an appointment from the patient workspace.""" + def create_diagnosis_appointment( + self, payload: Mapping[str, Any] | None = None, **fields: Any + ) -> Any: + """Create an appointment from the diagnosis workspace.""" + def cancel_patient_appointment(self, appointment_id: int) -> Any: """Cancel an appointment from the patient workspace.""" def cancel_diagnosis_appointment(self, appointment_id: int) -> Any: """Cancel a diagnosis-list appointment through the doctor route.""" + def get_assistant_watch_ticket(self, diagnosis_id: int) -> dict[str, Any]: + """Return a receive-only room ticket for the assigned assistant.""" + def get_diagnosis_detail(self, diagnosis_id: int, *, readonly: bool = False) -> dict[str, Any]: """Return an editable or permission-aware readonly diagnosis detail.""" @@ -1536,6 +1544,13 @@ class RemoteDoctorRepository: return self.client.post("firstvisit.myPatient/createAppointment", _body(payload, fields)) + def create_diagnosis_appointment( + self, payload: Mapping[str, Any] | None = None, **fields: Any + ) -> Any: + """Create an appointment through the canonical diagnosis-list route.""" + + return self.client.post("doctor.appointment/create", _body(payload, fields)) + def cancel_patient_appointment(self, appointment_id: int) -> Any: """Cancel an appointment through the patient-scoped endpoint.""" @@ -1548,6 +1563,18 @@ class RemoteDoctorRepository: raise ValueError("appointment_id must be positive") return self.client.post("doctor.appointment/cancel", {"id": appointment_id}) + def get_assistant_watch_ticket(self, diagnosis_id: int) -> dict[str, Any]: + """Load the server-authorized receive-only TRTC room parameters.""" + + if diagnosis_id <= 0: + raise ValueError("diagnosis_id must be positive") + return dict( + _require_mapping( + self.client.get("tcm.diagnosis/watchCall", {"diagnosis_id": diagnosis_id}), + "tcm.diagnosis/watchCall", + ) + ) + def patient_detail(self, diagnosis_id: int) -> dict[str, Any]: """Compatibility name for permission-aware readonly diagnosis details.""" @@ -1603,7 +1630,7 @@ class RemoteDoctorRepository: ) -> dict[str, Any]: """Create a diagnosis using the complete edit-form mapping.""" - body = _body(diagnosis, fields) + body = _diagnosis_create_body(diagnosis, fields) result = self.client.post("tcm.diagnosis/add", body) return _merge_result(body, result) @@ -2285,6 +2312,44 @@ def _body( return result +def _diagnosis_create_body( + payload: Mapping[str, Any] | None, + fields: Mapping[str, Any], +) -> dict[str, Any]: + """Validate the production ``tcm.diagnosis/add`` identity contract.""" + + body = _body(payload, fields) + patient_name = str(body.get("patient_name") or "").strip() + phone = str(body.get("phone") or "").strip() + diagnosis_type = str(body.get("diagnosis_type") or "").strip() + local_hospital_name = str(body.get("local_hospital_name") or "").strip() + if not patient_name: + raise ValueError("patient_name is required") + if not re.fullmatch(r"1[3-9]\d{9}", phone): + raise ValueError("phone must be a valid 11-digit mobile number") + gender = _to_int(body.get("gender"), -1) + if gender not in {0, 1}: + raise ValueError("gender must be 0 or 1") + age = _to_int(body.get("age"), -1) + if age < 0 or age > 150: + raise ValueError("age must be between 0 and 150") + if not diagnosis_type: + raise ValueError("diagnosis_type is required") + if not local_hospital_name: + raise ValueError("local_hospital_name is required") + body.update( + { + "patient_name": patient_name, + "phone": phone, + "gender": gender, + "age": age, + "diagnosis_type": diagnosis_type, + "local_hospital_name": local_hospital_name, + } + ) + return body + + _RECORD_DATE_PATTERN = re.compile(r"^\d{4}-\d{2}-\d{2}$") _RECORD_TIME_PATTERN = re.compile(r"^(?:[01]\d|2[0-3]):[0-5]\d$") diff --git a/app/src/doctor_workstation/ui/diagnosis_index_widgets.py b/app/src/doctor_workstation/ui/diagnosis_index_widgets.py index a763a1c86..985e33c13 100644 --- a/app/src/doctor_workstation/ui/diagnosis_index_widgets.py +++ b/app/src/doctor_workstation/ui/diagnosis_index_widgets.py @@ -1284,7 +1284,7 @@ class DiagnosisTableHost(QFrame): def __init__( self, *, - action_policy: Mapping[str, bool] | None = None, + action_policy: Mapping[str, Any] | None = None, parent: QWidget | None = None, ) -> None: super().__init__(parent) @@ -1419,8 +1419,51 @@ class DiagnosisTableHost(QFrame): layout = QHBoxLayout(host) layout.setContentsMargins(3, 2, 3, 2) layout.setAlignment(Qt.AlignmentFlag.AlignCenter) - video_capable = self.action_policy.get("video_call", False) - if video_capable and _appointment_active(record): + watch_state = str(first_value(record, "video_call_hint.state", default="none") or "none") + watch_label = display_text( + first_value(record, "video_call_hint.label", default=""), + "暂无可旁观通话", + ) + watch_user_id = _as_int(self.action_policy.get("watch_user_id")) + assigned_assistant_id = _as_int( + first_value(record, "assistant_id", "assistant", default=0) + ) + watch_capable = bool(self.action_policy.get("watch_call", False)) + assigned_watcher = ( + watch_capable + and watch_user_id > 0 + and assigned_assistant_id == watch_user_id + ) + video_capable = bool(self.action_policy.get("video_call", False)) + if assigned_watcher and watch_state in {"live", "pending_room"}: + button = QToolButton(host) + button.setText("进入旁观") + button.setProperty("rowLink", "success" if watch_state == "live" else "warning") + button.setCursor(Qt.CursorShape.PointingHandCursor) + button.setEnabled(watch_state == "live") + button.setToolTip( + "仅观看,不会开启摄像头与麦克风" + if watch_state == "live" + else "医生尚未接通或未同步房间号,请稍后再试" + ) + button.clicked.connect( + lambda _checked=False, item=record: self.action_requested.emit( + "watch_call", item + ) + ) + layout.addWidget(button) + elif assigned_watcher: + label = QLabel(watch_label, host) + label.setProperty("fixedMuted", True) + label.setAlignment(Qt.AlignmentFlag.AlignCenter) + label.setWordWrap(True) + layout.addWidget(label) + elif watch_state in {"live", "pending_room"}: + label = QLabel("通话中" if watch_state == "live" else "接通中", host) + label.setProperty("fixedMuted", True) + label.setAlignment(Qt.AlignmentFlag.AlignCenter) + layout.addWidget(label) + elif video_capable and _appointment_active(record): button = QToolButton(host) button.setText("进入视频问诊") button.setProperty("rowLink", "primary") diff --git a/app/src/doctor_workstation/ui/pages/consultations.py b/app/src/doctor_workstation/ui/pages/consultations.py index 30f762111..64e7e6b6a 100644 --- a/app/src/doctor_workstation/ui/pages/consultations.py +++ b/app/src/doctor_workstation/ui/pages/consultations.py @@ -390,6 +390,12 @@ def _watch_cell(_value: Any, row: Any) -> str: }.get(str(state), display_text(label or state)) +def _watch_state(row: Any) -> str: + """Return the server-authored assistant-watch state for one diagnosis.""" + + return str(first_value(row, "video_call_hint.state", default="none") or "none") + + def _option_rows(value: Any, dictionary_type: str = "") -> list[Any]: if isinstance(value, Sequence) and not isinstance(value, (str, bytes)): return list(value) @@ -428,7 +434,7 @@ class _DiagnosisCreateDialog(QDialog): form.addRow("手机号 *", self.phone) self.gender = QComboBox() self.gender.addItem("男", 1) - self.gender.addItem("女", 2) + self.gender.addItem("女", 0) form.addRow("性别 *", self.gender) self.age = QSpinBox() self.age.setRange(0, 150) @@ -445,6 +451,9 @@ class _DiagnosisCreateDialog(QDialog): form.addRow("诊断类型 *", self.diagnosis_type) self.syndrome_type = QLineEdit() form.addRow("证型", self.syndrome_type) + self.local_hospital_name = QLineEdit() + self.local_hospital_name.setMaxLength(255) + form.addRow("当地就诊医院名称 *", self.local_hospital_name) self.local_hospital_diagnosis = QLineEdit() form.addRow("当地医院诊断 *", self.local_hospital_diagnosis) root.addLayout(form) @@ -471,6 +480,7 @@ class _DiagnosisCreateDialog(QDialog): "fasting_blood_sugar": self.fasting_blood_sugar.value(), "diagnosis_type": self.diagnosis_type.text().strip(), "syndrome_type": self.syndrome_type.text().strip(), + "local_hospital_name": self.local_hospital_name.text().strip(), "local_hospital_diagnosis": [local_diagnosis] if local_diagnosis else [], "diagnosis_date": QDate.currentDate().toString("yyyy-MM-dd"), "status": 1, @@ -487,6 +497,9 @@ class _DiagnosisCreateDialog(QDialog): if not payload["diagnosis_type"]: self.banner.show_message("请输入诊断类型。", "warning") return + if not payload["local_hospital_name"]: + self.banner.show_message("请输入当地就诊医院名称。", "warning") + return if not payload["local_hospital_diagnosis"]: self.banner.show_message("请输入当地医院诊断。", "warning") return @@ -526,13 +539,14 @@ class _DiagnosisOrderDialog(QDialog): def __init__(self, record: Any, parent: QWidget | None = None) -> None: super().__init__(parent) - self._patient_id = _as_int(first_value(record, "patient_id", "source_patient_id")) + self._diagnosis_id = _as_int(first_value(record, "diagnosis_id", "id")) self.setWindowTitle("创建订单") self.setMinimumWidth(480) root = QVBoxLayout(self) form = QFormLayout() patient = QLabel( - f"{display_text(first_value(record, 'patient_name'), '患者')} (#{self._patient_id})" + f"{display_text(first_value(record, 'patient_name'), '患者')} " + f"(诊单 #{self._diagnosis_id})" ) patient.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) form.addRow("患者", patient) @@ -561,8 +575,8 @@ class _DiagnosisOrderDialog(QDialog): root.addWidget(buttons) def _accept_checked(self) -> None: - if self._patient_id <= 0: - QMessageBox.warning(self, "创建订单", "患者标识不完整,无法创建订单。") + if self._diagnosis_id <= 0: + QMessageBox.warning(self, "创建订单", "诊单标识不完整,无法创建订单。") return if self.order_type.currentData() is None: QMessageBox.warning(self, "创建订单", "请选择订单类型。") @@ -571,7 +585,8 @@ class _DiagnosisOrderDialog(QDialog): def payload(self) -> dict[str, Any]: return { - "patient_id": self._patient_id, + # The server order domain historically names the diagnosis owner ``patient_id``. + "patient_id": self._diagnosis_id, "order_type": _as_int(self.order_type.currentData()), "amount": float(self.amount.value()), "remark": self.remark.text().strip(), @@ -844,6 +859,7 @@ class ConsultationsPage(QWidget): """Diagnosis workspace with canonical filters and guarded row actions.""" video_requested = Signal(dict) + watch_requested = Signal(dict) def __init__( self, @@ -894,6 +910,10 @@ class ConsultationsPage(QWidget): "appointment_logs": _repository_method_name(repository, "list_appointment_logs"), "create_order": _repository_method_name(repository, "create_diagnosis_order"), "order_qr": _repository_method_name(repository, "generate_order_qrcode"), + "create_appointment": _repository_method_name( + repository, "create_diagnosis_appointment" + ), + "watch_call": _repository_method_name(repository, "get_assistant_watch_ticket"), } root = QVBoxLayout(self) @@ -1186,10 +1206,18 @@ class ConsultationsPage(QWidget): "view": _canonical_allowed(permissions, "tcm.diagnosis/readonlyDetail"), "edit": _canonical_allowed(permissions, "tcm.diagnosis/edit"), "prescription": _canonical_allowed(permissions, "tcm.diagnosis/kaifang"), - "appointment": _canonical_allowed(permissions, "tcm.diagnosis/guahao"), + "appointment": bool( + _canonical_allowed(permissions, "tcm.diagnosis/guahao") + and self._repository_methods["create_appointment"] + ), "assign": _canonical_allowed(permissions, "tcm.diagnosis/assign"), "delete": _canonical_allowed(permissions, "tcm.diagnosis/delete"), "video_call": self._native_video_capable, + "watch_call": bool( + _canonical_allowed(permissions, "tcm.diagnosis/watchCall") + and self._repository_methods["watch_call"] + ), + "watch_user_id": _as_int(first_value(current_user, "id", "user_id")), "appointment_cancel": bool( _canonical_allowed(permissions, "tcm.diagnosis/guahao") and self._repository_methods["cancel_appointment"] @@ -1870,6 +1898,7 @@ class ConsultationsPage(QWidget): "confirm_qr": self._request_confirm_qr, "appointment_logs": self._request_appointment_logs, "create_order": self._create_diagnosis_order, + "watch_call": self._request_watch_call, "delete": self._delete_selected, } handler = actions.get(action) @@ -2014,22 +2043,42 @@ class ConsultationsPage(QWidget): self._run_mutation(cancel, "医助指派已取消。") def _book_selected_appointment(self) -> None: - if not _canonical_allowed(self.permissions, "tcm.diagnosis/guahao"): + method_name = self._repository_methods.get("create_appointment") + if ( + not _canonical_allowed(self.permissions, "tcm.diagnosis/guahao") + or method_name is None + or self._mutation_pending + ): return record = self.table.current_data() if record is None: return + diagnosis_id = _as_int(first_value(record, "diagnosis_id", "id", default=0)) + if diagnosis_id <= 0: + show_toast(self, "诊单标识不完整,无法预约。", "warning") + return # Kept lazy to avoid making the two page modules import each other at startup. from .patients import _AppointmentDialog dialog = _AppointmentDialog(record, repository=self.repository, parent=self) if dialog.exec() != QDialog.DialogCode.Accepted: return - payload = MappingProxyType(dialog.payload()) + current = self.table.current_data() + if ( + not _canonical_allowed(self.permissions, "tcm.diagnosis/guahao") + or not callable(getattr(self.repository, method_name, None)) + or _as_int(first_value(current, "diagnosis_id", "id", default=0)) != diagnosis_id + ): + show_toast(self, "权限或当前诊单已变化,本次未预约。", "warning") + return + appointment_payload = dict(dialog.payload()) + # The doctor appointment contract names the diagnosis owner ``patient_id``. + appointment_payload["patient_id"] = diagnosis_id + payload = MappingProxyType(appointment_payload) self._run_mutation( lambda: invoke( self.repository, - "book_patient_appointment", + method_name, payload=payload, **payload, ), @@ -2289,9 +2338,8 @@ class ConsultationsPage(QWidget): ): return diagnosis_id = _as_int(first_value(record, "diagnosis_id", "id", default=0)) - patient_id = _as_int(first_value(record, "patient_id", "source_patient_id", default=0)) - if diagnosis_id <= 0 or patient_id <= 0: - show_toast(self, "患者或诊单标识不完整,无法创建订单。", "warning") + if diagnosis_id <= 0: + show_toast(self, "诊单标识不完整,无法创建订单。", "warning") return dialog = _DiagnosisOrderDialog(record, self) if dialog.exec() != QDialog.DialogCode.Accepted: @@ -2302,12 +2350,14 @@ class ConsultationsPage(QWidget): or not callable(getattr(self.repository, method_name, None)) or not callable(getattr(self.repository, qr_method_name, None)) or _as_int(first_value(current, "diagnosis_id", "id", default=0)) != diagnosis_id - or _as_int(first_value(current, "patient_id", "source_patient_id", default=0)) - != patient_id ): show_toast(self, "权限或当前诊单已变化,本次未创建订单。", "warning") return - payload = MappingProxyType(dialog.payload()) + order_payload = dict(dialog.payload()) + # The order endpoint also names the diagnosis owner ``patient_id``. + # Derive it from the selected row so a source patient id can never leak here. + order_payload["patient_id"] = diagnosis_id + payload = MappingProxyType(order_payload) snapshot = deepcopy(record) generation = self._begin_order_flow() run_async( @@ -2321,7 +2371,6 @@ class ConsultationsPage(QWidget): result, snapshot, diagnosis_id, - patient_id, generation, ), on_error=lambda error: self._diagnosis_order_create_error(error, generation), @@ -2346,7 +2395,6 @@ class ConsultationsPage(QWidget): self, generation: int, diagnosis_id: int, - patient_id: int, ) -> bool: if generation != self._order_flow_generation: return False @@ -2356,23 +2404,18 @@ class ConsultationsPage(QWidget): if method_name is None or not callable(getattr(self.repository, method_name, None)): return False current = self.table.current_data() - return bool( - _as_int(first_value(current, "diagnosis_id", "id", default=0)) == diagnosis_id - and _as_int(first_value(current, "patient_id", "source_patient_id", default=0)) - == patient_id - ) + return _as_int(first_value(current, "diagnosis_id", "id", default=0)) == diagnosis_id def _diagnosis_order_created( self, result: Any, record: Any, diagnosis_id: int, - patient_id: int, generation: int, ) -> None: if generation != self._order_flow_generation: return - if not self._order_flow_guard(generation, diagnosis_id, patient_id): + if not self._order_flow_guard(generation, diagnosis_id): self.banner.show_message("权限或当前诊单已变化,未展示付款二维码。", "danger") self._finish_order_flow(generation, refresh=True) return @@ -2390,7 +2433,6 @@ class ConsultationsPage(QWidget): lambda retry_order_no: self._request_order_qr( retry_order_no, diagnosis_id, - patient_id, generation, dialog, ) @@ -2400,7 +2442,6 @@ class ConsultationsPage(QWidget): self._request_order_qr( order_no, diagnosis_id, - patient_id, generation, dialog, ) @@ -2409,7 +2450,6 @@ class ConsultationsPage(QWidget): self, order_no: str, diagnosis_id: int, - patient_id: int, generation: int, dialog: _DiagnosisOrderQrDialog, ) -> None: @@ -2418,7 +2458,7 @@ class ConsultationsPage(QWidget): if order_no != dialog.order_no: dialog.set_failure("订单号已变化,无法生成付款二维码。", retryable=False) return - if not self._order_flow_guard(generation, diagnosis_id, patient_id): + if not self._order_flow_guard(generation, diagnosis_id): dialog.set_failure( "权限或当前诊单已变化,无法生成付款二维码。", retryable=False, @@ -2438,14 +2478,12 @@ class ConsultationsPage(QWidget): on_success=lambda result: self._diagnosis_order_qr_success( result, diagnosis_id, - patient_id, generation, dialog, ), on_error=lambda error: self._diagnosis_order_qr_error( error, diagnosis_id, - patient_id, generation, dialog, ), @@ -2456,13 +2494,12 @@ class ConsultationsPage(QWidget): self, result: Any, diagnosis_id: int, - patient_id: int, generation: int, dialog: _DiagnosisOrderQrDialog, ) -> None: if dialog is not self._order_qr_dialog or generation != self._order_flow_generation: return - if not self._order_flow_guard(generation, diagnosis_id, patient_id): + if not self._order_flow_guard(generation, diagnosis_id): dialog.set_failure( "权限或当前诊单已变化,未展示付款二维码。", retryable=False, @@ -2479,13 +2516,12 @@ class ConsultationsPage(QWidget): self, error: Exception, diagnosis_id: int, - patient_id: int, generation: int, dialog: _DiagnosisOrderQrDialog, ) -> None: if dialog is not self._order_qr_dialog or generation != self._order_flow_generation: return - retryable = self._order_flow_guard(generation, diagnosis_id, patient_id) + retryable = self._order_flow_guard(generation, diagnosis_id) message = ( f"付款二维码生成失败:{friendly_error(error)}" if retryable @@ -2904,6 +2940,31 @@ class ConsultationsPage(QWidget): return self.video_requested.emit(payload) + def _request_watch_call(self) -> None: + method_name = self._repository_methods.get("watch_call") + record = self.table.current_data() + if ( + not _canonical_allowed(self.permissions, "tcm.diagnosis/watchCall") + or method_name is None + or record is None + ): + return + diagnosis_id = _as_int(first_value(record, "diagnosis_id", "id", default=0)) + user_id = _as_int(first_value(self.current_user, "id", "user_id", default=0)) + assistant_id = _as_int(first_value(record, "assistant_id", "assistant", default=0)) + if diagnosis_id <= 0 or user_id <= 0 or assistant_id != user_id: + self.banner.show_message("仅当前诊单指派的医助可旁观通话。", "warning") + return + if _watch_state(record) != "live": + self.banner.show_message("医生尚未接通或未同步房间号,请稍后再试。", "warning") + return + self.watch_requested.emit( + { + "diagnosis_id": diagnosis_id, + "patient_name": display_text(first_value(record, "patient_name"), "患者"), + } + ) + def _poll_refresh(self) -> None: """Refresh rows and chip counts without showing the table mask.""" diff --git a/app/src/doctor_workstation/ui/shell.py b/app/src/doctor_workstation/ui/shell.py index bc69481a7..c34c3a4cf 100644 --- a/app/src/doctor_workstation/ui/shell.py +++ b/app/src/doctor_workstation/ui/shell.py @@ -457,6 +457,7 @@ class ShellWindow(QMainWindow): logout_requested = Signal() video_requested = Signal(dict) + watch_requested = Signal(dict) page_changed = Signal(str) def __init__( @@ -913,6 +914,8 @@ class ShellWindow(QMainWindow): ) if hasattr(page, "video_requested"): page.video_requested.connect(lambda payload: self.video_requested.emit(payload)) + if hasattr(page, "watch_requested"): + page.watch_requested.connect(lambda payload: self.watch_requested.emit(payload)) index = self.stack.addWidget(page) self.pages[item.key] = page self.page_titles[index] = title diff --git a/app/src/doctor_workstation/video/__init__.py b/app/src/doctor_workstation/video/__init__.py index 3d960521c..da35d44ce 100644 --- a/app/src/doctor_workstation/video/__init__.py +++ b/app/src/doctor_workstation/video/__init__.py @@ -5,8 +5,12 @@ from .launcher import ( VideoCallLauncher, VideoCallRequest, VideoTicketError, + VideoWatchLauncher, + VideoWatchRequest, launch_video_call, + launch_video_watch, normalize_backend_ticket, + normalize_backend_watch_ticket, require_supported_backend, ) from .lifecycle import OrderedCallLifecycle @@ -17,7 +21,11 @@ __all__ = [ "VideoCallLauncher", "VideoCallRequest", "VideoTicketError", + "VideoWatchLauncher", + "VideoWatchRequest", "launch_video_call", + "launch_video_watch", "normalize_backend_ticket", + "normalize_backend_watch_ticket", "require_supported_backend", ] diff --git a/app/src/doctor_workstation/video/launcher.py b/app/src/doctor_workstation/video/launcher.py index a45883f00..c46dcff6a 100644 --- a/app/src/doctor_workstation/video/launcher.py +++ b/app/src/doctor_workstation/video/launcher.py @@ -261,6 +261,70 @@ class VideoCallRequest: } +@dataclass(frozen=True, slots=True) +class VideoWatchRequest: + """Validated receive-only room ticket for an assigned medical assistant.""" + + sdk_app_id: int + user_id: str + user_sig: str = field(repr=False) + diagnosis_id: Identifier + room_id: int | None = None + str_room_id: str | None = None + patient_name: str = "" + backend_mode: BackendMode = BackendMode.EMBEDDED + + def __post_init__(self) -> None: + object.__setattr__(self, "sdk_app_id", _sdk_app_id(self.sdk_app_id)) + object.__setattr__(self, "user_id", _non_empty_string(self.user_id, "userID")) + object.__setattr__(self, "user_sig", _non_empty_string(self.user_sig, "userSig")) + object.__setattr__(self, "diagnosis_id", _identifier(self.diagnosis_id, "diagnosisId")) + numeric_room = self.room_id + string_room = str(self.str_room_id or "").strip() + if numeric_room is not None: + if isinstance(numeric_room, bool): + raise VideoTicketError("roomId must be a positive integer") + try: + numeric_room = int(numeric_room) + except (TypeError, ValueError) as exc: + raise VideoTicketError("roomId must be a positive integer") from exc + if numeric_room <= 0: + raise VideoTicketError("roomId must be a positive integer") + object.__setattr__(self, "room_id", numeric_room) + if numeric_room is None and not string_room: + raise VideoTicketError("backend watch ticket is missing roomId or strRoomId") + if numeric_room is not None and string_room: + raise VideoTicketError("backend watch ticket has conflicting room identifiers") + object.__setattr__(self, "str_room_id", string_room or None) + object.__setattr__(self, "patient_name", str(self.patient_name or "").strip()) + object.__setattr__(self, "backend_mode", BackendMode.parse(self.backend_mode)) + + def to_web_config(self) -> dict[str, Any]: + """Return the in-memory receive-only Web companion configuration.""" + + config: dict[str, Any] = { + "SDKAppID": self.sdk_app_id, + "userID": self.user_id, + "userSig": self.user_sig, + "diagnosisId": self.diagnosis_id, + "patientName": self.patient_name, + } + if self.room_id is not None: + config["roomId"] = self.room_id + else: + config["strRoomId"] = self.str_room_id + return config + + def safe_log_context(self) -> dict[str, Any]: + """Return non-secret watch metadata suitable for structured logs.""" + + return { + "diagnosis_id": self.diagnosis_id, + "room_kind": "numeric" if self.room_id is not None else "string", + "backend_mode": self.backend_mode.value, + } + + def normalize_backend_ticket( ticket: Any, *, @@ -327,6 +391,70 @@ def normalize_backend_ticket( ) +def normalize_backend_watch_ticket( + ticket: Mapping[str, Any], + *, + diagnosis_id: Any, + backend_mode: BackendMode | str = BackendMode.EMBEDDED, +) -> VideoWatchRequest: + """Normalize the canonical ``tcm.diagnosis/watchCall`` response.""" + + if not isinstance(ticket, Mapping): + raise VideoTicketError("backend watch ticket must be a mapping") + payload = _ticket_payload(ticket) + payload_diagnosis = _read_aliases( + payload, + ("diagnosisId", "diagnosis_id"), + "diagnosisId", + _identifier, + required=False, + ) + normalized_diagnosis = _merge_identifier( + payload_diagnosis, + diagnosis_id, + "diagnosisId", + ) + room_id = _read_aliases( + payload, + ("roomId", "room_id"), + "roomId", + lambda value, field_name: _sdk_app_id(value, field_name), + required=False, + ) + str_room_id = _read_aliases( + payload, + ("strRoomId", "str_room_id"), + "strRoomId", + _non_empty_string, + required=False, + ) + return VideoWatchRequest( + sdk_app_id=_read_aliases( + payload, + ("SDKAppID", "sdkAppId", "sdkAppID"), + "SDKAppID", + _sdk_app_id, + ), + user_id=_read_aliases( + payload, + ("userID", "userId"), + "userID", + _non_empty_string, + ), + user_sig=_read_aliases( + payload, + ("userSig", "user_sig"), + "userSig", + _non_empty_string, + ), + diagnosis_id=normalized_diagnosis, + room_id=room_id, + str_room_id=str_room_id, + patient_name=str(payload.get("patientName", payload.get("patient_name", "")) or ""), + backend_mode=BackendMode.parse(backend_mode), + ) + + @dataclass(slots=True) class VideoCallLauncher: """Small composition root that defers the optional Qt import until launch.""" @@ -403,3 +531,48 @@ def launch_video_call( diagnosis_id=diagnosis_id, patient_id=patient_id, ) + + +@dataclass(slots=True) +class VideoWatchLauncher: + """Launcher for the receive-only assistant watch surface.""" + + backend_mode: BackendMode | str = BackendMode.EMBEDDED + local_dist: str | Path | None = None + remote_url: str | None = None + logger: Any = None + + def launch(self, ticket: Mapping[str, Any], *, diagnosis_id: Any) -> Any: + require_supported_backend(self.backend_mode) + request = normalize_backend_watch_ticket( + ticket, + diagnosis_id=diagnosis_id, + backend_mode=self.backend_mode, + ) + from .window import open_video_watch + + return open_video_watch( + request, + local_dist=self.local_dist, + remote_url=self.remote_url, + logger=self.logger, + ) + + +def launch_video_watch( + ticket: Mapping[str, Any], + *, + diagnosis_id: Any, + backend_mode: BackendMode | str = BackendMode.EMBEDDED, + local_dist: str | Path | None = None, + remote_url: str | None = None, + logger: Any = None, +) -> Any: + """Validate a server-issued room ticket and open a receive-only window.""" + + return VideoWatchLauncher( + backend_mode=backend_mode, + local_dist=local_dist, + remote_url=remote_url, + logger=logger, + ).launch(ticket, diagnosis_id=diagnosis_id) diff --git a/app/src/doctor_workstation/video/window.py b/app/src/doctor_workstation/video/window.py index c8cf16747..29ed7ce3d 100644 --- a/app/src/doctor_workstation/video/window.py +++ b/app/src/doctor_workstation/video/window.py @@ -21,6 +21,7 @@ from urllib.parse import parse_qsl, urlsplit from .launcher import ( VideoCallRequest, VideoTicketError, + VideoWatchRequest, require_supported_backend, ) from .lifecycle import OrderedCallLifecycle @@ -178,7 +179,10 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration message = json.loads(payload) except (TypeError, ValueError): return - if isinstance(message, Mapping) and message.get("source") == "doctor-call": + if isinstance(message, Mapping) and message.get("source") in { + "doctor-call", + "assistant-watch", + }: self._callback(message) class _EmbeddedVideoWindow(QMainWindow): # type: ignore[misc, valid-type] @@ -189,9 +193,9 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration def __init__( self, - request: VideoCallRequest, + request: VideoCallRequest | VideoWatchRequest, location: CompanionLocation, - lifecycle: OrderedCallLifecycle, + lifecycle: OrderedCallLifecycle | None, *, logger: logging.Logger, ) -> None: @@ -199,6 +203,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration self.request = request self.location = location self.lifecycle = lifecycle + self._watch_mode = isinstance(request, VideoWatchRequest) self.logger = logger try: self._policy = TrustedDocumentPolicy.from_url( @@ -216,7 +221,9 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration self._legacy_grants: list[tuple[Any, Any]] = [] self._permission_grants: list[Any] = [] - self.setWindowTitle("视频面诊") + title = "旁观视频通话" if self._watch_mode else "视频面诊" + patient_name = getattr(request, "patient_name", "") + self.setWindowTitle(f"{title} · {patient_name}" if patient_name else title) self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, True) self.resize(1120, 760) self.setMinimumSize(760, 520) @@ -271,7 +278,12 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration self._page.permissionRequested.connect(self._grant_media_permission) def _permission_context_is_trusted(self, origin: Any) -> bool: - if self._closing or self._released or not self._media_active: + if ( + self._watch_mode + or self._closing + or self._released + or not self._media_active + ): return False if not self._policy.allows_main_document(self._page.url().toString()): return False @@ -326,7 +338,13 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration self.close() return + if self._watch_mode: + self._start_watch_companion() + return + try: + if self.lifecycle is None: + raise VideoWindowError("video call lifecycle is unavailable") start_future = self.lifecycle.start() except Exception: self.logger.error( @@ -370,6 +388,28 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration """ self._page.runJavaScript(script, self._after_injection) + def _start_watch_companion(self) -> None: + """Inject receive-only room credentials without enabling capture.""" + + if self._closing: + return + self._media_active = True + config_json = json.dumps( + self.request.to_web_config(), + ensure_ascii=True, + separators=(",", ":"), + ) + script = f""" + (() => {{ + if (!window.doctorWatch || typeof window.doctorWatch.start !== 'function') {{ + return false; + }} + void window.doctorWatch.start({config_json}).catch(() => undefined); + return true; + }})() + """ + self._page.runJavaScript(script, self._after_injection) + def _after_injection(self, result: Any) -> None: self._injected = result is not False if not self._injected: @@ -379,9 +419,12 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration def _handle_bridge_message(self, message: Mapping[str, Any]) -> None: if self._closing: return + expected_source = "assistant-watch" if self._watch_mode else "doctor-call" + if message.get("source") != expected_source: + return event = str(message.get("event", "")) room_id = message.get("roomId", message.get("room_id")) - if room_id not in (None, ""): + if room_id not in (None, "") and self.lifecycle is not None: self.lifecycle.bind_room(room_id) if event == "room": return @@ -414,10 +457,14 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration self._closing = True self._media_active = False if self._injected and not self._companion_ended and not self._released: - self._page.runJavaScript( - "void window.doctorCall?.hangup?.().catch(() => undefined)" + script = ( + "void window.doctorWatch?.leave?.().catch(() => undefined)" + if self._watch_mode + else "void window.doctorCall?.hangup?.().catch(() => undefined)" ) - self.lifecycle.end(self._close_reason) + self._page.runJavaScript(script) + if self.lifecycle is not None: + self.lifecycle.end(self._close_reason) self._release_webengine() def _release_webengine(self) -> None: @@ -550,6 +597,58 @@ class VideoCallWindow: wait = wait_for_lifecycle +class VideoWatchWindow: + """Facade for one receive-only assistant watch session.""" + + def __init__( + self, + request: VideoWatchRequest, + *, + local_dist: str | Path | None = None, + remote_url: str | None = None, + logger: logging.Logger | None = None, + ) -> None: + try: + self.backend_mode = require_supported_backend(request.backend_mode) + except VideoTicketError as error: + raise VideoWindowError(str(error)) from error + if not WEBENGINE_AVAILABLE: + raise VideoWindowError( + "embedded video is unavailable and automatic browser fallback is disabled" + ) + if QApplication is None or QApplication.instance() is None: + raise VideoWindowError("embedded video requires an active QApplication") + self.request = request + self.logger = logger or _LOGGER + self.location = resolve_companion_location( + local_dist=local_dist, + remote_url=remote_url, + ) + self._session: Any = None + + @property + def qt_window(self) -> Any: + return self._session + + def open(self) -> VideoWatchWindow: + self._session = _EmbeddedVideoWindow( + self.request, + self.location, + None, + logger=self.logger, + ) + self._session.show() + self._session.raise_() + self._session.activateWindow() + return self + + show = open + + def close(self) -> None: + if self._session is not None: + self._session.close() + + def open_video_call( request: VideoCallRequest, *, @@ -573,13 +672,34 @@ def open_video_call( ).open() +def open_video_watch( + request: VideoWatchRequest, + *, + local_dist: str | Path | None = None, + remote_url: str | None = None, + logger: logging.Logger | None = None, +) -> VideoWatchWindow: + """Create and immediately open a trusted receive-only watch window.""" + + if not isinstance(request, VideoWatchRequest): + raise VideoTicketError("request must be a VideoWatchRequest") + return VideoWatchWindow( + request, + local_dist=local_dist, + remote_url=remote_url, + logger=logger, + ).open() + + __all__ = [ "CompanionLocation", "TrustedDocumentPolicy", "VideoCallWindow", + "VideoWatchWindow", "VideoWindowError", "WEBENGINE_AVAILABLE", "open_video_call", + "open_video_watch", "resolve_companion_location", "webengine_unavailable_reason", ] diff --git a/app/tests/test_consultations_parity_ui.py b/app/tests/test_consultations_parity_ui.py index 5eb9510be..ac3cd9564 100644 --- a/app/tests/test_consultations_parity_ui.py +++ b/app/tests/test_consultations_parity_ui.py @@ -12,6 +12,7 @@ from PySide6.QtWidgets import ( QApplication, QDialog, QInputDialog, + QLabel, QMessageBox, QToolButton, QWidget, @@ -20,6 +21,7 @@ from PySide6.QtWidgets import ( from doctor_workstation.core import PermissionSet from doctor_workstation.ui.dialogs import diagnosis as diagnosis_module from doctor_workstation.ui.pages import consultations as consultations_module +from doctor_workstation.ui.pages import patients as patients_module from doctor_workstation.ui.pages.consultations import ( ConsultationsPage, _video_payload, @@ -117,6 +119,166 @@ def test_video_condition_never_uses_diagnosis_status_or_missed_status() -> None: assert payload["patient_id"] == 301 +def test_create_and_order_dialogs_use_production_diagnosis_contract( + application: QApplication, +) -> None: + create_dialog = consultations_module._DiagnosisCreateDialog() + assert create_dialog.gender.itemData(create_dialog.gender.findText("女")) == 0 + create_dialog.patient_name.setText("林晓岚") + create_dialog.phone.setText("13800138000") + create_dialog.gender.setCurrentIndex(create_dialog.gender.findData(0)) + create_dialog.diagnosis_type.setText("复诊") + create_dialog.local_hospital_name.setText("杭州市第一人民医院") + create_dialog.local_hospital_diagnosis.setText("2型糖尿病") + payload = create_dialog.payload() + assert payload["gender"] == 0 + assert payload["local_hospital_name"] == "杭州市第一人民医院" + create_dialog.close() + + order_dialog = consultations_module._DiagnosisOrderDialog(_row(), None) + order_dialog.order_type.setCurrentIndex(order_dialog.order_type.findData(2)) + order_dialog.amount.setValue(88.5) + assert order_dialog.payload()["patient_id"] == 501 + order_dialog.close() + application.processEvents() + + +def test_diagnosis_appointment_uses_doctor_route_capability_and_diagnosis_owner( + application: QApplication, + immediate_async: None, + monkeypatch: pytest.MonkeyPatch, +) -> None: + calls: list[dict[str, Any]] = [] + + class Repository: + def create_diagnosis_appointment( + self, payload: dict[str, Any] | None = None, **fields: Any + ) -> dict[str, Any]: + calls.append(dict(payload or fields)) + return {"ok": True} + + class AcceptedAppointmentDialog: + def __init__(self, *_args: Any, **_kwargs: Any) -> None: + pass + + def exec(self) -> Any: + return QDialog.DialogCode.Accepted + + def payload(self) -> dict[str, Any]: + return { + "diagnosis_id": 501, + "patient_id": 301, + "doctor_id": 77, + "appointment_date": "2026-08-12", + "appointment_time": "09:00-09:30", + } + + page = ConsultationsPage( + Repository(), + permissions=PermissionSet(["tcm.diagnosis/guahao"]), + ) + page.table.set_rows([_row()]) + page.table.selectRow(0) + monkeypatch.setattr(patients_module, "_AppointmentDialog", AcceptedAppointmentDialog) + monkeypatch.setattr(page, "refresh", lambda *_args, **_kwargs: None) + + page._book_selected_appointment() + + assert calls == [ + { + "diagnosis_id": 501, + "patient_id": 501, + "doctor_id": 77, + "appointment_date": "2026-08-12", + "appointment_time": "09:00-09:30", + } + ] + page.close() + application.processEvents() + + +def test_assigned_assistant_can_enter_receive_only_live_watch( + application: QApplication, +) -> None: + class Repository: + def get_assistant_watch_ticket(self, diagnosis_id: int) -> dict[str, Any]: + return {"diagnosis_id": diagnosis_id} + + page = ConsultationsPage( + Repository(), + permissions=PermissionSet(["tcm.diagnosis/watchCall"]), + current_user={"id": 2001, "name": "周医助"}, + ) + row = _row( + assistant_id=2001, + video_call_hint={"state": "live", "label": "通话中", "room_id": 9001}, + ) + page.table.set_rows([row]) + page.table.selectRow(0) + requested: list[dict[str, Any]] = [] + page.watch_requested.connect(requested.append) + + watch_cell = page.table_host.fixed.indexWidget(page.table_host.model.index(0, 10)) + assert watch_cell is not None + watch_buttons = [ + button + for button in watch_cell.findChildren(QToolButton) + if button.text() == "进入旁观" + ] + assert len(watch_buttons) == 1 + assert watch_buttons[0].isEnabled() + assert "不会开启摄像头与麦克风" in watch_buttons[0].toolTip() + watch_buttons[0].click() + + assert requested == [{"diagnosis_id": 501, "patient_name": "林晓岚"}] + page.close() + application.processEvents() + + +def test_watch_entry_is_disabled_until_room_is_live_and_hidden_from_other_assistants( + application: QApplication, +) -> None: + class Repository: + def get_assistant_watch_ticket(self, diagnosis_id: int) -> dict[str, Any]: + return {"diagnosis_id": diagnosis_id} + + pending = ConsultationsPage( + Repository(), + permissions=PermissionSet(["tcm.diagnosis/watchCall"]), + current_user={"id": 2001}, + ) + pending.table.set_rows( + [ + _row( + assistant_id=2001, + video_call_hint={"state": "pending_room", "label": "接通中"}, + ) + ] + ) + pending_cell = pending.table_host.fixed.indexWidget(pending.table_host.model.index(0, 10)) + pending_button = next( + button + for button in pending_cell.findChildren(QToolButton) + if button.text() == "进入旁观" + ) + assert not pending_button.isEnabled() + pending.close() + + other = ConsultationsPage( + Repository(), + permissions=PermissionSet(["tcm.diagnosis/watchCall"]), + current_user={"id": 2002}, + ) + other.table.set_rows( + [_row(assistant_id=2001, video_call_hint={"state": "live", "label": "通话中"})] + ) + other_cell = other.table_host.fixed.indexWidget(other.table_host.model.index(0, 10)) + assert all(button.text() != "进入旁观" for button in other_cell.findChildren(QToolButton)) + assert any(label.text() == "通话中" for label in other_cell.findChildren(QLabel)) + other.close() + application.processEvents() + + def test_nested_appointments_confirmation_and_prescription_labels() -> None: row = _row( appointment_id=None, @@ -914,7 +1076,7 @@ def test_menu_handlers_call_only_permission_gated_real_repository_methods( ("logs", 501), ( "order", - {"patient_id": 301, "order_type": 2, "amount": 88.5, "remark": "复诊"}, + {"patient_id": 501, "order_type": 2, "amount": 88.5, "remark": "复诊"}, ), ("order_qr", "O-1"), ] @@ -1065,14 +1227,14 @@ def test_diagnosis_order_qr_failure_retries_without_creating_a_second_order( assert dialog.retry_button.isEnabled() assert "生成失败" in dialog.status_label.text() assert calls == [ - ("create", (301, 2, 88.5, "复诊")), + ("create", (501, 2, 88.5, "复诊")), ("qr", "PAY-RETRY-1"), ] dialog.retry_button.click() assert calls == [ - ("create", (301, 2, 88.5, "复诊")), + ("create", (501, 2, 88.5, "复诊")), ("qr", "PAY-RETRY-1"), ("qr", "PAY-RETRY-1"), ] diff --git a/app/tests/test_diagnosis_index_visual.py b/app/tests/test_diagnosis_index_visual.py index 0c09f4454..1a1ba3633 100644 --- a/app/tests/test_diagnosis_index_visual.py +++ b/app/tests/test_diagnosis_index_visual.py @@ -36,6 +36,9 @@ class _CancellationRepository: def cancel_diagnosis_appointment(self, appointment_id: int) -> None: del appointment_id + def create_diagnosis_appointment(self, payload: Any = None, **fields: Any) -> None: + del payload, fields + class _FullMenuRepository(_CancellationRepository): def generate_video_qrcode( @@ -466,9 +469,11 @@ def test_full_more_menu_requires_each_real_repository_capability( "appointment_cancel": True, "video_qr": True, "confirm_qr": True, - "appointment_logs": True, - "create_order": True, - } + "appointment_logs": True, + "create_order": True, + "watch_call": False, + "watch_user_id": 0, + } page.close() application.processEvents() diff --git a/app/tests/test_repository_parity.py b/app/tests/test_repository_parity.py index b5196b748..8388853ae 100644 --- a/app/tests/test_repository_parity.py +++ b/app/tests/test_repository_parity.py @@ -65,6 +65,13 @@ class RecordingClient: return {} if endpoint == "doctor.appointment/availableSlots": return {"slots": [{"time": "09:00", "available": True}]} + if endpoint == "tcm.diagnosis/watchCall": + return { + "sdkAppId": 1400123456, + "userId": "doctor_20", + "userSig": "short-lived", + "roomId": 9001, + } if endpoint == "tcm.prescriptionOrder/paidPayOrders": return {"lists": [{"id": 9}], "deposit_min_amount": 50} return {"lists": [], "count": 0, "extend": {"scope": {"label": "server"}}} @@ -200,7 +207,26 @@ def test_remote_new_contracts_use_exact_admin_endpoints_and_dtos() -> None: repository.assign_patient(5, 20, is_inherit=1) repository.fill_patient_id_card(5, "410000199001010000") repository.book_patient_appointment({"diagnosis_id": 5, "appointment_date": "2026-08-10"}) + repository.create_diagnosis_appointment( + { + "diagnosis_id": 5, + "patient_id": 5, + "doctor_id": 9, + "appointment_date": "2026-08-11", + } + ) repository.cancel_patient_appointment(7) + watch_ticket = repository.get_assistant_watch_ticket(5) + repository.create_diagnosis( + { + "patient_name": " 林晓岚 ", + "phone": "13800138000", + "gender": 0, + "age": 36, + "diagnosis_type": "复诊", + "local_hospital_name": "杭州市第一人民医院", + } + ) repository.update_diagnosis(5, {"clinical_diagnosis": "气虚证"}) repository.list_appointment_rosters( doctor_id=1, @@ -238,7 +264,28 @@ def test_remote_new_contracts_use_exact_admin_endpoints_and_dtos() -> None: }, ) in client.post_calls assert ("tcm.diagnosis/edit", {"id": 5, "clinical_diagnosis": "气虚证"}) in client.post_calls + assert ( + "doctor.appointment/create", + { + "diagnosis_id": 5, + "patient_id": 5, + "doctor_id": 9, + "appointment_date": "2026-08-11", + }, + ) in client.post_calls + assert ( + "tcm.diagnosis/add", + { + "patient_name": "林晓岚", + "phone": "13800138000", + "gender": 0, + "age": 36, + "diagnosis_type": "复诊", + "local_hospital_name": "杭州市第一人民医院", + }, + ) in client.post_calls assert slots == {"slots": [{"time": "09:00", "available": True}]} + assert watch_ticket["roomId"] == 9001 get_endpoints = {endpoint for endpoint, _ in client.get_calls} assert { "tcm.prescriptionOrder/paidPayOrders", @@ -250,6 +297,7 @@ def test_remote_new_contracts_use_exact_admin_endpoints_and_dtos() -> None: "tcm.diagnosis/assignLogList", "doctor.roster/lists", "doctor.appointment/availableSlots", + "tcm.diagnosis/watchCall", } <= get_endpoints @@ -270,6 +318,34 @@ def test_remote_note_rejects_local_material_references(unsafe_reference: str) -> ) +@pytest.mark.parametrize( + ("changes", "message"), + [ + ({"gender": 2}, "gender"), + ({"local_hospital_name": ""}, "local_hospital_name"), + ], +) +def test_remote_diagnosis_create_rejects_invalid_production_dto_before_transport( + changes: dict[str, Any], message: str +) -> None: + client = RecordingClient() + repository = RemoteDoctorRepository(client) # type: ignore[arg-type] + payload = { + "patient_name": "林晓岚", + "phone": "13800138000", + "gender": 0, + "age": 36, + "diagnosis_type": "复诊", + "local_hospital_name": "杭州市第一人民医院", + **changes, + } + + with pytest.raises(ValueError, match=message): + repository.create_diagnosis(payload) + + assert not client.post_calls + + def test_remote_dynamic_menu_preserves_json_metadata_but_drops_runtime_objects() -> None: """Future menu fields pass through safely without evaluating arbitrary values.""" diff --git a/app/tests/test_video_contract.py b/app/tests/test_video_contract.py index 52336b95f..40c1fa033 100644 --- a/app/tests/test_video_contract.py +++ b/app/tests/test_video_contract.py @@ -19,7 +19,9 @@ from doctor_workstation.video.launcher import ( # noqa: E402 VideoCallLauncher, VideoCallRequest, VideoTicketError, + VideoWatchRequest, normalize_backend_ticket, + normalize_backend_watch_ticket, ) from doctor_workstation.video.lifecycle import OrderedCallLifecycle # noqa: E402 from doctor_workstation.video.security import ( # noqa: E402 @@ -57,6 +59,58 @@ def test_normalizes_admin_ticket_aliases_to_companion_contract() -> None: } +def test_normalizes_receive_only_assistant_watch_ticket() -> None: + request = normalize_backend_watch_ticket( + { + "sdkAppId": 1400123456, + "userId": "doctor_20", + "userSig": "short-lived-watch-ticket", + "strRoomId": " diagnosis-room-501 ", + "patientName": "林晓岚", + }, + diagnosis_id=501, + ) + + assert request == VideoWatchRequest( + sdk_app_id=1400123456, + user_id="doctor_20", + user_sig="short-lived-watch-ticket", + diagnosis_id=501, + str_room_id="diagnosis-room-501", + patient_name="林晓岚", + ) + assert request.to_web_config() == { + "SDKAppID": 1400123456, + "userID": "doctor_20", + "userSig": "short-lived-watch-ticket", + "diagnosisId": 501, + "patientName": "林晓岚", + "strRoomId": "diagnosis-room-501", + } + assert "short-lived-watch-ticket" not in repr(request) + assert "short-lived-watch-ticket" not in str(request.safe_log_context()) + + +@pytest.mark.parametrize( + "room_fields", + [ + {}, + {"roomId": 9001, "strRoomId": "room-9001"}, + ], +) +def test_rejects_missing_or_conflicting_watch_room(room_fields: dict[str, object]) -> None: + with pytest.raises(VideoTicketError, match="room"): + normalize_backend_watch_ticket( + { + "sdkAppId": 1400123456, + "userId": "doctor_20", + "userSig": "short-lived-watch-ticket", + **room_fields, + }, + diagnosis_id=501, + ) + + def test_accepts_uppercase_aliases_and_nested_backend_envelope() -> None: request = VideoCallRequest.from_backend_ticket( { diff --git a/app/video_companion/dist/assets/index-BuO_uDya.css b/app/video_companion/dist/assets/index-BuO_uDya.css deleted file mode 100644 index 9f3778393..000000000 --- a/app/video_companion/dist/assets/index-BuO_uDya.css +++ /dev/null @@ -1 +0,0 @@ -:root{font-family:Inter,PingFang SC,Microsoft YaHei,system-ui,sans-serif;color:#f7f8fa;background:#0b0f14;font-synthesis:none;text-rendering:optimizeLegibility}*{box-sizing:border-box}html,body,#app{width:100%;height:100%;margin:0;overflow:hidden}button,input{font:inherit}.call-stage{position:relative;width:100%;height:100%;min-height:420px;overflow:hidden;background:radial-gradient(circle at 50% 35%,rgba(39,74,83,.22),transparent 38%),#0b0f14}.call-kit,.call-stage :is(.TUICallKit-desktop,.TUICallKit-mobile,#tuicallkit-id){width:100%!important;height:100%!important;max-width:none!important;max-height:none!important}.status-card{position:absolute;inset:50% auto auto 50%;display:grid;grid-template-columns:12px minmax(0,1fr);gap:18px;width:min(520px,calc(100% - 48px));padding:30px 32px;transform:translate(-50%,-50%);border:1px solid rgba(255,255,255,.09);border-radius:20px;background:#131920e6;box-shadow:0 24px 70px #00000052;backdrop-filter:blur(18px)}.eyebrow{margin:0 0 12px;color:#8f9ba8;font-size:12px;font-weight:700;letter-spacing:.16em;text-transform:uppercase}.status-card h1{margin:0;font-size:clamp(22px,3.2vw,34px);font-weight:600;line-height:1.25}.status-hint{margin:14px 0 0;color:#9aa5b1;font-size:14px}.status-dot{width:10px;height:10px;margin-top:5px;border-radius:50%;background:#77818c;box-shadow:0 0 0 5px #77818c1f}.status-dot--starting,.status-dot--live{background:#52c99a;box-shadow:0 0 0 5px #52c99a24}.status-dot--error{background:#f26d6d;box-shadow:0 0 0 5px #f26d6d24}.live-status{position:absolute;z-index:20;top:18px;left:50%;display:flex;align-items:center;gap:10px;padding:9px 14px;transform:translate(-50%);border:1px solid rgba(255,255,255,.1);border-radius:999px;background:#0b0f14c2;color:#e8edf2;font-size:13px;backdrop-filter:blur(14px)}.live-status .status-dot{width:7px;height:7px;margin:0;box-shadow:none} diff --git a/app/video_companion/dist/assets/index-CG-V4g-D.css b/app/video_companion/dist/assets/index-CG-V4g-D.css new file mode 100644 index 000000000..b829a4c29 --- /dev/null +++ b/app/video_companion/dist/assets/index-CG-V4g-D.css @@ -0,0 +1 @@ +:root{font-family:Inter,PingFang SC,Microsoft YaHei,system-ui,sans-serif;color:#f7f8fa;background:#0b0f14;font-synthesis:none;text-rendering:optimizeLegibility}*{box-sizing:border-box}html,body,#app{width:100%;height:100%;margin:0;overflow:hidden}button,input{font:inherit}.call-stage{position:relative;width:100%;height:100%;min-height:420px;overflow:hidden;background:radial-gradient(circle at 50% 35%,rgba(39,74,83,.22),transparent 38%),#0b0f14}.call-kit,.call-stage :is(.TUICallKit-desktop,.TUICallKit-mobile,#tuicallkit-id){width:100%!important;height:100%!important;max-width:none!important;max-height:none!important}.watch-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:16px;width:100%;height:100%;padding:64px 18px 18px}.watch-tile{position:relative;min-height:260px;overflow:hidden;border:1px solid rgba(255,255,255,.1);border-radius:14px;background:#10171f}.watch-tile__caption{position:absolute;z-index:2;top:12px;left:12px;padding:6px 10px;border-radius:6px;background:#080c11b8;color:#eef3f7;font-size:12px}.watch-tile__view{width:100%;height:100%}.status-card{position:absolute;inset:50% auto auto 50%;display:grid;grid-template-columns:12px minmax(0,1fr);gap:18px;width:min(520px,calc(100% - 48px));padding:30px 32px;transform:translate(-50%,-50%);border:1px solid rgba(255,255,255,.09);border-radius:20px;background:#131920e6;box-shadow:0 24px 70px #00000052;backdrop-filter:blur(18px)}.eyebrow{margin:0 0 12px;color:#8f9ba8;font-size:12px;font-weight:700;letter-spacing:.16em;text-transform:uppercase}.status-card h1{margin:0;font-size:clamp(22px,3.2vw,34px);font-weight:600;line-height:1.25}.status-hint{margin:14px 0 0;color:#9aa5b1;font-size:14px}.status-dot{width:10px;height:10px;margin-top:5px;border-radius:50%;background:#77818c;box-shadow:0 0 0 5px #77818c1f}.status-dot--starting,.status-dot--live{background:#52c99a;box-shadow:0 0 0 5px #52c99a24}.status-dot--error{background:#f26d6d;box-shadow:0 0 0 5px #f26d6d24}.live-status{position:absolute;z-index:20;top:18px;left:50%;display:flex;align-items:center;gap:10px;padding:9px 14px;transform:translate(-50%);border:1px solid rgba(255,255,255,.1);border-radius:999px;background:#0b0f14c2;color:#e8edf2;font-size:13px;backdrop-filter:blur(14px)}.live-status .status-dot{width:7px;height:7px;margin:0;box-shadow:none} diff --git a/app/video_companion/dist/assets/index-le5ZH3pL.js b/app/video_companion/dist/assets/index-DluArHub.js similarity index 73% rename from app/video_companion/dist/assets/index-le5ZH3pL.js rename to app/video_companion/dist/assets/index-DluArHub.js index 2b06e79e9..6b1a0406d 100644 --- a/app/video_companion/dist/assets/index-le5ZH3pL.js +++ b/app/video_companion/dist/assets/index-DluArHub.js @@ -2,19 +2,19 @@ * @vue/shared v3.5.13 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT -**//*! #__NO_SIDE_EFFECTS__ */function $j(t){const i=Object.create(null);for(const r of t.split(","))i[r]=1;return r=>r in i}const qn={},Cw=[],Lu=()=>{},HtA=()=>!1,nY=t=>t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&(t.charCodeAt(2)>122||t.charCodeAt(2)<97),A3=t=>t.startsWith("onUpdate:"),Sg=Object.assign,e3=(t,i)=>{const r=t.indexOf(i);r>-1&&t.splice(r,1)},VtA=Object.prototype.hasOwnProperty,yn=(t,i)=>VtA.call(t,i),Ro=Array.isArray,Bw=t=>aY(t)==="[object Map]",_8=t=>aY(t)==="[object Set]",xo=t=>typeof t=="function",va=t=>typeof t=="string",sd=t=>typeof t=="symbol",ta=t=>t!==null&&typeof t=="object",b8=t=>(ta(t)||xo(t))&&xo(t.then)&&xo(t.catch),L8=Object.prototype.toString,aY=t=>L8.call(t),qtA=t=>aY(t).slice(8,-1),F8=t=>aY(t)==="[object Object]",t3=t=>va(t)&&t!=="NaN"&&t[0]!=="-"&&""+parseInt(t,10)===t,FG=$j(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),sY=t=>{const i=Object.create(null);return r=>i[r]||(i[r]=t(r))},KtA=/-(\w)/g,mC=sY(t=>t.replace(KtA,(i,r)=>r?r.toUpperCase():"")),jtA=/\B([A-Z])/g,Rp=sY(t=>t.replace(jtA,"-$1").toLowerCase()),gY=sY(t=>t.charAt(0).toUpperCase()+t.slice(1)),CK=sY(t=>t?`on${gY(t)}`:""),Cp=(t,i)=>!Object.is(t,i),BK=(t,...i)=>{for(let r=0;r{Object.defineProperty(t,i,{configurable:!0,enumerable:!1,writable:s,value:r})},WtA=t=>{const i=parseFloat(t);return isNaN(i)?t:i},ztA=t=>{const i=va(t)?Number(t):NaN;return isNaN(i)?t:i};let wz;const IY=()=>wz||(wz=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function zr(t){if(Ro(t)){const i={};for(let r=0;r{if(r){const s=r.split(XtA);s.length>1&&(i[s[0].trim()]=s[1].trim())}}),i}function Qi(t){let i="";if(va(t))i=t;else if(Ro(t))for(let r=0;r!!(t&&t.__v_isRef===!0),Wt=t=>va(t)?t:t==null?"":Ro(t)||ta(t)&&(t.toString===L8||!xo(t.toString))?x8(t)?Wt(t.value):JSON.stringify(t,Y8,2):String(t),Y8=(t,i)=>x8(i)?Y8(t,i.value):Bw(i)?{[`Map(${i.size})`]:[...i.entries()].reduce((r,[s,g],B)=>(r[uK(s,B)+" =>"]=g,r),{})}:_8(i)?{[`Set(${i.size})`]:[...i.values()].map(r=>uK(r))}:sd(i)?uK(i):ta(i)&&!Ro(i)&&!F8(i)?String(i):i,uK=(t,i="")=>{var r;return sd(t)?`Symbol(${(r=t.description)!=null?r:i})`:t};/** +**//*! #__NO_SIDE_EFFECTS__ */function r3(t){const i=Object.create(null);for(const r of t.split(","))i[r]=1;return r=>r in i}const qn={},Qw=[],Ou=()=>{},iiA=()=>!1,lY=t=>t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&(t.charCodeAt(2)>122||t.charCodeAt(2)<97),n3=t=>t.startsWith("onUpdate:"),Sg=Object.assign,a3=(t,i)=>{const r=t.indexOf(i);r>-1&&t.splice(r,1)},oiA=Object.prototype.hasOwnProperty,yn=(t,i)=>oiA.call(t,i),Ro=Array.isArray,dw=t=>CY(t)==="[object Map]",Y8=t=>CY(t)==="[object Set]",xo=t=>typeof t=="function",va=t=>typeof t=="string",cd=t=>typeof t=="symbol",ta=t=>t!==null&&typeof t=="object",P8=t=>(ta(t)||xo(t))&&xo(t.then)&&xo(t.catch),J8=Object.prototype.toString,CY=t=>J8.call(t),riA=t=>CY(t).slice(8,-1),H8=t=>CY(t)==="[object Object]",s3=t=>va(t)&&t!=="NaN"&&t[0]!=="-"&&""+parseInt(t,10)===t,YG=r3(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),BY=t=>{const i=Object.create(null);return r=>i[r]||(i[r]=t(r))},niA=/-(\w)/g,mC=BY(t=>t.replace(niA,(i,r)=>r?r.toUpperCase():"")),aiA=/\B([A-Z])/g,vp=BY(t=>t.replace(aiA,"-$1").toLowerCase()),uY=BY(t=>t.charAt(0).toUpperCase()+t.slice(1)),pK=BY(t=>t?`on${uY(t)}`:""),Qp=(t,i)=>!Object.is(t,i),fK=(t,...i)=>{for(let r=0;r{Object.defineProperty(t,i,{configurable:!0,enumerable:!1,writable:s,value:r})},siA=t=>{const i=parseFloat(t);return isNaN(i)?t:i},giA=t=>{const i=va(t)?Number(t):NaN;return isNaN(i)?t:i};let _z;const QY=()=>_z||(_z=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function zr(t){if(Ro(t)){const i={};for(let r=0;r{if(r){const s=r.split(ciA);s.length>1&&(i[s[0].trim()]=s[1].trim())}}),i}function Qi(t){let i="";if(va(t))i=t;else if(Ro(t))for(let r=0;r!!(t&&t.__v_isRef===!0),Wt=t=>va(t)?t:t==null?"":Ro(t)||ta(t)&&(t.toString===J8||!xo(t.toString))?K8(t)?Wt(t.value):JSON.stringify(t,j8,2):String(t),j8=(t,i)=>K8(i)?j8(t,i.value):dw(i)?{[`Map(${i.size})`]:[...i.entries()].reduce((r,[s,g],B)=>(r[mK(s,B)+" =>"]=g,r),{})}:Y8(i)?{[`Set(${i.size})`]:[...i.values()].map(r=>mK(r))}:cd(i)?mK(i):ta(i)&&!Ro(i)&&!H8(i)?String(i):i,mK=(t,i="")=>{var r;return cd(t)?`Symbol(${(r=t.description)!=null?r:i})`:t};/** * @vue/reactivity v3.5.13 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT -**/let ll;class oiA{constructor(i=!1){this.detached=i,this._active=!0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=ll,!i&&ll&&(this.index=(ll.scopes||(ll.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let i,r;if(this.scopes)for(i=0,r=this.scopes.length;i0)return;if(OG){let i=OG;for(OG=void 0;i;){const r=i.next;i.next=void 0,i.flags&=-9,i=r}}let t;for(;UG;){let i=UG;for(UG=void 0;i;){const r=i.next;if(i.next=void 0,i.flags&=-9,i.flags&1)try{i.trigger()}catch(s){t||(t=s)}i=r}}if(t)throw t}function V8(t){for(let i=t.deps;i;i=i.nextDep)i.version=-1,i.prevActiveLink=i.dep.activeLink,i.dep.activeLink=i}function q8(t){let i,r=t.depsTail,s=r;for(;s;){const g=s.prevDep;s.version===-1?(s===r&&(r=g),r3(s),niA(s)):i=s,s.dep.activeLink=s.prevActiveLink,s.prevActiveLink=void 0,s=g}t.deps=i,t.depsTail=r}function sj(t){for(let i=t.deps;i;i=i.nextDep)if(i.dep.version!==i.version||i.dep.computed&&(K8(i.dep.computed)||i.dep.version!==i.version))return!0;return!!t._dirty}function K8(t){if(t.flags&4&&!(t.flags&16)||(t.flags&=-17,t.globalVersion===ek))return;t.globalVersion=ek;const i=t.dep;if(t.flags|=2,i.version>0&&!t.isSSR&&t.deps&&!sj(t)){t.flags&=-3;return}const r=ea,s=EB;ea=t,EB=!0;try{V8(t);const g=t.fn(t._value);(i.version===0||Cp(g,t._value))&&(t._value=g,i.version++)}catch(g){throw i.version++,g}finally{ea=r,EB=s,q8(t),t.flags&=-3}}function r3(t,i=!1){const{dep:r,prevSub:s,nextSub:g}=t;if(s&&(s.nextSub=g,t.prevSub=void 0),g&&(g.prevSub=s,t.nextSub=void 0),r.subs===t&&(r.subs=s,!s&&r.computed)){r.computed.flags&=-5;for(let B=r.computed.deps;B;B=B.nextDep)r3(B,!0)}!i&&!--r.sc&&r.map&&r.map.delete(r.key)}function niA(t){const{prevDep:i,nextDep:r}=t;i&&(i.nextDep=r,t.prevDep=void 0),r&&(r.prevDep=i,t.nextDep=void 0)}let EB=!0;const j8=[];function Mp(){j8.push(EB),EB=!1}function wp(){const t=j8.pop();EB=t===void 0?!0:t}function Sz(t){const{cleanup:i}=t;if(t.cleanup=void 0,i){const r=ea;ea=void 0;try{i()}finally{ea=r}}}let ek=0;class aiA{constructor(i,r){this.sub=i,this.dep=r,this.version=r.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class n3{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(!ea||!EB||ea===this.computed)return;let r=this.activeLink;if(r===void 0||r.sub!==ea)r=this.activeLink=new aiA(ea,this),ea.deps?(r.prevDep=ea.depsTail,ea.depsTail.nextDep=r,ea.depsTail=r):ea.deps=ea.depsTail=r,W8(r);else if(r.version===-1&&(r.version=this.version,r.nextDep)){const s=r.nextDep;s.prevDep=r.prevDep,r.prevDep&&(r.prevDep.nextDep=s),r.prevDep=ea.depsTail,r.nextDep=void 0,ea.depsTail.nextDep=r,ea.depsTail=r,ea.deps===r&&(ea.deps=s)}return r}trigger(i){this.version++,ek++,this.notify(i)}notify(i){i3();try{for(let r=this.subs;r;r=r.prevSub)r.sub.notify()&&r.sub.dep.notify()}finally{o3()}}}function W8(t){if(t.dep.sc++,t.sub.flags&4){const i=t.dep.computed;if(i&&!t.dep.subs){i.flags|=20;for(let s=i.deps;s;s=s.nextDep)W8(s)}const r=t.dep.subs;r!==t&&(t.prevSub=r,r&&(r.nextSub=t)),t.dep.subs=t}}const N2=new WeakMap,tD=Symbol(""),gj=Symbol(""),tk=Symbol("");function GI(t,i,r){if(EB&&ea){let s=N2.get(t);s||N2.set(t,s=new Map);let g=s.get(r);g||(s.set(r,g=new n3),g.map=s,g.key=r),g.track()}}function od(t,i,r,s,g,B){const Q=N2.get(t);if(!Q){ek++;return}const f=m=>{m&&m.trigger()};if(i3(),i==="clear")Q.forEach(f);else{const m=Ro(t),M=m&&t3(r);if(m&&r==="length"){const v=Number(s);Q.forEach((U,AA)=>{(AA==="length"||AA===tk||!sd(AA)&&AA>=v)&&f(U)})}else switch((r!==void 0||Q.has(void 0))&&f(Q.get(r)),M&&f(Q.get(tk)),i){case"add":m?M&&f(Q.get("length")):(f(Q.get(tD)),Bw(t)&&f(Q.get(gj)));break;case"delete":m||(f(Q.get(tD)),Bw(t)&&f(Q.get(gj)));break;case"set":Bw(t)&&f(Q.get(tD));break}}o3()}function siA(t,i){const r=N2.get(t);return r&&r.get(i)}function KM(t){const i=an(t);return i===t?i:(GI(i,"iterate",tk),hC(t)?i:i.map(kI))}function cY(t){return GI(t=an(t),"iterate",tk),t}const giA={__proto__:null,[Symbol.iterator](){return dK(this,Symbol.iterator,kI)},concat(...t){return KM(this).concat(...t.map(i=>Ro(i)?KM(i):i))},entries(){return dK(this,"entries",t=>(t[1]=kI(t[1]),t))},every(t,i){return zQ(this,"every",t,i,void 0,arguments)},filter(t,i){return zQ(this,"filter",t,i,r=>r.map(kI),arguments)},find(t,i){return zQ(this,"find",t,i,kI,arguments)},findIndex(t,i){return zQ(this,"findIndex",t,i,void 0,arguments)},findLast(t,i){return zQ(this,"findLast",t,i,kI,arguments)},findLastIndex(t,i){return zQ(this,"findLastIndex",t,i,void 0,arguments)},forEach(t,i){return zQ(this,"forEach",t,i,void 0,arguments)},includes(...t){return hK(this,"includes",t)},indexOf(...t){return hK(this,"indexOf",t)},join(t){return KM(this).join(t)},lastIndexOf(...t){return hK(this,"lastIndexOf",t)},map(t,i){return zQ(this,"map",t,i,void 0,arguments)},pop(){return cG(this,"pop")},push(...t){return cG(this,"push",t)},reduce(t,...i){return vz(this,"reduce",t,i)},reduceRight(t,...i){return vz(this,"reduceRight",t,i)},shift(){return cG(this,"shift")},some(t,i){return zQ(this,"some",t,i,void 0,arguments)},splice(...t){return cG(this,"splice",t)},toReversed(){return KM(this).toReversed()},toSorted(t){return KM(this).toSorted(t)},toSpliced(...t){return KM(this).toSpliced(...t)},unshift(...t){return cG(this,"unshift",t)},values(){return dK(this,"values",kI)}};function dK(t,i,r){const s=cY(t),g=s[i]();return s!==t&&!hC(t)&&(g._next=g.next,g.next=()=>{const B=g._next();return B.value&&(B.value=r(B.value)),B}),g}const IiA=Array.prototype;function zQ(t,i,r,s,g,B){const Q=cY(t),f=Q!==t&&!hC(t),m=Q[i];if(m!==IiA[i]){const U=m.apply(t,B);return f?kI(U):U}let M=r;Q!==t&&(f?M=function(U,AA){return r.call(this,kI(U),AA,t)}:r.length>2&&(M=function(U,AA){return r.call(this,U,AA,t)}));const v=m.call(Q,M,s);return f&&g?g(v):v}function vz(t,i,r,s){const g=cY(t);let B=r;return g!==t&&(hC(t)?r.length>3&&(B=function(Q,f,m){return r.call(this,Q,f,m,t)}):B=function(Q,f,m){return r.call(this,Q,kI(f),m,t)}),g[i](B,...s)}function hK(t,i,r){const s=an(t);GI(s,"iterate",tk);const g=s[i](...r);return(g===-1||g===!1)&&g3(r[0])?(r[0]=an(r[0]),s[i](...r)):g}function cG(t,i,r=[]){Mp(),i3();const s=an(t)[i].apply(t,r);return o3(),wp(),s}const ciA=$j("__proto__,__v_isRef,__isVue"),z8=new Set(Object.getOwnPropertyNames(Symbol).filter(t=>t!=="arguments"&&t!=="caller").map(t=>Symbol[t]).filter(sd));function EiA(t){sd(t)||(t=String(t));const i=an(this);return GI(i,"has",t),i.hasOwnProperty(t)}class Z8{constructor(i=!1,r=!1){this._isReadonly=i,this._isShallow=r}get(i,r,s){if(r==="__v_skip")return i.__v_skip;const g=this._isReadonly,B=this._isShallow;if(r==="__v_isReactive")return!g;if(r==="__v_isReadonly")return g;if(r==="__v_isShallow")return B;if(r==="__v_raw")return s===(g?B?miA:eZ:B?AZ:$8).get(i)||Object.getPrototypeOf(i)===Object.getPrototypeOf(s)?i:void 0;const Q=Ro(i);if(!g){let m;if(Q&&(m=giA[r]))return m;if(r==="hasOwnProperty")return EiA}const f=Reflect.get(i,r,wg(i)?i:s);return(sd(r)?z8.has(r):ciA(r))||(g||GI(i,"get",r),B)?f:wg(f)?Q&&t3(r)?f:f.value:ta(f)?g?T2(f):Xm(f):f}}class X8 extends Z8{constructor(i=!1){super(!1,i)}set(i,r,s,g){let B=i[r];if(!this._isShallow){const m=CD(B);if(!hC(s)&&!CD(s)&&(B=an(B),s=an(s)),!Ro(i)&&wg(B)&&!wg(s))return m?!1:(B.value=s,!0)}const Q=Ro(i)&&t3(r)?Number(r)t,Wx=t=>Reflect.getPrototypeOf(t);function QiA(t,i,r){return function(...s){const g=this.__v_raw,B=an(g),Q=Bw(B),f=t==="entries"||t===Symbol.iterator&&Q,m=t==="keys"&&Q,M=g[t](...s),v=r?Ij:i?cj:kI;return!i&&GI(B,"iterate",m?gj:tD),{next(){const{value:U,done:AA}=M.next();return AA?{value:U,done:AA}:{value:f?[v(U[0]),v(U[1])]:v(U),done:AA}},[Symbol.iterator](){return this}}}}function zx(t){return function(...i){return t==="delete"?!1:t==="clear"?void 0:this}}function diA(t,i){const r={get(g){const B=this.__v_raw,Q=an(B),f=an(g);t||(Cp(g,f)&&GI(Q,"get",g),GI(Q,"get",f));const{has:m}=Wx(Q),M=i?Ij:t?cj:kI;if(m.call(Q,g))return M(B.get(g));if(m.call(Q,f))return M(B.get(f));B!==Q&&B.get(g)},get size(){const g=this.__v_raw;return!t&&GI(an(g),"iterate",tD),Reflect.get(g,"size",g)},has(g){const B=this.__v_raw,Q=an(B),f=an(g);return t||(Cp(g,f)&&GI(Q,"has",g),GI(Q,"has",f)),g===f?B.has(g):B.has(g)||B.has(f)},forEach(g,B){const Q=this,f=Q.__v_raw,m=an(f),M=i?Ij:t?cj:kI;return!t&&GI(m,"iterate",tD),f.forEach((v,U)=>g.call(B,M(v),M(U),Q))}};return Sg(r,t?{add:zx("add"),set:zx("set"),delete:zx("delete"),clear:zx("clear")}:{add(g){!i&&!hC(g)&&!CD(g)&&(g=an(g));const B=an(this);return Wx(B).has.call(B,g)||(B.add(g),od(B,"add",g,g)),this},set(g,B){!i&&!hC(B)&&!CD(B)&&(B=an(B));const Q=an(this),{has:f,get:m}=Wx(Q);let M=f.call(Q,g);M||(g=an(g),M=f.call(Q,g));const v=m.call(Q,g);return Q.set(g,B),M?Cp(B,v)&&od(Q,"set",g,B):od(Q,"add",g,B),this},delete(g){const B=an(this),{has:Q,get:f}=Wx(B);let m=Q.call(B,g);m||(g=an(g),m=Q.call(B,g)),f&&f.call(B,g);const M=B.delete(g);return m&&od(B,"delete",g,void 0),M},clear(){const g=an(this),B=g.size!==0,Q=g.clear();return B&&od(g,"clear",void 0,void 0),Q}}),["keys","values","entries",Symbol.iterator].forEach(g=>{r[g]=QiA(g,t,i)}),r}function a3(t,i){const r=diA(t,i);return(s,g,B)=>g==="__v_isReactive"?!t:g==="__v_isReadonly"?t:g==="__v_raw"?s:Reflect.get(yn(r,g)&&g in s?r:s,g,B)}const hiA={get:a3(!1,!1)},piA={get:a3(!1,!0)},fiA={get:a3(!0,!1)};const $8=new WeakMap,AZ=new WeakMap,eZ=new WeakMap,miA=new WeakMap;function DiA(t){switch(t){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function yiA(t){return t.__v_skip||!Object.isExtensible(t)?0:DiA(qtA(t))}function Xm(t){return CD(t)?t:s3(t,!1,CiA,hiA,$8)}function RiA(t){return s3(t,!1,uiA,piA,AZ)}function T2(t){return s3(t,!0,BiA,fiA,eZ)}function s3(t,i,r,s,g){if(!ta(t)||t.__v_raw&&!(i&&t.__v_isReactive))return t;const B=g.get(t);if(B)return B;const Q=yiA(t);if(Q===0)return t;const f=new Proxy(t,Q===2?s:r);return g.set(t,f),f}function uw(t){return CD(t)?uw(t.__v_raw):!!(t&&t.__v_isReactive)}function CD(t){return!!(t&&t.__v_isReadonly)}function hC(t){return!!(t&&t.__v_isShallow)}function g3(t){return t?!!t.__v_raw:!1}function an(t){const i=t&&t.__v_raw;return i?an(i):t}function MiA(t){return!yn(t,"__v_skip")&&Object.isExtensible(t)&&U8(t,"__v_skip",!0),t}const kI=t=>ta(t)?Xm(t):t,cj=t=>ta(t)?T2(t):t;function wg(t){return t?t.__v_isRef===!0:!1}function Ne(t){return wiA(t,!1)}function wiA(t,i){return wg(t)?t:new SiA(t,i)}class SiA{constructor(i,r){this.dep=new n3,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=r?i:an(i),this._value=r?i:kI(i),this.__v_isShallow=r}get value(){return this.dep.track(),this._value}set value(i){const r=this._rawValue,s=this.__v_isShallow||hC(i)||CD(i);i=s?i:an(i),Cp(i,r)&&(this._rawValue=i,this._value=s?i:kI(i),this.dep.trigger())}}function W(t){return wg(t)?t.value:t}const viA={get:(t,i,r)=>i==="__v_raw"?t:W(Reflect.get(t,i,r)),set:(t,i,r,s)=>{const g=t[i];return wg(g)&&!wg(r)?(g.value=r,!0):Reflect.set(t,i,r,s)}};function tZ(t){return uw(t)?t:new Proxy(t,viA)}function Mo(t){const i=Ro(t)?new Array(t.length):{};for(const r in t)i[r]=iZ(t,r);return i}class NiA{constructor(i,r,s){this._object=i,this._key=r,this._defaultValue=s,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 siA(an(this._object),this._key)}}class TiA{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 pK(t,i,r){return wg(t)?t:xo(t)?new TiA(t):ta(t)&&arguments.length>1?iZ(t,i,r):Ne(t)}function iZ(t,i,r){const s=t[i];return wg(s)?s:new NiA(t,i,r)}class GiA{constructor(i,r,s){this.fn=i,this.setter=r,this._value=void 0,this.dep=new n3(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=ek-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!r,this.isSSR=s}notify(){if(this.flags|=16,!(this.flags&8)&&ea!==this)return H8(this,!0),!0}get value(){const i=this.dep.track();return K8(this),i&&(i.version=this.dep.version),this._value}set value(i){this.setter&&this.setter(i)}}function kiA(t,i,r=!1){let s,g;return xo(t)?s=t:(s=t.get,g=t.set),new GiA(s,g,r)}const Zx={},G2=new WeakMap;let qm;function _iA(t,i=!1,r=qm){if(r){let s=G2.get(r);s||G2.set(r,s=[]),s.push(t)}}function biA(t,i,r=qn){const{immediate:s,deep:g,once:B,scheduler:Q,augmentJob:f,call:m}=r,M=VA=>g?VA:hC(VA)||g===!1||g===0?rd(VA,1):rd(VA);let v,U,AA,z,sA=!1,eA=!1;if(wg(t)?(U=()=>t.value,sA=hC(t)):uw(t)?(U=()=>M(t),sA=!0):Ro(t)?(eA=!0,sA=t.some(VA=>uw(VA)||hC(VA)),U=()=>t.map(VA=>{if(wg(VA))return VA.value;if(uw(VA))return M(VA);if(xo(VA))return m?m(VA,2):VA()})):xo(t)?i?U=m?()=>m(t,2):t:U=()=>{if(AA){Mp();try{AA()}finally{wp()}}const VA=qm;qm=v;try{return m?m(t,3,[z]):t(z)}finally{qm=VA}}:U=Lu,i&&g){const VA=U,ue=g===!0?1/0:g;U=()=>rd(VA(),ue)}const X=riA(),QA=()=>{v.stop(),X&&X.active&&e3(X.effects,v)};if(B&&i){const VA=i;i=(...ue)=>{VA(...ue),QA()}}let wA=eA?new Array(t.length).fill(Zx):Zx;const HA=VA=>{if(!(!(v.flags&1)||!v.dirty&&!VA))if(i){const ue=v.run();if(g||sA||(eA?ue.some((jA,Ve)=>Cp(jA,wA[Ve])):Cp(ue,wA))){AA&&AA();const jA=qm;qm=v;try{const Ve=[ue,wA===Zx?void 0:eA&&wA[0]===Zx?[]:wA,z];m?m(i,3,Ve):i(...Ve),wA=ue}finally{qm=jA}}}else v.run()};return f&&f(HA),v=new P8(U),v.scheduler=Q?()=>Q(HA,!1):HA,z=VA=>_iA(VA,!1,v),AA=v.onStop=()=>{const VA=G2.get(v);if(VA){if(m)m(VA,4);else for(const ue of VA)ue();G2.delete(v)}},i?s?HA(!0):wA=v.run():Q?Q(HA.bind(null,!0),!0):v.run(),QA.pause=v.pause.bind(v),QA.resume=v.resume.bind(v),QA.stop=QA,QA}function rd(t,i=1/0,r){if(i<=0||!ta(t)||t.__v_skip||(r=r||new Set,r.has(t)))return t;if(r.add(t),i--,wg(t))rd(t.value,i,r);else if(Ro(t))for(let s=0;s{rd(s,i,r)});else if(F8(t)){for(const s in t)rd(t[s],i,r);for(const s of Object.getOwnPropertySymbols(t))Object.prototype.propertyIsEnumerable.call(t,s)&&rd(t[s],i,r)}return t}/** +**/let Cl;class QiA{constructor(i=!1){this.detached=i,this._active=!0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=Cl,!i&&Cl&&(this.index=(Cl.scopes||(Cl.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let i,r;if(this.scopes)for(i=0,r=this.scopes.length;i0)return;if(JG){let i=JG;for(JG=void 0;i;){const r=i.next;i.next=void 0,i.flags&=-9,i=r}}let t;for(;PG;){let i=PG;for(PG=void 0;i;){const r=i.next;if(i.next=void 0,i.flags&=-9,i.flags&1)try{i.trigger()}catch(s){t||(t=s)}i=r}}if(t)throw t}function X8(t){for(let i=t.deps;i;i=i.nextDep)i.version=-1,i.prevActiveLink=i.dep.activeLink,i.dep.activeLink=i}function $8(t){let i,r=t.depsTail,s=r;for(;s;){const g=s.prevDep;s.version===-1?(s===r&&(r=g),c3(s),hiA(s)):i=s,s.dep.activeLink=s.prevActiveLink,s.prevActiveLink=void 0,s=g}t.deps=i,t.depsTail=r}function Cj(t){for(let i=t.deps;i;i=i.nextDep)if(i.dep.version!==i.version||i.dep.computed&&(AZ(i.dep.computed)||i.dep.version!==i.version))return!0;return!!t._dirty}function AZ(t){if(t.flags&4&&!(t.flags&16)||(t.flags&=-17,t.globalVersion===ak))return;t.globalVersion=ak;const i=t.dep;if(t.flags|=2,i.version>0&&!t.isSSR&&t.deps&&!Cj(t)){t.flags&=-3;return}const r=ea,s=EB;ea=t,EB=!0;try{X8(t);const g=t.fn(t._value);(i.version===0||Qp(g,t._value))&&(t._value=g,i.version++)}catch(g){throw i.version++,g}finally{ea=r,EB=s,$8(t),t.flags&=-3}}function c3(t,i=!1){const{dep:r,prevSub:s,nextSub:g}=t;if(s&&(s.nextSub=g,t.prevSub=void 0),g&&(g.prevSub=s,t.nextSub=void 0),r.subs===t&&(r.subs=s,!s&&r.computed)){r.computed.flags&=-5;for(let B=r.computed.deps;B;B=B.nextDep)c3(B,!0)}!i&&!--r.sc&&r.map&&r.map.delete(r.key)}function hiA(t){const{prevDep:i,nextDep:r}=t;i&&(i.nextDep=r,t.prevDep=void 0),r&&(r.prevDep=i,t.nextDep=void 0)}let EB=!0;const eZ=[];function Np(){eZ.push(EB),EB=!1}function Tp(){const t=eZ.pop();EB=t===void 0?!0:t}function bz(t){const{cleanup:i}=t;if(t.cleanup=void 0,i){const r=ea;ea=void 0;try{i()}finally{ea=r}}}let ak=0;class piA{constructor(i,r){this.sub=i,this.dep=r,this.version=r.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class E3{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(!ea||!EB||ea===this.computed)return;let r=this.activeLink;if(r===void 0||r.sub!==ea)r=this.activeLink=new piA(ea,this),ea.deps?(r.prevDep=ea.depsTail,ea.depsTail.nextDep=r,ea.depsTail=r):ea.deps=ea.depsTail=r,tZ(r);else if(r.version===-1&&(r.version=this.version,r.nextDep)){const s=r.nextDep;s.prevDep=r.prevDep,r.prevDep&&(r.prevDep.nextDep=s),r.prevDep=ea.depsTail,r.nextDep=void 0,ea.depsTail.nextDep=r,ea.depsTail=r,ea.deps===r&&(ea.deps=s)}return r}trigger(i){this.version++,ak++,this.notify(i)}notify(i){g3();try{for(let r=this.subs;r;r=r.prevSub)r.sub.notify()&&r.sub.dep.notify()}finally{I3()}}}function tZ(t){if(t.dep.sc++,t.sub.flags&4){const i=t.dep.computed;if(i&&!t.dep.subs){i.flags|=20;for(let s=i.deps;s;s=s.nextDep)tZ(s)}const r=t.dep.subs;r!==t&&(t.prevSub=r,r&&(r.nextSub=t)),t.dep.subs=t}}const F2=new WeakMap,nD=Symbol(""),Bj=Symbol(""),sk=Symbol("");function GI(t,i,r){if(EB&&ea){let s=F2.get(t);s||F2.set(t,s=new Map);let g=s.get(r);g||(s.set(r,g=new E3),g.map=s,g.key=r),g.track()}}function ad(t,i,r,s,g,B){const Q=F2.get(t);if(!Q){ak++;return}const f=m=>{m&&m.trigger()};if(g3(),i==="clear")Q.forEach(f);else{const m=Ro(t),M=m&&s3(r);if(m&&r==="length"){const v=Number(s);Q.forEach((U,AA)=>{(AA==="length"||AA===sk||!cd(AA)&&AA>=v)&&f(U)})}else switch((r!==void 0||Q.has(void 0))&&f(Q.get(r)),M&&f(Q.get(sk)),i){case"add":m?M&&f(Q.get("length")):(f(Q.get(nD)),dw(t)&&f(Q.get(Bj)));break;case"delete":m||(f(Q.get(nD)),dw(t)&&f(Q.get(Bj)));break;case"set":dw(t)&&f(Q.get(nD));break}}I3()}function fiA(t,i){const r=F2.get(t);return r&&r.get(i)}function zM(t){const i=an(t);return i===t?i:(GI(i,"iterate",sk),hC(t)?i:i.map(kI))}function dY(t){return GI(t=an(t),"iterate",sk),t}const miA={__proto__:null,[Symbol.iterator](){return yK(this,Symbol.iterator,kI)},concat(...t){return zM(this).concat(...t.map(i=>Ro(i)?zM(i):i))},entries(){return yK(this,"entries",t=>(t[1]=kI(t[1]),t))},every(t,i){return $Q(this,"every",t,i,void 0,arguments)},filter(t,i){return $Q(this,"filter",t,i,r=>r.map(kI),arguments)},find(t,i){return $Q(this,"find",t,i,kI,arguments)},findIndex(t,i){return $Q(this,"findIndex",t,i,void 0,arguments)},findLast(t,i){return $Q(this,"findLast",t,i,kI,arguments)},findLastIndex(t,i){return $Q(this,"findLastIndex",t,i,void 0,arguments)},forEach(t,i){return $Q(this,"forEach",t,i,void 0,arguments)},includes(...t){return RK(this,"includes",t)},indexOf(...t){return RK(this,"indexOf",t)},join(t){return zM(this).join(t)},lastIndexOf(...t){return RK(this,"lastIndexOf",t)},map(t,i){return $Q(this,"map",t,i,void 0,arguments)},pop(){return BG(this,"pop")},push(...t){return BG(this,"push",t)},reduce(t,...i){return Lz(this,"reduce",t,i)},reduceRight(t,...i){return Lz(this,"reduceRight",t,i)},shift(){return BG(this,"shift")},some(t,i){return $Q(this,"some",t,i,void 0,arguments)},splice(...t){return BG(this,"splice",t)},toReversed(){return zM(this).toReversed()},toSorted(t){return zM(this).toSorted(t)},toSpliced(...t){return zM(this).toSpliced(...t)},unshift(...t){return BG(this,"unshift",t)},values(){return yK(this,"values",kI)}};function yK(t,i,r){const s=dY(t),g=s[i]();return s!==t&&!hC(t)&&(g._next=g.next,g.next=()=>{const B=g._next();return B.value&&(B.value=r(B.value)),B}),g}const DiA=Array.prototype;function $Q(t,i,r,s,g,B){const Q=dY(t),f=Q!==t&&!hC(t),m=Q[i];if(m!==DiA[i]){const U=m.apply(t,B);return f?kI(U):U}let M=r;Q!==t&&(f?M=function(U,AA){return r.call(this,kI(U),AA,t)}:r.length>2&&(M=function(U,AA){return r.call(this,U,AA,t)}));const v=m.call(Q,M,s);return f&&g?g(v):v}function Lz(t,i,r,s){const g=dY(t);let B=r;return g!==t&&(hC(t)?r.length>3&&(B=function(Q,f,m){return r.call(this,Q,f,m,t)}):B=function(Q,f,m){return r.call(this,Q,kI(f),m,t)}),g[i](B,...s)}function RK(t,i,r){const s=an(t);GI(s,"iterate",sk);const g=s[i](...r);return(g===-1||g===!1)&&B3(r[0])?(r[0]=an(r[0]),s[i](...r)):g}function BG(t,i,r=[]){Np(),g3();const s=an(t)[i].apply(t,r);return I3(),Tp(),s}const yiA=r3("__proto__,__v_isRef,__isVue"),iZ=new Set(Object.getOwnPropertyNames(Symbol).filter(t=>t!=="arguments"&&t!=="caller").map(t=>Symbol[t]).filter(cd));function RiA(t){cd(t)||(t=String(t));const i=an(this);return GI(i,"has",t),i.hasOwnProperty(t)}class oZ{constructor(i=!1,r=!1){this._isReadonly=i,this._isShallow=r}get(i,r,s){if(r==="__v_skip")return i.__v_skip;const g=this._isReadonly,B=this._isShallow;if(r==="__v_isReactive")return!g;if(r==="__v_isReadonly")return g;if(r==="__v_isShallow")return B;if(r==="__v_raw")return s===(g?B?biA:sZ:B?aZ:nZ).get(i)||Object.getPrototypeOf(i)===Object.getPrototypeOf(s)?i:void 0;const Q=Ro(i);if(!g){let m;if(Q&&(m=miA[r]))return m;if(r==="hasOwnProperty")return RiA}const f=Reflect.get(i,r,wg(i)?i:s);return(cd(r)?iZ.has(r):yiA(r))||(g||GI(i,"get",r),B)?f:wg(f)?Q&&s3(r)?f:f.value:ta(f)?g?HG(f):tD(f):f}}class rZ extends oZ{constructor(i=!1){super(!1,i)}set(i,r,s,g){let B=i[r];if(!this._isShallow){const m=QD(B);if(!hC(s)&&!QD(s)&&(B=an(B),s=an(s)),!Ro(i)&&wg(B)&&!wg(s))return m?!1:(B.value=s,!0)}const Q=Ro(i)&&s3(r)?Number(r)t,t2=t=>Reflect.getPrototypeOf(t);function NiA(t,i,r){return function(...s){const g=this.__v_raw,B=an(g),Q=dw(B),f=t==="entries"||t===Symbol.iterator&&Q,m=t==="keys"&&Q,M=g[t](...s),v=r?uj:i?Qj:kI;return!i&&GI(B,"iterate",m?Bj:nD),{next(){const{value:U,done:AA}=M.next();return AA?{value:U,done:AA}:{value:f?[v(U[0]),v(U[1])]:v(U),done:AA}},[Symbol.iterator](){return this}}}}function i2(t){return function(...i){return t==="delete"?!1:t==="clear"?void 0:this}}function TiA(t,i){const r={get(g){const B=this.__v_raw,Q=an(B),f=an(g);t||(Qp(g,f)&&GI(Q,"get",g),GI(Q,"get",f));const{has:m}=t2(Q),M=i?uj:t?Qj:kI;if(m.call(Q,g))return M(B.get(g));if(m.call(Q,f))return M(B.get(f));B!==Q&&B.get(g)},get size(){const g=this.__v_raw;return!t&&GI(an(g),"iterate",nD),Reflect.get(g,"size",g)},has(g){const B=this.__v_raw,Q=an(B),f=an(g);return t||(Qp(g,f)&&GI(Q,"has",g),GI(Q,"has",f)),g===f?B.has(g):B.has(g)||B.has(f)},forEach(g,B){const Q=this,f=Q.__v_raw,m=an(f),M=i?uj:t?Qj:kI;return!t&&GI(m,"iterate",nD),f.forEach((v,U)=>g.call(B,M(v),M(U),Q))}};return Sg(r,t?{add:i2("add"),set:i2("set"),delete:i2("delete"),clear:i2("clear")}:{add(g){!i&&!hC(g)&&!QD(g)&&(g=an(g));const B=an(this);return t2(B).has.call(B,g)||(B.add(g),ad(B,"add",g,g)),this},set(g,B){!i&&!hC(B)&&!QD(B)&&(B=an(B));const Q=an(this),{has:f,get:m}=t2(Q);let M=f.call(Q,g);M||(g=an(g),M=f.call(Q,g));const v=m.call(Q,g);return Q.set(g,B),M?Qp(B,v)&&ad(Q,"set",g,B):ad(Q,"add",g,B),this},delete(g){const B=an(this),{has:Q,get:f}=t2(B);let m=Q.call(B,g);m||(g=an(g),m=Q.call(B,g)),f&&f.call(B,g);const M=B.delete(g);return m&&ad(B,"delete",g,void 0),M},clear(){const g=an(this),B=g.size!==0,Q=g.clear();return B&&ad(g,"clear",void 0,void 0),Q}}),["keys","values","entries",Symbol.iterator].forEach(g=>{r[g]=NiA(g,t,i)}),r}function l3(t,i){const r=TiA(t,i);return(s,g,B)=>g==="__v_isReactive"?!t:g==="__v_isReadonly"?t:g==="__v_raw"?s:Reflect.get(yn(r,g)&&g in s?r:s,g,B)}const GiA={get:l3(!1,!1)},kiA={get:l3(!1,!0)},_iA={get:l3(!0,!1)};const nZ=new WeakMap,aZ=new WeakMap,sZ=new WeakMap,biA=new WeakMap;function LiA(t){switch(t){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function FiA(t){return t.__v_skip||!Object.isExtensible(t)?0:LiA(riA(t))}function tD(t){return QD(t)?t:C3(t,!1,wiA,GiA,nZ)}function UiA(t){return C3(t,!1,viA,kiA,aZ)}function HG(t){return C3(t,!0,SiA,_iA,sZ)}function C3(t,i,r,s,g){if(!ta(t)||t.__v_raw&&!(i&&t.__v_isReactive))return t;const B=g.get(t);if(B)return B;const Q=FiA(t);if(Q===0)return t;const f=new Proxy(t,Q===2?s:r);return g.set(t,f),f}function hw(t){return QD(t)?hw(t.__v_raw):!!(t&&t.__v_isReactive)}function QD(t){return!!(t&&t.__v_isReadonly)}function hC(t){return!!(t&&t.__v_isShallow)}function B3(t){return t?!!t.__v_raw:!1}function an(t){const i=t&&t.__v_raw;return i?an(i):t}function OiA(t){return!yn(t,"__v_skip")&&Object.isExtensible(t)&&V8(t,"__v_skip",!0),t}const kI=t=>ta(t)?tD(t):t,Qj=t=>ta(t)?HG(t):t;function wg(t){return t?t.__v_isRef===!0:!1}function Ne(t){return xiA(t,!1)}function xiA(t,i){return wg(t)?t:new YiA(t,i)}class YiA{constructor(i,r){this.dep=new E3,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=r?i:an(i),this._value=r?i:kI(i),this.__v_isShallow=r}get value(){return this.dep.track(),this._value}set value(i){const r=this._rawValue,s=this.__v_isShallow||hC(i)||QD(i);i=s?i:an(i),Qp(i,r)&&(this._rawValue=i,this._value=s?i:kI(i),this.dep.trigger())}}function W(t){return wg(t)?t.value:t}const PiA={get:(t,i,r)=>i==="__v_raw"?t:W(Reflect.get(t,i,r)),set:(t,i,r,s)=>{const g=t[i];return wg(g)&&!wg(r)?(g.value=r,!0):Reflect.set(t,i,r,s)}};function gZ(t){return hw(t)?t:new Proxy(t,PiA)}function Mo(t){const i=Ro(t)?new Array(t.length):{};for(const r in t)i[r]=IZ(t,r);return i}class JiA{constructor(i,r,s){this._object=i,this._key=r,this._defaultValue=s,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 fiA(an(this._object),this._key)}}class HiA{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 MK(t,i,r){return wg(t)?t:xo(t)?new HiA(t):ta(t)&&arguments.length>1?IZ(t,i,r):Ne(t)}function IZ(t,i,r){const s=t[i];return wg(s)?s:new JiA(t,i,r)}class ViA{constructor(i,r,s){this.fn=i,this.setter=r,this._value=void 0,this.dep=new E3(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=ak-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!r,this.isSSR=s}notify(){if(this.flags|=16,!(this.flags&8)&&ea!==this)return Z8(this,!0),!0}get value(){const i=this.dep.track();return AZ(this),i&&(i.version=this.dep.version),this._value}set value(i){this.setter&&this.setter(i)}}function qiA(t,i,r=!1){let s,g;return xo(t)?s=t:(s=t.get,g=t.set),new ViA(s,g,r)}const o2={},U2=new WeakMap;let zm;function KiA(t,i=!1,r=zm){if(r){let s=U2.get(r);s||U2.set(r,s=[]),s.push(t)}}function jiA(t,i,r=qn){const{immediate:s,deep:g,once:B,scheduler:Q,augmentJob:f,call:m}=r,M=qA=>g?qA:hC(qA)||g===!1||g===0?sd(qA,1):sd(qA);let v,U,AA,z,sA=!1,eA=!1;if(wg(t)?(U=()=>t.value,sA=hC(t)):hw(t)?(U=()=>M(t),sA=!0):Ro(t)?(eA=!0,sA=t.some(qA=>hw(qA)||hC(qA)),U=()=>t.map(qA=>{if(wg(qA))return qA.value;if(hw(qA))return M(qA);if(xo(qA))return m?m(qA,2):qA()})):xo(t)?i?U=m?()=>m(t,2):t:U=()=>{if(AA){Np();try{AA()}finally{Tp()}}const qA=zm;zm=v;try{return m?m(t,3,[z]):t(z)}finally{zm=qA}}:U=Ou,i&&g){const qA=U,ue=g===!0?1/0:g;U=()=>sd(qA(),ue)}const X=diA(),QA=()=>{v.stop(),X&&X.active&&a3(X.effects,v)};if(B&&i){const qA=i;i=(...ue)=>{qA(...ue),QA()}}let wA=eA?new Array(t.length).fill(o2):o2;const HA=qA=>{if(!(!(v.flags&1)||!v.dirty&&!qA))if(i){const ue=v.run();if(g||sA||(eA?ue.some((jA,Ve)=>Qp(jA,wA[Ve])):Qp(ue,wA))){AA&&AA();const jA=zm;zm=v;try{const Ve=[ue,wA===o2?void 0:eA&&wA[0]===o2?[]:wA,z];m?m(i,3,Ve):i(...Ve),wA=ue}finally{zm=jA}}}else v.run()};return f&&f(HA),v=new W8(U),v.scheduler=Q?()=>Q(HA,!1):HA,z=qA=>KiA(qA,!1,v),AA=v.onStop=()=>{const qA=U2.get(v);if(qA){if(m)m(qA,4);else for(const ue of qA)ue();U2.delete(v)}},i?s?HA(!0):wA=v.run():Q?Q(HA.bind(null,!0),!0):v.run(),QA.pause=v.pause.bind(v),QA.resume=v.resume.bind(v),QA.stop=QA,QA}function sd(t,i=1/0,r){if(i<=0||!ta(t)||t.__v_skip||(r=r||new Set,r.has(t)))return t;if(r.add(t),i--,wg(t))sd(t.value,i,r);else if(Ro(t))for(let s=0;s{sd(s,i,r)});else if(H8(t)){for(const s in t)sd(t[s],i,r);for(const s of Object.getOwnPropertySymbols(t))Object.prototype.propertyIsEnumerable.call(t,s)&&sd(t[s],i,r)}return t}/** * @vue/runtime-core v3.5.13 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT -**/function Qk(t,i,r,s){try{return s?t(...s):t()}catch(g){EY(g,i,r)}}function CB(t,i,r,s){if(xo(t)){const g=Qk(t,i,r,s);return g&&b8(g)&&g.catch(B=>{EY(B,i,r)}),g}if(Ro(t)){const g=[];for(let B=0;B>>1,g=Dc[s],B=ik(g);B=ik(r)?Dc.push(t):Dc.splice(FiA(i),0,t),t.flags|=1,rZ()}}function rZ(){k2||(k2=oZ.then(aZ))}function UiA(t){Ro(t)?Qw.push(...t):ap&&t.id===-1?ap.splice(XM+1,0,t):t.flags&1||(Qw.push(t),t.flags|=1),rZ()}function Nz(t,i,r=vu+1){for(;rik(r)-ik(s));if(Qw.length=0,ap){ap.push(...i);return}for(ap=i,XM=0;XMt.id==null?t.flags&2?-1:1/0:t.id;function aZ(t){try{for(vu=0;vu{s._d&&Hz(-1);const B=_2(i);let Q;try{Q=t(...g)}finally{_2(B),s._d&&Hz(1)}return Q};return s._n=!0,s._c=!0,s._d=!0,s}function aa(t,i){if(Mg===null)return t;const r=hY(Mg),s=t.dirs||(t.dirs=[]);for(let g=0;gt.__isTeleport,xG=t=>t&&(t.disabled||t.disabled===""),Tz=t=>t&&(t.defer||t.defer===""),Gz=t=>typeof SVGElement<"u"&&t instanceof SVGElement,kz=t=>typeof MathMLElement=="function"&&t instanceof MathMLElement,Ej=(t,i)=>{const r=t&&t.to;return va(r)?i?i(r):null:r},IZ={name:"Teleport",__isTeleport:!0,process(t,i,r,s,g,B,Q,f,m,M){const{mc:v,pc:U,pbc:AA,o:{insert:z,querySelector:sA,createText:eA,createComment:X}}=M,QA=xG(i.props);let{shapeFlag:wA,children:HA,dynamicChildren:VA}=i;if(t==null){const ue=i.el=eA(""),jA=i.anchor=eA("");z(ue,r,s),z(jA,r,s);const Ve=(Me,qe)=>{wA&16&&(g&&g.isCE&&(g.ce._teleportTarget=Me),v(HA,Me,qe,g,B,Q,f,m))},Ze=()=>{const Me=i.target=Ej(i.props,sA),qe=cZ(Me,i,eA,z);Me&&(Q!=="svg"&&Gz(Me)?Q="svg":Q!=="mathml"&&kz(Me)&&(Q="mathml"),QA||(Ve(Me,qe),B2(i,!1)))};QA&&(Ve(r,jA),B2(i,!0)),Tz(i.props)?fc(()=>{Ze(),i.el.__isMounted=!0},B):Ze()}else{if(Tz(i.props)&&!t.el.__isMounted){fc(()=>{IZ.process(t,i,r,s,g,B,Q,f,m,M),delete t.el.__isMounted},B);return}i.el=t.el,i.targetStart=t.targetStart;const ue=i.anchor=t.anchor,jA=i.target=t.target,Ve=i.targetAnchor=t.targetAnchor,Ze=xG(t.props),Me=Ze?r:jA,qe=Ze?ue:Ve;if(Q==="svg"||Gz(jA)?Q="svg":(Q==="mathml"||kz(jA))&&(Q="mathml"),VA?(AA(t.dynamicChildren,VA,Me,g,B,Q,f),E3(t,i,!0)):m||U(t,i,Me,qe,g,B,Q,f,!1),QA)Ze?i.props&&t.props&&i.props.to!==t.props.to&&(i.props.to=t.props.to):Xx(i,r,ue,M,1);else if((i.props&&i.props.to)!==(t.props&&t.props.to)){const Et=i.target=Ej(i.props,sA);Et&&Xx(i,Et,null,M,0)}else Ze&&Xx(i,jA,Ve,M,1);B2(i,QA)}},remove(t,i,r,{um:s,o:{remove:g}},B){const{shapeFlag:Q,children:f,anchor:m,targetStart:M,targetAnchor:v,target:U,props:AA}=t;if(U&&(g(M),g(v)),B&&g(m),Q&16){const z=B||!xG(AA);for(let sA=0;sA{t.isMounted=!0}),hZ(()=>{t.isUnmounting=!0}),t}const sC=[Function,Array],EZ={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:sC,onEnter:sC,onAfterEnter:sC,onEnterCancelled:sC,onBeforeLeave:sC,onLeave:sC,onAfterLeave:sC,onLeaveCancelled:sC,onBeforeAppear:sC,onAppear:sC,onAfterAppear:sC,onAppearCancelled:sC},lZ=t=>{const i=t.subTree;return i.component?lZ(i.component):i},PiA={name:"BaseTransition",props:EZ,setup(t,{slots:i}){const r=UoA(),s=YiA();return()=>{const g=i.default&&uZ(i.default(),!0);if(!g||!g.length)return;const B=CZ(g),Q=an(t),{mode:f}=Q;if(s.isLeaving)return fK(B);const m=_z(B);if(!m)return fK(B);let M=lj(m,Q,s,r,U=>M=U);m.type!==yc&&ok(m,M);let v=r.subTree&&_z(r.subTree);if(v&&v.type!==yc&&!Km(m,v)&&lZ(r).type!==yc){let U=lj(v,Q,s,r);if(ok(v,U),f==="out-in"&&m.type!==yc)return s.isLeaving=!0,U.afterLeave=()=>{s.isLeaving=!1,r.job.flags&8||r.update(),delete U.afterLeave,v=void 0},fK(B);f==="in-out"&&m.type!==yc?U.delayLeave=(AA,z,sA)=>{const eA=BZ(s,v);eA[String(v.key)]=v,AA[sp]=()=>{z(),AA[sp]=void 0,delete M.delayedLeave,v=void 0},M.delayedLeave=()=>{sA(),delete M.delayedLeave,v=void 0}}:v=void 0}else v&&(v=void 0);return B}}};function CZ(t){let i=t[0];if(t.length>1){for(const r of t)if(r.type!==yc){i=r;break}}return i}const JiA=PiA;function BZ(t,i){const{leavingVNodes:r}=t;let s=r.get(i.type);return s||(s=Object.create(null),r.set(i.type,s)),s}function lj(t,i,r,s,g){const{appear:B,mode:Q,persisted:f=!1,onBeforeEnter:m,onEnter:M,onAfterEnter:v,onEnterCancelled:U,onBeforeLeave:AA,onLeave:z,onAfterLeave:sA,onLeaveCancelled:eA,onBeforeAppear:X,onAppear:QA,onAfterAppear:wA,onAppearCancelled:HA}=i,VA=String(t.key),ue=BZ(r,t),jA=(Me,qe)=>{Me&&CB(Me,s,9,qe)},Ve=(Me,qe)=>{const Et=qe[1];jA(Me,qe),Ro(Me)?Me.every(Je=>Je.length<=1)&&Et():Me.length<=1&&Et()},Ze={mode:Q,persisted:f,beforeEnter(Me){let qe=m;if(!r.isMounted)if(B)qe=X||m;else return;Me[sp]&&Me[sp](!0);const Et=ue[VA];Et&&Km(t,Et)&&Et.el[sp]&&Et.el[sp](),jA(qe,[Me])},enter(Me){let qe=M,Et=v,Je=U;if(!r.isMounted)if(B)qe=QA||M,Et=wA||v,Je=HA||U;else return;let $e=!1;const Dt=Me[$x]=Zi=>{$e||($e=!0,Zi?jA(Je,[Me]):jA(Et,[Me]),Ze.delayedLeave&&Ze.delayedLeave(),Me[$x]=void 0)};qe?Ve(qe,[Me,Dt]):Dt()},leave(Me,qe){const Et=String(t.key);if(Me[$x]&&Me[$x](!0),r.isUnmounting)return qe();jA(AA,[Me]);let Je=!1;const $e=Me[sp]=Dt=>{Je||(Je=!0,qe(),Dt?jA(eA,[Me]):jA(sA,[Me]),Me[sp]=void 0,ue[Et]===t&&delete ue[Et])};ue[Et]=t,z?Ve(z,[Me,$e]):$e()},clone(Me){const qe=lj(Me,i,r,s,g);return g&&g(qe),qe}};return Ze}function fK(t){if(BY(t))return t=hp(t),t.children=null,t}function _z(t){if(!BY(t))return gZ(t.type)&&t.children?CZ(t.children):t;const{shapeFlag:i,children:r}=t;if(r){if(i&16)return r[0];if(i&32&&xo(r.default))return r.default()}}function ok(t,i){t.shapeFlag&6&&t.component?(t.transition=i,ok(t.component.subTree,i)):t.shapeFlag&128?(t.ssContent.transition=i.clone(t.ssContent),t.ssFallback.transition=i.clone(t.ssFallback)):t.transition=i}function uZ(t,i=!1,r){let s=[],g=0;for(let B=0;B1)for(let B=0;Bb2(sA,i&&(Ro(i)?i[eA]:i),r,s,g));return}if(dw(s)&&!g){s.shapeFlag&512&&s.type.__asyncResolved&&s.component.subTree.component&&b2(t,i,r,s.component.subTree);return}const B=s.shapeFlag&4?hY(s.component):s.el,Q=g?null:B,{i:f,r:m}=t,M=i&&i.r,v=f.refs===qn?f.refs={}:f.refs,U=f.setupState,AA=an(U),z=U===qn?()=>!1:sA=>yn(AA,sA);if(M!=null&&M!==m&&(va(M)?(v[M]=null,z(M)&&(U[M]=null)):wg(M)&&(M.value=null)),xo(m))Qk(m,f,12,[Q,v]);else{const sA=va(m),eA=wg(m);if(sA||eA){const X=()=>{if(t.f){const QA=sA?z(m)?U[m]:v[m]:m.value;g?Ro(QA)&&e3(QA,B):Ro(QA)?QA.includes(B)||QA.push(B):sA?(v[m]=[B],z(m)&&(U[m]=v[m])):(m.value=[B],t.k&&(v[t.k]=m.value))}else sA?(v[m]=Q,z(m)&&(U[m]=Q)):eA&&(m.value=Q,t.k&&(v[t.k]=Q))};Q?(X.id=-1,fc(X,r)):X()}}}IY().requestIdleCallback;IY().cancelIdleCallback;const dw=t=>!!t.type.__asyncLoader,BY=t=>t.type.__isKeepAlive;function HiA(t,i){dZ(t,"a",i)}function ViA(t,i){dZ(t,"da",i)}function dZ(t,i,r=oI){const s=t.__wdc||(t.__wdc=()=>{let g=r;for(;g;){if(g.isDeactivated)return;g=g.parent}return t()});if(uY(i,s,r),r){let g=r.parent;for(;g&&g.parent;)BY(g.parent.vnode)&&qiA(s,i,r,g),g=g.parent}}function qiA(t,i,r,s){const g=uY(i,t,s,!0);Ya(()=>{e3(s[i],g)},r)}function uY(t,i,r=oI,s=!1){if(r){const g=r[t]||(r[t]=[]),B=i.__weh||(i.__weh=(...Q)=>{Mp();const f=dk(r),m=CB(i,r,t,Q);return f(),wp(),m});return s?g.unshift(B):g.push(B),B}}const gd=t=>(i,r=oI)=>{(!ak||t==="sp")&&uY(t,(...s)=>i(...s),r)},KiA=gd("bm"),gs=gd("m"),jiA=gd("bu"),WiA=gd("u"),hZ=gd("bum"),Ya=gd("um"),ziA=gd("sp"),ZiA=gd("rtg"),XiA=gd("rtc");function $iA(t,i=oI){uY("ec",t,i)}const AoA="components";function eoA(t,i){return ioA(AoA,t,!0,i)||t}const toA=Symbol.for("v-ndc");function ioA(t,i,r=!0,s=!1){const g=Mg||oI;if(g){const B=g.type;{const f=JoA(B,!1);if(f&&(f===i||f===mC(i)||f===gY(mC(i))))return B}const Q=bz(g[t]||B[t],i)||bz(g.appContext[t],i);return!Q&&s?B:Q}}function bz(t,i){return t&&(t[i]||t[mC(i)]||t[gY(mC(i))])}function DC(t,i,r,s){let g;const B=r,Q=Ro(t);if(Q||va(t)){const f=Q&&uw(t);let m=!1;f&&(m=!hC(t),t=cY(t)),g=new Array(t.length);for(let M=0,v=t.length;Mi(f,m,void 0,B));else{const f=Object.keys(t);g=new Array(f.length);for(let m=0,M=f.length;mnk(i)?!(i.type===yc||i.type===Tn&&!pZ(i.children)):!0)?t:null}const Cj=t=>t?OZ(t)?hY(t):Cj(t.parent):null,YG=Sg(Object.create(null),{$:t=>t,$el:t=>t.vnode.el,$data:t=>t.data,$props:t=>t.props,$attrs:t=>t.attrs,$slots:t=>t.slots,$refs:t=>t.refs,$parent:t=>Cj(t.parent),$root:t=>Cj(t.root),$host:t=>t.ce,$emit:t=>t.emit,$options:t=>mZ(t),$forceUpdate:t=>t.f||(t.f=()=>{I3(t.update)}),$nextTick:t=>t.n||(t.n=lY.bind(t.proxy)),$watch:t=>yoA.bind(t)}),mK=(t,i)=>t!==qn&&!t.__isScriptSetup&&yn(t,i),ooA={get({_:t},i){if(i==="__v_skip")return!0;const{ctx:r,setupState:s,data:g,props:B,accessCache:Q,type:f,appContext:m}=t;let M;if(i[0]!=="$"){const z=Q[i];if(z!==void 0)switch(z){case 1:return s[i];case 2:return g[i];case 4:return r[i];case 3:return B[i]}else{if(mK(s,i))return Q[i]=1,s[i];if(g!==qn&&yn(g,i))return Q[i]=2,g[i];if((M=t.propsOptions[0])&&yn(M,i))return Q[i]=3,B[i];if(r!==qn&&yn(r,i))return Q[i]=4,r[i];Bj&&(Q[i]=0)}}const v=YG[i];let U,AA;if(v)return i==="$attrs"&&GI(t.attrs,"get",""),v(t);if((U=f.__cssModules)&&(U=U[i]))return U;if(r!==qn&&yn(r,i))return Q[i]=4,r[i];if(AA=m.config.globalProperties,yn(AA,i))return AA[i]},set({_:t},i,r){const{data:s,setupState:g,ctx:B}=t;return mK(g,i)?(g[i]=r,!0):s!==qn&&yn(s,i)?(s[i]=r,!0):yn(t.props,i)||i[0]==="$"&&i.slice(1)in t?!1:(B[i]=r,!0)},has({_:{data:t,setupState:i,accessCache:r,ctx:s,appContext:g,propsOptions:B}},Q){let f;return!!r[Q]||t!==qn&&yn(t,Q)||mK(i,Q)||(f=B[0])&&yn(f,Q)||yn(s,Q)||yn(YG,Q)||yn(g.config.globalProperties,Q)},defineProperty(t,i,r){return r.get!=null?t._.accessCache[i]=0:yn(r,"value")&&this.set(t,i,r.value,null),Reflect.defineProperty(t,i,r)}};function Lz(t){return Ro(t)?t.reduce((i,r)=>(i[r]=null,i),{}):t}let Bj=!0;function roA(t){const i=mZ(t),r=t.proxy,s=t.ctx;Bj=!1,i.beforeCreate&&Fz(i.beforeCreate,t,"bc");const{data:g,computed:B,methods:Q,watch:f,provide:m,inject:M,created:v,beforeMount:U,mounted:AA,beforeUpdate:z,updated:sA,activated:eA,deactivated:X,beforeDestroy:QA,beforeUnmount:wA,destroyed:HA,unmounted:VA,render:ue,renderTracked:jA,renderTriggered:Ve,errorCaptured:Ze,serverPrefetch:Me,expose:qe,inheritAttrs:Et,components:Je,directives:$e,filters:Dt}=i;if(M&&noA(M,s,null),Q)for(const qt in Q){const ai=Q[qt];xo(ai)&&(s[qt]=ai.bind(r))}if(g){const qt=g.call(r,r);ta(qt)&&(t.data=Xm(qt))}if(Bj=!0,B)for(const qt in B){const ai=B[qt],Ki=xo(ai)?ai.bind(r,r):xo(ai.get)?ai.get.bind(r,r):Lu,Ur=!xo(ai)&&xo(ai.set)?ai.set.bind(r):Lu,Er=rt({get:Ki,set:Ur});Object.defineProperty(s,qt,{enumerable:!0,configurable:!0,get:()=>Er.value,set:no=>Er.value=no})}if(f)for(const qt in f)fZ(f[qt],s,r,qt);if(m){const qt=xo(m)?m.call(r):m;Reflect.ownKeys(qt).forEach(ai=>{gE(ai,qt[ai])})}v&&Fz(v,t,"c");function bi(qt,ai){Ro(ai)?ai.forEach(Ki=>qt(Ki.bind(r))):ai&&qt(ai.bind(r))}if(bi(KiA,U),bi(gs,AA),bi(jiA,z),bi(WiA,sA),bi(HiA,eA),bi(ViA,X),bi($iA,Ze),bi(XiA,jA),bi(ZiA,Ve),bi(hZ,wA),bi(Ya,VA),bi(ziA,Me),Ro(qe))if(qe.length){const qt=t.exposed||(t.exposed={});qe.forEach(ai=>{Object.defineProperty(qt,ai,{get:()=>r[ai],set:Ki=>r[ai]=Ki})})}else t.exposed||(t.exposed={});ue&&t.render===Lu&&(t.render=ue),Et!=null&&(t.inheritAttrs=Et),Je&&(t.components=Je),$e&&(t.directives=$e),Me&&QZ(t)}function noA(t,i,r=Lu){Ro(t)&&(t=uj(t));for(const s in t){const g=t[s];let B;ta(g)?"default"in g?B=rI(g.from||s,g.default,!0):B=rI(g.from||s):B=rI(g),wg(B)?Object.defineProperty(i,s,{enumerable:!0,configurable:!0,get:()=>B.value,set:Q=>B.value=Q}):i[s]=B}}function Fz(t,i,r){CB(Ro(t)?t.map(s=>s.bind(i.proxy)):t.bind(i.proxy),i,r)}function fZ(t,i,r,s){let g=s.includes(".")?_Z(r,s):()=>r[s];if(va(t)){const B=i[t];xo(B)&&Un(g,B)}else if(xo(t))Un(g,t.bind(r));else if(ta(t))if(Ro(t))t.forEach(B=>fZ(B,i,r,s));else{const B=xo(t.handler)?t.handler.bind(r):i[t.handler];xo(B)&&Un(g,B,t)}}function mZ(t){const i=t.type,{mixins:r,extends:s}=i,{mixins:g,optionsCache:B,config:{optionMergeStrategies:Q}}=t.appContext,f=B.get(i);let m;return f?m=f:!g.length&&!r&&!s?m=i:(m={},g.length&&g.forEach(M=>L2(m,M,Q,!0)),L2(m,i,Q)),ta(i)&&B.set(i,m),m}function L2(t,i,r,s=!1){const{mixins:g,extends:B}=i;B&&L2(t,B,r,!0),g&&g.forEach(Q=>L2(t,Q,r,!0));for(const Q in i)if(!(s&&Q==="expose")){const f=aoA[Q]||r&&r[Q];t[Q]=f?f(t[Q],i[Q]):i[Q]}return t}const aoA={data:Uz,props:Oz,emits:Oz,methods:hG,computed:hG,beforeCreate:dc,created:dc,beforeMount:dc,mounted:dc,beforeUpdate:dc,updated:dc,beforeDestroy:dc,beforeUnmount:dc,destroyed:dc,unmounted:dc,activated:dc,deactivated:dc,errorCaptured:dc,serverPrefetch:dc,components:hG,directives:hG,watch:goA,provide:Uz,inject:soA};function Uz(t,i){return i?t?function(){return Sg(xo(t)?t.call(this,this):t,xo(i)?i.call(this,this):i)}:i:t}function soA(t,i){return hG(uj(t),uj(i))}function uj(t){if(Ro(t)){const i={};for(let r=0;r1)return r&&xo(i)?i.call(s&&s.proxy):i}}const yZ={},RZ=()=>Object.create(yZ),MZ=t=>Object.getPrototypeOf(t)===yZ;function EoA(t,i,r,s=!1){const g={},B=RZ();t.propsDefaults=Object.create(null),wZ(t,i,g,B);for(const Q in t.propsOptions[0])Q in g||(g[Q]=void 0);r?t.props=s?g:RiA(g):t.type.props?t.props=g:t.props=B,t.attrs=B}function loA(t,i,r,s){const{props:g,attrs:B,vnode:{patchFlag:Q}}=t,f=an(g),[m]=t.propsOptions;let M=!1;if((s||Q>0)&&!(Q&16)){if(Q&8){const v=t.vnode.dynamicProps;for(let U=0;U{m=!0;const[AA,z]=SZ(U,i,!0);Sg(Q,AA),z&&f.push(...z)};!r&&i.mixins.length&&i.mixins.forEach(v),t.extends&&v(t.extends),t.mixins&&t.mixins.forEach(v)}if(!B&&!m)return ta(t)&&s.set(t,Cw),Cw;if(Ro(B))for(let v=0;vt[0]==="_"||t==="$stable",c3=t=>Ro(t)?t.map(Gu):[Gu(t)],BoA=(t,i,r)=>{if(i._n)return i;const s=Vt((...g)=>c3(i(...g)),r);return s._c=!1,s},NZ=(t,i,r)=>{const s=t._ctx;for(const g in t){if(vZ(g))continue;const B=t[g];if(xo(B))i[g]=BoA(g,B,s);else if(B!=null){const Q=c3(B);i[g]=()=>Q}}},TZ=(t,i)=>{const r=c3(i);t.slots.default=()=>r},GZ=(t,i,r)=>{for(const s in i)(r||s!=="_")&&(t[s]=i[s])},uoA=(t,i,r)=>{const s=t.slots=RZ();if(t.vnode.shapeFlag&32){const g=i._;g?(GZ(s,i,r),r&&U8(s,"_",g,!0)):NZ(i,s)}else i&&TZ(t,i)},QoA=(t,i,r)=>{const{vnode:s,slots:g}=t;let B=!0,Q=qn;if(s.shapeFlag&32){const f=i._;f?r&&f===1?B=!1:GZ(g,i,r):(B=!i.$stable,NZ(i,g)),Q=i}else i&&(TZ(t,i),Q={default:1});if(B)for(const f in g)!vZ(f)&&Q[f]==null&&delete g[f]},fc=ToA;function doA(t){return hoA(t)}function hoA(t,i){const r=IY();r.__VUE__=!0;const{insert:s,remove:g,patchProp:B,createElement:Q,createText:f,createComment:m,setText:M,setElementText:v,parentNode:U,nextSibling:AA,setScopeId:z=Lu,insertStaticContent:sA}=t,eA=(MA,YA,pe,st=null,Te=null,be=null,yt=void 0,ht=null,ae=!!YA.dynamicChildren)=>{if(MA===YA)return;MA&&!Km(MA,YA)&&(st=Ni(MA),no(MA,Te,be,!0),MA=null),YA.patchFlag===-2&&(ae=!1,YA.dynamicChildren=null);const{type:ye,ref:Xe,shapeFlag:ot}=YA;switch(ye){case dY:X(MA,YA,pe,st);break;case yc:QA(MA,YA,pe,st);break;case yK:MA==null&&wA(YA,pe,st,yt);break;case Tn:Je(MA,YA,pe,st,Te,be,yt,ht,ae);break;default:ot&1?ue(MA,YA,pe,st,Te,be,yt,ht,ae):ot&6?$e(MA,YA,pe,st,Te,be,yt,ht,ae):(ot&64||ot&128)&&ye.process(MA,YA,pe,st,Te,be,yt,ht,ae,Di)}Xe!=null&&Te&&b2(Xe,MA&&MA.ref,be,YA||MA,!YA)},X=(MA,YA,pe,st)=>{if(MA==null)s(YA.el=f(YA.children),pe,st);else{const Te=YA.el=MA.el;YA.children!==MA.children&&M(Te,YA.children)}},QA=(MA,YA,pe,st)=>{MA==null?s(YA.el=m(YA.children||""),pe,st):YA.el=MA.el},wA=(MA,YA,pe,st)=>{[MA.el,MA.anchor]=sA(MA.children,YA,pe,st,MA.el,MA.anchor)},HA=({el:MA,anchor:YA},pe,st)=>{let Te;for(;MA&&MA!==YA;)Te=AA(MA),s(MA,pe,st),MA=Te;s(YA,pe,st)},VA=({el:MA,anchor:YA})=>{let pe;for(;MA&&MA!==YA;)pe=AA(MA),g(MA),MA=pe;g(YA)},ue=(MA,YA,pe,st,Te,be,yt,ht,ae)=>{YA.type==="svg"?yt="svg":YA.type==="math"&&(yt="mathml"),MA==null?jA(YA,pe,st,Te,be,yt,ht,ae):Me(MA,YA,Te,be,yt,ht,ae)},jA=(MA,YA,pe,st,Te,be,yt,ht)=>{let ae,ye;const{props:Xe,shapeFlag:ot,transition:zt,dirs:yi}=MA;if(ae=MA.el=Q(MA.type,be,Xe&&Xe.is,Xe),ot&8?v(ae,MA.children):ot&16&&Ze(MA.children,ae,null,st,Te,DK(MA,be),yt,ht),yi&&Om(MA,null,st,"created"),Ve(ae,MA,MA.scopeId,yt,st),Xe){for(const Ei in Xe)Ei!=="value"&&!FG(Ei)&&B(ae,Ei,null,Xe[Ei],be,st);"value"in Xe&&B(ae,"value",null,Xe.value,be),(ye=Xe.onVnodeBeforeMount)&&Su(ye,st,MA)}yi&&Om(MA,null,st,"beforeMount");const Hi=poA(Te,zt);Hi&&zt.beforeEnter(ae),s(ae,YA,pe),((ye=Xe&&Xe.onVnodeMounted)||Hi||yi)&&fc(()=>{ye&&Su(ye,st,MA),Hi&&zt.enter(ae),yi&&Om(MA,null,st,"mounted")},Te)},Ve=(MA,YA,pe,st,Te)=>{if(pe&&z(MA,pe),st)for(let be=0;be{for(let ye=ae;ye{const ht=YA.el=MA.el;let{patchFlag:ae,dynamicChildren:ye,dirs:Xe}=YA;ae|=MA.patchFlag&16;const ot=MA.props||qn,zt=YA.props||qn;let yi;if(pe&&xm(pe,!1),(yi=zt.onVnodeBeforeUpdate)&&Su(yi,pe,YA,MA),Xe&&Om(YA,MA,pe,"beforeUpdate"),pe&&xm(pe,!0),(ot.innerHTML&&zt.innerHTML==null||ot.textContent&&zt.textContent==null)&&v(ht,""),ye?qe(MA.dynamicChildren,ye,ht,pe,st,DK(YA,Te),be):yt||ai(MA,YA,ht,null,pe,st,DK(YA,Te),be,!1),ae>0){if(ae&16)Et(ht,ot,zt,pe,Te);else if(ae&2&&ot.class!==zt.class&&B(ht,"class",null,zt.class,Te),ae&4&&B(ht,"style",ot.style,zt.style,Te),ae&8){const Hi=YA.dynamicProps;for(let Ei=0;Ei{yi&&Su(yi,pe,YA,MA),Xe&&Om(YA,MA,pe,"updated")},st)},qe=(MA,YA,pe,st,Te,be,yt)=>{for(let ht=0;ht{if(YA!==pe){if(YA!==qn)for(const be in YA)!FG(be)&&!(be in pe)&&B(MA,be,YA[be],null,Te,st);for(const be in pe){if(FG(be))continue;const yt=pe[be],ht=YA[be];yt!==ht&&be!=="value"&&B(MA,be,ht,yt,Te,st)}"value"in pe&&B(MA,"value",YA.value,pe.value,Te)}},Je=(MA,YA,pe,st,Te,be,yt,ht,ae)=>{const ye=YA.el=MA?MA.el:f(""),Xe=YA.anchor=MA?MA.anchor:f("");let{patchFlag:ot,dynamicChildren:zt,slotScopeIds:yi}=YA;yi&&(ht=ht?ht.concat(yi):yi),MA==null?(s(ye,pe,st),s(Xe,pe,st),Ze(YA.children||[],pe,Xe,Te,be,yt,ht,ae)):ot>0&&ot&64&&zt&&MA.dynamicChildren?(qe(MA.dynamicChildren,zt,pe,Te,be,yt,ht),(YA.key!=null||Te&&YA===Te.subTree)&&E3(MA,YA,!0)):ai(MA,YA,pe,Xe,Te,be,yt,ht,ae)},$e=(MA,YA,pe,st,Te,be,yt,ht,ae)=>{YA.slotScopeIds=ht,MA==null?YA.shapeFlag&512?Te.ctx.activate(YA,pe,st,yt,ae):Dt(YA,pe,st,Te,be,yt,ae):Zi(MA,YA,ae)},Dt=(MA,YA,pe,st,Te,be,yt)=>{const ht=MA.component=FoA(MA,st,Te);if(BY(MA)&&(ht.ctx.renderer=Di),OoA(ht,!1,yt),ht.asyncDep){if(Te&&Te.registerDep(ht,bi,yt),!MA.el){const ae=ht.subTree=ze(yc);QA(null,ae,YA,pe)}}else bi(ht,MA,YA,pe,Te,be,yt)},Zi=(MA,YA,pe)=>{const st=YA.component=MA.component;if(voA(MA,YA,pe))if(st.asyncDep&&!st.asyncResolved){qt(st,YA,pe);return}else st.next=YA,st.update();else YA.el=MA.el,st.vnode=YA},bi=(MA,YA,pe,st,Te,be,yt)=>{const ht=()=>{if(MA.isMounted){let{next:ot,bu:zt,u:yi,parent:Hi,vnode:Ei}=MA;{const Nr=kZ(MA);if(Nr){ot&&(ot.el=Ei.el,qt(MA,ot,yt)),Nr.asyncDep.then(()=>{MA.isUnmounted||ht()});return}}let ji=ot,Xo;xm(MA,!1),ot?(ot.el=Ei.el,qt(MA,ot,yt)):ot=Ei,zt&&BK(zt),(Xo=ot.props&&ot.props.onVnodeBeforeUpdate)&&Su(Xo,Hi,ot,Ei),xm(MA,!0);const sr=Pz(MA),Lo=MA.subTree;MA.subTree=sr,eA(Lo,sr,U(Lo.el),Ni(Lo),MA,Te,be),ot.el=sr.el,ji===null&&NoA(MA,sr.el),yi&&fc(yi,Te),(Xo=ot.props&&ot.props.onVnodeUpdated)&&fc(()=>Su(Xo,Hi,ot,Ei),Te)}else{let ot;const{el:zt,props:yi}=YA,{bm:Hi,m:Ei,parent:ji,root:Xo,type:sr}=MA,Lo=dw(YA);xm(MA,!1),Hi&&BK(Hi),!Lo&&(ot=yi&&yi.onVnodeBeforeMount)&&Su(ot,ji,YA),xm(MA,!0);{Xo.ce&&Xo.ce._injectChildStyle(sr);const Nr=MA.subTree=Pz(MA);eA(null,Nr,pe,st,MA,Te,be),YA.el=Nr.el}if(Ei&&fc(Ei,Te),!Lo&&(ot=yi&&yi.onVnodeMounted)){const Nr=YA;fc(()=>Su(ot,ji,Nr),Te)}(YA.shapeFlag&256||ji&&dw(ji.vnode)&&ji.vnode.shapeFlag&256)&&MA.a&&fc(MA.a,Te),MA.isMounted=!0,YA=pe=st=null}};MA.scope.on();const ae=MA.effect=new P8(ht);MA.scope.off();const ye=MA.update=ae.run.bind(ae),Xe=MA.job=ae.runIfDirty.bind(ae);Xe.i=MA,Xe.id=MA.uid,ae.scheduler=()=>I3(Xe),xm(MA,!0),ye()},qt=(MA,YA,pe)=>{YA.component=MA;const st=MA.vnode.props;MA.vnode=YA,MA.next=null,loA(MA,YA.props,st,pe),QoA(MA,YA.children,pe),Mp(),Nz(MA),wp()},ai=(MA,YA,pe,st,Te,be,yt,ht,ae=!1)=>{const ye=MA&&MA.children,Xe=MA?MA.shapeFlag:0,ot=YA.children,{patchFlag:zt,shapeFlag:yi}=YA;if(zt>0){if(zt&128){Ur(ye,ot,pe,st,Te,be,yt,ht,ae);return}else if(zt&256){Ki(ye,ot,pe,st,Te,be,yt,ht,ae);return}}yi&8?(Xe&16&&lr(ye,Te,be),ot!==ye&&v(pe,ot)):Xe&16?yi&16?Ur(ye,ot,pe,st,Te,be,yt,ht,ae):lr(ye,Te,be,!0):(Xe&8&&v(pe,""),yi&16&&Ze(ot,pe,st,Te,be,yt,ht,ae))},Ki=(MA,YA,pe,st,Te,be,yt,ht,ae)=>{MA=MA||Cw,YA=YA||Cw;const ye=MA.length,Xe=YA.length,ot=Math.min(ye,Xe);let zt;for(zt=0;ztXe?lr(MA,Te,be,!0,!1,ot):Ze(YA,pe,st,Te,be,yt,ht,ae,ot)},Ur=(MA,YA,pe,st,Te,be,yt,ht,ae)=>{let ye=0;const Xe=YA.length;let ot=MA.length-1,zt=Xe-1;for(;ye<=ot&&ye<=zt;){const yi=MA[ye],Hi=YA[ye]=ae?gp(YA[ye]):Gu(YA[ye]);if(Km(yi,Hi))eA(yi,Hi,pe,null,Te,be,yt,ht,ae);else break;ye++}for(;ye<=ot&&ye<=zt;){const yi=MA[ot],Hi=YA[zt]=ae?gp(YA[zt]):Gu(YA[zt]);if(Km(yi,Hi))eA(yi,Hi,pe,null,Te,be,yt,ht,ae);else break;ot--,zt--}if(ye>ot){if(ye<=zt){const yi=zt+1,Hi=yizt)for(;ye<=ot;)no(MA[ye],Te,be,!0),ye++;else{const yi=ye,Hi=ye,Ei=new Map;for(ye=Hi;ye<=zt;ye++){const Kr=YA[ye]=ae?gp(YA[ye]):Gu(YA[ye]);Kr.key!=null&&Ei.set(Kr.key,ye)}let ji,Xo=0;const sr=zt-Hi+1;let Lo=!1,Nr=0;const Vo=new Array(sr);for(ye=0;ye=sr){no(Kr,Te,be,!0);continue}let Qn;if(Kr.key!=null)Qn=Ei.get(Kr.key);else for(ji=Hi;ji<=zt;ji++)if(Vo[ji-Hi]===0&&Km(Kr,YA[ji])){Qn=ji;break}Qn===void 0?no(Kr,Te,be,!0):(Vo[Qn-Hi]=ye+1,Qn>=Nr?Nr=Qn:Lo=!0,eA(Kr,YA[Qn],pe,null,Te,be,yt,ht,ae),Xo++)}const et=Lo?foA(Vo):Cw;for(ji=et.length-1,ye=sr-1;ye>=0;ye--){const Kr=Hi+ye,Qn=YA[Kr],ho=Kr+1{const{el:be,type:yt,transition:ht,children:ae,shapeFlag:ye}=MA;if(ye&6){Er(MA.component.subTree,YA,pe,st);return}if(ye&128){MA.suspense.move(YA,pe,st);return}if(ye&64){yt.move(MA,YA,pe,Di);return}if(yt===Tn){s(be,YA,pe);for(let ot=0;otht.enter(be),Te);else{const{leave:ot,delayLeave:zt,afterLeave:yi}=ht,Hi=()=>s(be,YA,pe),Ei=()=>{ot(be,()=>{Hi(),yi&&yi()})};zt?zt(be,Hi,Ei):Ei()}else s(be,YA,pe)},no=(MA,YA,pe,st=!1,Te=!1)=>{const{type:be,props:yt,ref:ht,children:ae,dynamicChildren:ye,shapeFlag:Xe,patchFlag:ot,dirs:zt,cacheIndex:yi}=MA;if(ot===-2&&(Te=!1),ht!=null&&b2(ht,null,pe,MA,!0),yi!=null&&(YA.renderCache[yi]=void 0),Xe&256){YA.ctx.deactivate(MA);return}const Hi=Xe&1&&zt,Ei=!dw(MA);let ji;if(Ei&&(ji=yt&&yt.onVnodeBeforeUnmount)&&Su(ji,YA,MA),Xe&6)yr(MA.component,pe,st);else{if(Xe&128){MA.suspense.unmount(pe,st);return}Hi&&Om(MA,null,YA,"beforeUnmount"),Xe&64?MA.type.remove(MA,YA,pe,Di,st):ye&&!ye.hasOnce&&(be!==Tn||ot>0&&ot&64)?lr(ye,YA,pe,!1,!0):(be===Tn&&ot&384||!Te&&Xe&16)&&lr(ae,YA,pe),st&&Kn(MA)}(Ei&&(ji=yt&&yt.onVnodeUnmounted)||Hi)&&fc(()=>{ji&&Su(ji,YA,MA),Hi&&Om(MA,null,YA,"unmounted")},pe)},Kn=MA=>{const{type:YA,el:pe,anchor:st,transition:Te}=MA;if(YA===Tn){Xi(pe,st);return}if(YA===yK){VA(MA);return}const be=()=>{g(pe),Te&&!Te.persisted&&Te.afterLeave&&Te.afterLeave()};if(MA.shapeFlag&1&&Te&&!Te.persisted){const{leave:yt,delayLeave:ht}=Te,ae=()=>yt(pe,be);ht?ht(MA.el,be,ae):ae()}else be()},Xi=(MA,YA)=>{let pe;for(;MA!==YA;)pe=AA(MA),g(MA),MA=pe;g(YA)},yr=(MA,YA,pe)=>{const{bum:st,scope:Te,job:be,subTree:yt,um:ht,m:ae,a:ye}=MA;Yz(ae),Yz(ye),st&&BK(st),Te.stop(),be&&(be.flags|=8,no(yt,MA,YA,pe)),ht&&fc(ht,YA),fc(()=>{MA.isUnmounted=!0},YA),YA&&YA.pendingBranch&&!YA.isUnmounted&&MA.asyncDep&&!MA.asyncResolved&&MA.suspenseId===YA.pendingId&&(YA.deps--,YA.deps===0&&YA.resolve())},lr=(MA,YA,pe,st=!1,Te=!1,be=0)=>{for(let yt=be;yt{if(MA.shapeFlag&6)return Ni(MA.component.subTree);if(MA.shapeFlag&128)return MA.suspense.next();const YA=AA(MA.anchor||MA.el),pe=YA&&YA[sZ];return pe?AA(pe):YA};let wt=!1;const Ji=(MA,YA,pe)=>{MA==null?YA._vnode&&no(YA._vnode,null,null,!0):eA(YA._vnode||null,MA,YA,null,null,null,pe),YA._vnode=MA,wt||(wt=!0,Nz(),nZ(),wt=!1)},Di={p:eA,um:no,m:Er,r:Kn,mt:Dt,mc:Ze,pc:ai,pbc:qe,n:Ni,o:t};return{render:Ji,hydrate:void 0,createApp:coA(Ji)}}function DK({type:t,props:i},r){return r==="svg"&&t==="foreignObject"||r==="mathml"&&t==="annotation-xml"&&i&&i.encoding&&i.encoding.includes("html")?void 0:r}function xm({effect:t,job:i},r){r?(t.flags|=32,i.flags|=4):(t.flags&=-33,i.flags&=-5)}function poA(t,i){return(!t||t&&!t.pendingBranch)&&i&&!i.persisted}function E3(t,i,r=!1){const s=t.children,g=i.children;if(Ro(s)&&Ro(g))for(let B=0;B>1,t[r[f]]0&&(i[s]=r[B-1]),r[B]=s)}}for(B=r.length,Q=r[B-1];B-- >0;)r[B]=Q,Q=i[Q];return r}function kZ(t){const i=t.subTree.component;if(i)return i.asyncDep&&!i.asyncResolved?i:kZ(i)}function Yz(t){if(t)for(let i=0;irI(moA);function Nw(t,i){return l3(t,null,i)}function Un(t,i,r){return l3(t,i,r)}function l3(t,i,r=qn){const{immediate:s,deep:g,flush:B,once:Q}=r,f=Sg({},r),m=i&&s||!i&&B!=="post";let M;if(ak){if(B==="sync"){const z=DoA();M=z.__watcherHandles||(z.__watcherHandles=[])}else if(!m){const z=()=>{};return z.stop=Lu,z.resume=Lu,z.pause=Lu,z}}const v=oI;f.call=(z,sA,eA)=>CB(z,v,sA,eA);let U=!1;B==="post"?f.scheduler=z=>{fc(z,v&&v.suspense)}:B!=="sync"&&(U=!0,f.scheduler=(z,sA)=>{sA?z():I3(z)}),f.augmentJob=z=>{i&&(z.flags|=4),U&&(z.flags|=2,v&&(z.id=v.uid,z.i=v))};const AA=biA(t,i,f);return ak&&(M?M.push(AA):m&&AA()),AA}function yoA(t,i,r){const s=this.proxy,g=va(t)?t.includes(".")?_Z(s,t):()=>s[t]:t.bind(s,s);let B;xo(i)?B=i:(B=i.handler,r=i);const Q=dk(this),f=l3(g,B.bind(s),r);return Q(),f}function _Z(t,i){const r=i.split(".");return()=>{let s=t;for(let g=0;gi==="modelValue"||i==="model-value"?t.modelModifiers:t[`${i}Modifiers`]||t[`${mC(i)}Modifiers`]||t[`${Rp(i)}Modifiers`];function MoA(t,i,...r){if(t.isUnmounted)return;const s=t.vnode.props||qn;let g=r;const B=i.startsWith("update:"),Q=B&&RoA(s,i.slice(7));Q&&(Q.trim&&(g=r.map(v=>va(v)?v.trim():v)),Q.number&&(g=r.map(WtA)));let f,m=s[f=CK(i)]||s[f=CK(mC(i))];!m&&B&&(m=s[f=CK(Rp(i))]),m&&CB(m,t,6,g);const M=s[f+"Once"];if(M){if(!t.emitted)t.emitted={};else if(t.emitted[f])return;t.emitted[f]=!0,CB(M,t,6,g)}}function bZ(t,i,r=!1){const s=i.emitsCache,g=s.get(t);if(g!==void 0)return g;const B=t.emits;let Q={},f=!1;if(!xo(t)){const m=M=>{const v=bZ(M,i,!0);v&&(f=!0,Sg(Q,v))};!r&&i.mixins.length&&i.mixins.forEach(m),t.extends&&m(t.extends),t.mixins&&t.mixins.forEach(m)}return!B&&!f?(ta(t)&&s.set(t,null),null):(Ro(B)?B.forEach(m=>Q[m]=null):Sg(Q,B),ta(t)&&s.set(t,Q),Q)}function QY(t,i){return!t||!nY(i)?!1:(i=i.slice(2).replace(/Once$/,""),yn(t,i[0].toLowerCase()+i.slice(1))||yn(t,Rp(i))||yn(t,i))}function Pz(t){const{type:i,vnode:r,proxy:s,withProxy:g,propsOptions:[B],slots:Q,attrs:f,emit:m,render:M,renderCache:v,props:U,data:AA,setupState:z,ctx:sA,inheritAttrs:eA}=t,X=_2(t);let QA,wA;try{if(r.shapeFlag&4){const VA=g||s,ue=VA;QA=Gu(M.call(ue,VA,v,U,z,AA,sA)),wA=f}else{const VA=i;QA=Gu(VA.length>1?VA(U,{attrs:f,slots:Q,emit:m}):VA(U,null)),wA=i.props?f:woA(f)}}catch(VA){PG.length=0,EY(VA,t,1),QA=ze(yc)}let HA=QA;if(wA&&eA!==!1){const VA=Object.keys(wA),{shapeFlag:ue}=HA;VA.length&&ue&7&&(B&&VA.some(A3)&&(wA=SoA(wA,B)),HA=hp(HA,wA,!1,!0))}return r.dirs&&(HA=hp(HA,null,!1,!0),HA.dirs=HA.dirs?HA.dirs.concat(r.dirs):r.dirs),r.transition&&ok(HA,r.transition),QA=HA,_2(X),QA}const woA=t=>{let i;for(const r in t)(r==="class"||r==="style"||nY(r))&&((i||(i={}))[r]=t[r]);return i},SoA=(t,i)=>{const r={};for(const s in t)(!A3(s)||!(s.slice(9)in i))&&(r[s]=t[s]);return r};function voA(t,i,r){const{props:s,children:g,component:B}=t,{props:Q,children:f,patchFlag:m}=i,M=B.emitsOptions;if(i.dirs||i.transition)return!0;if(r&&m>=0){if(m&1024)return!0;if(m&16)return s?Jz(s,Q,M):!!Q;if(m&8){const v=i.dynamicProps;for(let U=0;Ut.__isSuspense;function ToA(t,i){i&&i.pendingBranch?Ro(t)?i.effects.push(...t):i.effects.push(t):UiA(t)}const Tn=Symbol.for("v-fgt"),dY=Symbol.for("v-txt"),yc=Symbol.for("v-cmt"),yK=Symbol.for("v-stc"),PG=[];let Cl=null;function qA(t=!1){PG.push(Cl=t?null:[])}function GoA(){PG.pop(),Cl=PG[PG.length-1]||null}let rk=1;function Hz(t,i=!1){rk+=t,t<0&&Cl&&i&&(Cl.hasOnce=!0)}function FZ(t){return t.dynamicChildren=rk>0?Cl||Cw:null,GoA(),rk>0&&Cl&&Cl.push(t),t}function Ue(t,i,r,s,g,B){return FZ(ce(t,i,r,s,g,B,!0))}function _t(t,i,r,s,g){return FZ(ze(t,i,r,s,g,!0))}function nk(t){return t?t.__v_isVNode===!0:!1}function Km(t,i){return t.type===i.type&&t.key===i.key}const UZ=({key:t})=>t??null,u2=({ref:t,ref_key:i,ref_for:r})=>(typeof t=="number"&&(t=""+t),t!=null?va(t)||wg(t)||xo(t)?{i:Mg,r:t,k:i,f:!!r}:t:null);function ce(t,i=null,r=null,s=0,g=null,B=t===Tn?0:1,Q=!1,f=!1){const m={__v_isVNode:!0,__v_skip:!0,type:t,props:i,key:i&&UZ(i),ref:i&&u2(i),scopeId:CY,slotScopeIds:null,children:r,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:B,patchFlag:s,dynamicProps:g,dynamicChildren:null,appContext:null,ctx:Mg};return f?(C3(m,r),B&128&&t.normalize(m)):r&&(m.shapeFlag|=va(r)?8:16),rk>0&&!Q&&Cl&&(m.patchFlag>0||B&6)&&m.patchFlag!==32&&Cl.push(m),m}const ze=koA;function koA(t,i=null,r=null,s=0,g=null,B=!1){if((!t||t===toA)&&(t=yc),nk(t)){const f=hp(t,i,!0);return r&&C3(f,r),rk>0&&!B&&Cl&&(f.shapeFlag&6?Cl[Cl.indexOf(t)]=f:Cl.push(f)),f.patchFlag=-2,f}if(HoA(t)&&(t=t.__vccOpts),i){i=_oA(i);let{class:f,style:m}=i;f&&!va(f)&&(i.class=Qi(f)),ta(m)&&(g3(m)&&!Ro(m)&&(m=Sg({},m)),i.style=zr(m))}const Q=va(t)?1:LZ(t)?128:gZ(t)?64:ta(t)?4:xo(t)?2:0;return ce(t,i,r,s,g,Q,B,!0)}function _oA(t){return t?g3(t)||MZ(t)?Sg({},t):t:null}function hp(t,i,r=!1,s=!1){const{props:g,ref:B,patchFlag:Q,children:f,transition:m}=t,M=i?dj(g||{},i):g,v={__v_isVNode:!0,__v_skip:!0,type:t.type,props:M,key:M&&UZ(M),ref:i&&i.ref?r&&B?Ro(B)?B.concat(u2(i)):[B,u2(i)]:u2(i):B,scopeId:t.scopeId,slotScopeIds:t.slotScopeIds,children:f,target:t.target,targetStart:t.targetStart,targetAnchor:t.targetAnchor,staticCount:t.staticCount,shapeFlag:t.shapeFlag,patchFlag:i&&t.type!==Tn?Q===-1?16:Q|16:Q,dynamicProps:t.dynamicProps,dynamicChildren:t.dynamicChildren,appContext:t.appContext,dirs:t.dirs,transition:m,component:t.component,suspense:t.suspense,ssContent:t.ssContent&&hp(t.ssContent),ssFallback:t.ssFallback&&hp(t.ssFallback),el:t.el,anchor:t.anchor,ctx:t.ctx,ce:t.ce};return m&&s&&ok(v,m.clone(v)),v}function Na(t=" ",i=0){return ze(dY,null,t,i)}function Tt(t="",i=!1){return i?(qA(),_t(yc,null,t)):ze(yc,null,t)}function Gu(t){return t==null||typeof t=="boolean"?ze(yc):Ro(t)?ze(Tn,null,t.slice()):nk(t)?gp(t):ze(dY,null,String(t))}function gp(t){return t.el===null&&t.patchFlag!==-1||t.memo?t:hp(t)}function C3(t,i){let r=0;const{shapeFlag:s}=t;if(i==null)i=null;else if(Ro(i))r=16;else if(typeof i=="object")if(s&65){const g=i.default;g&&(g._c&&(g._d=!1),C3(t,g()),g._c&&(g._d=!0));return}else{r=32;const g=i._;!g&&!MZ(i)?i._ctx=Mg:g===3&&Mg&&(Mg.slots._===1?i._=1:(i._=2,t.patchFlag|=1024))}else xo(i)?(i={default:i,_ctx:Mg},r=32):(i=String(i),s&64?(r=16,i=[Na(i)]):r=8);t.children=i,t.shapeFlag|=r}function dj(...t){const i={};for(let r=0;roI||Mg;let F2,hj;{const t=IY(),i=(r,s)=>{let g;return(g=t[r])||(g=t[r]=[]),g.push(s),B=>{g.length>1?g.forEach(Q=>Q(B)):g[0](B)}};F2=i("__VUE_INSTANCE_SETTERS__",r=>oI=r),hj=i("__VUE_SSR_SETTERS__",r=>ak=r)}const dk=t=>{const i=oI;return F2(t),t.scope.on(),()=>{t.scope.off(),F2(i)}},Vz=()=>{oI&&oI.scope.off(),F2(null)};function OZ(t){return t.vnode.shapeFlag&4}let ak=!1;function OoA(t,i=!1,r=!1){i&&hj(i);const{props:s,children:g}=t.vnode,B=OZ(t);EoA(t,s,B,i),uoA(t,g,r);const Q=B?xoA(t,i):void 0;return i&&hj(!1),Q}function xoA(t,i){const r=t.type;t.accessCache=Object.create(null),t.proxy=new Proxy(t.ctx,ooA);const{setup:s}=r;if(s){Mp();const g=t.setupContext=s.length>1?PoA(t):null,B=dk(t),Q=Qk(s,t,0,[t.props,g]),f=b8(Q);if(wp(),B(),(f||t.sp)&&!dw(t)&&QZ(t),f){if(Q.then(Vz,Vz),i)return Q.then(m=>{qz(t,m)}).catch(m=>{EY(m,t,0)});t.asyncDep=Q}else qz(t,Q)}else xZ(t)}function qz(t,i,r){xo(i)?t.type.__ssrInlineRender?t.ssrRender=i:t.render=i:ta(i)&&(t.setupState=tZ(i)),xZ(t)}function xZ(t,i,r){const s=t.type;t.render||(t.render=s.render||Lu);{const g=dk(t);Mp();try{roA(t)}finally{wp(),g()}}}const YoA={get(t,i){return GI(t,"get",""),t[i]}};function PoA(t){const i=r=>{t.exposed=r||{}};return{attrs:new Proxy(t.attrs,YoA),slots:t.slots,emit:t.emit,expose:i}}function hY(t){return t.exposed?t.exposeProxy||(t.exposeProxy=new Proxy(tZ(MiA(t.exposed)),{get(i,r){if(r in i)return i[r];if(r in YG)return YG[r](t)},has(i,r){return r in i||r in YG}})):t.proxy}function JoA(t,i=!0){return xo(t)?t.displayName||t.name:t.name||i&&t.__name}function HoA(t){return xo(t)&&"__vccOpts"in t}const rt=(t,i)=>kiA(t,i,ak);function VoA(t,i,r){const s=arguments.length;return s===2?ta(i)&&!Ro(i)?nk(i)?ze(t,null,[i]):ze(t,i):ze(t,null,i):(s>3?r=Array.prototype.slice.call(arguments,2):s===3&&nk(r)&&(r=[r]),ze(t,i,r))}const pj="3.5.13";/** +**/function Dk(t,i,r,s){try{return s?t(...s):t()}catch(g){hY(g,i,r)}}function uB(t,i,r,s){if(xo(t)){const g=Dk(t,i,r,s);return g&&P8(g)&&g.catch(B=>{hY(B,i,r)}),g}if(Ro(t)){const g=[];for(let B=0;B>>1,g=Dc[s],B=gk(g);B=gk(r)?Dc.push(t):Dc.splice(ziA(i),0,t),t.flags|=1,EZ()}}function EZ(){O2||(O2=cZ.then(CZ))}function ZiA(t){Ro(t)?pw.push(...t):Ip&&t.id===-1?Ip.splice(ew+1,0,t):t.flags&1||(pw.push(t),t.flags|=1),EZ()}function Fz(t,i,r=Gu+1){for(;rgk(r)-gk(s));if(pw.length=0,Ip){Ip.push(...i);return}for(Ip=i,ew=0;ewt.id==null?t.flags&2?-1:1/0:t.id;function CZ(t){try{for(Gu=0;Gu{s._d&&Zz(-1);const B=x2(i);let Q;try{Q=t(...g)}finally{x2(B),s._d&&Zz(1)}return Q};return s._n=!0,s._c=!0,s._d=!0,s}function aa(t,i){if(Mg===null)return t;const r=RY(Mg),s=t.dirs||(t.dirs=[]);for(let g=0;gt.__isTeleport,VG=t=>t&&(t.disabled||t.disabled===""),Uz=t=>t&&(t.defer||t.defer===""),Oz=t=>typeof SVGElement<"u"&&t instanceof SVGElement,xz=t=>typeof MathMLElement=="function"&&t instanceof MathMLElement,dj=(t,i)=>{const r=t&&t.to;return va(r)?i?i(r):null:r},QZ={name:"Teleport",__isTeleport:!0,process(t,i,r,s,g,B,Q,f,m,M){const{mc:v,pc:U,pbc:AA,o:{insert:z,querySelector:sA,createText:eA,createComment:X}}=M,QA=VG(i.props);let{shapeFlag:wA,children:HA,dynamicChildren:qA}=i;if(t==null){const ue=i.el=eA(""),jA=i.anchor=eA("");z(ue,r,s),z(jA,r,s);const Ve=(Me,qe)=>{wA&16&&(g&&g.isCE&&(g.ce._teleportTarget=Me),v(HA,Me,qe,g,B,Q,f,m))},ze=()=>{const Me=i.target=dj(i.props,sA),qe=dZ(Me,i,eA,z);Me&&(Q!=="svg"&&Oz(Me)?Q="svg":Q!=="mathml"&&xz(Me)&&(Q="mathml"),QA||(Ve(Me,qe),m2(i,!1)))};QA&&(Ve(r,jA),m2(i,!0)),Uz(i.props)?fc(()=>{ze(),i.el.__isMounted=!0},B):ze()}else{if(Uz(i.props)&&!t.el.__isMounted){fc(()=>{QZ.process(t,i,r,s,g,B,Q,f,m,M),delete t.el.__isMounted},B);return}i.el=t.el,i.targetStart=t.targetStart;const ue=i.anchor=t.anchor,jA=i.target=t.target,Ve=i.targetAnchor=t.targetAnchor,ze=VG(t.props),Me=ze?r:jA,qe=ze?ue:Ve;if(Q==="svg"||Oz(jA)?Q="svg":(Q==="mathml"||xz(jA))&&(Q="mathml"),qA?(AA(t.dynamicChildren,qA,Me,g,B,Q,f),d3(t,i,!0)):m||U(t,i,Me,qe,g,B,Q,f,!1),QA)ze?i.props&&t.props&&i.props.to!==t.props.to&&(i.props.to=t.props.to):r2(i,r,ue,M,1);else if((i.props&&i.props.to)!==(t.props&&t.props.to)){const Et=i.target=dj(i.props,sA);Et&&r2(i,Et,null,M,0)}else ze&&r2(i,jA,Ve,M,1);m2(i,QA)}},remove(t,i,r,{um:s,o:{remove:g}},B){const{shapeFlag:Q,children:f,anchor:m,targetStart:M,targetAnchor:v,target:U,props:AA}=t;if(U&&(g(M),g(v)),B&&g(m),Q&16){const z=B||!VG(AA);for(let sA=0;sA{t.isMounted=!0}),MZ(()=>{t.isUnmounting=!0}),t}const sC=[Function,Array],hZ={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:sC,onEnter:sC,onAfterEnter:sC,onEnterCancelled:sC,onBeforeLeave:sC,onLeave:sC,onAfterLeave:sC,onLeaveCancelled:sC,onBeforeAppear:sC,onAppear:sC,onAfterAppear:sC,onAppearCancelled:sC},pZ=t=>{const i=t.subTree;return i.component?pZ(i.component):i},eoA={name:"BaseTransition",props:hZ,setup(t,{slots:i}){const r=ZoA(),s=AoA();return()=>{const g=i.default&&DZ(i.default(),!0);if(!g||!g.length)return;const B=fZ(g),Q=an(t),{mode:f}=Q;if(s.isLeaving)return wK(B);const m=Yz(B);if(!m)return wK(B);let M=hj(m,Q,s,r,U=>M=U);m.type!==yc&&Ik(m,M);let v=r.subTree&&Yz(r.subTree);if(v&&v.type!==yc&&!Zm(m,v)&&pZ(r).type!==yc){let U=hj(v,Q,s,r);if(Ik(v,U),f==="out-in"&&m.type!==yc)return s.isLeaving=!0,U.afterLeave=()=>{s.isLeaving=!1,r.job.flags&8||r.update(),delete U.afterLeave,v=void 0},wK(B);f==="in-out"&&m.type!==yc?U.delayLeave=(AA,z,sA)=>{const eA=mZ(s,v);eA[String(v.key)]=v,AA[cp]=()=>{z(),AA[cp]=void 0,delete M.delayedLeave,v=void 0},M.delayedLeave=()=>{sA(),delete M.delayedLeave,v=void 0}}:v=void 0}else v&&(v=void 0);return B}}};function fZ(t){let i=t[0];if(t.length>1){for(const r of t)if(r.type!==yc){i=r;break}}return i}const toA=eoA;function mZ(t,i){const{leavingVNodes:r}=t;let s=r.get(i.type);return s||(s=Object.create(null),r.set(i.type,s)),s}function hj(t,i,r,s,g){const{appear:B,mode:Q,persisted:f=!1,onBeforeEnter:m,onEnter:M,onAfterEnter:v,onEnterCancelled:U,onBeforeLeave:AA,onLeave:z,onAfterLeave:sA,onLeaveCancelled:eA,onBeforeAppear:X,onAppear:QA,onAfterAppear:wA,onAppearCancelled:HA}=i,qA=String(t.key),ue=mZ(r,t),jA=(Me,qe)=>{Me&&uB(Me,s,9,qe)},Ve=(Me,qe)=>{const Et=qe[1];jA(Me,qe),Ro(Me)?Me.every(Je=>Je.length<=1)&&Et():Me.length<=1&&Et()},ze={mode:Q,persisted:f,beforeEnter(Me){let qe=m;if(!r.isMounted)if(B)qe=X||m;else return;Me[cp]&&Me[cp](!0);const Et=ue[qA];Et&&Zm(t,Et)&&Et.el[cp]&&Et.el[cp](),jA(qe,[Me])},enter(Me){let qe=M,Et=v,Je=U;if(!r.isMounted)if(B)qe=QA||M,Et=wA||v,Je=HA||U;else return;let $e=!1;const Dt=Me[n2]=Zi=>{$e||($e=!0,Zi?jA(Je,[Me]):jA(Et,[Me]),ze.delayedLeave&&ze.delayedLeave(),Me[n2]=void 0)};qe?Ve(qe,[Me,Dt]):Dt()},leave(Me,qe){const Et=String(t.key);if(Me[n2]&&Me[n2](!0),r.isUnmounting)return qe();jA(AA,[Me]);let Je=!1;const $e=Me[cp]=Dt=>{Je||(Je=!0,qe(),Dt?jA(eA,[Me]):jA(sA,[Me]),Me[cp]=void 0,ue[Et]===t&&delete ue[Et])};ue[Et]=t,z?Ve(z,[Me,$e]):$e()},clone(Me){const qe=hj(Me,i,r,s,g);return g&&g(qe),qe}};return ze}function wK(t){if(fY(t))return t=Dp(t),t.children=null,t}function Yz(t){if(!fY(t))return uZ(t.type)&&t.children?fZ(t.children):t;const{shapeFlag:i,children:r}=t;if(r){if(i&16)return r[0];if(i&32&&xo(r.default))return r.default()}}function Ik(t,i){t.shapeFlag&6&&t.component?(t.transition=i,Ik(t.component.subTree,i)):t.shapeFlag&128?(t.ssContent.transition=i.clone(t.ssContent),t.ssFallback.transition=i.clone(t.ssFallback)):t.transition=i}function DZ(t,i=!1,r){let s=[],g=0;for(let B=0;B1)for(let B=0;BY2(sA,i&&(Ro(i)?i[eA]:i),r,s,g));return}if(fw(s)&&!g){s.shapeFlag&512&&s.type.__asyncResolved&&s.component.subTree.component&&Y2(t,i,r,s.component.subTree);return}const B=s.shapeFlag&4?RY(s.component):s.el,Q=g?null:B,{i:f,r:m}=t,M=i&&i.r,v=f.refs===qn?f.refs={}:f.refs,U=f.setupState,AA=an(U),z=U===qn?()=>!1:sA=>yn(AA,sA);if(M!=null&&M!==m&&(va(M)?(v[M]=null,z(M)&&(U[M]=null)):wg(M)&&(M.value=null)),xo(m))Dk(m,f,12,[Q,v]);else{const sA=va(m),eA=wg(m);if(sA||eA){const X=()=>{if(t.f){const QA=sA?z(m)?U[m]:v[m]:m.value;g?Ro(QA)&&a3(QA,B):Ro(QA)?QA.includes(B)||QA.push(B):sA?(v[m]=[B],z(m)&&(U[m]=v[m])):(m.value=[B],t.k&&(v[t.k]=m.value))}else sA?(v[m]=Q,z(m)&&(U[m]=Q)):eA&&(m.value=Q,t.k&&(v[t.k]=Q))};Q?(X.id=-1,fc(X,r)):X()}}}QY().requestIdleCallback;QY().cancelIdleCallback;const fw=t=>!!t.type.__asyncLoader,fY=t=>t.type.__isKeepAlive;function ioA(t,i){RZ(t,"a",i)}function ooA(t,i){RZ(t,"da",i)}function RZ(t,i,r=oI){const s=t.__wdc||(t.__wdc=()=>{let g=r;for(;g;){if(g.isDeactivated)return;g=g.parent}return t()});if(mY(i,s,r),r){let g=r.parent;for(;g&&g.parent;)fY(g.parent.vnode)&&roA(s,i,r,g),g=g.parent}}function roA(t,i,r,s){const g=mY(i,t,s,!0);Ya(()=>{a3(s[i],g)},r)}function mY(t,i,r=oI,s=!1){if(r){const g=r[t]||(r[t]=[]),B=i.__weh||(i.__weh=(...Q)=>{Np();const f=Rk(r),m=uB(i,r,t,Q);return f(),Tp(),m});return s?g.unshift(B):g.push(B),B}}const Ed=t=>(i,r=oI)=>{(!lk||t==="sp")&&mY(t,(...s)=>i(...s),r)},noA=Ed("bm"),gs=Ed("m"),aoA=Ed("bu"),soA=Ed("u"),MZ=Ed("bum"),Ya=Ed("um"),goA=Ed("sp"),IoA=Ed("rtg"),coA=Ed("rtc");function EoA(t,i=oI){mY("ec",t,i)}const loA="components";function CoA(t,i){return uoA(loA,t,!0,i)||t}const BoA=Symbol.for("v-ndc");function uoA(t,i,r=!0,s=!1){const g=Mg||oI;if(g){const B=g.type;{const f=trA(B,!1);if(f&&(f===i||f===mC(i)||f===uY(mC(i))))return B}const Q=Pz(g[t]||B[t],i)||Pz(g.appContext[t],i);return!Q&&s?B:Q}}function Pz(t,i){return t&&(t[i]||t[mC(i)]||t[uY(mC(i))])}function DC(t,i,r,s){let g;const B=r,Q=Ro(t);if(Q||va(t)){const f=Q&&hw(t);let m=!1;f&&(m=!hC(t),t=dY(t)),g=new Array(t.length);for(let M=0,v=t.length;Mi(f,m,void 0,B));else{const f=Object.keys(t);g=new Array(f.length);for(let m=0,M=f.length;mEk(i)?!(i.type===yc||i.type===Tn&&!wZ(i.children)):!0)?t:null}const pj=t=>t?qZ(t)?RY(t):pj(t.parent):null,qG=Sg(Object.create(null),{$:t=>t,$el:t=>t.vnode.el,$data:t=>t.data,$props:t=>t.props,$attrs:t=>t.attrs,$slots:t=>t.slots,$refs:t=>t.refs,$parent:t=>pj(t.parent),$root:t=>pj(t.root),$host:t=>t.ce,$emit:t=>t.emit,$options:t=>vZ(t),$forceUpdate:t=>t.f||(t.f=()=>{u3(t.update)}),$nextTick:t=>t.n||(t.n=yk.bind(t.proxy)),$watch:t=>FoA.bind(t)}),SK=(t,i)=>t!==qn&&!t.__isScriptSetup&&yn(t,i),QoA={get({_:t},i){if(i==="__v_skip")return!0;const{ctx:r,setupState:s,data:g,props:B,accessCache:Q,type:f,appContext:m}=t;let M;if(i[0]!=="$"){const z=Q[i];if(z!==void 0)switch(z){case 1:return s[i];case 2:return g[i];case 4:return r[i];case 3:return B[i]}else{if(SK(s,i))return Q[i]=1,s[i];if(g!==qn&&yn(g,i))return Q[i]=2,g[i];if((M=t.propsOptions[0])&&yn(M,i))return Q[i]=3,B[i];if(r!==qn&&yn(r,i))return Q[i]=4,r[i];fj&&(Q[i]=0)}}const v=qG[i];let U,AA;if(v)return i==="$attrs"&&GI(t.attrs,"get",""),v(t);if((U=f.__cssModules)&&(U=U[i]))return U;if(r!==qn&&yn(r,i))return Q[i]=4,r[i];if(AA=m.config.globalProperties,yn(AA,i))return AA[i]},set({_:t},i,r){const{data:s,setupState:g,ctx:B}=t;return SK(g,i)?(g[i]=r,!0):s!==qn&&yn(s,i)?(s[i]=r,!0):yn(t.props,i)||i[0]==="$"&&i.slice(1)in t?!1:(B[i]=r,!0)},has({_:{data:t,setupState:i,accessCache:r,ctx:s,appContext:g,propsOptions:B}},Q){let f;return!!r[Q]||t!==qn&&yn(t,Q)||SK(i,Q)||(f=B[0])&&yn(f,Q)||yn(s,Q)||yn(qG,Q)||yn(g.config.globalProperties,Q)},defineProperty(t,i,r){return r.get!=null?t._.accessCache[i]=0:yn(r,"value")&&this.set(t,i,r.value,null),Reflect.defineProperty(t,i,r)}};function Jz(t){return Ro(t)?t.reduce((i,r)=>(i[r]=null,i),{}):t}let fj=!0;function doA(t){const i=vZ(t),r=t.proxy,s=t.ctx;fj=!1,i.beforeCreate&&Hz(i.beforeCreate,t,"bc");const{data:g,computed:B,methods:Q,watch:f,provide:m,inject:M,created:v,beforeMount:U,mounted:AA,beforeUpdate:z,updated:sA,activated:eA,deactivated:X,beforeDestroy:QA,beforeUnmount:wA,destroyed:HA,unmounted:qA,render:ue,renderTracked:jA,renderTriggered:Ve,errorCaptured:ze,serverPrefetch:Me,expose:qe,inheritAttrs:Et,components:Je,directives:$e,filters:Dt}=i;if(M&&hoA(M,s,null),Q)for(const qt in Q){const ai=Q[qt];xo(ai)&&(s[qt]=ai.bind(r))}if(g){const qt=g.call(r,r);ta(qt)&&(t.data=tD(qt))}if(fj=!0,B)for(const qt in B){const ai=B[qt],Ki=xo(ai)?ai.bind(r,r):xo(ai.get)?ai.get.bind(r,r):Ou,Ur=!xo(ai)&&xo(ai.set)?ai.set.bind(r):Ou,Er=rt({get:Ki,set:Ur});Object.defineProperty(s,qt,{enumerable:!0,configurable:!0,get:()=>Er.value,set:no=>Er.value=no})}if(f)for(const qt in f)SZ(f[qt],s,r,qt);if(m){const qt=xo(m)?m.call(r):m;Reflect.ownKeys(qt).forEach(ai=>{gE(ai,qt[ai])})}v&&Hz(v,t,"c");function bi(qt,ai){Ro(ai)?ai.forEach(Ki=>qt(Ki.bind(r))):ai&&qt(ai.bind(r))}if(bi(noA,U),bi(gs,AA),bi(aoA,z),bi(soA,sA),bi(ioA,eA),bi(ooA,X),bi(EoA,ze),bi(coA,jA),bi(IoA,Ve),bi(MZ,wA),bi(Ya,qA),bi(goA,Me),Ro(qe))if(qe.length){const qt=t.exposed||(t.exposed={});qe.forEach(ai=>{Object.defineProperty(qt,ai,{get:()=>r[ai],set:Ki=>r[ai]=Ki})})}else t.exposed||(t.exposed={});ue&&t.render===Ou&&(t.render=ue),Et!=null&&(t.inheritAttrs=Et),Je&&(t.components=Je),$e&&(t.directives=$e),Me&&yZ(t)}function hoA(t,i,r=Ou){Ro(t)&&(t=mj(t));for(const s in t){const g=t[s];let B;ta(g)?"default"in g?B=rI(g.from||s,g.default,!0):B=rI(g.from||s):B=rI(g),wg(B)?Object.defineProperty(i,s,{enumerable:!0,configurable:!0,get:()=>B.value,set:Q=>B.value=Q}):i[s]=B}}function Hz(t,i,r){uB(Ro(t)?t.map(s=>s.bind(i.proxy)):t.bind(i.proxy),i,r)}function SZ(t,i,r,s){let g=s.includes(".")?YZ(r,s):()=>r[s];if(va(t)){const B=i[t];xo(B)&&Un(g,B)}else if(xo(t))Un(g,t.bind(r));else if(ta(t))if(Ro(t))t.forEach(B=>SZ(B,i,r,s));else{const B=xo(t.handler)?t.handler.bind(r):i[t.handler];xo(B)&&Un(g,B,t)}}function vZ(t){const i=t.type,{mixins:r,extends:s}=i,{mixins:g,optionsCache:B,config:{optionMergeStrategies:Q}}=t.appContext,f=B.get(i);let m;return f?m=f:!g.length&&!r&&!s?m=i:(m={},g.length&&g.forEach(M=>P2(m,M,Q,!0)),P2(m,i,Q)),ta(i)&&B.set(i,m),m}function P2(t,i,r,s=!1){const{mixins:g,extends:B}=i;B&&P2(t,B,r,!0),g&&g.forEach(Q=>P2(t,Q,r,!0));for(const Q in i)if(!(s&&Q==="expose")){const f=poA[Q]||r&&r[Q];t[Q]=f?f(t[Q],i[Q]):i[Q]}return t}const poA={data:Vz,props:qz,emits:qz,methods:DG,computed:DG,beforeCreate:dc,created:dc,beforeMount:dc,mounted:dc,beforeUpdate:dc,updated:dc,beforeDestroy:dc,beforeUnmount:dc,destroyed:dc,unmounted:dc,activated:dc,deactivated:dc,errorCaptured:dc,serverPrefetch:dc,components:DG,directives:DG,watch:moA,provide:Vz,inject:foA};function Vz(t,i){return i?t?function(){return Sg(xo(t)?t.call(this,this):t,xo(i)?i.call(this,this):i)}:i:t}function foA(t,i){return DG(mj(t),mj(i))}function mj(t){if(Ro(t)){const i={};for(let r=0;r1)return r&&xo(i)?i.call(s&&s.proxy):i}}const TZ={},GZ=()=>Object.create(TZ),kZ=t=>Object.getPrototypeOf(t)===TZ;function RoA(t,i,r,s=!1){const g={},B=GZ();t.propsDefaults=Object.create(null),_Z(t,i,g,B);for(const Q in t.propsOptions[0])Q in g||(g[Q]=void 0);r?t.props=s?g:UiA(g):t.type.props?t.props=g:t.props=B,t.attrs=B}function MoA(t,i,r,s){const{props:g,attrs:B,vnode:{patchFlag:Q}}=t,f=an(g),[m]=t.propsOptions;let M=!1;if((s||Q>0)&&!(Q&16)){if(Q&8){const v=t.vnode.dynamicProps;for(let U=0;U{m=!0;const[AA,z]=bZ(U,i,!0);Sg(Q,AA),z&&f.push(...z)};!r&&i.mixins.length&&i.mixins.forEach(v),t.extends&&v(t.extends),t.mixins&&t.mixins.forEach(v)}if(!B&&!m)return ta(t)&&s.set(t,Qw),Qw;if(Ro(B))for(let v=0;vt[0]==="_"||t==="$stable",Q3=t=>Ro(t)?t.map(bu):[bu(t)],SoA=(t,i,r)=>{if(i._n)return i;const s=Vt((...g)=>Q3(i(...g)),r);return s._c=!1,s},FZ=(t,i,r)=>{const s=t._ctx;for(const g in t){if(LZ(g))continue;const B=t[g];if(xo(B))i[g]=SoA(g,B,s);else if(B!=null){const Q=Q3(B);i[g]=()=>Q}}},UZ=(t,i)=>{const r=Q3(i);t.slots.default=()=>r},OZ=(t,i,r)=>{for(const s in i)(r||s!=="_")&&(t[s]=i[s])},voA=(t,i,r)=>{const s=t.slots=GZ();if(t.vnode.shapeFlag&32){const g=i._;g?(OZ(s,i,r),r&&V8(s,"_",g,!0)):FZ(i,s)}else i&&UZ(t,i)},NoA=(t,i,r)=>{const{vnode:s,slots:g}=t;let B=!0,Q=qn;if(s.shapeFlag&32){const f=i._;f?r&&f===1?B=!1:OZ(g,i,r):(B=!i.$stable,FZ(i,g)),Q=i}else i&&(UZ(t,i),Q={default:1});if(B)for(const f in g)!LZ(f)&&Q[f]==null&&delete g[f]},fc=HoA;function ToA(t){return GoA(t)}function GoA(t,i){const r=QY();r.__VUE__=!0;const{insert:s,remove:g,patchProp:B,createElement:Q,createText:f,createComment:m,setText:M,setElementText:v,parentNode:U,nextSibling:AA,setScopeId:z=Ou,insertStaticContent:sA}=t,eA=(MA,YA,pe,st=null,Te=null,be=null,yt=void 0,ht=null,ae=!!YA.dynamicChildren)=>{if(MA===YA)return;MA&&!Zm(MA,YA)&&(st=Ni(MA),no(MA,Te,be,!0),MA=null),YA.patchFlag===-2&&(ae=!1,YA.dynamicChildren=null);const{type:ye,ref:Xe,shapeFlag:ot}=YA;switch(ye){case yY:X(MA,YA,pe,st);break;case yc:QA(MA,YA,pe,st);break;case NK:MA==null&&wA(YA,pe,st,yt);break;case Tn:Je(MA,YA,pe,st,Te,be,yt,ht,ae);break;default:ot&1?ue(MA,YA,pe,st,Te,be,yt,ht,ae):ot&6?$e(MA,YA,pe,st,Te,be,yt,ht,ae):(ot&64||ot&128)&&ye.process(MA,YA,pe,st,Te,be,yt,ht,ae,Di)}Xe!=null&&Te&&Y2(Xe,MA&&MA.ref,be,YA||MA,!YA)},X=(MA,YA,pe,st)=>{if(MA==null)s(YA.el=f(YA.children),pe,st);else{const Te=YA.el=MA.el;YA.children!==MA.children&&M(Te,YA.children)}},QA=(MA,YA,pe,st)=>{MA==null?s(YA.el=m(YA.children||""),pe,st):YA.el=MA.el},wA=(MA,YA,pe,st)=>{[MA.el,MA.anchor]=sA(MA.children,YA,pe,st,MA.el,MA.anchor)},HA=({el:MA,anchor:YA},pe,st)=>{let Te;for(;MA&&MA!==YA;)Te=AA(MA),s(MA,pe,st),MA=Te;s(YA,pe,st)},qA=({el:MA,anchor:YA})=>{let pe;for(;MA&&MA!==YA;)pe=AA(MA),g(MA),MA=pe;g(YA)},ue=(MA,YA,pe,st,Te,be,yt,ht,ae)=>{YA.type==="svg"?yt="svg":YA.type==="math"&&(yt="mathml"),MA==null?jA(YA,pe,st,Te,be,yt,ht,ae):Me(MA,YA,Te,be,yt,ht,ae)},jA=(MA,YA,pe,st,Te,be,yt,ht)=>{let ae,ye;const{props:Xe,shapeFlag:ot,transition:zt,dirs:yi}=MA;if(ae=MA.el=Q(MA.type,be,Xe&&Xe.is,Xe),ot&8?v(ae,MA.children):ot&16&&ze(MA.children,ae,null,st,Te,vK(MA,be),yt,ht),yi&&Jm(MA,null,st,"created"),Ve(ae,MA,MA.scopeId,yt,st),Xe){for(const Ei in Xe)Ei!=="value"&&!YG(Ei)&&B(ae,Ei,null,Xe[Ei],be,st);"value"in Xe&&B(ae,"value",null,Xe.value,be),(ye=Xe.onVnodeBeforeMount)&&Tu(ye,st,MA)}yi&&Jm(MA,null,st,"beforeMount");const Hi=koA(Te,zt);Hi&&zt.beforeEnter(ae),s(ae,YA,pe),((ye=Xe&&Xe.onVnodeMounted)||Hi||yi)&&fc(()=>{ye&&Tu(ye,st,MA),Hi&&zt.enter(ae),yi&&Jm(MA,null,st,"mounted")},Te)},Ve=(MA,YA,pe,st,Te)=>{if(pe&&z(MA,pe),st)for(let be=0;be{for(let ye=ae;ye{const ht=YA.el=MA.el;let{patchFlag:ae,dynamicChildren:ye,dirs:Xe}=YA;ae|=MA.patchFlag&16;const ot=MA.props||qn,zt=YA.props||qn;let yi;if(pe&&Hm(pe,!1),(yi=zt.onVnodeBeforeUpdate)&&Tu(yi,pe,YA,MA),Xe&&Jm(YA,MA,pe,"beforeUpdate"),pe&&Hm(pe,!0),(ot.innerHTML&&zt.innerHTML==null||ot.textContent&&zt.textContent==null)&&v(ht,""),ye?qe(MA.dynamicChildren,ye,ht,pe,st,vK(YA,Te),be):yt||ai(MA,YA,ht,null,pe,st,vK(YA,Te),be,!1),ae>0){if(ae&16)Et(ht,ot,zt,pe,Te);else if(ae&2&&ot.class!==zt.class&&B(ht,"class",null,zt.class,Te),ae&4&&B(ht,"style",ot.style,zt.style,Te),ae&8){const Hi=YA.dynamicProps;for(let Ei=0;Ei{yi&&Tu(yi,pe,YA,MA),Xe&&Jm(YA,MA,pe,"updated")},st)},qe=(MA,YA,pe,st,Te,be,yt)=>{for(let ht=0;ht{if(YA!==pe){if(YA!==qn)for(const be in YA)!YG(be)&&!(be in pe)&&B(MA,be,YA[be],null,Te,st);for(const be in pe){if(YG(be))continue;const yt=pe[be],ht=YA[be];yt!==ht&&be!=="value"&&B(MA,be,ht,yt,Te,st)}"value"in pe&&B(MA,"value",YA.value,pe.value,Te)}},Je=(MA,YA,pe,st,Te,be,yt,ht,ae)=>{const ye=YA.el=MA?MA.el:f(""),Xe=YA.anchor=MA?MA.anchor:f("");let{patchFlag:ot,dynamicChildren:zt,slotScopeIds:yi}=YA;yi&&(ht=ht?ht.concat(yi):yi),MA==null?(s(ye,pe,st),s(Xe,pe,st),ze(YA.children||[],pe,Xe,Te,be,yt,ht,ae)):ot>0&&ot&64&&zt&&MA.dynamicChildren?(qe(MA.dynamicChildren,zt,pe,Te,be,yt,ht),(YA.key!=null||Te&&YA===Te.subTree)&&d3(MA,YA,!0)):ai(MA,YA,pe,Xe,Te,be,yt,ht,ae)},$e=(MA,YA,pe,st,Te,be,yt,ht,ae)=>{YA.slotScopeIds=ht,MA==null?YA.shapeFlag&512?Te.ctx.activate(YA,pe,st,yt,ae):Dt(YA,pe,st,Te,be,yt,ae):Zi(MA,YA,ae)},Dt=(MA,YA,pe,st,Te,be,yt)=>{const ht=MA.component=zoA(MA,st,Te);if(fY(MA)&&(ht.ctx.renderer=Di),XoA(ht,!1,yt),ht.asyncDep){if(Te&&Te.registerDep(ht,bi,yt),!MA.el){const ae=ht.subTree=Ze(yc);QA(null,ae,YA,pe)}}else bi(ht,MA,YA,pe,Te,be,yt)},Zi=(MA,YA,pe)=>{const st=YA.component=MA.component;if(PoA(MA,YA,pe))if(st.asyncDep&&!st.asyncResolved){qt(st,YA,pe);return}else st.next=YA,st.update();else YA.el=MA.el,st.vnode=YA},bi=(MA,YA,pe,st,Te,be,yt)=>{const ht=()=>{if(MA.isMounted){let{next:ot,bu:zt,u:yi,parent:Hi,vnode:Ei}=MA;{const Nr=xZ(MA);if(Nr){ot&&(ot.el=Ei.el,qt(MA,ot,yt)),Nr.asyncDep.then(()=>{MA.isUnmounted||ht()});return}}let ji=ot,Xo;Hm(MA,!1),ot?(ot.el=Ei.el,qt(MA,ot,yt)):ot=Ei,zt&&fK(zt),(Xo=ot.props&&ot.props.onVnodeBeforeUpdate)&&Tu(Xo,Hi,ot,Ei),Hm(MA,!0);const sr=Wz(MA),Lo=MA.subTree;MA.subTree=sr,eA(Lo,sr,U(Lo.el),Ni(Lo),MA,Te,be),ot.el=sr.el,ji===null&&JoA(MA,sr.el),yi&&fc(yi,Te),(Xo=ot.props&&ot.props.onVnodeUpdated)&&fc(()=>Tu(Xo,Hi,ot,Ei),Te)}else{let ot;const{el:zt,props:yi}=YA,{bm:Hi,m:Ei,parent:ji,root:Xo,type:sr}=MA,Lo=fw(YA);Hm(MA,!1),Hi&&fK(Hi),!Lo&&(ot=yi&&yi.onVnodeBeforeMount)&&Tu(ot,ji,YA),Hm(MA,!0);{Xo.ce&&Xo.ce._injectChildStyle(sr);const Nr=MA.subTree=Wz(MA);eA(null,Nr,pe,st,MA,Te,be),YA.el=Nr.el}if(Ei&&fc(Ei,Te),!Lo&&(ot=yi&&yi.onVnodeMounted)){const Nr=YA;fc(()=>Tu(ot,ji,Nr),Te)}(YA.shapeFlag&256||ji&&fw(ji.vnode)&&ji.vnode.shapeFlag&256)&&MA.a&&fc(MA.a,Te),MA.isMounted=!0,YA=pe=st=null}};MA.scope.on();const ae=MA.effect=new W8(ht);MA.scope.off();const ye=MA.update=ae.run.bind(ae),Xe=MA.job=ae.runIfDirty.bind(ae);Xe.i=MA,Xe.id=MA.uid,ae.scheduler=()=>u3(Xe),Hm(MA,!0),ye()},qt=(MA,YA,pe)=>{YA.component=MA;const st=MA.vnode.props;MA.vnode=YA,MA.next=null,MoA(MA,YA.props,st,pe),NoA(MA,YA.children,pe),Np(),Fz(MA),Tp()},ai=(MA,YA,pe,st,Te,be,yt,ht,ae=!1)=>{const ye=MA&&MA.children,Xe=MA?MA.shapeFlag:0,ot=YA.children,{patchFlag:zt,shapeFlag:yi}=YA;if(zt>0){if(zt&128){Ur(ye,ot,pe,st,Te,be,yt,ht,ae);return}else if(zt&256){Ki(ye,ot,pe,st,Te,be,yt,ht,ae);return}}yi&8?(Xe&16&&lr(ye,Te,be),ot!==ye&&v(pe,ot)):Xe&16?yi&16?Ur(ye,ot,pe,st,Te,be,yt,ht,ae):lr(ye,Te,be,!0):(Xe&8&&v(pe,""),yi&16&&ze(ot,pe,st,Te,be,yt,ht,ae))},Ki=(MA,YA,pe,st,Te,be,yt,ht,ae)=>{MA=MA||Qw,YA=YA||Qw;const ye=MA.length,Xe=YA.length,ot=Math.min(ye,Xe);let zt;for(zt=0;ztXe?lr(MA,Te,be,!0,!1,ot):ze(YA,pe,st,Te,be,yt,ht,ae,ot)},Ur=(MA,YA,pe,st,Te,be,yt,ht,ae)=>{let ye=0;const Xe=YA.length;let ot=MA.length-1,zt=Xe-1;for(;ye<=ot&&ye<=zt;){const yi=MA[ye],Hi=YA[ye]=ae?Ep(YA[ye]):bu(YA[ye]);if(Zm(yi,Hi))eA(yi,Hi,pe,null,Te,be,yt,ht,ae);else break;ye++}for(;ye<=ot&&ye<=zt;){const yi=MA[ot],Hi=YA[zt]=ae?Ep(YA[zt]):bu(YA[zt]);if(Zm(yi,Hi))eA(yi,Hi,pe,null,Te,be,yt,ht,ae);else break;ot--,zt--}if(ye>ot){if(ye<=zt){const yi=zt+1,Hi=yizt)for(;ye<=ot;)no(MA[ye],Te,be,!0),ye++;else{const yi=ye,Hi=ye,Ei=new Map;for(ye=Hi;ye<=zt;ye++){const Kr=YA[ye]=ae?Ep(YA[ye]):bu(YA[ye]);Kr.key!=null&&Ei.set(Kr.key,ye)}let ji,Xo=0;const sr=zt-Hi+1;let Lo=!1,Nr=0;const Vo=new Array(sr);for(ye=0;ye=sr){no(Kr,Te,be,!0);continue}let Qn;if(Kr.key!=null)Qn=Ei.get(Kr.key);else for(ji=Hi;ji<=zt;ji++)if(Vo[ji-Hi]===0&&Zm(Kr,YA[ji])){Qn=ji;break}Qn===void 0?no(Kr,Te,be,!0):(Vo[Qn-Hi]=ye+1,Qn>=Nr?Nr=Qn:Lo=!0,eA(Kr,YA[Qn],pe,null,Te,be,yt,ht,ae),Xo++)}const et=Lo?_oA(Vo):Qw;for(ji=et.length-1,ye=sr-1;ye>=0;ye--){const Kr=Hi+ye,Qn=YA[Kr],ho=Kr+1{const{el:be,type:yt,transition:ht,children:ae,shapeFlag:ye}=MA;if(ye&6){Er(MA.component.subTree,YA,pe,st);return}if(ye&128){MA.suspense.move(YA,pe,st);return}if(ye&64){yt.move(MA,YA,pe,Di);return}if(yt===Tn){s(be,YA,pe);for(let ot=0;otht.enter(be),Te);else{const{leave:ot,delayLeave:zt,afterLeave:yi}=ht,Hi=()=>s(be,YA,pe),Ei=()=>{ot(be,()=>{Hi(),yi&&yi()})};zt?zt(be,Hi,Ei):Ei()}else s(be,YA,pe)},no=(MA,YA,pe,st=!1,Te=!1)=>{const{type:be,props:yt,ref:ht,children:ae,dynamicChildren:ye,shapeFlag:Xe,patchFlag:ot,dirs:zt,cacheIndex:yi}=MA;if(ot===-2&&(Te=!1),ht!=null&&Y2(ht,null,pe,MA,!0),yi!=null&&(YA.renderCache[yi]=void 0),Xe&256){YA.ctx.deactivate(MA);return}const Hi=Xe&1&&zt,Ei=!fw(MA);let ji;if(Ei&&(ji=yt&&yt.onVnodeBeforeUnmount)&&Tu(ji,YA,MA),Xe&6)yr(MA.component,pe,st);else{if(Xe&128){MA.suspense.unmount(pe,st);return}Hi&&Jm(MA,null,YA,"beforeUnmount"),Xe&64?MA.type.remove(MA,YA,pe,Di,st):ye&&!ye.hasOnce&&(be!==Tn||ot>0&&ot&64)?lr(ye,YA,pe,!1,!0):(be===Tn&&ot&384||!Te&&Xe&16)&&lr(ae,YA,pe),st&&Kn(MA)}(Ei&&(ji=yt&&yt.onVnodeUnmounted)||Hi)&&fc(()=>{ji&&Tu(ji,YA,MA),Hi&&Jm(MA,null,YA,"unmounted")},pe)},Kn=MA=>{const{type:YA,el:pe,anchor:st,transition:Te}=MA;if(YA===Tn){Xi(pe,st);return}if(YA===NK){qA(MA);return}const be=()=>{g(pe),Te&&!Te.persisted&&Te.afterLeave&&Te.afterLeave()};if(MA.shapeFlag&1&&Te&&!Te.persisted){const{leave:yt,delayLeave:ht}=Te,ae=()=>yt(pe,be);ht?ht(MA.el,be,ae):ae()}else be()},Xi=(MA,YA)=>{let pe;for(;MA!==YA;)pe=AA(MA),g(MA),MA=pe;g(YA)},yr=(MA,YA,pe)=>{const{bum:st,scope:Te,job:be,subTree:yt,um:ht,m:ae,a:ye}=MA;jz(ae),jz(ye),st&&fK(st),Te.stop(),be&&(be.flags|=8,no(yt,MA,YA,pe)),ht&&fc(ht,YA),fc(()=>{MA.isUnmounted=!0},YA),YA&&YA.pendingBranch&&!YA.isUnmounted&&MA.asyncDep&&!MA.asyncResolved&&MA.suspenseId===YA.pendingId&&(YA.deps--,YA.deps===0&&YA.resolve())},lr=(MA,YA,pe,st=!1,Te=!1,be=0)=>{for(let yt=be;yt{if(MA.shapeFlag&6)return Ni(MA.component.subTree);if(MA.shapeFlag&128)return MA.suspense.next();const YA=AA(MA.anchor||MA.el),pe=YA&&YA[BZ];return pe?AA(pe):YA};let wt=!1;const Ji=(MA,YA,pe)=>{MA==null?YA._vnode&&no(YA._vnode,null,null,!0):eA(YA._vnode||null,MA,YA,null,null,null,pe),YA._vnode=MA,wt||(wt=!0,Fz(),lZ(),wt=!1)},Di={p:eA,um:no,m:Er,r:Kn,mt:Dt,mc:ze,pc:ai,pbc:qe,n:Ni,o:t};return{render:Ji,hydrate:void 0,createApp:yoA(Ji)}}function vK({type:t,props:i},r){return r==="svg"&&t==="foreignObject"||r==="mathml"&&t==="annotation-xml"&&i&&i.encoding&&i.encoding.includes("html")?void 0:r}function Hm({effect:t,job:i},r){r?(t.flags|=32,i.flags|=4):(t.flags&=-33,i.flags&=-5)}function koA(t,i){return(!t||t&&!t.pendingBranch)&&i&&!i.persisted}function d3(t,i,r=!1){const s=t.children,g=i.children;if(Ro(s)&&Ro(g))for(let B=0;B>1,t[r[f]]0&&(i[s]=r[B-1]),r[B]=s)}}for(B=r.length,Q=r[B-1];B-- >0;)r[B]=Q,Q=i[Q];return r}function xZ(t){const i=t.subTree.component;if(i)return i.asyncDep&&!i.asyncResolved?i:xZ(i)}function jz(t){if(t)for(let i=0;irI(boA);function _w(t,i){return h3(t,null,i)}function Un(t,i,r){return h3(t,i,r)}function h3(t,i,r=qn){const{immediate:s,deep:g,flush:B,once:Q}=r,f=Sg({},r),m=i&&s||!i&&B!=="post";let M;if(lk){if(B==="sync"){const z=LoA();M=z.__watcherHandles||(z.__watcherHandles=[])}else if(!m){const z=()=>{};return z.stop=Ou,z.resume=Ou,z.pause=Ou,z}}const v=oI;f.call=(z,sA,eA)=>uB(z,v,sA,eA);let U=!1;B==="post"?f.scheduler=z=>{fc(z,v&&v.suspense)}:B!=="sync"&&(U=!0,f.scheduler=(z,sA)=>{sA?z():u3(z)}),f.augmentJob=z=>{i&&(z.flags|=4),U&&(z.flags|=2,v&&(z.id=v.uid,z.i=v))};const AA=jiA(t,i,f);return lk&&(M?M.push(AA):m&&AA()),AA}function FoA(t,i,r){const s=this.proxy,g=va(t)?t.includes(".")?YZ(s,t):()=>s[t]:t.bind(s,s);let B;xo(i)?B=i:(B=i.handler,r=i);const Q=Rk(this),f=h3(g,B.bind(s),r);return Q(),f}function YZ(t,i){const r=i.split(".");return()=>{let s=t;for(let g=0;gi==="modelValue"||i==="model-value"?t.modelModifiers:t[`${i}Modifiers`]||t[`${mC(i)}Modifiers`]||t[`${vp(i)}Modifiers`];function OoA(t,i,...r){if(t.isUnmounted)return;const s=t.vnode.props||qn;let g=r;const B=i.startsWith("update:"),Q=B&&UoA(s,i.slice(7));Q&&(Q.trim&&(g=r.map(v=>va(v)?v.trim():v)),Q.number&&(g=r.map(siA)));let f,m=s[f=pK(i)]||s[f=pK(mC(i))];!m&&B&&(m=s[f=pK(vp(i))]),m&&uB(m,t,6,g);const M=s[f+"Once"];if(M){if(!t.emitted)t.emitted={};else if(t.emitted[f])return;t.emitted[f]=!0,uB(M,t,6,g)}}function PZ(t,i,r=!1){const s=i.emitsCache,g=s.get(t);if(g!==void 0)return g;const B=t.emits;let Q={},f=!1;if(!xo(t)){const m=M=>{const v=PZ(M,i,!0);v&&(f=!0,Sg(Q,v))};!r&&i.mixins.length&&i.mixins.forEach(m),t.extends&&m(t.extends),t.mixins&&t.mixins.forEach(m)}return!B&&!f?(ta(t)&&s.set(t,null),null):(Ro(B)?B.forEach(m=>Q[m]=null):Sg(Q,B),ta(t)&&s.set(t,Q),Q)}function DY(t,i){return!t||!lY(i)?!1:(i=i.slice(2).replace(/Once$/,""),yn(t,i[0].toLowerCase()+i.slice(1))||yn(t,vp(i))||yn(t,i))}function Wz(t){const{type:i,vnode:r,proxy:s,withProxy:g,propsOptions:[B],slots:Q,attrs:f,emit:m,render:M,renderCache:v,props:U,data:AA,setupState:z,ctx:sA,inheritAttrs:eA}=t,X=x2(t);let QA,wA;try{if(r.shapeFlag&4){const qA=g||s,ue=qA;QA=bu(M.call(ue,qA,v,U,z,AA,sA)),wA=f}else{const qA=i;QA=bu(qA.length>1?qA(U,{attrs:f,slots:Q,emit:m}):qA(U,null)),wA=i.props?f:xoA(f)}}catch(qA){KG.length=0,hY(qA,t,1),QA=Ze(yc)}let HA=QA;if(wA&&eA!==!1){const qA=Object.keys(wA),{shapeFlag:ue}=HA;qA.length&&ue&7&&(B&&qA.some(n3)&&(wA=YoA(wA,B)),HA=Dp(HA,wA,!1,!0))}return r.dirs&&(HA=Dp(HA,null,!1,!0),HA.dirs=HA.dirs?HA.dirs.concat(r.dirs):r.dirs),r.transition&&Ik(HA,r.transition),QA=HA,x2(X),QA}const xoA=t=>{let i;for(const r in t)(r==="class"||r==="style"||lY(r))&&((i||(i={}))[r]=t[r]);return i},YoA=(t,i)=>{const r={};for(const s in t)(!n3(s)||!(s.slice(9)in i))&&(r[s]=t[s]);return r};function PoA(t,i,r){const{props:s,children:g,component:B}=t,{props:Q,children:f,patchFlag:m}=i,M=B.emitsOptions;if(i.dirs||i.transition)return!0;if(r&&m>=0){if(m&1024)return!0;if(m&16)return s?zz(s,Q,M):!!Q;if(m&8){const v=i.dynamicProps;for(let U=0;Ut.__isSuspense;function HoA(t,i){i&&i.pendingBranch?Ro(t)?i.effects.push(...t):i.effects.push(t):ZiA(t)}const Tn=Symbol.for("v-fgt"),yY=Symbol.for("v-txt"),yc=Symbol.for("v-cmt"),NK=Symbol.for("v-stc"),KG=[];let Bl=null;function VA(t=!1){KG.push(Bl=t?null:[])}function VoA(){KG.pop(),Bl=KG[KG.length-1]||null}let ck=1;function Zz(t,i=!1){ck+=t,t<0&&Bl&&i&&(Bl.hasOnce=!0)}function HZ(t){return t.dynamicChildren=ck>0?Bl||Qw:null,VoA(),ck>0&&Bl&&Bl.push(t),t}function Ue(t,i,r,s,g,B){return HZ(ce(t,i,r,s,g,B,!0))}function _t(t,i,r,s,g){return HZ(Ze(t,i,r,s,g,!0))}function Ek(t){return t?t.__v_isVNode===!0:!1}function Zm(t,i){return t.type===i.type&&t.key===i.key}const VZ=({key:t})=>t??null,D2=({ref:t,ref_key:i,ref_for:r})=>(typeof t=="number"&&(t=""+t),t!=null?va(t)||wg(t)||xo(t)?{i:Mg,r:t,k:i,f:!!r}:t:null);function ce(t,i=null,r=null,s=0,g=null,B=t===Tn?0:1,Q=!1,f=!1){const m={__v_isVNode:!0,__v_skip:!0,type:t,props:i,key:i&&VZ(i),ref:i&&D2(i),scopeId:pY,slotScopeIds:null,children:r,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:B,patchFlag:s,dynamicProps:g,dynamicChildren:null,appContext:null,ctx:Mg};return f?(p3(m,r),B&128&&t.normalize(m)):r&&(m.shapeFlag|=va(r)?8:16),ck>0&&!Q&&Bl&&(m.patchFlag>0||B&6)&&m.patchFlag!==32&&Bl.push(m),m}const Ze=qoA;function qoA(t,i=null,r=null,s=0,g=null,B=!1){if((!t||t===BoA)&&(t=yc),Ek(t)){const f=Dp(t,i,!0);return r&&p3(f,r),ck>0&&!B&&Bl&&(f.shapeFlag&6?Bl[Bl.indexOf(t)]=f:Bl.push(f)),f.patchFlag=-2,f}if(irA(t)&&(t=t.__vccOpts),i){i=KoA(i);let{class:f,style:m}=i;f&&!va(f)&&(i.class=Qi(f)),ta(m)&&(B3(m)&&!Ro(m)&&(m=Sg({},m)),i.style=zr(m))}const Q=va(t)?1:JZ(t)?128:uZ(t)?64:ta(t)?4:xo(t)?2:0;return ce(t,i,r,s,g,Q,B,!0)}function KoA(t){return t?B3(t)||kZ(t)?Sg({},t):t:null}function Dp(t,i,r=!1,s=!1){const{props:g,ref:B,patchFlag:Q,children:f,transition:m}=t,M=i?yj(g||{},i):g,v={__v_isVNode:!0,__v_skip:!0,type:t.type,props:M,key:M&&VZ(M),ref:i&&i.ref?r&&B?Ro(B)?B.concat(D2(i)):[B,D2(i)]:D2(i):B,scopeId:t.scopeId,slotScopeIds:t.slotScopeIds,children:f,target:t.target,targetStart:t.targetStart,targetAnchor:t.targetAnchor,staticCount:t.staticCount,shapeFlag:t.shapeFlag,patchFlag:i&&t.type!==Tn?Q===-1?16:Q|16:Q,dynamicProps:t.dynamicProps,dynamicChildren:t.dynamicChildren,appContext:t.appContext,dirs:t.dirs,transition:m,component:t.component,suspense:t.suspense,ssContent:t.ssContent&&Dp(t.ssContent),ssFallback:t.ssFallback&&Dp(t.ssFallback),el:t.el,anchor:t.anchor,ctx:t.ctx,ce:t.ce};return m&&s&&Ik(v,m.clone(v)),v}function Na(t=" ",i=0){return Ze(yY,null,t,i)}function Tt(t="",i=!1){return i?(VA(),_t(yc,null,t)):Ze(yc,null,t)}function bu(t){return t==null||typeof t=="boolean"?Ze(yc):Ro(t)?Ze(Tn,null,t.slice()):Ek(t)?Ep(t):Ze(yY,null,String(t))}function Ep(t){return t.el===null&&t.patchFlag!==-1||t.memo?t:Dp(t)}function p3(t,i){let r=0;const{shapeFlag:s}=t;if(i==null)i=null;else if(Ro(i))r=16;else if(typeof i=="object")if(s&65){const g=i.default;g&&(g._c&&(g._d=!1),p3(t,g()),g._c&&(g._d=!0));return}else{r=32;const g=i._;!g&&!kZ(i)?i._ctx=Mg:g===3&&Mg&&(Mg.slots._===1?i._=1:(i._=2,t.patchFlag|=1024))}else xo(i)?(i={default:i,_ctx:Mg},r=32):(i=String(i),s&64?(r=16,i=[Na(i)]):r=8);t.children=i,t.shapeFlag|=r}function yj(...t){const i={};for(let r=0;roI||Mg;let J2,Rj;{const t=QY(),i=(r,s)=>{let g;return(g=t[r])||(g=t[r]=[]),g.push(s),B=>{g.length>1?g.forEach(Q=>Q(B)):g[0](B)}};J2=i("__VUE_INSTANCE_SETTERS__",r=>oI=r),Rj=i("__VUE_SSR_SETTERS__",r=>lk=r)}const Rk=t=>{const i=oI;return J2(t),t.scope.on(),()=>{t.scope.off(),J2(i)}},Xz=()=>{oI&&oI.scope.off(),J2(null)};function qZ(t){return t.vnode.shapeFlag&4}let lk=!1;function XoA(t,i=!1,r=!1){i&&Rj(i);const{props:s,children:g}=t.vnode,B=qZ(t);RoA(t,s,B,i),voA(t,g,r);const Q=B?$oA(t,i):void 0;return i&&Rj(!1),Q}function $oA(t,i){const r=t.type;t.accessCache=Object.create(null),t.proxy=new Proxy(t.ctx,QoA);const{setup:s}=r;if(s){Np();const g=t.setupContext=s.length>1?erA(t):null,B=Rk(t),Q=Dk(s,t,0,[t.props,g]),f=P8(Q);if(Tp(),B(),(f||t.sp)&&!fw(t)&&yZ(t),f){if(Q.then(Xz,Xz),i)return Q.then(m=>{$z(t,m)}).catch(m=>{hY(m,t,0)});t.asyncDep=Q}else $z(t,Q)}else KZ(t)}function $z(t,i,r){xo(i)?t.type.__ssrInlineRender?t.ssrRender=i:t.render=i:ta(i)&&(t.setupState=gZ(i)),KZ(t)}function KZ(t,i,r){const s=t.type;t.render||(t.render=s.render||Ou);{const g=Rk(t);Np();try{doA(t)}finally{Tp(),g()}}}const ArA={get(t,i){return GI(t,"get",""),t[i]}};function erA(t){const i=r=>{t.exposed=r||{}};return{attrs:new Proxy(t.attrs,ArA),slots:t.slots,emit:t.emit,expose:i}}function RY(t){return t.exposed?t.exposeProxy||(t.exposeProxy=new Proxy(gZ(OiA(t.exposed)),{get(i,r){if(r in i)return i[r];if(r in qG)return qG[r](t)},has(i,r){return r in i||r in qG}})):t.proxy}function trA(t,i=!0){return xo(t)?t.displayName||t.name:t.name||i&&t.__name}function irA(t){return xo(t)&&"__vccOpts"in t}const rt=(t,i)=>qiA(t,i,lk);function orA(t,i,r){const s=arguments.length;return s===2?ta(i)&&!Ro(i)?Ek(i)?Ze(t,null,[i]):Ze(t,i):Ze(t,null,i):(s>3?r=Array.prototype.slice.call(arguments,2):s===3&&Ek(r)&&(r=[r]),Ze(t,i,r))}const Mj="3.5.13";/** * @vue/runtime-dom v3.5.13 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT -**/let fj;const Kz=typeof window<"u"&&window.trustedTypes;if(Kz)try{fj=Kz.createPolicy("vue",{createHTML:t=>t})}catch{}const YZ=fj?t=>fj.createHTML(t):t=>t,qoA="http://www.w3.org/2000/svg",KoA="http://www.w3.org/1998/Math/MathML",ed=typeof document<"u"?document:null,jz=ed&&ed.createElement("template"),joA={insert:(t,i,r)=>{i.insertBefore(t,r||null)},remove:t=>{const i=t.parentNode;i&&i.removeChild(t)},createElement:(t,i,r,s)=>{const g=i==="svg"?ed.createElementNS(qoA,t):i==="mathml"?ed.createElementNS(KoA,t):r?ed.createElement(t,{is:r}):ed.createElement(t);return t==="select"&&s&&s.multiple!=null&&g.setAttribute("multiple",s.multiple),g},createText:t=>ed.createTextNode(t),createComment:t=>ed.createComment(t),setText:(t,i)=>{t.nodeValue=i},setElementText:(t,i)=>{t.textContent=i},parentNode:t=>t.parentNode,nextSibling:t=>t.nextSibling,querySelector:t=>ed.querySelector(t),setScopeId(t,i){t.setAttribute(i,"")},insertStaticContent(t,i,r,s,g,B){const Q=r?r.previousSibling:i.lastChild;if(g&&(g===B||g.nextSibling))for(;i.insertBefore(g.cloneNode(!0),r),!(g===B||!(g=g.nextSibling)););else{jz.innerHTML=YZ(s==="svg"?`${t}`:s==="mathml"?`${t}`:t);const f=jz.content;if(s==="svg"||s==="mathml"){const m=f.firstChild;for(;m.firstChild;)f.appendChild(m.firstChild);f.removeChild(m)}i.insertBefore(f,r)}return[Q?Q.nextSibling:i.firstChild,r?r.previousSibling:i.lastChild]}},tp="transition",EG="animation",sk=Symbol("_vtc"),PZ={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},WoA=Sg({},EZ,PZ),zoA=t=>(t.displayName="Transition",t.props=WoA,t),ZoA=zoA((t,{slots:i})=>VoA(JiA,XoA(t),i)),Ym=(t,i=[])=>{Ro(t)?t.forEach(r=>r(...i)):t&&t(...i)},Wz=t=>t?Ro(t)?t.some(i=>i.length>1):t.length>1:!1;function XoA(t){const i={};for(const Je in t)Je in PZ||(i[Je]=t[Je]);if(t.css===!1)return i;const{name:r="v",type:s,duration:g,enterFromClass:B=`${r}-enter-from`,enterActiveClass:Q=`${r}-enter-active`,enterToClass:f=`${r}-enter-to`,appearFromClass:m=B,appearActiveClass:M=Q,appearToClass:v=f,leaveFromClass:U=`${r}-leave-from`,leaveActiveClass:AA=`${r}-leave-active`,leaveToClass:z=`${r}-leave-to`}=t,sA=$oA(g),eA=sA&&sA[0],X=sA&&sA[1],{onBeforeEnter:QA,onEnter:wA,onEnterCancelled:HA,onLeave:VA,onLeaveCancelled:ue,onBeforeAppear:jA=QA,onAppear:Ve=wA,onAppearCancelled:Ze=HA}=i,Me=(Je,$e,Dt,Zi)=>{Je._enterCancelled=Zi,Pm(Je,$e?v:f),Pm(Je,$e?M:Q),Dt&&Dt()},qe=(Je,$e)=>{Je._isLeaving=!1,Pm(Je,U),Pm(Je,z),Pm(Je,AA),$e&&$e()},Et=Je=>($e,Dt)=>{const Zi=Je?Ve:wA,bi=()=>Me($e,Je,Dt);Ym(Zi,[$e,bi]),zz(()=>{Pm($e,Je?m:B),ZQ($e,Je?v:f),Wz(Zi)||Zz($e,s,eA,bi)})};return Sg(i,{onBeforeEnter(Je){Ym(QA,[Je]),ZQ(Je,B),ZQ(Je,Q)},onBeforeAppear(Je){Ym(jA,[Je]),ZQ(Je,m),ZQ(Je,M)},onEnter:Et(!1),onAppear:Et(!0),onLeave(Je,$e){Je._isLeaving=!0;const Dt=()=>qe(Je,$e);ZQ(Je,U),Je._enterCancelled?(ZQ(Je,AA),A5()):(A5(),ZQ(Je,AA)),zz(()=>{Je._isLeaving&&(Pm(Je,U),ZQ(Je,z),Wz(VA)||Zz(Je,s,X,Dt))}),Ym(VA,[Je,Dt])},onEnterCancelled(Je){Me(Je,!1,void 0,!0),Ym(HA,[Je])},onAppearCancelled(Je){Me(Je,!0,void 0,!0),Ym(Ze,[Je])},onLeaveCancelled(Je){qe(Je),Ym(ue,[Je])}})}function $oA(t){if(t==null)return null;if(ta(t))return[RK(t.enter),RK(t.leave)];{const i=RK(t);return[i,i]}}function RK(t){return ztA(t)}function ZQ(t,i){i.split(/\s+/).forEach(r=>r&&t.classList.add(r)),(t[sk]||(t[sk]=new Set)).add(i)}function Pm(t,i){i.split(/\s+/).forEach(s=>s&&t.classList.remove(s));const r=t[sk];r&&(r.delete(i),r.size||(t[sk]=void 0))}function zz(t){requestAnimationFrame(()=>{requestAnimationFrame(t)})}let ArA=0;function Zz(t,i,r,s){const g=t._endId=++ArA,B=()=>{g===t._endId&&s()};if(r!=null)return setTimeout(B,r);const{type:Q,timeout:f,propCount:m}=erA(t,i);if(!Q)return s();const M=Q+"end";let v=0;const U=()=>{t.removeEventListener(M,AA),B()},AA=z=>{z.target===t&&++v>=m&&U()};setTimeout(()=>{v(r[sA]||"").split(", "),g=s(`${tp}Delay`),B=s(`${tp}Duration`),Q=Xz(g,B),f=s(`${EG}Delay`),m=s(`${EG}Duration`),M=Xz(f,m);let v=null,U=0,AA=0;i===tp?Q>0&&(v=tp,U=Q,AA=B.length):i===EG?M>0&&(v=EG,U=M,AA=m.length):(U=Math.max(Q,M),v=U>0?Q>M?tp:EG:null,AA=v?v===tp?B.length:m.length:0);const z=v===tp&&/\b(transform|all)(,|$)/.test(s(`${tp}Property`).toString());return{type:v,timeout:U,propCount:AA,hasTransform:z}}function Xz(t,i){for(;t.length$z(r)+$z(t[s])))}function $z(t){return t==="auto"?0:Number(t.slice(0,-1).replace(",","."))*1e3}function A5(){return document.body.offsetHeight}function trA(t,i,r){const s=t[sk];s&&(i=(i?[i,...s]:[...s]).join(" ")),i==null?t.removeAttribute("class"):r?t.setAttribute("class",i):t.className=i}const U2=Symbol("_vod"),JZ=Symbol("_vsh"),sa={beforeMount(t,{value:i},{transition:r}){t[U2]=t.style.display==="none"?"":t.style.display,r&&i?r.beforeEnter(t):lG(t,i)},mounted(t,{value:i},{transition:r}){r&&i&&r.enter(t)},updated(t,{value:i,oldValue:r},{transition:s}){!i!=!r&&(s?i?(s.beforeEnter(t),lG(t,!0),s.enter(t)):s.leave(t,()=>{lG(t,!1)}):lG(t,i))},beforeUnmount(t,{value:i}){lG(t,i)}};function lG(t,i){t.style.display=i?t[U2]:"none",t[JZ]=!i}const irA=Symbol(""),orA=/(^|;)\s*display\s*:/;function rrA(t,i,r){const s=t.style,g=va(r);let B=!1;if(r&&!g){if(i)if(va(i))for(const Q of i.split(";")){const f=Q.slice(0,Q.indexOf(":")).trim();r[f]==null&&Q2(s,f,"")}else for(const Q in i)r[Q]==null&&Q2(s,Q,"");for(const Q in r)Q==="display"&&(B=!0),Q2(s,Q,r[Q])}else if(g){if(i!==r){const Q=s[irA];Q&&(r+=";"+Q),s.cssText=r,B=orA.test(r)}}else i&&t.removeAttribute("style");U2 in t&&(t[U2]=B?s.display:"",t[JZ]&&(s.display="none"))}const e5=/\s*!important$/;function Q2(t,i,r){if(Ro(r))r.forEach(s=>Q2(t,i,s));else if(r==null&&(r=""),i.startsWith("--"))t.setProperty(i,r);else{const s=nrA(t,i);e5.test(r)?t.setProperty(Rp(s),r.replace(e5,""),"important"):t[s]=r}}const t5=["Webkit","Moz","ms"],MK={};function nrA(t,i){const r=MK[i];if(r)return r;let s=mC(i);if(s!=="filter"&&s in t)return MK[i]=s;s=gY(s);for(let g=0;gwK||(crA.then(()=>wK=0),wK=Date.now());function lrA(t,i){const r=s=>{if(!s._vts)s._vts=Date.now();else if(s._vts<=r.attached)return;CB(CrA(s,r.value),i,5,[s])};return r.value=t,r.attached=ErA(),r}function CrA(t,i){if(Ro(i)){const r=t.stopImmediatePropagation;return t.stopImmediatePropagation=()=>{r.call(t),t._stopped=!0},i.map(s=>g=>!g._stopped&&s&&s(g))}else return i}const s5=t=>t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&t.charCodeAt(2)>96&&t.charCodeAt(2)<123,BrA=(t,i,r,s,g,B)=>{const Q=g==="svg";i==="class"?trA(t,s,Q):i==="style"?rrA(t,r,s):nY(i)?A3(i)||grA(t,i,r,s,B):(i[0]==="."?(i=i.slice(1),!0):i[0]==="^"?(i=i.slice(1),!1):urA(t,i,s,Q))?(r5(t,i,s),!t.tagName.includes("-")&&(i==="value"||i==="checked"||i==="selected")&&o5(t,i,s,Q,B,i!=="value")):t._isVueCE&&(/[A-Z]/.test(i)||!va(s))?r5(t,mC(i),s,B,i):(i==="true-value"?t._trueValue=s:i==="false-value"&&(t._falseValue=s),o5(t,i,s,Q))};function urA(t,i,r,s){if(s)return!!(i==="innerHTML"||i==="textContent"||i in t&&s5(i)&&xo(r));if(i==="spellcheck"||i==="draggable"||i==="translate"||i==="form"||i==="list"&&t.tagName==="INPUT"||i==="type"&&t.tagName==="TEXTAREA")return!1;if(i==="width"||i==="height"){const g=t.tagName;if(g==="IMG"||g==="VIDEO"||g==="CANVAS"||g==="SOURCE")return!1}return s5(i)&&va(r)?!1:i in t}const QrA=["ctrl","shift","alt","meta"],drA={stop:t=>t.stopPropagation(),prevent:t=>t.preventDefault(),self:t=>t.target!==t.currentTarget,ctrl:t=>!t.ctrlKey,shift:t=>!t.shiftKey,alt:t=>!t.altKey,meta:t=>!t.metaKey,left:t=>"button"in t&&t.button!==0,middle:t=>"button"in t&&t.button!==1,right:t=>"button"in t&&t.button!==2,exact:(t,i)=>QrA.some(r=>t[`${r}Key`]&&!i.includes(r))},ul=(t,i)=>{const r=t._withMods||(t._withMods={}),s=i.join(".");return r[s]||(r[s]=(g,...B)=>{for(let Q=0;Q{const r=t._withKeys||(t._withKeys={}),s=i.join(".");return r[s]||(r[s]=g=>{if(!("key"in g))return;const B=Rp(g.key);if(i.some(Q=>Q===B||hrA[Q]===B))return t(g)})},frA=Sg({patchProp:BrA},joA);let g5;function HZ(){return g5||(g5=doA(frA))}const iD=(...t)=>{HZ().render(...t)},mrA=(...t)=>{const i=HZ().createApp(...t),{mount:r}=i;return i.mount=s=>{const g=yrA(s);if(!g)return;const B=i._component;!xo(B)&&!B.render&&!B.template&&(B.template=g.innerHTML),g.nodeType===1&&(g.textContent="");const Q=r(g,!1,DrA(g));return g instanceof Element&&(g.removeAttribute("v-cloak"),g.setAttribute("data-v-app","")),Q},i};function DrA(t){if(t instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&t instanceof MathMLElement)return"mathml"}function yrA(t){return va(t)?document.querySelector(t):t}var bI=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function RrA(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function hk(t){if(t.__esModule)return t;var i=t.default;if(typeof i=="function"){var r=function s(){return this instanceof s?Reflect.construct(i,arguments,this.constructor):i.apply(this,arguments)};r.prototype=i.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(s){var g=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(r,s,g.get?g:{enumerable:!0,get:function(){return t[s]}})}),r}function MrA(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var pG={exports:{}},d2={exports:{}},wrA=d2.exports,I5;function VZ(){return I5||(I5=1,function(t,i){(function(r,s){t.exports=s()})(wrA,function(){const r=C=>C===void 0,s=C=>typeof C=="string",g=C=>{var E;return(E=Object.prototype.toString.call(C).match(/^\[object (.*)\]$/))===null||E===void 0?void 0:E[1].toLowerCase()},B=C=>typeof Array.isArray=="function"?Array.isArray(C):g(C)==="array",Q=C=>C!==null&&typeof C=="object",f=C=>B(C)||Q(C),m=C=>{if(typeof C!="string")return!1;const E=C[0];return!/[^a-zA-Z0-9]/.test(E)},M=C=>{if(typeof C!="object"||C===null)return!1;const E=Object.getPrototypeOf(C);if(E===null)return!0;let h=E;for(;Object.getPrototypeOf(h)!==null;)h=Object.getPrototypeOf(h);return E===h};function v(C=99999999){return Math.round(Math.random()*C)}const U=(C,E,h,D)=>{if(!f(C)||!f(E))return 0;let N=0;const O=Object.keys(E);let Y;for(let j=0,IA=O.length;j"u"&&typeof uni.requireNativePlugin=="function",Er=Je&&typeof wx.miniapp=="object",no=typeof uni<"u",Kn=Zi&&typeof tt.enterChat=="function",Xi=Je||Dt||Zi||qt||ai||Ur||Ki,yr=typeof window>"u"&&!Xi&&typeof bI<"u"&&bI.NativeScriptGlobals!==void 0,lr=typeof bI<"u"&&(bI.nativeModuleProxy!==void 0||bI.ReactNative!==void 0),Ni=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,wt=typeof uni<"u"?!Xi:typeof window<"u"&&!Xi&&!lr,Ji=Dt?qq:Zi?tt:qt?swan:ai?my:Je?wx:Ur?uni:Ki?jd:{},Di=wt&&window&&window.navigator&&window.navigator.userAgent||"",ar=/(micromessenger|webbrowser)/i.test(Di),MA=function(){let C="WEB";return ar?C="WEB":Dt?C="QQ_MP":Zi?C="TT_MP":qt?C="BAIDU_MP":ai?C="ALI_MP":Je?C=Er?"DONUT_NATIVE_APP":"WX_MP":Ur?C="UNI_NATIVE_APP":yr?C="NS_NATIVE_APP":lr&&(C="RN_NATIVE_APP"),z[C]}(),YA=/iPad/i.test(Di),pe=/iPhone/i.test(Di)&&!YA,st=/iPod/i.test(Di),Te=pe||YA||st,be=function(){const C=Di.match(/OS (\d+)_/i);return C&&C[1]?C[1]:null}(),yt=/Android/i.test(Di),ht=function(){const C=Di.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!C)return null;const E=C[1]&&parseFloat(C[1]),h=C[2]&&parseFloat(C[2]);return E&&h?parseFloat(`${C[1]}.${C[2]}`):E||null}(),ae=/Firefox/i.test(Di),ye=/Edge/i.test(Di),Xe=!ye&&/Chrome/i.test(Di),ot=/MSIE/.test(Di)||Di.indexOf("Trident")>-1&&Di.indexOf("rv:11.0")>-1,zt=function(){const C=/MSIE\s(\d+)\.\d/.exec(Di);let E=C&&parseFloat(C[1]);return!E&&/Trident\/7.0/i.test(Di)&&/rv:11.0/.test(Di)&&(E=11),E}(),yi=/Safari/i.test(Di)&&!Xe&&!yt&&!ye,Hi=/Windows/i.test(Di),Ei=/MAC OS X/i.test(Di),ji=wt&&typeof Worker<"u"&&!ot,Xo=yt||Te,sr=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:C}=window.navigator;return!(!Te||C||yi)}();function Lo(){let C="unknown";if(Ei&&(C="mac"),Hi&&(C="windows"),Te&&(C="ios"),yt&&(C="android"),Xi)try{const{platform:E}=Ji.getSystemInfoSync();E!==void 0&&(C=E)}catch(E){console.error(E)}return C}const Nr=typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0&&typeof window>"u";function Vo(C,E){var h={};for(var D in C)Object.prototype.hasOwnProperty.call(C,D)&&E.indexOf(D)<0&&(h[D]=C[D]);if(C!=null&&typeof Object.getOwnPropertySymbols=="function"){var N=0;for(D=Object.getOwnPropertySymbols(C);N{Ji.request({url:h,data:D,method:E,timeout:N,header:{"content-type":jn},success:j=>O(j.data),fail:()=>Y(new Error(`{"message":"Network error","code":${Kr}}`))})}):Nr?void 0:new Promise((O,Y)=>{const j=new XMLHttpRequest,IA=setTimeout(()=>{j.abort(),Y(new Error(`{"message":"Request timeout","code":${Qn}}`))},N);j.onreadystatechange=function(){if(j.readyState===4)if(clearTimeout(IA),j.status===200||j.status===304)try{O(j.responseText?JSON.parse(j.responseText):null)}catch{O(j.responseText)}else Y(new Error(`{"message":"Network error","code":${Kr}}`))},j.open(E,h,!0),j.setRequestHeader("Content-type",jn),j.send(D||null)})})}function $r(C){if(C==null)return!0;if(typeof C=="boolean")return!1;if(typeof C=="number")return C===0;if(typeof C=="string"||typeof C=="function"||Array.isArray(C))return C.length===0;if(C instanceof Error)return C.message==="";if(M(C)){for(const E in C)if(Object.prototype.hasOwnProperty.call(C,E))return!1;return!0}return(Object.prototype.toString.call(C)==="[object Map]"||Object.prototype.toString.call(C)==="[object Set]"||Object.prototype.toString.call(C)==="[object File]")&&C.size===0}function On(C,E){if(C===null||typeof C!="object")return C;const h=E||new WeakMap;if(h.has(C))return h.get(C);if(C instanceof Date)return new Date(C.getTime());if(C instanceof RegExp)return new RegExp(C.source,C.flags);if(C instanceof Map){const O=new Map;return h.set(C,O),C.forEach((Y,j)=>{O.set(On(j,h),On(Y,h))}),O}if(C instanceof Set){const O=new Set;return h.set(C,O),C.forEach(Y=>{O.add(On(Y,h))}),O}if(Array.isArray(C)){const O=[];return h.set(C,O),C.forEach(Y=>{O.push(On(Y,h))}),O}const D=Object.getPrototypeOf(C),N=Object.create(D);return h.set(C,N),[...Object.getOwnPropertyNames(C),...Object.getOwnPropertySymbols(C)].forEach(O=>{if(O==="__ob__"||O==="__v_skip"||O==="__v_isRef"||O==="__v_isReadonly")return;const Y=Object.getOwnPropertyDescriptor(C,O);Y&&(Y.get||Y.set?Object.defineProperty(N,O,Y):N[O]=On(C[O],h))}),N}function An(C,E,h){const D=new WeakSet,N=(O,Y)=>{if(E&&(Y=E(O,Y)),Y===void 0)return"undefined";if(Y===null)return null;if(Number.isNaN(Y))return"NaN";if(Y===1/0)return"Infinity";if(Y===-1/0)return"-Infinity";if(typeof Y=="function")return`[Function: ${Y.name||"anonymous"}]`;if(typeof Y=="symbol")return Y.toString();if(typeof Y=="bigint")return`${Y.toString()}n`;if(typeof Y=="object"&&Y!==null){if(D.has(Y))return"[Circular]";D.add(Y)}return Y instanceof Date?Y.toISOString():Y instanceof Error?{name:Y.name,message:Y.message}:Y instanceof Map?{dataType:"Map",value:Array.from(Y.entries())}:Y instanceof Set?{dataType:"Set",value:Array.from(Y.values())}:Y};try{return JSON.stringify(C,N,h)}catch(O){return console.error("Failed to stringify:",O),""}}function Tr(){let C,E;return{promise:new Promise((h,D)=>{C=h,E=D}),resolve:C,reject:E}}var ei,Es=Object.freeze({__proto__:null,ANDROID_VERSION:ht,IE_VERSION:zt,IN_ALIPAY_MINI_APP:ai,IN_BAIDU_MINI_APP:qt,IN_BROWSER:wt,IN_DONUT_NATIVE_APP:Er,IN_FEISHU_MINI_APP:Kn,IN_JD_MINI_APP:Ki,IN_MINI_APP:Xi,IN_NODE:Nr,IN_NS_NATIVE_APP:yr,IN_QQ_MINI_APP:Dt,IN_RN_APP:lr,IN_TT_MINI_APP:Zi,IN_TT_MINI_GAME:bi,IN_UNI_APP:no,IN_UNI_NATIVE_APP:Ur,IN_WX_MINI_APP:Je,IN_WX_MINI_APP_DESK:Et,IN_WX_MINI_GAME:$e,IN_WX_MINI_PLUGIN:Ni,IOS_VERSION:be,IS_ANDROID:yt,IS_CHROME:Xe,IS_EDGE:ye,IS_FIREFOX:ae,IS_IE:ot,IS_IOS:Te,IS_IPAD:YA,IS_IPHONE:pe,IS_IPOD:st,IS_MAC:Ei,IS_SAFARI:yi,IS_WECHAT:ar,IS_WIN:Hi,IS_WORKER_AVAILABLE:ji,MINI_APP_NAMESPACE:Ji,USER_AGENT:Di,base16EncodeBinaryString:AA,deepCopyWithMethods:On,deepMerge:U,generatePromise:Tr,getPlatformType:Lo,getType:g,httpRequest:$t,isArray:B,isArrayOrObject:f,isEmpty:$r,isH5:Xo,isIOSWebView:sr,isNumber:C=>C!==null&&(typeof C=="number"&&!Number.isNaN(C-0)||typeof C=="object"&&C.constructor===Number),isObject:Q,isPlainObject:M,isString:s,isUndefined:r,isUniIOSApp:function(){return Ur&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:m,platform:MA,randomInt:v,randomString:function(){const C="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let E="";for(let h=32;h>0;--h)E+=C[Math.floor(62*Math.random())];return E},safeStringify:An});class jr{constructor(){this.listeners={}}on(E,h,D){this.listeners[E]||(this.listeners[E]=[]),this.listeners[E].push({fn:h,context:D})}off(E,h,D){var N;h&&(this.listeners[E]=(N=this.listeners[E])===null||N===void 0?void 0:N.filter(O=>{const Y=O.fn===h,j=!D||O.context===D;return!(Y&&j)}))}emit(E,...h){const D=this.listeners[E];D&&D.forEach(N=>{const{fn:O,context:Y}=N;try{O.apply(Y,h)}catch(j){console.warn(`Error in event handler for ${E} error: ${An(j)}`)}})}once(E,h,D){const N=(...O)=>{h.apply(D,O),this.off(E,N)};this.on(E,N)}}(function(C){C.BUSINESS_COMMAND="business_command",C.C2C_REALTIME_MESSAGE="c2c_realtime_message",C.C2C_MESSAGE_MODIFIED="c2c_message_modified",C.C2C_REVOKED_MESSAGE="c2c_message_revoked",C.GROUP_REALTIME_MESSAGE="group_realtime_message",C.GROUP_MESSAGE_MODIFIED="group_message_modified",C.GROUP_MESSAGE_REVOKED="group_message_revoked",C.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",C.MESSAGE_REACTION_UPDATED="message_reaction_updated",C.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",C.GROUP_AT_TIPS="group_at_tips",C.USER_STATUS_UPDATE="user_status_update",C.FRIEND_LIST_MODIFIED="friend_list_modified",C.PROFILE_MODIFIED="profile_modified",C.CONV_MODIFIED="conversation_modified",C.GROUP_TIPS_NOTIFICATION="group_tips_notification",C.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",C.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",C.GROUP_SYSTEM_NOTIFICATION="group_system_notification",C.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",C.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",C.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",C.FOLLOW_LIST_UPDATED="follow_list_updated",C.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",C.ALL_MESSAGE_READ="all_message_read",C.CONVERSATION_MARK_UPDATED="conversation_mark_updated",C.CONVERSATION_GROUP_ADD="conversation_group_add",C.CONVERSATION_GROUP_DELETED="conversation_group_deleted",C.CONVERSATION_GROUP_UPDATED="conversation_group_updated",C.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",C.TOPIC_AT_TIPS="topic_at_tips",C.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",C.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",C.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",C.TOPIC_LATEST_MESSAGE="topic_latest_message",C.GROUP_MESSAGE_PINNED="group_message_pinned"})(ei||(ei={}));const Gr=[16,17];function $o(C){var E;const h=[];return(E=C?.GroupTips)===null||E===void 0||E.forEach(D=>{var N;D.GroupInfo.MillionGroupFlag===2?h.push(ei.TOPIC_TIPS_NOTIFICATION):Gr.includes((N=D?.MsgBody)===null||N===void 0?void 0:N.OpType)?h.push(ei.GROUP_MESSAGE_PINNED):h.push(ei.GROUP_TIPS_NOTIFICATION)}),h}const sn=[{conditions:[{type:"event",value:100}],subType:ei.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:ei.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:ei.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:ei.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:ei.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:ei.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:ei.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:ei.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:ei.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:ei.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(C){var E;const h=[];return(E=C?.C2cNotifyMsgArray)===null||E===void 0||E.forEach(D=>{D.WithdrawC2cMsgNotify&&h.push(ei.C2C_REVOKED_MESSAGE),D.C2cReadedReceipt&&h.push(ei.C2C_MESSAGE_PEER_READ),D.ReadC2cMsgNotify&&h.push(ei.C2C_MESSAGE_READ_SYNC),D.MuteNotificationsSync&&h.push(ei.C2C_REMIND_TYPE_SYNC)}),h}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:$o},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(C){var E;const h=[];return(E=C?.GroupTips)===null||E===void 0||E.forEach(D=>{Array.isArray(D.MsgBody.GroupWithdrawInfoArray)?h.push(ei.GROUP_MESSAGE_REVOKED):Array.isArray(D.MsgBody.GroupMsgReceiptList)?h.push(ei.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(D.MsgBody.GroupReadInfoArray)?D.MsgBody.GroupReadInfoArray[0].TopicId?h.push(ei.TOPIC_MESSAGE_READ_SYNC):h.push(ei.GROUP_MESSAGE_READ_SYNC):D.GroupInfo.MillionGroupFlag===2?h.push(ei.TOPIC_SYSTEM_NOTIFICATION):h.push(ei.GROUP_SYSTEM_NOTIFICATION)}),h}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:$o},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(C){var E;const h=[];return(E=C?.GroupTips)===null||E===void 0||E.forEach(D=>{const{GroupAtTips:{TopicId:N}}=D;N?h.push(ei.TOPIC_AT_TIPS):h.push(ei.GROUP_AT_TIPS)}),h}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(C){var E;const h=[];return(E=C?.RecentContactMod)===null||E===void 0||E.forEach(D=>{switch(D.PushType){case Me.CONV_MARK_UPDATED:h.push(ei.CONVERSATION_MARK_UPDATED);break;case Me.CONV_GROUP_ADDED:h.push(ei.CONVERSATION_GROUP_ADD);break;case Me.CONV_GROUP_DELETED:h.push(ei.CONVERSATION_GROUP_DELETED);break;case Me.CONV_GROUP_UPDATED:h.push(ei.CONVERSATION_GROUP_UPDATED);break;default:h.push(ei.CONV_MODIFIED)}}),h}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:ei.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:ei.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:ei.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:ei.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:ei.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:ei.ALL_MESSAGE_READ}];var dn;function hn(C){var E;const h=Array.isArray((E=C?.body)===null||E===void 0?void 0:E.EventArray)?C.body.EventArray:[],D=[];return h.forEach(N=>{N.Flag=C.body.Flag;const O=sn.find(j=>j.conditions.every(IA=>{switch(IA.type){case"event":return N.Event===IA.value;case"hasKey":return Object.prototype.hasOwnProperty.call(N,IA.value);default:return!1}}));if(!O)return null;let Y=[];typeof O.subTypeParser=="function"?Y=O.subTypeParser(N):O.subType&&(Y=O.subType),Array.isArray(Y)?Y.forEach(j=>{D.push({type:`${dn.SERVER_PUSH_MESSAGE}:${j}`,data:N})}):D.push({type:`${dn.SERVER_PUSH_MESSAGE}:${Y}`,data:N})}),D}(function(C){C.SERVER_PUSH_MESSAGE="im_open_push.msg_push",C.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",C.ERROR="error"})(dn||(dn={}));const Gi={[dn.SERVER_PUSH_MESSAGE]:hn,[dn.SERVER_PUSH_MESSAGE_MULTIPLE]:hn,[dn.ERROR]:function(C){const{errorCode:E}=C;return[{type:`error:${E}`,data:C}]}},pn=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._filteredCallbackMap=new Map,this._outerEventEmitter=new jr,this._innerEventEmitter=new jr,this.InnerEventSubType=ei}subscribeInnerEvent(C,E,h,D,N){var O;let Y,j,IA,BA;["string","number"].includes(typeof E)?(IA=`${C}:${E}`,BA=h,j=D,Y=N):(IA=C,BA=E,j=h,Y=typeof D=="function"?D:void 0),Y?this._subscribeWithFilter(IA,BA,j,Y):(O=this._innerEventEmitter)===null||O===void 0||O.on(IA,BA,j)}emitInnerEvent(C,E){var h,D;if((h=this._innerEventEmitter)===null||h===void 0||h.emit(C,E),Object.keys(Gi).includes(C)){const N=(D=Gi[C])===null||D===void 0?void 0:D.call(Gi,E);N?.forEach(O=>{var Y;O&&((Y=this._innerEventEmitter)===null||Y===void 0||Y.emit(O.type,O.data))})}}subscribeOuterEvent(C,E,h){var D;(D=this._outerEventEmitter)===null||D===void 0||D.on(C,E,h)}unSubscribeOuterEvent(C,E,h){var D;(D=this._outerEventEmitter)===null||D===void 0||D.off(C,E,h)}unSubscribeInnerEvent(C,E,h,D){if(["string","number"].includes(typeof E)){const N=h,O=`${C}:${E}`;this._unsubscribeEvent(O,N,D)}else{const N=E;this._unsubscribeEvent(C,N,h)}}emitOuterEvent(C,E){var h;(h=this._outerEventEmitter)===null||h===void 0||h.emit(C,E)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}_subscribeWithFilter(C,E,h,D){var N;const O=Y=>{D.call(h,Y)&&E.call(h,Y)};this._filteredCallbackMap.has(C)||this._filteredCallbackMap.set(C,[]),this._filteredCallbackMap.get(C).push({originalCallback:E,filteredCallback:O,filter:D,context:h}),(N=this._innerEventEmitter)===null||N===void 0||N.on(C,O,h)}_unsubscribeEvent(C,E,h){var D,N;const O=this._filteredCallbackMap.get(C);if(O){const Y=O.findIndex(j=>j.originalCallback===E&&j.context===h);if(Y!==-1){const{filteredCallback:j}=O[Y];return(D=this._innerEventEmitter)===null||D===void 0||D.off(C,j,h),O.splice(Y,1),void(O.length===0&&this._filteredCallbackMap.delete(C))}}(N=this._innerEventEmitter)===null||N===void 0||N.off(C,E,h)}};class nI{constructor(){this._socket=null}connectSocket(E){return this._socket=new WebSocket(E),this._socket}send(E){var h,D;try{(h=this._socket)===null||h===void 0||h.send(E)}catch(N){(D=this._onSendFail)===null||D===void 0||D.call(this,N)}}bindSocketHandlers(E){const{onOpen:h,onMessage:D,onClose:N,onError:O,onSendFail:Y}=E;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=h,this._socket.onmessage=D,this._socket.onclose=N,this._socket.onerror=O,this._onSendFail=Y)}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 gr{constructor(E){this._onError=E.onError}connectSocket(E){const h=this;return this._socket=Ji.connectSocket({url:E,header:{"content-type":"application/json"},complete:()=>{},fail:D=>h._onError(D)}),this._socket}send(E){var h;(h=this._socket)===null||h===void 0||h.send({data:E,fail:this._onSendFail})}bindSocketHandlers(E){const{onOpen:h,onMessage:D,onClose:N,onError:O,onSendFail:Y}=E;this._socket&&(this._socket.onClose(N),this._socket.onOpen(h),this._socket.onMessage(D),this._socket.onError(O),this._onSendFail=Y)}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 gn="CONNECT",Yo="SEND",Tg="DISCONNECT",So="OPEN",ao="MESSAGE",EE="CLOSE",Ta="ERROR",po="SEND_FAIL";class Ja{constructor(){this._worker=null,this._blobUrl=null}connectSocket(E){const h=new Blob([` +**/let wj;const A5=typeof window<"u"&&window.trustedTypes;if(A5)try{wj=A5.createPolicy("vue",{createHTML:t=>t})}catch{}const jZ=wj?t=>wj.createHTML(t):t=>t,rrA="http://www.w3.org/2000/svg",nrA="http://www.w3.org/1998/Math/MathML",od=typeof document<"u"?document:null,e5=od&&od.createElement("template"),arA={insert:(t,i,r)=>{i.insertBefore(t,r||null)},remove:t=>{const i=t.parentNode;i&&i.removeChild(t)},createElement:(t,i,r,s)=>{const g=i==="svg"?od.createElementNS(rrA,t):i==="mathml"?od.createElementNS(nrA,t):r?od.createElement(t,{is:r}):od.createElement(t);return t==="select"&&s&&s.multiple!=null&&g.setAttribute("multiple",s.multiple),g},createText:t=>od.createTextNode(t),createComment:t=>od.createComment(t),setText:(t,i)=>{t.nodeValue=i},setElementText:(t,i)=>{t.textContent=i},parentNode:t=>t.parentNode,nextSibling:t=>t.nextSibling,querySelector:t=>od.querySelector(t),setScopeId(t,i){t.setAttribute(i,"")},insertStaticContent(t,i,r,s,g,B){const Q=r?r.previousSibling:i.lastChild;if(g&&(g===B||g.nextSibling))for(;i.insertBefore(g.cloneNode(!0),r),!(g===B||!(g=g.nextSibling)););else{e5.innerHTML=jZ(s==="svg"?`${t}`:s==="mathml"?`${t}`:t);const f=e5.content;if(s==="svg"||s==="mathml"){const m=f.firstChild;for(;m.firstChild;)f.appendChild(m.firstChild);f.removeChild(m)}i.insertBefore(f,r)}return[Q?Q.nextSibling:i.firstChild,r?r.previousSibling:i.lastChild]}},rp="transition",uG="animation",Ck=Symbol("_vtc"),WZ={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},srA=Sg({},hZ,WZ),grA=t=>(t.displayName="Transition",t.props=srA,t),IrA=grA((t,{slots:i})=>orA(toA,crA(t),i)),Vm=(t,i=[])=>{Ro(t)?t.forEach(r=>r(...i)):t&&t(...i)},t5=t=>t?Ro(t)?t.some(i=>i.length>1):t.length>1:!1;function crA(t){const i={};for(const Je in t)Je in WZ||(i[Je]=t[Je]);if(t.css===!1)return i;const{name:r="v",type:s,duration:g,enterFromClass:B=`${r}-enter-from`,enterActiveClass:Q=`${r}-enter-active`,enterToClass:f=`${r}-enter-to`,appearFromClass:m=B,appearActiveClass:M=Q,appearToClass:v=f,leaveFromClass:U=`${r}-leave-from`,leaveActiveClass:AA=`${r}-leave-active`,leaveToClass:z=`${r}-leave-to`}=t,sA=ErA(g),eA=sA&&sA[0],X=sA&&sA[1],{onBeforeEnter:QA,onEnter:wA,onEnterCancelled:HA,onLeave:qA,onLeaveCancelled:ue,onBeforeAppear:jA=QA,onAppear:Ve=wA,onAppearCancelled:ze=HA}=i,Me=(Je,$e,Dt,Zi)=>{Je._enterCancelled=Zi,qm(Je,$e?v:f),qm(Je,$e?M:Q),Dt&&Dt()},qe=(Je,$e)=>{Je._isLeaving=!1,qm(Je,U),qm(Je,z),qm(Je,AA),$e&&$e()},Et=Je=>($e,Dt)=>{const Zi=Je?Ve:wA,bi=()=>Me($e,Je,Dt);Vm(Zi,[$e,bi]),i5(()=>{qm($e,Je?m:B),Ad($e,Je?v:f),t5(Zi)||o5($e,s,eA,bi)})};return Sg(i,{onBeforeEnter(Je){Vm(QA,[Je]),Ad(Je,B),Ad(Je,Q)},onBeforeAppear(Je){Vm(jA,[Je]),Ad(Je,m),Ad(Je,M)},onEnter:Et(!1),onAppear:Et(!0),onLeave(Je,$e){Je._isLeaving=!0;const Dt=()=>qe(Je,$e);Ad(Je,U),Je._enterCancelled?(Ad(Je,AA),a5()):(a5(),Ad(Je,AA)),i5(()=>{Je._isLeaving&&(qm(Je,U),Ad(Je,z),t5(qA)||o5(Je,s,X,Dt))}),Vm(qA,[Je,Dt])},onEnterCancelled(Je){Me(Je,!1,void 0,!0),Vm(HA,[Je])},onAppearCancelled(Je){Me(Je,!0,void 0,!0),Vm(ze,[Je])},onLeaveCancelled(Je){qe(Je),Vm(ue,[Je])}})}function ErA(t){if(t==null)return null;if(ta(t))return[TK(t.enter),TK(t.leave)];{const i=TK(t);return[i,i]}}function TK(t){return giA(t)}function Ad(t,i){i.split(/\s+/).forEach(r=>r&&t.classList.add(r)),(t[Ck]||(t[Ck]=new Set)).add(i)}function qm(t,i){i.split(/\s+/).forEach(s=>s&&t.classList.remove(s));const r=t[Ck];r&&(r.delete(i),r.size||(t[Ck]=void 0))}function i5(t){requestAnimationFrame(()=>{requestAnimationFrame(t)})}let lrA=0;function o5(t,i,r,s){const g=t._endId=++lrA,B=()=>{g===t._endId&&s()};if(r!=null)return setTimeout(B,r);const{type:Q,timeout:f,propCount:m}=CrA(t,i);if(!Q)return s();const M=Q+"end";let v=0;const U=()=>{t.removeEventListener(M,AA),B()},AA=z=>{z.target===t&&++v>=m&&U()};setTimeout(()=>{v(r[sA]||"").split(", "),g=s(`${rp}Delay`),B=s(`${rp}Duration`),Q=r5(g,B),f=s(`${uG}Delay`),m=s(`${uG}Duration`),M=r5(f,m);let v=null,U=0,AA=0;i===rp?Q>0&&(v=rp,U=Q,AA=B.length):i===uG?M>0&&(v=uG,U=M,AA=m.length):(U=Math.max(Q,M),v=U>0?Q>M?rp:uG:null,AA=v?v===rp?B.length:m.length:0);const z=v===rp&&/\b(transform|all)(,|$)/.test(s(`${rp}Property`).toString());return{type:v,timeout:U,propCount:AA,hasTransform:z}}function r5(t,i){for(;t.lengthn5(r)+n5(t[s])))}function n5(t){return t==="auto"?0:Number(t.slice(0,-1).replace(",","."))*1e3}function a5(){return document.body.offsetHeight}function BrA(t,i,r){const s=t[Ck];s&&(i=(i?[i,...s]:[...s]).join(" ")),i==null?t.removeAttribute("class"):r?t.setAttribute("class",i):t.className=i}const H2=Symbol("_vod"),zZ=Symbol("_vsh"),sa={beforeMount(t,{value:i},{transition:r}){t[H2]=t.style.display==="none"?"":t.style.display,r&&i?r.beforeEnter(t):QG(t,i)},mounted(t,{value:i},{transition:r}){r&&i&&r.enter(t)},updated(t,{value:i,oldValue:r},{transition:s}){!i!=!r&&(s?i?(s.beforeEnter(t),QG(t,!0),s.enter(t)):s.leave(t,()=>{QG(t,!1)}):QG(t,i))},beforeUnmount(t,{value:i}){QG(t,i)}};function QG(t,i){t.style.display=i?t[H2]:"none",t[zZ]=!i}const urA=Symbol(""),QrA=/(^|;)\s*display\s*:/;function drA(t,i,r){const s=t.style,g=va(r);let B=!1;if(r&&!g){if(i)if(va(i))for(const Q of i.split(";")){const f=Q.slice(0,Q.indexOf(":")).trim();r[f]==null&&y2(s,f,"")}else for(const Q in i)r[Q]==null&&y2(s,Q,"");for(const Q in r)Q==="display"&&(B=!0),y2(s,Q,r[Q])}else if(g){if(i!==r){const Q=s[urA];Q&&(r+=";"+Q),s.cssText=r,B=QrA.test(r)}}else i&&t.removeAttribute("style");H2 in t&&(t[H2]=B?s.display:"",t[zZ]&&(s.display="none"))}const s5=/\s*!important$/;function y2(t,i,r){if(Ro(r))r.forEach(s=>y2(t,i,s));else if(r==null&&(r=""),i.startsWith("--"))t.setProperty(i,r);else{const s=hrA(t,i);s5.test(r)?t.setProperty(vp(s),r.replace(s5,""),"important"):t[s]=r}}const g5=["Webkit","Moz","ms"],GK={};function hrA(t,i){const r=GK[i];if(r)return r;let s=mC(i);if(s!=="filter"&&s in t)return GK[i]=s;s=uY(s);for(let g=0;gkK||(yrA.then(()=>kK=0),kK=Date.now());function MrA(t,i){const r=s=>{if(!s._vts)s._vts=Date.now();else if(s._vts<=r.attached)return;uB(wrA(s,r.value),i,5,[s])};return r.value=t,r.attached=RrA(),r}function wrA(t,i){if(Ro(i)){const r=t.stopImmediatePropagation;return t.stopImmediatePropagation=()=>{r.call(t),t._stopped=!0},i.map(s=>g=>!g._stopped&&s&&s(g))}else return i}const B5=t=>t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&t.charCodeAt(2)>96&&t.charCodeAt(2)<123,SrA=(t,i,r,s,g,B)=>{const Q=g==="svg";i==="class"?BrA(t,s,Q):i==="style"?drA(t,r,s):lY(i)?n3(i)||mrA(t,i,r,s,B):(i[0]==="."?(i=i.slice(1),!0):i[0]==="^"?(i=i.slice(1),!1):vrA(t,i,s,Q))?(E5(t,i,s),!t.tagName.includes("-")&&(i==="value"||i==="checked"||i==="selected")&&c5(t,i,s,Q,B,i!=="value")):t._isVueCE&&(/[A-Z]/.test(i)||!va(s))?E5(t,mC(i),s,B,i):(i==="true-value"?t._trueValue=s:i==="false-value"&&(t._falseValue=s),c5(t,i,s,Q))};function vrA(t,i,r,s){if(s)return!!(i==="innerHTML"||i==="textContent"||i in t&&B5(i)&&xo(r));if(i==="spellcheck"||i==="draggable"||i==="translate"||i==="form"||i==="list"&&t.tagName==="INPUT"||i==="type"&&t.tagName==="TEXTAREA")return!1;if(i==="width"||i==="height"){const g=t.tagName;if(g==="IMG"||g==="VIDEO"||g==="CANVAS"||g==="SOURCE")return!1}return B5(i)&&va(r)?!1:i in t}const NrA=["ctrl","shift","alt","meta"],TrA={stop:t=>t.stopPropagation(),prevent:t=>t.preventDefault(),self:t=>t.target!==t.currentTarget,ctrl:t=>!t.ctrlKey,shift:t=>!t.shiftKey,alt:t=>!t.altKey,meta:t=>!t.metaKey,left:t=>"button"in t&&t.button!==0,middle:t=>"button"in t&&t.button!==1,right:t=>"button"in t&&t.button!==2,exact:(t,i)=>NrA.some(r=>t[`${r}Key`]&&!i.includes(r))},ul=(t,i)=>{const r=t._withMods||(t._withMods={}),s=i.join(".");return r[s]||(r[s]=(g,...B)=>{for(let Q=0;Q{const r=t._withKeys||(t._withKeys={}),s=i.join(".");return r[s]||(r[s]=g=>{if(!("key"in g))return;const B=vp(g.key);if(i.some(Q=>Q===B||GrA[Q]===B))return t(g)})},_rA=Sg({patchProp:SrA},arA);let u5;function ZZ(){return u5||(u5=ToA(_rA))}const aD=(...t)=>{ZZ().render(...t)},brA=(...t)=>{const i=ZZ().createApp(...t),{mount:r}=i;return i.mount=s=>{const g=FrA(s);if(!g)return;const B=i._component;!xo(B)&&!B.render&&!B.template&&(B.template=g.innerHTML),g.nodeType===1&&(g.textContent="");const Q=r(g,!1,LrA(g));return g instanceof Element&&(g.removeAttribute("v-cloak"),g.setAttribute("data-v-app","")),Q},i};function LrA(t){if(t instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&t instanceof MathMLElement)return"mathml"}function FrA(t){return va(t)?document.querySelector(t):t}var bI=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function XZ(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Mk(t){if(t.__esModule)return t;var i=t.default;if(typeof i=="function"){var r=function s(){return this instanceof s?Reflect.construct(i,arguments,this.constructor):i.apply(this,arguments)};r.prototype=i.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(s){var g=Object.getOwnPropertyDescriptor(t,s);Object.defineProperty(r,s,g.get?g:{enumerable:!0,get:function(){return t[s]}})}),r}function UrA(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var yG={exports:{}},R2={exports:{}},OrA=R2.exports,Q5;function $Z(){return Q5||(Q5=1,function(t,i){(function(r,s){t.exports=s()})(OrA,function(){const r=C=>C===void 0,s=C=>typeof C=="string",g=C=>{var E;return(E=Object.prototype.toString.call(C).match(/^\[object (.*)\]$/))===null||E===void 0?void 0:E[1].toLowerCase()},B=C=>typeof Array.isArray=="function"?Array.isArray(C):g(C)==="array",Q=C=>C!==null&&typeof C=="object",f=C=>B(C)||Q(C),m=C=>{if(typeof C!="string")return!1;const E=C[0];return!/[^a-zA-Z0-9]/.test(E)},M=C=>{if(typeof C!="object"||C===null)return!1;const E=Object.getPrototypeOf(C);if(E===null)return!0;let h=E;for(;Object.getPrototypeOf(h)!==null;)h=Object.getPrototypeOf(h);return E===h};function v(C=99999999){return Math.round(Math.random()*C)}const U=(C,E,h,D)=>{if(!f(C)||!f(E))return 0;let N=0;const O=Object.keys(E);let Y;for(let j=0,IA=O.length;j"u"&&typeof uni.requireNativePlugin=="function",Er=Je&&typeof wx.miniapp=="object",no=typeof uni<"u",Kn=Zi&&typeof tt.enterChat=="function",Xi=Je||Dt||Zi||qt||ai||Ur||Ki,yr=typeof window>"u"&&!Xi&&typeof bI<"u"&&bI.NativeScriptGlobals!==void 0,lr=typeof bI<"u"&&(bI.nativeModuleProxy!==void 0||bI.ReactNative!==void 0),Ni=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,wt=typeof uni<"u"?!Xi:typeof window<"u"&&!Xi&&!lr,Ji=Dt?qq:Zi?tt:qt?swan:ai?my:Je?wx:Ur?uni:Ki?jd:{},Di=wt&&window&&window.navigator&&window.navigator.userAgent||"",ar=/(micromessenger|webbrowser)/i.test(Di),MA=function(){let C="WEB";return ar?C="WEB":Dt?C="QQ_MP":Zi?C="TT_MP":qt?C="BAIDU_MP":ai?C="ALI_MP":Je?C=Er?"DONUT_NATIVE_APP":"WX_MP":Ur?C="UNI_NATIVE_APP":yr?C="NS_NATIVE_APP":lr&&(C="RN_NATIVE_APP"),z[C]}(),YA=/iPad/i.test(Di),pe=/iPhone/i.test(Di)&&!YA,st=/iPod/i.test(Di),Te=pe||YA||st,be=function(){const C=Di.match(/OS (\d+)_/i);return C&&C[1]?C[1]:null}(),yt=/Android/i.test(Di),ht=function(){const C=Di.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!C)return null;const E=C[1]&&parseFloat(C[1]),h=C[2]&&parseFloat(C[2]);return E&&h?parseFloat(`${C[1]}.${C[2]}`):E||null}(),ae=/Firefox/i.test(Di),ye=/Edge/i.test(Di),Xe=!ye&&/Chrome/i.test(Di),ot=/MSIE/.test(Di)||Di.indexOf("Trident")>-1&&Di.indexOf("rv:11.0")>-1,zt=function(){const C=/MSIE\s(\d+)\.\d/.exec(Di);let E=C&&parseFloat(C[1]);return!E&&/Trident\/7.0/i.test(Di)&&/rv:11.0/.test(Di)&&(E=11),E}(),yi=/Safari/i.test(Di)&&!Xe&&!yt&&!ye,Hi=/Windows/i.test(Di),Ei=/MAC OS X/i.test(Di),ji=wt&&typeof Worker<"u"&&!ot,Xo=yt||Te,sr=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:C}=window.navigator;return!(!Te||C||yi)}();function Lo(){let C="unknown";if(Ei&&(C="mac"),Hi&&(C="windows"),Te&&(C="ios"),yt&&(C="android"),Xi)try{const{platform:E}=Ji.getSystemInfoSync();E!==void 0&&(C=E)}catch(E){console.error(E)}return C}const Nr=typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0&&typeof window>"u";function Vo(C,E){var h={};for(var D in C)Object.prototype.hasOwnProperty.call(C,D)&&E.indexOf(D)<0&&(h[D]=C[D]);if(C!=null&&typeof Object.getOwnPropertySymbols=="function"){var N=0;for(D=Object.getOwnPropertySymbols(C);N{Ji.request({url:h,data:D,method:E,timeout:N,header:{"content-type":jn},success:j=>O(j.data),fail:()=>Y(new Error(`{"message":"Network error","code":${Kr}}`))})}):Nr?void 0:new Promise((O,Y)=>{const j=new XMLHttpRequest,IA=setTimeout(()=>{j.abort(),Y(new Error(`{"message":"Request timeout","code":${Qn}}`))},N);j.onreadystatechange=function(){if(j.readyState===4)if(clearTimeout(IA),j.status===200||j.status===304)try{O(j.responseText?JSON.parse(j.responseText):null)}catch{O(j.responseText)}else Y(new Error(`{"message":"Network error","code":${Kr}}`))},j.open(E,h,!0),j.setRequestHeader("Content-type",jn),j.send(D||null)})})}function $r(C){if(C==null)return!0;if(typeof C=="boolean")return!1;if(typeof C=="number")return C===0;if(typeof C=="string"||typeof C=="function"||Array.isArray(C))return C.length===0;if(C instanceof Error)return C.message==="";if(M(C)){for(const E in C)if(Object.prototype.hasOwnProperty.call(C,E))return!1;return!0}return(Object.prototype.toString.call(C)==="[object Map]"||Object.prototype.toString.call(C)==="[object Set]"||Object.prototype.toString.call(C)==="[object File]")&&C.size===0}function On(C,E){if(C===null||typeof C!="object")return C;const h=E||new WeakMap;if(h.has(C))return h.get(C);if(C instanceof Date)return new Date(C.getTime());if(C instanceof RegExp)return new RegExp(C.source,C.flags);if(C instanceof Map){const O=new Map;return h.set(C,O),C.forEach((Y,j)=>{O.set(On(j,h),On(Y,h))}),O}if(C instanceof Set){const O=new Set;return h.set(C,O),C.forEach(Y=>{O.add(On(Y,h))}),O}if(Array.isArray(C)){const O=[];return h.set(C,O),C.forEach(Y=>{O.push(On(Y,h))}),O}const D=Object.getPrototypeOf(C),N=Object.create(D);return h.set(C,N),[...Object.getOwnPropertyNames(C),...Object.getOwnPropertySymbols(C)].forEach(O=>{if(O==="__ob__"||O==="__v_skip"||O==="__v_isRef"||O==="__v_isReadonly")return;const Y=Object.getOwnPropertyDescriptor(C,O);Y&&(Y.get||Y.set?Object.defineProperty(N,O,Y):N[O]=On(C[O],h))}),N}function An(C,E,h){const D=new WeakSet,N=(O,Y)=>{if(E&&(Y=E(O,Y)),Y===void 0)return"undefined";if(Y===null)return null;if(Number.isNaN(Y))return"NaN";if(Y===1/0)return"Infinity";if(Y===-1/0)return"-Infinity";if(typeof Y=="function")return`[Function: ${Y.name||"anonymous"}]`;if(typeof Y=="symbol")return Y.toString();if(typeof Y=="bigint")return`${Y.toString()}n`;if(typeof Y=="object"&&Y!==null){if(D.has(Y))return"[Circular]";D.add(Y)}return Y instanceof Date?Y.toISOString():Y instanceof Error?{name:Y.name,message:Y.message}:Y instanceof Map?{dataType:"Map",value:Array.from(Y.entries())}:Y instanceof Set?{dataType:"Set",value:Array.from(Y.values())}:Y};try{return JSON.stringify(C,N,h)}catch(O){return console.error("Failed to stringify:",O),""}}function Tr(){let C,E;return{promise:new Promise((h,D)=>{C=h,E=D}),resolve:C,reject:E}}var ei,Es=Object.freeze({__proto__:null,ANDROID_VERSION:ht,IE_VERSION:zt,IN_ALIPAY_MINI_APP:ai,IN_BAIDU_MINI_APP:qt,IN_BROWSER:wt,IN_DONUT_NATIVE_APP:Er,IN_FEISHU_MINI_APP:Kn,IN_JD_MINI_APP:Ki,IN_MINI_APP:Xi,IN_NODE:Nr,IN_NS_NATIVE_APP:yr,IN_QQ_MINI_APP:Dt,IN_RN_APP:lr,IN_TT_MINI_APP:Zi,IN_TT_MINI_GAME:bi,IN_UNI_APP:no,IN_UNI_NATIVE_APP:Ur,IN_WX_MINI_APP:Je,IN_WX_MINI_APP_DESK:Et,IN_WX_MINI_GAME:$e,IN_WX_MINI_PLUGIN:Ni,IOS_VERSION:be,IS_ANDROID:yt,IS_CHROME:Xe,IS_EDGE:ye,IS_FIREFOX:ae,IS_IE:ot,IS_IOS:Te,IS_IPAD:YA,IS_IPHONE:pe,IS_IPOD:st,IS_MAC:Ei,IS_SAFARI:yi,IS_WECHAT:ar,IS_WIN:Hi,IS_WORKER_AVAILABLE:ji,MINI_APP_NAMESPACE:Ji,USER_AGENT:Di,base16EncodeBinaryString:AA,deepCopyWithMethods:On,deepMerge:U,generatePromise:Tr,getPlatformType:Lo,getType:g,httpRequest:$t,isArray:B,isArrayOrObject:f,isEmpty:$r,isH5:Xo,isIOSWebView:sr,isNumber:C=>C!==null&&(typeof C=="number"&&!Number.isNaN(C-0)||typeof C=="object"&&C.constructor===Number),isObject:Q,isPlainObject:M,isString:s,isUndefined:r,isUniIOSApp:function(){return Ur&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:m,platform:MA,randomInt:v,randomString:function(){const C="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let E="";for(let h=32;h>0;--h)E+=C[Math.floor(62*Math.random())];return E},safeStringify:An});class jr{constructor(){this.listeners={}}on(E,h,D){this.listeners[E]||(this.listeners[E]=[]),this.listeners[E].push({fn:h,context:D})}off(E,h,D){var N;h&&(this.listeners[E]=(N=this.listeners[E])===null||N===void 0?void 0:N.filter(O=>{const Y=O.fn===h,j=!D||O.context===D;return!(Y&&j)}))}emit(E,...h){const D=this.listeners[E];D&&D.forEach(N=>{const{fn:O,context:Y}=N;try{O.apply(Y,h)}catch(j){console.warn(`Error in event handler for ${E} error: ${An(j)}`)}})}once(E,h,D){const N=(...O)=>{h.apply(D,O),this.off(E,N)};this.on(E,N)}}(function(C){C.BUSINESS_COMMAND="business_command",C.C2C_REALTIME_MESSAGE="c2c_realtime_message",C.C2C_MESSAGE_MODIFIED="c2c_message_modified",C.C2C_REVOKED_MESSAGE="c2c_message_revoked",C.GROUP_REALTIME_MESSAGE="group_realtime_message",C.GROUP_MESSAGE_MODIFIED="group_message_modified",C.GROUP_MESSAGE_REVOKED="group_message_revoked",C.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",C.MESSAGE_REACTION_UPDATED="message_reaction_updated",C.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",C.GROUP_AT_TIPS="group_at_tips",C.USER_STATUS_UPDATE="user_status_update",C.FRIEND_LIST_MODIFIED="friend_list_modified",C.PROFILE_MODIFIED="profile_modified",C.CONV_MODIFIED="conversation_modified",C.GROUP_TIPS_NOTIFICATION="group_tips_notification",C.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",C.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",C.GROUP_SYSTEM_NOTIFICATION="group_system_notification",C.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",C.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",C.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",C.FOLLOW_LIST_UPDATED="follow_list_updated",C.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",C.ALL_MESSAGE_READ="all_message_read",C.CONVERSATION_MARK_UPDATED="conversation_mark_updated",C.CONVERSATION_GROUP_ADD="conversation_group_add",C.CONVERSATION_GROUP_DELETED="conversation_group_deleted",C.CONVERSATION_GROUP_UPDATED="conversation_group_updated",C.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",C.TOPIC_AT_TIPS="topic_at_tips",C.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",C.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",C.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",C.TOPIC_LATEST_MESSAGE="topic_latest_message",C.GROUP_MESSAGE_PINNED="group_message_pinned"})(ei||(ei={}));const Gr=[16,17];function $o(C){var E;const h=[];return(E=C?.GroupTips)===null||E===void 0||E.forEach(D=>{var N;D.GroupInfo.MillionGroupFlag===2?h.push(ei.TOPIC_TIPS_NOTIFICATION):Gr.includes((N=D?.MsgBody)===null||N===void 0?void 0:N.OpType)?h.push(ei.GROUP_MESSAGE_PINNED):h.push(ei.GROUP_TIPS_NOTIFICATION)}),h}const sn=[{conditions:[{type:"event",value:100}],subType:ei.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:ei.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:ei.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:ei.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:ei.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:ei.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:ei.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:ei.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:ei.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:ei.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(C){var E;const h=[];return(E=C?.C2cNotifyMsgArray)===null||E===void 0||E.forEach(D=>{D.WithdrawC2cMsgNotify&&h.push(ei.C2C_REVOKED_MESSAGE),D.C2cReadedReceipt&&h.push(ei.C2C_MESSAGE_PEER_READ),D.ReadC2cMsgNotify&&h.push(ei.C2C_MESSAGE_READ_SYNC),D.MuteNotificationsSync&&h.push(ei.C2C_REMIND_TYPE_SYNC)}),h}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:$o},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(C){var E;const h=[];return(E=C?.GroupTips)===null||E===void 0||E.forEach(D=>{Array.isArray(D.MsgBody.GroupWithdrawInfoArray)?h.push(ei.GROUP_MESSAGE_REVOKED):Array.isArray(D.MsgBody.GroupMsgReceiptList)?h.push(ei.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(D.MsgBody.GroupReadInfoArray)?D.MsgBody.GroupReadInfoArray[0].TopicId?h.push(ei.TOPIC_MESSAGE_READ_SYNC):h.push(ei.GROUP_MESSAGE_READ_SYNC):D.GroupInfo.MillionGroupFlag===2?h.push(ei.TOPIC_SYSTEM_NOTIFICATION):h.push(ei.GROUP_SYSTEM_NOTIFICATION)}),h}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:$o},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(C){var E;const h=[];return(E=C?.GroupTips)===null||E===void 0||E.forEach(D=>{const{GroupAtTips:{TopicId:N}}=D;N?h.push(ei.TOPIC_AT_TIPS):h.push(ei.GROUP_AT_TIPS)}),h}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(C){var E;const h=[];return(E=C?.RecentContactMod)===null||E===void 0||E.forEach(D=>{switch(D.PushType){case Me.CONV_MARK_UPDATED:h.push(ei.CONVERSATION_MARK_UPDATED);break;case Me.CONV_GROUP_ADDED:h.push(ei.CONVERSATION_GROUP_ADD);break;case Me.CONV_GROUP_DELETED:h.push(ei.CONVERSATION_GROUP_DELETED);break;case Me.CONV_GROUP_UPDATED:h.push(ei.CONVERSATION_GROUP_UPDATED);break;default:h.push(ei.CONV_MODIFIED)}}),h}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:ei.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:ei.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:ei.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:ei.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:ei.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:ei.ALL_MESSAGE_READ}];var dn;function hn(C){var E;const h=Array.isArray((E=C?.body)===null||E===void 0?void 0:E.EventArray)?C.body.EventArray:[],D=[];return h.forEach(N=>{N.Flag=C.body.Flag;const O=sn.find(j=>j.conditions.every(IA=>{switch(IA.type){case"event":return N.Event===IA.value;case"hasKey":return Object.prototype.hasOwnProperty.call(N,IA.value);default:return!1}}));if(!O)return null;let Y=[];typeof O.subTypeParser=="function"?Y=O.subTypeParser(N):O.subType&&(Y=O.subType),Array.isArray(Y)?Y.forEach(j=>{D.push({type:`${dn.SERVER_PUSH_MESSAGE}:${j}`,data:N})}):D.push({type:`${dn.SERVER_PUSH_MESSAGE}:${Y}`,data:N})}),D}(function(C){C.SERVER_PUSH_MESSAGE="im_open_push.msg_push",C.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",C.ERROR="error"})(dn||(dn={}));const Gi={[dn.SERVER_PUSH_MESSAGE]:hn,[dn.SERVER_PUSH_MESSAGE_MULTIPLE]:hn,[dn.ERROR]:function(C){const{errorCode:E}=C;return[{type:`error:${E}`,data:C}]}},pn=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._filteredCallbackMap=new Map,this._outerEventEmitter=new jr,this._innerEventEmitter=new jr,this.InnerEventSubType=ei}subscribeInnerEvent(C,E,h,D,N){var O;let Y,j,IA,BA;["string","number"].includes(typeof E)?(IA=`${C}:${E}`,BA=h,j=D,Y=N):(IA=C,BA=E,j=h,Y=typeof D=="function"?D:void 0),Y?this._subscribeWithFilter(IA,BA,j,Y):(O=this._innerEventEmitter)===null||O===void 0||O.on(IA,BA,j)}emitInnerEvent(C,E){var h,D;if((h=this._innerEventEmitter)===null||h===void 0||h.emit(C,E),Object.keys(Gi).includes(C)){const N=(D=Gi[C])===null||D===void 0?void 0:D.call(Gi,E);N?.forEach(O=>{var Y;O&&((Y=this._innerEventEmitter)===null||Y===void 0||Y.emit(O.type,O.data))})}}subscribeOuterEvent(C,E,h){var D;(D=this._outerEventEmitter)===null||D===void 0||D.on(C,E,h)}unSubscribeOuterEvent(C,E,h){var D;(D=this._outerEventEmitter)===null||D===void 0||D.off(C,E,h)}unSubscribeInnerEvent(C,E,h,D){if(["string","number"].includes(typeof E)){const N=h,O=`${C}:${E}`;this._unsubscribeEvent(O,N,D)}else{const N=E;this._unsubscribeEvent(C,N,h)}}emitOuterEvent(C,E){var h;(h=this._outerEventEmitter)===null||h===void 0||h.emit(C,E)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}_subscribeWithFilter(C,E,h,D){var N;const O=Y=>{D.call(h,Y)&&E.call(h,Y)};this._filteredCallbackMap.has(C)||this._filteredCallbackMap.set(C,[]),this._filteredCallbackMap.get(C).push({originalCallback:E,filteredCallback:O,filter:D,context:h}),(N=this._innerEventEmitter)===null||N===void 0||N.on(C,O,h)}_unsubscribeEvent(C,E,h){var D,N;const O=this._filteredCallbackMap.get(C);if(O){const Y=O.findIndex(j=>j.originalCallback===E&&j.context===h);if(Y!==-1){const{filteredCallback:j}=O[Y];return(D=this._innerEventEmitter)===null||D===void 0||D.off(C,j,h),O.splice(Y,1),void(O.length===0&&this._filteredCallbackMap.delete(C))}}(N=this._innerEventEmitter)===null||N===void 0||N.off(C,E,h)}};class nI{constructor(){this._socket=null}connectSocket(E){return this._socket=new WebSocket(E),this._socket}send(E){var h,D;try{(h=this._socket)===null||h===void 0||h.send(E)}catch(N){(D=this._onSendFail)===null||D===void 0||D.call(this,N)}}bindSocketHandlers(E){const{onOpen:h,onMessage:D,onClose:N,onError:O,onSendFail:Y}=E;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=h,this._socket.onmessage=D,this._socket.onclose=N,this._socket.onerror=O,this._onSendFail=Y)}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 gr{constructor(E){this._onError=E.onError}connectSocket(E){const h=this;return this._socket=Ji.connectSocket({url:E,header:{"content-type":"application/json"},complete:()=>{},fail:D=>h._onError(D)}),this._socket}send(E){var h;(h=this._socket)===null||h===void 0||h.send({data:E,fail:this._onSendFail})}bindSocketHandlers(E){const{onOpen:h,onMessage:D,onClose:N,onError:O,onSendFail:Y}=E;this._socket&&(this._socket.onClose(N),this._socket.onOpen(h),this._socket.onMessage(D),this._socket.onError(O),this._onSendFail=Y)}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 gn="CONNECT",Yo="SEND",Tg="DISCONNECT",So="OPEN",ao="MESSAGE",lE="CLOSE",Ta="ERROR",po="SEND_FAIL";class Ja{constructor(){this._worker=null,this._blobUrl=null}connectSocket(E){const h=new Blob([` let _socket = null; self.onmessage = (event) => { @@ -111,11 +111,11 @@ _socket = null; } } -`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(h)),this._worker.postMessage({type:gn,url:E})}send(E){var h,D;try{(h=this._worker)===null||h===void 0||h.postMessage({type:Yo,data:E})}catch(N){(D=this._onSendFail)===null||D===void 0||D.call(this,N)}}bindSocketHandlers(E){const{onOpen:h,onMessage:D,onClose:N,onError:O,onSendFail:Y}=E;if(this._worker){const j={[So]:h,[ao]:D,[EE]:N,[Ta]:O,[po]:Y};this._onSendFail=Y,this._worker.onmessage=IA=>{var BA;const{type:mA}=IA?.data||{};typeof j[mA]=="function"&&((BA=j[mA])===null||BA===void 0||BA.call(j,IA?.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:Tg}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class Mc{}var Qr,Fo=new class{constructor(){this._store=new Map}get(C){return this._store.get(C)}getStorage(C){return Xi?ai?my.getStorageSync({key:C}).data:Ji.getStorageSync(C):this._canUseLocalStorage()?localStorage.getItem(C):{}}set(C,E){const h=this._store.get(C)||{};E instanceof Map?this._store.set(C,E):this._store.set(C,Object.assign(Object.assign({},h),E))}setStorage(C,E){Xi?ai?my.setStorageSync({key:C,data:JSON.stringify(E)}):Ji.setStorageSync(C,JSON.stringify(E)):this._canUseLocalStorage()&&localStorage.setItem(C,JSON.stringify(E))}clear(C){typeof C=="string"?this._store.set(C,{}):this._store.clear()}clearLocalStorage(C){this._canUseLocalStorage()&&(typeof C=="string"?localStorage.setItem(C,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return typeof window<"u"&&navigator&&navigator.cookieEnabled&&localStorage}};class $s{connectSocket(E){return this._socket=Ji.connectSocket({url:E,header:{"content-type":"application/json"},multiple:!0,complete:()=>{}}),this._socket}send(E){var h;(h=this._socket)===null||h===void 0||h.send({data:E,fail:this._onSendFail})}bindSocketHandlers(E){const{onOpen:h,onMessage:D,onClose:N,onError:O,onSendFail:Y}=E;this._socket&&(this._socket.onClose(N),this._socket.onOpen(h),this._socket.onMessage(j=>D(j?.data)),this._socket.onError(()=>O),this._onSendFail=Y)}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(C){C[C.CONNECTED=0]="CONNECTED",C[C.CONNECTING=1]="CONNECTING",C[C.DISCONNECTED=2]="DISCONNECTED"})(Qr||(Qr={}));class Ha{constructor(E){this._url="",this._readyState=Qr.DISCONNECTED,this._url=E,this._id=v(),this._emitter=new jr,ai?this._socket=new $s:Je||Ur||Zi||Dt||Ki||qt?this._socket=new gr({onError:this._onError.bind(this)}):Nr?this._socket=new Mc:this._canUseWebWorker()?this._socket=new Ja:this._socket=new nI,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[Qr.CONNECTED,Qr.CONNECTING].includes(this._readyState)||(this._readyState=Qr.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(E){this._readyState!==Qr.CONNECTED?this.reconnect():this._socket.send(E)}reconnect(){[Qr.CONNECTED,Qr.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(E,h,D){this._emitter.on(E,h,D)}off(E,h,D){this._emitter.off(E,h,D)}isConnected(){return this._readyState===Qr.CONNECTED}disconnect(){this._readyState=Qr.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(E){this._readyState===Qr.CONNECTING&&(this._readyState=Qr.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:E}))}_onMessage(E){this._emitter.emit("message",E)}_onClose(E){this._readyState=Qr.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:E})}_onError(E){this._readyState=Qr.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:E})}_onSendFail(E){this._readyState=Qr.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:E})}_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 E=Fo.get("cloudConfig")||{};return(r(E.isWorkerEnabled)||E.isWorkerEnabled==="1")&&ji}}const Gs={[Ve.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[Ve.KOREA]:[[3e7,4e7],[173e7,174e7]],[Ve.GERMANY]:[[4e7,5e7],[174e7,175e7]],[Ve.IND]:[[5e7,6e7],[175e7,176e7]],[Ve.JPN]:[[6e7,7e7],[176e7,177e7]],[Ve.USA]:[[7e7,8e7],[177e7,178e7]],[Ve.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[Ve.KSA]:[[9e7,1e8],[179e7,18e8]]};function Ga(C){var E;if(!((E=Fo.get("instance"))===null||E===void 0)&&E.oversea)return Ve.OVERSEA;for(const h of Object.keys(Gs))for(const[D,N]of Gs[h])if(C>=D&&C`${_A}=${mA[_A]}`).join("&"));var mA;return h?`${C}/binfo?${BA}&compress=gzip`:`${C}/info?${BA}`}function qo(C){const E=Fo.get("instance"),{sdkAppId:h,testEnv:D,proxyServer:N}=E,O=Ga(h);if(D)return en(Ze.TEST[O].DEFAULT,{isBinary:C});if(!$r(N))return en(N,{isBinary:C});const Y=Ze.PRODUCTION[O],j=wt&&Y.ANYCAST,IA=wt,BA=!!Y.BACKUP_CN;return en({[Rr.INITIAL]:()=>(fo=Rr.DEFAULT,Y.DEFAULT),[Rr.DEFAULT]:()=>(fo=Rr.IPV6,Y.IPV6),[Rr.IPV6]:()=>(fo=Rr.BACKUP,Y.BACKUP),[Rr.BACKUP]:()=>IA?(fo=Rr.BACKUP_WEB_ONLY,function(mA){const _A=Math.floor(10001*Math.random())+1e4;return mA.replace("*",String(_A))}(Y.BACKUP_WEB_ONLY)):BA?(fo=Rr.BACKUP_CN,Y.BACKUP_CN):j?(fo=Rr.ANYCAST,Y.ANYCAST):Y.DEFAULT,[Rr.BACKUP_WEB_ONLY]:()=>BA?(fo=Rr.BACKUP_CN,Y.BACKUP_CN):j?(fo=Rr.ANYCAST,Y.ANYCAST):Y.DEFAULT,[Rr.BACKUP_CN]:()=>(fo=j?Rr.ANYCAST:Rr.DEFAULT,Y[fo]),[Rr.ANYCAST]:()=>(fo=Rr.DEFAULT,Y.ANYCAST="",Y.DEFAULT)}[fo](),{isBinary:C})}var Gg=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(C,E){const h=Date.now(),D=h-C;this._timeOffsetWithServer=E+D-h}};const kg=16;var fn=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(C){const{id:E}=C;this.removeTask(E),this._tasks.push(C),this._taskMap.set(E,C),this._sort(),this._scheduleNextTask()}_createTask(C){const{id:E,callback:h,context:D,isOnce:N=!1,intervalMs:O=kg}=C,Y=Math.max(O,kg);return{id:E,nextExecuteTime:Date.now()+Y,intervalMs:O,callback:h,context:D,isOnce:N}}addTask(C){const E=this._createTask(C);this._addTaskToScheduler(E)}addOnceTask(C){const E=this._createTask(Object.assign(Object.assign({},C),{isOnce:!0}));this._addTaskToScheduler(E)}removeTask(C){const E=this._tasks.findIndex(h=>h.id===C);E>-1&&(this._tasks.splice(E,1),this._taskMap.delete(C),this._scheduleNextTask())}updateTaskInterval(C,E){const h=this._taskMap.get(C);h&&(h.intervalMs=E,h.nextExecuteTime=Date.now()+E,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((C,E)=>C.nextExecuteTime-E.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const C=this._tasks[0];if(C){const E=Math.max(0,C.nextExecuteTime-Date.now());this._timer=setTimeout(()=>this._execute(),E)}}_execute(){const C=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=C;){const E=this._tasks[0];try{E.context?E.callback.call(E.context):E.callback(),E.isOnce?this.removeTask(E.id):(E.nextExecuteTime=C+E.intervalMs,this._sort())}catch(h){console.warn(`Task ${E.id} execution failed:`,h),E.isOnce&&this.removeTask(E.id)}}this._scheduleNextTask()}};function ls(C){const E=[];for(let h=0;h=55296&&D<=56319){const N=C.charCodeAt(++h)-56320+(D-55296<<10)+65536;E.push(240|N>>18,128|N>>12&63,128|N>>6&63,128|63&N)}else D<=127?E.push(D):D<=2047?E.push(192|D>>6,128|63&D):E.push(224|D>>12,128|D>>6&63,128|63&D)}return new Uint8Array(E)}function Or(C){const E=Array.isArray(C)?[]:Object.create(null);for(const h in C)Object.prototype.hasOwnProperty.call(C,h)&&m(h)&&C[h]!=null&&(C[h]===null||typeof C[h]!="object"?E[h]=C[h]:E[h]=Or(C[h]));return E}function Po(C,E){if(sA.includes(C))return 0;const h=ls(JSON.stringify(E));let D=4294967295;const{length:N}=h;for(let O=0;O>>=1:D=D>>>1^3988292384}return(4294967295^D)>>>0}function Ba(C){const{servcmd:E,data:h}=C,D=function(O){const Y=Fo.get("login")||{},j=Fo.get("instance")||{};return{servcmd:O,ver:"v4",platform:MA,websdkappid:537048168,websdkversion:"1.7.3",a2:Y.a2Key||void 0,tinyid:Y.tinyID||void 0,status_instid:Y.statusInstanceId||0,sdkappid:j.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:Y.a2Key?void 0:Y.userId,usersig:Y.a2Key?void 0:Y.userSig,sdkability:478343027,sdkability_ext:AA(""),cappid:j.applicationID||0,tjgID:"",seq:Va(),cs:0}}(E),N=Or(h);return D.cs=Po(E,N),{head:D,body:N}}function Mr(C){const{servcmd:E,data:h}=C,D=function(O){const Y=Fo.get("login")||{},j=Fo.get("instance")||{};return{servcmd:O,ver:"v4",platform:MA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:j.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:Y.statusInstanceId||0,sdkability:478343027,sdkability_ext:AA(""),cappid:j.applicationID||0,seq:Va(),cs:0}}(E),N=Or(h);return D.cs=Po(E,N),{head:D,body:N}}let Cs=v();function Va(){return Cs=Cs<2415919103?Cs+1:v(),Cs}function P(){var C;const E=Fo.get("login")||{},h=Fo.get("instance")||{};return{sdk_type:30,sdk_app_id:h.sdkAppId,sdk_version:"1.6.18",tiny_id:Number(E.tinyID),user_id:E.userId||((C=Fo.get("webPush"))===null||C===void 0?void 0:C.userId),platform:MA,instance_id:h.instanceId,trace_id:new Date().getTime()}}var F,EA=Object.freeze({__proto__:null,calcBodyCRC:Po,filterProtocolDataInvalidFields:Or,generateCosSpecifiedData:function(C){const{servcmd:E,data:h}=C,D=function(O){const Y=Fo.get("login")||{},j=Fo.get("instance")||{};return{servcmd:O,ver:"v4",platform:MA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:j.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:Y.userId,usersig:Y.userSig,status_instid:Y.statusInstanceId||0,sdkability:478343027,sdkability_ext:AA(""),cappid:j.applicationID||0,seq:Va(),cs:0}}(E),N=Or(h);return D.cs=Po(E,N),{head:D,body:N}},generateProtocolData:Ba,generateSSOLogProtocolData:Mr,generateSequence:Va,getCommonHead:P,getHostSite:Ga,taskScheduler:fn,timeManager:Gg});(function(C){C[C.info=4]="info",C[C.warning=5]="warning",C[C.error=6]="error"})(F||(F={}));const RA={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 GA{constructor(E){this.level=F.info,this._canSendLog=!0,this._logCreatedAt=Gg.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:h,eventType:D=0,message:N="",costTime:O=0,error:Y,uiPlatform:j,moreMessage:IA="",code:BA=0,startTime:mA=0}=E||{};this.eventType=D,this.method=h,this.message=N,this.costTime=O,this.moreMessage=`${IA} startTime:${mA}`,this.code=BA,Y&&this.setError(Y),$r(j)||(this.uiPlatform=j)}setMoreMessage(E){this.moreMessage=`${this.moreMessage} ${E}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Gg.getTimeOffsetWithServer()}end(E=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=Gg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),E&&this._ssoLogModule.uploadSSOLogData())}setError(E){var h;return E instanceof Error?this._canSendLog?(!((h=Fo.get("netWorkMonitor"))===null||h===void 0)&&h.isNetworkOnline&&(E.errorCode&&(this.code=E.errorCode),E.errorMessage&&this.setMoreMessage(E.errorMessage)),this.level=F.error,this):this:(console.warn("SSOLogData.setError value not instanceof Error, please check!"),this)}setLogInfo(E){return Object.keys(E).forEach(h=>{Object.keys(RA).includes(h)&&(this[h]=E[h])}),this}setSSOLogModule(E){this._ssoLogModule=E}_convertSSOLogDataKeyToServe(){const E={};return Object.keys(this).forEach(h=>{const D=h;RA[D]&&(E[RA[D]]=this[D])}),E}_getUiPlatform(){var E;const h=(E=Fo.get("instance"))===null||E===void 0?void 0:E.scene;if(typeof h=="string"){const D=Number(h);return isNaN(D)?void 0:D}}_getSDKEdition(){var E;return(E=Fo.get("instance"))===null||E===void 0?void 0:E.sdkEdition}}var WA;(function(C){C.RECONNECTED="reconnected",C.CLOUD_CONFIG_UPDATE="cloud_config_update",C.SOCKET_DISCONNECTED="socket_disconnected"})(WA||(WA={}));var Ce=WA;const ge=20,we=6e4,_e=[4,5,6],Ke="report-logger";var Bt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=ge,this._maxThreshold=100,this._waitingTime=we,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=eA.DEBUG,this._throttleConfig={global:{throttleTime:ue,maxCount:jA},single:{throttleTime:HA,maxCount:VA}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,pn.subscribeInnerEvent(Ce.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),fn.addTask({id:Ke,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(C){const{evt_rpt_threshold:E=ge,evt_rpt_waiting:h=we,evt_rpt_level:D=_e,evt_rpt_sdkappid_bl:N="",evt_rpt_tinyid_wl:O="",evt_rpt_global_throttle_time:Y=ue,evt_rpt_global_throttle_count:j=jA,evt_rpt_single_throttle_time:IA=HA,evt_rpt_single_throttle_count:BA=VA}=C||{};this._sdkAppIdBlackList=N.split(",").map(mA=>Number(mA)),this._waitingTime=Number(h),this._minThreshold=E,this._reportLevel=D,this._tinyIdWhiteList=O.split(","),this._throttleConfig={global:{throttleTime:Y,maxCount:j},single:{throttleTime:IA,maxCount:BA}}}createSSOLogData(C){const E=new GA(C);return E.setSSOLogModule(this),this._ssoLogMap.set(C.method,E),E}getSSOLogData(C){return this._ssoLogMap.get(C)||{}}pushToLogQueue(C){C&&(this._logQueue.push(C),this._shouldUploadImmediately()&&this.uploadSSOLogData())}setLogLevel(C){[eA.DEBUG,eA.ERROR,eA.INFO,eA.NONE,eA.WARN].includes(C)&&(this._logLevel=C)}debug(C,E="",h){this._log(eA.DEBUG,C,E,h)}info(C,E="",h){this._log(eA.INFO,C,E,h)}warn(C,E="",h){this._log(eA.WARN,C,E,h)}error(C,E="",h){this._log(eA.ERROR,C,E,h)}_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 et(this,void 0,void 0,function*(){if(this._logQueue.length===0)return;const C=this._logQueue.slice();this._logQueue=[];try{const E=this._filterLogs(C);if(E.length===0)return void(this._lastReportAt=Date.now());const h={Header:P(),Event:E};$r(h.Header.user_id)||(yield function(D){const N="imopenstat.tim_web_report_v2",O=Mr({servcmd:N,data:D}),Y=`${O.head.seq}${N}`;return II.sendPacket(O,{requestId:Y})}(h))}catch(E){this._requeueFailedLogs(C),this.debug("uploadSSOLogData",An(E))}finally{this._lastReportAt=Date.now()}})}_requeueFailedLogs(C){this._logQueue=C.concat(this._logQueue);const E=this._logQueue.length-200;E>0&&(this._logQueue.splice(0,E),this.debug("uploadSSOLogData",`log queue overflow, dropped ${E} oldest logs`))}_savePlatFormInfo(){var C,E;if(Je){const h=(E=(C=wx.getAccountInfoSync)===null||C===void 0?void 0:C.call(wx))===null||E===void 0?void 0:E.miniProgram;if(h){const{appId:D,envVersion:N}=h;Fo.set("instance",{appId:D,envVersion:N})}}else wt&&Fo.set("instance",{href:window.location.href})}_filterLogs(C){const{tinyID:E}=Fo.get("login")||{},{sdkAppId:h}=Fo.get("instance")||{};return this._sdkAppIdBlackList.includes(h)&&!this._tinyIdWhiteList.includes(E)?[]:C.filter(D=>this._reportLevel.includes(D.level))}_checkThrottle(C){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(C)}_checkGlobalThrottle(){const C=Date.now();if(C-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=C;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(C){const E=Date.now(),h=this._singleThrottleMap.get(C);return h?E-h.startTime>=this._throttleConfig.single.throttleTime?(h.count=1,h.startTime=E,!1):h.count>=this._throttleConfig.single.maxCount||(h.count++,!1):(this._singleThrottleMap.set(C,{count:1,startTime:E}),!1)}_shouldLog(C){return C>=this._logLevel&&this._logLevel!==eA.NONE}_shouldReport(C){return this._reportLevel.includes(wA[C])}_formatLog(C,E,h,D){const N=new Date,O=`${N.getHours()}:${N.getMinutes()}:${N.getSeconds()}:${N.getMilliseconds()}`,Y=`<${eA[C]}>`;return ot||Xi?[`${X} [${O}] ${Y} [${E}] ${h}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",X,"",`[${O}] ${Y} [${E}] ${h} params: ${An(D)}`]}_log(C,E,h,D){if(this._shouldLog(C)){const N=this._formatLog(C,E,h,D);QA[C].apply(console,N)}if(this._shouldReport(C)){const N=this._getThrottleKey(E,h,D);this._checkThrottle(N)||this.createSSOLogData(Object.assign(Object.assign({message:h},D),{method:E})).end()}}_getThrottleKey(C,E,h){const D=`${C}${E}${An(Object.assign(Object.assign({},h),{costTime:""}))}`,N=ls(JSON.stringify(D));let O=4294967295;const{length:Y}=N;for(let j=0;j>>=1:O=O>>>1^3988292384}return`${(4294967295^O)>>>0}`}reset(){console.log("SSO_LOG_MODULE.reset"),fn.removeTask(Ke),pn.unSubscribeInnerEvent(Ce.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=ge,this._maxThreshold=100,this._waitingTime=we,this._logQueue=[],this._logLevel=eA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const Rt=15e3,Ye="Channel",nt="channel_schedule_task",ii="channel_reconnect_task",oi="connected",Ko="connecting",Kt="disconnected",ro=1e3,ks="network_status_change",Zr="activity_status_change",In="send_fail",xr="reconnect_failed",sI="socket_error",jo="socket_close";function OI(C){return OI=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(E){return typeof E}:function(E){return E&&typeof Symbol=="function"&&E.constructor===Symbol&&E!==Symbol.prototype?"symbol":typeof E},OI(C)}function _g(C){throw new Error('Could not dynamically require "'+C+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var gI,ml={exports:{}},ua=(gI||(gI=1,function(C){C.exports=function E(h,D,N){function O(IA,BA){if(!D[IA]){if(!h[IA]){if(!BA&&_g)return _g(IA);if(Y)return Y(IA,!0);var mA=new Error("Cannot find module '"+IA+"'");throw mA.code="MODULE_NOT_FOUND",mA}var _A=D[IA]={exports:{}};h[IA][0].call(_A.exports,function(xA){return O(h[IA][1][xA]||xA)},_A,_A.exports,E,h,D,N)}return D[IA].exports}for(var Y=_g,j=0;j>>6:(xA<65536?_A[Se++]=224|xA>>>12:(_A[Se++]=240|xA>>>18,_A[Se++]=128|xA>>>12&63),_A[Se++]=128|xA>>>6&63),_A[Se++]=128|63&xA);return _A},D.buf2binstring=function(mA){return BA(mA,mA.length)},D.binstring2buf=function(mA){for(var _A=new N.Buf8(mA.length),xA=0,Qe=_A.length;xA>10&1023,at[Qe++]=56320|1023&Re)}return BA(at,Qe)},D.utf8border=function(mA,_A){var xA;for((_A=_A||mA.length)>mA.length&&(_A=mA.length),xA=_A-1;0<=xA&&(192&mA[xA])==128;)xA--;return xA<0||xA===0?_A:xA+j[mA[xA]]>_A?xA:_A}},{"./common":1}],3:[function(E,h,D){h.exports=function(N,O,Y,j){for(var IA=65535&N,BA=N>>>16&65535,mA=0;Y!==0;){for(Y-=mA=2e3>>1:O>>>1;Y[j]=O}return Y}();h.exports=function(O,Y,j,IA){var BA=N,mA=IA+j;O^=-1;for(var _A=IA;_A>>8^BA[255&(O^Y[_A])];return-1^O}},{}],6:[function(E,h,D){h.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(E,h,D){h.exports=function(N,O){var Y,j,IA,BA,mA,_A,xA,Qe,Re,Se,At,at,jt,Bi,ri,St,eo,to,Yt,si,zo,te,je,dA,ut;Y=N.state,j=N.next_in,dA=N.input,IA=j+(N.avail_in-5),BA=N.next_out,ut=N.output,mA=BA-(O-N.avail_out),_A=BA+(N.avail_out-257),xA=Y.dmax,Qe=Y.wsize,Re=Y.whave,Se=Y.wnext,At=Y.window,at=Y.hold,jt=Y.bits,Bi=Y.lencode,ri=Y.distcode,St=(1<>>=Yt=to>>>24,jt-=Yt,(Yt=to>>>16&255)==0)ut[BA++]=65535&to;else{if(!(16&Yt)){if(!(64&Yt)){to=Bi[(65535&to)+(at&(1<>>=Yt,jt-=Yt),jt<15&&(at+=dA[j++]<>>=Yt=to>>>24,jt-=Yt,!(16&(Yt=to>>>16&255))){if(!(64&Yt)){to=ri[(65535&to)+(at&(1<>>=Yt,jt-=Yt,(Yt=BA-mA)>3,at&=(1<<(jt-=si<<3))-1,N.next_in=j,N.next_out=BA,N.avail_in=j>>24&255)+(te>>>8&65280)+((65280&te)<<8)+((255&te)<<24)}function at(){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 N.Buf16(320),this.work=new N.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function jt(te){var je;return te&&te.state?(je=te.state,te.total_in=te.total_out=je.total=0,te.msg="",je.wrap&&(te.adler=1&je.wrap),je.mode=Qe,je.last=0,je.havedict=0,je.dmax=32768,je.head=null,je.hold=0,je.bits=0,je.lencode=je.lendyn=new N.Buf32(Re),je.distcode=je.distdyn=new N.Buf32(Se),je.sane=1,je.back=-1,_A):xA}function Bi(te){var je;return te&&te.state?((je=te.state).wsize=0,je.whave=0,je.wnext=0,jt(te)):xA}function ri(te,je){var dA,ut;return te&&te.state?(ut=te.state,je<0?(dA=0,je=-je):(dA=1+(je>>4),je<48&&(je&=15)),je&&(je<8||15=lt.wsize?(N.arraySet(lt.window,je,dA-lt.wsize,lt.wsize,0),lt.wnext=0,lt.whave=lt.wsize):(ut<(Cr=lt.wsize-lt.wnext)&&(Cr=ut),N.arraySet(lt.window,je,dA-ut,Cr,lt.wnext),(ut-=Cr)?(N.arraySet(lt.window,je,dA-ut,ut,0),lt.wnext=ut,lt.whave=lt.wsize):(lt.wnext+=Cr,lt.wnext===lt.wsize&&(lt.wnext=0),lt.whave>>8&255,dA.check=Y(dA.check,re,2,0),Oe=Fe=0,dA.mode=2;break}if(dA.flags=0,dA.head&&(dA.head.done=!1),!(1&dA.wrap)||(((255&Fe)<<8)+(Fe>>8))%31){te.msg="incorrect header check",dA.mode=30;break}if((15&Fe)!=8){te.msg="unknown compression method",dA.mode=30;break}if(Oe-=4,gA=8+(15&(Fe>>>=4)),dA.wbits===0)dA.wbits=gA;else if(gA>dA.wbits){te.msg="invalid window size",dA.mode=30;break}dA.dmax=1<>8&1),512&dA.flags&&(re[0]=255&Fe,re[1]=Fe>>>8&255,dA.check=Y(dA.check,re,2,0)),Oe=Fe=0,dA.mode=3;case 3:for(;Oe<32;){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>>8&255,re[2]=Fe>>>16&255,re[3]=Fe>>>24&255,dA.check=Y(dA.check,re,4,0)),Oe=Fe=0,dA.mode=4;case 4:for(;Oe<16;){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>8),512&dA.flags&&(re[0]=255&Fe,re[1]=Fe>>>8&255,dA.check=Y(dA.check,re,2,0)),Oe=Fe=0,dA.mode=5;case 5:if(1024&dA.flags){for(;Oe<16;){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>>8&255,dA.check=Y(dA.check,re,2,0)),Oe=Fe=0}else dA.head&&(dA.head.extra=null);dA.mode=6;case 6:if(1024&dA.flags&&(Jt<(ti=dA.length)&&(ti=Jt),ti&&(dA.head&&(gA=dA.head.extra_len-dA.length,dA.head.extra||(dA.head.extra=new Array(dA.head.extra_len)),N.arraySet(dA.head.extra,ut,lt,ti,gA)),512&dA.flags&&(dA.check=Y(dA.check,ut,ti,lt)),Jt-=ti,lt+=ti,dA.length-=ti),dA.length))break A;dA.length=0,dA.mode=7;case 7:if(2048&dA.flags){if(Jt===0)break A;for(ti=0;gA=ut[lt+ti++],dA.head&&gA&&dA.length<65536&&(dA.head.name+=String.fromCharCode(gA)),gA&&ti>9&1,dA.head.done=!0),te.adler=dA.check=0,dA.mode=12;break;case 10:for(;Oe<32;){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>>=7&Oe,Oe-=7&Oe,dA.mode=27;break}for(;Oe<3;){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>>=1)){case 0:dA.mode=14;break;case 1:if(si(dA),dA.mode=20,je!==6)break;Fe>>>=2,Oe-=2;break A;case 2:dA.mode=17;break;case 3:te.msg="invalid block type",dA.mode=30}Fe>>>=2,Oe-=2;break;case 14:for(Fe>>>=7&Oe,Oe-=7&Oe;Oe<32;){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>>16^65535)){te.msg="invalid stored block lengths",dA.mode=30;break}if(dA.length=65535&Fe,Oe=Fe=0,dA.mode=15,je===6)break A;case 15:dA.mode=16;case 16:if(ti=dA.length){if(Jt>>=5,Oe-=5,dA.ndist=1+(31&Fe),Fe>>>=5,Oe-=5,dA.ncode=4+(15&Fe),Fe>>>=4,Oe-=4,286>>=3,Oe-=3}for(;dA.have<19;)dA.lens[LA[dA.have++]]=0;if(dA.lencode=dA.lendyn,dA.lenbits=7,vA={bits:dA.lenbits},pA=IA(0,dA.lens,0,19,dA.lencode,0,dA.work,vA),dA.lenbits=vA.bits,pA){te.msg="invalid code lengths set",dA.mode=30;break}dA.have=0,dA.mode=19;case 19:for(;dA.have>>16&255,Xa=65535&UA,!((Bo=UA>>>24)<=Oe);){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>>=Bo,Oe-=Bo,dA.lens[dA.have++]=Xa;else{if(Xa===16){for(Ae=Bo+2;Oe>>=Bo,Oe-=Bo,dA.have===0){te.msg="invalid bit length repeat",dA.mode=30;break}gA=dA.lens[dA.have-1],ti=3+(3&Fe),Fe>>>=2,Oe-=2}else if(Xa===17){for(Ae=Bo+3;Oe>>=Bo)),Fe>>>=3,Oe-=3}else{for(Ae=Bo+7;Oe>>=Bo)),Fe>>>=7,Oe-=7}if(dA.have+ti>dA.nlen+dA.ndist){te.msg="invalid bit length repeat",dA.mode=30;break}for(;ti--;)dA.lens[dA.have++]=gA}}if(dA.mode===30)break;if(dA.lens[256]===0){te.msg="invalid code -- missing end-of-block",dA.mode=30;break}if(dA.lenbits=9,vA={bits:dA.lenbits},pA=IA(BA,dA.lens,0,dA.nlen,dA.lencode,0,dA.work,vA),dA.lenbits=vA.bits,pA){te.msg="invalid literal/lengths set",dA.mode=30;break}if(dA.distbits=6,dA.distcode=dA.distdyn,vA={bits:dA.distbits},pA=IA(mA,dA.lens,dA.nlen,dA.ndist,dA.distcode,0,dA.work,vA),dA.distbits=vA.bits,pA){te.msg="invalid distances set",dA.mode=30;break}if(dA.mode=20,je===6)break A;case 20:dA.mode=21;case 21:if(6<=Jt&&258<=mo){te.next_out=Co,te.avail_out=mo,te.next_in=lt,te.avail_in=Jt,dA.hold=Fe,dA.bits=Oe,j(te,Zo),Co=te.next_out,Cr=te.output,mo=te.avail_out,lt=te.next_in,ut=te.input,Jt=te.avail_in,Fe=dA.hold,Oe=dA.bits,dA.mode===12&&(dA.back=-1);break}for(dA.back=0;Da=(UA=dA.lencode[Fe&(1<>>16&255,Xa=65535&UA,!((Bo=UA>>>24)<=Oe);){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>ia)])>>>16&255,Xa=65535&UA,!(ia+(Bo=UA>>>24)<=Oe);){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>>=ia,Oe-=ia,dA.back+=ia}if(Fe>>>=Bo,Oe-=Bo,dA.back+=Bo,dA.length=Xa,Da===0){dA.mode=26;break}if(32&Da){dA.back=-1,dA.mode=12;break}if(64&Da){te.msg="invalid literal/length code",dA.mode=30;break}dA.extra=15&Da,dA.mode=22;case 22:if(dA.extra){for(Ae=dA.extra;Oe>>=dA.extra,Oe-=dA.extra,dA.back+=dA.extra}dA.was=dA.length,dA.mode=23;case 23:for(;Da=(UA=dA.distcode[Fe&(1<>>16&255,Xa=65535&UA,!((Bo=UA>>>24)<=Oe);){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>ia)])>>>16&255,Xa=65535&UA,!(ia+(Bo=UA>>>24)<=Oe);){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>>=ia,Oe-=ia,dA.back+=ia}if(Fe>>>=Bo,Oe-=Bo,dA.back+=Bo,64&Da){te.msg="invalid distance code",dA.mode=30;break}dA.offset=Xa,dA.extra=15&Da,dA.mode=24;case 24:if(dA.extra){for(Ae=dA.extra;Oe>>=dA.extra,Oe-=dA.extra,dA.back+=dA.extra}if(dA.offset>dA.dmax){te.msg="invalid distance too far back",dA.mode=30;break}dA.mode=25;case 25:if(mo===0)break A;if(ti=Zo-mo,dA.offset>ti){if((ti=dA.offset-ti)>dA.whave&&dA.sane){te.msg="invalid distance too far back",dA.mode=30;break}ti>dA.wnext?(ti-=dA.wnext,_n=dA.wsize-ti):_n=dA.wnext-ti,ti>dA.length&&(ti=dA.length),Eg=dA.window}else Eg=Cr,_n=Co-dA.offset,ti=dA.length;for(moeo?(Yt=_n[Eg+Se[je]],si=Oe[xs+Se[je]]):(Yt=96,si=0),at=1<>Co)+(jt-=at)]=to<<24|Yt<<16|si,jt!==0;);for(at=1<>=1;if(at!==0?(Fe&=at-1,Fe+=at):Fe=0,je++,--Zo[te]==0){if(te===ut)break;te=mA[_A+Se[je]]}if(Cr{const j=new Uint8Array(Y).slice(4);let IA;try{IA=ua.inflate(j,{to:"string"})}catch(BA){console.error("inflate error",BA)}return IA})(C.data):function(Y){const j=new Uint8Array(Y);let IA="",BA=0;const{length:mA}=j;for(;BA0)for(let Re=0;Re{var D;const{uplinkData:N,canResend:O,resolve:Y,reject:j,timeout:IA}=E;if(O){this._pendingRequests.set(h,{resolve:Y,reject:j,timestamp:Date.now(),uplinkData:N,timeout:IA,canResend:O});const BA=this._isBinarySupported?ls(N).buffer:N;(D=this._socketAdapter)===null||D===void 0||D.send(BA)}else this._pendingRequests.delete(h)})}_onConnect(C){const{socketId:E,event:h={}}=C||{};this._connectionId=E,this._connectionEstablishedTime=Date.now();const D=Date.now()-this._connectionStartTime,N=`${Ye}.onConnect cost:${D} ms. socketID:${E} res:${JSON.stringify(h)}`;if(this._ssoLog({method:"onConnect",message:N}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const O=`${Ye}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:O}),pn.emitInnerEvent(Ce.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:oi,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(C){const E=Ba({servcmd:"openim.ws_msg_push_ack",data:{SessionData:C}});this.sendPacket(E)}_executeScheduledTaskIfReady(){return et(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var C;return((C=this._socketAdapter)===null||C===void 0?void 0:C.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return et(this,void 0,void 0,function*(){var C;const E=Ba({servcmd:"heartbeat.alive",data:{}});try{const h=`${E.head.seq}${E.head.servcmd}`;yield this.sendPacket(E,{requestId:h,timeout:3e3})}catch(h){const D=(C=Fo.get("netWorkMonitor"))===null||C===void 0?void 0:C.isNetworkOnline,N=`${Ye}.sendHeartbeat failed. isNetWorkOnline:${D} error: ${An(h)}`;this._ssoLog({method:"sendHeartbeatError",message:N}),this._handleConnectStateChange({state:Kt,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return et(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=Ur?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(C){const E=`${Ye}.networkStatusChange ${JSON.stringify(C)}`;this._ssoLog({method:"networkStatusChange",message:E});const{isNetworkOnline:h,networkType:D}=C;h&&D!=="none"?this._handleConnectStateChange({state:oi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:ks}):this._handleConnectStateChange({state:Kt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:ks})}isPrivateNetWork(){const C=Fo.get("instance")||{};return C.proxyServer&&!C.fileDownloadProxy}_handleConnectStateChange(C){const{state:E,shouldAttemptReconnect:h,shouldEmitEvent:D,reason:N}=C,O=`${Ye}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${h} shouldEmitEvent: ${D} reason: ${N}`;this._currentConnectState!==E&&(this._ssoLog({method:"handleConnectStateChange",message:O}),D&&(Bt.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${E}`),pn.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:E}}),this._currentConnectState=E,E===Kt&&pn.emitInnerEvent(Ce.SOCKET_DISCONNECTED)),h&&(this._resetReconnectDelay(),fn.addTask({id:ii,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(C){var E,h;const D=(h=(E=this._socketAdapter)===null||E===void 0?void 0:E._ws)===null||h===void 0?void 0:h.readyState,N=`${Ye}.activityStatusChange ${JSON.stringify(C)} readyState: ${D}`;Bt.debug("activityStatusChange",N),D===3&&this._handleConnectStateChange({state:Kt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Zr})}_resetReconnectDelay(){var C;Bt.debug(`${Ye}._resetReconnectDelay`),fn.removeTask(ii);const E=(C=Fo.get("activityMonitor"))===null||C===void 0?void 0:C.isActive;this._intendedDelay=E?ro:1e3}_scheduleReconnectWithBackoff(){var C;const E=(C=Fo.get("activityMonitor"))===null||C===void 0?void 0:C.isActive;this._intendedDelay=E?Math.min(5e3,Math.max(ro,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const h=new Date().toTimeString().slice(0,8),D=`${Ye}.scheduleReconnectWithBackoff timeStr: ${h} intendedDelay: ${this._intendedDelay}`;Bt.debug(D),this.reconnect(),fn.updateTaskInterval(ii,this._intendedDelay)}_ssoLog(C){const{method:E,message:h}=C;Bt.info(E,h)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(C){et(this,void 0,void 0,function*(){const E=C.split("/")[2];if(!E.startsWith("ws"))return;const h=`https://${E}/v3/netcheck/getconninfo?${C.slice(C.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield $t({method:"GET",url:h,data:{}})}catch(D){Bt.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${D.message}`)}})}(this._url),function(C){et(this,void 0,void 0,function*(){const E=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${C.slice(C.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield $t({method:"GET",url:E,data:{}})}catch(h){Bt.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${h.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[C,E]of this._pendingRequests.entries()){const{reject:h,timestamp:D,timeout:N}=E;Date.now()-D>=N&&(this._pendingRequests.delete(C),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),h({errorCode:Qn,errorInfo:"NETWORK_TIMEOUT",data:{requestId:C}}))}}_updateIsBinarySupported(){var C;if(!((C=Fo.get("instance"))===null||C===void 0)&&C.devMode)return void(this._isBinarySupported=!1);const E=Lo();if((ai||Je&&E==="windows"||Kn)&&(this._isBinarySupported=!1),Ur){const{uniRuntimeVersion:h=""}=Ji.getSystemInfoSync();(function(D){const N=D.split(".").map(Number),[O=0,Y=0,j=0]=N;return O>2||!(O<2)&&(Y>2||!(Y<2)&&j>=6)})(h)||(this._isBinarySupported=!1)}}_isCompressedData(C){const E=new Uint8Array(C);return E[0]===67&&E[1]===79&&E[2]===77&&E[3]===80}};const ZA={init:function(C){Fo.set("instance",C),II.init()},destroy:function(){II.dispose(),Fo.clear(),fn.dispose()},notificationCenter:pn,channel:II,store:Fo,ssoLog:Bt,utils:Es,common:EA,constants:qe},Ag=C=>typeof C=="function";function cI(C,E,h){const D=h||[];if(!C||!E)return!1;const N=Object.keys(C).filter(Y=>!D.includes(Y)),O=Object.keys(E).filter(Y=>!D.includes(Y));return N.length===O.length&&N.every(Y=>!!E.hasOwnProperty(Y)&&(typeof C[Y]=="object"&&C[Y]!==null?cI(C[Y],E[Y],h):C[Y]===E[Y]))}var Bs;(function(C){C.SDK_READY="sdkStateReady",C.SDK_NOT_READY="sdkStateNotReady",C.SDK_DESTROY="sdkDestroy",C.MESSAGE_RECEIVED="onMessageReceived",C.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",C.MESSAGE_MODIFIED="onMessageModified",C.MESSAGE_REVOKED="onMessageRevoked",C.MESSAGE_READ_BY_PEER="onMessageReadByPeer",C.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",C.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",C.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",C.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",C.CONVERSATION_LIST_UPDATED="onConversationListUpdated",C.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",C.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",C.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",C.GROUP_LIST_UPDATED="onGroupListUpdated",C.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",C.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",C.TOPIC_CREATED="onTopicCreated",C.TOPIC_DELETED="onTopicDeleted",C.TOPIC_UPDATED="onTopicUpdated",C.PROFILE_UPDATED="onProfileUpdated",C.USER_STATUS_UPDATED="onUserStatusUpdated",C.BLACKLIST_UPDATED="blacklistUpdated",C.FRIEND_LIST_UPDATED="onFriendListUpdated",C.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",C.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",C.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",C.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",C.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",C.KICKED_OUT="kickedOut",C.ERROR="error",C.NET_STATE_CHANGE="netStateChange",C.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",C.SERVER_CONFIG_UPDATED="onServerConfigUpdated",C.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated",C.WEB_PUSH_MESSAGE_RECEIVED="onWebPushMessageReceived",C.GROUP_ONLINE_MEMBER_COUNT_CHANGED="onGroupOnlineMemberCountChanged",C.RICH_STATUS_CHANGED="onRichStatusChanged"})(Bs||(Bs={}));var eg,kr=Bs;(function(C){C.LOGOUT="logout",C.DESTROY="destroy",C.CLOUD_CONFIG_UPDATE="cloud_config_update",C.PROFILE_UPDATE="profile_updated",C.ERROR="error",C.RECONNECTED="reconnected",C.FORCE_OFFLINE="im_open_status.stat_forceoffline",C.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",C.OVERLOAD_PUSH="OverLoadPush.notify2",C.NEW_MESSAGE="new_message",C.MESSAGE_PUSH="im_open_push.msg_push",C.MESSAGE_DELETED="message_deleted",C.MESSAGE_REVOKED="message_revoked",C.MESSAGE_MODIFIED="message_modified",C.SOCKET_DISCONNECTED="socket_disconnected",C.CONVERSATION_UPDATED="conversation_updated",C.TOPIC_MESSAGE_DELETED="topic_message_deleted",C.TOPIC_MESSAGE_REVOKED="topic_message_revoked",C.TOPIC_MESSAGE_MODIFIED="topic_message_modified",C.TOPIC_NEW_MESSAGE="topic_new_message",C.QUALITY_STAT="quality_stat",C.SYNC_CONVERSATION_LIST="sync_conversation_list",C.HISTORY_MESSAGE_FETCHED="history_message_fetched"})(eg||(eg={}));var EI,Gt=eg;(function(C){C.NEW_INVITATION_RECEIVED="newInvitationReceived",C.INVITEE_ACCEPTED="ts_invitee_accepted",C.INVITEE_REJECTED="ts_invitee_rejected",C.INVITATION_CANCELLED="ts_invitation_cancelled",C.INVITATION_TIMEOUT="ts_invitation_timeout",C.INVITATION_MODIFIED="ts_invitation_modified"})(EI||(EI={}));var Dl=EI;const xI=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),_s={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 tg;(function(C){C.UNSENT="unSend",C.SUCCESS="success",C.FAIL="fail"})(tg||(tg={}));const ka={modify:Gt.MESSAGE_MODIFIED,delete:Gt.MESSAGE_DELETED,revoke:Gt.MESSAGE_REVOKED};var wc;(function(C){C[C.FORWARD=0]="FORWARD",C[C.BACKWARD=1]="BACKWARD"})(wc||(wc={}));const lE=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},_s),{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:tg,Direction:wc}),qa={[ka.modify]:Gt.TOPIC_MESSAGE_MODIFIED,[ka.delete]:Gt.TOPIC_MESSAGE_DELETED,[ka.revoke]:Gt.TOPIC_MESSAGE_REVOKED},CE={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"},yC=Object.assign({},CE),us={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},lI=Object.assign(Object.assign(Object.assign(Object.assign({},us),{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"}),ig=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"}),yl={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},_a={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},Qs={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},Rl=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},yl),{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:_a,GROUP_TIPS_OPERATION_TYPE:Qs}),YI={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},vo=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},xI),lE),yC),lI),ig),Rl),YI),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),Qa={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},BE={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},cn={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"},kt={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"},Gn={[cn.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:kt.USER_STATUS_UPDATE},{stepId:kt.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:kt.UNREAD_MESSAGE_SYNC,dependency:kt.C2C_HISTORY_MESSAGE_RECOVER},{stepId:kt.CONVERSATION_RECOVER},{stepId:kt.HISTORY_MESSAGE_RECOVER,dependency:kt.CONVERSATION_RECOVER},{stepId:kt.BLACKLIST_RECOVER},{stepId:kt.FRIEND_RECOVER},{stepId:kt.FRIEND_APPLICATION_LIST_RECOVER},{stepId:kt.GROUP_REVOKED_NOTICE_RECOVER,dependency:kt.HISTORY_MESSAGE_RECOVER},{stepId:kt.GROUP_TIPS_RECOVER,dependency:kt.HISTORY_MESSAGE_RECOVER},{stepId:kt.TOPIC_REQUEST_INFO_RESET},{stepId:kt.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:kt.UNREAD_MESSAGE_SYNC},{stepId:kt.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:kt.UNREAD_MESSAGE_SYNC},{stepId:kt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[kt.UNREAD_MESSAGE_SYNC,kt.CONVERSATION_RECOVER]},{stepId:kt.EMIT_C2C_MESSAGE_EVENT,dependency:[kt.UNREAD_MESSAGE_SYNC,kt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:kt.C2C_HISTORY_MESSAGE_RECOVER,dependency:kt.CONVERSATION_RECOVER},{stepId:kt.STREAM_MESSAGE_RECOVER}],[cn.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:kt.COMMERCIAL_CONFIG_UPDATE},{stepId:kt.CLOUD_CONFIG_SYNC},{stepId:kt.USER_PROFILE_SYNC},{stepId:kt.UNREAD_MESSAGE_SYNC},{stepId:kt.FRIEND_AND_BLACKLIST_SYNC},{stepId:kt.GROUP_LIST_SYNC},{stepId:kt.CONVERSATION_LIST_SYNC},{stepId:kt.SIGNALING_MESSAGE_RECOVER,dependency:kt.UNREAD_MESSAGE_SYNC},{stepId:kt.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[kt.UNREAD_MESSAGE_SYNC]},{stepId:kt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[kt.UNREAD_MESSAGE_SYNC,kt.CONVERSATION_LIST_SYNC]},{stepId:kt.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[kt.GROUP_LIST_SYNC,kt.CONVERSATION_LIST_SYNC]},{stepId:kt.CONVERSATION_GROUP_LIST_SYNC},{stepId:kt.CONVERSATION_GROUP_UPDATE,dependency:[kt.CONVERSATION_LIST_SYNC,kt.CONVERSATION_GROUP_LIST_SYNC]},{stepId:kt.QUALITY_REPORT}],[cn.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:kt.HANDLE_C2C_NEW_MESSAGE},{stepId:kt.UNREAD_MESSAGE_SYNC},{stepId:kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:kt.HANDLE_C2C_NEW_MESSAGE},{stepId:kt.EMIT_C2C_MESSAGE_EVENT,dependency:[kt.HANDLE_C2C_NEW_MESSAGE,kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:kt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[kt.UNREAD_MESSAGE_SYNC]}],[cn.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:kt.HANDLE_GROUP_NEW_MESSAGE},{stepId:kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:kt.HANDLE_GROUP_NEW_MESSAGE},{stepId:kt.UPDATE_GROUP_NEXT_SEQUENCE,dependency:kt.HANDLE_GROUP_NEW_MESSAGE},{stepId:kt.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:kt.HANDLE_GROUP_NEW_MESSAGE},{stepId:kt.EMIT_GROUP_MESSAGE_EVENT,dependency:[kt.HANDLE_GROUP_NEW_MESSAGE,kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[cn.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:kt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:kt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:kt.EMIT_GROUP_TIPS_EVENT,dependency:[kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,kt.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},PI={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},Sc={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},tn=["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 Ml=Object.freeze({__proto__:null,ERROR_CODE:Qa,InnerEvent:Gt,NEED_LOG_API:tn,OuterConstant:vo,OuterEvent:kr,PUSH:YI,QUALITY_METRICS:PI,SDK_EDITION:BE,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:Sc,SignalingEvent:Dl,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Gn,WORKFLOW_NAME:cn,WORKFLOW_STEP:kt}),ba,da,on;(function(C){C[C.USER_INITIATED=0]="USER_INITIATED",C[C.KICKED_OUT=1]="KICKED_OUT"})(ba||(ba={})),function(C){C[C.multipleAccount=1]="multipleAccount",C[C.multipleDevice=2]="multipleDevice",C[C.restApi=3]="restApi"}(da||(da={})),function(C){C[C.multipleDevice=3002]="multipleDevice",C[C.multipleAccount=3003]="multipleAccount",C[C.usersigExpired=70001]="usersigExpired",C[C.restApi=20002]="restApi"}(on||(on={}));const Xr={[da.multipleAccount]:"multipleAccount",[da.multipleDevice]:"multipleDevice",[da.restApi]:"REST_API_Kick",[on.multipleAccount]:"multipleAccount",[on.multipleDevice]:"multipleDevice",[on.restApi]:"REST_API_Kick",[on.usersigExpired]:"userSigExpired"},wl="login_online_presence_task",{ERROR:bs,DESTROY:vc,FORCE_OFFLINE:CI}=Gt,{KICKED_OUT_MULT_ACCOUNT:uE,KICKED_OUT_MULT_DEVICE:RC,KICKED_OUT_REST_API:Nc,ACCOUNT_A2KEY_EXPIRED:Sl,MSG_A2KEY_EXPIRED:JI}=Qa;class bg{init(){const{notificationCenter:E}=ZA;E.subscribeInnerEvent(CI,this._handleForceOfflineFromServerPush,this),E.subscribeInnerEvent(bs,JI,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),E.subscribeInnerEvent(bs,Sl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),E.subscribeInnerEvent(bs,uE,this._handleForceOfflineFromResponse,this),E.subscribeInnerEvent(bs,RC,this._handleForceOfflineFromResponse,this),E.subscribeInnerEvent(bs,Nc,this._handleForceOfflineFromResponse,this),E.subscribeInnerEvent(vc,this._dispose,this)}_handleForceOfflineFromServerPush(E){var h;if(((h=ZA.store.get("login"))===null||h===void 0?void 0:h.isLoggedIn)===!0){const{EventArray:D=[]}=E?.body||{};this._extractKickedOutMessages(D).forEach(N=>{const{KickoutMsgNotify:{KickType:O,NewInstInfo:Y,Instid:j}}=N;this._isCurrentInstanceKickedOut(j)&&this._processKickedOutReasonInfo({kickedOutReasonCode:O,newInstanceInfo:Y})})}}_extractKickedOutMessages(E){return E.reduce((h,D)=>[...h,...D.C2cNotifyMsgArray||[]],[]).filter(h=>{var D;return this._isKickedOut((D=h?.KickoutMsgNotify)===null||D===void 0?void 0:D.KickType)})}_handleForceOfflineFromResponse(E){const{errorCode:h}=E;this._processKickedOutReasonInfo({kickedOutReasonCode:h})}_processKickedOutReasonInfo(E){return et(this,void 0,void 0,function*(){const{kickedOutReasonCode:h}=E,{ssoLog:D,utils:{safeStringify:N}}=ZA;try{this._logKickedOutEvent(E),this._shouldLogoutAfterKickedOut(h)?yield ZA.login.loginAction.logout(ba.KICKED_OUT):ZA.login.loginAction.handleLogoutCompleted()}catch(O){D.debug("_processKickedOutReasonInfo",` fail ${N(O)}`)}finally{ZA.notificationCenter.emitOuterEvent(kr.KICKED_OUT,{data:{type:Xr[h]},name:kr.KICKED_OUT})}})}_logKickedOutEvent(E){const{kickedOutReasonCode:h,newInstanceInfo:D={}}=E,N=`type:${Xr[h]} newInstanceInfo: ${JSON.stringify(D)}`;ZA.ssoLog.warn("kickedOut",N)}_isKickedOut(E){return[da.multipleAccount,da.multipleDevice,da.restApi].includes(E)}_isChatLoginEvent(E){const{requestHead:h}=E||{};return h?.idtype!==1}_shouldLogoutAfterKickedOut(E){return![on.usersigExpired,da.restApi].includes(E)}_isCurrentInstanceKickedOut(E){const{isLoggedIn:h,statusInstanceId:D}=ZA.store.get("login")||{};return h===!0&&E===D}_dispose(){const{notificationCenter:E}=ZA;E.unSubscribeInnerEvent(CI,this._handleForceOfflineFromServerPush,this),E.unSubscribeInnerEvent(bs,Sl,this._handleForceOfflineFromResponse,this),E.unSubscribeInnerEvent(bs,JI,this._handleForceOfflineFromResponse,this),E.unSubscribeInnerEvent(bs,uE,this._handleForceOfflineFromResponse,this),E.unSubscribeInnerEvent(bs,RC,this._handleForceOfflineFromResponse,this),E.unSubscribeInnerEvent(bs,Nc,this._handleForceOfflineFromResponse,this),E.unSubscribeInnerEvent(vc,this._dispose,this)}}function QE(C){return et(this,void 0,void 0,function*(){const E="im_open_status.wslogin",h=ZA.common.generateProtocolData({servcmd:E,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:C}}),D=`${h.head.seq}${E}`,N=yield ZA.channel.sendPacket(h,{timeout:9e4,requestId:D});if(N){const{HelloInterval:O,InstId:Y,TinyId:j,TimeStamp:IA,CustomStatus:BA,PurchaseBits:mA,A2Key:_A,RichMsgAuthKey:xA,ErrorCode:Qe,ErrorInfo:Re,ActionStatus:Se}=N;return{helloInterval:O,instanceID:Y,tinyID:j,timeStamp:IA,customStatus:BA,purchaseBits:mA,a2Key:_A,authKey:xA,errorCode:Qe,errorInfo:Re,actionStatus:Se}}})}function vl(){const{store:C}=ZA;return Ga(C.get("instance").sdkAppId)!==Ve.CHINA}function Tc(C){var E;try{const h=Fo.getStorage("errorMessage");if(!C||!h)return"";const D=((E=JSON.parse(h))===null||E===void 0?void 0:E.errorMessage)||{},{code:N,replacement1:O="",replacement2:Y=""}=C;if(!N)return"";const j=vl()?`${N}_en`:`${N}_cn`;let IA=D[D[j]?j:N]||"";return IA&&(O&&(IA=IA.replace("$replacement1",O)),Y&&(IA=IA.replace("$replacement2",Y))),IA}catch(h){return console.warn("Error parsing stored error messages:",h),""}}class lo extends Error{constructor(E={}){E.code=E.code||E.errorCode;let{functionName:h="Unknown",code:D,message:N="",data:O="",moreMessage:Y="",errorMessage:j=""}=E;j=(D?Tc(E):"")||j||N;let IA=D?`${h} failed. error: {"message": ${j}, "code": ${D}}`:`${h} failed. error: {"message": ${j}}`;IA=`${IA} ${Y}`,super(),this.code=D,this.errorCode=D,this.errorMessage=j,this.message=IA,this.data=O}}function ds(C,E){var h;if(C&&((h=ZA.store.get("login"))===null||h===void 0?void 0:h.isLoggedIn)!==!0)throw new lo({code:Qa.USER_NOT_LOGGED_IN,functionName:E})}function QB(C,E,h){if(Array.isArray(C))for(let D=0;D{return BA===(mA=D,Object.prototype.toString.call(mA).match(/^\[object (.*)\]$/)[1].toLowerCase());var mA})){for(let mA=0;mA{const{interceptor:N,context:O}=D;N.apply(O,[h])})}(C)}function mn(C,E){kc.push({interceptor:C,context:E})}function Lg(C){const{params:E,auth:h}=C;E&&typeof E=="object"&&Object.assign(dB,E),h&&typeof h=="object"&&Object.assign(MC,h)}function dE(C){return ZA.store.get("commercialConfig").get(C)}class Ir{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(E,h)=>{const D=Date.now();h?(this._stepStartTimes.set(`${E}-${h}`,D),ZA.ssoLog.debug("_executeWorkflowStep",`[Workflow ${E}] Step ${h} started at ${new Date(D).toISOString()}`)):(this._workflowStartTimes.set(E,D),ZA.ssoLog.debug("_executeWorkflowStep",`[Workflow ${E}] started at ${new Date(D).toISOString()}`))},success:(E,h)=>{const D=Date.now();if(h){const N=this._stepStartTimes.get(`${E}-${h}`),O=N?D-N:0;this._stepStartTimes.delete(`${E}-${h}`),ZA.ssoLog.debug("_executeWorkflowStep",`[Workflow ${E}] Step ${h} completed successfully at ${new Date(D).toISOString()} (${O}ms)`)}else{const N=this._workflowStartTimes.get(E),O=N?D-N:0;this._workflowStartTimes.delete(E),ZA.ssoLog.debug("_executeWorkflowStep",`[Workflow ${E}] completed successfully at ${new Date(D).toISOString()} (${O}ms)`)}},error:(E,h,D)=>{const{ssoLog:N,utils:{safeStringify:O}}=ZA,Y=Date.now();if(h){const j=this._stepStartTimes.get(`${E}-${h}`),IA=j?Y-j:0;this._stepStartTimes.delete(`${E}-${h}`),N.error("_executeWorkflowStep",`[Workflow ${E}] Step ${h} failed at ${new Date(Y).toISOString()} (${IA}ms) ${O(D)}`,{error:D})}else{const j=this._workflowStartTimes.get(E),IA=j?Y-j:0;this._workflowStartTimes.delete(E),N.error("_executeWorkflowStep",`[Workflow ${E}] failed at ${new Date(Y).toISOString()} (${IA}ms) ${O(D)}`,{error:D})}}}}static getInstance(){return Ir._instance||(Ir._instance=new Ir),Ir._instance}static setInstance(E){Ir._instance=E}init(){this._initializeWorkflows()}registerWorkflowStep(E,h,D,N){if(!this._handlers.has(E))return void ZA.ssoLog.debug("registerWorkflowStep",`Workflow '${E}' not defined in core`);if(!Gn[E].find(Y=>Y.stepId===h))return void ZA.ssoLog.debug("registerWorkflowStep",`Step '${h}' not defined in workflow '${E}'`);const O=this._handlers.get(E);O.has(h)||O.set(h,N?D.bind(N):D)}executeWorkflow(E,h){return et(this,void 0,void 0,function*(){if(!this._validateWorkflow(E))return;ZA.ssoLog.debug("executeWorkflow",`[Workflow ${E}] Started execution at ${new Date().toISOString()}`);const D=Gn[E],N={},O={cancelled:!1};this._activeWorkflows.set(E,{cancelToken:O});try{const Y=new Map;D.forEach(IA=>{Y.set(IA.stepId,IA)});const j={workflowName:E,pendingSteps:new Set(D.map(IA=>IA.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:Y,stepResults:N,data:h,cancelToken:O};yield new Promise((IA,BA)=>{const mA=()=>{if(O.cancelled)return void IA();this._getExecutableSteps({pendingSteps:j.pendingSteps,completedSteps:j.completedSteps,stepMap:j.stepMap,workflowName:E}).filter(_A=>!j.runningSteps.has(_A)).forEach(_A=>{j.completedSteps.has(_A)||j.runningSteps.has(_A)||this._executeWorkflowStep(_A,j,{onComplete:()=>{if(j.pendingSteps.size===0)return void IA();this._getExecutableSteps({pendingSteps:j.pendingSteps,completedSteps:j.completedSteps,stepMap:j.stepMap,workflowName:E}).filter(xA=>!j.runningSteps.has(xA)).length===0&&j.runningSteps.size===0&&(ZA.ssoLog.debug("executeWorkflow",`Workflow ${E} completed with some steps skipped due to dependency failures`),IA())},onError:BA,onStepComplete:mA})})};mA()}),ZA.ssoLog.debug("executeWorkflow",`[Workflow ${E}] Completed execution at ${new Date().toISOString()}`)}catch(Y){ZA.ssoLog.error("executeWorkflow",`[Workflow ${E}] Failed execution at ${new Date().toISOString()}`,{error:Y})}finally{this._activeWorkflows.delete(E)}})}_executeWorkflowStep(E,h,D){return et(this,void 0,void 0,function*(){const{workflowName:N,runningSteps:O,stepMap:Y,stepResults:j,data:IA}=h;O.add(E),this._logWorkflowExecution(N,E,"start");try{const BA=Y.get(E);let mA=null;BA?.dependency&&(s(BA.dependency)?mA=j[BA.dependency]:Array.isArray(BA.dependency)&&(mA={},BA.dependency.forEach(xA=>{mA[xA]=j[xA]})));const _A=this._handlers.get(N).get(E);if(_A){const xA=yield Promise.resolve(_A({data:IA,result:mA}));j[E]=xA,this._logWorkflowExecution(N,E,"success")}h.completedSteps.add(E)}catch(BA){const mA=`[Workflow].${N}.${E}`,{errorCode:_A,errorInfo:xA=`${mA} failed`}=BA||{},Qe=new lo({functionName:mA,code:_A,message:xA});ZA.ssoLog.error(mA,xA,{error:Qe}),this._logWorkflowExecution(N,E,"error",BA),D.onError(BA)}finally{O.delete(E),h.pendingSteps.delete(E),D.onStepComplete(),D.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Gn).forEach(E=>{this._handlers.has(E)||this._handlers.set(E,new Map)})}_cancelWorkFlow(E){const h=this._activeWorkflows.get(E);if(!h)return;const{cancelToken:D}=h;D.cancelled=!0,this._activeWorkflows.delete(E)}_cancelAllWorkflows(){Object.keys(Gn).forEach(E=>{this._cancelWorkFlow(E)})}_validateWorkflow(E){return Gn[E]?!!this._handlers.get(E):!1}_getExecutableSteps(E){const{pendingSteps:h,completedSteps:D,stepMap:N,workflowName:O}=E;return Array.from(h).filter(Y=>{const j=N.get(Y)||{},{dependency:IA,skipIfDependencyMissing:BA=!0}=j;if(!IA)return!0;if(s(IA))return this._isStepRegistered({workflowName:O,stepId:IA})?D.has(IA):!BA;if(B(IA)){if(IA.filter(mA=>!this._isStepRegistered({workflowName:O,stepId:mA})).length>0&&BA)return!1;for(const mA of IA)if(!D.has(mA))return!1;return!0}return!1})}_isStepRegistered(E){var h;const{workflowName:D,stepId:N}=E;return(h=this._handlers.get(D))===null||h===void 0?void 0:h.has(N)}_logWorkflowExecution(E,h,D,N){this._logHandlers[D](E,h)}}const og=new Map,Ka=({type:C,groupID:E})=>C===vo.GRP_COMMUNITY||`${E}`.startsWith(_a.COMMUNITY)&&!`${E}`.includes(_a.TOPIC),ca=(C="")=>{const E=C.startsWith("GROUP")?C.replace("GROUP",""):C;return E.startsWith(_a.COMMUNITY)&&`${E}`.includes(_a.TOPIC)},hE="openim",wC="million_group_open_http_svc";function Ls(C){return et(this,void 0,void 0,function*(){const{servcmd:E,data:h}=function(O){const{data:Y}=O;return _c(Y)||SC(Y)}(C)?function(O){let{servcmd:Y,data:j}=O;return SC(j)?function(IA){const{servcmd:BA,data:mA}=IA;let{GroupId:_A=""}=mA;const xA=_A;return[_A]=xA.split(_a.TOPIC),{servcmd:rg(BA),data:Object.assign(Object.assign({},mA),{GroupId:_A,TopicId:xA})}}(O):(_c(j)&&(Y=rg(Y)),{servcmd:Y,data:j})}(C):C,D=ZA.common.generateProtocolData({servcmd:E,data:h}),N=`${D.head.seq}${E}`;return ZA.channel.sendPacket(D,{requestId:N,timeout:C.timeout})})}function _c(C){const{Type:E,GroupId:h,GroupIdList:D=[]}=C,N=h||D[0]||"";return Ka({type:E,groupID:N})}function SC(C){const{GroupId:E=""}=C;return ca(E)}function rg(C){if(C.includes(hE))return C;const E=C.split(".")[1];return`${wC}.${E}`}function Wr(){var C;return(C=ZA.store.get("login"))===null||C===void 0?void 0:C.userId}const ng=C=>B(C)||Q(C),hs=(C,E,h,D)=>{if(!ng(C)||!ng(E))return 0;let N=0;const O=Object.keys(E);let Y;for(let j=0,IA=O.length;j{if(r(E))return"";if(C===vo.MSG_TEXT)return E.text||"";const h=Nl[C];return h?pB(h):""},VI=[{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}],BI="im_sdk_config_mgr.fetch_config",pE="im_sdk_config_mgr.push_configv2",Lc="cloud-config",uI=2996,Fg=new class{init(C){this.core=C}};function ja(C){return et(this,void 0,void 0,function*(){const{sdkAppId:E}=Fg.core.store.get("instance")||{},h=Fg.core.helper.generateProtocolData({servcmd:BI,data:{uint32_sdkappid:E,uint64_version:C}}),D=`${h.head.seq}${BI}`;return Fg.core.channel.sendPacket(h,{requestId:D})})}var Fs=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(C){this._core=C;const{notificationCenter:E,InnerEvent:h,helper:D,constants:{WORKFLOW_NAME:N,WORKFLOW_STEP:O},channel:Y}=C;E.subscribeInnerEvent(pE,this._handlePushedConfig,this),D.registerWorkflowStep(N.SYNC_SERVER_INFO_AFTER_LOGIN,O.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),E.subscribeInnerEvent(h.LOGOUT,this._reset,this),E.subscribeInnerEvent(h.DESTROY,this._dispose,this),D.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(VI),Y.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(C){return et(this,void 0,void 0,function*(){var E;const h={code:0,data:""};return C&&(h.data=((E=this._core.store.get("cloudConfig"))===null||E===void 0?void 0:E[C])||""),h})}checkMethodCallOverLimit(C){if(!this._cmdFrequencyLimitMap.has(C))return;if(!this._methodCallFrequencyMap.has(C))return void this._methodCallFrequencyMap.set(C,{startTime:Date.now(),methodCallCounter:1});const{count:E,interval:h}=this._cmdFrequencyLimitMap.get(C);let{startTime:D,methodCallCounter:N}=this._methodCallFrequencyMap.get(C);if(Date.now()-D>1e3*h)this._methodCallFrequencyMap.set(C,{startTime:Date.now(),methodCallCounter:1});else if(N+=1,this._methodCallFrequencyMap.set(C,{startTime:D,methodCallCounter:N}),N>E)throw new this._core.helper.ChatError({code:uI,replacement1:C})}_handlePushedConfig(C){return et(this,void 0,void 0,function*(){const{ssoLog:E,utils:{safeStringify:h}}=this._core;E.info("_handlePushedConfig",h(C)),yield this._updateCloudConfig(C)})}_handleLoginSuccess(){return et(this,void 0,void 0,function*(){const{ssoLog:C,utils:{safeStringify:E}}=this._core;try{if(this._canFetch()){const h=yield ja(this._version);C.info("_fetchCloudConfigIfLogin",E(h)),yield this._updateCloudConfig(h)}this._core.helper.taskScheduler.addTask({id:Lc,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(h){C.debug("_fetchCloudConfigIfLogin",E(h))}})}_fetchCloudConfigIfReady(){return et(this,void 0,void 0,function*(){const{ssoLog:C,utils:{safeStringify:E}}=this._core;if(this._canFetch())try{const h=yield ja(this._version);C.info("_fetchCloudConfigIfReady",E(h)),yield this._updateCloudConfig(h)}catch(h){C.error("_fetchCloudConfigIfReady",E(h))}})}_updateCloudConfig(C){return et(this,void 0,void 0,function*(){const E=this._parseCloudConfig(C);E&&(this._core.store.set("cloudConfig",E),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,E),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:E}}))})}_canFetch(){const{isLoggedIn:C}=this._core.store.get("login")||{};return C&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(C){const{int32_error_code:E,str_error_message:h,str_json_config:D,uint32_expired_time:N,uint32_sdkappid:O,uint64_version:Y}=C;let j=null;if(E===0){if(this._version!==Y)try{j=JSON.parse(D),this._version=Y}catch{}this._expirationTime=Date.now()+1e3*N}else this._expirationTime=E===void 0?Date.now()+36e5:Date.now()+12e4;return j}_parseCmdFreqLimit(){return et(this,void 0,void 0,function*(){var C;let E=(C=yield this.getServerConfig("cmd_frequency_limit"))===null||C===void 0?void 0:C.data;const{isEmpty:h}=this._core.utils;if(!h(E))try{E=JSON.parse(E),this._updateCmdFreqLimitMap(E)}catch(D){console.warn(D)}})}_updateCmdFreqLimitMap(C){C.forEach(E=>{this._cmdFrequencyLimitMap.set(E.cmd,{interval:E.interval,count:E.count})})}_reset(){this._core.helper.taskScheduler.removeTask(Lc),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(VI),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:C,InnerEvent:E}=this._core;C.unSubscribeInnerEvent(pE,this._handlePushedConfig,this),C.unSubscribeInnerEvent(E.LOGOUT,this._reset,this),C.unSubscribeInnerEvent(E.DESTROY,this._dispose,this),this._reset()}};class No{constructor(E=0,h=0){this.high=E,this.low=h}equal(E){return E!==null&&this.low===E.low&&this.high===E.high}toString(){const E=Number(this.high).toString(16);let h=Number(this.low).toString(16);if(h.length<8){let D=8-h.length;for(;D;)h=`0${h}`,D--}return E+h}}const Fc={SEARCH_GRP_SNS:new No(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new No(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new No(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new No(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new No(0,Math.pow(2,6)).toString(),USER_STATUS:new No(0,Math.pow(2,7)).toString(),CONV_MARK:new No(0,Math.pow(2,9)).toString(),CONV_GROUP:new No(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new No(0,Math.pow(2,11)).toString(),MSG_EXT:new No(0,Math.pow(2,13)).toString(),GRP_COUNTER:new No(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new No(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new No(Math.pow(2,7)).toString(),PLUGIN_CS:new No(Math.pow(2,8)).toString(),PLUGIN_PUSH:new No(Math.pow(2,9)).toString(),PLUGIN_BOT:new No(Math.pow(2,10)).toString(),MSG_REACTION:new No(Math.pow(2,16)).toString(),FOLLOW:new No(Math.pow(2,20)).toString()},Ug="CommercialConfig",vC="commercial-config";var fE=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(C){this._core=C;const{helper:E,notificationCenter:h,constants:{WORKFLOW_NAME:D,WORKFLOW_STEP:N,InnerEvent:O}}=C;h.subscribeInnerEvent(O.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),h.subscribeInnerEvent(O.LOGOUT,this._handleLogout,this),h.subscribeInnerEvent(O.DESTROY,this._dispose,this),E.registerWorkflowStep(D.SYNC_SERVER_INFO_AFTER_LOGIN,N.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),C.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),C.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(C){return et(this,void 0,void 0,function*(){const E=parseInt(C,10).toString(2),{length:h}=E;let D,N=!0;for(let O=h-1,Y=0;O>=0;O--,Y++)if(E.charAt(O)==="1"&&(D=Y<32?new No(0,2**Y).toString():new No(2**(Y-32),0).toString(),!this._featureMap.get(D))){N=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${Ug}.isFeatureEnabled decimalNumber:${C} key:${D} ret:${N}`),{code:0,data:{enabled:N}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return et(this,void 0,void 0,function*(){var C;const{ssoLog:E,utils:{safeStringify:h},common:{buildAndSendPacket:D}}=this._core;try{this._isFetching=!0;const N=yield D({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:(C=this._core.store.get("instance"))===null||C===void 0?void 0:C.sdkAppId}});N&&(this._parseCommercialConfig(N),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(N){E.error("_fetchAndParseCommercialConfig",h(N))}finally{this._isFetching=!1}})}_syncCommercialConfig(C){return et(this,void 0,void 0,function*(){const{purchaseBits:E}=C?.data||{};E&&(this._parsePurchaseBits(E),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:vC,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var C;const E=(C=this._core.store.get("login"))===null||C===void 0?void 0:C.isLoggedIn,h=Date.now()>=this._expirationTime;return E&&!this._isFetching&&h}_handlePushedConfig(C){C?.body&&(this._parseCommercialConfig(C.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return et(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(C){const{ssoLog:E}=this._core;if(typeof C!="object")return;const{int32_error_code:h,str_error_message:D,str_purchase_bits:N,uint32_expired_time:O}=C;h===0?(this._parsePurchaseBits(N),this._expirationTime=Date.now()+1e3*O):h===void 0?(E.warn("_parseCommercialConfig",`${Ug}._parseCommercialConfig failed. Invalid message format:`,C),this._expirationTime=Date.now()+36e5):(E.warn("_parseCommercialConfig",`${Ug}._parseCommercialConfig errorCode:${h} errorMessage:${D}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(C){return C&&typeof C=="string"&&C.length>=1&&C.length<=64&&/[01]{1,64}/.test(C)}_parsePurchaseBits(C){const{ssoLog:E,utils:{safeStringify:h}}=this._core;if(this._isValidPurchaseBits(C)){this._purchaseBits=C,this._featureMap.clear(),this._methodKeyMap.clear();let D=null;for(let N=C.length-1,O=0;N>=0;N--,O++)if(D=O<32?new No(0,2**O).toString():new No(2**(O-32),0).toString(),C[N]==="1"){this._featureMap.set(D,!0);const Y=this._getKeyByValue(Fc,D);Y&&this._methodKeyMap.set(Y,!0)}else{this._featureMap.set(D,!1);const Y=this._getKeyByValue(Fc,D);Y&&this._methodKeyMap.set(Y,!1)}}else E.warn("_parsePurchaseBits",`${Ug}.parsePurchaseBits invalid purchases:${h(C)}`)}_getKeyByValue(C,E){const h=Object.entries(C).find(([D,N])=>N===E);return h?h[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(vC),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},Tl=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(C){this._core=C;const{notificationCenter:E,InnerEvent:h,channel:D}=this._core;E.subscribeInnerEvent(h.OVERLOAD_PUSH,this._handleOverLoadPush,this),E.subscribeInnerEvent(h.LOGOUT,this._reset,this),E.subscribeInnerEvent(h.DESTROY,this._dispose,this),D.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(C){if(!this._serverOverloadInfoMap.has(C))return;const{overloadStartTimestamp:E,delaySeconds:h}=this._serverOverloadInfoMap.get(C);if(Date.now()-E<=1e3*h)throw new this._core.helper.ChatError({functionName:C,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(C)}_handleOverLoadPush(C){const{OverLoadServCmd:E,DelaySecs:h}=C;this._serverOverloadInfoMap.set(E,{overloadStartTimestamp:Date.now(),delaySeconds:h})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:C,InnerEvent:E}=this._core;C.unSubscribeInnerEvent(E.OVERLOAD_PUSH,this._handleOverLoadPush,this),C.unSubscribeInnerEvent(E.LOGOUT,this._reset,this),C.unSubscribeInnerEvent(E.DESTROY,this._dispose,this)}},Ou=new class{constructor(){this.name="ConfigCenter"}install(C){Fg.init(C),Fs.install(C),fE.install(C),Tl.install(C)}},fB=new class{constructor(){this.name="ErrorMessage",this._core=null}install(C){return et(this,void 0,void 0,function*(){if(this._core=C,this._canFetch()){const E=yield this._fetchErrorMessage();if(!E)return;const h=this._parseResponse(E);this._saveErrorMessage(h)}})}_canFetch(){const C=this._core.store.getStorage("errorMessage");return!C||this._isExpired(C)}_saveErrorMessage(C){this._core.store.setStorage("errorMessage",{errorMessage:C,errorMessageSavedTime:new Date().getTime()})}_fetchErrorMessage(){return et(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(C){console.error(C)}})}_isExpired(C){if(!C)return!0;const{errorMessageSavedTime:E}=C;return E&&new Date().getTime()-E>=6048e5}_parseResponse(C){if(typeof C=="string"){const E=C.split(`; -`),h={},D=new RegExp(/'/g);for(let N=0;N{var Bi,ri,St;const eo=function(to,Yt){const{From_Account:si,From_AccountHeadurl:zo,From_AccountNick:te,IsNeedReadReceipt:je,MsgBody:dA,MsgClientTime:ut,MsgRandom:Cr,MsgSeq:lt,MsgTimeStamp:Co,SendMsgControl:Jt,SupportMessageExtension:mo,To_Account:Fe,TinyId:Oe,MsgCheckResult:xs,CloudCustomData:Zo,IsPeerRead:ti,MsgFlagBits:_n,MsgVersion:Eg,EventArray:Bo}=to;return{from:si,avatar:zo,nick:te,needReadReceipt:je===1,readReceiptSentByPeer:ti,clientTime:ut,messageFlagBits:_n,random:Cr,sequence:lt,time:Co,messageControlInfo:Jt,isSupportExtension:mo,to:Fe,tinyID:Oe,checkResult:xs,cloudCustomData:Zo,messageVersion:Eg,eventArray:Bo,elements:Yt.message.messageHelper.parseServerPushMessageElement(dA)}}(jt,Se);if(!((St=(ri=(Bi=jt?.EventArray)===null||Bi===void 0?void 0:Bi[0])===null||ri===void 0?void 0:ri.hasOwnProperty)===null||St===void 0)&&St.call(ri,"C2cNotifyMsgArray"))at.push(...function(to){var Yt;const si=[];return(Yt=to.EventArray)===null||Yt===void 0||Yt.forEach(zo=>{var te,je;const{C2cNotifyMsgArray:dA}=zo,ut=(je=(te=dA?.[0])===null||te===void 0?void 0:te.WithdrawC2cMsgNotify)===null||je===void 0?void 0:je.C2cWithdrawInfoArray;Array.isArray(ut)&&si.push(...ut)}),si}(jt));else{const to=Se.message.messageFactory.createMessage(Object.assign(Object.assign({},eo),{conversationType:"C2C",flow:"in"})),{elements:Yt}=eo;to.setElement(Yt),At.push(to)}}),{unreadMessageList:At,revokedMessageList:at}}(IA.MsgList,E);return{syncFlag:IA?.SyncFlag,unreadMessageList:xA,revokedMessageList:Qe,unreadCountList:BA,overflowUnreadCountList:mA,cookie:IA?.Cookie,groupTipList:_A}}catch(IA){console.warn(IA)}})}var Og,QI;(function(C){C[C.START_SYNC=0]="START_SYNC",C[C.SYNCING=1]="SYNCING",C[C.SYNC_COMPLETE=2]="SYNC_COMPLETE"})(Og||(Og={})),function(C){C[C.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",C[C.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(QI||(QI={}));var pi=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie="",this._localConversationIDListBeforeDisconnect=[]}install(C){this._core=C;const{constants:E}=C;C.helper.registerWorkflowStep(E.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,E.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),C.helper.registerWorkflowStep(E.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,E.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),C.helper.registerWorkflowStep(E.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,E.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.SOCKET_DISCONNECTED,this._handleDisconnect,this),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.LOGOUT,this._reset,this),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(C){return et(this,void 0,void 0,function*(){const{isAfterReOnline:E=!1,isAfterNewMessageReceived:h=!1,isAfterLogin:D=!1}=C||{};let N=Og.START_SYNC;const O=[],Y=[],j=[],IA=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:N});){const BA=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:N,syncTriggerEvent:h?QI.NEW_MESSAGE_RECEIVED:QI.LOGIN_SUCCESS});if(!BA)break;const{unreadMessageList:mA=[],revokedMessageList:_A=[],overflowUnreadCountList:xA,unreadCountList:Qe,groupTipList:Re}=BA;if(this._cookie=BA?.cookie||"",N=BA?.syncFlag,this._parseAndSaveUnreadMessageList(mA),j.push(..._A),this._updateConversationUnreadOptions({unreadCountList:Qe,overflowUnreadCountList:xA,conversationUpdateFieldList:O}),Array.isArray(Re)&&Y.push(...Re),E){const{messages:Se}=this._handleNewMessageList(mA);IA.push(...Se)}}return E?{conversationUpdateFieldList:O,revokedMessageList:j,unreadMessageMap:this._unreadDBMessageMap,groupTipList:Y,messages:IA,isUnreadC2CMessage:!0}:{conversationUpdateFieldList:O,isInstantMessage:!D,isUnreadC2CMessage:!0,revokedMessageList:j,unreadMessageMap:this._unreadDBMessageMap,groupTipList:Y}})}_syncUnreadDBMessageAfterLogin(){return et(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(C){return et(this,void 0,void 0,function*(){if(C.data.Flag===1)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(C){const{unreadCountList:E,overflowUnreadCountList:h,conversationUpdateFieldList:D}=C,{constants:{OuterConstant:{CONV_C2C:N,CONV_SYSTEM:O}}}=this._core;E?.forEach(Y=>{const{From_Account:j,UnreadCount:IA}=Y;if(j!==O){const BA=D.find(({conversationID:mA})=>mA===`${N}${j}`);BA?BA.unreadCount=IA:D.push({conversationID:`${N}${j}`,unreadCount:IA,type:N})}}),h?.forEach(Y=>{const{From_Account:j,LastMsgTime:IA}=Y;j!==O&&(D.find(({conversationID:BA})=>BA===`${N}${j}`)||D.push({conversationID:`${N}${j}`,type:N,lastMsgTime:IA}))})}_syncUnreadDBMessageAfterReOnline(){return et(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(C){var E;const{messageDataHandler:h}=this._core.message||{},D=(E=this._core.store.get("login"))===null||E===void 0?void 0:E.userId,{from:N,nick:O,avatar:Y,conversationID:j=""}=C;if(N!==D){const IA=h.getLatestMsgSentByPeer(j);if(IA){const{nick:BA,avatar:mA}=IA;O&&Y?O===BA&&Y===mA||h.updateNickAndAvatarOfSentMessage({conversationID:j,latestNick:O,latestAvatar:Y,isSentByMe:!1}):(C.nick=BA,C.avatar=mA)}}else{const IA=h.getLatestMsgSentByMe(j);!IA||O===IA.nick&&Y===IA.avatar||h.updateNickAndAvatarOfSentMessage({conversationID:j,latestNick:O,latestAvatar:Y,isSentByMe:!0})}}_handleNewMessageList(C){const{messageDataHandler:E}=this._core.message||{},h=new Map,D=[];return C.forEach(N=>{this._updateMessageProfile(N);let O=N.isModified===1;if(E.isMessageSentByCurrentInstance(N)?N.isModified=O:O=!1,N.isOnlineMessage())N._onlineOnlyFlag=!0,E.isMessageSentByCurrentInstance(N)||D.push(N);else if(this._shouldStoreUnreadMessage(N)){if(E.storeConversationMessage(N)){const{conversationID:Y,conversationType:j,conversationSubType:IA,flow:BA,_isExcludedFromUnreadCount:mA,_isExcludedFromLastMessage:_A}=N,xA=_A?"":N;h.has(Y)?(h.get(Y).lastMessage=xA,BA==="in"&&(mA||h.get(Y).unreadCount++)):h.set(Y,{conversationID:Y,type:j,subType:IA,unreadCount:mA||BA!=="in"?0:1,lastMessage:xA})}E.isMessageSentByCurrentInstance(N)&&!O||D.push(N)}}),{messages:D,conversationOptions:h}}_shouldStoreUnreadMessage(C){var E;const{conversationID:h}=C,{message:D,appStore:N,utils:{isEmpty:O}}=this._core||{},Y=Array.from(((E=N.conversationStore.getConversationMap())===null||E===void 0?void 0:E.keys())||[]),j=this._getLocalLastMessageTime(h);return!D.messageDataHandler.isInMessageList(C)&&Y.includes(h)&&this._localConversationIDListBeforeDisconnect.includes(h)&&!O(j)}_fetchUnreadDBMessage(C){return et(this,void 0,void 0,function*(){const{ssoLog:E,utils:{safeStringify:h}}=this._core;try{E.debug("_fetchUnreadDBMessage",`unread-message-synchronizer._fetchUnreadDBMessage options:${h(C)}`);const N=yield xu(C,this._core);if(!N)return null;const{syncFlag:O,unreadMessageList:Y,revokedMessageList:j,cookie:IA,unreadCountList:BA,overflowUnreadCountList:mA,groupTipList:_A}=N;return this._parseAndSaveUnreadMessageList(Y),{syncFlag:O,cookie:IA,unreadMessageList:Y,revokedMessageList:j,unreadCountList:BA,overflowUnreadCountList:mA,groupTipList:_A}}catch(D){console.log(D)}})}_canContinueSync({cookie:C,syncFlag:E}){var h;return E===Og.START_SYNC||E===Og.SYNCING&&!(!((h=this._core)===null||h===void 0)&&h.helper.isEmpty(C))}_parseAndSaveUnreadMessageList(C){C.forEach(E=>{const{ID:h}=E;this._unreadDBMessageMap.set(h,E)})}_handleDisconnect(){var C;const{appStore:E}=this._core;this._localConversationIDListBeforeDisconnect=Array.from(((C=E.conversationStore.getConversationMap())===null||C===void 0?void 0:C.keys())||[])}_getLocalLastMessageTime(C){const{message:E}=this._core,h=E.messageDataHandler.getLocalMessageList(C),D=h[h.length-1];return D?.time}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var C,E;(C=this._core)===null||C===void 0||C.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(E=this._core)===null||E===void 0||E.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},mB=new class{init(C){var E;this._core=C,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.DESTROY,this._dispose,this),document?.addEventListener("visibilitychange",this._visibilityChangeHandler),(E=this._core)===null||E===void 0||E.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var C,E;const h=document?.visibilityState==="visible";(C=this._core)===null||C===void 0||C.store.set("activityMonitor",{isActive:h}),(E=this._core)===null||E===void 0||E.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:h})}_reset(){var C;(C=this._core)===null||C===void 0||C.store.clear("activityMonitor")}_dispose(){document?.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:C,InnerEvent:E}=this._core;C.unSubscribeInnerEvent(E.DESTROY,this._dispose,this),this._reset()}},Gl=new class{init(C){var E;this._core=C,this._bindAppActivityEvent(),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.DESTROY,this._dispose,this),(E=this._core)===null||E===void 0||E.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var C,E,h,D,N;const{MINI_APP_NAMESPACE:O,IN_TT_MINI_GAME:Y,IN_WX_MINI_GAME:j}=((C=this._core)===null||C===void 0?void 0:C.utils)||{};Y||j?((E=O?.onShow)===null||E===void 0||E.call(O,()=>{var IA,BA;(IA=this._core)===null||IA===void 0||IA.store.set("activityMonitor",{isActive:!0}),(BA=this._core)===null||BA===void 0||BA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(h=O?.onHide)===null||h===void 0||h.call(O,()=>{var IA,BA;(IA=this._core)===null||IA===void 0||IA.store.set("activityMonitor",{isActive:!1}),(BA=this._core)===null||BA===void 0||BA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):((D=O?.onAppShow)===null||D===void 0||D.call(O,()=>{var IA,BA;(IA=this._core)===null||IA===void 0||IA.store.set("activityMonitor",{isActive:!0}),(BA=this._core)===null||BA===void 0||BA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(N=O?.onAppHide)===null||N===void 0||N.call(O,()=>{var IA,BA;(IA=this._core)===null||IA===void 0||IA.store.set("activityMonitor",{isActive:!1}),(BA=this._core)===null||BA===void 0||BA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var C;(C=this._core)===null||C===void 0||C.store.clear("activityMonitor")}_dispose(){const{notificationCenter:C,InnerEvent:E}=this._core;C.unSubscribeInnerEvent(E.DESTROY,this._dispose,this),this._reset()}},kl=new class{init(C){const{IN_MINI_APP:E,IN_WX_MINI_PLUGIN:h}=C.helper;h||(E?Gl.init(C):mB.init(C))}};const NC="none",_l="online";var xg=new class{init(C){this._core=C,this._activateNetworkMonitoring(),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return et(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(C){var E,h;const{isConnected:D,networkType:N}=C;(E=this._core)===null||E===void 0||E.store.set("netWorkMonitor",{isNetworkOnline:D,networkType:N}),(h=this._core)===null||h===void 0||h.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:D,networkType:N})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:_l})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:NC})}_reset(){var C;this._deactivateNetworkMonitoring(),(C=this._core)===null||C===void 0||C.store.clear("netWorkMonitor")}_dispose(){var C,E;(C=this._core)===null||C===void 0||C.notificationCenter.unSubscribeInnerEvent((E=this._core)===null||E===void 0?void 0:E.InnerEvent.DESTROY,this._dispose,this),this._reset()}},qI=new class{init(C){this._core=C,this._activateNetworkMonitoring(),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return et(this,void 0,void 0,function*(){try{const{utils:{MINI_APP_NAMESPACE:C}}=this._core;this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),C.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(C){console.error(C)}})}_deactivateNetworkMonitoring(){if(this._mpNetworkStatusCallback!==null){const{utils:{MINI_APP_NAMESPACE:C}}=this._core;C.offNetworkStatusChange&&C.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null}}_onNetworkStatusChange(C){var E,h;const{isConnected:D,networkType:N}=C;(E=this._core)===null||E===void 0||E.store.set("netWorkMonitor",{isNetworkOnline:D,networkType:N}),(h=this._core)===null||h===void 0||h.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:D,networkType:N})}_reset(){var C;this._deactivateNetworkMonitoring(),(C=this._core)===null||C===void 0||C.store.clear("netWorkMonitor")}_dispose(){var C,E;(C=this._core)===null||C===void 0||C.notificationCenter.unSubscribeInnerEvent((E=this._core)===null||E===void 0?void 0:E.InnerEvent.DESTROY,this._dispose,this),this._reset()}},mE=new class{init(C){const{IN_MINI_APP:E}=C.utils;E?qI.init(C):xg.init(C)}},DE=new class{constructor(){this.name="SystemStateMonitor"}install(C){kl.init(C),mE.init(C)}};const DB=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.*"]),Rn="tui_room_svr.*";var ps=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=DB}install(C){this._core=C;const{notificationCenter:E,InnerEvent:h,helper:D}=C;E.subscribeInnerEvent(h.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),E.subscribeInnerEvent(h.LOGOUT,this._reset,this),E.subscribeInnerEvent(h.DESTROY,this._dispose,this),E.subscribeInnerEvent("im_open_push.msg_push",E.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),D.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),D.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(C){return et(this,void 0,void 0,function*(){const E="transferBusinessCommand";try{const{serviceCommand:h=Rn}=C||{};if(!this._isValidTransferredCommand(h))throw new this._core.helper.ChatError({code:2995,functionName:E});return{code:0,data:(yield function(N,O){return et(this,void 0,void 0,function*(){const{helper:Y,channel:j}=O,{serviceCommand:IA=Rn,data:BA}=N||{};let mA={};try{mA=typeof BA=="string"?JSON.parse(BA):BA}catch(Qe){console.warn(Qe)}const _A=Y.generateProtocolData({servcmd:IA,data:mA}),xA=`${_A.head.seq}${IA}`;return j.sendPacket(_A,{requestId:xA,shouldRejectOnError:!1})})}(C,this._core))||{}}}catch(h){throw console.warn(h),new this._core.helper.ChatError({code:h?.errorCode,message:h?.errorInfo,data:{},functionName:E})}})}_onCloudConfigUpdate(C={}){try{if(typeof C.rtc_cmd!="string")return;const E=JSON.parse(C.rtc_cmd);Array.isArray(E)&&(this._transferredCommands=new Set([...this._transferredCommands,...E]))}catch(E){console.log(E)}}_isValidTransferredCommand(C=""){const E=`${C?.split(".")[0]}.*`;return this._transferredCommands.has(E)}_onServerPushBusinessCommand(C){const{OuterEvent:E,notificationCenter:h}=this._core,{MsgContent:D}=C||{},{ROOM_CUSTOM_DATA_RECEIVED:N}=E;h.emitOuterEvent(N,{name:N,data:D})}_reset(){this._transferredCommands=DB}_dispose(){const{notificationCenter:C,InnerEvent:E}=this._core;this._reset(),C.unSubscribeInnerEvent(E.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),C.unSubscribeInnerEvent(E.LOGOUT,this._reset,this),C.unSubscribeInnerEvent(E.DESTROY,this._dispose,this),C.unSubscribeInnerEvent("im_open_push.msg_push",C.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const ag=new class{init(C){this.core=C}};function yB(C){return et(this,void 0,void 0,function*(){var E;const{message:h,user:D,appStore:N,constants:{OuterConstant:O}}=ag.core,Y=N.conversationStore.getConversationMap();if(Y.has(C)){const IA=(E=Y.get(C))===null||E===void 0?void 0:E.userProfile;if(IA&&C.startsWith(O.CONV_C2C)){const{avatar:BA,nick:mA}=IA;ag.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:C,latestAvatar:BA,latestNick:mA,isSentByMe:!1})}}const{data:j}=(yield D.userProfile.getMyProfile())||{};if(j){const{avatar:IA,nick:BA}=j;h.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:C,latestAvatar:IA,latestNick:BA,isSentByMe:!0})}})}function KI(C){return et(this,void 0,void 0,function*(){const E=C.map(h=>h.revoker);try{const h=yield function(D){return et(this,void 0,void 0,function*(){var N,O;const Y=yield(N=ag.core.user.userProfile)===null||N===void 0?void 0:N.getUserProfile({userIDList:D});return Y?.data?(O=Y.data)===null||O===void 0?void 0:O.reduce((j,{userID:IA,nick:BA,avatar:mA})=>(j[IA]={nick:BA||"",avatar:mA||""},j),{}):null})}(E);h&&C.forEach(D=>{const{revoker:N}=D;h[N]&&(D.revokerInfo.nick=h[N].nick||"",D.revokerInfo.avatar=h[N].avatar||"",D.revokerInfo.userID=N)})}catch(h){console.debug(h)}})}const RB=1,Wn=2,yE=20,wr=2500,MB=1,Yg=300;function TC(C){return et(this,void 0,void 0,function*(){var E,h;const{appStore:D,utils:{isEmpty:N},common:{getCurrentUserID:O},notificationCenter:Y,OuterEvent:j,OuterConstant:{CONV_C2C:IA}}=ag.core,{messageList:BA,conversationID:mA}=C,_A=D.conversationStore.getConversationMap();let xA=(E=_A.get(mA))===null||E===void 0?void 0:E.peerReadTime;if(!xA){const Re=mA.replace(IA,""),Se=yield function(At){return et(this,void 0,void 0,function*(){const at={To_Account:At};return ag.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:at})})}([Re]);if(Se){const{ReadTime:At}=Se;xA=At?.[0],_A.has(mA)&&(_A.get(mA).peerReadTime=xA)}}if(_A.has(mA)){const Re=(h=_A.get(mA))===null||h===void 0?void 0:h.lastMessage;N(Re)||Re.fromAccount===O()&&Re.lastTime<=xA&&!Re.isPeerRead&&(Re.isPeerRead=!0,D.conversationStore.updateConversation(mA,{lastMessage:Re}))}const Qe=[];BA.forEach(Re=>{Re.time<=xA&&!Re.isPeerRead&&Re.flow==="out"&&(Re.isPeerRead=!0,Qe.push(Re))}),Qe.length>0&&Y.emitOuterEvent(j.MESSAGE_READ_BY_PEER,{name:j.MESSAGE_READ_BY_PEER,data:Qe})})}var jI=new class{init(C){this._core=C,C.helper.registerApi({apiName:"getMessageList",context:this}),C.helper.registerApi({apiName:"getMessageListHopping",context:this}),C.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(C){return et(this,void 0,void 0,function*(){try{const{message:E,OuterConstant:{Direction:h,CONV_C2C:D,CONV_GROUP:N},InnerEvent:{HISTORY_MESSAGE_FETCHED:O},notificationCenter:Y}=this._core,{conversationID:j,nextReqMessageID:IA}=C,BA=yE;if(j==="@TIM#SYSTEM")return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const mA=this._getAvailableLocalMessagesCount({conversationID:j,nextReqMessageID:IA});if(this._needFetchHistoryMessageList({conversationID:j,availableLocalMessagesCount:mA,targetCount:BA})){let _A=null;if(j.startsWith(N)?_A=yield E.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:j,sequence:Number(IA),count:BA,direction:h.FORWARD,shouldMarkCompleted:!0}):j.startsWith(D)&&(_A=yield E.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:j,messageID:IA,count:BA,direction:h.FORWARD,shouldMarkCompleted:!0})),_A){const{nextReqMessageIDFromServer:xA,hasNoMoreHistoryMessage:Qe,messageList:Re}=_A,Se=E.messageDataHandler.prependLocalMessageList({messageList:Re,conversationID:j});(function(ri){const{appStore:St,message:eo,OuterConstant:to}=ag.core,Yt=St.conversationStore.getConversation(ri),si=eo.messageDataHandler.getLocalMessageList(ri);if(!Yt||si.length===0||ri===to.CONV_SYSTEM)return;const zo=[];for(let je=0;jedA.isRevoked).length;te=zo.length-Yt.unreadCount-je}else te=zo.length-Yt.unreadCount;for(let je=0;jeri.isRevoked);yield KI(at),Y.emitInnerEvent(O,Se);const jt={nextReqMessageID:Qe?"":String(xA),messageList:At,isCompleted:Qe},Bi=At.map(ri=>ri.sequence);return{code:0,data:jt,successLog:{message:`conversationID: ${j} nextReqMessageID: ${IA} availableLocalMessagesCount: ${mA} sequenceList: ${JSON.stringify(Bi)}`}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:j,nextReqMessageID:IA,count:BA}),successLog:{message:`conversationID: ${j} nextReqMessageID: ${IA} availableLocalMessagesCount: ${mA}}`}}}catch(E){const{code:h,message:D}=E||{};throw new this._core.helper.ChatError({code:h,message:D,moreMessage:`options: ${this._core.utils.safeStringify(C)}`})}})}getMessageListHopping(C){return et(this,void 0,void 0,function*(){var E,h;const{OuterConstant:{Direction:D,CONV_C2C:N,CONV_GROUP:O},utils:{safeStringify:Y}}=this._core,{conversationID:j,sequence:IA,time:BA,direction:mA=D.FORWARD}=C,{utils:{isEmpty:_A},message:xA,notificationCenter:Qe,InnerEvent:{HISTORY_MESSAGE_FETCHED:Re}}=this._core;if(![D.BACKWARD,D.FORWARD].includes(mA))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${Y(C)}`});let{count:Se=yE}=C;Se=Se>yE?yE:Se;let At=null;if(j.startsWith(O)){if(At=yield xA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:j,sequence:IA,count:Se,direction:mA}),At){const{nextReqMessageIDFromServer:at,hasNoMoreHistoryMessage:jt,messageList:Bi,invisibleSequenceList:ri}=At;if(this._core.message.messageDataHandler.storeSparseMessageList(Bi),Qe.emitInnerEvent(Re,Bi),mA===D.FORWARD){const St=jt&&at<1;return{code:0,data:{messageList:Bi,isCompleted:St,nextMessageSeq:St?"":at}}}if(mA===D.BACKWARD){if(_A(Bi)&&_A(ri))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const St=((E=Bi?.[Bi.length-1])===null||E===void 0?void 0:E.sequence)||0,eo=((h=ri?.[ri.length-1])===null||h===void 0?void 0:h.sequence)||0;return{code:0,data:{messageList:Bi.filter(to=>to.sequence>=IA),isCompleted:!jt,nextMessageSeq:jt?Math.max(St,eo)+1:""}}}return{code:0,data:At}}}else if(j.startsWith(N)&&(At=yield xA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:j,count:Se+1,time:BA,direction:mA}),At)){const{messageList:at,lastMessageTime:jt,hasNoMoreHistoryMessage:Bi}=At;return Qe.emitInnerEvent(Re,at),Bi||(mA===D.FORWARD?at.shift():at.pop()),xA.messageDataHandler.storeSparseMessageList(at),yield TC({messageList:at,conversationID:j}),{code:0,data:{messageList:at,isCompleted:Bi,nextMessageTime:Bi?"":jt}}}})}clearHistoryMessage(C){return et(this,void 0,void 0,function*(){var E;const{appStore:h,common:{ChatError:D,getCurrentUserID:N},OuterConstant:{CONV_C2C:O,CONV_GROUP:Y},apiMap:j,message:IA}=this._core,BA=h.conversationStore.getConversation(C);if(!BA)throw new D({code:wr});const mA={fromAccount:N()},{type:_A}=BA;_A===O?(mA.type=RB,mA.toAccount=C.replace(O,"")):_A===Y&&(mA.type=Wn,mA.toGroupID=C.replace(Y,""));try{return yield(E=j?.setMessageRead)===null||E===void 0?void 0:E.call(j,{conversationID:C}),(yield function(Qe){return et(this,void 0,void 0,function*(){const{fromAccount:Re,type:Se,toAccount:At,toGroupID:at}=Qe,jt={From_Account:Re,Type:Se,To_Account:At,ToGroupid:at};return ag.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:jt})})}(mA))&&(IA.messageDataHandler.deleteConversationMessageList(C),IA.messageHistory.completedHistoryConversations.delete(C),IA.messageHistory.clearHistoryMessageListFetchAnchors(C),this._updateConversationLastMessage(C)),{code:0,data:{conversationID:C},successLog:{message:`convID:${C}`}}}catch(xA){const{errorCode:Qe}=xA;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:Qe,moreMessage:`convID:${C}`})}})}_updateConversationLastMessage(C){const{appStore:E}=this._core;E.conversationStore.updateConversation(C,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:C,nextReqMessageID:E}){const{OuterConstant:{CONV_C2C:h,CONV_GROUP:D}}=this._core,N=this._core.message.messageDataHandler.getLocalMessageList(C),{length:O}=N;if(!E)return O;let Y=-1;return C?.startsWith(h)?Y=N.findIndex(j=>j.ID===E):C?.startsWith(D)&&(Y=N.findIndex(j=>E.includes("-")?j.ID===E:String(j.sequence)===E)),Y===-1?0:Y}_needFetchHistoryMessageList({conversationID:C,availableLocalMessagesCount:E,targetCount:h}){const{message:D}=this._core;return EE.startsWith(N)?xA.ID===h:String(xA.sequence)===h),mA=_A>D?_A-D:0,IA=_A):mA=j>D?j-D:0,BA.messageList=Y.slice(mA,_A),BA.isCompleted=IA<=D&&O.messageHistory.completedHistoryConversations.has(E),BA.isCompleted?BA.nextReqMessageID="":BA.nextReqMessageID=this._generateNextReqMessageID({conversationID:E,targetIndex:mA}),E.startsWith(N)&&(yield yB(E),yield TC({messageList:BA.messageList,conversationID:E})),BA})}_generateNextReqMessageID({conversationID:C,targetIndex:E}){const h=this._core.message.messageDataHandler.getLocalMessageList(C);return C.startsWith("C2C")?h[E].ID:String(h[E].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(C){this._core=C;const{common:{workflowManager:E},constants:{WORKFLOW_NAME:h,WORKFLOW_STEP:D,InnerEvent:N}}=C;E.registerWorkflowStep(h.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),E.registerWorkflowStep(h.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.C2C_HISTORY_MESSAGE_RECOVER,this._syncC2COfflineMessage,this),C.notificationCenter.subscribeInnerEvent(N.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncGroupOfflineMessage(C){const{conversationList:E}=C?.result||{},{OuterConstant:h,utils:{isArray:D}}=this._core;if(D(E)){const N=E.filter(O=>O.type===h.CONV_GROUP&&O.groupProfile.type!==h.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(N)}}_recoverGroupHistoryMessage(C){return et(this,void 0,void 0,function*(){const{OuterConstant:E}=this._core,h=[],D=[];return yield Promise.all(C?.map(N=>et(this,void 0,void 0,function*(){const{groupProfile:{groupID:O}={},lastMessage:{lastSequence:Y}={}}=N,j=`${E.CONV_GROUP}${O}`;let IA=this._getLocalLastMessageSequence(j);this._shouldRecoverHistory({localLastMessageSequence:IA,serverLastMessageSequence:Y})&&(yield this._recoverGroupHistoryForConversation({conversationID:j,localLastMessageSequence:IA,serverLastMessageSequence:Y,groupTipList:D})),h.push(j.replace(E.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:h,groupTipList:D}})}_recoverGroupHistoryForConversation(C){return et(this,arguments,void 0,function*({conversationID:E,localLastMessageSequence:h,serverLastMessageSequence:D,groupTipList:N}){try{const{utils:{isArray:O,isObject:Y,isEmpty:j},OuterEvent:IA,OuterConstant:BA,notificationCenter:mA,message:_A,appStore:xA,common:{getMessagePreviewText:Qe,buildLastMessage:Re}}=this._core,Se=D-h,At=Math.min(20,Se),at={},jt=yield _A.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:E,sequence:h+At,direction:BA.Direction.FORWARD,count:At}),{nextReqMessageIDFromServer:Bi,hasNoMoreHistoryMessage:ri,messageList:St,serverGroupTipList:eo}=jt;O(eo)&&N.push(...eo);const to=ri&&Bi<0,Yt=[];if(O(St)&&(St.forEach(si=>{_A.messageReceiver.groupMessageReceiver.updateMessageProfile(si),si.from===BA.CONV_SYSTEM&&(si.isSystemMessage=!1),_A.messageDataHandler.storeConversationMessage(si)&&!j(si.payload)&&(Yt.push(si),si._isExcludedFromLastMessage||(at.lastMessage=Re(si)))}),Yt.length>0&&mA.emitOuterEvent(IA.MESSAGE_RECEIVED,{name:IA.MESSAGE_RECEIVED,data:Yt})),!to&&St.length>0){const si=St[St.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:E,localLastMessageSequence:si,serverLastMessageSequence:D,groupTipList:N})}Y(at.lastMessage)&&(at.lastMessage.messageForShow=Qe(at.lastMessage.type,at.lastMessage.payload),xA.conversationStore.updateConversation(E,at))}catch(O){this._core.ssoLog.error("_recoverGroupHistoryForConversation",`Recovery failed for conversation:${E}`,{error:O})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:C}=this._core,E=C.messageDataHandler.getContinuousMessagesByConversation();for(const[h,D]of E){const N=Array.from(D.values());if(N?.length>0){const O=N[N.length-1];h.startsWith("C2C")?this._lastMessageTimeMapOnDisconnect.set(h,O.time):h.startsWith("GROUP")&&this._lastMessageSequenceMapOnDisconnect.set(h,O.sequence)}}}_getLocalLastMessageSequence(C){const{message:E}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(C))return this._lastMessageSequenceMapOnDisconnect.get(C);const h=E.messageDataHandler.getLocalMessageList(C),D=h[h.length-1];return D?.sequence}_shouldRecoverHistory(C){const{localLastMessageSequence:E,serverLastMessageSequence:h}=C;if(typeof E!="number"||typeof h!="number")return!1;const D=h-E;return h!==0&&E>0&&D>=MB&&D{O.type===h.CONV_C2C&&N.push(O)}),this._recoverC2CHistoryMessage(N)}}_recoverC2CHistoryMessage(C){return et(this,void 0,void 0,function*(){yield Promise.all(C?.map(E=>et(this,void 0,void 0,function*(){const{conversationID:h,lastMessage:{lastTime:D}={}}=E,N=this._getLocalLastMessageTime(h);this._shouldRecoverC2CHistory({localLastMessageTime:N,serverLastMessageTime:D})&&(yield this._recoverHistoryForC2CConversation({conversationID:h,localLastMessageTime:N,serverLastMessageTime:D}))})))})}_shouldRecoverC2CHistory(C){const{localLastMessageTime:E,serverLastMessageTime:h}=C,D=h-E;return E>0&&D>=1&&D<=600}_recoverHistoryForC2CConversation(C){return et(this,void 0,void 0,function*(){var E;const{conversationID:h,localLastMessageTime:D,serverLastMessageTime:N}=C,{utils:{isArray:O,isObject:Y,isEmpty:j,safeStringify:IA},OuterEvent:BA,OuterConstant:mA,notificationCenter:_A,message:xA,appStore:Qe,common:{getMessagePreviewText:Re,buildLastMessage:Se}}=this._core;try{const At={},at=yield xA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:h,direction:mA.Direction.BACKWARD,time:D,count:20});if(j(at))return;const{hasNoMoreHistoryMessage:jt,messageList:Bi}=at,ri=[];O(Bi)&&(Bi.forEach(eo=>{xA.messageDataHandler.storeConversationMessage(eo)&&!j(eo.payload)&&(ri.push(eo),eo._isExcludedFromLastMessage||(At.lastMessage=Se(eo)))}),ri.length>0&&_A.emitOuterEvent(BA.MESSAGE_RECEIVED,{name:BA.MESSAGE_RECEIVED,data:ri}));const St=(E=Bi[Bi.length-1])===null||E===void 0?void 0:E.time;!jt&&St>N&&(yield this._recoverHistoryForC2CConversation({conversationID:h,localLastMessageTime:St,serverLastMessageTime:N})),Y(At.lastMessage)&&(At.lastMessage.messageForShow=Re(At.lastMessage.type,At.lastMessage.payload),Qe.conversationStore.updateConversation(h,At))}catch(At){this._core.ssoLog.error("_recoverHistoryForC2CConversation",`Recovery failed for conversation:${h} error: ${IA(At)}`)}})}_getLocalLastMessageTime(C){const{message:E}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(C))return this._lastMessageTimeMapOnDisconnect.get(C);const h=E.messageDataHandler.getLocalMessageList(C),D=h[h.length-1];return D?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},wB=new class{constructor(){this.name="HistoryMessage"}install(C){this._core=C,ag.init(C),jI.init(C),ha.init(C),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.LOGOUT,this._reset,this),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:C,InnerEvent:E}=this._core;C.unSubscribeInnerEvent(E.LOGOUT,this._reset,this),C.unSubscribeInnerEvent(E.DESTROY,this.dispose,this),ha.dispose()}_reset(){ha.reset()}},pa=new class{init(C){this.core=C}},sg=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(C){const{helper:{registerExperimentalAPI:E}}=C;this._core=C,E("reportModalView",this),E("reportTUIFeatureUsage",this),E("reportRoomEngineEvent",this)}reportModalView(C){const{ssoLog:E,utils:{safeStringify:h,isString:D}}=this._core;try{if(!D(C))throw new Error("reportModalView data is not a string");E.createSSOLogData({method:"reportModalView",message:C,eventType:30}).end(!0)}catch(N){E.debug(`reportModalView Report failed: ${h(N)}`)}}reportTUIFeatureUsage(C){const{ssoLog:E,utils:{safeStringify:h,isEmpty:D}}=this._core,{atomicStoreID:N}=C;try{D(N)||this._reportedAtomicStoreIDs.has(N)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${C.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:N}),this._reportedAtomicStoreIDs.add(N))}catch(O){E.debug(`reportTUIFeatureUsage Report failed: ${h(O)}`)}}reportRoomEngineEvent(C){const{utils:{safeStringify:E},ssoLog:h}=this._core;try{h.debug(`reportRoomEngineEvent Report: ${E(C)}`);const{eventId:D,eventCode:N,eventResult:O,eventMessage:Y,moreMessage:j,extensionMessage:IA}=C;h.createSSOLogData({method:IA,code:D,message:Y,eventType:30,costTime:N,uiPlatform:O,moreMessage:j}).end(!0)}catch(D){h.debug(`reportRoomEngineEvent Report failed: ${E(D)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},GC=new class{constructor(){this.name="DataReport"}install(C){this._core=C;const{notificationCenter:E,InnerEvent:{LOGOUT:h,DESTROY:D}}=C;pa.init(C),sg.init(C),E.subscribeInnerEvent(h,this._reset,this),E.subscribeInnerEvent(D,this._dispose,this)}_reset(){sg.reset()}_dispose(){const{notificationCenter:C,InnerEvent:{LOGOUT:E,DESTROY:h}}=this._core;C.unSubscribeInnerEvent(E,this._reset,this),C.unSubscribeInnerEvent(h,this._dispose,this),sg.dispose()}};let bl=BE.STANDARD,Mn=[];bl=BE.BASIC,Mn=[fB,Ou,pi,DE,ps,wB,GC];function WI(C,E){const{operationType:h,memberInfoList:D,operatorInfo:N}=C||{};let O={};if($r(D)?$r(N)||(O=N):h!==Qs.JOINED&&h!==Qs.KICKED&&h!==Qs.ADMIN_SET&&h!==Qs.ADMIN_CANCELED||(O=Object.assign({},D[0])),!$r(O)){const{nick:Y="",avatar:j=""}=O;E.nick=Y,E.avatar=j}}const RE=C=>({lastTime:C?.time||C?.lastTime||0,lastSequence:C?.sequence||C?.lastSequence||0,fromAccount:C?.from||C?.fromAccount||"",messageForShow:bc(C?.type,C?.payload),payload:C?.payload||null,type:C?.type||"",isRevoked:C?.isRevoked||!1,cloudCustomData:C?.cloudCustomData||"",onlineOnlyFlag:C?._onlineOnlyFlag||!1,nick:C?.nick||"",nameCard:C?.nameCard||"",version:C?.version||0,isPeerRead:C?.isPeerRead||!1,revoker:C?.revoker||null});var dI=Object.freeze({__proto__:null,ChatError:lo,WorkflowManager:Ir,buildAndSendPacket:Ls,buildLastMessage:RE,get builtInPlugins(){return Mn},checkBusinessCapabilityBits:dE,deepMerge:hs,getCurrentUserID:Wr,getErrorMessage:Tc,getMessagePreviewText:bc,isC2CConv:C=>s(C)&&C.slice(0,3)===us.CONV_C2C,isCommunity:Ka,isGroupConv:C=>s(C)&&C.slice(0,5)===us.CONV_GROUP,isInternational:vl,isTopic:ca,isUnlimitedAVChatRoom:function(){var C;return!!(!((C=ZA.store.get("instance"))===null||C===void 0)&&C.unlimitedAVChatRoom)},liteChatInstanceMap:og,registerInterceptor:mn,registerValidateConfig:Lg,requireAuth:ds,get sdkEdition(){return bl},setGroupTipsUserInfo:WI,t:pB,updateGroupAtInfo:(C,E)=>{const{CONV_AT_ME:h,CONV_AT_ALL:D,CONV_AT_ALL_AT_ME:N}=vo;if(function(j,IA){const{CONV_AT_ME:BA,CONV_AT_ALL:mA,CONV_AT_ALL_AT_ME:_A}=vo,{groupID:xA,sequence:Qe}=j;let Re=!1;return Ka({groupID:xA})&&IA.forEach(Se=>{Se.messageSequence===Qe&&(Se.atTypeArray.includes(BA)&&j.groupAtType.includes(mA)&&(Se.atTypeArray=[_A]),Se.atTypeArray.includes(mA)&&j.groupAtType.includes(BA)&&(Se.atTypeArray=[_A],Se.__random=j.__random,Se.__sequence=j.__sequence),Re=!0)}),Re}(C,E))return;let O=[...C.groupAtType];O.includes(h)&&O.includes(D)&&(O=[N]);const Y={from:C.from,groupID:C.groupID,topicID:C.topicID,messageSequence:C.sequence,atTypeArray:O,__random:C.__random,__sequence:C.__sequence};E.push(Y)},validateAndExecute:HI,validateParameters:QB});class fs{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return fs._instance||(fs._instance=new fs),fs._instance}static setInstance(E){fs._instance=E}installBuiltInPlugin(E){E&&this._installPlugin(E,this._builtInPlugins)}installExternalPlugin(E){E&&this._installPlugin(E,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(E,h){let D=[];D=B(E)?E:[E];const N=D.findIndex(Y=>Y?.name==="AVChatRoom"),O=N>-1?D.splice(N,1):[];D.forEach(Y=>{this._isPluginInstalled(Y.name)||(Y&&Ag(Y.install)?(h.add(Y.name),Ag(Y.getInstalledSubPlugins)?(O?.forEach(j=>h.add(j?.name)),Y.install(Wo.getInstance().exposeApiForPlugin(),O)):Y.install(Wo.getInstance().exposeApiForPlugin()),Ag(Y.handleLoginSuccess)&&this._isLoggedIn()&&Y.handleLoginSuccess()):Ag(Y)?(h.add(Y.name),Y(Wo.getInstance().exposeApiForPlugin()),Ag(Y.handleLoginSuccess)&&this._isLoggedIn()&&Y.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(E){return this._builtInPlugins.has(E)||this._externalPlugins.has(E)}_isLoggedIn(){var E;return((E=ZA.store.get("login"))===null||E===void 0?void 0:E.isLoggedIn)===!0}}var Uc=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(C){return this._conversationMap.get(C)}updateConversation(C,E,h){const{emit:D=!0,needSort:N=!1}=h||{},O=this._conversationMap.get(C);O&&!$r(E)&&(Object.keys(E).forEach(Y=>{O[Y]=E[Y]}),D&&ZA.notificationCenter.emitInnerEvent(Gt.CONVERSATION_UPDATED,{needSort:N}))}deleteConversation(C){this._conversationMap.has(C)&&(this._conversationMap.delete(C),ZA.notificationCenter.emitInnerEvent(Gt.CONVERSATION_UPDATED))}},ms=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(C){return this._groupMap.get(C)}updateGroup(C,E){const h=this._groupMap.get(C);h&&!$r(E)&&Object.keys(E).forEach(D=>{h[D]=E[D]})}},zI=new class{constructor(){this._messagesByConversation=new Map}updateMessage(C,E,h){var D;const{operation:N,updateUnreadCount:O=!0}=h,Y=Vo(h,["operation","updateUnreadCount"]),j=[];for(const IA of E){const BA=(D=this._messagesByConversation.get(C))===null||D===void 0?void 0:D.get(IA);if(!BA)return!1;Object.keys(Y).forEach(mA=>{BA[mA]=Y[mA]}),j.push(BA)}return this._emitMessageStoreOperationEvent(N,{conversationID:C,messageList:j,updateUnreadCount:O}),j}getMessagesByConversation(C){var E;return[...((E=this._messagesByConversation.get(C))===null||E===void 0?void 0:E.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(C,E){const{conversationID:h}=E;ca(h)?ZA.notificationCenter.emitInnerEvent(qa[C],E):ZA.notificationCenter.emitInnerEvent(C,E)}},xn=new class{constructor(){this.userProfileMap=new Map,this.friendMap=new Map}getUserProfileMap(){return this.userProfileMap}getFriendMap(){return this.friendMap}getUserProfile(C){return this.userProfileMap.get(C)}getFriend(C){return this.friendMap.get(C)}},Yu=Object.freeze({__proto__:null,conversationStore:Uc,groupStore:ms,messageStore:zI,userStore:xn});class Wo{static getInstance(){return Wo._instance||(Wo._instance=new Wo),Wo._instance}static setInstance(E){Wo._instance=E}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:ZA.notificationCenter.subscribeOuterEvent.bind(ZA.notificationCenter),off:ZA.notificationCenter.unSubscribeOuterEvent.bind(ZA.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:fs.getInstance().installExternalPlugin.bind(fs.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(E){ZA.ssoLog.debug("registerPlugin",E)}statKeyFeatureUsage(E){ZA.ssoLog.debug("statTUIKeyFeatures",E)}setLogLevel(E){ZA.ssoLog.debug("setLogLevel",E),ZA.ssoLog.setLogLevel(E)}setApplicationID(E){ZA.store.set("instance",{applicationID:E})}getApiMap(){return this._apiMap}setApiMap(E){this._apiMap=E}registerApi(E){const{common:{timeManager:h},utils:{safeStringify:D}}=ZA,{apiName:N,context:O,methodName:Y=N,matcher:j}=E;this._apiHandlersMap[N]||(this._apiHandlersMap[N]=[]),this._apiHandlersMap[N].push({context:O,methodName:Y,matcher:j}),this._apiMap[N]&&this._apiHandlersMap[N].length!==1||(this._apiMap[N]=(...IA)=>{const BA=h.getServerTimeMs();let mA=0;N==="login"&&(mA=4),tn.includes(N)&&ZA.ssoLog.debug(N,`${N} start params: ${D(IA)}`),HI(Y,IA);const _A=this._apiHandlersMap[N];for(const xA of _A)if(!xA.matcher||xA.matcher(IA))try{const Qe=xA.context[xA.methodName].bind(xA.context)(...IA);return this._isPromiseLike(Qe)?this._handleAsyncResult(Qe,N,mA,BA):(this._reportApiSuccessLog({result:Qe,apiName:N,eventType:mA,startTime:BA}),Qe)}catch(Qe){throw ZA.ssoLog.error(N,`${N} fail ${Qe?.message||Qe?.errorMessage})`,{error:Qe,costTime:h.getServerTimeMs()-BA,eventType:mA,method:N}),Qe}})}registerExperimentalAPI(E,h,D){const N=D||E;this._experimentalApiMap[E]=h[N].bind(h)}destroy(){return et(this,void 0,void 0,function*(){var E,h;try{!((E=ZA.store.get("login"))===null||E===void 0)&&E.isLogin&&(yield this._apiMap.logout()),ZA.notificationCenter.emitInnerEvent(Gt.DESTROY)}catch(D){console.debug("destroy error: ",D)}finally{ZA.notificationCenter.emitOuterEvent(kr.SDK_DESTROY,{SDKAppID:(h=ZA.store.get("instance"))===null||h===void 0?void 0:h.sdkAppId}),og.clear(),fs.getInstance().clear(),Ir.getInstance().destroy(),ZA.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:Gt,InnerEventSubType:ZA.notificationCenter.InnerEventSubType,OuterEvent:kr,OuterConstant:vo,SignalingEvent:Dl,helper:Object.assign(Object.assign(Object.assign({},ZA.utils),ZA.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:mn,registerValidateConfig:Lg,checkBusinessCapabilityBits:dE,registerWorkflowStep:Ir.getInstance().registerWorkflowStep.bind(Ir.getInstance()),ChatError:lo}),apiMap:this._apiMap},ZA),{constants:Object.assign(Object.assign({},Ml),ZA.constants),common:Object.assign(Object.assign(Object.assign({},dI),ZA.common),{workflowManager:Ir.getInstance()}),utils:ZA.utils,appStore:Yu})}callExperimentalAPI(E,h){return ZA.ssoLog.debug(`callExperimentalAPI.${E} start params: ${ZA.utils.safeStringify(h)}`),this._experimentalApiMap[E]?this._experimentalApiMap[E](h):(ZA.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${E} not found, params: ${ZA.utils.safeStringify(h)}`),Promise.reject(new lo({code:Qa.INVALID_OPERATION})))}_isPromiseLike(E){return E!==null&&typeof E=="object"&&typeof E.then=="function"}_handleAsyncResult(E,h,D,N){return E.then(O=>(this._reportApiSuccessLog({result:O,apiName:h,eventType:D,startTime:N}),O)).catch(O=>{throw ZA.ssoLog.error(h,`${h} fail ${O?.message||O?.errorMessage})`,{error:O,costTime:ZA.common.timeManager.getServerTimeMs()-N,eventType:D,method:h,startTime:N}),O})}_reportApiSuccessLog(E){let{result:h,apiName:D,startTime:N,eventType:O}=E;const{timeManager:Y}=ZA.common,{successLog:{message:j,moreMessage:IA}={message:"",moreMessage:""}}=h||{},BA=Y.getServerTimeMs();D==="login"&&(N+=Y.getTimeOffsetWithServer()),tn.includes(D)&&ZA.ssoLog.info(D,`${D} success ${j} ${IA}`,{costTime:BA-N,eventType:O,message:j,moreMessage:IA,startTime:N}),h?.successLog&&delete h.successLog}}class Oc{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:E,store:h}=ZA;h.set("login",{isReady:!1}),Wo.getInstance().registerApi({apiName:"login",context:this}),Wo.getInstance().registerApi({apiName:"logout",context:this}),Wo.getInstance().registerApi({apiName:"getLoginUser",context:this}),Wo.getInstance().registerApi({apiName:"isReady",context:this}),Wo.getInstance().registerApi({apiName:"getServerTime",context:this}),Wo.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),E.subscribeInnerEvent(Gt.RECONNECTED,this._reLogin,this),ZA.notificationCenter.subscribeInnerEvent(Gt.DESTROY,this._dispose,this)}login(E){return et(this,void 0,void 0,function*(){var h;const{sdkEdition:D}=ZA.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new lo({functionName:"login",code:Qa.REPEAT_LOGIN});const N=yield this._performLogin(E);this._validateAfterLogin(N),this._handleLoginSuccess(N),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const O=(h=ZA.channel.getSocketAdapter())===null||h===void 0?void 0:h.getId(),{appId:Y,href:j}=ZA.store.get("instance")||{},{instanceID:IA,customStatus:BA}=N||{};return{code:0,data:N,successLog:{message:D,moreMessage:`socketID:${O} instanceID:${IA} customStatus:${BA} href: ${j} appId: ${Y}`}}}catch(N){const{errorCode:O}=N;O!==Qa.REPEAT_LOGIN&&(this._latestLoginAt=0);const Y=new lo({functionName:"login",code:O});throw console.error(Y),Y}})}_reLogin(){return et(this,void 0,void 0,function*(){var E;try{if(!this._isLoginIn())return;const h=yield QE(this._customLoginInfo);if(h){const{instanceID:D,customStatus:N}=h;ZA.store.set("login",{statusInstanceId:D}),Ir.getInstance().executeWorkflow(cn.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:N,statusType:CE.USER_STATUS_ONLINE});const O=(E=ZA.channel.getSocketAdapter())===null||E===void 0?void 0:E.getId();ZA.ssoLog.info("reLogin",`socketId:${O} instanceId:${D}`)}}catch(h){console.warn(h)}})}logout(){return et(this,arguments,void 0,function*(E=ba.USER_INITIATED){const{ssoLog:h}=ZA;h.debug("logout",`logout start logoutReason: ${E}`);try{yield this._performLogout(E),h.info("logout","logout success"),ZA.ssoLog.uploadSSOLogData()}catch(D){const{errorCode:N}=D;throw new lo({functionName:"logout",code:N})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?Wr():""}isReady(){var E;return(E=ZA.store.get("login"))===null||E===void 0?void 0:E.isReady}setCustomLoginInfo(E=""){this._customLoginInfo=E}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),Ir.getInstance().reset(),ZA.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:E}=ZA.common;return E.getServerTimeMs()}_updateAndEmitSDKReady(){ZA.store.set("login",{isReady:!0}),setTimeout(()=>{ZA.notificationCenter.emitOuterEvent(kr.SDK_READY,{name:kr.SDK_READY})},1)}_updateAndEmitSDKNotReady(){ZA.store.set("login",{isReady:!1}),ZA.notificationCenter.emitOuterEvent(kr.SDK_NOT_READY,{name:kr.SDK_NOT_READY})}_validateAfterLogin(E){const h="login";if(!E)throw new lo({functionName:h,message:"login response is empty"});const{tinyID:D,a2Key:N}=E||{};if(!D)throw new lo({functionName:h,code:Qa.NO_TINYID});if(!N)throw new lo({functionName:h,code:Qa.NO_A2KEY})}_createRepeatLoginResponse(){var E;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:Tc({code:"RepeatLogin",replacement1:(E=ZA.store.get("login"))===null||E===void 0?void 0:E.userId}),repeatLogin:!0}}}_performLogin(E){return et(this,void 0,void 0,function*(){const{userID:h,userSig:D}=E;return ZA.store.set("login",{userId:h,userSig:D}),this._latestLoginAt=Date.now(),QE(this._customLoginInfo)})}_ensureAsyncComplete(){return et(this,void 0,void 0,function*(){yield new Promise(E=>{setTimeout(()=>E(null),1)})})}_handleLoginSuccess(E){const{timeManager:h}=ZA.common,{helloInterval:D,timeStamp:N,customStatus:O,purchaseBits:Y}=E,j=1e3*N;h.calculateTimeOffsetWithServer(this._latestLoginAt,j),this._helloInterval=D||120,this._updateLoginStore(E),ZA.user.userStatus.setCustomStatus(O),Ir.getInstance().executeWorkflow(cn.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:Y}),ZA.common.taskScheduler.addTask({id:wl,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(E){return function(h){return et(this,void 0,void 0,function*(){const{logoutReason:D}=h,N="im_open_status.wslogout",O=ZA.common.generateProtocolData({servcmd:N,data:{wslogout_type:D,isWebUniapp:0}}),Y=`${O.head.seq}${N}`;return yield ZA.channel.sendPacket(O,{requestId:Y})})}({logoutReason:E})}_updateLoginStore(E){const{a2Key:h,tinyID:D,instanceID:N,authKey:O}=E;ZA.store.set("login",{a2Key:h,tinyID:D,statusInstanceId:N,authKey:O,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return et(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const E="im_open_status.wshello",h=ZA.common.generateProtocolData({servcmd:E,data:{isWebUniapp:0}}),D=`${h.head.seq}${E}`;return ZA.channel.sendPacket(h,{requestId:D})}()}catch(E){ZA.ssoLog.warn("_sendOnlinePresenceRequest",` error:${E.message}`)}})}_isLoginIn(){var E;return((E=ZA.store.get("login"))===null||E===void 0?void 0:E.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){ZA.common.taskScheduler.removeTask(wl),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",ZA.store.clear("login"),ZA.store.set("login",{isReady:!1}),ZA.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:E}=ZA;E.unSubscribeInnerEvent(Gt.RECONNECTED,this._reLogin,this),E.unSubscribeInnerEvent(Gt.DESTROY,this._dispose,this)}}const ME={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},Pg={logout:!0};class gg{constructor(){this.loginAction=new Oc,this.kickedOutHandler=new bg,this.loginAction.init(),this.kickedOutHandler.init(),Lg({auth:Pg,params:ME})}}var En,Ds,Wa;(function(C){C.CONV_C2C="C2C",C.CONV_GROUP="GROUP",C.CONV_TOPIC="TOPIC",C.CONV_SYSTEM="@TIM#SYSTEM"})(En||(En={})),function(C){C.MSG_PRIORITY_HIGH="High",C.MSG_PRIORITY_NORMAL="Normal",C.MSG_PRIORITY_LOW="Low",C.MSG_PRIORITY_LOWEST="Lowest"}(Ds||(Ds={})),function(C){C.MSG_TEXT="TIMTextElem",C.MSG_CUSTOM="TIMCustomElem",C.MSG_LOCATION="TIMLocationElem",C.MSG_FACE="TIMFaceElem",C.MSG_IMAGE="TIMImageElem",C.MSG_AUDIO="TIMSoundElem",C.MSG_FILE="TIMFileElem",C.MSG_VIDEO="TIMVideoFileElem",C.MSG_GRP_TIP="TIMGroupTipElem",C.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",C.MSG_MERGER="TIMRelayElem"}(Wa||(Wa={}));const Ll={1:Ds.MSG_PRIORITY_HIGH,2:Ds.MSG_PRIORITY_NORMAL,3:Ds.MSG_PRIORITY_LOW,4:Ds.MSG_PRIORITY_LOWEST},SB=0,Pu=1;var li;(function(C){C.IN="in",C.OUT="out"})(li||(li={}));const wE=2,hI={};function vB(C){if(!C)return 0;if(hI[C]===void 0){const E=new Date,h=`3${E.getHours()}`.slice(-2),D=`0${E.getMinutes()}`.slice(-2),N=`0${E.getSeconds()}`.slice(-2);hI[C]=parseInt([h,D,N,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${hI[C]}`)}else hI[C]+=1;return hI[C]}class NB{constructor(E){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=Ds.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:h=ZA.common.timeManager.getServerTimeSeconds()||0,senderTinyID:D,currentUser:N,needReadReceipt:O,isSupportExtension:Y,customModerationConfigurationId:j,to:IA,from:BA,nick:mA="",avatar:_A="",time:xA,messageControlInfo:Qe,tinyID:Re,cloudCustomData:Se="",messageLifeTime:At,messageVersion:at=0,conversationType:jt,sequence:Bi,checkResult:ri=0,isPlaceMessage:St=0,messageFlagBits:eo,receiverList:to,isSystemMessage:Yt=!1,status:si=tg.SUCCESS,revokeReason:zo="",conversationSubType:te,clientSequence:je,protocol:dA="JSON",revokerInfo:ut={userID:"",nick:"",avatar:""},readReceiptInfo:Cr={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:lt,groupProfile:Co,atUserList:Jt,flow:mo,isRead:Fe=!1,priority:Oe=Ds.MSG_PRIORITY_NORMAL,onlineOnlyFlag:xs=!1,nameCard:Zo="",quoteInfo:ti}=E;var _n;this.clientTime=h,this.senderTinyID=D||Re,this.needReadReceipt=O===!0||O===1,this.isSupportExtension=Y===!0||Y===1,this._cmConfigID=j,this.to=IA,this.nick=mA,this.avatar=_A,this.protocol=dA,this.random=lt===void 0?(_n=_n||99999999,Math.round(Math.random()*_n)):lt,this.time=xA||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!Qe?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!Qe?.excludedFromUnreadCount,this.isModified=!!at,this.cloudCustomData=Se,this.messageLifeTime=At,this.from=BA||null,this.sequence=Bi||0,this.conversationType=jt||En.CONV_C2C,this.hasRiskContent=ri>1,this.version=at,this.isPlaceMessage=St,this.isRevoked=St===2||eo===8,this.isSystemMessage=Yt,this.readReceiptInfo=Cr,this.revokeReason=zo,this.revokerInfo=ut,this._receiverList=to,this.conversationSubType=te,this.revoker=ut?.revoker||"",this.clientSequence=je||Bi||0,this.status=si,this.atUserList=Jt||[],this.flow=mo,this.isRead=Fe,this.priority=Oe,this._onlineOnlyFlag=xs,this.nameCard=Zo,this.quoteInfo=ti,this.reInitialize(N),this._initC2CReadReceiptInfo(E),this._extractGroupInfo(Co)}getElements(){return this._elements}isOnlineMessage(){return this.messageLifeTime===0}setElement(E){Array.isArray(E)?this._elements=E:this._elements=[E],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(E=>E.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(E){this._relayFlag=E}validateBeforeSend(){var E,h,D;return this._relayFlag?{isValid:!0}:((E=this._elements)===null||E===void 0?void 0:E.length)>0?(D=(h=this._elements[0])===null||h===void 0?void 0:h.validateBeforeSend)===null||D===void 0?void 0:D.call(h):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(E){const{readReceiptSentByPeer:h,timestamp:D=0}=E;this.conversationType===En.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=h===1,this.readReceiptInfo.timestamp=D)}_extractGroupInfo(E){if(!E)return;const{From_AccountNick:h,From_AccountHeadurl:D,MsgFrom_AccountExtraInfo:N,GroupType:O}=E,{NameCard:Y}=N||{};typeof h=="string"&&(this.nick=h),typeof D=="string"&&(this.avatar=D),typeof Y=="string"&&(this.nameCard=Y),this.conversationSubType=O}reInitialize(E){E===this.from&&(this.isRead=!0),this._initSequence(E),this._concatConversationID(E),this.generateMessageID()}_concatConversationID(E){let h="";const D=this.conversationType;D!==En.CONV_SYSTEM?(h=D===En.CONV_C2C?E===this.from?this.to:this.from:this.to,this.conversationID=h?`${D}${h}`:null):this.conversationID=En.CONV_SYSTEM}_initSequence(E){this.clientSequence===0&&E&&(this.clientSequence=vB(E)),this.sequence===0&&this.conversationType===En.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===En.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(E){this.isRead=E}}class pI{static parseServerPushElement(E){const{MsgContent:h={}}=E,{Data:D,Ext:N,Desc:O}=h;return new pI({data:D,description:O,extension:N})}constructor(E){this.type=Wa.MSG_CUSTOM;const{data:h="",description:D="",extension:N=""}=E;this.content={data:h,description:D,extension:N}}transformToServerFormat(E){const{isMergerMessage:h=!1}=E||{},D=h?this.payload:this.content,{data:N,description:O,extension:Y}=D;return{MsgType:this.type,MsgContent:{Data:N,Ext:Y,Desc:O}}}validateBeforeSend(){const{isEmpty:E}=ZA.utils,h=[this.content.data,this.content.description,this.content.extension].some(D=>!E(D));return{isValid:h,error:h?null:{message:"content can not be empty"}}}}class SE{static parseServerPushElement(E){const{MsgContent:h={Text:""}}=E,{Text:D}=h;return new SE({text:D})}constructor(E){this.type=_s.MSG_TEXT,this.content={text:E.text||""}}validateBeforeSend(){var E,h;return((h=(E=this.content)===null||E===void 0?void 0:E.text)===null||h===void 0?void 0:h.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(E){const{isMergerMessage:h=!1}=E||{},D=h?this.payload:this.content,{text:N}=D;return{MsgType:this.type,MsgContent:{Text:N}}}}var ZI=new class{constructor(){this._elementClassMap={[Wa.MSG_CUSTOM]:pI,[Wa.MSG_TEXT]:SE}}init(){Wo.getInstance().registerApi({apiName:"createCustomMessage",context:this}),Wo.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(C,E){var h;(h=E).prototype!==void 0&&"constructor"in h.prototype&&(this._elementClassMap[C]=E)}getElementClass(C){return this._elementClassMap[C]}createMessage(C){const{from:E,flow:h=li.OUT}=C,{userId:D}=ZA.store.get("login")||{};this._isSendByCurrentInstance({from:E,flow:h,currentUser:D})?this._updateWithSenderInfo(C):this._isMultiEndpointSyncMessage({from:E,flow:h,currentUser:D})&&(C.flow=li.OUT);const N=Object.assign(Object.assign({},C),{currentUser:D});return new NB(N)}createCustomMessage(C){const E=Wr(),h=this.createMessage(Object.assign(Object.assign({},C),{from:E})),D=this._elementClassMap[Wa.MSG_CUSTOM];if(!h)return null;if(D){const N=new D(C.payload);h.setElement(N)}return h}createTextMessage(C){var E;if(!C)return null;const h=typeof C.payload=="string"?C.payload:((E=C?.payload)===null||E===void 0?void 0:E.text)||"",D=new SE({text:h}),N=Wr(),O=ZA.message.messageFactory.createMessage(Object.assign(Object.assign({},C),{from:N}));return O.setElement(D),O}_updateWithSenderInfo(C){var E,h;const{nick:D,avatar:N,conversationType:O,to:Y}=C,{userId:j,tinyID:IA}=ZA.store.get("login")||{},BA=xn.getUserProfile(j);return C.nick=D||BA?.nick||"",C.avatar=N||BA?.avatar||"",C.tinyID=C.tinyID||IA||"",C.from=j,C.status=tg.UNSENT,C.flow=li.OUT,O===us.CONV_GROUP&&(C.nameCard=(h=(E=ms.getGroup(Y))===null||E===void 0?void 0:E.selfInfo)===null||h===void 0?void 0:h.nameCard),C}_isMultiEndpointSyncMessage(C){const{from:E,flow:h,currentUser:D}=C;return E===D&&h===li.IN}_isSendByCurrentInstance(C){const{from:E,flow:h,currentUser:D}=C;return E===D&&h===li.OUT}};const xc={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}},TB={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},Yc={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function XI(C,E){return Object.keys(E).forEach(h=>{const{range:D,defaultValue:N}=E[h];C[h]=D.includes(C[h])?C[h]:N}),C}function Us(C){const E=C.lastIndexOf(".");return E===-1?C:C.slice(0,E)}function fI(C){const{androidInfo:E={},androidOPPOChannelID:h=""}=C,D=E.OPPOChannelID||h,N=XI(E,TB),{sound:O="",FCMChannelID:Y=""}=N,j=Vo(N,["sound","FCMChannelID"]);return Object.assign(Object.assign({},j),{Sound:Us(O),OPPOChannelID:D,GoogleChannelID:Y})}function kC(C){const{apnsInfo:E={},ignoreIOSBadge:h=!1,disableVoipPush:D}=C,N=XI(E,Yc),{ignoreIOSBadge:O,disableVoipPush:Y,enableIOSBackgroundNotification:j}=N,IA=Vo(N,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),BA=O===!0||h===!0?1:0;let mA;return r(D)||(mA=D===!1?1:0),r(Y)||(mA=Y===!1?1:0),Object.assign(Object.assign({},IA),{BadgeMode:BA,IsVoipPush:mA,ContentAvailable:j?1:0})}function Fl(C){return ZA.utils.isPlainObject(C)?{PushFlag:C.disablePush===!0?1:0,Title:C.title||"",Desc:C.description||"",Ext:C.extension||"",ApnsInfo:kC(C),AndroidInfo:fI(C)}:xc}function Pc(C){const{From_AccountHeadurl:E,From_AccountNick:h,IsNeedReadReceipt:D,IsPeerRead:N,IsSyncMsg:O,MsgBody:Y,MsgClientTime:j,MsgLifeTime:IA,MsgRandom:BA,MsgSeq:mA,MsgTimeStamp:_A,SendMsgControl:xA,SupportMessageExtension:Qe,TinyId:Re,MsgCheckResult:Se,CloudCustomData:At,MsgVersion:at,MsgFlagBits:jt,RevokerInfo:Bi,InnerSdkCustomData:ri}=C;let St,{From_Account:eo,To_Account:to}=C;if(O===1){const Yt=to;to=eo,eo=Yt}if(Bi){const{Reason:Yt,Revoker_Account:si,Revoker_FromUin:zo}=Bi;St={reason:Yt,revoker:si,revokerFromUin:zo,userID:si}}return{from:eo,avatar:E,nick:h,needReadReceipt:D===1,isSyncMessage:O,clientTime:j,messageLifeTime:IA,random:BA,sequence:mA,time:_A,messageControlInfo:{excludedFromLastMessage:xA?.NoLastMsg===1,excludedFromUnreadCount:xA?.NoUnread===1},isSupportExtension:Qe,to,tinyID:Re,checkResult:Se,cloudCustomData:At,revokerInfo:St,messageVersion:at,messageFlagBits:jt,readReceiptSentByPeer:N,elements:za(Y),onlineOnlyFlag:IA===0,quoteInfo:Ol(ri)}}function vE(C){const{From_Account:E,MsgBody:h,MsgClientTime:D,MsgRandom:N,MsgSeq:O,MsgTimeStamp:Y,To_Account:j,MsgVersion:IA,CloudCustomData:BA,MsgCheckResult:mA}=C;return{from:E,clientTime:D,random:N,sequence:O,time:Y,to:j,elements:za(h),messageVersion:IA,cloudCustomData:BA,checkResult:mA}}function di(C){const{ClientSeq:E,From_Account:h,GroupInfo:D,MsgBody:N,MsgClientTime:O,MsgRandom:Y,MsgSeq:j,MsgTimeStamp:IA,SendMsgControl:BA,SupportMessageExtension:mA,TinyId:_A,CloudCustomData:xA,MsgVersion:Qe,MsgCheckResult:Re,NeedReadReceipt:Se,IsPlaceMsg:At,RevokerInfo:at,GroupAtInfo:jt,OnlineOnlyFlag:Bi,InnerSdkCustomData:ri}=C;let St,eo=Ds.MSG_PRIORITY_NORMAL;if(Object.keys(Ll).includes(String(C.MsgPriority))&&(eo=Ll[C.MsgPriority]),at){const{Reason:Yt,Revoker_Account:si,Revoker_FromUin:zo}=at;St={reason:Yt,revoker:si,revokerFromUin:zo,userID:si}}const to=function(Yt){const si=[];return Array.isArray(Yt)&&Yt.forEach(zo=>{zo.GroupAtAllFlag===SB?si.push(zo.GroupAt_Account):zo.GroupAtAllFlag===Pu&&si.push(vo.MSG_AT_ALL)}),si}(jt);return{clientSequence:E,from:h,groupProfile:D,clientTime:O,priority:eo,random:Y,sequence:j,time:IA,messageControlInfo:{excludedFromLastMessage:BA?.NoLastMsg===1,excludedFromUnreadCount:BA?.NoUnread===1},isSupportExtension:mA,tinyID:_A,cloudCustomData:xA,messageVersion:Qe,checkResult:Re,needReadReceipt:Se,isPlaceMessage:At,revokerInfo:St,atUserList:to,elements:za(N),to:Ul(C),onlineOnlyFlag:Bi===1,quoteInfo:Ol(ri)}}function Ul(C){const{utils:{isEmpty:E},constants:{IS_TOPIC_MESSAGE:h}}=ZA,{ToGroupId:D,GroupInfo:{MillionGroupFlag:N=0,TopicId:O}={}}=C;return N!==h||E(O)?D:O}function za(C){if(!C)return null;if(Array.isArray(C))return C.map(h=>{const D=ZA.message.messageFactory.getElementClass(h.MsgType);return D?.parseServerPushElement(h)});const E=ZA.message.messageFactory.getElementClass(C.MsgType);return E?.parseServerPushElement(C)}function NE(C){const{From_Account:E,MsgBody:h,MsgClientTime:D,MsgRandom:N,MsgSeq:O,MsgTimeStamp:Y,GroupId:j,TopicId:IA,MsgVersion:BA,CloudCustomData:mA,MsgCheckResult:_A}=C;return{from:E,clientTime:D,random:N,sequence:O,time:Y,groupID:j,topicID:IA,elements:za(h),messageVersion:BA,cloudCustomData:mA,checkResult:_A}}function Ol(C){const{utils:{isString:E,safeStringify:h},ssoLog:D}=ZA;if(!E(C))return null;try{const{messageID:N,messageTime:O,messageSequence:Y}=JSON.parse(C).businessQuote;return{msgID:N,messageTime:O,messageSequence:Y}}catch(N){return D.debug("_parseServerQuoteInfo",h(N)),null}}function Jg({conversationUpdateFields:C,message:E}){const{conversationID:h,conversationType:D,conversationSubType:N,flow:O,_isExcludedFromUnreadCount:Y,_isExcludedFromLastMessage:j}=E,IA=j?"":RE(E),BA=!Y&&O===li.IN;C.has(h)?(C.get(h).lastMessage=IA,BA&&C.get(h).unreadCount++):C.set(h,{conversationID:h,type:D,subType:N,unreadCount:BA?1:0,lastMessage:IA})}function TE(C){return C.filter(E=>{const h=!$r(E?._elements),D=E?.isPlaceMessage===1;return h||ZA.ssoLog.error("emptyMessageBody",`from:${E.from} to:${E.to} sequence:${E.sequence}`),h&&!D})}function Hg(C){const{messageDataHandler:E}=ZA.message;return!E.isInMessageList(C)&&!E.isMessageSentByCurrentInstance(C)}var Vg=Object.freeze({__proto__:null,autoIncrementIndex:vB,createAndroidPushInfo:fI,createApnsPushInfo:kC,createOfflinePushInfo:Fl,filterValidMessages:TE,getAndroidSoundName:Us,parseServerGroupMessage:di,parseServerPushC2CModifyMessage:vE,parseServerPushGroupModifyMessage:NE,parseServerPushMessage:Pc,parseServerPushMessageElement:za,shouldStoreMessage:Hg,updateConversationFields:Jg});const{isPlainObject:fa}=ZA.utils;function xl(C,E={}){const{onlineUserOnly:h,messageControlInfo:D}=E;let{offlinePushInfo:N}=E;C.conversationType===En.CONV_C2C&&h===!0&&(N?N.disablePush=!0:N={disablePush:!0});let O="";typeof C.cloudCustomData=="string"&&C.cloudCustomData.length>0&&(O=C.cloudCustomData);const Y=[];if(D&&fa(D)){const{excludedFromUnreadCount:j,excludedFromLastMessage:IA,excludedFromContentModeration:BA}=D;j===!0&&Y.push("NoUnread"),IA===!0&&Y.push("NoLastMsg"),BA===!0&&Y.push("NoMsgCheck")}return{onlineUserOnly:h,cloudCustomData:O,messageControlInfo:Y,offlinePushInfo:N}}function zn(C){const{webhookInfo:{disableCloudMessagePreHook:E=!1,disableCloudMessagePostHook:h=!1}={}}=C||{};if(!E&&!h)return;const D=[];return E&&D.push("ForbidBeforeSendMsgCallback"),h&&D.push("ForbidAfterSendMsgCallback"),D}function dr(C,E){return et(this,void 0,void 0,function*(){const h=C.conversationType===En.CONV_GROUP?function(N,O){var Y;const j=xl(N,O),{onlineUserOnly:IA,cloudCustomData:BA,messageControlInfo:mA,offlinePushInfo:_A}=j,xA=JSON.parse(JSON.stringify(N.transformElementsToServerFormat()));let Qe;return B(N._receiverList)&&N._receiverList.length>0&&(Qe=N._receiverList,N._receiverList.length>50&&(Qe=N._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:(Y=ZA.store.get("login"))===null||Y===void 0?void 0:Y.userId,GroupId:N.to,MsgBody:xA,CloudCustomData:BA,Random:N.random,MsgPriority:N.priority,ClientSeq:N.clientSequence,GroupAtInfo:N._groupAtInfoList,OnlineOnlyFlag:IA?1:0,MsgClientTime:N.clientTime,OfflinePushInfo:Fl(_A),SendMsgControl:IA?void 0:mA,NeedReadReceipt:N.needReadReceipt===!0?1:0,To_Account:Qe,SupportMessageExtension:N.isSupportExtension===!0?1:0,IsRelayMsg:N._relayFlag===!0?1:0,CustomModerationConfigID:N._cmConfigID,ForbidCallbackControl:zn(O),InnerSdkCustomData:GB(N)}}}(C,E):function(N,O){var Y;const j=xl(N,O),{onlineUserOnly:IA,cloudCustomData:BA,messageControlInfo:mA,offlinePushInfo:_A}=j,xA=IA===!0?0:void 0,Qe=JSON.parse(JSON.stringify(N.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:(Y=ZA.store.get("login"))===null||Y===void 0?void 0:Y.userId,To_Account:N.to,MsgBody:Qe,CloudCustomData:BA,MsgSeq:N.sequence,MsgRandom:N.random,MsgLifeTime:xA,From_AccountNick:N.nick,From_AccountHeadurl:N.avatar,SendMsgControl:xA!==0?mA:void 0,MsgClientTime:N.clientTime,IsNeedReadReceipt:N.needReadReceipt===!0?1:0,SupportMessageExtension:N.isSupportExtension===!0?1:0,IsRelayMsg:N._relayFlag===!0?1:0,CustomModerationConfigID:N._cmConfigID,OfflinePushInfo:Fl(_A),ForbidCallbackControl:zn(O),InnerSdkCustomData:GB(N)}}}(C,E),D=yield Ls(h);return D?{time:D.MsgTime,messageDropReason:D.MsgDropReason,sequence:D.MsgSeq}:null})}function Yn(C){return et(this,void 0,void 0,function*(){const{from:E,to:h,version:D=0,sequence:N,random:O,time:Y,type:j,cloudCustomData:IA}=C,BA={From_Account:E,To_Account:h,MsgVersion:D,MsgSeq:N,MsgRandom:O,MsgTime:Y,MsgType:j,MsgBody:C.transformElementsToServerFormat(),CloudCustomData:IA},mA=yield Ls({servcmd:"openim.modify_c2c_msg",data:BA});if(mA){const{MsgBody:_A,MsgVersion:xA,CloudCustomData:Qe}=mA;return{elements:za(_A),messageVersion:xA,cloudCustomData:Qe}}})}function qg(C){return et(this,void 0,void 0,function*(){const{to:E,version:h=0,sequence:D,cloudCustomData:N}=C,O={GroupId:E,MsgVersion:h,MsgSeq:D,MsgBody:C.transformElementsToServerFormat(),CloudCustomData:N},Y=yield Ls({servcmd:"openim.modify_group_msg",data:O});if(Y){const{MsgBody:j,MsgVersion:IA,CloudCustomData:BA}=Y;return{elements:za(j),messageVersion:IA,cloudCustomData:BA}}})}function GE(C){return et(this,void 0,void 0,function*(){const{groupID:E,count:h,messageSequence:D,messageSequenceList:N,getType:O}=C,Y={GroupId:E,ReqMsgNumber:h,WithRecalledMsg:1,Version:1,GetType:O};return D&&(Y.ReqMsgSeq=D),B(N)&&N.length>0&&(Y.ReqMsgSeqList=N),yield Ls({servcmd:"group_open_http_svc.group_msg_get",data:Y})})}function $I(C){return et(this,void 0,void 0,function*(){const{peerAccount:E,count:h,lastMessageTime:D,messageKey:N,direction:O}=C;return Ls({servcmd:"openim.getroammsg",data:{Peer_Account:E,MaxCnt:h,WithRecalledMsg:1,LastMsgTime:D,MsgKey:N,GetDirection:O}})})}function GB(C){if(ZA.utils.isObject(C.quoteInfo)){const{msgID:E,messageSequence:h,messageTime:D}=C.quoteInfo;return JSON.stringify({businessQuote:{messageID:E,messageSequence:h,messageTime:D}})}}var Ig=Object.freeze({__proto__:null,createMessagePackOptions:xl,generateForbidCallbackControl:zn,getC2CRoamingMessagesByAnchor:$I,getGroupRoamingMessagesByAnchor:GE,getRoamingMessages:function(C){return et(this,void 0,void 0,function*(){const{peerAccount:E,count:h,lastMessageTime:D,messageKey:N}=C;return(yield Ls({servcmd:"openim.getroammsg",data:{Peer_Account:E,MaxCnt:h||15,LastMsgTime:D||0,MsgKey:N,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:Yn,modifyGroupMessage:qg,sendMessage:dr});const{isPlainObject:kE}=ZA.utils,{MSG_AUDIO:kB,MSG_FILE:_E,MSG_IMAGE:Ju,MSG_VIDEO:bE,MSG_MERGER:Jc}=vo;class LE{constructor(){this._sendProtocolMap=new Map}init(){Wo.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:E=>![kB,_E,Ju,bE,Jc].includes(E[0].type)})}registerSendProtocol(E,h,D){this._sendProtocolMap.set(E,h.bind(D))}sendMessage(E,h){return et(this,void 0,void 0,function*(){const{TOTAL_COUNT:D,SEND_COST:N,SUCCESS_COUNT:O,FAILED_COUNT:Y}=Sc;if(!(E instanceof NB))throw new lo({code:Qa.MSG_INSTANCE_REQUIRED});const j=E.validateBeforeSend();if(!j.isValid){const{code:mA,message:_A=""}=j.error||{};throw new lo({code:mA,message:_A})}this._reportMessageSendQuality({name:D,message:E});let IA=!1;const{messageDataHandler:BA}=ZA.message||{};try{const{messageControlInfo:mA}=h||{};let _A=null;BA.addRandomOfSentMessage(E.random);const xA=Date.now(),Qe=this._getSendProtocol(E);if(E.conversationType===En.CONV_C2C?(IA=h?.onlineUserOnly===!0,_A=yield Qe(E,h)):E.conversationType===En.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(E),_A=yield Qe(E,h)),_A){const{messageDropReason:Re,sequence:Se,time:At}=_A;if(this._updateNickAndAvatarOfSentMessageByMe(E),Re&&this._logRateLimitInfo(E,Se,Re),this._reportMessageSendQuality({name:O,message:E}),this._reportMessageSendQuality({name:N,message:E,startTs:xA}),E.isResend===!0){const at=BA.findMessage(E.ID);at&&(ZA.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${at.ID}`),BA.deleteConversationMessage(at))}return E.status=tg.SUCCESS,E.time=At,E.conversationType===En.CONV_GROUP&&(E.sequence=Se),IA?E._onlineOnlyFlag=!0:(BA.storeConversationMessage(E),this._applySentMessageControlInfo(E,mA),this._emitOnlineMessageSent(E)),E.type===_s.MSG_STREAM?{code:0,data:{message:E,streamMessageID:_A.streamMessageID}}:{code:0,data:{message:E}}}}catch(mA){E.status=tg.FAIL,BA.removeRandomOfSentMessage(E.random);let{errorCode:_A}=mA||{},xA=mA?.errorInfo||mA?.message||"";throw this._hasRiskContent(_A)&&(E.hasRiskContent=!0),IA||this._isRejectedByRestApi(_A)||BA.storeConversationMessage(E),this._reportMessageSendQuality({name:Y,message:E,error:mA}),new lo({code:_A,message:xA,data:{message:E},moreMessage:`type:${E.type} from:${E.from} to:${E.to}`})}})}_hasRiskContent(E){return E===80001||E===80004}_isRejectedByRestApi(E){return E>=10100&&E<=10200||E>=120001&&E<=13e4}_emitOnlineMessageSent(E){const h=E._isExcludedFromLastMessage?"":E,{conversationID:D,conversationType:N}=E,O=ca(D)?Gt.TOPIC_NEW_MESSAGE:Gt.NEW_MESSAGE;ZA.notificationCenter.emitInnerEvent(O,{result:{conversationUpdateFieldList:[{conversationID:D,type:N,message:E,lastMessage:h,unreadCount:0}]}})}_applySentMessageControlInfo(E,h){h&&kE(h)&&(h.excludedFromLastMessage===!0&&(E._isExcludedFromLastMessage=!0),h.excludedFromUnreadCount===!0&&(E._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(E,h,D){const N=`from:${E.from} to:${E.to} sequence:${h} messageDropReason:${D}`;ZA.ssoLog.warn("messageDropReason",N)}_updateNickAndAvatarOfSentMessageByMe(E){const{messageDataHandler:h}=ZA.message||{};let D=!1;const{conversationID:N}=E,O=h.getLatestMsgSentByMe(N);if(O){const{nick:Y,avatar:j}=O;Y===E.nick&&j===E.avatar||(D=!0),D&&h.updateNickAndAvatarOfSentMessage({conversationID:N,latestNick:E.nick,latestAvatar:E.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(E){return et(this,void 0,void 0,function*(){var h,D,N;const{to:O,from:Y}=E;let j=O,IA=ms.getGroup(j);if(Ka({groupID:j})&&IA?.isSupportTopic)throw new lo({code:Qa.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(ca(O)&&([j]=O.split(_a.TOPIC),IA=ms.getGroup(j)),!IA&&typeof((h=Wo.getInstance().getApiMap())===null||h===void 0?void 0:h.getGroupProfile)=="function"){const BA=yield Wo.getInstance().getApiMap().getGroupProfile({groupID:j});if(((N=(D=BA?.data)===null||D===void 0?void 0:D.group)===null||N===void 0?void 0:N.type)===vo.GRP_AVCHATROOM){const mA=Tc({code:Qa.MSG_SEND_FAIL_NOT_IN_AV,replacement1:Y,replacement2:j});throw new lo({code:Qa.MSG_SEND_FAIL_NOT_IN_AV,message:mA})}}return!0})}_reportMessageSendQuality(E){ZA.notificationCenter.emitInnerEvent(Gt.QUALITY_STAT,{label:PI.MESSAGE_SEND_SUCCESS_RATE,data:E})}_getSendProtocol(E){return this._sendProtocolMap.get(E.type)||dr}}var _B=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){ZA.notificationCenter.subscribeInnerEvent(Gt.LOGOUT,this._reset,this),ZA.notificationCenter.subscribeInnerEvent(Gt.DESTROY,this._dispose,this)}get _messagesByConversation(){return zI.getMessages()}storeConversationMessage(C,E=!1){if(Nr)return!0;const{conversationID:h}=C;if(!h||(this._messagesByConversation.has(h)||this._messagesByConversation.set(h,new Map),this._shouldSkipStoreMessage(C,E)))return!1;const D=this._getUniqueIdOfMessage(C);return this._messagesByConversation.get(h).set(D,C),this._updateLatestMessageMap(C),!0}_updateLatestMessageMap(C){const{conversationID:E}=C;C.flow==="out"?this._setLatestMsgSentByMe(E,C):E.startsWith("C2C")&&this._setLatestMsgSentByPeer(E,C)}_shouldSkipStoreMessage(C,E){const h=this._getUniqueIdOfMessage(C),D=this._messagesByConversation.get(C.conversationID);if(D?.has(h)){const N=D?.get(h);if(!E||N?.isModified===!0)return!0}return!1}deleteConversationMessage(C){var E;const{conversationID:h=""}=C,D=this._getUniqueIdOfMessage(C);this._messagesByConversation.has(h)&&((E=this._messagesByConversation.get(h))===null||E===void 0||E.delete(D))}modifyConversationMessage(C,E){var h;if(!this._messagesByConversation.has(C)&&!this._sparseMessagesByConversation.has(C))return{isUpdated:!1,message:null};const D=this._getUniqueIdOfMessage(E),N=this._getMessageFromLocalMessage(C,D);if(N){const{messageVersion:O,elements:Y,cloudCustomData:j,checkResult:IA=0}=E,BA=IA>1;if(ZA.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${N.version} remoteVersion:${O}`),N.versionN.ID===C)||null,E)break;if(!E){const D=Array.from(this._sparseMessagesByConversation.values());for(const N of D)if(E=N.get(C)||null,E)break}return E}deleteConversationMessageList(C){this._messagesByConversation.has(C)&&(this._messagesByConversation.delete(C),this._latestMessageSentByMeMap.delete(C),this._latestMessageSentByPeerMap.delete(C)),this._sparseMessagesByConversation.has(C)&&this._sparseMessagesByConversation.delete(C)}revokeMessage({conversationID:C,sequence:E,random:h,revoker:D}){const N=this._messagesByConversation.get(C);let O=null;if(N){const Y=Array.from(N.values());if(O=this._findMessageBySequenceAndRandom({messageList:Y,random:h,sequence:E}),O){const j=this._getUniqueIdOfMessage(O);return zI.updateMessage(C,[j],{isRevoked:!0,revoker:D,operation:ka.revoke}),O}}if(this._sparseMessagesByConversation.has(C)){const Y=Array.from(this._sparseMessagesByConversation.get(C).values());if(O=this._findMessageBySequenceAndRandom({messageList:Y,random:h,sequence:E}),O)return O.isRevoked=!0,O.revoker=D,O}}_findMessageBySequenceAndRandom({messageList:C,sequence:E,random:h}){for(let D=0;D0){const Y=new Map([...N,...O.entries()]);this._messagesByConversation.set(h,Y),this._updateLatestMessageSentByMe(h),this._updateLatestMessageSentByPeer(h)}return D}storeSparseMessageList(C){if(C.length===0)return;const{conversationID:E}=C[0],h=C.length;this._sparseMessagesByConversation.has(E)||this._sparseMessagesByConversation.set(E,new Map);const D=this._sparseMessagesByConversation.get(E);for(let N=0;N=0;D--)if(h[D].flow==="out"){this._setLatestMsgSentByMe(C,h[D]);break}}}_updateLatestMessageSentByPeer(C){var E;const h=Array.from(((E=this._messagesByConversation.get(C))===null||E===void 0?void 0:E.values())||[]);if(h.length!==0&&C.startsWith("C2C")){for(let D=h.length-1;D>=0;D--)if(h[D].flow==="in"){this._setLatestMsgSentByPeer(C,h[D]);break}}}_getUniqueIdOfMessage(C){const{from:E,to:h,random:D,sequence:N,time:O}=C;return`${E}-${h}-${D}-${N}-${O}`}_setLatestMsgSentByPeer(C,E){this._latestMessageSentByPeerMap.set(C,E)}_setLatestMsgSentByMe(C,E){this._latestMessageSentByMeMap.set(C,E)}getLatestMsgSentByPeer(C){return this._latestMessageSentByPeerMap.get(C)}getLatestMsgSentByMe(C){return this._latestMessageSentByMeMap.get(C)}addRandomOfSentMessage(C){this._randomOfSentMessageList.add(C)}removeRandomOfSentMessage(C){this._randomOfSentMessageList.delete(C)}updateNickAndAvatarOfSentMessage(C){const{conversationID:E="",latestAvatar:h,latestNick:D,isSentByMe:N=!0}=C,O=this._messagesByConversation.get(E);if(!O)return;const Y=Array.from(O.values()),j=N?"out":"in";Y.forEach(IA=>{const{nick:BA,avatar:mA,flow:_A}=IA;_A===j&&(BA!==D&&(IA.nick=D),mA!==h&&(IA.avatar=h))})}isInMessageList(C){var E;const{conversationID:h}=C;if(!h||!this._messagesByConversation.has(h))return!1;const D=this._getUniqueIdOfMessage(C);return(E=this._messagesByConversation.get(h))===null||E===void 0?void 0:E.has(D)}isMessageSentByCurrentInstance(C){const{random:E}=C;return this._randomOfSentMessageList.has(E)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(C){const E=this._messagesByConversation.get(C);return E?[...E.values()]:[]}getSparseMessageList(C){const E=this._sparseMessagesByConversation.get(C);return E?[...E.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),ZA.notificationCenter.unSubscribeInnerEvent(Gt.LOGOUT,this._reset,this),ZA.notificationCenter.unSubscribeInnerEvent(Gt.DESTROY,this._dispose,this)}};function Zn(C,E){const h=Uc.getConversation(C);if(h?.lastMessage){const{lastMessage:D}=h,{lastTime:N,lastSequence:O,version:Y}=D,{time:j,sequence:IA,messageVersion:BA,elements:mA,cloudCustomData:_A}=E;N===j&&O===IA&&Y!==BA&&(D.type=mA[0].type,D.payload=mA[0].content,D.messageForShow=bc(D.type,D.payload),D.cloudCustomData=_A,D.version=BA,Uc.updateConversation(C,{lastMessage:D}))}}class Os{init(){Wo.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(E){return et(this,void 0,void 0,function*(){const{to:h,payload:D,sequence:N,conversationType:O,random:Y,time:j,from:IA,type:BA}=E;if(this._canModifyMessageElement(BA)){const mA=E?._elements||[];mA.length>=1&&(mA[0].type=BA,mA[0].content=D)}try{let mA=null,_A=null;if(O===En.CONV_C2C?mA=yield Yn(E):O===En.CONV_GROUP&&(mA=yield qg(E)),mA){let xA=`${O}${h}`;return h===Wr()&&O===En.CONV_C2C&&(xA=`${O}${IA}`),_A={conversationType:O,from:IA,to:h,time:j,random:Y,sequence:N,elements:mA?.elements,cloudCustomData:mA?.cloudCustomData,messageVersion:mA?.messageVersion,conversationID:xA},this._handleModifyMessageSuccess(_A),{code:0,data:{message:E},successLog:{message:`to:${h}`}}}}catch(mA){const{errorCode:_A}=mA||{};throw new lo({functionName:"modifyMessage",code:_A,moreMessage:`to:${h}`})}})}_handleModifyMessageSuccess(E){const{conversationID:h}=E,{isUpdated:D,message:N}=ZA.message.messageDataHandler.modifyConversationMessage(h,E);D===!0&&ZA.notificationCenter.emitOuterEvent(kr.MESSAGE_MODIFIED,{name:kr.MESSAGE_MODIFIED,data:[N]}),ZA.notificationCenter.emitInnerEvent(Gt.MESSAGE_MODIFIED,{conversationID:h,message:N}),Zn(h,E)}_canModifyMessageElement(E){return[Wa.MSG_TEXT,Wa.MSG_CUSTOM,Wa.MSG_LOCATION,Wa.MSG_FACE].includes(E)}}class Za{init(){const{notificationCenter:E}=ZA,{InnerEventSubType:h}=E;Ir.getInstance().registerWorkflowStep(cn.RECEIVE_C2C_NEW_MESSAGE,kt.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),Ir.getInstance().registerWorkflowStep(cn.RECEIVE_C2C_NEW_MESSAGE,kt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),Ir.getInstance().registerWorkflowStep(cn.SYNC_SERVER_INFO_AFTER_RE_ONLINE,kt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),E.subscribeInnerEvent(Gt.MESSAGE_PUSH,h.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),E.subscribeInnerEvent(Gt.MESSAGE_PUSH,h.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),E.subscribeInnerEvent(Gt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(E){Ir.getInstance().executeWorkflow(cn.RECEIVE_C2C_NEW_MESSAGE,E)}_handleC2CMessagePush(E){const h=E.data||{},{messageDataHandler:D}=ZA.message||{},N=[],O=new Map;return h.C2cMsgArray.forEach(Y=>{const j=this._generateC2CMessage(Y);this._updateMessageProfile(j);let IA=j.isModified===1;D.isMessageSentByCurrentInstance(j)?j.isModified=IA:IA=!1,j._onlineOnlyFlag?D.isMessageSentByCurrentInstance(j)||N.push(j):Hg(j)&&(D.storeConversationMessage(j)&&Jg({conversationUpdateFields:O,message:j}),D.isMessageSentByCurrentInstance(j)&&!IA||N.push(j))}),{conversationUpdateFieldList:[...O.values()],messages:N}}_emitMessageEventsAfterReceiveNewMessage(E){var h;const{messages:D=[]}=((h=E.result)===null||h===void 0?void 0:h[kt.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(D)}_emitMessageEventsAfterSyncUnreadMessage(E){var h;const{messages:D=[]}=((h=E.result)===null||h===void 0?void 0:h[kt.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(D)}_emitMessageEvents(E){const h=E?.filter(N=>N?.isModified===!0)||[];h.length>0&&ZA.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:h});const D=E?.filter(N=>!N?.isModified);D.length>0&&ZA.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:D})}_generateC2CMessage(E){const h=En.CONV_C2C,D=Pc(E),N=ZA.message.messageFactory.createMessage(Object.assign(Object.assign({},D),{conversationType:h,flow:li.IN})),{elements:O}=D;return N.setElement(O),N}_updateMessageProfile(E){var h;const{messageDataHandler:D}=ZA.message||{},N=(h=ZA.store.get("login"))===null||h===void 0?void 0:h.userId,{from:O,nick:Y,avatar:j,conversationID:IA=""}=E;if(O!==N){const BA=D.getLatestMsgSentByPeer(IA);if(BA){const{nick:mA,avatar:_A}=BA;r(Y)||r(j)?(E.nick=s(mA)?mA:E.nick,E.avatar=s(_A)?_A:E.avatar):Y===mA&&j===_A||(D.updateNickAndAvatarOfSentMessage({conversationID:IA,latestNick:Y,latestAvatar:j,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:IA,nick:Y,avatar:j}))}}else{const BA=D.getLatestMsgSentByMe(IA);!BA||Y===BA.nick&&j===BA.avatar||D.updateNickAndAvatarOfSentMessage({conversationID:IA,latestNick:Y,latestAvatar:j,isSentByMe:!0})}}_updateConversationUserProfile(E){const{conversationID:h,nick:D,avatar:N}=E,O=Uc.getConversation(h),{userProfile:Y={}}=O||{};Y.avatar===N&&Y.nick===D||Uc.updateConversation(h,{userProfile:Object.assign(Object.assign({},Y),{nick:D,avatar:N})})}_updateMessageListDueToModify(E){const{conversationID:h}=E,{isUpdated:D,message:N}=ZA.message.messageDataHandler.modifyConversationMessage(h,E);D===!0&&ZA.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[N]}),ZA.notificationCenter.emitInnerEvent("ModifyMessageSuccess",E),Zn(h,E)}_handleC2CMessageModify(E){E.C2cMsgModNotifys.forEach(h=>{var D;const N=En.CONV_C2C;let O=vE(h);const{to:Y,from:j}=O;let IA=`${N}${Y}`;Y===((D=ZA.store.get("login"))===null||D===void 0?void 0:D.userId)&&(IA=`${N}${j}`),O=Object.assign({conversationType:N,conversationID:IA},O),this._updateMessageListDueToModify(O)})}_dispose(){const{notificationCenter:E}=ZA,{InnerEventSubType:h}=E;ZA.notificationCenter.unSubscribeInnerEvent(Gt.MESSAGE_PUSH,h.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),ZA.notificationCenter.unSubscribeInnerEvent(Gt.MESSAGE_PUSH,h.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),ZA.notificationCenter.unSubscribeInnerEvent(Gt.DESTROY,this._dispose,this)}}class FE{init(){const{notificationCenter:E}=ZA,{InnerEventSubType:h}=E;Ir.getInstance().registerWorkflowStep(cn.RECEIVE_GROUP_NEW_MESSAGE,kt.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),Ir.getInstance().registerWorkflowStep(cn.RECEIVE_GROUP_NEW_MESSAGE,kt.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),E.subscribeInnerEvent(Gt.MESSAGE_PUSH,h.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),E.subscribeInnerEvent(Gt.MESSAGE_PUSH,h.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),E.subscribeInnerEvent(Gt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(E){this._canExecuteReceiverNewMessageWorkFlow(E)&&Ir.getInstance().executeWorkflow(cn.RECEIVE_GROUP_NEW_MESSAGE,E)}_handleGroupMessagePush(E){const h=E.data||{},{messageDataHandler:D}=ZA.message,N=[],O=new Map,Y=h?.GroupMsgArray;return Y?.forEach(j=>{if(j.GroupInfo.NotVisible===1)return;const IA=this._generateGroupMessage(j);this.updateMessageProfile(IA);let BA=IA.isModified===1;D.isMessageSentByCurrentInstance(IA)?IA.isModified=BA:BA=!1,IA._onlineOnlyFlag?D.isMessageSentByCurrentInstance(IA)||N.push(IA):Hg(IA)&&D.storeConversationMessage(IA)&&(N.push(IA),Jg({conversationUpdateFields:O,message:IA}))}),{conversationUpdateFieldList:[...O.values()],messages:N}}_emitMessageEvents(E){var h;const{messages:D}=((h=E.result)===null||h===void 0?void 0:h[kt.HANDLE_GROUP_NEW_MESSAGE])||{},N=D?.filter(Y=>Y?.isModified===!0)||[];N.length>0&&ZA.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:N});const O=D?.filter(Y=>!Y?.isModified)||[];O.length>0&&ZA.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:O})}_generateGroupMessage(E){const h=En.CONV_GROUP,D=di(E),N=ZA.message.messageFactory.createMessage(Object.assign(Object.assign({},D),{conversationType:h,flow:li.IN})),{elements:O}=D;return N.setElement(O),N}updateMessageProfile(E){var h;const{messageDataHandler:D}=ZA.message||{},N=(h=ZA.store.get("login"))===null||h===void 0?void 0:h.userId,{from:O,nick:Y,avatar:j,conversationID:IA="",_elements:BA}=E;if(O===N){const mA=D.getLatestMsgSentByMe(IA);!mA||Y===mA.nick&&j===mA.avatar||D.updateNickAndAvatarOfSentMessage({conversationID:IA,latestNick:Y,latestAvatar:j,isSentByMe:!0})}else if(O===vo.CONV_SYSTEM){const{operationType:mA,memberInfoList:_A,operatorInfo:xA}=BA;let Qe={};if($r(_A)?$r(xA)||(Qe=xA):[Qs.JOINED,Qs.KICKED,Qs.ADMIN_SET,Qs.ADMIN_CANCELED].includes(mA)&&(Qe=Object.assign({},_A[0])),!$r(Qe)){const{nick:Re="",avatar:Se=""}=Qe;E.nick=Re,E.avatar=Se}}}_updateMessageListDueToModify(E){const{conversationID:h}=E,{isUpdated:D,message:N}=ZA.message.messageDataHandler.modifyConversationMessage(h,E);D===!0&&ZA.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[N]}),Zn(h,E)}_handleGroupMessageModify(E){E.GroupMsgModNotifys.forEach(h=>{const D=En.CONV_GROUP;let N=NE(h);const{topicID:O,groupID:Y}=N,j=O||Y,IA=`${D}${j}`;N=Object.assign({conversationType:D,conversationID:IA,to:j},N),this._updateMessageListDueToModify(N)})}_dispose(){const{notificationCenter:E}=ZA,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:h,GROUP_MESSAGE_MODIFIED:D}}=E;E.unSubscribeInnerEvent(Gt.MESSAGE_PUSH,h,this._handleGroupMessagePush,this),E.unSubscribeInnerEvent(Gt.MESSAGE_PUSH,D,this._handleGroupMessageModify,this),E.unSubscribeInnerEvent(Gt.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(E){var h,D;const{GroupId:N,GroupType:O}=((D=(h=E?.GroupMsgArray)===null||h===void 0?void 0:h[0])===null||D===void 0?void 0:D.GroupInfo)||{},Y=O===yl.GRP_AVCHATROOM;return!(!ms.getGroup(N)&&Y)}}var Yl=new class{constructor(){this.c2cMessageReceiver=new Za,this.groupMessageReceiver=new FE}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const UE={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:C=>!(!C.startsWith("C2C")&&!C.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:C=>function(E){var h;return typeof E?.text!="string"||typeof E.text=="string"&&((h=E?.text)===null||h===void 0?void 0:h.length)===0?"payload.text must be a string":!0}(C)}}},OE={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var Ac=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(C){return et(this,void 0,void 0,function*(){try{const{conversationID:E,count:h,direction:D,sequence:N,messageSequenceList:O,shouldMarkCompleted:Y=!1,getType:j}=C,IA=E.replace(us.CONV_GROUP,""),BA=[];let mA=N;if(D===wc.BACKWARD){if(typeof N!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};mA=N+h-1}const _A=yield GE({groupID:IA,count:h,messageSequence:mA,messageSequenceList:O,getType:j});if(_A){const{RspMsgList:xA=[],NextReqMsgSeq:Qe=0,IsFinished:Re,InvisibleMsgSeq:Se}=_A,At=`groupID:${IA} sequence:${N} reqSeq:${mA} direction:${D} complete:${Re} nextSequence:${Qe} remoteMsgCount:${xA.length} invisibleSequenceList:${Se}`,at=[];for(let ri=0;ri=N),jt&&Y&&this.completedHistoryConversations.add(E);const Bi=TE(at);return ZA.ssoLog.info("getGroupRoamingMessagesByAnchor",At),{messageList:Bi,invisibleSequenceList:Se,nextReqMessageIDFromServer:Qe,hasNoMoreHistoryMessage:jt,serverGroupTipList:BA}}}catch(E){const{errorCode:h,errorInfo:D}=E||{};throw new lo({code:h,message:D})}})}clearHistoryMessageListFetchAnchors(C){this._historyMessageListFetchAnchors.delete(C)}isHistoryMessageFetchCompleted(C){return this.completedHistoryConversations.has(C)}_parseMessage(C){var E;const h=us.CONV_GROUP;C.Event===4&&(C.MsgBody.MsgType=vo.MSG_GRP_TIP);const D=di(C),N=ZI.createMessage(Object.assign(Object.assign({},D),{conversationType:h,flow:"in"}));return WI(((E=D.elements)===null||E===void 0?void 0:E.content)||{},N),N.setElement(D.elements),N}getC2CRoamingMessagesByAnchor(C){return et(this,void 0,void 0,function*(){var E;try{const{conversationID:h,count:D,messageID:N,time:O,direction:Y,shouldMarkCompleted:j=!1}=C;let IA=O,BA="";if(!O){const xA=N?ZA.message.messageDataHandler.findMessage(N):null;if(IA=xA?.time||0,N&&this._historyMessageListFetchAnchors.has(h)){const Qe=this._historyMessageListFetchAnchors.get(h);IA=Qe.lastMessageTime,BA=Qe.messageKey}}const mA=h.replace(us.CONV_C2C,""),_A=yield $I({count:D,lastMessageTime:IA,messageKey:BA,peerAccount:mA,direction:Y});if(_A){const{MsgList:xA=[],Complete:Qe,MsgKey:Re,LastMsgTime:Se}=_A;this._historyMessageListFetchAnchors.set(h,{messageKey:Re,lastMessageTime:Se});const At=[];for(let ri=0;ri{const{tag:N,value:O}=D;N&&N.indexOf(ys)>-1?h.profileCustomField.push({key:N,value:O}):Hc.has(N)&&(h[Hc.get(N)]=O)}),Object.assign(Object.assign({},Rs),h)}parseProfileItem(C=[]){const E=[];return C.forEach(h=>{E.push({tag:h.Tag,value:h.Value})}),E}parseProfileList(C=[]){const E=[];return C.forEach(h=>{E.push({tag:h.Tag,value:h.ValueBytes})}),E}convertParamsToProfile(C){const E=[];return Object.keys(C).forEach(h=>{h!==ln&&E.push({tag:kn[h.toUpperCase()],value:C[h]})}),C.profileCustomField&&B(C.profileCustomField)&&C.profileCustomField.forEach(h=>{E.push({tag:h.key,value:h.value})}),E}normalizeProfileFields(C){const E={},h=[];return C.forEach(D=>{const{tag:N,value:O}=D;if(N&&N.indexOf(ys)>-1&&h.push({key:N,value:O}),Hc.has(N)&&O!==void 0){const Y=Hc.get(N);E[Y]=O}}),h.length>0&&(E.profileCustomField=h),E}};const{generateProtocolData:Vc}=ZA.common;function Pl(C){return et(this,void 0,void 0,function*(){const E="profile.portrait_get_all",h={From_Account:Wr(),UserItem:[]};C.forEach(Y=>{h.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:Y})});const D=Vc({servcmd:E,data:h}),N=`${D.head.seq}${E}`,O=yield ZA.channel.sendPacket(D,{requestId:N});if(O)return function(Y){const{ActionStatus:j,ErrorCode:IA,ErrorDisplay:BA,ErrorInfo:mA,UserProfileItem:_A}=Y,xA=[];return _A.map(Qe=>{const{To_Account:Re,CustomSequence:Se,ResultCode:At,ResultInfo:at,StandardSequence:jt,ProfileItem:Bi}=Qe,ri=Ms.parseProfileItem(Bi);xA.push({userId:Re,customSequence:Se,resultCode:At,resultInfo:at,standardSequence:jt,profileItem:ri})}),{actionStatus:j,errorCode:IA,errorDisplay:BA,errorInfo:mA,userProfile:xA}}(O)})}function ma(C){return xn.getFriendMap().has(C)}const{isEmpty:tc}=ZA.utils;class bB{constructor(){this._strangerProfileMap=new Map}init(){Wo.getInstance().registerApi({apiName:"getMyProfile",context:this}),Wo.getInstance().registerApi({apiName:"getUserProfile",context:this}),Wo.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=Ms.createProfile.bind(Ms);const{notificationCenter:E}=ZA;Ir.getInstance().registerWorkflowStep(cn.SYNC_SERVER_INFO_AFTER_LOGIN,kt.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),E.subscribeInnerEvent(Gt.MESSAGE_PUSH,E.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),E.subscribeInnerEvent(Gt.LOGOUT,this._reset,this),E.subscribeInnerEvent(Gt.DESTROY,this._dispose,this)}getMyProfile(){return et(this,void 0,void 0,function*(){try{const E=Wr(),h=yield Pl([E]);if(h){const D=this._handleProfileFormResponse(h)[0];return xn.getUserProfileMap().set(E,D),{code:0,data:D}}}catch(E){const{errorCode:h,errorInfo:D}=E;throw new lo({functionName:"getMyProfile",code:h,message:D})}})}getUserProfile(E){return et(this,void 0,void 0,function*(){try{let{userIDList:h}=E;const{userIdListToRequest:D,profileFromCache:N}=this._filterRequestAndCacheUsers(h);if(D.length===0)return{code:0,data:N,successLog:{message:`userIDList.length:${h.length}`}};D.length>cg&&(ZA.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),D.length=cg);const{data:O,error:Y}=yield this._batchFetchUserProfiles(D),j=D.length,IA=O.length,BA=j-IA;if(N.length===0&&j===BA&&!tc(Y))throw Y;if(B(O))return O.forEach(_A=>{ma(_A.userID)?xn.getUserProfileMap().set(_A.userID,_A):this._strangerProfileMap.set(_A.userID,_A)}),{code:0,data:O.concat(N),successLog:{message:`getUserProfile query:${j} success:${IA} fail:${BA} from cache:${N.length}`}}}catch(h){throw new lo(h)}})}getMyProfileCacheThenServer(){return et(this,void 0,void 0,function*(){const E=Wr(),h=xn.getUserProfileMap().has(E);return h?{code:0,data:h}:this.getMyProfile()})}updateMyProfile(E){return et(this,void 0,void 0,function*(){const h=Wr(),D={};for(const O in E)E[O]!==void 0&&(D[O]=E[O]);const N=Ms.convertParamsToProfile(D);try{yield function(BA){return et(this,void 0,void 0,function*(){const mA="profile.portrait_set",_A=Vc({servcmd:mA,data:BA}),xA=`${_A.head.seq}${mA}`,Qe=yield ZA.channel.sendPacket(_A,{requestId:xA});if(Qe){const{ActionStatus:Re,ErrorCode:Se,ErrorDisplay:At,ErrorInfo:at}=Qe;return{actionStatus:Re,errorCode:Se,errorDisplay:At,errorInfo:at}}})}({From_Account:h,ProfileItem:N});const Y=xn.getUserProfile(h);let j;j=Y?Object.assign(Object.assign({},Y),D):Ms.createProfile(h,N);const IA=!cI(Y,j,["lastUpdatedTime"]);return j.lastUpdatedTime=Date.now(),xn.getUserProfileMap().set(h,j),IA&&this._emitProfileUpdated(j),{code:0,data:j,successLog:{message:`profileArray: ${ZA.utils.safeStringify(N)}`}}}catch(O){const{errorCode:Y,errorInfo:j}=O;throw new lo({functionName:"updateMyProfile",code:Y,message:j,moreMessage:`params: ${ZA.utils.safeStringify(E)}`})}})}updateMyNickAndAvatar(E){return et(this,void 0,void 0,function*(){const h=Wr(),D=Date.now(),N=xn.getUserProfile(h);let O={};O=N?Object.assign(N,E):Ms.createProfile(h,E),O.lastUpdatedTime=D,xn.getUserProfileMap().set(h,O)})}_onProfileDataModify(E){const h=function(O){const{Profile_Account:Y,PushType:j,ProfileList:IA}=O;return{userId:Y,pushType:j,profileList:Ms.parseProfileList(IA)}}(E.ProfileDataMod[0]);if(tc(h))return;const{isProfileUpdated:D,profile:N}=this._handleProfileModified(h);D&&this._emitProfileUpdated(N)}_emitProfileUpdated(E){ZA.notificationCenter.emitInnerEvent(Gt.PROFILE_UPDATE,{name:Gt.PROFILE_UPDATE,data:[E]}),ZA.notificationCenter.emitOuterEvent(kr.PROFILE_UPDATED,{name:kr.PROFILE_UPDATED,data:[E]}),Uc.updateConversation(`C2C${E?.userID}`,{userProfile:E})}_dispose(){const{notificationCenter:E}=ZA;E.unSubscribeInnerEvent(Gt.LOGOUT,this._reset,this),E.unSubscribeInnerEvent(Gt.MESSAGE_PUSH,E.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),E.unSubscribeInnerEvent(Gt.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(E){const{userId:h,profileList:D}=E,N=xn.getUserProfile(h);if(!(Wr()===h||ma(h)&&N))return{isProfileUpdated:!1,profile:null};const O=Ms.normalizeProfileFields(D),Y=Object.keys(O).some(mA=>mA===ln?this._isCustomFieldChanged(N.profileCustomField,O.profileCustomField):N[mA]!==O[mA]);if(!Y)return{isProfileUpdated:!1,profile:N};const j=Date.now(),IA=Object.prototype.hasOwnProperty.call(O,ln)?this._mergeProfileCustomField(N.profileCustomField,O.profileCustomField):N.profileCustomField,BA=Object.assign(Object.assign(Object.assign({},N),O),{profileCustomField:IA,lastUpdatedTime:j});return xn.getUserProfileMap().set(h,BA),{isProfileUpdated:Y,profile:BA}}_filterRequestAndCacheUsers(E){const h=[],D=[];return E.forEach(N=>{const O=xn.getUserProfileMap().has(N);ma(N)&&O?D.push(xn.getUserProfile(N)):this._isStrangerAndProfileValid(N)?D.push(this._strangerProfileMap.get(N)):h.push(N)}),{userIdListToRequest:h,profileFromCache:D}}_handleProfileFormResponse(E){const{userProfile:h}=E;if(!Array.isArray(h))return[];const D=h.filter(O=>O.userId!=="@TLS#NOT_FOUND"&&O.userId!==""&&!tc(O.profileItem)),N=Date.now();return D.map(O=>{const Y=Ms.createProfile(O.userId,O.profileItem);return Y.lastUpdatedTime=N,Y})}_isStrangerAndProfileValid(E){var h;if(!ma(E)){const{lastUpdatedTime:D=0}=this._strangerProfileMap.get(E)||{},N=((h=ZA.store.get("cloudConfig"))===null||h===void 0?void 0:h.stranger_profile_expiration_time)||6e5;return Date.now()-D<=N}return!1}_chunkUserIDList(E,h){return Array.from({length:Math.ceil(E.length/h)},(D,N)=>E.slice(N*h,(N+1)*h))}_batchFetchUserProfiles(E){return et(this,void 0,void 0,function*(){const h=[],D=[];let N={};return this._chunkUserIDList(E,100).forEach(O=>{h.push(Pl(O))}),(yield Promise.allSettled(h)).forEach(O=>{if(O.status==="fulfilled"){const Y=O.value,j=this._handleProfileFormResponse(Y);B(j)&&D.push(...j)}else if(O.status==="rejected"){const{code:Y,message:j}=O.reason||{};N={errorCode:Y,message:j}}}),{data:D,error:N}})}_isCustomFieldChanged(E=[],h=[]){if(!B(h)||h.length===0)return!1;if(!B(E)||E.length===0)return!0;const D=new Map(E.map(N=>[N.key,N.value]));return h.some(N=>D.get(N.key)!==N.value)}_mergeProfileCustomField(E=[],h=[]){const D=B(E)?E.map(N=>Object.assign({},N)):[];return B(h)&&h.length!==0&&h.forEach(({key:N,value:O})=>{const Y=D.find(j=>j.key===N);Y?Y.value=O:D.push({key:N,value:O})}),D}_reset(){xn.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const Jl=new Map,Hl=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let C=0,E=Hl.length;C>(-2*O&6)):0)N="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(N);try{return decodeURIComponent(escape(h))}catch(D){return console.warn(D),""}}const{isEmpty:xE}=ZA.utils,{generateProtocolData:Ci}=ZA.common;function Vl(C){return et(this,void 0,void 0,function*(){const E="im_open_status.ws_get_user_status",h=Ci({servcmd:E,data:{To_Account:C}}),D=`${h.head.seq}${E}`,N=yield ZA.channel.sendPacket(h,{requestId:D});if(N)return function(O){const{ErrorCode:Y,ErrorInfo:j,ErrorList:IA=[],UserStatusList:BA=[]}=O,mA=BA.map(xA=>{const{To_Account:Qe,Status:Re,CustomStatus:Se,Detail:At=[]}=xA;return{userID:Qe,statusType:Re,customStatus:qc(Se),onlineDevices:YE(At)}}),_A=IA.map(xA=>{const{To_Account:Qe,Invalid_Account:Re,ErrorCode:Se,ErrorInfo:At}=xA;return{userID:xE(Re)?Qe:Re,code:Se,message:At}});return{errorCode:Y,errorInfo:j,successUserList:mA,failureUserList:_A}}(N)})}function YE(C){const E=[];return C?.forEach(h=>{const{Platform:D,Status:N}=h;N==="Online"&&E.push(D)}),E}class LB{constructor(){this._customStatus=""}init(){const{notificationCenter:E}=ZA;Wo.getInstance().registerApi({apiName:"getUserStatus",context:this}),Wo.getInstance().registerApi({apiName:"setSelfStatus",context:this}),Wo.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),Wo.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),Ir.getInstance().registerWorkflowStep(cn.SYNC_SERVER_INFO_AFTER_RE_ONLINE,kt.USER_STATUS_UPDATE,this._onReOnline,this),E.subscribeInnerEvent(Gt.MESSAGE_PUSH,E.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),E.subscribeInnerEvent(Gt.LOGOUT,this._reset,this),E.subscribeInnerEvent(Gt.DESTROY,this._dispose,this)}setSelfStatus(E){return et(this,void 0,void 0,function*(){const h=Wr(),{customStatus:D}=E;try{return yield function(N){return et(this,void 0,void 0,function*(){const O="im_open_status.ws_set_custom_status",Y=Ci({servcmd:O,data:{CustomStatus:N}}),j=`${Y.head.seq}${O}`,IA=yield ZA.channel.sendPacket(Y,{requestId:j});if(IA){const{ErrorCode:BA,ErrorInfo:mA}=IA;return{errorCode:BA,errorInfo:mA}}})}(D),this._customStatus=D,{code:0,data:{userID:h,statusType:Kg,customStatus:D},successLog:{message:`customStatus: ${D}`}}}catch(N){const{errorCode:O,errorInfo:Y}=N;throw new lo({functionName:"setSelfStatus",code:O,message:Y})}})}getUserStatus(E){return et(this,void 0,void 0,function*(){const{userIDList:h=[]}=E;if(this._isOnlyMeInArray(h))return this._getMyStatus();const D=yield this._getUserStatus(h);return Object.assign(Object.assign({},D),{successLog:{message:`userIDList length: ${h.length}`}})})}setCustomStatus(E){const h=qc(E);this._customStatus=h}subscribeUserStatus(E){return et(this,void 0,void 0,function*(){try{const{userIDList:h=[]}=E;this._checkBusinessCapabilityBits("subscribeUserStatus");const D=this._getMaxUserCount("subscribe"),N=this._sliceUserIDList(h,D),O=yield function(j){return et(this,void 0,void 0,function*(){const{channel:IA}=ZA,BA="im_open_status.ws_status_subscribe",mA=Ci({servcmd:BA,data:{To_Account:j}}),_A=`${mA.head.seq}${BA}`;return yield IA.sendPacket(mA,{requestId:_A})})}(N),Y=this._parseResponse(O);return{code:0,data:{failureUserList:Y},successLog:{message:`userID length:${h.length} failCount: ${Y.length}`}}}catch(h){const{errorCode:D}=h;throw new lo({functionName:"subscribeUserStatus",code:D})}})}unsubscribeUserStatus(E){return et(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:h=[]}=E,D=this._getMaxUserCount("unsubscribe"),N=this._sliceUserIDList(h,D),O=yield function(j){return et(this,void 0,void 0,function*(){const{channel:IA}=ZA,BA="im_open_status.ws_status_unsubscribe";let mA={};mA=j.length===0?{UnsubscribeAll:1}:{To_Account:j};const _A=Ci({servcmd:BA,data:mA}),xA=`${_A.head.seq}${BA}`;return yield IA.sendPacket(_A,{requestId:xA})})}(N),Y=this._parseResponse(O);return{code:0,data:{failureUserList:Y},successLog:{message:`userID length:${h.length} failCount: ${Y.length}`}}}catch(h){const{errorCode:D}=h;throw new lo({functionName:"unsubscribeUserStatus",code:D})}})}_onUserStatusUpdate(E){const{UserStatusList:h=[]}=E||{},D=h.map(N=>{const{To_Account:O,Status:Y,CustomStatus:j,Platform:IA}=N,BA={userID:O,statusType:Y,customStatus:qc(j)};return IA&&(BA.onlineDevices=IA),BA});this._emitUserStatusUpdatedEvent(D)}_onReOnline(E){const h=qc(E.data.customStatus);if(this._customStatus===h)return;this._customStatus=h;const D={userID:Wr(),statusType:Kg,customStatus:h};this._emitUserStatusUpdatedEvent(D)}_emitUserStatusUpdatedEvent(E){ZA.notificationCenter.emitOuterEvent(kr.USER_STATUS_UPDATED,{name:kr.USER_STATUS_UPDATED,data:E})}_sliceUserIDList(E,h){return E.slice(0,h)}_parseResponse(E){const{ErrorList:h=[]}=E;return h.map(D=>{const{To_Account:N,Invalid_Account:O,ErrorCode:Y,ErrorInfo:j}=D;return{userID:ZA.utils.isEmpty(O)?N:O,code:Y,message:j}})}_checkBusinessCapabilityBits(E){if(!ZA.store.get("commercialConfig").get(wn))throw new lo({functionName:E,code:Qa.NO_USE,replacement1:E})}_getMaxUserCount(E){const h=ZA.store.get("cloudConfig")||{},D={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}},{key:N,default:O}=D[E],Y=h[N]||O;return parseInt(Y,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:Wr(),statusType:Kg,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(E){return et(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const h=this._getMaxUserCount("query"),D=this._sliceUserIDList(E,h),N=yield Vl(D),{successUserList:O,failureUserList:Y}=N||{};return{code:0,data:{successUserList:O,failureUserList:Y}}}catch(h){const{errorCode:D}=h;throw new lo({functionName:"getUserStatus",code:D})}})}_isOnlyMeInArray(E){const h=Wr();return E.length===1&&E.indexOf(h)>-1}_dispose(){const{notificationCenter:E}=ZA;E.unSubscribeInnerEvent(Gt.MESSAGE_PUSH,E.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),E.unSubscribeInnerEvent(Gt.DESTROY,this._dispose,this),E.unSubscribeInnerEvent(Gt.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const L={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(C){for(const E of C){if(typeof E!="object")return"Each item in profileCustomField must be an object";if(typeof E?.key!="string")return"Each item.key in profileCustomField must be a string";if(!E?.key.startsWith(ys))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}}},w={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class q{constructor(){this.userProfile=new bB,this.userStatus=new LB,this.userProfile.init(),this.userStatus.init(),Lg({auth:w,params:L})}}function y(C){const E=[];if(!s(C))return E;const h=C.length;if(h===0)return E;for(let D=h-1;D>=0;D--)C[D]==="1"&&E.push(2**(h-D-1));return E}var T,V,$;(function(C){C.NOT_START="notStart",C.PENDING="pending",C.RESOLVED="resolved",C.REJECTED="rejected"})(T||(T={})),function(C){C[C.C2C=1]="C2C",C[C.GROUP=2]="GROUP"}(V||(V={})),function(C){C[C.C2C=8]="C2C",C[C.GROUP=2]="GROUP"}($||($={}));class CA{constructor(){this._name="SyncConversationHandler",this._pagingStatus=T.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:E}=ZA;Ir.getInstance().registerWorkflowStep(cn.SYNC_SERVER_INFO_AFTER_RE_ONLINE,kt.CONVERSATION_RECOVER,this._syncConversationList,this),Ir.getInstance().registerWorkflowStep(cn.SYNC_SERVER_INFO_AFTER_LOGIN,kt.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),E.subscribeInnerEvent(Gt.LOGOUT,this._reset,this),E.subscribeInnerEvent(Gt.DESTROY,this._dispose,this),ZA.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===T.RESOLVED}_syncConversationListAfterLogin(){return et(this,void 0,void 0,function*(){return this._pagingStatus=T.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return et(this,void 0,void 0,function*(){const{ssoLog:E,utils:{safeStringify:h}}=ZA;E.debug("_syncConversationList","start");try{const D=yield this._pagingGetConversationList(!0);this._pagingStatus=T.RESOLVED;const{conversationList:N=[]}=D||{};return E.info("_syncConversationList",`success count:${N.length}`),D}catch(D){const N=new lo(D);E.error("_syncConversationList",`fail ${h(D)}`,{error:N})}})}_pagingGetConversationList(E){return et(this,void 0,void 0,function*(){try{const h=[];this._pagingStatus=T.PENDING;const D=yield function(_A){return et(this,void 0,void 0,function*(){const{fromAccount:xA,pagingTimeStamp:Qe,pagingStartIndex:Re,pagingPinnedTimeStamp:Se,pagingPinnedStartIndex:At}=_A;return Ls({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:xA,StartIndex:Re,TimeStamp:Qe,TopStartIndex:At,TopTimeStamp:Se}})})}({fromAccount:Wr(),pagingTimeStamp:E?this._pagingTimeStamp:0,pagingStartIndex:E?this._pagingStartIndex:0,pagingPinnedTimeStamp:E?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:E?this._pagingPinnedStartIndex:0}),{CompleteFlag:N,SessionItem:O=[],TimeStamp:Y,StartIndex:j,TopTimeStamp:IA,TopStartIndex:BA}=D||{};let mA=[];if(N===1&&(this._pagingStatus=T.RESOLVED),O.length>0&&(mA=this._getConversationOptions(O),h.push(...mA)),ZA.notificationCenter.emitInnerEvent(Gt.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:mA}),this._pagingTimeStamp=Y,this._pagingStartIndex=j,this._pagingPinnedTimeStamp=IA,this._pagingPinnedStartIndex=BA,N!==1){const{conversationList:_A}=yield this._pagingGetConversationList(E);h.push(..._A)}return{conversationList:h}}catch(h){throw h}})}_getConversationOptions(E){const{utils:{isUndefined:h}}=ZA,D=this._convertConversationKey(E);return this._filterValidConversations(D).map(N=>(h(N.lastMsg)&&(N.lastMsg={elements:[]}),N.type===V.C2C?this._assembleC2COption(N):this._assembleGroupOption(N)))}_filterValidConversations(E){return E.filter(({type:h,userID:D})=>h===V.C2C&&!function(N){let O;return N.startsWith(vo.CONV_C2C)&&(O=N.replace(vo.CONV_C2C,"")),O==="@TLS#ERROR"||O==="@TLS#NOT_FOUND"}(D)||h===2)}_assembleC2COption(E){var h,D,N,O,Y,j,IA,BA;const mA=this._createUserprofile(E);return{conversationID:`${vo.CONV_C2C}${E.userID}`,type:vo.CONV_C2C,lastMessage:{lastTime:E.time,lastSequence:E.sequence,fromAccount:E.lastC2CMsgFromAccount,type:!((h=E.lastMsg)===null||h===void 0)&&h.elements[0]?(D=E.lastMsg)===null||D===void 0?void 0:D.elements[0].type:null,payload:!((N=E.lastMsg)===null||N===void 0)&&N.elements[0]?this._amendLayersOverLimitProp(E.lastMsg.elements[0].content):null,cloudCustomData:((j=(Y=(O=E.lastMsg)===null||O===void 0?void 0:O.elements)===null||Y===void 0?void 0:Y[0])===null||j===void 0?void 0:j.cloudCustomData)||"",isRevoked:E.lastMessageFlag===$.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(E),revoker:((BA=(IA=E.lastMsg)===null||IA===void 0?void 0:IA.revokerInfo)===null||BA===void 0?void 0:BA.revoker)||null},unreadCount:0,userProfile:mA,peerReadTime:E.peerReadTime,isPinned:E.isPinned===1,customData:E.customMark||"",markList:y(E.standardMark),conversationGroupList:[],remark:E.friendRemark||"",messageRemindType:this._transMsgRemindType(E.messageRemindType)}}_createUserprofile(E){var h;const{userID:D,nick:N,peerAvatar:O}=E,Y=[{tag:"Tag_Profile_IM_Nick",value:N},{tag:"Tag_Profile_IM_Image",value:O}];return(h=ZA.user.userProfile)===null||h===void 0?void 0:h.createProfile(D,Y)}_computeIsPeerRead(E){const h=Wr(),{lastC2CMsgFromAccount:D,time:N,c2cPeerReadTime:O}=E;return D===h&&N<=O}_assembleGroupOption(E){var h,D,N,O,Y;return{conversationID:`${vo.CONV_GROUP}${E.groupID}`,type:vo.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:E.time,lastSequence:E.sequence,fromAccount:E.msgGroupFromAccount},this._patchTypeAndPayload(E)),{cloudCustomData:((N=(D=(h=E.lastMsg)===null||h===void 0?void 0:h.elements)===null||D===void 0?void 0:D[0])===null||N===void 0?void 0:N.cloudCustomData)||"",isRevoked:E.lastMessageFlag===$.GROUP,onlineOnlyFlag:!1,nick:E.msgGroupFromNickName||"",nameCard:E.msgGroupFromCardName||"",revoker:((Y=(O=E.lastMsg)===null||O===void 0?void 0:O.revokerInfo)===null||Y===void 0?void 0:Y.revoker)||null}),groupProfile:{groupID:E.groupID,name:E.groupNick,avatar:E.groupImage,type:E.groupType,nextMessageSeq:E.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(E),peerReadTime:0,isPinned:E.isPinned===1,version:0,customData:E.customMark||"",markList:y(E.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(E.messageRemindType),subType:E.groupType}}_convertConversationKey(E){return E.map(h=>({type:h.Type,userID:h.To_Account,nick:h.C2cNick,peerAvatar:h.C2cImage,time:h.MsgTimeStamp,sequence:h.MsgSeq,lastC2CMsgFromAccount:h.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(h.LastMsg),lastMessageFlag:h.LastMsgFlags,c2cPeerReadTime:h.C2cPeerReadTime,peerReadTime:h.C2cPeerReadTime,friendRemark:h.C2cRemark,isPinned:h.TopFlags,standardMark:h.StandardMark,customMark:h.CustomMark,messageRemindType:h.MsgRecvOption,groupID:h.ToAccount,groupNick:h.GroupNick,groupImage:h.GroupImage,groupType:h.GroupType,nextMessageSeq:h.GroupNextMsgSeq,msgGroupFromAccount:h.MsgGroupFrom_Account,msgGroupFromNickName:h.MsgGroupFromNickName,msgGroupFromCardName:h.MsgGroupFromCardName,unreadCount:h.UnreadMsgCount,noUnreadCount:h.GroupIgnoredUnreadSeqCount}))}_convertLastMsgKey(E){var h,D,N;const{utils:{isEmpty:O}}=ZA;if(O(E))return null;let Y="",j=null;if(!O(E.GroupTips)){const{From_Account:IA,GroupName:BA}=((h=E.GroupTips)===null||h===void 0?void 0:h.GroupInfo)||{};Y=vo.MSG_GRP_TIP,j=Object.assign(Object.assign({},this._parseContent(Y,E.GroupTips.MsgBody)),{groupProfile:{from:IA,groupName:BA}})}return E.MsgBody&&(Y=(D=E.MsgBody[0])===null||D===void 0?void 0:D.MsgType,j=this._parseContent(Y,E.MsgBody[0])),{event:E.Event,elements:[{type:Y,content:j,cloudCustomData:E.CloudCustomData}],revokerInfo:{revoker:(N=E.RevokerInfo)===null||N===void 0?void 0:N.Revoker_Account}}}_parseContent(E,h){var D;if(!h)return h;const N=ZA.message.messageFactory.getElementClass(E);return N?(D=N.parseServerPushElement(h))===null||D===void 0?void 0:D.content:h}_amendLayersOverLimitProp(E){const{LayersOverLimit:h}=E;return Vo(E,["LayersOverLimit"]).layersOverLimit=h===1,E}_transMsgRemindType(E){let h="";return E===0?h=vo.MSG_REMIND_ACPT_AND_NOTE:E===1?h=vo.MSG_REMIND_DISCARD:E===2?h=vo.MSG_REMIND_ACPT_NOT_NOTE:E===3&&(h=vo.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),h}_patchTypeAndPayload(E){var h;const{utils:{isUndefined:D}}=ZA,{event:N,elements:O=[]}=E.lastMsg||{};return D(N)?{type:O[0]?O[0].type:null,payload:O[0]?this._amendLayersOverLimitProp(O[0].content):null}:{type:vo.MSG_GRP_TIP,payload:((h=O?.[0])===null||h===void 0?void 0:h.content)||{}}}_computeGroupUnreadCount(E){const{unreadCount:h=0,noUnreadCount:D=0}=E,N=h-D;return N>0?N:0}_reset(){this._pagingStatus=T.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:E}=ZA;E.unSubscribeInnerEvent(Gt.LOGOUT,this._reset,this),E.unSubscribeInnerEvent(Gt.DESTROY,this._dispose,this)}}class NA{constructor(){this.syncConversationHandler=new CA,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Ia}`);var KA={create:function(C){var E,h;const{SDKAppID:D,testEnv:N=!1,devMode:O=!1,unlimitedAVChatRoom:Y=!1,scene:j="",oversea:IA=!1,instance:BA,disableIndependentDomain:mA=!1,proxyServer:_A=""}=C;let xA=D;if(!function(Re){if(typeof Re=="number")return!0;const Se=Number(Re);return!Number.isNaN(Se)}(xA))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(xA=Number(xA),og.has(xA))return og.get(xA);let Qe=null;if(BA)Qe=BA,Qe._workflowManager&&Ir.setInstance(Qe._workflowManager),Qe._pluginManager&&Qe._pluginManager.installBuiltInPlugin(Mn),BA.isReady()&&((h=(E=Ir.getInstance()).executeWorkflow)===null||h===void 0||h.call(E,cn.SYNC_SERVER_INFO_AFTER_LOGIN));else{const Re=function(){function ri(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${ri()+ri()}${ri()}${ri()}${ri()}${ri()}${ri()}${ri()}`}();ZA.init({sdkAppId:xA,instanceId:Re,testEnv:N,devMode:O,unlimitedAVChatRoom:Y,disableIndependentDomain:mA,scene:j,oversea:IA,sdkEdition:bl,version:Ia,proxyServer:_A}),Ir.getInstance().init(),ZA.message=new ec,ZA.user=new q,ZA.login=new gg,ZA.conversation=new NA,fs.getInstance().installBuiltInPlugin(Mn),Qe=Wo.getInstance().exposeApiForClient(),Qe._workflowManager=Ir.getInstance(),Qe._pluginManager=fs.getInstance();const{utils:{IS_WORKER_AVAILABLE:Se,USER_AGENT:At,getPlatformType:at,isIOSWebView:jt}}=ZA,Bi=`instanceID:${Re} SDKAppID:${D} platform:${MA} host:${at()} isIOSWebView:${jt} workerAvailable:${Se} UserAgent:${At}`;ZA.ssoLog.info("sdkConstruct",Bi)}return og.set(xA,Qe),Qe},TSignaling:Dl,EVENT:kr,VERSION:Ia,TYPES:vo};return KA})}(d2)),d2.exports}var fG={exports:{}},h2={exports:{}},SrA=h2.exports,c5;function vrA(){return c5||(c5=1,function(t,i){(function(r,s){t.exports=s()})(SrA,function(){function r(A,e){return e.forEach(function(o){o&&typeof o!="string"&&!Array.isArray(o)&&Object.keys(o).forEach(function(n){if(n!=="default"&&!(n in A)){var a=Object.getOwnPropertyDescriptor(o,n);Object.defineProperty(A,n,a.get?a:{enumerable:!0,get:function(){return o[n]}})}})}),Object.freeze(A)}var s=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof bI<"u"?bI:typeof self<"u"?self:{};function g(A){return A&&A.__esModule&&Object.prototype.hasOwnProperty.call(A,"default")?A.default:A}var B=function(A){return A&&A.Math===Math&&A},Q=B(typeof globalThis=="object"&&globalThis)||B(typeof window=="object"&&window)||B(typeof self=="object"&&self)||B(typeof s=="object"&&s)||B(typeof s=="object"&&s)||function(){return this}()||Function("return this")(),f={},m=function(A){try{return!!A()}catch{return!0}},M=!m(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),v=!m(function(){var A=function(){}.bind();return typeof A!="function"||A.hasOwnProperty("prototype")}),U=v,AA=Function.prototype.call,z=U?AA.bind(AA):function(){return AA.apply(AA,arguments)},sA={},eA={}.propertyIsEnumerable,X=Object.getOwnPropertyDescriptor,QA=X&&!eA.call({1:2},1);sA.f=QA?function(A){var e=X(this,A);return!!e&&e.enumerable}:eA;var wA,HA,VA=function(A,e){return{enumerable:!(1&A),configurable:!(2&A),writable:!(4&A),value:e}},ue=v,jA=Function.prototype,Ve=jA.call,Ze=ue&&jA.bind.bind(Ve,Ve),Me=ue?Ze:function(A){return function(){return Ve.apply(A,arguments)}},qe=Me,Et=qe({}.toString),Je=qe("".slice),$e=function(A){return Je(Et(A),8,-1)},Dt=m,Zi=$e,bi=Object,qt=Me("".split),ai=Dt(function(){return!bi("z").propertyIsEnumerable(0)})?function(A){return Zi(A)==="String"?qt(A,""):bi(A)}:bi,Ki=function(A){return A==null},Ur=Ki,Er=TypeError,no=function(A){if(Ur(A))throw new Er("Can't call method on "+A);return A},Kn=ai,Xi=no,yr=function(A){return Kn(Xi(A))},lr=typeof document=="object"&&document.all,Ni=lr===void 0&&lr!==void 0?function(A){return typeof A=="function"||A===lr}:function(A){return typeof A=="function"},wt=Ni,Ji=function(A){return typeof A=="object"?A!==null:wt(A)},Di=Q,ar=Ni,MA=function(A,e){return arguments.length<2?(o=Di[A],ar(o)?o:void 0):Di[A]&&Di[A][e];var o},YA=Me({}.isPrototypeOf),pe=Q.navigator,st=pe&&pe.userAgent,Te=st?String(st):"",be=Q,yt=Te,ht=be.process,ae=be.Deno,ye=ht&&ht.versions||ae&&ae.version,Xe=ye&&ye.v8;Xe&&(HA=(wA=Xe.split("."))[0]>0&&wA[0]<4?1:+(wA[0]+wA[1])),!HA&&yt&&(!(wA=yt.match(/Edge\/(\d+)/))||wA[1]>=74)&&(wA=yt.match(/Chrome\/(\d+)/))&&(HA=+wA[1]);var ot=HA,zt=ot,yi=m,Hi=Q.String,Ei=!!Object.getOwnPropertySymbols&&!yi(function(){var A=Symbol("symbol detection");return!Hi(A)||!(Object(A)instanceof Symbol)||!Symbol.sham&&zt&&zt<41}),ji=Ei&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Xo=MA,sr=Ni,Lo=YA,Nr=Object,Vo=ji?function(A){return typeof A=="symbol"}:function(A){var e=Xo("Symbol");return sr(e)&&Lo(e.prototype,Nr(A))},et=String,Kr=function(A){try{return et(A)}catch{return"Object"}},Qn=Ni,ho=Kr,jn=TypeError,$t=function(A){if(Qn(A))return A;throw new jn(ho(A)+" is not a function")},$r=$t,On=Ki,An=function(A,e){var o=A[e];return On(o)?void 0:$r(o)},Tr=z,ei=Ni,Es=Ji,jr=TypeError,Gr={exports:{}},$o=Q,sn=Object.defineProperty,dn=function(A,e){try{sn($o,A,{value:e,configurable:!0,writable:!0})}catch{$o[A]=e}return e},hn=Q,Gi=dn,pn="__core-js_shared__",nI=Gr.exports=hn[pn]||Gi(pn,{});(nI.versions||(nI.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 gr=Gr.exports,gn=gr,Yo=function(A,e){return gn[A]||(gn[A]=e||{})},Tg=no,So=Object,ao=function(A){return So(Tg(A))},EE=ao,Ta=Me({}.hasOwnProperty),po=Object.hasOwn||function(A,e){return Ta(EE(A),e)},Ja=Me,Mc=0,Qr=Math.random(),Fo=Ja(1.1.toString),$s=function(A){return"Symbol("+(A===void 0?"":A)+")_"+Fo(++Mc+Qr,36)},Ha=Yo,Gs=po,Ga=$s,Rr=Ei,Ia=ji,fo=Q.Symbol,aI=Ha("wks"),en=Ia?fo.for||fo:fo&&fo.withoutSetter||Ga,qo=function(A){return Gs(aI,A)||(aI[A]=Rr&&Gs(fo,A)?fo[A]:en("Symbol."+A)),aI[A]},Gg=z,kg=Ji,fn=Vo,ls=An,Or=function(A,e){var o,n;if(e==="string"&&ei(o=A.toString)&&!Es(n=Tr(o,A))||ei(o=A.valueOf)&&!Es(n=Tr(o,A))||e!=="string"&&ei(o=A.toString)&&!Es(n=Tr(o,A)))return n;throw new jr("Can't convert object to primitive value")},Po=TypeError,Ba=qo("toPrimitive"),Mr=function(A,e){if(!kg(A)||fn(A))return A;var o,n=ls(A,Ba);if(n){if(e===void 0&&(e="default"),o=Gg(n,A,e),!kg(o)||fn(o))return o;throw new Po("Can't convert object to primitive value")}return e===void 0&&(e="number"),Or(A,e)},Cs=Mr,Va=Vo,P=function(A){var e=Cs(A,"string");return Va(e)?e:e+""},F=Ji,EA=Q.document,RA=F(EA)&&F(EA.createElement),GA=function(A){return RA?EA.createElement(A):{}},WA=GA,Ce=!M&&!m(function(){return Object.defineProperty(WA("div"),"a",{get:function(){return 7}}).a!==7}),ge=M,we=z,_e=sA,Ke=VA,Bt=yr,Rt=P,Ye=po,nt=Ce,ii=Object.getOwnPropertyDescriptor;f.f=ge?ii:function(A,e){if(A=Bt(A),e=Rt(e),nt)try{return ii(A,e)}catch{}if(Ye(A,e))return Ke(!we(_e.f,A,e),A[e])};var oi={},Ko=M&&m(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),Kt=Ji,ro=String,ks=TypeError,Zr=function(A){if(Kt(A))return A;throw new ks(ro(A)+" is not an object")},In=M,xr=Ce,sI=Ko,jo=Zr,OI=P,_g=TypeError,gI=Object.defineProperty,ml=Object.getOwnPropertyDescriptor,ua="enumerable",II="configurable",ZA="writable";oi.f=In?sI?function(A,e,o){if(jo(A),e=OI(e),jo(o),typeof A=="function"&&e==="prototype"&&"value"in o&&ZA in o&&!o[ZA]){var n=ml(A,e);n&&n[ZA]&&(A[e]=o.value,o={configurable:II in o?o[II]:n[II],enumerable:ua in o?o[ua]:n[ua],writable:!1})}return gI(A,e,o)}:gI:function(A,e,o){if(jo(A),e=OI(e),jo(o),xr)try{return gI(A,e,o)}catch{}if("get"in o||"set"in o)throw new _g("Accessors not supported");return"value"in o&&(A[e]=o.value),A};var Ag=oi,cI=VA,Bs=M?function(A,e,o){return Ag.f(A,e,cI(1,o))}:function(A,e,o){return A[e]=o,A},eg={exports:{}},kr=M,EI=po,Gt=Function.prototype,Dl=kr&&Object.getOwnPropertyDescriptor,xI=EI(Gt,"name"),_s={PROPER:xI&&function(){}.name==="something",CONFIGURABLE:xI&&(!kr||kr&&Dl(Gt,"name").configurable)},tg=Ni,ka=gr,wc=Me(Function.toString);tg(ka.inspectSource)||(ka.inspectSource=function(A){return wc(A)});var lE,qa,CE,yC=ka.inspectSource,us=Ni,lI=Q.WeakMap,ig=us(lI)&&/native code/.test(String(lI)),yl=$s,_a=Yo("keys"),Qs=function(A){return _a[A]||(_a[A]=yl(A))},Rl={},YI=ig,vo=Q,Qa=Ji,BE=Bs,cn=po,kt=gr,Gn=Qs,PI=Rl,Sc="Object already initialized",tn=vo.TypeError,Ml=vo.WeakMap;if(YI||kt.state){var ba=kt.state||(kt.state=new Ml);ba.get=ba.get,ba.has=ba.has,ba.set=ba.set,lE=function(A,e){if(ba.has(A))throw new tn(Sc);return e.facade=A,ba.set(A,e),e},qa=function(A){return ba.get(A)||{}},CE=function(A){return ba.has(A)}}else{var da=Gn("state");PI[da]=!0,lE=function(A,e){if(cn(A,da))throw new tn(Sc);return e.facade=A,BE(A,da,e),e},qa=function(A){return cn(A,da)?A[da]:{}},CE=function(A){return cn(A,da)}}var on={set:lE,get:qa,has:CE,enforce:function(A){return CE(A)?qa(A):lE(A,{})},getterFor:function(A){return function(e){var o;if(!Qa(e)||(o=qa(e)).type!==A)throw new tn("Incompatible receiver, "+A+" required");return o}}},Xr=Me,wl=m,bs=Ni,vc=po,CI=M,uE=_s.CONFIGURABLE,RC=yC,Nc=on.enforce,Sl=on.get,JI=String,bg=Object.defineProperty,QE=Xr("".slice),vl=Xr("".replace),Tc=Xr([].join),lo=CI&&!wl(function(){return bg(function(){},"length",{value:8}).length!==8}),ds=String(String).split("String"),QB=eg.exports=function(A,e,o){QE(JI(e),0,7)==="Symbol("&&(e="["+vl(JI(e),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),o&&o.getter&&(e="get "+e),o&&o.setter&&(e="set "+e),(!vc(A,"name")||uE&&A.name!==e)&&(CI?bg(A,"name",{value:e,configurable:!0}):A.name=e),lo&&o&&vc(o,"arity")&&A.length!==o.arity&&bg(A,"length",{value:o.arity});try{o&&vc(o,"constructor")&&o.constructor?CI&&bg(A,"prototype",{writable:!1}):A.prototype&&(A.prototype=void 0)}catch{}var n=Nc(A);return vc(n,"source")||(n.source=Tc(ds,typeof e=="string"?e:"")),A};Function.prototype.toString=QB(function(){return bs(this)&&Sl(this).source||RC(this)},"toString");var Gc=eg.exports,kc=Ni,MC=oi,dB=Gc,HI=dn,mn=function(A,e,o,n){n||(n={});var a=n.enumerable,I=n.name!==void 0?n.name:e;if(kc(o)&&dB(o,I,n),n.global)a?A[e]=o:HI(e,o);else{try{n.unsafe?A[e]&&(a=!0):delete A[e]}catch{}a?A[e]=o:MC.f(A,e,{value:o,enumerable:!1,configurable:!n.nonConfigurable,writable:!n.nonWritable})}return A},Lg={},dE=Math.ceil,Ir=Math.floor,og=Math.trunc||function(A){var e=+A;return(e>0?Ir:dE)(e)},Ka=og,ca=function(A){var e=+A;return e!=e||e===0?0:Ka(e)},hE=ca,wC=Math.max,Ls=Math.min,_c=function(A,e){var o=hE(A);return o<0?wC(o+e,0):Ls(o,e)},SC=ca,rg=Math.min,Wr=function(A){var e=SC(A);return e>0?rg(e,9007199254740991):0},ng=Wr,hs=function(A){return ng(A.length)},hB=yr,pB=_c,Nl=hs,bc=function(A){return function(e,o,n){var a=hB(e),I=Nl(a);if(I===0)return!A&&-1;var c,u=pB(n,I);if(A&&o!=o){for(;I>u;)if((c=a[u++])!=c)return!0}else for(;I>u;u++)if((A||u in a)&&a[u]===o)return A||u||0;return!A&&-1}},VI={includes:bc(!0),indexOf:bc(!1)},BI=po,pE=yr,Lc=VI.indexOf,uI=Rl,Fg=Me([].push),ja=function(A,e){var o,n=pE(A),a=0,I=[];for(o in n)!BI(uI,o)&&BI(n,o)&&Fg(I,o);for(;e.length>a;)BI(n,o=e[a++])&&(~Lc(I,o)||Fg(I,o));return I},Fs=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],No=ja,Fc=Fs.concat("length","prototype");Lg.f=Object.getOwnPropertyNames||function(A){return No(A,Fc)};var Ug={};Ug.f=Object.getOwnPropertySymbols;var vC=MA,fE=Lg,Tl=Ug,Ou=Zr,fB=Me([].concat),xu=vC("Reflect","ownKeys")||function(A){var e=fE.f(Ou(A)),o=Tl.f;return o?fB(e,o(A)):e},Og=po,QI=xu,pi=f,mB=oi,Gl=function(A,e,o){for(var n=QI(e),a=mB.f,I=pi.f,c=0;cc;)xc.f(A,o=a[c++],n[o]);return A};var Us,fI=MA("document","documentElement"),kC=Zr,Fl=hI,Pc=Fs,vE=Rl,di=fI,Ul=GA,za="prototype",NE="script",Ol=Qs("IE_PROTO"),Jg=function(){},TE=function(A){return"<"+NE+">"+A+""},Hg=function(A){A.write(TE("")),A.close();var e=A.parentWindow.Object;return A=null,e},Vg=function(){try{Us=new ActiveXObject("htmlfile")}catch{}Vg=typeof document<"u"?document.domain&&Us?Hg(Us):function(){var e,o=Ul("iframe"),n="java"+NE+":";return o.style.display="none",di.appendChild(o),o.src=String(n),(e=o.contentWindow.document).open(),e.write(TE("document.F=Object")),e.close(),e.F}():Hg(Us);for(var A=Pc.length;A--;)delete Vg[za][Pc[A]];return Vg()};vE[Ol]=!0;var fa=Object.create||function(A,e){var o;return A!==null?(Jg[za]=kC(A),o=new Jg,Jg[za]=null,o[Ol]=A):o=Vg(),e===void 0?o:Fl.f(o,e)},xl=qo,zn=fa,dr=oi.f,Yn=xl("unscopables"),qg=Array.prototype;qg[Yn]===void 0&&dr(qg,Yn,{configurable:!0,value:zn(null)});var GE=function(A){qg[Yn][A]=!0},$I=VI.includes,GB=GE;wr({target:"Array",proto:!0,forced:m(function(){return!Array(1).includes()})},{includes:function(A){return $I(this,A,arguments.length>1?arguments[1]:void 0)}}),GB("includes");var Ig,kE,kB,_E={},Ju=!m(function(){function A(){}return A.prototype.constructor=null,Object.getPrototypeOf(new A)!==A.prototype}),bE=po,Jc=Ni,LE=ao,_B=Ju,Zn=Qs("IE_PROTO"),Os=Object,Za=Os.prototype,FE=_B?Os.getPrototypeOf:function(A){var e=LE(A);if(bE(e,Zn))return e[Zn];var o=e.constructor;return Jc(o)&&e instanceof o?o.prototype:e instanceof Os?Za:null},Yl=m,UE=Ni,OE=Ji,Ac=FE,ec=mn,Xn=qo("iterator"),kn=!1;[].keys&&("next"in(kB=[].keys())?(kE=Ac(Ac(kB)))!==Object.prototype&&(Ig=kE):kn=!0);var ys=!OE(Ig)||Yl(function(){var A={};return Ig[Xn].call(A)!==A});ys&&(Ig={}),UE(Ig[Xn])||ec(Ig,Xn,function(){return this});var ln={IteratorPrototype:Ig,BUGGY_SAFARI_ITERATORS:kn},wn=oi.f,Kg=po,cg=qo("toStringTag"),Rs=function(A,e,o){A&&!o&&(A=A.prototype),A&&!Kg(A,cg)&&wn(A,cg,{configurable:!0,value:e})},Hc=ln.IteratorPrototype,Ms=fa,Vc=VA,Pl=Rs,ma=_E,tc=function(){return this},bB=function(A,e,o,n){var a=e+" Iterator";return A.prototype=Ms(Hc,{next:Vc(+!n,o)}),Pl(A,a,!1),ma[a]=tc,A},Jl=Me,Hl=$t,qc=Ji,xE=function(A){return qc(A)||A===null},Ci=String,Vl=TypeError,YE=function(A,e,o){try{return Jl(Hl(Object.getOwnPropertyDescriptor(A,e)[o]))}catch{}},LB=Ji,L=no,w=function(A){if(xE(A))return A;throw new Vl("Can't set "+Ci(A)+" as a prototype")},q=Object.setPrototypeOf||("__proto__"in{}?function(){var A,e=!1,o={};try{(A=YE(Object.prototype,"__proto__","set"))(o,[]),e=o instanceof Array}catch{}return function(n,a){return L(n),w(a),LB(n)&&(e?A(n,a):n.__proto__=a),n}}():void 0),y=wr,T=z,V=Ni,$=bB,CA=FE,NA=q,KA=Rs,C=Bs,E=mn,h=_E,D=_s.PROPER,N=_s.CONFIGURABLE,O=ln.IteratorPrototype,Y=ln.BUGGY_SAFARI_ITERATORS,j=qo("iterator"),IA="keys",BA="values",mA="entries",_A=function(){return this},xA=function(A,e,o,n,a,I,c){$(o,e,n);var u,d,R,k=function(Ie){if(Ie===a&&TA)return TA;if(!Y&&Ie&&Ie in iA)return iA[Ie];switch(Ie){case IA:case BA:case mA:return function(){return new o(this,Ie)}}return function(){return new o(this)}},_=e+" Iterator",Z=!1,iA=A.prototype,cA=iA[j]||iA["@@iterator"]||a&&iA[a],TA=!Y&&cA||k(a),JA=e==="Array"&&iA.entries||cA;if(JA&&(u=CA(JA.call(new A)))!==Object.prototype&&u.next&&(CA(u)!==O&&(NA?NA(u,O):V(u[j])||E(u,j,_A)),KA(u,_,!0)),D&&a===BA&&cA&&cA.name!==BA&&(N?C(iA,"name",BA):(Z=!0,TA=function(){return T(cA,this)})),a)if(d={values:k(BA),keys:I?TA:k(IA),entries:k(mA)},c)for(R in d)(Y||Z||!(R in iA))&&E(iA,R,d[R]);else y({target:e,proto:!0,forced:Y||Z},d);return iA[j]!==TA&&E(iA,j,TA,{name:a}),h[e]=TA,d},Qe=function(A,e){return{value:A,done:e}},Re=yr,Se=GE,At=_E,at=on,jt=oi.f,Bi=xA,ri=Qe,St=M,eo="Array Iterator",to=at.set,Yt=at.getterFor(eo),si=Bi(Array,"Array",function(A,e){to(this,{type:eo,target:Re(A),index:0,kind:e})},function(){var A=Yt(this),e=A.target,o=A.index++;if(!e||o>=e.length)return A.target=null,ri(void 0,!0);switch(A.kind){case"keys":return ri(o,!1);case"values":return ri(e[o],!1)}return ri([o,e[o]],!1)},"values"),zo=At.Arguments=At.Array;if(Se("keys"),Se("values"),Se("entries"),St&&zo.name!=="values")try{jt(zo,"name",{value:"values"})}catch{}var te=$t,je=ao,dA=ai,ut=hs,Cr=TypeError,lt="Reduce of empty array with no initial value",Co=function(A){return function(e,o,n,a){var I=je(e),c=dA(I),u=ut(I);if(te(o),u===0&&n<2)throw new Cr(lt);var d=A?u-1:0,R=A?-1:1;if(n<2)for(;;){if(d in c){a=c[d],d+=R;break}if(d+=R,A?d<0:u<=d)throw new Cr(lt)}for(;A?d>=0:u>d;d+=R)d in c&&(a=o(a,c[d],d,I));return a}},Jt={left:Co(!1),right:Co(!0)},mo=m,Fe=function(A,e){var o=[][A];return!!o&&mo(function(){o.call(null,e||function(){return 1},1)})},Oe=Q,xs=Te,Zo=$e,ti=function(A){return xs.slice(0,A.length)===A},_n=ti("Bun/")?"BUN":ti("Cloudflare-Workers")?"CLOUDFLARE":ti("Deno/")?"DENO":ti("Node.js/")?"NODE":Oe.Bun&&typeof Bun.version=="string"?"BUN":Oe.Deno&&typeof Deno.version=="object"?"DENO":Zo(Oe.process)==="process"?"NODE":Oe.window&&Oe.document?"BROWSER":"REST",Eg=_n==="NODE",Bo=Jt.left;wr({target:"Array",proto:!0,forced:!Eg&&ot>79&&ot<83||!Fe("reduce")},{reduce:function(A){var e=arguments.length;return Bo(this,A,e,e>1?arguments[1]:void 0)}});var Da=Jt.right;wr({target:"Array",proto:!0,forced:!Eg&&ot>79&&ot<83||!Fe("reduceRight")},{reduceRight:function(A){return Da(this,A,arguments.length,arguments.length>1?arguments[1]:void 0)}});var Xa=$e,ia=Array.isArray||function(A){return Xa(A)==="Array"},b=wr,rA=ia,gA=Me([].reverse),pA=[1,2];b({target:"Array",proto:!0,forced:String(pA)===String(pA.reverse())},{reverse:function(){return rA(this)&&(this.length=this.length),gA(this)}});var vA=Kr,Ae=TypeError,UA=Me([].slice),re=UA,LA=Math.floor,se=function(A,e){var o=A.length;if(o<8)for(var n,a,I=1;I0;)A[a]=A[--a];a!==I++&&(A[a]=n)}else for(var c=LA(o/2),u=se(re(A,0,c),e),d=se(re(A,c),e),R=u.length,k=d.length,_=0,Z=0;_3)){if(fD)return!0;if(Qt)return Qt<603;var A,e,o,n,a="";for(A=65;A<76;A++){switch(e=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(n=0;n<47;n++)Ti.push({k:e+n,v:o})}for(Ti.sort(function(I,c){return c.v-I.v}),n=0;n$a(d)?1:-1}}(A)),o=$i(a),n=0;no||d!=d?1/0*c:c*d},Lk=Math.fround||function(A){return bk(A,11920928955078125e-23,34028234663852886e22,11754943508222875e-54)},LY=Array,FY=Math.abs,bC=Math.pow,UY=Math.floor,Fk=Math.log,OY=Math.LN2,Lw={pack:function(A,e,o){var n,a,I,c=LY(o),u=8*o-e-1,d=(1<>1,k=e===23?bC(2,-24)-bC(2,-77):0,_=A<0||A===0&&1/A<0?1:0,Z=0;for((A=FY(A))!=A||A===1/0?(a=A!=A?1:0,n=d):(n=UY(Fk(A)/OY),A*(I=bC(2,-n))<1&&(n--,I*=2),(A+=n+R>=1?k/I:k*bC(2,1-R))*I>=2&&(n++,I/=2),n+R>=d?(a=0,n=d):n+R>=1?(a=(A*I-1)*bC(2,e),n+=R):(a=A*bC(2,R-1)*bC(2,e),n=0));e>=8;)c[Z++]=255&a,a/=256,e-=8;for(n=n<0;)c[Z++]=255&n,n/=256,u-=8;return c[Z-1]|=128*_,c},unpack:function(A,e){var o,n=A.length,a=8*n-e-1,I=(1<>1,u=a-7,d=n-1,R=A[d--],k=127&R;for(R>>=7;u>0;)k=256*k+A[d--],u-=8;for(o=k&(1<<-u)-1,k>>=-u,u+=e;u>0;)o=256*o+A[d--],u-=8;if(k===0)k=1-c;else{if(k===I)return o?NaN:R?-1/0:1/0;o+=bC(2,e),k-=c}return(R?-1:1)*o*bC(2,k-e)}},xY=ao,Uk=_c,YY=hs,Ok=function(A){for(var e=xY(this),o=YY(e),n=arguments.length,a=Uk(n>1?arguments[1]:void 0,o),I=n>2?arguments[2]:void 0,c=I===void 0?o:Uk(I,o);c>a;)e[a++]=A;return e},PY=Ni,JY=Ji,Fw=q,Uw=function(A,e,o){var n,a;return Fw&&PY(n=e.constructor)&&n!==o&&JY(a=n.prototype)&&a!==o.prototype&&Fw(A,a),A},Sp=Q,RD=Me,MD=M,FB=Cn,HY=Bs,VY=dI,wD=JE,Ow=m,Hu=oc,qY=ca,KY=Wr,SD=mD,xk=Lk,xw=Lw,Yk=FE,Pk=q,jY=Ok,WY=UA,zY=Uw,Jk=Gl,Hk=Rs,vD=on,Vu=_s.PROPER,Yw=_s.CONFIGURABLE,qu="ArrayBuffer",Ku="DataView",ld="prototype",Pw="Wrong index",Jw=vD.getterFor(qu),vp=vD.getterFor(Ku),Vk=vD.set,HE=Sp[qu],VE=HE,Cd=VE&&VE[ld],qE=Sp[Ku],UB=qE&&qE[ld],LC=Object.prototype,ND=Sp.Array,Bd=Sp.RangeError,ZY=RD(jY),XY=RD([].reverse),TD=xw.pack,GD=xw.unpack,qk=function(A){return[255&A]},Kk=function(A){return[255&A,A>>8&255]},Hw=function(A){return[255&A,A>>8&255,A>>16&255,A>>24&255]},Vw=function(A){return A[3]<<24|A[2]<<16|A[1]<<8|A[0]},qw=function(A){return TD(xk(A),23,4)},jk=function(A){return TD(A,52,8)},Np=function(A,e,o){VY(A[ld],e,{configurable:!0,get:function(){return o(this)[e]}})},FC=function(A,e,o,n){var a=vp(A),I=SD(o),c=!!n;if(I+e>a.byteLength)throw new Bd(Pw);var u=a.bytes,d=I+a.byteOffset,R=WY(u,d,d+e);return c?R:XY(R)},OB=function(A,e,o,n,a,I){var c=vp(A),u=SD(o),d=n(+a),R=!!I;if(u+e>c.byteLength)throw new Bd(Pw);for(var k=c.bytes,_=u+c.byteOffset,Z=0;Z>24)},setUint8:function(A,e){Kw(this,A,e<<24>>24)}},{unsafe:!0})}else Cd=(VE=function(A){Hu(this,Cd);var e=SD(A);Vk(this,{type:qu,bytes:ZY(ND(e),0),byteLength:e}),MD||(this.byteLength=e,this.detached=!1)})[ld],UB=(qE=function(A,e,o){Hu(this,UB),Hu(A,Cd);var n=Jw(A),a=n.byteLength,I=qY(e);if(I<0||I>a)throw new Bd("Wrong offset");if(I+(o=o===void 0?a-I:KY(o))>a)throw new Bd("Wrong length");Vk(this,{type:Ku,buffer:A,byteLength:o,byteOffset:I,bytes:n.bytes}),MD||(this.buffer=A,this.byteLength=o,this.byteOffset=I)})[ld],MD&&(Np(VE,"byteLength",Jw),Np(qE,"buffer",vp),Np(qE,"byteLength",vp),Np(qE,"byteOffset",vp)),wD(UB,{getInt8:function(A){return FC(this,1,A)[0]<<24>>24},getUint8:function(A){return FC(this,1,A)[0]},getInt16:function(A){var e=FC(this,2,A,arguments.length>1&&arguments[1]);return(e[1]<<8|e[0])<<16>>16},getUint16:function(A){var e=FC(this,2,A,arguments.length>1&&arguments[1]);return e[1]<<8|e[0]},getInt32:function(A){return Vw(FC(this,4,A,arguments.length>1&&arguments[1]))},getUint32:function(A){return Vw(FC(this,4,A,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(A){return GD(FC(this,4,A,arguments.length>1&&arguments[1]),23)},getFloat64:function(A){return GD(FC(this,8,A,arguments.length>1&&arguments[1]),52)},setInt8:function(A,e){OB(this,1,A,qk,e)},setUint8:function(A,e){OB(this,1,A,qk,e)},setInt16:function(A,e){OB(this,2,A,Kk,e,arguments.length>2&&arguments[2])},setUint16:function(A,e){OB(this,2,A,Kk,e,arguments.length>2&&arguments[2])},setInt32:function(A,e){OB(this,4,A,Hw,e,arguments.length>2&&arguments[2])},setUint32:function(A,e){OB(this,4,A,Hw,e,arguments.length>2&&arguments[2])},setFloat32:function(A,e){OB(this,4,A,qw,e,arguments.length>2&&arguments[2])},setFloat64:function(A,e){OB(this,8,A,jk,e,arguments.length>2&&arguments[2])}});Hk(VE,qu),Hk(qE,Ku);var kD={ArrayBuffer:VE,DataView:qE},$Y=MA,AP=dI,_D=M,zk=qo("species"),bD=function(A){var e=$Y(A);_D&&e&&!e[zk]&&AP(e,zk,{configurable:!0,get:function(){return this}})},eP=bD,jw="ArrayBuffer",Zk=kD[jw];wr({global:!0,constructor:!0,forced:Q[jw]!==Zk},{ArrayBuffer:Zk}),eP(jw);var tP=$e,UC=Me,jl=function(A){if(tP(A)==="Function")return UC(A)},Xk=wr,ud=jl,iP=m,$k=Zr,A_=_c,oP=Wr,Ww=kD.ArrayBuffer,zw=kD.DataView,e_=zw.prototype,Zw=ud(Ww.prototype.slice),rP=ud(e_.getUint8),nP=ud(e_.setUint8);Xk({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:iP(function(){return!new Ww(2).slice(1,void 0).byteLength})},{slice:function(A,e){if(Zw&&e===void 0)return Zw($k(this),A);for(var o=$k(this).byteLength,n=A_(A,o),a=A_(e===void 0?o:e,o),I=new Ww(oP(a-n)),c=new zw(this),u=new zw(I),d=0;nI;I++)if((u=Ie(A[I]))&&_S(vd,u))return u;return new Yp(!1)}n=e1(A,a)}for(d=Z?A.next:n.next;!(R=ZP(d,n)).done;){try{u=Ie(R.value)}catch(XA){ib(n,"throw",XA)}if(typeof u=="object"&&u&&_S(vd,u))return u}return new Yp(!1)},LS=qo("iterator"),FS=!1;try{var o1=0,US={next:function(){return{done:!!o1++}},return:function(){FS=!0}};US[LS]=function(){return this},Array.from(US,function(){throw 2})}catch{}var Nd=function(A,e){try{if(!e&&!FS)return!1}catch{return!1}var o=!1;try{var n={};n[LS]=function(){return{next:function(){return{done:o=!0}}}},A(n)}catch{}return o},Td=Lp,OS=Zu.CONSTRUCTOR||!Nd(function(A){Td.all(A).then(void 0,function(){})}),xS=z,Pp=$t,r1=Dd,n1=dS,ey=bS;wr({target:"Promise",stat:!0,forced:OS},{all:function(A){var e=this,o=r1.f(e),n=o.resolve,a=o.reject,I=n1(function(){var c=Pp(e.resolve),u=[],d=0,R=1;ey(A,function(k){var _=d++,Z=!1;R++,xS(c,e,k).then(function(iA){Z||(Z=!0,u[_]=iA,--R||n(u))},a)}),--R||n(u)});return I.error&&a(I.value),o.promise}});var YS=wr,PS=Zu.CONSTRUCTOR,JS=Lp,a1=MA,s1=Ni,ob=mn,Gd=JS&&JS.prototype;if(YS({target:"Promise",proto:!0,forced:PS,real:!0},{catch:function(A){return this.then(void 0,A)}}),s1(JS)){var rb=a1("Promise").prototype.catch;Gd.catch!==rb&&ob(Gd,"catch",rb,{unsafe:!0})}var g1=z,Jp=$t,I1=Dd,c1=dS,E1=bS;wr({target:"Promise",stat:!0,forced:OS},{race:function(A){var e=this,o=I1.f(e),n=o.reject,a=c1(function(){var I=Jp(e.resolve);E1(A,function(c){g1(I,e,c).then(o.resolve,n)})});return a.error&&n(a.value),o.promise}});var nb=Dd;wr({target:"Promise",stat:!0,forced:Zu.CONSTRUCTOR},{reject:function(A){var e=nb.f(this);return(0,e.reject)(A),e.promise}});var ab=Zr,l1=Ji,C1=Dd,sb=function(A,e){if(ab(A),l1(e)&&e.constructor===A)return e;var o=C1.f(A);return(0,o.resolve)(e),o.promise},B1=wr,gb=Zu.CONSTRUCTOR,Ib=sb;MA("Promise"),B1({target:"Promise",stat:!0,forced:gb},{resolve:function(A){return Ib(this,A)}});var nc=wr,ty=Lp,u1=m,HS=MA,cb=Ni,Eb=g_,VS=sb,Q1=mn,iy=ty&&ty.prototype;if(nc({target:"Promise",proto:!0,real:!0,forced:!!ty&&u1(function(){iy.finally.call({then:function(){}},function(){})})},{finally:function(A){var e=Eb(this,HS("Promise")),o=cb(A);return this.then(o?function(n){return VS(e,A()).then(function(){return n})}:A,o?function(n){return VS(e,A()).then(function(){throw n})}:A)}}),cb(ty)){var lb=HS("Promise").prototype.finally;iy.finally!==lb&&Q1(iy,"finally",lb,{unsafe:!0})}var d1=Ji,h1=$e,qS=qo("match"),KS=function(A){var e;return d1(A)&&((e=A[qS])!==void 0?!!e:h1(A)==="RegExp")},p1=m,oy=Q.RegExp,f1=!p1(function(){var A=!0;try{oy(".","d")}catch{A=!1}var e={},o="",n=A?"dgimsy":"gimsy",a=function(u,d){Object.defineProperty(e,u,{get:function(){return o+=d,!0}})},I={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var c in A&&(I.hasIndices="d"),I)a(c,I[c]);return Object.getOwnPropertyDescriptor(oy.prototype,"flags").get.call(e)!==n||o!==n}),Cb=Zr,Bb=function(){var A=Cb(this),e="";return A.hasIndices&&(e+="d"),A.global&&(e+="g"),A.ignoreCase&&(e+="i"),A.multiline&&(e+="m"),A.dotAll&&(e+="s"),A.unicode&&(e+="u"),A.unicodeSets&&(e+="v"),A.sticky&&(e+="y"),e},jS=z,Hp=po,ub=YA,ry={correct:f1},WS=Bb,Qb=RegExp.prototype,ny=ry.correct?function(A){return A.flags}:function(A){return ry.correct||!ub(Qb,A)||Hp(A,"flags")?A.flags:jS(WS,A)},ay=m,sy=Q.RegExp,zS=ay(function(){var A=sy("a","y");return A.lastIndex=2,A.exec("abcd")!==null}),m1=zS||ay(function(){return!sy("a","y").sticky}),db=zS||ay(function(){var A=sy("^r","gy");return A.lastIndex=2,A.exec("str")!==null}),tQ={BROKEN_CARET:db,MISSED_STICKY:m1,UNSUPPORTED_Y:zS},ZS=oi.f,XS=m,$S=Q.RegExp,A0=XS(function(){var A=$S(".","s");return!(A.dotAll&&A.test(` -`)&&A.flags==="s")}),hb=m,D1=Q.RegExp,pb=hb(function(){var A=D1("(?b)","g");return A.exec("b").groups.a!=="b"||"b".replace(A,"$c")!=="bc"}),kd=M,e0=Q,_d=Me,t0=Rn,y1=Uw,R1=Bs,M1=fa,w1=Lg.f,gy=YA,fb=KS,i0=Mn,mb=ny,Vp=tQ,o0=function(A,e,o){o in A||ZS(A,o,{configurable:!0,get:function(){return e[o]},set:function(n){e[o]=n}})},Iy=mn,cy=m,S1=po,r0=on.enforce,Ey=bD,Db=A0,bd=pb,v1=qo("match"),YB=e0.RegExp,Ld=YB.prototype,N1=e0.SyntaxError,yb=_d(Ld.exec),Fd=_d("".charAt),Rb=_d("".replace),n0=_d("".indexOf),a0=_d("".slice),T1=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,ac=/a/g,PB=/a/g,Mb=new YB(ac)!==ac,wb=Vp.MISSED_STICKY,G1=Vp.UNSUPPORTED_Y,s0=kd&&(!Mb||wb||Db||bd||cy(function(){return PB[v1]=!1,YB(ac)!==ac||YB(PB)===PB||String(YB(ac,"i"))!=="/a/i"}));if(t0("RegExp",s0)){for(var JB=function(A,e){var o,n,a,I,c,u,d=gy(Ld,this),R=fb(A),k=e===void 0,_=[],Z=A;if(!d&&R&&k&&A.constructor===JB)return A;if((R||gy(Ld,A))&&(A=A.source,k&&(e=mb(Z))),A=A===void 0?"":i0(A),e=e===void 0?"":i0(e),Z=A,Db&&"dotAll"in ac&&(n=!!e&&n0(e,"s")>-1)&&(e=Rb(e,/s/g,"")),o=e,wb&&"sticky"in ac&&(a=!!e&&n0(e,"y")>-1)&&G1&&(e=Rb(e,/y/g,"")),bd&&(I=function(iA){for(var cA,TA=iA.length,JA=0,Ie="",XA=[],Ft=M1(null),ie=!1,ke=!1,Nt=0,Ut="";JA<=TA;JA++){if((cA=Fd(iA,JA))==="\\")cA+=Fd(iA,++JA);else if(cA==="]")ie=!1;else if(!ie)switch(!0){case cA==="[":ie=!0;break;case cA==="(":if(Ie+=cA,a0(iA,JA+1,JA+3)==="?:")continue;yb(T1,a0(iA,JA+1))&&(JA+=2,ke=!0),Nt++;continue;case(cA===">"&&ke):if(Ut===""||S1(Ft,Ut))throw new N1("Invalid capture group name");Ft[Ut]=!0,XA[XA.length]=[Ut,Nt],ke=!1,Ut="";continue}ke?Ut+=cA:Ie+=cA}return[Ie,XA]}(A),A=I[0],_=I[1]),c=y1(YB(A,e),d?this:Ld,JB),(n||a||_.length)&&(u=r0(c),n&&(u.dotAll=!0,u.raw=JB(function(iA){for(var cA,TA=iA.length,JA=0,Ie="",XA=!1;JA<=TA;JA++)(cA=Fd(iA,JA))!=="\\"?XA||cA!=="."?(cA==="["?XA=!0:cA==="]"&&(XA=!1),Ie+=cA):Ie+="[\\s\\S]":Ie+=cA+Fd(iA,++JA);return Ie}(A),o)),a&&(u.sticky=!0),_.length&&(u.groups=_)),A!==Z)try{R1(c,"source",Z===""?"(?:)":Z)}catch{}return c},g0=w1(YB),I0=0;g0.length>I0;)o0(JB,YB,g0[I0++]);Ld.constructor=JB,JB.prototype=Ld,Iy(e0,"RegExp",JB,{constructor:!0})}Ey("RegExp");var Ud=z,iQ=Me,HB=Mn,k1=Bb,Od=tQ,Sb=fa,vb=on.get,_1=A0,b1=pb,L1=Yo("native-string-replace",String.prototype.replace),oQ=RegExp.prototype.exec,c0=oQ,F1=iQ("".charAt),U1=iQ("".indexOf),Nb=iQ("".replace),qp=iQ("".slice),E0=function(){var A=/a/,e=/b*/g;return Ud(oQ,A,"a"),Ud(oQ,e,"a"),A.lastIndex!==0||e.lastIndex!==0}(),Tb=Od.BROKEN_CARET,l0=/()??/.exec("")[1]!==void 0;(E0||l0||Tb||_1||b1)&&(c0=function(A){var e,o,n,a,I,c,u,d=this,R=vb(d),k=HB(A),_=R.raw;if(_)return _.lastIndex=d.lastIndex,e=Ud(c0,_,k),d.lastIndex=_.lastIndex,e;var Z=R.groups,iA=Tb&&d.sticky,cA=Ud(k1,d),TA=d.source,JA=0,Ie=k;if(iA&&(cA=Nb(cA,"y",""),U1(cA,"g")===-1&&(cA+="g"),Ie=qp(k,d.lastIndex),d.lastIndex>0&&(!d.multiline||d.multiline&&F1(k,d.lastIndex-1)!==` -`)&&(TA="(?: "+TA+")",Ie=" "+Ie,JA++),o=new RegExp("^(?:"+TA+")",cA)),l0&&(o=new RegExp("^"+TA+"$(?!\\s)",cA)),E0&&(n=d.lastIndex),a=Ud(oQ,iA?o:d,Ie),iA?a?(a.input=qp(a.input,JA),a[0]=qp(a[0],JA),a.index=d.lastIndex,d.lastIndex+=a[0].length):d.lastIndex=0:E0&&a&&(d.lastIndex=d.global?a.index+a[0].length:n),l0&&a&&a.length>1&&Ud(L1,a[0],o,function(){for(I=1;I0;(n>>>=1)&&(e+=e))1&n&&(o+=e);return o},xd=no,Yd=_b(x1),uy=_b("".slice),bb=Math.ceil,C0=function(A){return function(e,o,n){var a,I,c=By(xd(e)),u=O1(o),d=c.length,R=n===void 0?" ":By(n);return u<=d||R===""?c:((I=Yd(R,bb((a=u-d)/R.length))).length>a&&(I=uy(I,0,a)),A?c+I:I+c)}},B0={start:C0(!1)},u0=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Te),Y1=B0.start;wr({target:"String",proto:!0,forced:u0},{padStart:function(A){return Y1(this,A,arguments.length>1?arguments[1]:void 0)}});var Lb=z,Q0=mn,Fb=Kp,d0=m,h0=qo,P1=h0("species"),Ub=RegExp.prototype,Qy=Me,J1=ca,Pd=Mn,Jd=no,p0=Qy("".charAt),Ob=Qy("".charCodeAt),H1=Qy("".slice),xb=function(A){return function(e,o){var n,a,I=Pd(Jd(e)),c=J1(o),u=I.length;return c<0||c>=u?A?"":void 0:(n=Ob(I,c))<55296||n>56319||c+1===u||(a=Ob(I,c+1))<56320||a>57343?A?p0(I,c):n:A?H1(I,c,c+2):a-56320+(n-55296<<10)+65536}},dy={codeAt:xb(!1),charAt:xb(!0)},V1=dy.charAt,hy=Me,q1=ao,K1=Math.floor,f0=hy("".charAt),m0=hy("".replace),D0=hy("".slice),j1=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,W1=/\$([$&'`]|\d{1,2})/g,Yb=function(A,e,o,n,a,I){var c=o+A.length,u=n.length,d=W1;return a!==void 0&&(a=q1(a),d=j1),m0(I,d,function(R,k){var _;switch(f0(k,0)){case"$":return"$";case"&":return A;case"`":return D0(e,0,o);case"'":return D0(e,c);case"<":_=a[D0(k,1,-1)];break;default:var Z=+k;if(Z===0)return R;if(Z>u){var iA=K1(Z/10);return iA===0?R:iA<=u?n[iA-1]===void 0?f0(k,1):n[iA-1]+f0(k,1):R}_=n[Z-1]}return _===void 0?"":_})},Pb=z,z1=Zr,Jb=Ni,Z1=$e,Hb=Kp,X1=TypeError,$1=OC,Vb=z,py=Me,AJ=function(A,e,o,n){var a=h0(A),I=!d0(function(){var R={};return R[a]=function(){return 7},""[A](R)!==7}),c=I&&!d0(function(){var R=!1,k=/a/,_;return k.exec=function(){return R=!0,null},k[a](""),!R});if(!I||!c||o){var u=/./[a],d=e(a,""[A],function(R,k,_,Z,iA){var cA=k.exec;return cA===Fb||cA===Ub.exec?I&&!iA?{done:!0,value:Lb(u,k,_,Z)}:{done:!0,value:Lb(R,_,k,Z)}:{done:!1}});Q0(String.prototype,A,d[0]),Q0(Ub,a,d[1])}},eJ=m,tJ=Zr,qb=Ni,iJ=Ji,oJ=ca,Kb=Wr,rQ=Mn,fy=no,jb=function(A,e,o){return e+(o?V1(A,e).length:1)},Dy=An,Wb=Yb,zb=ny,rJ=function(A,e){var o=A.exec;if(Jb(o)){var n=Pb(o,A,e);return n!==null&&z1(n),n}if(Z1(A)==="RegExp")return Pb(Hb,A,e);throw new X1("RegExp#exec called on incompatible receiver")},yy=qo("replace"),y0=Math.max,nJ=Math.min,Zb=py([].concat),R0=py([].push),Ry=py("".indexOf),Xb=py("".slice),aJ=function(A){return A===void 0?A:String(A)},sJ="a".replace(/./,"$0")==="$0",$b=!!/./[yy]&&/./[yy]("a","$0")==="",gJ=!eJ(function(){var A=/./;return A.exec=function(){var e=[];return e.groups={a:"7"},e},"".replace(A,"$")!=="7"});AJ("replace",function(A,e,o){var n=$b?"$":"$0";return[function(a,I){var c=fy(this),u=iJ(a)?Dy(a,yy):void 0;return u?Vb(u,a,c,I):Vb(e,rQ(c),a,I)},function(a,I){var c=tJ(this),u=rQ(a);if(typeof I=="string"&&Ry(I,n)===-1&&Ry(I,"$<")===-1){var d=o(e,c,u,I);if(d.done)return d.value}var R=qb(I);R||(I=rQ(I));var k,_=rQ(zb(c)),Z=Ry(_,"g")!==-1;Z&&(k=Ry(_,"u")!==-1,c.lastIndex=0);for(var iA,cA=[];(iA=rJ(c,u))!==null&&(R0(cA,iA),Z);)rQ(iA[0])===""&&(c.lastIndex=jb(u,Kb(c.lastIndex),k));for(var TA="",JA=0,Ie=0;Ie=JA&&(TA+=Xb(u,JA,ie)+XA,JA=ie+Ft.length)}return TA+Xb(u,JA)}]},!gJ||!sJ||$b);var My=` -\v\f\r                 \u2028\u2029\uFEFF`,IJ=no,cJ=Mn,M0=My,w0=Me("".replace),AL=RegExp("^["+M0+"]+"),EJ=RegExp("(^|[^"+M0+"])["+M0+"]+$"),lJ=function(A){return function(e){var o=cJ(IJ(e));return 1&A&&(o=w0(o,AL,"")),2&A&&(o=w0(o,EJ,"$1")),o}},CJ={trim:lJ(3)},BJ=_s.PROPER,uJ=m,eL=My,QJ=CJ.trim;wr({target:"String",proto:!0,forced:function(A){return uJ(function(){return!!eL[A]()||"​…᠎"[A]()!=="​…᠎"||BJ&&eL[A].name!==A})}("trim")},{trim:function(){return QJ(this)}});var mI,Hd,wy,S0={exports:{}},dJ=Cn,v0=M,Wg=Q,tL=Ni,iL=Ji,Vd=po,Sy=sg,N0=Kr,T0=Bs,G0=mn,oL=dI,hJ=YA,k0=FE,nQ=q,pJ=qo,fJ=$s,_0=on.enforce,PC=Wg.Int8Array,qd=PC&&PC.prototype,rL=Wg.Uint8ClampedArray,nL=rL&&rL.prototype,Wl=PC&&k0(PC),jE=qd&&k0(qd),mJ=Object.prototype,b0=Wg.TypeError,aL=pJ("toStringTag"),L0=fJ("TYPED_ARRAY_TAG"),jp="TypedArrayConstructor",WE=dJ&&!!nQ&&Sy(Wg.opera)!=="Opera",sL=!1,VB={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},gL={BigInt64Array:8,BigUint64Array:8},vy=function(A){if(!iL(A))return!1;var e=Sy(A);return Vd(VB,e)||Vd(gL,e)};for(mI in VB)(wy=(Hd=Wg[mI])&&Hd.prototype)?_0(wy)[jp]=Hd:WE=!1;for(mI in gL)(wy=(Hd=Wg[mI])&&Hd.prototype)&&(_0(wy)[jp]=Hd);if((!WE||!tL(Wl)||Wl===Function.prototype)&&(Wl=function(){throw new b0("Incorrect invocation")},WE))for(mI in VB)Wg[mI]&&nQ(Wg[mI],Wl);if((!WE||!jE||jE===mJ)&&(jE=Wl.prototype,WE))for(mI in VB)Wg[mI]&&nQ(Wg[mI].prototype,jE);if(WE&&k0(nL)!==jE&&nQ(nL,jE),v0&&!Vd(jE,aL))for(mI in sL=!0,oL(jE,aL,{configurable:!0,get:function(){return iL(this)?this[L0]:void 0}}),VB)Wg[mI]&&T0(Wg[mI],L0,mI);var zE={NATIVE_ARRAY_BUFFER_VIEWS:WE,TYPED_ARRAY_TAG:sL&&L0,aTypedArray:function(A){if(vy(A))return A;throw new b0("Target is not a typed array")},aTypedArrayConstructor:function(A){if(tL(A)&&(!nQ||hJ(Wl,A)))return A;throw new b0(N0(A)+" is not a typed array constructor")},exportTypedArrayMethod:function(A,e,o,n){if(v0){if(o)for(var a in VB){var I=Wg[a];if(I&&Vd(I.prototype,A))try{delete I.prototype[A]}catch{try{I.prototype[A]=e}catch{}}}jE[A]&&!o||G0(jE,A,o?e:WE&&qd[A]||e,n)}},exportTypedArrayStaticMethod:function(A,e,o){var n,a;if(v0){if(nQ){if(o){for(n in VB)if((a=Wg[n])&&Vd(a,A))try{delete a[A]}catch{}}if(Wl[A]&&!o)return;try{return G0(Wl,A,o?e:WE&&Wl[A]||e)}catch{}}for(n in VB)!(a=Wg[n])||a[A]&&!o||G0(a,A,e)}},isTypedArray:vy,TypedArray:Wl,TypedArrayPrototype:jE},F0=Q,Wp=m,Ny=Nd,DJ=zE.NATIVE_ARRAY_BUFFER_VIEWS,IL=F0.ArrayBuffer,aQ=F0.Int8Array,cL=!DJ||!Wp(function(){aQ(1)})||!Wp(function(){new aQ(-1)})||!Ny(function(A){new aQ,new aQ(null),new aQ(1.5),new aQ(A)},!0)||Wp(function(){return new aQ(new IL(2),1,void 0).length!==1}),yJ=Ji,RJ=Math.floor,EL=Number.isInteger||function(A){return!yJ(A)&&isFinite(A)&&RJ(A)===A},MJ=ca,wJ=RangeError,Ty=function(A){var e=MJ(A);if(e<0)throw new wJ("The argument can't be less than 0");return e},SJ=RangeError,lL=function(A,e){var o=Ty(A);if(o%e)throw new SJ("Wrong offset");return o},vJ=Math.round,CL=sg,NJ=Mr,TJ=TypeError,Gy=function(A){var e=NJ(A,"number");if(typeof e=="number")throw new TJ("Can't convert number to bigint");return BigInt(e)},BL=jc,uL=z,GJ=a_,kJ=ao,QL=hs,dL=eQ,_J=xp,hL=GS,pL=function(A){var e=CL(A);return e==="BigInt64Array"||e==="BigUint64Array"},bJ=zE.aTypedArrayConstructor,LJ=Gy,ky=function(A){var e,o,n,a,I,c,u,d,R=GJ(this),k=kJ(A),_=arguments.length,Z=_>1?arguments[1]:void 0,iA=Z!==void 0,cA=_J(k);if(cA&&!hL(cA))for(d=(u=dL(k,cA)).next,k=[];!(c=uL(d,u)).done;)k.push(c.value);for(iA&&_>2&&(Z=BL(Z,arguments[2])),o=QL(k),n=new(bJ(R))(o),a=pL(n),e=0;o>e;e++)I=iA?Z(k[e],e):k[e],n[e]=a?LJ(I):+I;return n},U0=ia,O0=eS,FJ=Ji,UJ=qo("species"),fL=Array,OJ=function(A){var e;return U0(A)&&(e=A.constructor,(O0(e)&&(e===fL||U0(e.prototype))||FJ(e)&&(e=e[UJ])===null)&&(e=void 0)),e===void 0?fL:e},mL=jc,xJ=ai,YJ=ao,DL=hs,PJ=function(A,e){return new(OJ(A))(e===0?0:e)},x0=Me([].push),yL=function(A){var e=A===1,o=A===2,n=A===3,a=A===4,I=A===6,c=A===7,u=A===5||I;return function(d,R,k,_){for(var Z,iA,cA=YJ(d),TA=xJ(cA),JA=DL(TA),Ie=mL(R,k),XA=0,Ft=_||PJ,ie=e?Ft(d,JA):o||c?Ft(d,0):void 0;JA>XA;XA++)if((u||XA in TA)&&(iA=Ie(Z=TA[XA],XA,cA),A))if(e)ie[XA]=iA;else if(iA)switch(A){case 3:return!0;case 5:return Z;case 6:return XA;case 2:x0(ie,Z)}else switch(A){case 4:return!1;case 7:x0(ie,Z)}return I?-1:n||a?a:ie}},RL={forEach:yL(0)},JJ=hs,ML=wr,wL=Q,SL=z,vL=M,HJ=cL,zp=zE,NL=kD,TL=oc,VJ=VA,qB=Bs,qJ=EL,KJ=Wr,GL=mD,Y0=lL,kL=function(A){var e=vJ(A);return e<0?0:e>255?255:255&e},P0=P,sQ=po,jJ=sg,J0=Ji,H0=Vo,WJ=fa,V0=YA,_y=q,zJ=Lg.f,_L=ky,bL=RL.forEach,by=bD,ZJ=dI,LL=oi,FL=f,UL=function(A,e,o){for(var n=0,a=arguments.length>2?o:JJ(e),I=new A(a);a>n;)I[n]=e[n++];return I},XJ=Uw,q0=on.get,$J=on.set,gQ=on.enforce,OL=LL.f,AH=FL.f,K0=wL.RangeError,xL=NL.ArrayBuffer,eH=xL.prototype,tH=NL.DataView,Kd=zp.NATIVE_ARRAY_BUFFER_VIEWS,YL=zp.TYPED_ARRAY_TAG,PL=zp.TypedArray,Zp=zp.TypedArrayPrototype,Xp=zp.isTypedArray,IQ="BYTES_PER_ELEMENT",Ly="Wrong length",Fy=function(A,e){ZJ(A,e,{configurable:!0,get:function(){return q0(this)[e]}})},JL=function(A){var e;return V0(eH,A)||(e=jJ(A))==="ArrayBuffer"||e==="SharedArrayBuffer"},j0=function(A,e){return Xp(A)&&!H0(e)&&e in A&&qJ(+e)&&e>=0},Uy=function(A,e){return e=P0(e),j0(A,e)?VJ(2,A[e]):AH(A,e)},HL=function(A,e,o){return e=P0(e),!(j0(A,e)&&J0(o)&&sQ(o,"value"))||sQ(o,"get")||sQ(o,"set")||o.configurable||sQ(o,"writable")&&!o.writable||sQ(o,"enumerable")&&!o.enumerable?OL(A,e,o):(A[e]=o.value,A)};vL?(Kd||(FL.f=Uy,LL.f=HL,Fy(Zp,"buffer"),Fy(Zp,"byteOffset"),Fy(Zp,"byteLength"),Fy(Zp,"length")),ML({target:"Object",stat:!0,forced:!Kd},{getOwnPropertyDescriptor:Uy,defineProperty:HL}),S0.exports=function(A,e,o){var n=A.match(/\d+/)[0]/8,a=A+(o?"Clamped":"")+"Array",I="get"+A,c="set"+A,u=wL[a],d=u,R=d&&d.prototype,k={},_=function(iA,cA){OL(iA,cA,{get:function(){return function(TA,JA){var Ie=q0(TA);return Ie.view[I](JA*n+Ie.byteOffset,!0)}(this,cA)},set:function(TA){return function(JA,Ie,XA){var Ft=q0(JA);Ft.view[c](Ie*n+Ft.byteOffset,o?kL(XA):XA,!0)}(this,cA,TA)},enumerable:!0})};Kd?HJ&&(d=e(function(iA,cA,TA,JA){return TL(iA,R),XJ(J0(cA)?JL(cA)?JA!==void 0?new u(cA,Y0(TA,n),JA):TA!==void 0?new u(cA,Y0(TA,n)):new u(cA):Xp(cA)?UL(d,cA):SL(_L,d,cA):new u(GL(cA)),iA,d)}),_y&&_y(d,PL),bL(zJ(u),function(iA){iA in d||qB(d,iA,u[iA])}),d.prototype=R):(d=e(function(iA,cA,TA,JA){TL(iA,R);var Ie,XA,Ft,ie=0,ke=0;if(J0(cA)){if(!JL(cA))return Xp(cA)?UL(d,cA):SL(_L,d,cA);Ie=cA,ke=Y0(TA,n);var Nt=cA.byteLength;if(JA===void 0){if(Nt%n)throw new K0(Ly);if((XA=Nt-ke)<0)throw new K0(Ly)}else if((XA=KJ(JA)*n)+ke>Nt)throw new K0(Ly);Ft=XA/n}else Ft=GL(cA),Ie=new xL(XA=Ft*n);for($J(iA,{buffer:Ie,byteOffset:ke,byteLength:XA,length:Ft,view:new tH(Ie)});ie1?arguments[1]:void 0,e>2?arguments[2]:void 0)},W0(function(){var A=0;return new Int8Array(2).fill({valueOf:function(){return A++}}),A!==1})),(0,zE.exportTypedArrayStaticMethod)("from",ky,cL);var KL=Q,jL=z,Z0=zE,WL=hs,sH=lL,gH=ao,zL=m,IH=KL.RangeError,X0=KL.Int8Array,$0=X0&&X0.prototype,Av=$0&&$0.set,ev=Z0.aTypedArray,ZL=Z0.exportTypedArrayMethod,Oy=!zL(function(){var A=new Uint8ClampedArray(2);return jL(Av,A,{length:1,0:3},1),A[1]!==3}),XL=Oy&&Z0.NATIVE_ARRAY_BUFFER_VIEWS&&zL(function(){var A=new X0(2);return A.set(1),A.set("2",1),A[0]!==0||A[1]!==2});ZL("set",function(A){ev(this);var e=sH(arguments.length>1?arguments[1]:void 0,1),o=gH(A);if(Oy)return jL(Av,this,o,e);var n=this.length,a=WL(o),I=0;if(a+e>n)throw new IH("Wrong length");for(;I0&&1/n<0?1:-1:o>n}}(A))},!xy||sv);var AF=wr,gv=z,Af=Me,Iv=no,cv=Ni,lH=Ji,eF=KS,ef=Mn,CH=An,tf=ny,tF=Yb,BH=qo("replace"),iF=TypeError,ZE=Af("".indexOf);Af("".replace);var of=Af("".slice),uH=Math.max;AF({target:"String",proto:!0},{replaceAll:function(A,e){var o,n,a,I,c,u,d,R,k,_=Iv(this),Z=0,iA="";if(lH(A)){if(eF(A)&&(o=ef(Iv(tf(A))),!~ZE(o,"g")))throw new iF("`.replaceAll` does not allow non-global regexes");if(n=CH(A,BH))return gv(n,A,_,e)}for(a=ef(_),I=ef(A),(c=cv(e))||(e=ef(e)),u=I.length,d=uH(1,u),R=ZE(a,I);R!==-1;)k=c?ef(e(I,R,a)):tF(I,a,R,[],void 0,e),iA+=of(a,Z,R)+k,Z=R+u,R=R+d>a.length?-1:ZE(a,I,R+d);return Z1?arguments[1]:void 0)},rF=Q,nF=Ev,hH=lv,Py=dH,pH=Bs,aF=function(A){if(A&&A.forEach!==Py)try{pH(A,"forEach",Py)}catch{A.forEach=Py}};for(var Cv in nF)nF[Cv]&&aF(rF[Cv]&&rF[Cv].prototype);aF(hH);var Jy=Q,sF=Ev,fH=lv,rf=si,nf=Bs,mH=Rs,Bv=qo("iterator"),uv=rf.values,gF=function(A,e){if(A){if(A[Bv]!==uv)try{nf(A,Bv,uv)}catch{A[Bv]=uv}if(mH(A,e,!0),sF[e]){for(var o in rf)if(A[o]!==rf[o])try{nf(A,o,rf[o])}catch{A[o]=rf[o]}}}};for(var Qv in sF)gF(Jy[Qv]&&Jy[Qv].prototype,Qv);gF(fH,"DOMTokenList");var dv=JD.clear;wr({global:!0,bind:!0,enumerable:!0,forced:Q.clearImmediate!==dv},{clearImmediate:dv});var af=Q,DH=OC,yH=Ni,RH=_n,MH=Te,wH=UA,SH=xD,hv=af.Function,vH=/MSIE .\./.test(MH)||RH==="BUN"&&function(){var A=af.Bun.version.split(".");return A.length<3||A[0]==="0"&&(A[1]<3||A[1]==="3"&&A[2]==="0")}(),IF=wr,cF=Q,Hy=JD.set,NH=function(A,e){var o=1;return vH?function(n,a){var I=SH(arguments.length,1)>o,c=yH(n)?n:hv(n),u=I?wH(arguments,o):[],d=I?function(){DH(c,this,u)}:c;return A(d)}:A},pv=cF.setImmediate?NH(Hy):Hy;IF({global:!0,bind:!0,enumerable:!0,forced:cF.setImmediate!==pv},{setImmediate:pv});var JC=dy.charAt,TH=Mn,Vy=on,GH=xA,EF=Qe,lF="String Iterator",kH=Vy.set,CF=Vy.getterFor(lF);GH(String,"String",function(A){kH(this,{type:lF,string:TH(A),index:0})},function(){var A,e=CF(this),o=e.string,n=e.index;return n>=o.length?EF(void 0,!0):(A=JC(o,n),e.index+=A.length,EF(A,!1))});var _H=m,bH=M,LH=qo("iterator"),BF=!_H(function(){var A=new URL("b?a=1&b=2&c=3","https://a"),e=A.searchParams,o=new URLSearchParams("a=1&a=2&b=3"),n="";return A.pathname="c%20d",e.forEach(function(a,I){e.delete("b"),n+=I+a}),o.delete("a",2),o.delete("b",void 0),!e.size&&!bH||!e.sort||A.href!=="https://a/c%20d?a=1&c=3"||e.get("c")!=="3"||String(new URLSearchParams("?a=1"))!=="a=1"||!e[LH]||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"||n!=="a1c3"||new URL("https://x",void 0).host!=="x"}),uF=M,FH=Me,fv=z,mv=m,Dv=pI,UH=Ug,OH=sA,xH=ao,QF=ai,cQ=Object.assign,dF=Object.defineProperty,hF=FH([].concat),YH=!cQ||mv(function(){if(uF&&cQ({b:1},cQ(dF({},"a",{enumerable:!0,get:function(){dF(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var A={},e={},o=Symbol("assign detection"),n="abcdefghijklmnopqrst";return A[o]=7,n.split("").forEach(function(a){e[a]=a}),cQ({},A)[o]!==7||Dv(cQ({},e)).join("")!==n})?function(A,e){for(var o=xH(A),n=arguments.length,a=1,I=UH.f,c=OH.f;n>a;)for(var u,d=QF(arguments[a++]),R=I?hF(Dv(d),I(d)):Dv(d),k=R.length,_=0;k>_;)u=R[_++],uF&&!fv(c,d,u)||(o[u]=d[u]);return o}:cQ,PH=Zr,JH=Ab,HH=M,VH=oi,pF=VA,qH=jc,sf=z,fF=ao,mF=function(A,e,o,n){try{return n?e(PH(o)[0],o[1]):e(o)}catch(a){JH(A,"throw",a)}},yv=GS,KH=eS,jH=hs,gf=function(A,e,o){HH?VH.f(A,e,pF(0,o)):A[e]=o},Rv=eQ,WH=xp,DF=Array,KB=Me,Mv=2147483647,yF=/[^\0-\u007E]/,wv=/[.\u3002\uFF0E\uFF61]/g,RF="Overflow: input needs wider integers to process",MF=RangeError,zH=KB(wv.exec),jB=Math.floor,qy=String.fromCharCode,Ky=KB("".charCodeAt),sc=KB([].join),WB=KB([].push),Pn=KB("".replace),wF=KB("".split),ZH=KB("".toLowerCase),SF=function(A){return A+22+75*(A<26)},Sv=function(A,e,o){var n=0;for(A=o?jB(A/700):A>>1,A+=jB(A/e);A>455;)A=jB(A/35),n+=36;return jB(n+36*A/(A+38))},XH=function(A){var e=[];A=function(Ie){for(var XA=[],Ft=0,ie=Ie.length;Ft=55296&&ke<=56319&&Ft=I&&njB((Mv-c)/_))throw new MF(RF);for(c+=(k-I)*_,I=k,o=0;oMv)throw new MF(RF);if(n===I){for(var Z=c,iA=36;;){var cA=iA<=u?1:iA>=u+26?26:iA-u;if(Za;){if(e=+arguments[a++],$H(e,1114111)!==e)throw new AV(e+" is not a valid code point");o[a]=e<65536?HC(e):HC(55296+((e-=65536)>>10),e%1024+56320)}return cf(o,"")}});var EQ=wr,Zd=Q,lQ=y_,vv=MA,To=z,gc=Me,Xd=M,Nv=BF,NF=mn,eV=dI,tV=JE,iV=Rs,oV=bB,Ef=on,TF=oc,Tv=Ni,rV=po,nV=jc,aV=sg,sV=Zr,GF=Ji,Bg=Mn,gV=fa,kF=VA,_F=eQ,IV=xp,jy=Qe,$d=xD,cV=He,EV=qo("iterator"),CQ="URLSearchParams",Gv=CQ+"Iterator",bF=Ef.set,Ps=Ef.getterFor(CQ),VC=Ef.getterFor(Gv),LF=lQ("fetch"),Ah=lQ("Request"),lf=lQ("Headers"),kv=Ah&&Ah.prototype,FF=lf&&lf.prototype,UF=Zd.TypeError,lV=Zd.encodeURIComponent,CV=String.fromCharCode,BV=vv("String","fromCodePoint"),uV=parseInt,Wy=gc("".charAt),zy=gc([].join),qC=gc([].push),OF=gc("".replace),QV=gc([].shift),xF=gc([].splice),YF=gc("".split),PF=gc("".slice),_v=gc(/./.exec),JF=/\+/g,dV=/^[0-9a-f]+$/i,HF=function(A,e){var o=PF(A,e,e+2);return _v(dV,o)?uV(o,16):NaN},hV=function(A){for(var e=0,o=128;o>0&&A&o;o>>=1)e++;return e},pV=function(A){var e=null;switch(A.length){case 1:e=A[0];break;case 2:e=(31&A[0])<<6|63&A[1];break;case 3:e=(15&A[0])<<12|(63&A[1])<<6|63&A[2];break;case 4:e=(7&A[0])<<18|(63&A[1])<<12|(63&A[2])<<6|63&A[3]}return e>1114111?null:e},VF=function(A){for(var e=(A=OF(A,JF," ")).length,o="",n=0;ne){o+="%",n++;continue}var I=HF(A,n+1);if(I!=I){o+=a,n++;continue}n+=2;var c=hV(I);if(c===0)a=CV(I);else{if(c===1||c>4){o+="�",n++;continue}for(var u=[I],d=1;de||Wy(A,n)!=="%");){var R=HF(A,n+1);if(R!=R){n+=3;break}if(R>191||R<128)break;qC(u,R),n+=2,d++}if(u.length!==c){o+="�";continue}var k=pV(u);k===null?o+="�":a=BV(k)}}o+=a,n++}return o},fV=/[!'()~]|%20/g,mV={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},DV=function(A){return mV[A]},qF=function(A){return OF(lV(A),fV,DV)},bv=oV(function(A,e){bF(this,{type:Gv,target:Ps(A).entries,index:0,kind:e})},CQ,function(){var A=VC(this),e=A.target,o=A.index++;if(!e||o>=e.length)return A.target=null,jy(void 0,!0);var n=e[o];switch(A.kind){case"keys":return jy(n.key,!1);case"values":return jy(n.value,!1)}return jy([n.key,n.value],!1)},!0),KF=function(A){this.entries=[],this.url=null,A!==void 0&&(GF(A)?this.parseObject(A):this.parseQuery(typeof A=="string"?Wy(A,0)==="?"?PF(A,1):A:Bg(A)))};KF.prototype={type:CQ,bindURL:function(A){this.url=A,this.update()},parseObject:function(A){var e,o,n,a,I,c,u,d=this.entries,R=IV(A);if(R)for(o=(e=_F(A,R)).next;!(n=To(o,e)).done;){if(I=(a=_F(sV(n.value))).next,(c=To(I,a)).done||(u=To(I,a)).done||!To(I,a).done)throw new UF("Expected sequence with length 2");qC(d,{key:Bg(c.value),value:Bg(u.value)})}else for(var k in A)rV(A,k)&&qC(d,{key:k,value:Bg(A[k])})},parseQuery:function(A){if(A)for(var e,o,n=this.entries,a=YF(A,"&"),I=0;I0?arguments[0]:void 0));Xd||(this.size=A.entries.length)},BQ=eh.prototype;if(tV(BQ,{append:function(A,e){var o=Ps(this);$d(arguments.length,2),qC(o.entries,{key:Bg(A),value:Bg(e)}),Xd||this.size++,o.updateURL()},delete:function(A){for(var e=Ps(this),o=$d(arguments.length,1),n=e.entries,a=Bg(A),I=o<2?void 0:arguments[1],c=I===void 0?I:Bg(I),u=0;uo.key?1:-1}),A.updateURL()},forEach:function(A){for(var e,o=Ps(this).entries,n=nV(A,arguments.length>1?arguments[1]:void 0),a=0;a1?jF(arguments[1]):{})}}),Tv(Ah)){var Fv=function(A){return TF(this,kv),new Ah(A,arguments.length>1?jF(arguments[1]):{})};kv.constructor=Fv,Fv.prototype=kv,EQ({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:Fv})}}var Ic,RV=wr,Uv=M,WF=BF,Ov=Q,zF=jc,Wc=Me,Zy=mn,zc=dI,MV=oc,xv=po,Yv=YH,zB=function(A){var e=fF(A),o=KH(this),n=arguments.length,a=n>1?arguments[1]:void 0,I=a!==void 0;I&&(a=qH(a,n>2?arguments[2]:void 0));var c,u,d,R,k,_,Z=WH(e),iA=0;if(!Z||this===DF&&yv(Z))for(c=jH(e),u=o?new this(c):DF(c);c>iA;iA++)_=I?a(e[iA],iA):e[iA],gf(u,iA,_);else for(u=o?new this:[],k=(R=Rv(e,Z)).next;!(d=sf(k,R)).done;iA++)_=I?mF(R,a,[d.value,iA],!0):d.value,gf(u,iA,_);return u.length=iA,u},XE=UA,Pv=dy.codeAt,wV=function(A){var e,o,n=[],a=wF(Pn(ZH(A),wv,"."),".");for(e=0;e?@[\\\]^|]/,LV=/[\0\t\n\r #/:<>?@[\\\]^|]/,FV=/^[\u0000-\u0020]+/,UV=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,OV=/[\t\n\r]/g,oh=function(A){var e,o,n,a;if(typeof A=="number"){for(e=[],o=0;o<4;o++)kV(e,A%256),A=jC(A/256);return Cf(e,".")}if(typeof A=="object"){for(e="",n=function(I){for(var c=null,u=1,d=null,R=0,k=0;k<8;k++)I[k]!==0?(R>u&&(c=d,u=R),d=null,R=0):(d===null&&(d=k),++R);return R>u?d:c}(A),o=0;o<8;o++)a&&A[o]===0||(a&&(a=!1),n===o?(e+=o?":":"::",a=!0):(e+=GV(A[o],16),o<7&&(e+=":")));return"["+e+"]"}return A},rh={},oU=Yv({},rh,{" ":1,'"':1,"<":1,">":1,"`":1}),jv=Yv({},oU,{"#":1,"?":1,"{":1,"}":1}),XB=Yv({},jv,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),Al=function(A,e){var o=Pv(A,0);return o>32&&o<127&&!xv(e,A)?A:encodeURIComponent(A)},WC={ftp:21,file:null,http:80,https:443,ws:80,wss:443},nh=function(A,e){var o;return A.length===2&&$E(Bf,Zc(A,0))&&((o=Zc(A,1))===":"||!e&&o==="|")},Wv=function(A){var e;return A.length>1&&nh(uQ(A,0,2))&&(A.length===2||(e=Zc(A,2))==="/"||e==="\\"||e==="?"||e==="#")},uf=function(A){return A==="."||tR(A)==="%2e"},rU=function(A){return(A=tR(A))===".."||A==="%2e."||A===".%2e"||A==="%2e%2e"},cc={},DI={},$B={},zl={},Au={},rR={},nU={},Qf={},nR={},aR={},sR={},gR={},IR={},cR={},zv={},ER={},ah={},Zl={},df={},yI={},ug={},lR=function(A,e,o){var n,a,I,c=KC(A);if(e){if(a=this.parse(c))throw new Hv(a);this.searchParams=null}else{if(o!==void 0&&(n=new lR(o,!0)),a=this.parse(c,null,n))throw new Hv(a);(I=TV(new NV)).bindURL(this),this.searchParams=I}};lR.prototype={type:"URL",parse:function(A,e,o){var n,a,I,c,u=this,d=e||cc,R=0,k="",_=!1,Z=!1,iA=!1;for(A=KC(A),e||(u.scheme="",u.username="",u.password="",u.host=null,u.port=null,u.path=[],u.query=null,u.fragment=null,u.cannotBeABaseURL=!1,A=AR(A,FV,""),A=AR(A,UV,"$1")),A=AR(A,OV,""),n=zB(A);R<=n.length;){switch(a=n[R],d){case cc:if(!a||!$E(Bf,a)){if(e)return qv;d=$B;continue}k+=tR(a),d=DI;break;case DI:if(a&&($E(_V,a)||a==="+"||a==="-"||a==="."))k+=tR(a);else{if(a!==":"){if(e)return qv;k="",d=$B,R=0;continue}if(e&&(u.isSpecial()!==xv(WC,k)||k==="file"&&(u.includesCredentials()||u.port!==null)||u.scheme==="file"&&!u.host))return;if(u.scheme=k,e)return void(u.isSpecial()&&WC[u.scheme]===u.port&&(u.port=null));k="",u.scheme==="file"?d=cR:u.isSpecial()&&o&&o.scheme===u.scheme?d=zl:u.isSpecial()?d=Qf:n[R+1]==="/"?(d=Au,R++):(u.cannotBeABaseURL=!0,ih(u.path,""),d=df)}break;case $B:if(!o||o.cannotBeABaseURL&&a!=="#")return qv;if(o.cannotBeABaseURL&&a==="#"){u.scheme=o.scheme,u.path=XE(o.path),u.query=o.query,u.fragment="",u.cannotBeABaseURL=!0,d=ug;break}d=o.scheme==="file"?cR:rR;continue;case zl:if(a!=="/"||n[R+1]!=="/"){d=rR;continue}d=nR,R++;break;case Au:if(a==="/"){d=aR;break}d=Zl;continue;case rR:if(u.scheme=o.scheme,a===Ic)u.username=o.username,u.password=o.password,u.host=o.host,u.port=o.port,u.path=XE(o.path),u.query=o.query;else if(a==="/"||a==="\\"&&u.isSpecial())d=nU;else if(a==="?")u.username=o.username,u.password=o.password,u.host=o.host,u.port=o.port,u.path=XE(o.path),u.query="",d=yI;else{if(a!=="#"){u.username=o.username,u.password=o.password,u.host=o.host,u.port=o.port,u.path=XE(o.path),u.path.length--,d=Zl;continue}u.username=o.username,u.password=o.password,u.host=o.host,u.port=o.port,u.path=XE(o.path),u.query=o.query,u.fragment="",d=ug}break;case nU:if(!u.isSpecial()||a!=="/"&&a!=="\\"){if(a!=="/"){u.username=o.username,u.password=o.password,u.host=o.host,u.port=o.port,d=Zl;continue}d=aR}else d=nR;break;case Qf:if(d=nR,a!=="/"||Zc(k,R+1)!=="/")continue;R++;break;case nR:if(a!=="/"&&a!=="\\"){d=aR;continue}break;case aR:if(a==="@"){_&&(k="%40"+k),_=!0,I=zB(k);for(var cA=0;cA65535)return iR;u.port=u.isSpecial()&&Ie===WC[u.scheme]?null:Ie,k=""}if(e)return;d=ah;continue}return iR}k+=a;break;case cR:if(u.scheme="file",a==="/"||a==="\\")d=zv;else{if(!o||o.scheme!=="file"){d=Zl;continue}switch(a){case Ic:u.host=o.host,u.path=XE(o.path),u.query=o.query;break;case"?":u.host=o.host,u.path=XE(o.path),u.query="",d=yI;break;case"#":u.host=o.host,u.path=XE(o.path),u.query=o.query,u.fragment="",d=ug;break;default:Wv(Cf(XE(n,R),""))||(u.host=o.host,u.path=XE(o.path),u.shortenPath()),d=Zl;continue}}break;case zv:if(a==="/"||a==="\\"){d=ER;break}o&&o.scheme==="file"&&!Wv(Cf(XE(n,R),""))&&(nh(o.path[0],!0)?ih(u.path,o.path[0]):u.host=o.host),d=Zl;continue;case ER:if(a===Ic||a==="/"||a==="\\"||a==="?"||a==="#"){if(!e&&nh(k))d=Zl;else if(k===""){if(u.host="",e)return;d=ah}else{if(c=u.parseHost(k))return c;if(u.host==="localhost"&&(u.host=""),e)return;k="",d=ah}continue}k+=a;break;case ah:if(u.isSpecial()){if(d=Zl,a!=="/"&&a!=="\\")continue}else if(e||a!=="?")if(e||a!=="#"){if(a!==Ic&&(d=Zl,a!=="/"))continue}else u.fragment="",d=ug;else u.query="",d=yI;break;case Zl:if(a===Ic||a==="/"||a==="\\"&&u.isSpecial()||!e&&(a==="?"||a==="#")){if(rU(k)?(u.shortenPath(),a==="/"||a==="\\"&&u.isSpecial()||ih(u.path,"")):uf(k)?a==="/"||a==="\\"&&u.isSpecial()||ih(u.path,""):(u.scheme==="file"&&!u.path.length&&nh(k)&&(u.host&&(u.host=""),k=Zc(k,0)+":"),ih(u.path,k)),k="",u.scheme==="file"&&(a===Ic||a==="?"||a==="#"))for(;u.path.length>1&&u.path[0]==="";)eR(u.path);a==="?"?(u.query="",d=yI):a==="#"&&(u.fragment="",d=ug)}else k+=Al(a,jv);break;case df:a==="?"?(u.query="",d=yI):a==="#"?(u.fragment="",d=ug):a!==Ic&&(u.path[0]+=Al(a,rh));break;case yI:e||a!=="#"?a!==Ic&&(a==="'"&&u.isSpecial()?u.query+="%27":u.query+=a==="#"?"%23":Al(a,rh)):(u.fragment="",d=ug);break;case ug:a!==Ic&&(u.fragment+=Al(a,oU))}R++}},parseHost:function(A){var e,o,n;if(Zc(A,0)==="["){if(Zc(A,A.length-1)!=="]"||(e=function(a){var I,c,u,d,R,k,_,Z=[0,0,0,0,0,0,0,0],iA=0,cA=null,TA=0,JA=function(){return Zc(a,TA)};if(JA()===":"){if(Zc(a,1)!==":")return;TA+=2,cA=++iA}for(;JA();){if(iA===8)return;if(JA()!==":"){for(I=c=0;c<4&&$E(tU,JA());)I=16*I+$y(JA(),16),TA++,c++;if(JA()==="."){if(c===0||(TA-=c,iA>6))return;for(u=0;JA();){if(d=null,u>0){if(!(JA()==="."&&u<4))return;TA++}if(!$E(Kv,JA()))return;for(;$E(Kv,JA());){if(R=$y(JA(),10),d===null)d=R;else{if(d===0)return;d=10*d+R}if(d>255)return;TA++}Z[iA]=256*Z[iA]+d,++u!==2&&u!==4||iA++}if(u!==4)return;break}if(JA()===":"){if(TA++,!JA())return}else if(JA())return;Z[iA++]=I}else{if(cA!==null)return;TA++,cA=++iA}}if(cA!==null)for(k=iA-cA,iA=7;iA!==0&&k>0;)_=Z[iA],Z[iA--]=Z[cA+k-1],Z[cA+--k]=_;else if(iA!==8)return;return Z}(uQ(A,1,-1)),!e))return ZB;this.host=e}else if(this.isSpecial()){if(A=wV(A),$E(iU,A)||(e=function(a){var I,c,u,d,R,k,_,Z=Vv(a,".");if(Z.length&&Z[Z.length-1]===""&&Z.length--,(I=Z.length)>4)return a;for(c=[],u=0;u1&&Zc(d,0)==="0"&&(R=$E(oR,d)?16:8,d=uQ(d,R===8?1:2)),d==="")k=0;else{if(!$E(R===10?eU:R===8?bV:tU,d))return a;k=$y(d,R)}ih(c,k)}for(u=0;u=$F(256,5-I))return null}else if(k>255)return null;for(_=AU(c),u=0;u1?arguments[1]:void 0,n=vV(e,new lR(A,!1,o));Uv||(e.href=n.serialize(),e.origin=n.getOrigin(),e.protocol=n.getProtocol(),e.username=n.getUsername(),e.password=n.getPassword(),e.host=n.getHost(),e.hostname=n.getHostname(),e.port=n.getPort(),e.pathname=n.getPathname(),e.search=n.getSearch(),e.searchParams=n.getSearchParams(),e.hash=n.getHash())},Qg=zC.prototype,dg=function(A,e){return{get:function(){return Xy(this)[A]()},set:e&&function(o){return Xy(this)[e](o)},configurable:!0,enumerable:!0}};if(Uv&&(zc(Qg,"href",dg("serialize","setHref")),zc(Qg,"origin",dg("getOrigin")),zc(Qg,"protocol",dg("getProtocol","setProtocol")),zc(Qg,"username",dg("getUsername","setUsername")),zc(Qg,"password",dg("getPassword","setPassword")),zc(Qg,"host",dg("getHost","setHost")),zc(Qg,"hostname",dg("getHostname","setHostname")),zc(Qg,"port",dg("getPort","setPort")),zc(Qg,"pathname",dg("getPathname","setPathname")),zc(Qg,"search",dg("getSearch","setSearch")),zc(Qg,"searchParams",dg("getSearchParams")),zc(Qg,"hash",dg("getHash","setHash"))),Zy(Qg,"toJSON",function(){return Xy(this).serialize()},{enumerable:!0}),Zy(Qg,"toString",function(){return Xy(this).serialize()},{enumerable:!0}),th){var aU=th.createObjectURL,CR=th.revokeObjectURL;aU&&Zy(zC,"createObjectURL",zF(aU,th)),CR&&Zy(zC,"revokeObjectURL",zF(CR,th))}SV(zC,"URL"),RV({global:!0,constructor:!0,forced:!WF,sham:!Uv},{URL:zC});var sU=z;wr({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return sU(URL.prototype.toString,this)}});let gU=!0,BR=!0;function hf(A,e,o){const n=A.match(e);return n&&n.length>=o&&parseFloat(n[o],10)}function eu(A,e,o){if(!A.RTCPeerConnection)return;const n=A.RTCPeerConnection.prototype,a=n.addEventListener;n.addEventListener=function(c,u){if(c!==e)return a.apply(this,arguments);const d=R=>{const k=o(R);k&&(u.handleEvent?u.handleEvent(k):u(k))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(u,d),a.apply(this,[c,d])};const I=n.removeEventListener;n.removeEventListener=function(c,u){if(c!==e||!this._eventMap||!this._eventMap[e])return I.apply(this,arguments);if(!this._eventMap[e].has(u))return I.apply(this,arguments);const d=this._eventMap[e].get(u);return this._eventMap[e].delete(u),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,I.apply(this,[c,d])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(c){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),c&&this.addEventListener(e,this["_on"+e]=c)},enumerable:!0,configurable:!0})}function IU(A){return typeof A!="boolean"?new Error("Argument type: "+typeof A+". Please use a boolean."):(gU=A,A?"adapter.js logging disabled":"adapter.js logging enabled")}function xV(A){return typeof A!="boolean"?new Error("Argument type: "+typeof A+". Please use a boolean."):(BR=!A,"adapter.js deprecation warnings "+(A?"disabled":"enabled"))}function uR(){if(typeof window=="object"){if(gU)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function pf(A,e){BR&&console.warn(A+" is deprecated, please use "+e+" instead.")}function Zv(A){return Object.prototype.toString.call(A)==="[object Object]"}function Xv(A){return Zv(A)?Object.keys(A).reduce(function(e,o){const n=Zv(A[o]),a=n?Xv(A[o]):A[o],I=n&&!Object.keys(a).length;return a===void 0||I?e:Object.assign(e,{[o]:a})},{}):A}function $v(A,e,o){e&&!o.has(e.id)&&(o.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?$v(A,A.get(e[n]),o):n.endsWith("Ids")&&e[n].forEach(a=>{$v(A,A.get(a),o)})}))}function cU(A,e,o){const n=o?"outbound-rtp":"inbound-rtp",a=new Map;if(e===null)return a;const I=[];return A.forEach(c=>{c.type==="track"&&c.trackIdentifier===e.id&&I.push(c)}),I.forEach(c=>{A.forEach(u=>{u.type===n&&u.trackId===c.id&&$v(A,u,a)})}),a}const AN=uR;function EU(A,e){const o=A&&A.navigator;if(!o.mediaDevices)return;const n=function(c){if(typeof c!="object"||c.mandatory||c.optional)return c;const u={};return Object.keys(c).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const R=typeof c[d]=="object"?c[d]:{ideal:c[d]};R.exact!==void 0&&typeof R.exact=="number"&&(R.min=R.max=R.exact);const k=function(_,Z){return _?_+Z.charAt(0).toUpperCase()+Z.slice(1):Z==="deviceId"?"sourceId":Z};if(R.ideal!==void 0){u.optional=u.optional||[];let _={};typeof R.ideal=="number"?(_[k("min",d)]=R.ideal,u.optional.push(_),_={},_[k("max",d)]=R.ideal,u.optional.push(_)):(_[k("",d)]=R.ideal,u.optional.push(_))}R.exact!==void 0&&typeof R.exact!="number"?(u.mandatory=u.mandatory||{},u.mandatory[k("",d)]=R.exact):["min","max"].forEach(_=>{R[_]!==void 0&&(u.mandatory=u.mandatory||{},u.mandatory[k(_,d)]=R[_])})}),c.advanced&&(u.optional=(u.optional||[]).concat(c.advanced)),u},a=function(c,u){if(e.version>=61)return u(c);if((c=JSON.parse(JSON.stringify(c)))&&typeof c.audio=="object"){const d=function(R,k,_){k in R&&!(_ in R)&&(R[_]=R[k],delete R[k])};d((c=JSON.parse(JSON.stringify(c))).audio,"autoGainControl","googAutoGainControl"),d(c.audio,"noiseSuppression","googNoiseSuppression"),c.audio=n(c.audio)}if(c&&typeof c.video=="object"){let d=c.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const R=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&(!o.mediaDevices.getSupportedConstraints||!o.mediaDevices.getSupportedConstraints().facingMode||R)){let k;if(delete c.video.facingMode,d.exact==="environment"||d.ideal==="environment"?k=["back","rear"]:d.exact!=="user"&&d.ideal!=="user"||(k=["front"]),k)return o.mediaDevices.enumerateDevices().then(_=>{_=_.filter(iA=>iA.kind==="videoinput");let Z=_.find(iA=>k.some(cA=>iA.label.toLowerCase().includes(cA)));return!Z&&_.length&&k.includes("back")&&(Z=_[_.length-1]),Z&&(c.video.deviceId=d.exact?{exact:Z.deviceId}:{ideal:Z.deviceId}),c.video=n(c.video),AN("chrome: "+JSON.stringify(c)),u(c)})}c.video=n(c.video)}return AN("chrome: "+JSON.stringify(c)),u(c)},I=function(c){return e.version>=64?c:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[c.name]||c.name,message:c.message,constraint:c.constraint||c.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(o.getUserMedia=function(c,u,d){a(c,R=>{o.webkitGetUserMedia(R,u,k=>{d&&d(I(k))})})}.bind(o),o.mediaDevices.getUserMedia){const c=o.mediaDevices.getUserMedia.bind(o.mediaDevices);o.mediaDevices.getUserMedia=function(u){return a(u,d=>c(d).then(R=>{if(d.audio&&!R.getAudioTracks().length||d.video&&!R.getVideoTracks().length)throw R.getTracks().forEach(k=>{k.stop()}),new DOMException("","NotFoundError");return R},R=>Promise.reject(I(R))))}}}function lU(A){A.MediaStream=A.MediaStream||A.webkitMediaStream}function CU(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 e=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=o=>{o.stream.addEventListener("addtrack",n=>{let a;a=A.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(c=>c.track&&c.track.id===n.track.id):{track:n.track};const I=new Event("track");I.track=n.track,I.receiver=a,I.transceiver={receiver:a},I.streams=[o.stream],this.dispatchEvent(I)}),o.stream.getTracks().forEach(n=>{let a;a=A.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(c=>c.track&&c.track.id===n.id):{track:n};const I=new Event("track");I.track=n,I.receiver=a,I.transceiver={receiver:a},I.streams=[o.stream],this.dispatchEvent(I)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else eu(A,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function eN(A){if(typeof A=="object"&&A.RTCPeerConnection&&!("getSenders"in A.RTCPeerConnection.prototype)&&"createDTMFSender"in A.RTCPeerConnection.prototype){const e=function(a,I){return{track:I,get dtmf(){return this._dtmf===void 0&&(I.kind==="audio"?this._dtmf=a.createDTMFSender(I):this._dtmf=null),this._dtmf},_pc:a}};if(!A.RTCPeerConnection.prototype.getSenders){A.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const a=A.RTCPeerConnection.prototype.addTrack;A.RTCPeerConnection.prototype.addTrack=function(c,u){let d=a.apply(this,arguments);return d||(d=e(this,c),this._senders.push(d)),d};const I=A.RTCPeerConnection.prototype.removeTrack;A.RTCPeerConnection.prototype.removeTrack=function(c){I.apply(this,arguments);const u=this._senders.indexOf(c);u!==-1&&this._senders.splice(u,1)}}const o=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(a){this._senders=this._senders||[],o.apply(this,[a]),a.getTracks().forEach(I=>{this._senders.push(e(this,I))})};const n=A.RTCPeerConnection.prototype.removeStream;A.RTCPeerConnection.prototype.removeStream=function(a){this._senders=this._senders||[],n.apply(this,[a]),a.getTracks().forEach(I=>{const c=this._senders.find(u=>u.track===I);c&&this._senders.splice(this._senders.indexOf(c),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 e=A.RTCPeerConnection.prototype.getSenders;A.RTCPeerConnection.prototype.getSenders=function(){const o=e.apply(this,[]);return o.forEach(n=>n._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 BU(A){if(!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){const[o,n,a]=arguments;if(arguments.length>0&&typeof o=="function")return e.apply(this,arguments);if(e.length===0&&(arguments.length===0||typeof o!="function"))return e.apply(this,[]);const I=function(u){const d={};return u.result().forEach(R=>{const k={id:R.id,timestamp:R.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[R.type]||R.type};R.names().forEach(_=>{k[_]=R.stat(_)}),d[k.id]=k}),d},c=function(u){return new Map(Object.keys(u).map(d=>[d,u[d]]))};if(arguments.length>=2){const u=function(d){n(c(I(d)))};return e.apply(this,[u,o])}return new Promise((u,d)=>{e.apply(this,[function(R){u(c(I(R)))},d])}).then(n,a)}}function tN(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 a=o.apply(this,[]);return a.forEach(I=>I._pc=this),a});const n=A.RTCPeerConnection.prototype.addTrack;n&&(A.RTCPeerConnection.prototype.addTrack=function(){const a=n.apply(this,arguments);return a._pc=this,a}),A.RTCRtpSender.prototype.getStats=function(){const a=this;return this._pc.getStats().then(I=>cU(I,a.track,!0))}}if(!("getStats"in A.RTCRtpReceiver.prototype)){const o=A.RTCPeerConnection.prototype.getReceivers;o&&(A.RTCPeerConnection.prototype.getReceivers=function(){const n=o.apply(this,[]);return n.forEach(a=>a._pc=this),n}),eu(A,"track",n=>(n.receiver._pc=n.srcElement,n)),A.RTCRtpReceiver.prototype.getStats=function(){const n=this;return this._pc.getStats().then(a=>cU(a,n.track,!1))}}if(!("getStats"in A.RTCRtpSender.prototype)||!("getStats"in A.RTCRtpReceiver.prototype))return;const e=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof A.MediaStreamTrack){const o=arguments[0];let n,a,I;return this.getSenders().forEach(c=>{c.track===o&&(n?I=!0:n=c)}),this.getReceivers().forEach(c=>(c.track===o&&(a?I=!0:a=c),c.track===o)),I||n&&a?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):n?n.getStats():a?a.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function uU(A){A.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(I=>this._shimmedLocalStreams[I][0])};const e=A.RTCPeerConnection.prototype.addTrack;A.RTCPeerConnection.prototype.addTrack=function(I,c){if(!c)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const u=e.apply(this,arguments);return this._shimmedLocalStreams[c.id]?this._shimmedLocalStreams[c.id].indexOf(u)===-1&&this._shimmedLocalStreams[c.id].push(u):this._shimmedLocalStreams[c.id]=[c,u],u};const o=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(I){this._shimmedLocalStreams=this._shimmedLocalStreams||{},I.getTracks().forEach(d=>{if(this.getSenders().find(R=>R.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const c=this.getSenders();o.apply(this,arguments);const u=this.getSenders().filter(d=>c.indexOf(d)===-1);this._shimmedLocalStreams[I.id]=[I].concat(u)};const n=A.RTCPeerConnection.prototype.removeStream;A.RTCPeerConnection.prototype.removeStream=function(I){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[I.id],n.apply(this,arguments)};const a=A.RTCPeerConnection.prototype.removeTrack;A.RTCPeerConnection.prototype.removeTrack=function(I){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},I&&Object.keys(this._shimmedLocalStreams).forEach(c=>{const u=this._shimmedLocalStreams[c].indexOf(I);u!==-1&&this._shimmedLocalStreams[c].splice(u,1),this._shimmedLocalStreams[c].length===1&&delete this._shimmedLocalStreams[c]}),a.apply(this,arguments)}}function QU(A,e){if(!A.RTCPeerConnection)return;if(A.RTCPeerConnection.prototype.addTrack&&e.version>=65)return uU(A);const o=A.RTCPeerConnection.prototype.getLocalStreams;A.RTCPeerConnection.prototype.getLocalStreams=function(){const d=o.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(R=>this._reverseStreams[R.id])};const n=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(R=>{if(this.getSenders().find(k=>k.track===R))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const R=new A.MediaStream(d.getTracks());this._streams[d.id]=R,this._reverseStreams[R.id]=d,d=R}n.apply(this,[d])};const a=A.RTCPeerConnection.prototype.removeStream;function I(d,R){let k=R.sdp;return Object.keys(d._reverseStreams||[]).forEach(_=>{const Z=d._reverseStreams[_],iA=d._streams[Z.id];k=k.replace(new RegExp(iA.id,"g"),Z.id)}),new RTCSessionDescription({type:R.type,sdp:k})}A.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},a.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},A.RTCPeerConnection.prototype.addTrack=function(d,R){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const k=[].slice.call(arguments,1);if(k.length!==1||!k[0].getTracks().find(Z=>Z===d))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(Z=>Z.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const _=this._streams[R.id];if(_)_.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const Z=new A.MediaStream([d]);this._streams[R.id]=Z,this._reverseStreams[Z.id]=R,this.addStream(Z)}return this.getSenders().find(Z=>Z.track===d)},["createOffer","createAnswer"].forEach(function(d){const R=A.RTCPeerConnection.prototype[d],k={[d](){const _=arguments;return arguments.length&&typeof arguments[0]=="function"?R.apply(this,[Z=>{const iA=I(this,Z);_[0].apply(null,[iA])},Z=>{_[1]&&_[1].apply(null,Z)},arguments[2]]):R.apply(this,arguments).then(Z=>I(this,Z))}};A.RTCPeerConnection.prototype[d]=k[d]});const c=A.RTCPeerConnection.prototype.setLocalDescription;A.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(d,R){let k=R.sdp;return Object.keys(d._reverseStreams||[]).forEach(_=>{const Z=d._reverseStreams[_],iA=d._streams[Z.id];k=k.replace(new RegExp(Z.id,"g"),iA.id)}),new RTCSessionDescription({type:R.type,sdp:k})}(this,arguments[0]),c.apply(this,arguments)):c.apply(this,arguments)};const u=Object.getOwnPropertyDescriptor(A.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(A.RTCPeerConnection.prototype,"localDescription",{get(){const d=u.get.apply(this);return d.type===""?d:I(this,d)}}),A.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(d._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let R;this._streams=this._streams||{},Object.keys(this._streams).forEach(k=>{this._streams[k].getTracks().find(_=>d.track===_)&&(R=this._streams[k])}),R&&(R.getTracks().length===1?this.removeStream(this._reverseStreams[R.id]):R.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function ff(A,e){!A.RTCPeerConnection&&A.webkitRTCPeerConnection&&(A.RTCPeerConnection=A.webkitRTCPeerConnection),A.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(o){const n=A.RTCPeerConnection.prototype[o],a={[o](){return arguments[0]=new(o==="addIceCandidate"?A.RTCIceCandidate:A.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};A.RTCPeerConnection.prototype[o]=a[o]})}function dU(A,e){eu(A,"negotiationneeded",o=>{const n=o.target;if(!(e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")||n.signalingState==="stable")return o})}var iN=Object.freeze({__proto__:null,shimMediaStream:lU,shimOnTrack:CU,shimGetSendersWithDtmf:eN,shimGetStats:BU,shimSenderReceiverGetStats:tN,shimAddTrackRemoveTrackWithNative:uU,shimAddTrackRemoveTrack:QU,shimPeerConnection:ff,fixNegotiationNeeded:dU,shimGetUserMedia:EU,shimGetDisplayMedia:function(A,e){A.navigator.mediaDevices&&"getDisplayMedia"in A.navigator.mediaDevices||A.navigator.mediaDevices&&(typeof e=="function"?A.navigator.mediaDevices.getDisplayMedia=function(o){return e(o).then(n=>{const a=o.video&&o.video.width,I=o.video&&o.video.height,c=o.video&&o.video.frameRate;return o.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:n,maxFrameRate:c||3}},a&&(o.video.mandatory.maxWidth=a),I&&(o.video.mandatory.maxHeight=I),A.navigator.mediaDevices.getUserMedia(o)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function hU(A,e){const o=A&&A.navigator,n=A&&A.MediaStreamTrack;if(o.getUserMedia=function(a,I,c){pf("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),o.mediaDevices.getUserMedia(a).then(I,c)},!(e.version>55&&"autoGainControl"in o.mediaDevices.getSupportedConstraints())){const a=function(c,u,d){u in c&&!(d in c)&&(c[d]=c[u],delete c[u])},I=o.mediaDevices.getUserMedia.bind(o.mediaDevices);if(o.mediaDevices.getUserMedia=function(c){return typeof c=="object"&&typeof c.audio=="object"&&(c=JSON.parse(JSON.stringify(c)),a(c.audio,"autoGainControl","mozAutoGainControl"),a(c.audio,"noiseSuppression","mozNoiseSuppression")),I(c)},n&&n.prototype.getSettings){const c=n.prototype.getSettings;n.prototype.getSettings=function(){const u=c.apply(this,arguments);return a(u,"mozAutoGainControl","autoGainControl"),a(u,"mozNoiseSuppression","noiseSuppression"),u}}if(n&&n.prototype.applyConstraints){const c=n.prototype.applyConstraints;n.prototype.applyConstraints=function(u){return this.kind==="audio"&&typeof u=="object"&&(u=JSON.parse(JSON.stringify(u)),a(u,"autoGainControl","mozAutoGainControl"),a(u,"noiseSuppression","mozNoiseSuppression")),c.apply(this,[u])}}}}function pU(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 QR(A,e){if(typeof A!="object"||!A.RTCPeerConnection&&!A.mozRTCPeerConnection)return;!A.RTCPeerConnection&&A.mozRTCPeerConnection&&(A.RTCPeerConnection=A.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(a){const I=A.RTCPeerConnection.prototype[a],c={[a](){return arguments[0]=new(a==="addIceCandidate"?A.RTCIceCandidate:A.RTCSessionDescription)(arguments[0]),I.apply(this,arguments)}};A.RTCPeerConnection.prototype[a]=c[a]});const o={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){const[a,I,c]=arguments;return n.apply(this,[a||null]).then(u=>{if(e.version<53&&!I)try{u.forEach(d=>{d.type=o[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;u.forEach((R,k)=>{u.set(k,Object.assign({},R,{type:o[R.type]||R.type}))})}return u}).then(I,c)}}function fU(A){if(typeof A!="object"||!A.RTCPeerConnection||!A.RTCRtpSender||A.RTCRtpSender&&"getStats"in A.RTCRtpSender.prototype)return;const e=A.RTCPeerConnection.prototype.getSenders;e&&(A.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(a=>a._pc=this),n});const o=A.RTCPeerConnection.prototype.addTrack;o&&(A.RTCPeerConnection.prototype.addTrack=function(){const n=o.apply(this,arguments);return n._pc=this,n}),A.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function oN(A){if(typeof A!="object"||!A.RTCPeerConnection||!A.RTCRtpSender||A.RTCRtpSender&&"getStats"in A.RTCRtpReceiver.prototype)return;const e=A.RTCPeerConnection.prototype.getReceivers;e&&(A.RTCPeerConnection.prototype.getReceivers=function(){const o=e.apply(this,[]);return o.forEach(n=>n._pc=this),o}),eu(A,"track",o=>(o.receiver._pc=o.srcElement,o)),A.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function mU(A){A.RTCPeerConnection&&!("removeStream"in A.RTCPeerConnection.prototype)&&(A.RTCPeerConnection.prototype.removeStream=function(e){pf("removeStream","removeTrack"),this.getSenders().forEach(o=>{o.track&&e.getTracks().includes(o.track)&&this.removeTrack(o)})})}function rN(A){A.DataChannel&&!A.RTCDataChannel&&(A.RTCDataChannel=A.DataChannel)}function DU(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype.addTransceiver;e&&(A.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let o=arguments[1]&&arguments[1].sendEncodings;o===void 0&&(o=[]),o=[...o];const n=o.length>0;n&&o.forEach(I=>{if("rid"in I&&!/^[a-z0-9]{0,16}$/i.test(I.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in I&&!(parseFloat(I.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in I&&!(parseFloat(I.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const a=e.apply(this,arguments);if(n){const{sender:I}=a,c=I.getParameters();(!("encodings"in c)||c.encodings.length===1&&Object.keys(c.encodings[0]).length===0)&&(c.encodings=o,I.sendEncodings=o,this.setParametersPromises.push(I.setParameters(c).then(()=>{delete I.sendEncodings}).catch(()=>{delete I.sendEncodings})))}return a})}function yU(A){if(typeof A!="object"||!A.RTCRtpSender)return;const e=A.RTCRtpSender.prototype.getParameters;e&&(A.RTCRtpSender.prototype.getParameters=function(){const o=e.apply(this,arguments);return"encodings"in o||(o.encodings=[].concat(this.sendEncodings||[{}])),o})}function RU(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype.createOffer;A.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function MU(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype.createAnswer;A.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var wU=Object.freeze({__proto__:null,shimOnTrack:pU,shimPeerConnection:QR,shimSenderGetStats:fU,shimReceiverGetStats:oN,shimRemoveStream:mU,shimRTCDataChannel:rN,shimAddTransceiver:DU,shimGetParameters:yU,shimCreateOffer:RU,shimCreateAnswer:MU,shimGetUserMedia:hU,shimGetDisplayMedia:function(A,e){A.navigator.mediaDevices&&"getDisplayMedia"in A.navigator.mediaDevices||A.navigator.mediaDevices&&(A.navigator.mediaDevices.getDisplayMedia=function(o){if(!o||!o.video){const n=new DOMException("getDisplayMedia without video constraints is undefined");return n.name="NotFoundError",n.code=8,Promise.reject(n)}return o.video===!0?o.video={mediaSource:e}:o.video.mediaSource=e,A.navigator.mediaDevices.getUserMedia(o)})}});function SU(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 e=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(n=>e.call(this,n,o)),o.getVideoTracks().forEach(n=>e.call(this,n,o))},A.RTCPeerConnection.prototype.addTrack=function(o,...n){return n&&n.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in A.RTCPeerConnection.prototype||(A.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const o=this._localStreams.indexOf(e);if(o===-1)return;this._localStreams.splice(o,1);const n=e.getTracks();this.getSenders().forEach(a=>{n.includes(a.track)&&this.removeTrack(a)})})}}function vU(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=n=>{n.streams.forEach(a=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(a))return;this._remoteStreams.push(a);const I=new Event("addstream");I.stream=a,this.dispatchEvent(I)})})}});const e=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(){const o=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(n){n.streams.forEach(a=>{if(o._remoteStreams||(o._remoteStreams=[]),o._remoteStreams.indexOf(a)>=0)return;o._remoteStreams.push(a);const I=new Event("addstream");I.stream=a,o.dispatchEvent(I)})}),e.apply(o,arguments)}}}function nN(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype,o=e.createOffer,n=e.createAnswer,a=e.setLocalDescription,I=e.setRemoteDescription,c=e.addIceCandidate;e.createOffer=function(d,R){const k=arguments.length>=2?arguments[2]:arguments[0],_=o.apply(this,[k]);return R?(_.then(d,R),Promise.resolve()):_},e.createAnswer=function(d,R){const k=arguments.length>=2?arguments[2]:arguments[0],_=n.apply(this,[k]);return R?(_.then(d,R),Promise.resolve()):_};let u=function(d,R,k){const _=a.apply(this,[d]);return k?(_.then(R,k),Promise.resolve()):_};e.setLocalDescription=u,u=function(d,R,k){const _=I.apply(this,[d]);return k?(_.then(R,k),Promise.resolve()):_},e.setRemoteDescription=u,u=function(d,R,k){const _=c.apply(this,[d]);return k?(_.then(R,k),Promise.resolve()):_},e.addIceCandidate=u}function aN(A){const e=A&&A.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const o=e.mediaDevices,n=o.getUserMedia.bind(o);e.mediaDevices.getUserMedia=a=>n(NU(a))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(o,n,a){e.mediaDevices.getUserMedia(o).then(n,a)}.bind(e))}function NU(A){return A&&A.video!==void 0?Object.assign({},A,{video:Xv(A.video)}):A}function TU(A){if(!A.RTCPeerConnection)return;const e=A.RTCPeerConnection;A.RTCPeerConnection=function(o,n){if(o&&o.iceServers){const a=[];for(let I=0;Ie.generateCertificate})}function GU(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 dR(A){const e=A.RTCPeerConnection.prototype.createOffer;A.RTCPeerConnection.prototype.createOffer=function(o){if(o){o.offerToReceiveAudio!==void 0&&(o.offerToReceiveAudio=!!o.offerToReceiveAudio);const n=this.getTransceivers().find(I=>I.receiver.track.kind==="audio");o.offerToReceiveAudio===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):o.offerToReceiveAudio!==!0||n||this.addTransceiver("audio",{direction:"recvonly"}),o.offerToReceiveVideo!==void 0&&(o.offerToReceiveVideo=!!o.offerToReceiveVideo);const a=this.getTransceivers().find(I=>I.receiver.track.kind==="video");o.offerToReceiveVideo===!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.offerToReceiveVideo!==!0||a||this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function kU(A){typeof A!="object"||A.AudioContext||(A.AudioContext=A.webkitAudioContext)}var _U=Object.freeze({__proto__:null,shimLocalStreamsAPI:SU,shimRemoteStreamsAPI:vU,shimCallbacksAPI:nN,shimGetUserMedia:aN,shimConstraints:NU,shimRTCIceServerUrls:TU,shimTrackEventTransceiver:GU,shimCreateOfferLegacy:dR,shimAudioContext:kU}),bU={exports:{}};(function(A){const e={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};e.localCName=e.generateIdentifier(),e.splitLines=function(o){return o.trim().split(` +`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(h)),this._worker.postMessage({type:gn,url:E})}send(E){var h,D;try{(h=this._worker)===null||h===void 0||h.postMessage({type:Yo,data:E})}catch(N){(D=this._onSendFail)===null||D===void 0||D.call(this,N)}}bindSocketHandlers(E){const{onOpen:h,onMessage:D,onClose:N,onError:O,onSendFail:Y}=E;if(this._worker){const j={[So]:h,[ao]:D,[lE]:N,[Ta]:O,[po]:Y};this._onSendFail=Y,this._worker.onmessage=IA=>{var BA;const{type:mA}=IA?.data||{};typeof j[mA]=="function"&&((BA=j[mA])===null||BA===void 0||BA.call(j,IA?.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:Tg}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class Mc{}var Qr,Fo=new class{constructor(){this._store=new Map}get(C){return this._store.get(C)}getStorage(C){return Xi?ai?my.getStorageSync({key:C}).data:Ji.getStorageSync(C):this._canUseLocalStorage()?localStorage.getItem(C):{}}set(C,E){const h=this._store.get(C)||{};E instanceof Map?this._store.set(C,E):this._store.set(C,Object.assign(Object.assign({},h),E))}setStorage(C,E){Xi?ai?my.setStorageSync({key:C,data:JSON.stringify(E)}):Ji.setStorageSync(C,JSON.stringify(E)):this._canUseLocalStorage()&&localStorage.setItem(C,JSON.stringify(E))}clear(C){typeof C=="string"?this._store.set(C,{}):this._store.clear()}clearLocalStorage(C){this._canUseLocalStorage()&&(typeof C=="string"?localStorage.setItem(C,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return typeof window<"u"&&navigator&&navigator.cookieEnabled&&localStorage}};class $s{connectSocket(E){return this._socket=Ji.connectSocket({url:E,header:{"content-type":"application/json"},multiple:!0,complete:()=>{}}),this._socket}send(E){var h;(h=this._socket)===null||h===void 0||h.send({data:E,fail:this._onSendFail})}bindSocketHandlers(E){const{onOpen:h,onMessage:D,onClose:N,onError:O,onSendFail:Y}=E;this._socket&&(this._socket.onClose(N),this._socket.onOpen(h),this._socket.onMessage(j=>D(j?.data)),this._socket.onError(()=>O),this._onSendFail=Y)}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(C){C[C.CONNECTED=0]="CONNECTED",C[C.CONNECTING=1]="CONNECTING",C[C.DISCONNECTED=2]="DISCONNECTED"})(Qr||(Qr={}));class Ha{constructor(E){this._url="",this._readyState=Qr.DISCONNECTED,this._url=E,this._id=v(),this._emitter=new jr,ai?this._socket=new $s:Je||Ur||Zi||Dt||Ki||qt?this._socket=new gr({onError:this._onError.bind(this)}):Nr?this._socket=new Mc:this._canUseWebWorker()?this._socket=new Ja:this._socket=new nI,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[Qr.CONNECTED,Qr.CONNECTING].includes(this._readyState)||(this._readyState=Qr.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(E){this._readyState!==Qr.CONNECTED?this.reconnect():this._socket.send(E)}reconnect(){[Qr.CONNECTED,Qr.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(E,h,D){this._emitter.on(E,h,D)}off(E,h,D){this._emitter.off(E,h,D)}isConnected(){return this._readyState===Qr.CONNECTED}disconnect(){this._readyState=Qr.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(E){this._readyState===Qr.CONNECTING&&(this._readyState=Qr.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:E}))}_onMessage(E){this._emitter.emit("message",E)}_onClose(E){this._readyState=Qr.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:E})}_onError(E){this._readyState=Qr.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:E})}_onSendFail(E){this._readyState=Qr.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:E})}_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 E=Fo.get("cloudConfig")||{};return(r(E.isWorkerEnabled)||E.isWorkerEnabled==="1")&&ji}}const Gs={[Ve.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[Ve.KOREA]:[[3e7,4e7],[173e7,174e7]],[Ve.GERMANY]:[[4e7,5e7],[174e7,175e7]],[Ve.IND]:[[5e7,6e7],[175e7,176e7]],[Ve.JPN]:[[6e7,7e7],[176e7,177e7]],[Ve.USA]:[[7e7,8e7],[177e7,178e7]],[Ve.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[Ve.KSA]:[[9e7,1e8],[179e7,18e8]]};function Ga(C){var E;if(!((E=Fo.get("instance"))===null||E===void 0)&&E.oversea)return Ve.OVERSEA;for(const h of Object.keys(Gs))for(const[D,N]of Gs[h])if(C>=D&&C`${_A}=${mA[_A]}`).join("&"));var mA;return h?`${C}/binfo?${BA}&compress=gzip`:`${C}/info?${BA}`}function qo(C){const E=Fo.get("instance"),{sdkAppId:h,testEnv:D,proxyServer:N}=E,O=Ga(h);if(D)return en(ze.TEST[O].DEFAULT,{isBinary:C});if(!$r(N))return en(N,{isBinary:C});const Y=ze.PRODUCTION[O],j=wt&&Y.ANYCAST,IA=wt,BA=!!Y.BACKUP_CN;return en({[Rr.INITIAL]:()=>(fo=Rr.DEFAULT,Y.DEFAULT),[Rr.DEFAULT]:()=>(fo=Rr.IPV6,Y.IPV6),[Rr.IPV6]:()=>(fo=Rr.BACKUP,Y.BACKUP),[Rr.BACKUP]:()=>IA?(fo=Rr.BACKUP_WEB_ONLY,function(mA){const _A=Math.floor(10001*Math.random())+1e4;return mA.replace("*",String(_A))}(Y.BACKUP_WEB_ONLY)):BA?(fo=Rr.BACKUP_CN,Y.BACKUP_CN):j?(fo=Rr.ANYCAST,Y.ANYCAST):Y.DEFAULT,[Rr.BACKUP_WEB_ONLY]:()=>BA?(fo=Rr.BACKUP_CN,Y.BACKUP_CN):j?(fo=Rr.ANYCAST,Y.ANYCAST):Y.DEFAULT,[Rr.BACKUP_CN]:()=>(fo=j?Rr.ANYCAST:Rr.DEFAULT,Y[fo]),[Rr.ANYCAST]:()=>(fo=Rr.DEFAULT,Y.ANYCAST="",Y.DEFAULT)}[fo](),{isBinary:C})}var Gg=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(C,E){const h=Date.now(),D=h-C;this._timeOffsetWithServer=E+D-h}};const kg=16;var fn=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(C){const{id:E}=C;this.removeTask(E),this._tasks.push(C),this._taskMap.set(E,C),this._sort(),this._scheduleNextTask()}_createTask(C){const{id:E,callback:h,context:D,isOnce:N=!1,intervalMs:O=kg}=C,Y=Math.max(O,kg);return{id:E,nextExecuteTime:Date.now()+Y,intervalMs:O,callback:h,context:D,isOnce:N}}addTask(C){const E=this._createTask(C);this._addTaskToScheduler(E)}addOnceTask(C){const E=this._createTask(Object.assign(Object.assign({},C),{isOnce:!0}));this._addTaskToScheduler(E)}removeTask(C){const E=this._tasks.findIndex(h=>h.id===C);E>-1&&(this._tasks.splice(E,1),this._taskMap.delete(C),this._scheduleNextTask())}updateTaskInterval(C,E){const h=this._taskMap.get(C);h&&(h.intervalMs=E,h.nextExecuteTime=Date.now()+E,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((C,E)=>C.nextExecuteTime-E.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const C=this._tasks[0];if(C){const E=Math.max(0,C.nextExecuteTime-Date.now());this._timer=setTimeout(()=>this._execute(),E)}}_execute(){const C=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=C;){const E=this._tasks[0];try{E.context?E.callback.call(E.context):E.callback(),E.isOnce?this.removeTask(E.id):(E.nextExecuteTime=C+E.intervalMs,this._sort())}catch(h){console.warn(`Task ${E.id} execution failed:`,h),E.isOnce&&this.removeTask(E.id)}}this._scheduleNextTask()}};function ls(C){const E=[];for(let h=0;h=55296&&D<=56319){const N=C.charCodeAt(++h)-56320+(D-55296<<10)+65536;E.push(240|N>>18,128|N>>12&63,128|N>>6&63,128|63&N)}else D<=127?E.push(D):D<=2047?E.push(192|D>>6,128|63&D):E.push(224|D>>12,128|D>>6&63,128|63&D)}return new Uint8Array(E)}function Or(C){const E=Array.isArray(C)?[]:Object.create(null);for(const h in C)Object.prototype.hasOwnProperty.call(C,h)&&m(h)&&C[h]!=null&&(C[h]===null||typeof C[h]!="object"?E[h]=C[h]:E[h]=Or(C[h]));return E}function Po(C,E){if(sA.includes(C))return 0;const h=ls(JSON.stringify(E));let D=4294967295;const{length:N}=h;for(let O=0;O>>=1:D=D>>>1^3988292384}return(4294967295^D)>>>0}function Ba(C){const{servcmd:E,data:h}=C,D=function(O){const Y=Fo.get("login")||{},j=Fo.get("instance")||{};return{servcmd:O,ver:"v4",platform:MA,websdkappid:537048168,websdkversion:"1.7.3",a2:Y.a2Key||void 0,tinyid:Y.tinyID||void 0,status_instid:Y.statusInstanceId||0,sdkappid:j.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:Y.a2Key?void 0:Y.userId,usersig:Y.a2Key?void 0:Y.userSig,sdkability:478343027,sdkability_ext:AA(""),cappid:j.applicationID||0,tjgID:"",seq:Va(),cs:0}}(E),N=Or(h);return D.cs=Po(E,N),{head:D,body:N}}function Mr(C){const{servcmd:E,data:h}=C,D=function(O){const Y=Fo.get("login")||{},j=Fo.get("instance")||{};return{servcmd:O,ver:"v4",platform:MA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:j.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:Y.statusInstanceId||0,sdkability:478343027,sdkability_ext:AA(""),cappid:j.applicationID||0,seq:Va(),cs:0}}(E),N=Or(h);return D.cs=Po(E,N),{head:D,body:N}}let Cs=v();function Va(){return Cs=Cs<2415919103?Cs+1:v(),Cs}function P(){var C;const E=Fo.get("login")||{},h=Fo.get("instance")||{};return{sdk_type:30,sdk_app_id:h.sdkAppId,sdk_version:"1.6.18",tiny_id:Number(E.tinyID),user_id:E.userId||((C=Fo.get("webPush"))===null||C===void 0?void 0:C.userId),platform:MA,instance_id:h.instanceId,trace_id:new Date().getTime()}}var F,EA=Object.freeze({__proto__:null,calcBodyCRC:Po,filterProtocolDataInvalidFields:Or,generateCosSpecifiedData:function(C){const{servcmd:E,data:h}=C,D=function(O){const Y=Fo.get("login")||{},j=Fo.get("instance")||{};return{servcmd:O,ver:"v4",platform:MA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:j.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:Y.userId,usersig:Y.userSig,status_instid:Y.statusInstanceId||0,sdkability:478343027,sdkability_ext:AA(""),cappid:j.applicationID||0,seq:Va(),cs:0}}(E),N=Or(h);return D.cs=Po(E,N),{head:D,body:N}},generateProtocolData:Ba,generateSSOLogProtocolData:Mr,generateSequence:Va,getCommonHead:P,getHostSite:Ga,taskScheduler:fn,timeManager:Gg});(function(C){C[C.info=4]="info",C[C.warning=5]="warning",C[C.error=6]="error"})(F||(F={}));const RA={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 GA{constructor(E){this.level=F.info,this._canSendLog=!0,this._logCreatedAt=Gg.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:h,eventType:D=0,message:N="",costTime:O=0,error:Y,uiPlatform:j,moreMessage:IA="",code:BA=0,startTime:mA=0}=E||{};this.eventType=D,this.method=h,this.message=N,this.costTime=O,this.moreMessage=`${IA} startTime:${mA}`,this.code=BA,Y&&this.setError(Y),$r(j)||(this.uiPlatform=j)}setMoreMessage(E){this.moreMessage=`${this.moreMessage} ${E}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Gg.getTimeOffsetWithServer()}end(E=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=Gg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),E&&this._ssoLogModule.uploadSSOLogData())}setError(E){var h;return E instanceof Error?this._canSendLog?(!((h=Fo.get("netWorkMonitor"))===null||h===void 0)&&h.isNetworkOnline&&(E.errorCode&&(this.code=E.errorCode),E.errorMessage&&this.setMoreMessage(E.errorMessage)),this.level=F.error,this):this:(console.warn("SSOLogData.setError value not instanceof Error, please check!"),this)}setLogInfo(E){return Object.keys(E).forEach(h=>{Object.keys(RA).includes(h)&&(this[h]=E[h])}),this}setSSOLogModule(E){this._ssoLogModule=E}_convertSSOLogDataKeyToServe(){const E={};return Object.keys(this).forEach(h=>{const D=h;RA[D]&&(E[RA[D]]=this[D])}),E}_getUiPlatform(){var E;const h=(E=Fo.get("instance"))===null||E===void 0?void 0:E.scene;if(typeof h=="string"){const D=Number(h);return isNaN(D)?void 0:D}}_getSDKEdition(){var E;return(E=Fo.get("instance"))===null||E===void 0?void 0:E.sdkEdition}}var WA;(function(C){C.RECONNECTED="reconnected",C.CLOUD_CONFIG_UPDATE="cloud_config_update",C.SOCKET_DISCONNECTED="socket_disconnected"})(WA||(WA={}));var Ce=WA;const ge=20,we=6e4,_e=[4,5,6],Ke="report-logger";var Bt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=ge,this._maxThreshold=100,this._waitingTime=we,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=eA.DEBUG,this._throttleConfig={global:{throttleTime:ue,maxCount:jA},single:{throttleTime:HA,maxCount:qA}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,pn.subscribeInnerEvent(Ce.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),fn.addTask({id:Ke,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(C){const{evt_rpt_threshold:E=ge,evt_rpt_waiting:h=we,evt_rpt_level:D=_e,evt_rpt_sdkappid_bl:N="",evt_rpt_tinyid_wl:O="",evt_rpt_global_throttle_time:Y=ue,evt_rpt_global_throttle_count:j=jA,evt_rpt_single_throttle_time:IA=HA,evt_rpt_single_throttle_count:BA=qA}=C||{};this._sdkAppIdBlackList=N.split(",").map(mA=>Number(mA)),this._waitingTime=Number(h),this._minThreshold=E,this._reportLevel=D,this._tinyIdWhiteList=O.split(","),this._throttleConfig={global:{throttleTime:Y,maxCount:j},single:{throttleTime:IA,maxCount:BA}}}createSSOLogData(C){const E=new GA(C);return E.setSSOLogModule(this),this._ssoLogMap.set(C.method,E),E}getSSOLogData(C){return this._ssoLogMap.get(C)||{}}pushToLogQueue(C){C&&(this._logQueue.push(C),this._shouldUploadImmediately()&&this.uploadSSOLogData())}setLogLevel(C){[eA.DEBUG,eA.ERROR,eA.INFO,eA.NONE,eA.WARN].includes(C)&&(this._logLevel=C)}debug(C,E="",h){this._log(eA.DEBUG,C,E,h)}info(C,E="",h){this._log(eA.INFO,C,E,h)}warn(C,E="",h){this._log(eA.WARN,C,E,h)}error(C,E="",h){this._log(eA.ERROR,C,E,h)}_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 et(this,void 0,void 0,function*(){if(this._logQueue.length===0)return;const C=this._logQueue.slice();this._logQueue=[];try{const E=this._filterLogs(C);if(E.length===0)return void(this._lastReportAt=Date.now());const h={Header:P(),Event:E};$r(h.Header.user_id)||(yield function(D){const N="imopenstat.tim_web_report_v2",O=Mr({servcmd:N,data:D}),Y=`${O.head.seq}${N}`;return II.sendPacket(O,{requestId:Y})}(h))}catch(E){this._requeueFailedLogs(C),this.debug("uploadSSOLogData",An(E))}finally{this._lastReportAt=Date.now()}})}_requeueFailedLogs(C){this._logQueue=C.concat(this._logQueue);const E=this._logQueue.length-200;E>0&&(this._logQueue.splice(0,E),this.debug("uploadSSOLogData",`log queue overflow, dropped ${E} oldest logs`))}_savePlatFormInfo(){var C,E;if(Je){const h=(E=(C=wx.getAccountInfoSync)===null||C===void 0?void 0:C.call(wx))===null||E===void 0?void 0:E.miniProgram;if(h){const{appId:D,envVersion:N}=h;Fo.set("instance",{appId:D,envVersion:N})}}else wt&&Fo.set("instance",{href:window.location.href})}_filterLogs(C){const{tinyID:E}=Fo.get("login")||{},{sdkAppId:h}=Fo.get("instance")||{};return this._sdkAppIdBlackList.includes(h)&&!this._tinyIdWhiteList.includes(E)?[]:C.filter(D=>this._reportLevel.includes(D.level))}_checkThrottle(C){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(C)}_checkGlobalThrottle(){const C=Date.now();if(C-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=C;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(C){const E=Date.now(),h=this._singleThrottleMap.get(C);return h?E-h.startTime>=this._throttleConfig.single.throttleTime?(h.count=1,h.startTime=E,!1):h.count>=this._throttleConfig.single.maxCount||(h.count++,!1):(this._singleThrottleMap.set(C,{count:1,startTime:E}),!1)}_shouldLog(C){return C>=this._logLevel&&this._logLevel!==eA.NONE}_shouldReport(C){return this._reportLevel.includes(wA[C])}_formatLog(C,E,h,D){const N=new Date,O=`${N.getHours()}:${N.getMinutes()}:${N.getSeconds()}:${N.getMilliseconds()}`,Y=`<${eA[C]}>`;return ot||Xi?[`${X} [${O}] ${Y} [${E}] ${h}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",X,"",`[${O}] ${Y} [${E}] ${h} params: ${An(D)}`]}_log(C,E,h,D){if(this._shouldLog(C)){const N=this._formatLog(C,E,h,D);QA[C].apply(console,N)}if(this._shouldReport(C)){const N=this._getThrottleKey(E,h,D);this._checkThrottle(N)||this.createSSOLogData(Object.assign(Object.assign({message:h},D),{method:E})).end()}}_getThrottleKey(C,E,h){const D=`${C}${E}${An(Object.assign(Object.assign({},h),{costTime:""}))}`,N=ls(JSON.stringify(D));let O=4294967295;const{length:Y}=N;for(let j=0;j>>=1:O=O>>>1^3988292384}return`${(4294967295^O)>>>0}`}reset(){console.log("SSO_LOG_MODULE.reset"),fn.removeTask(Ke),pn.unSubscribeInnerEvent(Ce.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=ge,this._maxThreshold=100,this._waitingTime=we,this._logQueue=[],this._logLevel=eA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const Rt=15e3,Ye="Channel",nt="channel_schedule_task",ii="channel_reconnect_task",oi="connected",Ko="connecting",Kt="disconnected",ro=1e3,ks="network_status_change",Zr="activity_status_change",In="send_fail",xr="reconnect_failed",sI="socket_error",jo="socket_close";function OI(C){return OI=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(E){return typeof E}:function(E){return E&&typeof Symbol=="function"&&E.constructor===Symbol&&E!==Symbol.prototype?"symbol":typeof E},OI(C)}function _g(C){throw new Error('Could not dynamically require "'+C+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var gI,ml={exports:{}},ua=(gI||(gI=1,function(C){C.exports=function E(h,D,N){function O(IA,BA){if(!D[IA]){if(!h[IA]){if(!BA&&_g)return _g(IA);if(Y)return Y(IA,!0);var mA=new Error("Cannot find module '"+IA+"'");throw mA.code="MODULE_NOT_FOUND",mA}var _A=D[IA]={exports:{}};h[IA][0].call(_A.exports,function(xA){return O(h[IA][1][xA]||xA)},_A,_A.exports,E,h,D,N)}return D[IA].exports}for(var Y=_g,j=0;j>>6:(xA<65536?_A[Se++]=224|xA>>>12:(_A[Se++]=240|xA>>>18,_A[Se++]=128|xA>>>12&63),_A[Se++]=128|xA>>>6&63),_A[Se++]=128|63&xA);return _A},D.buf2binstring=function(mA){return BA(mA,mA.length)},D.binstring2buf=function(mA){for(var _A=new N.Buf8(mA.length),xA=0,Qe=_A.length;xA>10&1023,at[Qe++]=56320|1023&Re)}return BA(at,Qe)},D.utf8border=function(mA,_A){var xA;for((_A=_A||mA.length)>mA.length&&(_A=mA.length),xA=_A-1;0<=xA&&(192&mA[xA])==128;)xA--;return xA<0||xA===0?_A:xA+j[mA[xA]]>_A?xA:_A}},{"./common":1}],3:[function(E,h,D){h.exports=function(N,O,Y,j){for(var IA=65535&N,BA=N>>>16&65535,mA=0;Y!==0;){for(Y-=mA=2e3>>1:O>>>1;Y[j]=O}return Y}();h.exports=function(O,Y,j,IA){var BA=N,mA=IA+j;O^=-1;for(var _A=IA;_A>>8^BA[255&(O^Y[_A])];return-1^O}},{}],6:[function(E,h,D){h.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(E,h,D){h.exports=function(N,O){var Y,j,IA,BA,mA,_A,xA,Qe,Re,Se,At,at,jt,Bi,ri,St,eo,to,Yt,si,zo,te,je,dA,ut;Y=N.state,j=N.next_in,dA=N.input,IA=j+(N.avail_in-5),BA=N.next_out,ut=N.output,mA=BA-(O-N.avail_out),_A=BA+(N.avail_out-257),xA=Y.dmax,Qe=Y.wsize,Re=Y.whave,Se=Y.wnext,At=Y.window,at=Y.hold,jt=Y.bits,Bi=Y.lencode,ri=Y.distcode,St=(1<>>=Yt=to>>>24,jt-=Yt,(Yt=to>>>16&255)==0)ut[BA++]=65535&to;else{if(!(16&Yt)){if(!(64&Yt)){to=Bi[(65535&to)+(at&(1<>>=Yt,jt-=Yt),jt<15&&(at+=dA[j++]<>>=Yt=to>>>24,jt-=Yt,!(16&(Yt=to>>>16&255))){if(!(64&Yt)){to=ri[(65535&to)+(at&(1<>>=Yt,jt-=Yt,(Yt=BA-mA)>3,at&=(1<<(jt-=si<<3))-1,N.next_in=j,N.next_out=BA,N.avail_in=j>>24&255)+(te>>>8&65280)+((65280&te)<<8)+((255&te)<<24)}function at(){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 N.Buf16(320),this.work=new N.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function jt(te){var je;return te&&te.state?(je=te.state,te.total_in=te.total_out=je.total=0,te.msg="",je.wrap&&(te.adler=1&je.wrap),je.mode=Qe,je.last=0,je.havedict=0,je.dmax=32768,je.head=null,je.hold=0,je.bits=0,je.lencode=je.lendyn=new N.Buf32(Re),je.distcode=je.distdyn=new N.Buf32(Se),je.sane=1,je.back=-1,_A):xA}function Bi(te){var je;return te&&te.state?((je=te.state).wsize=0,je.whave=0,je.wnext=0,jt(te)):xA}function ri(te,je){var dA,ut;return te&&te.state?(ut=te.state,je<0?(dA=0,je=-je):(dA=1+(je>>4),je<48&&(je&=15)),je&&(je<8||15=lt.wsize?(N.arraySet(lt.window,je,dA-lt.wsize,lt.wsize,0),lt.wnext=0,lt.whave=lt.wsize):(ut<(Cr=lt.wsize-lt.wnext)&&(Cr=ut),N.arraySet(lt.window,je,dA-ut,Cr,lt.wnext),(ut-=Cr)?(N.arraySet(lt.window,je,dA-ut,ut,0),lt.wnext=ut,lt.whave=lt.wsize):(lt.wnext+=Cr,lt.wnext===lt.wsize&&(lt.wnext=0),lt.whave>>8&255,dA.check=Y(dA.check,re,2,0),Oe=Fe=0,dA.mode=2;break}if(dA.flags=0,dA.head&&(dA.head.done=!1),!(1&dA.wrap)||(((255&Fe)<<8)+(Fe>>8))%31){te.msg="incorrect header check",dA.mode=30;break}if((15&Fe)!=8){te.msg="unknown compression method",dA.mode=30;break}if(Oe-=4,gA=8+(15&(Fe>>>=4)),dA.wbits===0)dA.wbits=gA;else if(gA>dA.wbits){te.msg="invalid window size",dA.mode=30;break}dA.dmax=1<>8&1),512&dA.flags&&(re[0]=255&Fe,re[1]=Fe>>>8&255,dA.check=Y(dA.check,re,2,0)),Oe=Fe=0,dA.mode=3;case 3:for(;Oe<32;){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>>8&255,re[2]=Fe>>>16&255,re[3]=Fe>>>24&255,dA.check=Y(dA.check,re,4,0)),Oe=Fe=0,dA.mode=4;case 4:for(;Oe<16;){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>8),512&dA.flags&&(re[0]=255&Fe,re[1]=Fe>>>8&255,dA.check=Y(dA.check,re,2,0)),Oe=Fe=0,dA.mode=5;case 5:if(1024&dA.flags){for(;Oe<16;){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>>8&255,dA.check=Y(dA.check,re,2,0)),Oe=Fe=0}else dA.head&&(dA.head.extra=null);dA.mode=6;case 6:if(1024&dA.flags&&(Jt<(ti=dA.length)&&(ti=Jt),ti&&(dA.head&&(gA=dA.head.extra_len-dA.length,dA.head.extra||(dA.head.extra=new Array(dA.head.extra_len)),N.arraySet(dA.head.extra,ut,lt,ti,gA)),512&dA.flags&&(dA.check=Y(dA.check,ut,ti,lt)),Jt-=ti,lt+=ti,dA.length-=ti),dA.length))break A;dA.length=0,dA.mode=7;case 7:if(2048&dA.flags){if(Jt===0)break A;for(ti=0;gA=ut[lt+ti++],dA.head&&gA&&dA.length<65536&&(dA.head.name+=String.fromCharCode(gA)),gA&&ti>9&1,dA.head.done=!0),te.adler=dA.check=0,dA.mode=12;break;case 10:for(;Oe<32;){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>>=7&Oe,Oe-=7&Oe,dA.mode=27;break}for(;Oe<3;){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>>=1)){case 0:dA.mode=14;break;case 1:if(si(dA),dA.mode=20,je!==6)break;Fe>>>=2,Oe-=2;break A;case 2:dA.mode=17;break;case 3:te.msg="invalid block type",dA.mode=30}Fe>>>=2,Oe-=2;break;case 14:for(Fe>>>=7&Oe,Oe-=7&Oe;Oe<32;){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>>16^65535)){te.msg="invalid stored block lengths",dA.mode=30;break}if(dA.length=65535&Fe,Oe=Fe=0,dA.mode=15,je===6)break A;case 15:dA.mode=16;case 16:if(ti=dA.length){if(Jt>>=5,Oe-=5,dA.ndist=1+(31&Fe),Fe>>>=5,Oe-=5,dA.ncode=4+(15&Fe),Fe>>>=4,Oe-=4,286>>=3,Oe-=3}for(;dA.have<19;)dA.lens[LA[dA.have++]]=0;if(dA.lencode=dA.lendyn,dA.lenbits=7,vA={bits:dA.lenbits},pA=IA(0,dA.lens,0,19,dA.lencode,0,dA.work,vA),dA.lenbits=vA.bits,pA){te.msg="invalid code lengths set",dA.mode=30;break}dA.have=0,dA.mode=19;case 19:for(;dA.have>>16&255,Xa=65535&UA,!((Bo=UA>>>24)<=Oe);){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>>=Bo,Oe-=Bo,dA.lens[dA.have++]=Xa;else{if(Xa===16){for(Ae=Bo+2;Oe>>=Bo,Oe-=Bo,dA.have===0){te.msg="invalid bit length repeat",dA.mode=30;break}gA=dA.lens[dA.have-1],ti=3+(3&Fe),Fe>>>=2,Oe-=2}else if(Xa===17){for(Ae=Bo+3;Oe>>=Bo)),Fe>>>=3,Oe-=3}else{for(Ae=Bo+7;Oe>>=Bo)),Fe>>>=7,Oe-=7}if(dA.have+ti>dA.nlen+dA.ndist){te.msg="invalid bit length repeat",dA.mode=30;break}for(;ti--;)dA.lens[dA.have++]=gA}}if(dA.mode===30)break;if(dA.lens[256]===0){te.msg="invalid code -- missing end-of-block",dA.mode=30;break}if(dA.lenbits=9,vA={bits:dA.lenbits},pA=IA(BA,dA.lens,0,dA.nlen,dA.lencode,0,dA.work,vA),dA.lenbits=vA.bits,pA){te.msg="invalid literal/lengths set",dA.mode=30;break}if(dA.distbits=6,dA.distcode=dA.distdyn,vA={bits:dA.distbits},pA=IA(mA,dA.lens,dA.nlen,dA.ndist,dA.distcode,0,dA.work,vA),dA.distbits=vA.bits,pA){te.msg="invalid distances set",dA.mode=30;break}if(dA.mode=20,je===6)break A;case 20:dA.mode=21;case 21:if(6<=Jt&&258<=mo){te.next_out=Co,te.avail_out=mo,te.next_in=lt,te.avail_in=Jt,dA.hold=Fe,dA.bits=Oe,j(te,Zo),Co=te.next_out,Cr=te.output,mo=te.avail_out,lt=te.next_in,ut=te.input,Jt=te.avail_in,Fe=dA.hold,Oe=dA.bits,dA.mode===12&&(dA.back=-1);break}for(dA.back=0;Da=(UA=dA.lencode[Fe&(1<>>16&255,Xa=65535&UA,!((Bo=UA>>>24)<=Oe);){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>ia)])>>>16&255,Xa=65535&UA,!(ia+(Bo=UA>>>24)<=Oe);){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>>=ia,Oe-=ia,dA.back+=ia}if(Fe>>>=Bo,Oe-=Bo,dA.back+=Bo,dA.length=Xa,Da===0){dA.mode=26;break}if(32&Da){dA.back=-1,dA.mode=12;break}if(64&Da){te.msg="invalid literal/length code",dA.mode=30;break}dA.extra=15&Da,dA.mode=22;case 22:if(dA.extra){for(Ae=dA.extra;Oe>>=dA.extra,Oe-=dA.extra,dA.back+=dA.extra}dA.was=dA.length,dA.mode=23;case 23:for(;Da=(UA=dA.distcode[Fe&(1<>>16&255,Xa=65535&UA,!((Bo=UA>>>24)<=Oe);){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>ia)])>>>16&255,Xa=65535&UA,!(ia+(Bo=UA>>>24)<=Oe);){if(Jt===0)break A;Jt--,Fe+=ut[lt++]<>>=ia,Oe-=ia,dA.back+=ia}if(Fe>>>=Bo,Oe-=Bo,dA.back+=Bo,64&Da){te.msg="invalid distance code",dA.mode=30;break}dA.offset=Xa,dA.extra=15&Da,dA.mode=24;case 24:if(dA.extra){for(Ae=dA.extra;Oe>>=dA.extra,Oe-=dA.extra,dA.back+=dA.extra}if(dA.offset>dA.dmax){te.msg="invalid distance too far back",dA.mode=30;break}dA.mode=25;case 25:if(mo===0)break A;if(ti=Zo-mo,dA.offset>ti){if((ti=dA.offset-ti)>dA.whave&&dA.sane){te.msg="invalid distance too far back",dA.mode=30;break}ti>dA.wnext?(ti-=dA.wnext,_n=dA.wsize-ti):_n=dA.wnext-ti,ti>dA.length&&(ti=dA.length),Eg=dA.window}else Eg=Cr,_n=Co-dA.offset,ti=dA.length;for(moeo?(Yt=_n[Eg+Se[je]],si=Oe[xs+Se[je]]):(Yt=96,si=0),at=1<>Co)+(jt-=at)]=to<<24|Yt<<16|si,jt!==0;);for(at=1<>=1;if(at!==0?(Fe&=at-1,Fe+=at):Fe=0,je++,--Zo[te]==0){if(te===ut)break;te=mA[_A+Se[je]]}if(Cr{const j=new Uint8Array(Y).slice(4);let IA;try{IA=ua.inflate(j,{to:"string"})}catch(BA){console.error("inflate error",BA)}return IA})(C.data):function(Y){const j=new Uint8Array(Y);let IA="",BA=0;const{length:mA}=j;for(;BA0)for(let Re=0;Re{var D;const{uplinkData:N,canResend:O,resolve:Y,reject:j,timeout:IA}=E;if(O){this._pendingRequests.set(h,{resolve:Y,reject:j,timestamp:Date.now(),uplinkData:N,timeout:IA,canResend:O});const BA=this._isBinarySupported?ls(N).buffer:N;(D=this._socketAdapter)===null||D===void 0||D.send(BA)}else this._pendingRequests.delete(h)})}_onConnect(C){const{socketId:E,event:h={}}=C||{};this._connectionId=E,this._connectionEstablishedTime=Date.now();const D=Date.now()-this._connectionStartTime,N=`${Ye}.onConnect cost:${D} ms. socketID:${E} res:${JSON.stringify(h)}`;if(this._ssoLog({method:"onConnect",message:N}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const O=`${Ye}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:O}),pn.emitInnerEvent(Ce.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:oi,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(C){const E=Ba({servcmd:"openim.ws_msg_push_ack",data:{SessionData:C}});this.sendPacket(E)}_executeScheduledTaskIfReady(){return et(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var C;return((C=this._socketAdapter)===null||C===void 0?void 0:C.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return et(this,void 0,void 0,function*(){var C;const E=Ba({servcmd:"heartbeat.alive",data:{}});try{const h=`${E.head.seq}${E.head.servcmd}`;yield this.sendPacket(E,{requestId:h,timeout:3e3})}catch(h){const D=(C=Fo.get("netWorkMonitor"))===null||C===void 0?void 0:C.isNetworkOnline,N=`${Ye}.sendHeartbeat failed. isNetWorkOnline:${D} error: ${An(h)}`;this._ssoLog({method:"sendHeartbeatError",message:N}),this._handleConnectStateChange({state:Kt,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return et(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=Ur?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(C){const E=`${Ye}.networkStatusChange ${JSON.stringify(C)}`;this._ssoLog({method:"networkStatusChange",message:E});const{isNetworkOnline:h,networkType:D}=C;h&&D!=="none"?this._handleConnectStateChange({state:oi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:ks}):this._handleConnectStateChange({state:Kt,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:ks})}isPrivateNetWork(){const C=Fo.get("instance")||{};return C.proxyServer&&!C.fileDownloadProxy}_handleConnectStateChange(C){const{state:E,shouldAttemptReconnect:h,shouldEmitEvent:D,reason:N}=C,O=`${Ye}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${h} shouldEmitEvent: ${D} reason: ${N}`;this._currentConnectState!==E&&(this._ssoLog({method:"handleConnectStateChange",message:O}),D&&(Bt.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${E}`),pn.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:E}}),this._currentConnectState=E,E===Kt&&pn.emitInnerEvent(Ce.SOCKET_DISCONNECTED)),h&&(this._resetReconnectDelay(),fn.addTask({id:ii,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(C){var E,h;const D=(h=(E=this._socketAdapter)===null||E===void 0?void 0:E._ws)===null||h===void 0?void 0:h.readyState,N=`${Ye}.activityStatusChange ${JSON.stringify(C)} readyState: ${D}`;Bt.debug("activityStatusChange",N),D===3&&this._handleConnectStateChange({state:Kt,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:Zr})}_resetReconnectDelay(){var C;Bt.debug(`${Ye}._resetReconnectDelay`),fn.removeTask(ii);const E=(C=Fo.get("activityMonitor"))===null||C===void 0?void 0:C.isActive;this._intendedDelay=E?ro:1e3}_scheduleReconnectWithBackoff(){var C;const E=(C=Fo.get("activityMonitor"))===null||C===void 0?void 0:C.isActive;this._intendedDelay=E?Math.min(5e3,Math.max(ro,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const h=new Date().toTimeString().slice(0,8),D=`${Ye}.scheduleReconnectWithBackoff timeStr: ${h} intendedDelay: ${this._intendedDelay}`;Bt.debug(D),this.reconnect(),fn.updateTaskInterval(ii,this._intendedDelay)}_ssoLog(C){const{method:E,message:h}=C;Bt.info(E,h)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(C){et(this,void 0,void 0,function*(){const E=C.split("/")[2];if(!E.startsWith("ws"))return;const h=`https://${E}/v3/netcheck/getconninfo?${C.slice(C.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield $t({method:"GET",url:h,data:{}})}catch(D){Bt.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${D.message}`)}})}(this._url),function(C){et(this,void 0,void 0,function*(){const E=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${C.slice(C.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield $t({method:"GET",url:E,data:{}})}catch(h){Bt.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${h.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[C,E]of this._pendingRequests.entries()){const{reject:h,timestamp:D,timeout:N}=E;Date.now()-D>=N&&(this._pendingRequests.delete(C),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),h({errorCode:Qn,errorInfo:"NETWORK_TIMEOUT",data:{requestId:C}}))}}_updateIsBinarySupported(){var C;if(!((C=Fo.get("instance"))===null||C===void 0)&&C.devMode)return void(this._isBinarySupported=!1);const E=Lo();if((ai||Je&&E==="windows"||Kn)&&(this._isBinarySupported=!1),Ur){const{uniRuntimeVersion:h=""}=Ji.getSystemInfoSync();(function(D){const N=D.split(".").map(Number),[O=0,Y=0,j=0]=N;return O>2||!(O<2)&&(Y>2||!(Y<2)&&j>=6)})(h)||(this._isBinarySupported=!1)}}_isCompressedData(C){const E=new Uint8Array(C);return E[0]===67&&E[1]===79&&E[2]===77&&E[3]===80}};const ZA={init:function(C){Fo.set("instance",C),II.init()},destroy:function(){II.dispose(),Fo.clear(),fn.dispose()},notificationCenter:pn,channel:II,store:Fo,ssoLog:Bt,utils:Es,common:EA,constants:qe},Ag=C=>typeof C=="function";function cI(C,E,h){const D=h||[];if(!C||!E)return!1;const N=Object.keys(C).filter(Y=>!D.includes(Y)),O=Object.keys(E).filter(Y=>!D.includes(Y));return N.length===O.length&&N.every(Y=>!!E.hasOwnProperty(Y)&&(typeof C[Y]=="object"&&C[Y]!==null?cI(C[Y],E[Y],h):C[Y]===E[Y]))}var Bs;(function(C){C.SDK_READY="sdkStateReady",C.SDK_NOT_READY="sdkStateNotReady",C.SDK_DESTROY="sdkDestroy",C.MESSAGE_RECEIVED="onMessageReceived",C.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",C.MESSAGE_MODIFIED="onMessageModified",C.MESSAGE_REVOKED="onMessageRevoked",C.MESSAGE_READ_BY_PEER="onMessageReadByPeer",C.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",C.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",C.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",C.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",C.CONVERSATION_LIST_UPDATED="onConversationListUpdated",C.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",C.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",C.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",C.GROUP_LIST_UPDATED="onGroupListUpdated",C.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",C.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",C.TOPIC_CREATED="onTopicCreated",C.TOPIC_DELETED="onTopicDeleted",C.TOPIC_UPDATED="onTopicUpdated",C.PROFILE_UPDATED="onProfileUpdated",C.USER_STATUS_UPDATED="onUserStatusUpdated",C.BLACKLIST_UPDATED="blacklistUpdated",C.FRIEND_LIST_UPDATED="onFriendListUpdated",C.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",C.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",C.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",C.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",C.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",C.KICKED_OUT="kickedOut",C.ERROR="error",C.NET_STATE_CHANGE="netStateChange",C.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",C.SERVER_CONFIG_UPDATED="onServerConfigUpdated",C.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated",C.WEB_PUSH_MESSAGE_RECEIVED="onWebPushMessageReceived",C.GROUP_ONLINE_MEMBER_COUNT_CHANGED="onGroupOnlineMemberCountChanged",C.RICH_STATUS_CHANGED="onRichStatusChanged"})(Bs||(Bs={}));var eg,kr=Bs;(function(C){C.LOGOUT="logout",C.DESTROY="destroy",C.CLOUD_CONFIG_UPDATE="cloud_config_update",C.PROFILE_UPDATE="profile_updated",C.ERROR="error",C.RECONNECTED="reconnected",C.FORCE_OFFLINE="im_open_status.stat_forceoffline",C.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",C.OVERLOAD_PUSH="OverLoadPush.notify2",C.NEW_MESSAGE="new_message",C.MESSAGE_PUSH="im_open_push.msg_push",C.MESSAGE_DELETED="message_deleted",C.MESSAGE_REVOKED="message_revoked",C.MESSAGE_MODIFIED="message_modified",C.SOCKET_DISCONNECTED="socket_disconnected",C.CONVERSATION_UPDATED="conversation_updated",C.TOPIC_MESSAGE_DELETED="topic_message_deleted",C.TOPIC_MESSAGE_REVOKED="topic_message_revoked",C.TOPIC_MESSAGE_MODIFIED="topic_message_modified",C.TOPIC_NEW_MESSAGE="topic_new_message",C.QUALITY_STAT="quality_stat",C.SYNC_CONVERSATION_LIST="sync_conversation_list",C.HISTORY_MESSAGE_FETCHED="history_message_fetched"})(eg||(eg={}));var EI,Gt=eg;(function(C){C.NEW_INVITATION_RECEIVED="newInvitationReceived",C.INVITEE_ACCEPTED="ts_invitee_accepted",C.INVITEE_REJECTED="ts_invitee_rejected",C.INVITATION_CANCELLED="ts_invitation_cancelled",C.INVITATION_TIMEOUT="ts_invitation_timeout",C.INVITATION_MODIFIED="ts_invitation_modified"})(EI||(EI={}));var Dl=EI;const xI=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),_s={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 tg;(function(C){C.UNSENT="unSend",C.SUCCESS="success",C.FAIL="fail"})(tg||(tg={}));const ka={modify:Gt.MESSAGE_MODIFIED,delete:Gt.MESSAGE_DELETED,revoke:Gt.MESSAGE_REVOKED};var wc;(function(C){C[C.FORWARD=0]="FORWARD",C[C.BACKWARD=1]="BACKWARD"})(wc||(wc={}));const CE=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},_s),{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:tg,Direction:wc}),qa={[ka.modify]:Gt.TOPIC_MESSAGE_MODIFIED,[ka.delete]:Gt.TOPIC_MESSAGE_DELETED,[ka.revoke]:Gt.TOPIC_MESSAGE_REVOKED},BE={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"},yC=Object.assign({},BE),us={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},lI=Object.assign(Object.assign(Object.assign(Object.assign({},us),{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"}),ig=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"}),yl={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},_a={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},Qs={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},Rl=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},yl),{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:_a,GROUP_TIPS_OPERATION_TYPE:Qs}),YI={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},vo=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},xI),CE),yC),lI),ig),Rl),YI),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),Qa={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},uE={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},cn={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"},kt={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"},Gn={[cn.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:kt.USER_STATUS_UPDATE},{stepId:kt.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:kt.UNREAD_MESSAGE_SYNC,dependency:kt.C2C_HISTORY_MESSAGE_RECOVER},{stepId:kt.CONVERSATION_RECOVER},{stepId:kt.HISTORY_MESSAGE_RECOVER,dependency:kt.CONVERSATION_RECOVER},{stepId:kt.BLACKLIST_RECOVER},{stepId:kt.FRIEND_RECOVER},{stepId:kt.FRIEND_APPLICATION_LIST_RECOVER},{stepId:kt.GROUP_REVOKED_NOTICE_RECOVER,dependency:kt.HISTORY_MESSAGE_RECOVER},{stepId:kt.GROUP_TIPS_RECOVER,dependency:kt.HISTORY_MESSAGE_RECOVER},{stepId:kt.TOPIC_REQUEST_INFO_RESET},{stepId:kt.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:kt.UNREAD_MESSAGE_SYNC},{stepId:kt.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:kt.UNREAD_MESSAGE_SYNC},{stepId:kt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[kt.UNREAD_MESSAGE_SYNC,kt.CONVERSATION_RECOVER]},{stepId:kt.EMIT_C2C_MESSAGE_EVENT,dependency:[kt.UNREAD_MESSAGE_SYNC,kt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:kt.C2C_HISTORY_MESSAGE_RECOVER,dependency:kt.CONVERSATION_RECOVER},{stepId:kt.STREAM_MESSAGE_RECOVER}],[cn.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:kt.COMMERCIAL_CONFIG_UPDATE},{stepId:kt.CLOUD_CONFIG_SYNC},{stepId:kt.USER_PROFILE_SYNC},{stepId:kt.UNREAD_MESSAGE_SYNC},{stepId:kt.FRIEND_AND_BLACKLIST_SYNC},{stepId:kt.GROUP_LIST_SYNC},{stepId:kt.CONVERSATION_LIST_SYNC},{stepId:kt.SIGNALING_MESSAGE_RECOVER,dependency:kt.UNREAD_MESSAGE_SYNC},{stepId:kt.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[kt.UNREAD_MESSAGE_SYNC]},{stepId:kt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[kt.UNREAD_MESSAGE_SYNC,kt.CONVERSATION_LIST_SYNC]},{stepId:kt.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[kt.GROUP_LIST_SYNC,kt.CONVERSATION_LIST_SYNC]},{stepId:kt.CONVERSATION_GROUP_LIST_SYNC},{stepId:kt.CONVERSATION_GROUP_UPDATE,dependency:[kt.CONVERSATION_LIST_SYNC,kt.CONVERSATION_GROUP_LIST_SYNC]},{stepId:kt.QUALITY_REPORT}],[cn.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:kt.HANDLE_C2C_NEW_MESSAGE},{stepId:kt.UNREAD_MESSAGE_SYNC},{stepId:kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:kt.HANDLE_C2C_NEW_MESSAGE},{stepId:kt.EMIT_C2C_MESSAGE_EVENT,dependency:[kt.HANDLE_C2C_NEW_MESSAGE,kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:kt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[kt.UNREAD_MESSAGE_SYNC]}],[cn.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:kt.HANDLE_GROUP_NEW_MESSAGE},{stepId:kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:kt.HANDLE_GROUP_NEW_MESSAGE},{stepId:kt.UPDATE_GROUP_NEXT_SEQUENCE,dependency:kt.HANDLE_GROUP_NEW_MESSAGE},{stepId:kt.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:kt.HANDLE_GROUP_NEW_MESSAGE},{stepId:kt.EMIT_GROUP_MESSAGE_EVENT,dependency:[kt.HANDLE_GROUP_NEW_MESSAGE,kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[cn.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:kt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:kt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:kt.EMIT_GROUP_TIPS_EVENT,dependency:[kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,kt.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},PI={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},Sc={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},tn=["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 Ml=Object.freeze({__proto__:null,ERROR_CODE:Qa,InnerEvent:Gt,NEED_LOG_API:tn,OuterConstant:vo,OuterEvent:kr,PUSH:YI,QUALITY_METRICS:PI,SDK_EDITION:uE,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:Sc,SignalingEvent:Dl,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Gn,WORKFLOW_NAME:cn,WORKFLOW_STEP:kt}),ba,da,on;(function(C){C[C.USER_INITIATED=0]="USER_INITIATED",C[C.KICKED_OUT=1]="KICKED_OUT"})(ba||(ba={})),function(C){C[C.multipleAccount=1]="multipleAccount",C[C.multipleDevice=2]="multipleDevice",C[C.restApi=3]="restApi"}(da||(da={})),function(C){C[C.multipleDevice=3002]="multipleDevice",C[C.multipleAccount=3003]="multipleAccount",C[C.usersigExpired=70001]="usersigExpired",C[C.restApi=20002]="restApi"}(on||(on={}));const Xr={[da.multipleAccount]:"multipleAccount",[da.multipleDevice]:"multipleDevice",[da.restApi]:"REST_API_Kick",[on.multipleAccount]:"multipleAccount",[on.multipleDevice]:"multipleDevice",[on.restApi]:"REST_API_Kick",[on.usersigExpired]:"userSigExpired"},wl="login_online_presence_task",{ERROR:bs,DESTROY:vc,FORCE_OFFLINE:CI}=Gt,{KICKED_OUT_MULT_ACCOUNT:QE,KICKED_OUT_MULT_DEVICE:RC,KICKED_OUT_REST_API:Nc,ACCOUNT_A2KEY_EXPIRED:Sl,MSG_A2KEY_EXPIRED:JI}=Qa;class bg{init(){const{notificationCenter:E}=ZA;E.subscribeInnerEvent(CI,this._handleForceOfflineFromServerPush,this),E.subscribeInnerEvent(bs,JI,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),E.subscribeInnerEvent(bs,Sl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),E.subscribeInnerEvent(bs,QE,this._handleForceOfflineFromResponse,this),E.subscribeInnerEvent(bs,RC,this._handleForceOfflineFromResponse,this),E.subscribeInnerEvent(bs,Nc,this._handleForceOfflineFromResponse,this),E.subscribeInnerEvent(vc,this._dispose,this)}_handleForceOfflineFromServerPush(E){var h;if(((h=ZA.store.get("login"))===null||h===void 0?void 0:h.isLoggedIn)===!0){const{EventArray:D=[]}=E?.body||{};this._extractKickedOutMessages(D).forEach(N=>{const{KickoutMsgNotify:{KickType:O,NewInstInfo:Y,Instid:j}}=N;this._isCurrentInstanceKickedOut(j)&&this._processKickedOutReasonInfo({kickedOutReasonCode:O,newInstanceInfo:Y})})}}_extractKickedOutMessages(E){return E.reduce((h,D)=>[...h,...D.C2cNotifyMsgArray||[]],[]).filter(h=>{var D;return this._isKickedOut((D=h?.KickoutMsgNotify)===null||D===void 0?void 0:D.KickType)})}_handleForceOfflineFromResponse(E){const{errorCode:h}=E;this._processKickedOutReasonInfo({kickedOutReasonCode:h})}_processKickedOutReasonInfo(E){return et(this,void 0,void 0,function*(){const{kickedOutReasonCode:h}=E,{ssoLog:D,utils:{safeStringify:N}}=ZA;try{this._logKickedOutEvent(E),this._shouldLogoutAfterKickedOut(h)?yield ZA.login.loginAction.logout(ba.KICKED_OUT):ZA.login.loginAction.handleLogoutCompleted()}catch(O){D.debug("_processKickedOutReasonInfo",` fail ${N(O)}`)}finally{ZA.notificationCenter.emitOuterEvent(kr.KICKED_OUT,{data:{type:Xr[h]},name:kr.KICKED_OUT})}})}_logKickedOutEvent(E){const{kickedOutReasonCode:h,newInstanceInfo:D={}}=E,N=`type:${Xr[h]} newInstanceInfo: ${JSON.stringify(D)}`;ZA.ssoLog.warn("kickedOut",N)}_isKickedOut(E){return[da.multipleAccount,da.multipleDevice,da.restApi].includes(E)}_isChatLoginEvent(E){const{requestHead:h}=E||{};return h?.idtype!==1}_shouldLogoutAfterKickedOut(E){return![on.usersigExpired,da.restApi].includes(E)}_isCurrentInstanceKickedOut(E){const{isLoggedIn:h,statusInstanceId:D}=ZA.store.get("login")||{};return h===!0&&E===D}_dispose(){const{notificationCenter:E}=ZA;E.unSubscribeInnerEvent(CI,this._handleForceOfflineFromServerPush,this),E.unSubscribeInnerEvent(bs,Sl,this._handleForceOfflineFromResponse,this),E.unSubscribeInnerEvent(bs,JI,this._handleForceOfflineFromResponse,this),E.unSubscribeInnerEvent(bs,QE,this._handleForceOfflineFromResponse,this),E.unSubscribeInnerEvent(bs,RC,this._handleForceOfflineFromResponse,this),E.unSubscribeInnerEvent(bs,Nc,this._handleForceOfflineFromResponse,this),E.unSubscribeInnerEvent(vc,this._dispose,this)}}function dE(C){return et(this,void 0,void 0,function*(){const E="im_open_status.wslogin",h=ZA.common.generateProtocolData({servcmd:E,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:C}}),D=`${h.head.seq}${E}`,N=yield ZA.channel.sendPacket(h,{timeout:9e4,requestId:D});if(N){const{HelloInterval:O,InstId:Y,TinyId:j,TimeStamp:IA,CustomStatus:BA,PurchaseBits:mA,A2Key:_A,RichMsgAuthKey:xA,ErrorCode:Qe,ErrorInfo:Re,ActionStatus:Se}=N;return{helloInterval:O,instanceID:Y,tinyID:j,timeStamp:IA,customStatus:BA,purchaseBits:mA,a2Key:_A,authKey:xA,errorCode:Qe,errorInfo:Re,actionStatus:Se}}})}function vl(){const{store:C}=ZA;return Ga(C.get("instance").sdkAppId)!==Ve.CHINA}function Tc(C){var E;try{const h=Fo.getStorage("errorMessage");if(!C||!h)return"";const D=((E=JSON.parse(h))===null||E===void 0?void 0:E.errorMessage)||{},{code:N,replacement1:O="",replacement2:Y=""}=C;if(!N)return"";const j=vl()?`${N}_en`:`${N}_cn`;let IA=D[D[j]?j:N]||"";return IA&&(O&&(IA=IA.replace("$replacement1",O)),Y&&(IA=IA.replace("$replacement2",Y))),IA}catch(h){return console.warn("Error parsing stored error messages:",h),""}}class lo extends Error{constructor(E={}){E.code=E.code||E.errorCode;let{functionName:h="Unknown",code:D,message:N="",data:O="",moreMessage:Y="",errorMessage:j=""}=E;j=(D?Tc(E):"")||j||N;let IA=D?`${h} failed. error: {"message": ${j}, "code": ${D}}`:`${h} failed. error: {"message": ${j}}`;IA=`${IA} ${Y}`,super(),this.code=D,this.errorCode=D,this.errorMessage=j,this.message=IA,this.data=O}}function ds(C,E){var h;if(C&&((h=ZA.store.get("login"))===null||h===void 0?void 0:h.isLoggedIn)!==!0)throw new lo({code:Qa.USER_NOT_LOGGED_IN,functionName:E})}function pB(C,E,h){if(Array.isArray(C))for(let D=0;D{return BA===(mA=D,Object.prototype.toString.call(mA).match(/^\[object (.*)\]$/)[1].toLowerCase());var mA})){for(let mA=0;mA{const{interceptor:N,context:O}=D;N.apply(O,[h])})}(C)}function mn(C,E){kc.push({interceptor:C,context:E})}function Lg(C){const{params:E,auth:h}=C;E&&typeof E=="object"&&Object.assign(fB,E),h&&typeof h=="object"&&Object.assign(MC,h)}function hE(C){return ZA.store.get("commercialConfig").get(C)}class Ir{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(E,h)=>{const D=Date.now();h?(this._stepStartTimes.set(`${E}-${h}`,D),ZA.ssoLog.debug("_executeWorkflowStep",`[Workflow ${E}] Step ${h} started at ${new Date(D).toISOString()}`)):(this._workflowStartTimes.set(E,D),ZA.ssoLog.debug("_executeWorkflowStep",`[Workflow ${E}] started at ${new Date(D).toISOString()}`))},success:(E,h)=>{const D=Date.now();if(h){const N=this._stepStartTimes.get(`${E}-${h}`),O=N?D-N:0;this._stepStartTimes.delete(`${E}-${h}`),ZA.ssoLog.debug("_executeWorkflowStep",`[Workflow ${E}] Step ${h} completed successfully at ${new Date(D).toISOString()} (${O}ms)`)}else{const N=this._workflowStartTimes.get(E),O=N?D-N:0;this._workflowStartTimes.delete(E),ZA.ssoLog.debug("_executeWorkflowStep",`[Workflow ${E}] completed successfully at ${new Date(D).toISOString()} (${O}ms)`)}},error:(E,h,D)=>{const{ssoLog:N,utils:{safeStringify:O}}=ZA,Y=Date.now();if(h){const j=this._stepStartTimes.get(`${E}-${h}`),IA=j?Y-j:0;this._stepStartTimes.delete(`${E}-${h}`),N.error("_executeWorkflowStep",`[Workflow ${E}] Step ${h} failed at ${new Date(Y).toISOString()} (${IA}ms) ${O(D)}`,{error:D})}else{const j=this._workflowStartTimes.get(E),IA=j?Y-j:0;this._workflowStartTimes.delete(E),N.error("_executeWorkflowStep",`[Workflow ${E}] failed at ${new Date(Y).toISOString()} (${IA}ms) ${O(D)}`,{error:D})}}}}static getInstance(){return Ir._instance||(Ir._instance=new Ir),Ir._instance}static setInstance(E){Ir._instance=E}init(){this._initializeWorkflows()}registerWorkflowStep(E,h,D,N){if(!this._handlers.has(E))return void ZA.ssoLog.debug("registerWorkflowStep",`Workflow '${E}' not defined in core`);if(!Gn[E].find(Y=>Y.stepId===h))return void ZA.ssoLog.debug("registerWorkflowStep",`Step '${h}' not defined in workflow '${E}'`);const O=this._handlers.get(E);O.has(h)||O.set(h,N?D.bind(N):D)}executeWorkflow(E,h){return et(this,void 0,void 0,function*(){if(!this._validateWorkflow(E))return;ZA.ssoLog.debug("executeWorkflow",`[Workflow ${E}] Started execution at ${new Date().toISOString()}`);const D=Gn[E],N={},O={cancelled:!1};this._activeWorkflows.set(E,{cancelToken:O});try{const Y=new Map;D.forEach(IA=>{Y.set(IA.stepId,IA)});const j={workflowName:E,pendingSteps:new Set(D.map(IA=>IA.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:Y,stepResults:N,data:h,cancelToken:O};yield new Promise((IA,BA)=>{const mA=()=>{if(O.cancelled)return void IA();this._getExecutableSteps({pendingSteps:j.pendingSteps,completedSteps:j.completedSteps,stepMap:j.stepMap,workflowName:E}).filter(_A=>!j.runningSteps.has(_A)).forEach(_A=>{j.completedSteps.has(_A)||j.runningSteps.has(_A)||this._executeWorkflowStep(_A,j,{onComplete:()=>{if(j.pendingSteps.size===0)return void IA();this._getExecutableSteps({pendingSteps:j.pendingSteps,completedSteps:j.completedSteps,stepMap:j.stepMap,workflowName:E}).filter(xA=>!j.runningSteps.has(xA)).length===0&&j.runningSteps.size===0&&(ZA.ssoLog.debug("executeWorkflow",`Workflow ${E} completed with some steps skipped due to dependency failures`),IA())},onError:BA,onStepComplete:mA})})};mA()}),ZA.ssoLog.debug("executeWorkflow",`[Workflow ${E}] Completed execution at ${new Date().toISOString()}`)}catch(Y){ZA.ssoLog.error("executeWorkflow",`[Workflow ${E}] Failed execution at ${new Date().toISOString()}`,{error:Y})}finally{this._activeWorkflows.delete(E)}})}_executeWorkflowStep(E,h,D){return et(this,void 0,void 0,function*(){const{workflowName:N,runningSteps:O,stepMap:Y,stepResults:j,data:IA}=h;O.add(E),this._logWorkflowExecution(N,E,"start");try{const BA=Y.get(E);let mA=null;BA?.dependency&&(s(BA.dependency)?mA=j[BA.dependency]:Array.isArray(BA.dependency)&&(mA={},BA.dependency.forEach(xA=>{mA[xA]=j[xA]})));const _A=this._handlers.get(N).get(E);if(_A){const xA=yield Promise.resolve(_A({data:IA,result:mA}));j[E]=xA,this._logWorkflowExecution(N,E,"success")}h.completedSteps.add(E)}catch(BA){const mA=`[Workflow].${N}.${E}`,{errorCode:_A,errorInfo:xA=`${mA} failed`}=BA||{},Qe=new lo({functionName:mA,code:_A,message:xA});ZA.ssoLog.error(mA,xA,{error:Qe}),this._logWorkflowExecution(N,E,"error",BA),D.onError(BA)}finally{O.delete(E),h.pendingSteps.delete(E),D.onStepComplete(),D.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Gn).forEach(E=>{this._handlers.has(E)||this._handlers.set(E,new Map)})}_cancelWorkFlow(E){const h=this._activeWorkflows.get(E);if(!h)return;const{cancelToken:D}=h;D.cancelled=!0,this._activeWorkflows.delete(E)}_cancelAllWorkflows(){Object.keys(Gn).forEach(E=>{this._cancelWorkFlow(E)})}_validateWorkflow(E){return Gn[E]?!!this._handlers.get(E):!1}_getExecutableSteps(E){const{pendingSteps:h,completedSteps:D,stepMap:N,workflowName:O}=E;return Array.from(h).filter(Y=>{const j=N.get(Y)||{},{dependency:IA,skipIfDependencyMissing:BA=!0}=j;if(!IA)return!0;if(s(IA))return this._isStepRegistered({workflowName:O,stepId:IA})?D.has(IA):!BA;if(B(IA)){if(IA.filter(mA=>!this._isStepRegistered({workflowName:O,stepId:mA})).length>0&&BA)return!1;for(const mA of IA)if(!D.has(mA))return!1;return!0}return!1})}_isStepRegistered(E){var h;const{workflowName:D,stepId:N}=E;return(h=this._handlers.get(D))===null||h===void 0?void 0:h.has(N)}_logWorkflowExecution(E,h,D,N){this._logHandlers[D](E,h)}}const og=new Map,Ka=({type:C,groupID:E})=>C===vo.GRP_COMMUNITY||`${E}`.startsWith(_a.COMMUNITY)&&!`${E}`.includes(_a.TOPIC),ca=(C="")=>{const E=C.startsWith("GROUP")?C.replace("GROUP",""):C;return E.startsWith(_a.COMMUNITY)&&`${E}`.includes(_a.TOPIC)},pE="openim",wC="million_group_open_http_svc";function Ls(C){return et(this,void 0,void 0,function*(){const{servcmd:E,data:h}=function(O){const{data:Y}=O;return _c(Y)||SC(Y)}(C)?function(O){let{servcmd:Y,data:j}=O;return SC(j)?function(IA){const{servcmd:BA,data:mA}=IA;let{GroupId:_A=""}=mA;const xA=_A;return[_A]=xA.split(_a.TOPIC),{servcmd:rg(BA),data:Object.assign(Object.assign({},mA),{GroupId:_A,TopicId:xA})}}(O):(_c(j)&&(Y=rg(Y)),{servcmd:Y,data:j})}(C):C,D=ZA.common.generateProtocolData({servcmd:E,data:h}),N=`${D.head.seq}${E}`;return ZA.channel.sendPacket(D,{requestId:N,timeout:C.timeout})})}function _c(C){const{Type:E,GroupId:h,GroupIdList:D=[]}=C,N=h||D[0]||"";return Ka({type:E,groupID:N})}function SC(C){const{GroupId:E=""}=C;return ca(E)}function rg(C){if(C.includes(pE))return C;const E=C.split(".")[1];return`${wC}.${E}`}function Wr(){var C;return(C=ZA.store.get("login"))===null||C===void 0?void 0:C.userId}const ng=C=>B(C)||Q(C),hs=(C,E,h,D)=>{if(!ng(C)||!ng(E))return 0;let N=0;const O=Object.keys(E);let Y;for(let j=0,IA=O.length;j{if(r(E))return"";if(C===vo.MSG_TEXT)return E.text||"";const h=Nl[C];return h?DB(h):""},VI=[{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}],BI="im_sdk_config_mgr.fetch_config",fE="im_sdk_config_mgr.push_configv2",Lc="cloud-config",uI=2996,Fg=new class{init(C){this.core=C}};function ja(C){return et(this,void 0,void 0,function*(){const{sdkAppId:E}=Fg.core.store.get("instance")||{},h=Fg.core.helper.generateProtocolData({servcmd:BI,data:{uint32_sdkappid:E,uint64_version:C}}),D=`${h.head.seq}${BI}`;return Fg.core.channel.sendPacket(h,{requestId:D})})}var Fs=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(C){this._core=C;const{notificationCenter:E,InnerEvent:h,helper:D,constants:{WORKFLOW_NAME:N,WORKFLOW_STEP:O},channel:Y}=C;E.subscribeInnerEvent(fE,this._handlePushedConfig,this),D.registerWorkflowStep(N.SYNC_SERVER_INFO_AFTER_LOGIN,O.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),E.subscribeInnerEvent(h.LOGOUT,this._reset,this),E.subscribeInnerEvent(h.DESTROY,this._dispose,this),D.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(VI),Y.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(C){return et(this,void 0,void 0,function*(){var E;const h={code:0,data:""};return C&&(h.data=((E=this._core.store.get("cloudConfig"))===null||E===void 0?void 0:E[C])||""),h})}checkMethodCallOverLimit(C){if(!this._cmdFrequencyLimitMap.has(C))return;if(!this._methodCallFrequencyMap.has(C))return void this._methodCallFrequencyMap.set(C,{startTime:Date.now(),methodCallCounter:1});const{count:E,interval:h}=this._cmdFrequencyLimitMap.get(C);let{startTime:D,methodCallCounter:N}=this._methodCallFrequencyMap.get(C);if(Date.now()-D>1e3*h)this._methodCallFrequencyMap.set(C,{startTime:Date.now(),methodCallCounter:1});else if(N+=1,this._methodCallFrequencyMap.set(C,{startTime:D,methodCallCounter:N}),N>E)throw new this._core.helper.ChatError({code:uI,replacement1:C})}_handlePushedConfig(C){return et(this,void 0,void 0,function*(){const{ssoLog:E,utils:{safeStringify:h}}=this._core;E.info("_handlePushedConfig",h(C)),yield this._updateCloudConfig(C)})}_handleLoginSuccess(){return et(this,void 0,void 0,function*(){const{ssoLog:C,utils:{safeStringify:E}}=this._core;try{if(this._canFetch()){const h=yield ja(this._version);C.info("_fetchCloudConfigIfLogin",E(h)),yield this._updateCloudConfig(h)}this._core.helper.taskScheduler.addTask({id:Lc,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(h){C.debug("_fetchCloudConfigIfLogin",E(h))}})}_fetchCloudConfigIfReady(){return et(this,void 0,void 0,function*(){const{ssoLog:C,utils:{safeStringify:E}}=this._core;if(this._canFetch())try{const h=yield ja(this._version);C.info("_fetchCloudConfigIfReady",E(h)),yield this._updateCloudConfig(h)}catch(h){C.error("_fetchCloudConfigIfReady",E(h))}})}_updateCloudConfig(C){return et(this,void 0,void 0,function*(){const E=this._parseCloudConfig(C);E&&(this._core.store.set("cloudConfig",E),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,E),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:E}}))})}_canFetch(){const{isLoggedIn:C}=this._core.store.get("login")||{};return C&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(C){const{int32_error_code:E,str_error_message:h,str_json_config:D,uint32_expired_time:N,uint32_sdkappid:O,uint64_version:Y}=C;let j=null;if(E===0){if(this._version!==Y)try{j=JSON.parse(D),this._version=Y}catch{}this._expirationTime=Date.now()+1e3*N}else this._expirationTime=E===void 0?Date.now()+36e5:Date.now()+12e4;return j}_parseCmdFreqLimit(){return et(this,void 0,void 0,function*(){var C;let E=(C=yield this.getServerConfig("cmd_frequency_limit"))===null||C===void 0?void 0:C.data;const{isEmpty:h}=this._core.utils;if(!h(E))try{E=JSON.parse(E),this._updateCmdFreqLimitMap(E)}catch(D){console.warn(D)}})}_updateCmdFreqLimitMap(C){C.forEach(E=>{this._cmdFrequencyLimitMap.set(E.cmd,{interval:E.interval,count:E.count})})}_reset(){this._core.helper.taskScheduler.removeTask(Lc),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(VI),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:C,InnerEvent:E}=this._core;C.unSubscribeInnerEvent(fE,this._handlePushedConfig,this),C.unSubscribeInnerEvent(E.LOGOUT,this._reset,this),C.unSubscribeInnerEvent(E.DESTROY,this._dispose,this),this._reset()}};class No{constructor(E=0,h=0){this.high=E,this.low=h}equal(E){return E!==null&&this.low===E.low&&this.high===E.high}toString(){const E=Number(this.high).toString(16);let h=Number(this.low).toString(16);if(h.length<8){let D=8-h.length;for(;D;)h=`0${h}`,D--}return E+h}}const Fc={SEARCH_GRP_SNS:new No(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new No(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new No(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new No(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new No(0,Math.pow(2,6)).toString(),USER_STATUS:new No(0,Math.pow(2,7)).toString(),CONV_MARK:new No(0,Math.pow(2,9)).toString(),CONV_GROUP:new No(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new No(0,Math.pow(2,11)).toString(),MSG_EXT:new No(0,Math.pow(2,13)).toString(),GRP_COUNTER:new No(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new No(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new No(Math.pow(2,7)).toString(),PLUGIN_CS:new No(Math.pow(2,8)).toString(),PLUGIN_PUSH:new No(Math.pow(2,9)).toString(),PLUGIN_BOT:new No(Math.pow(2,10)).toString(),MSG_REACTION:new No(Math.pow(2,16)).toString(),FOLLOW:new No(Math.pow(2,20)).toString()},Ug="CommercialConfig",vC="commercial-config";var mE=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(C){this._core=C;const{helper:E,notificationCenter:h,constants:{WORKFLOW_NAME:D,WORKFLOW_STEP:N,InnerEvent:O}}=C;h.subscribeInnerEvent(O.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),h.subscribeInnerEvent(O.LOGOUT,this._handleLogout,this),h.subscribeInnerEvent(O.DESTROY,this._dispose,this),E.registerWorkflowStep(D.SYNC_SERVER_INFO_AFTER_LOGIN,N.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),C.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),C.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(C){return et(this,void 0,void 0,function*(){const E=parseInt(C,10).toString(2),{length:h}=E;let D,N=!0;for(let O=h-1,Y=0;O>=0;O--,Y++)if(E.charAt(O)==="1"&&(D=Y<32?new No(0,2**Y).toString():new No(2**(Y-32),0).toString(),!this._featureMap.get(D))){N=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${Ug}.isFeatureEnabled decimalNumber:${C} key:${D} ret:${N}`),{code:0,data:{enabled:N}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return et(this,void 0,void 0,function*(){var C;const{ssoLog:E,utils:{safeStringify:h},common:{buildAndSendPacket:D}}=this._core;try{this._isFetching=!0;const N=yield D({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:(C=this._core.store.get("instance"))===null||C===void 0?void 0:C.sdkAppId}});N&&(this._parseCommercialConfig(N),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(N){E.error("_fetchAndParseCommercialConfig",h(N))}finally{this._isFetching=!1}})}_syncCommercialConfig(C){return et(this,void 0,void 0,function*(){const{purchaseBits:E}=C?.data||{};E&&(this._parsePurchaseBits(E),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:vC,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var C;const E=(C=this._core.store.get("login"))===null||C===void 0?void 0:C.isLoggedIn,h=Date.now()>=this._expirationTime;return E&&!this._isFetching&&h}_handlePushedConfig(C){C?.body&&(this._parseCommercialConfig(C.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return et(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(C){const{ssoLog:E}=this._core;if(typeof C!="object")return;const{int32_error_code:h,str_error_message:D,str_purchase_bits:N,uint32_expired_time:O}=C;h===0?(this._parsePurchaseBits(N),this._expirationTime=Date.now()+1e3*O):h===void 0?(E.warn("_parseCommercialConfig",`${Ug}._parseCommercialConfig failed. Invalid message format:`,C),this._expirationTime=Date.now()+36e5):(E.warn("_parseCommercialConfig",`${Ug}._parseCommercialConfig errorCode:${h} errorMessage:${D}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(C){return C&&typeof C=="string"&&C.length>=1&&C.length<=64&&/[01]{1,64}/.test(C)}_parsePurchaseBits(C){const{ssoLog:E,utils:{safeStringify:h}}=this._core;if(this._isValidPurchaseBits(C)){this._purchaseBits=C,this._featureMap.clear(),this._methodKeyMap.clear();let D=null;for(let N=C.length-1,O=0;N>=0;N--,O++)if(D=O<32?new No(0,2**O).toString():new No(2**(O-32),0).toString(),C[N]==="1"){this._featureMap.set(D,!0);const Y=this._getKeyByValue(Fc,D);Y&&this._methodKeyMap.set(Y,!0)}else{this._featureMap.set(D,!1);const Y=this._getKeyByValue(Fc,D);Y&&this._methodKeyMap.set(Y,!1)}}else E.warn("_parsePurchaseBits",`${Ug}.parsePurchaseBits invalid purchases:${h(C)}`)}_getKeyByValue(C,E){const h=Object.entries(C).find(([D,N])=>N===E);return h?h[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(vC),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},Tl=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(C){this._core=C;const{notificationCenter:E,InnerEvent:h,channel:D}=this._core;E.subscribeInnerEvent(h.OVERLOAD_PUSH,this._handleOverLoadPush,this),E.subscribeInnerEvent(h.LOGOUT,this._reset,this),E.subscribeInnerEvent(h.DESTROY,this._dispose,this),D.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(C){if(!this._serverOverloadInfoMap.has(C))return;const{overloadStartTimestamp:E,delaySeconds:h}=this._serverOverloadInfoMap.get(C);if(Date.now()-E<=1e3*h)throw new this._core.helper.ChatError({functionName:C,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(C)}_handleOverLoadPush(C){const{OverLoadServCmd:E,DelaySecs:h}=C;this._serverOverloadInfoMap.set(E,{overloadStartTimestamp:Date.now(),delaySeconds:h})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:C,InnerEvent:E}=this._core;C.unSubscribeInnerEvent(E.OVERLOAD_PUSH,this._handleOverLoadPush,this),C.unSubscribeInnerEvent(E.LOGOUT,this._reset,this),C.unSubscribeInnerEvent(E.DESTROY,this._dispose,this)}},Pu=new class{constructor(){this.name="ConfigCenter"}install(C){Fg.init(C),Fs.install(C),mE.install(C),Tl.install(C)}},yB=new class{constructor(){this.name="ErrorMessage",this._core=null}install(C){return et(this,void 0,void 0,function*(){if(this._core=C,this._canFetch()){const E=yield this._fetchErrorMessage();if(!E)return;const h=this._parseResponse(E);this._saveErrorMessage(h)}})}_canFetch(){const C=this._core.store.getStorage("errorMessage");return!C||this._isExpired(C)}_saveErrorMessage(C){this._core.store.setStorage("errorMessage",{errorMessage:C,errorMessageSavedTime:new Date().getTime()})}_fetchErrorMessage(){return et(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(C){console.error(C)}})}_isExpired(C){if(!C)return!0;const{errorMessageSavedTime:E}=C;return E&&new Date().getTime()-E>=6048e5}_parseResponse(C){if(typeof C=="string"){const E=C.split(`; +`),h={},D=new RegExp(/'/g);for(let N=0;N{var Bi,ri,St;const eo=function(to,Yt){const{From_Account:si,From_AccountHeadurl:zo,From_AccountNick:te,IsNeedReadReceipt:je,MsgBody:dA,MsgClientTime:ut,MsgRandom:Cr,MsgSeq:lt,MsgTimeStamp:Co,SendMsgControl:Jt,SupportMessageExtension:mo,To_Account:Fe,TinyId:Oe,MsgCheckResult:xs,CloudCustomData:Zo,IsPeerRead:ti,MsgFlagBits:_n,MsgVersion:Eg,EventArray:Bo}=to;return{from:si,avatar:zo,nick:te,needReadReceipt:je===1,readReceiptSentByPeer:ti,clientTime:ut,messageFlagBits:_n,random:Cr,sequence:lt,time:Co,messageControlInfo:Jt,isSupportExtension:mo,to:Fe,tinyID:Oe,checkResult:xs,cloudCustomData:Zo,messageVersion:Eg,eventArray:Bo,elements:Yt.message.messageHelper.parseServerPushMessageElement(dA)}}(jt,Se);if(!((St=(ri=(Bi=jt?.EventArray)===null||Bi===void 0?void 0:Bi[0])===null||ri===void 0?void 0:ri.hasOwnProperty)===null||St===void 0)&&St.call(ri,"C2cNotifyMsgArray"))at.push(...function(to){var Yt;const si=[];return(Yt=to.EventArray)===null||Yt===void 0||Yt.forEach(zo=>{var te,je;const{C2cNotifyMsgArray:dA}=zo,ut=(je=(te=dA?.[0])===null||te===void 0?void 0:te.WithdrawC2cMsgNotify)===null||je===void 0?void 0:je.C2cWithdrawInfoArray;Array.isArray(ut)&&si.push(...ut)}),si}(jt));else{const to=Se.message.messageFactory.createMessage(Object.assign(Object.assign({},eo),{conversationType:"C2C",flow:"in"})),{elements:Yt}=eo;to.setElement(Yt),At.push(to)}}),{unreadMessageList:At,revokedMessageList:at}}(IA.MsgList,E);return{syncFlag:IA?.SyncFlag,unreadMessageList:xA,revokedMessageList:Qe,unreadCountList:BA,overflowUnreadCountList:mA,cookie:IA?.Cookie,groupTipList:_A}}catch(IA){console.warn(IA)}})}var Og,QI;(function(C){C[C.START_SYNC=0]="START_SYNC",C[C.SYNCING=1]="SYNCING",C[C.SYNC_COMPLETE=2]="SYNC_COMPLETE"})(Og||(Og={})),function(C){C[C.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",C[C.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(QI||(QI={}));var pi=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie="",this._localConversationIDListBeforeDisconnect=[]}install(C){this._core=C;const{constants:E}=C;C.helper.registerWorkflowStep(E.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,E.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),C.helper.registerWorkflowStep(E.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,E.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),C.helper.registerWorkflowStep(E.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,E.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.SOCKET_DISCONNECTED,this._handleDisconnect,this),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.LOGOUT,this._reset,this),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(C){return et(this,void 0,void 0,function*(){const{isAfterReOnline:E=!1,isAfterNewMessageReceived:h=!1,isAfterLogin:D=!1}=C||{};let N=Og.START_SYNC;const O=[],Y=[],j=[],IA=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:N});){const BA=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:N,syncTriggerEvent:h?QI.NEW_MESSAGE_RECEIVED:QI.LOGIN_SUCCESS});if(!BA)break;const{unreadMessageList:mA=[],revokedMessageList:_A=[],overflowUnreadCountList:xA,unreadCountList:Qe,groupTipList:Re}=BA;if(this._cookie=BA?.cookie||"",N=BA?.syncFlag,this._parseAndSaveUnreadMessageList(mA),j.push(..._A),this._updateConversationUnreadOptions({unreadCountList:Qe,overflowUnreadCountList:xA,conversationUpdateFieldList:O}),Array.isArray(Re)&&Y.push(...Re),E){const{messages:Se}=this._handleNewMessageList(mA);IA.push(...Se)}}return E?{conversationUpdateFieldList:O,revokedMessageList:j,unreadMessageMap:this._unreadDBMessageMap,groupTipList:Y,messages:IA,isUnreadC2CMessage:!0}:{conversationUpdateFieldList:O,isInstantMessage:!D,isUnreadC2CMessage:!0,revokedMessageList:j,unreadMessageMap:this._unreadDBMessageMap,groupTipList:Y}})}_syncUnreadDBMessageAfterLogin(){return et(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(C){return et(this,void 0,void 0,function*(){if(C.data.Flag===1)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(C){const{unreadCountList:E,overflowUnreadCountList:h,conversationUpdateFieldList:D}=C,{constants:{OuterConstant:{CONV_C2C:N,CONV_SYSTEM:O}}}=this._core;E?.forEach(Y=>{const{From_Account:j,UnreadCount:IA}=Y;if(j!==O){const BA=D.find(({conversationID:mA})=>mA===`${N}${j}`);BA?BA.unreadCount=IA:D.push({conversationID:`${N}${j}`,unreadCount:IA,type:N})}}),h?.forEach(Y=>{const{From_Account:j,LastMsgTime:IA}=Y;j!==O&&(D.find(({conversationID:BA})=>BA===`${N}${j}`)||D.push({conversationID:`${N}${j}`,type:N,lastMsgTime:IA}))})}_syncUnreadDBMessageAfterReOnline(){return et(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(C){var E;const{messageDataHandler:h}=this._core.message||{},D=(E=this._core.store.get("login"))===null||E===void 0?void 0:E.userId,{from:N,nick:O,avatar:Y,conversationID:j=""}=C;if(N!==D){const IA=h.getLatestMsgSentByPeer(j);if(IA){const{nick:BA,avatar:mA}=IA;O&&Y?O===BA&&Y===mA||h.updateNickAndAvatarOfSentMessage({conversationID:j,latestNick:O,latestAvatar:Y,isSentByMe:!1}):(C.nick=BA,C.avatar=mA)}}else{const IA=h.getLatestMsgSentByMe(j);!IA||O===IA.nick&&Y===IA.avatar||h.updateNickAndAvatarOfSentMessage({conversationID:j,latestNick:O,latestAvatar:Y,isSentByMe:!0})}}_handleNewMessageList(C){const{messageDataHandler:E}=this._core.message||{},h=new Map,D=[];return C.forEach(N=>{this._updateMessageProfile(N);let O=N.isModified===1;if(E.isMessageSentByCurrentInstance(N)?N.isModified=O:O=!1,N.isOnlineMessage())N._onlineOnlyFlag=!0,E.isMessageSentByCurrentInstance(N)||D.push(N);else if(this._shouldStoreUnreadMessage(N)){if(E.storeConversationMessage(N)){const{conversationID:Y,conversationType:j,conversationSubType:IA,flow:BA,_isExcludedFromUnreadCount:mA,_isExcludedFromLastMessage:_A}=N,xA=_A?"":N;h.has(Y)?(h.get(Y).lastMessage=xA,BA==="in"&&(mA||h.get(Y).unreadCount++)):h.set(Y,{conversationID:Y,type:j,subType:IA,unreadCount:mA||BA!=="in"?0:1,lastMessage:xA})}E.isMessageSentByCurrentInstance(N)&&!O||D.push(N)}}),{messages:D,conversationOptions:h}}_shouldStoreUnreadMessage(C){var E;const{conversationID:h}=C,{message:D,appStore:N,utils:{isEmpty:O}}=this._core||{},Y=Array.from(((E=N.conversationStore.getConversationMap())===null||E===void 0?void 0:E.keys())||[]),j=this._getLocalLastMessageTime(h);return!D.messageDataHandler.isInMessageList(C)&&Y.includes(h)&&this._localConversationIDListBeforeDisconnect.includes(h)&&!O(j)}_fetchUnreadDBMessage(C){return et(this,void 0,void 0,function*(){const{ssoLog:E,utils:{safeStringify:h}}=this._core;try{E.debug("_fetchUnreadDBMessage",`unread-message-synchronizer._fetchUnreadDBMessage options:${h(C)}`);const N=yield Ju(C,this._core);if(!N)return null;const{syncFlag:O,unreadMessageList:Y,revokedMessageList:j,cookie:IA,unreadCountList:BA,overflowUnreadCountList:mA,groupTipList:_A}=N;return this._parseAndSaveUnreadMessageList(Y),{syncFlag:O,cookie:IA,unreadMessageList:Y,revokedMessageList:j,unreadCountList:BA,overflowUnreadCountList:mA,groupTipList:_A}}catch(D){console.log(D)}})}_canContinueSync({cookie:C,syncFlag:E}){var h;return E===Og.START_SYNC||E===Og.SYNCING&&!(!((h=this._core)===null||h===void 0)&&h.helper.isEmpty(C))}_parseAndSaveUnreadMessageList(C){C.forEach(E=>{const{ID:h}=E;this._unreadDBMessageMap.set(h,E)})}_handleDisconnect(){var C;const{appStore:E}=this._core;this._localConversationIDListBeforeDisconnect=Array.from(((C=E.conversationStore.getConversationMap())===null||C===void 0?void 0:C.keys())||[])}_getLocalLastMessageTime(C){const{message:E}=this._core,h=E.messageDataHandler.getLocalMessageList(C),D=h[h.length-1];return D?.time}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var C,E;(C=this._core)===null||C===void 0||C.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(E=this._core)===null||E===void 0||E.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},RB=new class{init(C){var E;this._core=C,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.DESTROY,this._dispose,this),document?.addEventListener("visibilitychange",this._visibilityChangeHandler),(E=this._core)===null||E===void 0||E.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var C,E;const h=document?.visibilityState==="visible";(C=this._core)===null||C===void 0||C.store.set("activityMonitor",{isActive:h}),(E=this._core)===null||E===void 0||E.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:h})}_reset(){var C;(C=this._core)===null||C===void 0||C.store.clear("activityMonitor")}_dispose(){document?.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:C,InnerEvent:E}=this._core;C.unSubscribeInnerEvent(E.DESTROY,this._dispose,this),this._reset()}},Gl=new class{init(C){var E;this._core=C,this._bindAppActivityEvent(),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.DESTROY,this._dispose,this),(E=this._core)===null||E===void 0||E.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var C,E,h,D,N;const{MINI_APP_NAMESPACE:O,IN_TT_MINI_GAME:Y,IN_WX_MINI_GAME:j}=((C=this._core)===null||C===void 0?void 0:C.utils)||{};Y||j?((E=O?.onShow)===null||E===void 0||E.call(O,()=>{var IA,BA;(IA=this._core)===null||IA===void 0||IA.store.set("activityMonitor",{isActive:!0}),(BA=this._core)===null||BA===void 0||BA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(h=O?.onHide)===null||h===void 0||h.call(O,()=>{var IA,BA;(IA=this._core)===null||IA===void 0||IA.store.set("activityMonitor",{isActive:!1}),(BA=this._core)===null||BA===void 0||BA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):((D=O?.onAppShow)===null||D===void 0||D.call(O,()=>{var IA,BA;(IA=this._core)===null||IA===void 0||IA.store.set("activityMonitor",{isActive:!0}),(BA=this._core)===null||BA===void 0||BA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(N=O?.onAppHide)===null||N===void 0||N.call(O,()=>{var IA,BA;(IA=this._core)===null||IA===void 0||IA.store.set("activityMonitor",{isActive:!1}),(BA=this._core)===null||BA===void 0||BA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var C;(C=this._core)===null||C===void 0||C.store.clear("activityMonitor")}_dispose(){const{notificationCenter:C,InnerEvent:E}=this._core;C.unSubscribeInnerEvent(E.DESTROY,this._dispose,this),this._reset()}},kl=new class{init(C){const{IN_MINI_APP:E,IN_WX_MINI_PLUGIN:h}=C.helper;h||(E?Gl.init(C):RB.init(C))}};const NC="none",_l="online";var xg=new class{init(C){this._core=C,this._activateNetworkMonitoring(),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return et(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(C){var E,h;const{isConnected:D,networkType:N}=C;(E=this._core)===null||E===void 0||E.store.set("netWorkMonitor",{isNetworkOnline:D,networkType:N}),(h=this._core)===null||h===void 0||h.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:D,networkType:N})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:_l})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:NC})}_reset(){var C;this._deactivateNetworkMonitoring(),(C=this._core)===null||C===void 0||C.store.clear("netWorkMonitor")}_dispose(){var C,E;(C=this._core)===null||C===void 0||C.notificationCenter.unSubscribeInnerEvent((E=this._core)===null||E===void 0?void 0:E.InnerEvent.DESTROY,this._dispose,this),this._reset()}},qI=new class{init(C){this._core=C,this._activateNetworkMonitoring(),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return et(this,void 0,void 0,function*(){try{const{utils:{MINI_APP_NAMESPACE:C}}=this._core;this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),C.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(C){console.error(C)}})}_deactivateNetworkMonitoring(){if(this._mpNetworkStatusCallback!==null){const{utils:{MINI_APP_NAMESPACE:C}}=this._core;C.offNetworkStatusChange&&C.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null}}_onNetworkStatusChange(C){var E,h;const{isConnected:D,networkType:N}=C;(E=this._core)===null||E===void 0||E.store.set("netWorkMonitor",{isNetworkOnline:D,networkType:N}),(h=this._core)===null||h===void 0||h.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:D,networkType:N})}_reset(){var C;this._deactivateNetworkMonitoring(),(C=this._core)===null||C===void 0||C.store.clear("netWorkMonitor")}_dispose(){var C,E;(C=this._core)===null||C===void 0||C.notificationCenter.unSubscribeInnerEvent((E=this._core)===null||E===void 0?void 0:E.InnerEvent.DESTROY,this._dispose,this),this._reset()}},DE=new class{init(C){const{IN_MINI_APP:E}=C.utils;E?qI.init(C):xg.init(C)}},yE=new class{constructor(){this.name="SystemStateMonitor"}install(C){kl.init(C),DE.init(C)}};const MB=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.*"]),Rn="tui_room_svr.*";var ps=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=MB}install(C){this._core=C;const{notificationCenter:E,InnerEvent:h,helper:D}=C;E.subscribeInnerEvent(h.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),E.subscribeInnerEvent(h.LOGOUT,this._reset,this),E.subscribeInnerEvent(h.DESTROY,this._dispose,this),E.subscribeInnerEvent("im_open_push.msg_push",E.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),D.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),D.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(C){return et(this,void 0,void 0,function*(){const E="transferBusinessCommand";try{const{serviceCommand:h=Rn}=C||{};if(!this._isValidTransferredCommand(h))throw new this._core.helper.ChatError({code:2995,functionName:E});return{code:0,data:(yield function(N,O){return et(this,void 0,void 0,function*(){const{helper:Y,channel:j}=O,{serviceCommand:IA=Rn,data:BA}=N||{};let mA={};try{mA=typeof BA=="string"?JSON.parse(BA):BA}catch(Qe){console.warn(Qe)}const _A=Y.generateProtocolData({servcmd:IA,data:mA}),xA=`${_A.head.seq}${IA}`;return j.sendPacket(_A,{requestId:xA,shouldRejectOnError:!1})})}(C,this._core))||{}}}catch(h){throw console.warn(h),new this._core.helper.ChatError({code:h?.errorCode,message:h?.errorInfo,data:{},functionName:E})}})}_onCloudConfigUpdate(C={}){try{if(typeof C.rtc_cmd!="string")return;const E=JSON.parse(C.rtc_cmd);Array.isArray(E)&&(this._transferredCommands=new Set([...this._transferredCommands,...E]))}catch(E){console.log(E)}}_isValidTransferredCommand(C=""){const E=`${C?.split(".")[0]}.*`;return this._transferredCommands.has(E)}_onServerPushBusinessCommand(C){const{OuterEvent:E,notificationCenter:h}=this._core,{MsgContent:D}=C||{},{ROOM_CUSTOM_DATA_RECEIVED:N}=E;h.emitOuterEvent(N,{name:N,data:D})}_reset(){this._transferredCommands=MB}_dispose(){const{notificationCenter:C,InnerEvent:E}=this._core;this._reset(),C.unSubscribeInnerEvent(E.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),C.unSubscribeInnerEvent(E.LOGOUT,this._reset,this),C.unSubscribeInnerEvent(E.DESTROY,this._dispose,this),C.unSubscribeInnerEvent("im_open_push.msg_push",C.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const ag=new class{init(C){this.core=C}};function wB(C){return et(this,void 0,void 0,function*(){var E;const{message:h,user:D,appStore:N,constants:{OuterConstant:O}}=ag.core,Y=N.conversationStore.getConversationMap();if(Y.has(C)){const IA=(E=Y.get(C))===null||E===void 0?void 0:E.userProfile;if(IA&&C.startsWith(O.CONV_C2C)){const{avatar:BA,nick:mA}=IA;ag.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:C,latestAvatar:BA,latestNick:mA,isSentByMe:!1})}}const{data:j}=(yield D.userProfile.getMyProfile())||{};if(j){const{avatar:IA,nick:BA}=j;h.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:C,latestAvatar:IA,latestNick:BA,isSentByMe:!0})}})}function KI(C){return et(this,void 0,void 0,function*(){const E=C.map(h=>h.revoker);try{const h=yield function(D){return et(this,void 0,void 0,function*(){var N,O;const Y=yield(N=ag.core.user.userProfile)===null||N===void 0?void 0:N.getUserProfile({userIDList:D});return Y?.data?(O=Y.data)===null||O===void 0?void 0:O.reduce((j,{userID:IA,nick:BA,avatar:mA})=>(j[IA]={nick:BA||"",avatar:mA||""},j),{}):null})}(E);h&&C.forEach(D=>{const{revoker:N}=D;h[N]&&(D.revokerInfo.nick=h[N].nick||"",D.revokerInfo.avatar=h[N].avatar||"",D.revokerInfo.userID=N)})}catch(h){console.debug(h)}})}const SB=1,Wn=2,RE=20,wr=2500,vB=1,Yg=300;function TC(C){return et(this,void 0,void 0,function*(){var E,h;const{appStore:D,utils:{isEmpty:N},common:{getCurrentUserID:O},notificationCenter:Y,OuterEvent:j,OuterConstant:{CONV_C2C:IA}}=ag.core,{messageList:BA,conversationID:mA}=C,_A=D.conversationStore.getConversationMap();let xA=(E=_A.get(mA))===null||E===void 0?void 0:E.peerReadTime;if(!xA){const Re=mA.replace(IA,""),Se=yield function(At){return et(this,void 0,void 0,function*(){const at={To_Account:At};return ag.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:at})})}([Re]);if(Se){const{ReadTime:At}=Se;xA=At?.[0],_A.has(mA)&&(_A.get(mA).peerReadTime=xA)}}if(_A.has(mA)){const Re=(h=_A.get(mA))===null||h===void 0?void 0:h.lastMessage;N(Re)||Re.fromAccount===O()&&Re.lastTime<=xA&&!Re.isPeerRead&&(Re.isPeerRead=!0,D.conversationStore.updateConversation(mA,{lastMessage:Re}))}const Qe=[];BA.forEach(Re=>{Re.time<=xA&&!Re.isPeerRead&&Re.flow==="out"&&(Re.isPeerRead=!0,Qe.push(Re))}),Qe.length>0&&Y.emitOuterEvent(j.MESSAGE_READ_BY_PEER,{name:j.MESSAGE_READ_BY_PEER,data:Qe})})}var jI=new class{init(C){this._core=C,C.helper.registerApi({apiName:"getMessageList",context:this}),C.helper.registerApi({apiName:"getMessageListHopping",context:this}),C.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(C){return et(this,void 0,void 0,function*(){try{const{message:E,OuterConstant:{Direction:h,CONV_C2C:D,CONV_GROUP:N},InnerEvent:{HISTORY_MESSAGE_FETCHED:O},notificationCenter:Y}=this._core,{conversationID:j,nextReqMessageID:IA}=C,BA=RE;if(j==="@TIM#SYSTEM")return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const mA=this._getAvailableLocalMessagesCount({conversationID:j,nextReqMessageID:IA});if(this._needFetchHistoryMessageList({conversationID:j,availableLocalMessagesCount:mA,targetCount:BA})){let _A=null;if(j.startsWith(N)?_A=yield E.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:j,sequence:Number(IA),count:BA,direction:h.FORWARD,shouldMarkCompleted:!0}):j.startsWith(D)&&(_A=yield E.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:j,messageID:IA,count:BA,direction:h.FORWARD,shouldMarkCompleted:!0})),_A){const{nextReqMessageIDFromServer:xA,hasNoMoreHistoryMessage:Qe,messageList:Re}=_A,Se=E.messageDataHandler.prependLocalMessageList({messageList:Re,conversationID:j});(function(ri){const{appStore:St,message:eo,OuterConstant:to}=ag.core,Yt=St.conversationStore.getConversation(ri),si=eo.messageDataHandler.getLocalMessageList(ri);if(!Yt||si.length===0||ri===to.CONV_SYSTEM)return;const zo=[];for(let je=0;jedA.isRevoked).length;te=zo.length-Yt.unreadCount-je}else te=zo.length-Yt.unreadCount;for(let je=0;jeri.isRevoked);yield KI(at),Y.emitInnerEvent(O,Se);const jt={nextReqMessageID:Qe?"":String(xA),messageList:At,isCompleted:Qe},Bi=At.map(ri=>ri.sequence);return{code:0,data:jt,successLog:{message:`conversationID: ${j} nextReqMessageID: ${IA} availableLocalMessagesCount: ${mA} sequenceList: ${JSON.stringify(Bi)}`}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:j,nextReqMessageID:IA,count:BA}),successLog:{message:`conversationID: ${j} nextReqMessageID: ${IA} availableLocalMessagesCount: ${mA}}`}}}catch(E){const{code:h,message:D}=E||{};throw new this._core.helper.ChatError({code:h,message:D,moreMessage:`options: ${this._core.utils.safeStringify(C)}`})}})}getMessageListHopping(C){return et(this,void 0,void 0,function*(){var E,h;const{OuterConstant:{Direction:D,CONV_C2C:N,CONV_GROUP:O},utils:{safeStringify:Y}}=this._core,{conversationID:j,sequence:IA,time:BA,direction:mA=D.FORWARD}=C,{utils:{isEmpty:_A},message:xA,notificationCenter:Qe,InnerEvent:{HISTORY_MESSAGE_FETCHED:Re}}=this._core;if(![D.BACKWARD,D.FORWARD].includes(mA))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${Y(C)}`});let{count:Se=RE}=C;Se=Se>RE?RE:Se;let At=null;if(j.startsWith(O)){if(At=yield xA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:j,sequence:IA,count:Se,direction:mA}),At){const{nextReqMessageIDFromServer:at,hasNoMoreHistoryMessage:jt,messageList:Bi,invisibleSequenceList:ri}=At;if(this._core.message.messageDataHandler.storeSparseMessageList(Bi),Qe.emitInnerEvent(Re,Bi),mA===D.FORWARD){const St=jt&&at<1;return{code:0,data:{messageList:Bi,isCompleted:St,nextMessageSeq:St?"":at}}}if(mA===D.BACKWARD){if(_A(Bi)&&_A(ri))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const St=((E=Bi?.[Bi.length-1])===null||E===void 0?void 0:E.sequence)||0,eo=((h=ri?.[ri.length-1])===null||h===void 0?void 0:h.sequence)||0;return{code:0,data:{messageList:Bi.filter(to=>to.sequence>=IA),isCompleted:!jt,nextMessageSeq:jt?Math.max(St,eo)+1:""}}}return{code:0,data:At}}}else if(j.startsWith(N)&&(At=yield xA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:j,count:Se+1,time:BA,direction:mA}),At)){const{messageList:at,lastMessageTime:jt,hasNoMoreHistoryMessage:Bi}=At;return Qe.emitInnerEvent(Re,at),Bi||(mA===D.FORWARD?at.shift():at.pop()),xA.messageDataHandler.storeSparseMessageList(at),yield TC({messageList:at,conversationID:j}),{code:0,data:{messageList:at,isCompleted:Bi,nextMessageTime:Bi?"":jt}}}})}clearHistoryMessage(C){return et(this,void 0,void 0,function*(){var E;const{appStore:h,common:{ChatError:D,getCurrentUserID:N},OuterConstant:{CONV_C2C:O,CONV_GROUP:Y},apiMap:j,message:IA}=this._core,BA=h.conversationStore.getConversation(C);if(!BA)throw new D({code:wr});const mA={fromAccount:N()},{type:_A}=BA;_A===O?(mA.type=SB,mA.toAccount=C.replace(O,"")):_A===Y&&(mA.type=Wn,mA.toGroupID=C.replace(Y,""));try{return yield(E=j?.setMessageRead)===null||E===void 0?void 0:E.call(j,{conversationID:C}),(yield function(Qe){return et(this,void 0,void 0,function*(){const{fromAccount:Re,type:Se,toAccount:At,toGroupID:at}=Qe,jt={From_Account:Re,Type:Se,To_Account:At,ToGroupid:at};return ag.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:jt})})}(mA))&&(IA.messageDataHandler.deleteConversationMessageList(C),IA.messageHistory.completedHistoryConversations.delete(C),IA.messageHistory.clearHistoryMessageListFetchAnchors(C),this._updateConversationLastMessage(C)),{code:0,data:{conversationID:C},successLog:{message:`convID:${C}`}}}catch(xA){const{errorCode:Qe}=xA;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:Qe,moreMessage:`convID:${C}`})}})}_updateConversationLastMessage(C){const{appStore:E}=this._core;E.conversationStore.updateConversation(C,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:C,nextReqMessageID:E}){const{OuterConstant:{CONV_C2C:h,CONV_GROUP:D}}=this._core,N=this._core.message.messageDataHandler.getLocalMessageList(C),{length:O}=N;if(!E)return O;let Y=-1;return C?.startsWith(h)?Y=N.findIndex(j=>j.ID===E):C?.startsWith(D)&&(Y=N.findIndex(j=>E.includes("-")?j.ID===E:String(j.sequence)===E)),Y===-1?0:Y}_needFetchHistoryMessageList({conversationID:C,availableLocalMessagesCount:E,targetCount:h}){const{message:D}=this._core;return EE.startsWith(N)?xA.ID===h:String(xA.sequence)===h),mA=_A>D?_A-D:0,IA=_A):mA=j>D?j-D:0,BA.messageList=Y.slice(mA,_A),BA.isCompleted=IA<=D&&O.messageHistory.completedHistoryConversations.has(E),BA.isCompleted?BA.nextReqMessageID="":BA.nextReqMessageID=this._generateNextReqMessageID({conversationID:E,targetIndex:mA}),E.startsWith(N)&&(yield wB(E),yield TC({messageList:BA.messageList,conversationID:E})),BA})}_generateNextReqMessageID({conversationID:C,targetIndex:E}){const h=this._core.message.messageDataHandler.getLocalMessageList(C);return C.startsWith("C2C")?h[E].ID:String(h[E].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(C){this._core=C;const{common:{workflowManager:E},constants:{WORKFLOW_NAME:h,WORKFLOW_STEP:D,InnerEvent:N}}=C;E.registerWorkflowStep(h.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),E.registerWorkflowStep(h.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.C2C_HISTORY_MESSAGE_RECOVER,this._syncC2COfflineMessage,this),C.notificationCenter.subscribeInnerEvent(N.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncGroupOfflineMessage(C){const{conversationList:E}=C?.result||{},{OuterConstant:h,utils:{isArray:D}}=this._core;if(D(E)){const N=E.filter(O=>O.type===h.CONV_GROUP&&O.groupProfile.type!==h.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(N)}}_recoverGroupHistoryMessage(C){return et(this,void 0,void 0,function*(){const{OuterConstant:E}=this._core,h=[],D=[];return yield Promise.all(C?.map(N=>et(this,void 0,void 0,function*(){const{groupProfile:{groupID:O}={},lastMessage:{lastSequence:Y}={}}=N,j=`${E.CONV_GROUP}${O}`;let IA=this._getLocalLastMessageSequence(j);this._shouldRecoverHistory({localLastMessageSequence:IA,serverLastMessageSequence:Y})&&(yield this._recoverGroupHistoryForConversation({conversationID:j,localLastMessageSequence:IA,serverLastMessageSequence:Y,groupTipList:D})),h.push(j.replace(E.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:h,groupTipList:D}})}_recoverGroupHistoryForConversation(C){return et(this,arguments,void 0,function*({conversationID:E,localLastMessageSequence:h,serverLastMessageSequence:D,groupTipList:N}){try{const{utils:{isArray:O,isObject:Y,isEmpty:j},OuterEvent:IA,OuterConstant:BA,notificationCenter:mA,message:_A,appStore:xA,common:{getMessagePreviewText:Qe,buildLastMessage:Re}}=this._core,Se=D-h,At=Math.min(20,Se),at={},jt=yield _A.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:E,sequence:h+At,direction:BA.Direction.FORWARD,count:At}),{nextReqMessageIDFromServer:Bi,hasNoMoreHistoryMessage:ri,messageList:St,serverGroupTipList:eo}=jt;O(eo)&&N.push(...eo);const to=ri&&Bi<0,Yt=[];if(O(St)&&(St.forEach(si=>{_A.messageReceiver.groupMessageReceiver.updateMessageProfile(si),si.from===BA.CONV_SYSTEM&&(si.isSystemMessage=!1),_A.messageDataHandler.storeConversationMessage(si)&&!j(si.payload)&&(Yt.push(si),si._isExcludedFromLastMessage||(at.lastMessage=Re(si)))}),Yt.length>0&&mA.emitOuterEvent(IA.MESSAGE_RECEIVED,{name:IA.MESSAGE_RECEIVED,data:Yt})),!to&&St.length>0){const si=St[St.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:E,localLastMessageSequence:si,serverLastMessageSequence:D,groupTipList:N})}Y(at.lastMessage)&&(at.lastMessage.messageForShow=Qe(at.lastMessage.type,at.lastMessage.payload),xA.conversationStore.updateConversation(E,at))}catch(O){this._core.ssoLog.error("_recoverGroupHistoryForConversation",`Recovery failed for conversation:${E}`,{error:O})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:C}=this._core,E=C.messageDataHandler.getContinuousMessagesByConversation();for(const[h,D]of E){const N=Array.from(D.values());if(N?.length>0){const O=N[N.length-1];h.startsWith("C2C")?this._lastMessageTimeMapOnDisconnect.set(h,O.time):h.startsWith("GROUP")&&this._lastMessageSequenceMapOnDisconnect.set(h,O.sequence)}}}_getLocalLastMessageSequence(C){const{message:E}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(C))return this._lastMessageSequenceMapOnDisconnect.get(C);const h=E.messageDataHandler.getLocalMessageList(C),D=h[h.length-1];return D?.sequence}_shouldRecoverHistory(C){const{localLastMessageSequence:E,serverLastMessageSequence:h}=C;if(typeof E!="number"||typeof h!="number")return!1;const D=h-E;return h!==0&&E>0&&D>=vB&&D{O.type===h.CONV_C2C&&N.push(O)}),this._recoverC2CHistoryMessage(N)}}_recoverC2CHistoryMessage(C){return et(this,void 0,void 0,function*(){yield Promise.all(C?.map(E=>et(this,void 0,void 0,function*(){const{conversationID:h,lastMessage:{lastTime:D}={}}=E,N=this._getLocalLastMessageTime(h);this._shouldRecoverC2CHistory({localLastMessageTime:N,serverLastMessageTime:D})&&(yield this._recoverHistoryForC2CConversation({conversationID:h,localLastMessageTime:N,serverLastMessageTime:D}))})))})}_shouldRecoverC2CHistory(C){const{localLastMessageTime:E,serverLastMessageTime:h}=C,D=h-E;return E>0&&D>=1&&D<=600}_recoverHistoryForC2CConversation(C){return et(this,void 0,void 0,function*(){var E;const{conversationID:h,localLastMessageTime:D,serverLastMessageTime:N}=C,{utils:{isArray:O,isObject:Y,isEmpty:j,safeStringify:IA},OuterEvent:BA,OuterConstant:mA,notificationCenter:_A,message:xA,appStore:Qe,common:{getMessagePreviewText:Re,buildLastMessage:Se}}=this._core;try{const At={},at=yield xA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:h,direction:mA.Direction.BACKWARD,time:D,count:20});if(j(at))return;const{hasNoMoreHistoryMessage:jt,messageList:Bi}=at,ri=[];O(Bi)&&(Bi.forEach(eo=>{xA.messageDataHandler.storeConversationMessage(eo)&&!j(eo.payload)&&(ri.push(eo),eo._isExcludedFromLastMessage||(At.lastMessage=Se(eo)))}),ri.length>0&&_A.emitOuterEvent(BA.MESSAGE_RECEIVED,{name:BA.MESSAGE_RECEIVED,data:ri}));const St=(E=Bi[Bi.length-1])===null||E===void 0?void 0:E.time;!jt&&St>N&&(yield this._recoverHistoryForC2CConversation({conversationID:h,localLastMessageTime:St,serverLastMessageTime:N})),Y(At.lastMessage)&&(At.lastMessage.messageForShow=Re(At.lastMessage.type,At.lastMessage.payload),Qe.conversationStore.updateConversation(h,At))}catch(At){this._core.ssoLog.error("_recoverHistoryForC2CConversation",`Recovery failed for conversation:${h} error: ${IA(At)}`)}})}_getLocalLastMessageTime(C){const{message:E}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(C))return this._lastMessageTimeMapOnDisconnect.get(C);const h=E.messageDataHandler.getLocalMessageList(C),D=h[h.length-1];return D?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},NB=new class{constructor(){this.name="HistoryMessage"}install(C){this._core=C,ag.init(C),jI.init(C),ha.init(C),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.LOGOUT,this._reset,this),C.notificationCenter.subscribeInnerEvent(C.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:C,InnerEvent:E}=this._core;C.unSubscribeInnerEvent(E.LOGOUT,this._reset,this),C.unSubscribeInnerEvent(E.DESTROY,this.dispose,this),ha.dispose()}_reset(){ha.reset()}},pa=new class{init(C){this.core=C}},sg=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(C){const{helper:{registerExperimentalAPI:E}}=C;this._core=C,E("reportModalView",this),E("reportTUIFeatureUsage",this),E("reportRoomEngineEvent",this)}reportModalView(C){const{ssoLog:E,utils:{safeStringify:h,isString:D}}=this._core;try{if(!D(C))throw new Error("reportModalView data is not a string");E.createSSOLogData({method:"reportModalView",message:C,eventType:30}).end(!0)}catch(N){E.debug(`reportModalView Report failed: ${h(N)}`)}}reportTUIFeatureUsage(C){const{ssoLog:E,utils:{safeStringify:h,isEmpty:D}}=this._core,{atomicStoreID:N}=C;try{D(N)||this._reportedAtomicStoreIDs.has(N)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${C.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:N}),this._reportedAtomicStoreIDs.add(N))}catch(O){E.debug(`reportTUIFeatureUsage Report failed: ${h(O)}`)}}reportRoomEngineEvent(C){const{utils:{safeStringify:E},ssoLog:h}=this._core;try{h.debug(`reportRoomEngineEvent Report: ${E(C)}`);const{eventId:D,eventCode:N,eventResult:O,eventMessage:Y,moreMessage:j,extensionMessage:IA}=C;h.createSSOLogData({method:IA,code:D,message:Y,eventType:30,costTime:N,uiPlatform:O,moreMessage:j}).end(!0)}catch(D){h.debug(`reportRoomEngineEvent Report failed: ${E(D)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},GC=new class{constructor(){this.name="DataReport"}install(C){this._core=C;const{notificationCenter:E,InnerEvent:{LOGOUT:h,DESTROY:D}}=C;pa.init(C),sg.init(C),E.subscribeInnerEvent(h,this._reset,this),E.subscribeInnerEvent(D,this._dispose,this)}_reset(){sg.reset()}_dispose(){const{notificationCenter:C,InnerEvent:{LOGOUT:E,DESTROY:h}}=this._core;C.unSubscribeInnerEvent(E,this._reset,this),C.unSubscribeInnerEvent(h,this._dispose,this),sg.dispose()}};let bl=uE.STANDARD,Mn=[];bl=uE.BASIC,Mn=[yB,Pu,pi,yE,ps,NB,GC];function WI(C,E){const{operationType:h,memberInfoList:D,operatorInfo:N}=C||{};let O={};if($r(D)?$r(N)||(O=N):h!==Qs.JOINED&&h!==Qs.KICKED&&h!==Qs.ADMIN_SET&&h!==Qs.ADMIN_CANCELED||(O=Object.assign({},D[0])),!$r(O)){const{nick:Y="",avatar:j=""}=O;E.nick=Y,E.avatar=j}}const ME=C=>({lastTime:C?.time||C?.lastTime||0,lastSequence:C?.sequence||C?.lastSequence||0,fromAccount:C?.from||C?.fromAccount||"",messageForShow:bc(C?.type,C?.payload),payload:C?.payload||null,type:C?.type||"",isRevoked:C?.isRevoked||!1,cloudCustomData:C?.cloudCustomData||"",onlineOnlyFlag:C?._onlineOnlyFlag||!1,nick:C?.nick||"",nameCard:C?.nameCard||"",version:C?.version||0,isPeerRead:C?.isPeerRead||!1,revoker:C?.revoker||null});var dI=Object.freeze({__proto__:null,ChatError:lo,WorkflowManager:Ir,buildAndSendPacket:Ls,buildLastMessage:ME,get builtInPlugins(){return Mn},checkBusinessCapabilityBits:hE,deepMerge:hs,getCurrentUserID:Wr,getErrorMessage:Tc,getMessagePreviewText:bc,isC2CConv:C=>s(C)&&C.slice(0,3)===us.CONV_C2C,isCommunity:Ka,isGroupConv:C=>s(C)&&C.slice(0,5)===us.CONV_GROUP,isInternational:vl,isTopic:ca,isUnlimitedAVChatRoom:function(){var C;return!!(!((C=ZA.store.get("instance"))===null||C===void 0)&&C.unlimitedAVChatRoom)},liteChatInstanceMap:og,registerInterceptor:mn,registerValidateConfig:Lg,requireAuth:ds,get sdkEdition(){return bl},setGroupTipsUserInfo:WI,t:DB,updateGroupAtInfo:(C,E)=>{const{CONV_AT_ME:h,CONV_AT_ALL:D,CONV_AT_ALL_AT_ME:N}=vo;if(function(j,IA){const{CONV_AT_ME:BA,CONV_AT_ALL:mA,CONV_AT_ALL_AT_ME:_A}=vo,{groupID:xA,sequence:Qe}=j;let Re=!1;return Ka({groupID:xA})&&IA.forEach(Se=>{Se.messageSequence===Qe&&(Se.atTypeArray.includes(BA)&&j.groupAtType.includes(mA)&&(Se.atTypeArray=[_A]),Se.atTypeArray.includes(mA)&&j.groupAtType.includes(BA)&&(Se.atTypeArray=[_A],Se.__random=j.__random,Se.__sequence=j.__sequence),Re=!0)}),Re}(C,E))return;let O=[...C.groupAtType];O.includes(h)&&O.includes(D)&&(O=[N]);const Y={from:C.from,groupID:C.groupID,topicID:C.topicID,messageSequence:C.sequence,atTypeArray:O,__random:C.__random,__sequence:C.__sequence};E.push(Y)},validateAndExecute:HI,validateParameters:pB});class fs{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return fs._instance||(fs._instance=new fs),fs._instance}static setInstance(E){fs._instance=E}installBuiltInPlugin(E){E&&this._installPlugin(E,this._builtInPlugins)}installExternalPlugin(E){E&&this._installPlugin(E,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(E,h){let D=[];D=B(E)?E:[E];const N=D.findIndex(Y=>Y?.name==="AVChatRoom"),O=N>-1?D.splice(N,1):[];D.forEach(Y=>{this._isPluginInstalled(Y.name)||(Y&&Ag(Y.install)?(h.add(Y.name),Ag(Y.getInstalledSubPlugins)?(O?.forEach(j=>h.add(j?.name)),Y.install(Wo.getInstance().exposeApiForPlugin(),O)):Y.install(Wo.getInstance().exposeApiForPlugin()),Ag(Y.handleLoginSuccess)&&this._isLoggedIn()&&Y.handleLoginSuccess()):Ag(Y)?(h.add(Y.name),Y(Wo.getInstance().exposeApiForPlugin()),Ag(Y.handleLoginSuccess)&&this._isLoggedIn()&&Y.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(E){return this._builtInPlugins.has(E)||this._externalPlugins.has(E)}_isLoggedIn(){var E;return((E=ZA.store.get("login"))===null||E===void 0?void 0:E.isLoggedIn)===!0}}var Uc=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(C){return this._conversationMap.get(C)}updateConversation(C,E,h){const{emit:D=!0,needSort:N=!1}=h||{},O=this._conversationMap.get(C);O&&!$r(E)&&(Object.keys(E).forEach(Y=>{O[Y]=E[Y]}),D&&ZA.notificationCenter.emitInnerEvent(Gt.CONVERSATION_UPDATED,{needSort:N}))}deleteConversation(C){this._conversationMap.has(C)&&(this._conversationMap.delete(C),ZA.notificationCenter.emitInnerEvent(Gt.CONVERSATION_UPDATED))}},ms=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(C){return this._groupMap.get(C)}updateGroup(C,E){const h=this._groupMap.get(C);h&&!$r(E)&&Object.keys(E).forEach(D=>{h[D]=E[D]})}},zI=new class{constructor(){this._messagesByConversation=new Map}updateMessage(C,E,h){var D;const{operation:N,updateUnreadCount:O=!0}=h,Y=Vo(h,["operation","updateUnreadCount"]),j=[];for(const IA of E){const BA=(D=this._messagesByConversation.get(C))===null||D===void 0?void 0:D.get(IA);if(!BA)return!1;Object.keys(Y).forEach(mA=>{BA[mA]=Y[mA]}),j.push(BA)}return this._emitMessageStoreOperationEvent(N,{conversationID:C,messageList:j,updateUnreadCount:O}),j}getMessagesByConversation(C){var E;return[...((E=this._messagesByConversation.get(C))===null||E===void 0?void 0:E.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(C,E){const{conversationID:h}=E;ca(h)?ZA.notificationCenter.emitInnerEvent(qa[C],E):ZA.notificationCenter.emitInnerEvent(C,E)}},xn=new class{constructor(){this.userProfileMap=new Map,this.friendMap=new Map}getUserProfileMap(){return this.userProfileMap}getFriendMap(){return this.friendMap}getUserProfile(C){return this.userProfileMap.get(C)}getFriend(C){return this.friendMap.get(C)}},Hu=Object.freeze({__proto__:null,conversationStore:Uc,groupStore:ms,messageStore:zI,userStore:xn});class Wo{static getInstance(){return Wo._instance||(Wo._instance=new Wo),Wo._instance}static setInstance(E){Wo._instance=E}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:ZA.notificationCenter.subscribeOuterEvent.bind(ZA.notificationCenter),off:ZA.notificationCenter.unSubscribeOuterEvent.bind(ZA.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:fs.getInstance().installExternalPlugin.bind(fs.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(E){ZA.ssoLog.debug("registerPlugin",E)}statKeyFeatureUsage(E){ZA.ssoLog.debug("statTUIKeyFeatures",E)}setLogLevel(E){ZA.ssoLog.debug("setLogLevel",E),ZA.ssoLog.setLogLevel(E)}setApplicationID(E){ZA.store.set("instance",{applicationID:E})}getApiMap(){return this._apiMap}setApiMap(E){this._apiMap=E}registerApi(E){const{common:{timeManager:h},utils:{safeStringify:D}}=ZA,{apiName:N,context:O,methodName:Y=N,matcher:j}=E;this._apiHandlersMap[N]||(this._apiHandlersMap[N]=[]),this._apiHandlersMap[N].push({context:O,methodName:Y,matcher:j}),this._apiMap[N]&&this._apiHandlersMap[N].length!==1||(this._apiMap[N]=(...IA)=>{const BA=h.getServerTimeMs();let mA=0;N==="login"&&(mA=4),tn.includes(N)&&ZA.ssoLog.debug(N,`${N} start params: ${D(IA)}`),HI(Y,IA);const _A=this._apiHandlersMap[N];for(const xA of _A)if(!xA.matcher||xA.matcher(IA))try{const Qe=xA.context[xA.methodName].bind(xA.context)(...IA);return this._isPromiseLike(Qe)?this._handleAsyncResult(Qe,N,mA,BA):(this._reportApiSuccessLog({result:Qe,apiName:N,eventType:mA,startTime:BA}),Qe)}catch(Qe){throw ZA.ssoLog.error(N,`${N} fail ${Qe?.message||Qe?.errorMessage})`,{error:Qe,costTime:h.getServerTimeMs()-BA,eventType:mA,method:N}),Qe}})}registerExperimentalAPI(E,h,D){const N=D||E;this._experimentalApiMap[E]=h[N].bind(h)}destroy(){return et(this,void 0,void 0,function*(){var E,h;try{!((E=ZA.store.get("login"))===null||E===void 0)&&E.isLogin&&(yield this._apiMap.logout()),ZA.notificationCenter.emitInnerEvent(Gt.DESTROY)}catch(D){console.debug("destroy error: ",D)}finally{ZA.notificationCenter.emitOuterEvent(kr.SDK_DESTROY,{SDKAppID:(h=ZA.store.get("instance"))===null||h===void 0?void 0:h.sdkAppId}),og.clear(),fs.getInstance().clear(),Ir.getInstance().destroy(),ZA.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:Gt,InnerEventSubType:ZA.notificationCenter.InnerEventSubType,OuterEvent:kr,OuterConstant:vo,SignalingEvent:Dl,helper:Object.assign(Object.assign(Object.assign({},ZA.utils),ZA.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:mn,registerValidateConfig:Lg,checkBusinessCapabilityBits:hE,registerWorkflowStep:Ir.getInstance().registerWorkflowStep.bind(Ir.getInstance()),ChatError:lo}),apiMap:this._apiMap},ZA),{constants:Object.assign(Object.assign({},Ml),ZA.constants),common:Object.assign(Object.assign(Object.assign({},dI),ZA.common),{workflowManager:Ir.getInstance()}),utils:ZA.utils,appStore:Hu})}callExperimentalAPI(E,h){return ZA.ssoLog.debug(`callExperimentalAPI.${E} start params: ${ZA.utils.safeStringify(h)}`),this._experimentalApiMap[E]?this._experimentalApiMap[E](h):(ZA.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${E} not found, params: ${ZA.utils.safeStringify(h)}`),Promise.reject(new lo({code:Qa.INVALID_OPERATION})))}_isPromiseLike(E){return E!==null&&typeof E=="object"&&typeof E.then=="function"}_handleAsyncResult(E,h,D,N){return E.then(O=>(this._reportApiSuccessLog({result:O,apiName:h,eventType:D,startTime:N}),O)).catch(O=>{throw ZA.ssoLog.error(h,`${h} fail ${O?.message||O?.errorMessage})`,{error:O,costTime:ZA.common.timeManager.getServerTimeMs()-N,eventType:D,method:h,startTime:N}),O})}_reportApiSuccessLog(E){let{result:h,apiName:D,startTime:N,eventType:O}=E;const{timeManager:Y}=ZA.common,{successLog:{message:j,moreMessage:IA}={message:"",moreMessage:""}}=h||{},BA=Y.getServerTimeMs();D==="login"&&(N+=Y.getTimeOffsetWithServer()),tn.includes(D)&&ZA.ssoLog.info(D,`${D} success ${j} ${IA}`,{costTime:BA-N,eventType:O,message:j,moreMessage:IA,startTime:N}),h?.successLog&&delete h.successLog}}class Oc{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:E,store:h}=ZA;h.set("login",{isReady:!1}),Wo.getInstance().registerApi({apiName:"login",context:this}),Wo.getInstance().registerApi({apiName:"logout",context:this}),Wo.getInstance().registerApi({apiName:"getLoginUser",context:this}),Wo.getInstance().registerApi({apiName:"isReady",context:this}),Wo.getInstance().registerApi({apiName:"getServerTime",context:this}),Wo.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),E.subscribeInnerEvent(Gt.RECONNECTED,this._reLogin,this),ZA.notificationCenter.subscribeInnerEvent(Gt.DESTROY,this._dispose,this)}login(E){return et(this,void 0,void 0,function*(){var h;const{sdkEdition:D}=ZA.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new lo({functionName:"login",code:Qa.REPEAT_LOGIN});const N=yield this._performLogin(E);this._validateAfterLogin(N),this._handleLoginSuccess(N),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const O=(h=ZA.channel.getSocketAdapter())===null||h===void 0?void 0:h.getId(),{appId:Y,href:j}=ZA.store.get("instance")||{},{instanceID:IA,customStatus:BA}=N||{};return{code:0,data:N,successLog:{message:D,moreMessage:`socketID:${O} instanceID:${IA} customStatus:${BA} href: ${j} appId: ${Y}`}}}catch(N){const{errorCode:O}=N;O!==Qa.REPEAT_LOGIN&&(this._latestLoginAt=0);const Y=new lo({functionName:"login",code:O});throw console.error(Y),Y}})}_reLogin(){return et(this,void 0,void 0,function*(){var E;try{if(!this._isLoginIn())return;const h=yield dE(this._customLoginInfo);if(h){const{instanceID:D,customStatus:N}=h;ZA.store.set("login",{statusInstanceId:D}),Ir.getInstance().executeWorkflow(cn.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:N,statusType:BE.USER_STATUS_ONLINE});const O=(E=ZA.channel.getSocketAdapter())===null||E===void 0?void 0:E.getId();ZA.ssoLog.info("reLogin",`socketId:${O} instanceId:${D}`)}}catch(h){console.warn(h)}})}logout(){return et(this,arguments,void 0,function*(E=ba.USER_INITIATED){const{ssoLog:h}=ZA;h.debug("logout",`logout start logoutReason: ${E}`);try{yield this._performLogout(E),h.info("logout","logout success"),ZA.ssoLog.uploadSSOLogData()}catch(D){const{errorCode:N}=D;throw new lo({functionName:"logout",code:N})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?Wr():""}isReady(){var E;return(E=ZA.store.get("login"))===null||E===void 0?void 0:E.isReady}setCustomLoginInfo(E=""){this._customLoginInfo=E}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),Ir.getInstance().reset(),ZA.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:E}=ZA.common;return E.getServerTimeMs()}_updateAndEmitSDKReady(){ZA.store.set("login",{isReady:!0}),setTimeout(()=>{ZA.notificationCenter.emitOuterEvent(kr.SDK_READY,{name:kr.SDK_READY})},1)}_updateAndEmitSDKNotReady(){ZA.store.set("login",{isReady:!1}),ZA.notificationCenter.emitOuterEvent(kr.SDK_NOT_READY,{name:kr.SDK_NOT_READY})}_validateAfterLogin(E){const h="login";if(!E)throw new lo({functionName:h,message:"login response is empty"});const{tinyID:D,a2Key:N}=E||{};if(!D)throw new lo({functionName:h,code:Qa.NO_TINYID});if(!N)throw new lo({functionName:h,code:Qa.NO_A2KEY})}_createRepeatLoginResponse(){var E;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:Tc({code:"RepeatLogin",replacement1:(E=ZA.store.get("login"))===null||E===void 0?void 0:E.userId}),repeatLogin:!0}}}_performLogin(E){return et(this,void 0,void 0,function*(){const{userID:h,userSig:D}=E;return ZA.store.set("login",{userId:h,userSig:D}),this._latestLoginAt=Date.now(),dE(this._customLoginInfo)})}_ensureAsyncComplete(){return et(this,void 0,void 0,function*(){yield new Promise(E=>{setTimeout(()=>E(null),1)})})}_handleLoginSuccess(E){const{timeManager:h}=ZA.common,{helloInterval:D,timeStamp:N,customStatus:O,purchaseBits:Y}=E,j=1e3*N;h.calculateTimeOffsetWithServer(this._latestLoginAt,j),this._helloInterval=D||120,this._updateLoginStore(E),ZA.user.userStatus.setCustomStatus(O),Ir.getInstance().executeWorkflow(cn.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:Y}),ZA.common.taskScheduler.addTask({id:wl,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(E){return function(h){return et(this,void 0,void 0,function*(){const{logoutReason:D}=h,N="im_open_status.wslogout",O=ZA.common.generateProtocolData({servcmd:N,data:{wslogout_type:D,isWebUniapp:0}}),Y=`${O.head.seq}${N}`;return yield ZA.channel.sendPacket(O,{requestId:Y})})}({logoutReason:E})}_updateLoginStore(E){const{a2Key:h,tinyID:D,instanceID:N,authKey:O}=E;ZA.store.set("login",{a2Key:h,tinyID:D,statusInstanceId:N,authKey:O,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return et(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const E="im_open_status.wshello",h=ZA.common.generateProtocolData({servcmd:E,data:{isWebUniapp:0}}),D=`${h.head.seq}${E}`;return ZA.channel.sendPacket(h,{requestId:D})}()}catch(E){ZA.ssoLog.warn("_sendOnlinePresenceRequest",` error:${E.message}`)}})}_isLoginIn(){var E;return((E=ZA.store.get("login"))===null||E===void 0?void 0:E.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){ZA.common.taskScheduler.removeTask(wl),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",ZA.store.clear("login"),ZA.store.set("login",{isReady:!1}),ZA.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:E}=ZA;E.unSubscribeInnerEvent(Gt.RECONNECTED,this._reLogin,this),E.unSubscribeInnerEvent(Gt.DESTROY,this._dispose,this)}}const wE={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},Pg={logout:!0};class gg{constructor(){this.loginAction=new Oc,this.kickedOutHandler=new bg,this.loginAction.init(),this.kickedOutHandler.init(),Lg({auth:Pg,params:wE})}}var En,Ds,Wa;(function(C){C.CONV_C2C="C2C",C.CONV_GROUP="GROUP",C.CONV_TOPIC="TOPIC",C.CONV_SYSTEM="@TIM#SYSTEM"})(En||(En={})),function(C){C.MSG_PRIORITY_HIGH="High",C.MSG_PRIORITY_NORMAL="Normal",C.MSG_PRIORITY_LOW="Low",C.MSG_PRIORITY_LOWEST="Lowest"}(Ds||(Ds={})),function(C){C.MSG_TEXT="TIMTextElem",C.MSG_CUSTOM="TIMCustomElem",C.MSG_LOCATION="TIMLocationElem",C.MSG_FACE="TIMFaceElem",C.MSG_IMAGE="TIMImageElem",C.MSG_AUDIO="TIMSoundElem",C.MSG_FILE="TIMFileElem",C.MSG_VIDEO="TIMVideoFileElem",C.MSG_GRP_TIP="TIMGroupTipElem",C.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",C.MSG_MERGER="TIMRelayElem"}(Wa||(Wa={}));const Ll={1:Ds.MSG_PRIORITY_HIGH,2:Ds.MSG_PRIORITY_NORMAL,3:Ds.MSG_PRIORITY_LOW,4:Ds.MSG_PRIORITY_LOWEST},TB=0,Vu=1;var li;(function(C){C.IN="in",C.OUT="out"})(li||(li={}));const SE=2,hI={};function GB(C){if(!C)return 0;if(hI[C]===void 0){const E=new Date,h=`3${E.getHours()}`.slice(-2),D=`0${E.getMinutes()}`.slice(-2),N=`0${E.getSeconds()}`.slice(-2);hI[C]=parseInt([h,D,N,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${hI[C]}`)}else hI[C]+=1;return hI[C]}class kB{constructor(E){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=Ds.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:h=ZA.common.timeManager.getServerTimeSeconds()||0,senderTinyID:D,currentUser:N,needReadReceipt:O,isSupportExtension:Y,customModerationConfigurationId:j,to:IA,from:BA,nick:mA="",avatar:_A="",time:xA,messageControlInfo:Qe,tinyID:Re,cloudCustomData:Se="",messageLifeTime:At,messageVersion:at=0,conversationType:jt,sequence:Bi,checkResult:ri=0,isPlaceMessage:St=0,messageFlagBits:eo,receiverList:to,isSystemMessage:Yt=!1,status:si=tg.SUCCESS,revokeReason:zo="",conversationSubType:te,clientSequence:je,protocol:dA="JSON",revokerInfo:ut={userID:"",nick:"",avatar:""},readReceiptInfo:Cr={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:lt,groupProfile:Co,atUserList:Jt,flow:mo,isRead:Fe=!1,priority:Oe=Ds.MSG_PRIORITY_NORMAL,onlineOnlyFlag:xs=!1,nameCard:Zo="",quoteInfo:ti}=E;var _n;this.clientTime=h,this.senderTinyID=D||Re,this.needReadReceipt=O===!0||O===1,this.isSupportExtension=Y===!0||Y===1,this._cmConfigID=j,this.to=IA,this.nick=mA,this.avatar=_A,this.protocol=dA,this.random=lt===void 0?(_n=_n||99999999,Math.round(Math.random()*_n)):lt,this.time=xA||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!Qe?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!Qe?.excludedFromUnreadCount,this.isModified=!!at,this.cloudCustomData=Se,this.messageLifeTime=At,this.from=BA||null,this.sequence=Bi||0,this.conversationType=jt||En.CONV_C2C,this.hasRiskContent=ri>1,this.version=at,this.isPlaceMessage=St,this.isRevoked=St===2||eo===8,this.isSystemMessage=Yt,this.readReceiptInfo=Cr,this.revokeReason=zo,this.revokerInfo=ut,this._receiverList=to,this.conversationSubType=te,this.revoker=ut?.revoker||"",this.clientSequence=je||Bi||0,this.status=si,this.atUserList=Jt||[],this.flow=mo,this.isRead=Fe,this.priority=Oe,this._onlineOnlyFlag=xs,this.nameCard=Zo,this.quoteInfo=ti,this.reInitialize(N),this._initC2CReadReceiptInfo(E),this._extractGroupInfo(Co)}getElements(){return this._elements}isOnlineMessage(){return this.messageLifeTime===0}setElement(E){Array.isArray(E)?this._elements=E:this._elements=[E],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(E=>E.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(E){this._relayFlag=E}validateBeforeSend(){var E,h,D;return this._relayFlag?{isValid:!0}:((E=this._elements)===null||E===void 0?void 0:E.length)>0?(D=(h=this._elements[0])===null||h===void 0?void 0:h.validateBeforeSend)===null||D===void 0?void 0:D.call(h):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(E){const{readReceiptSentByPeer:h,timestamp:D=0}=E;this.conversationType===En.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=h===1,this.readReceiptInfo.timestamp=D)}_extractGroupInfo(E){if(!E)return;const{From_AccountNick:h,From_AccountHeadurl:D,MsgFrom_AccountExtraInfo:N,GroupType:O}=E,{NameCard:Y}=N||{};typeof h=="string"&&(this.nick=h),typeof D=="string"&&(this.avatar=D),typeof Y=="string"&&(this.nameCard=Y),this.conversationSubType=O}reInitialize(E){E===this.from&&(this.isRead=!0),this._initSequence(E),this._concatConversationID(E),this.generateMessageID()}_concatConversationID(E){let h="";const D=this.conversationType;D!==En.CONV_SYSTEM?(h=D===En.CONV_C2C?E===this.from?this.to:this.from:this.to,this.conversationID=h?`${D}${h}`:null):this.conversationID=En.CONV_SYSTEM}_initSequence(E){this.clientSequence===0&&E&&(this.clientSequence=GB(E)),this.sequence===0&&this.conversationType===En.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===En.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(E){this.isRead=E}}class pI{static parseServerPushElement(E){const{MsgContent:h={}}=E,{Data:D,Ext:N,Desc:O}=h;return new pI({data:D,description:O,extension:N})}constructor(E){this.type=Wa.MSG_CUSTOM;const{data:h="",description:D="",extension:N=""}=E;this.content={data:h,description:D,extension:N}}transformToServerFormat(E){const{isMergerMessage:h=!1}=E||{},D=h?this.payload:this.content,{data:N,description:O,extension:Y}=D;return{MsgType:this.type,MsgContent:{Data:N,Ext:Y,Desc:O}}}validateBeforeSend(){const{isEmpty:E}=ZA.utils,h=[this.content.data,this.content.description,this.content.extension].some(D=>!E(D));return{isValid:h,error:h?null:{message:"content can not be empty"}}}}class vE{static parseServerPushElement(E){const{MsgContent:h={Text:""}}=E,{Text:D}=h;return new vE({text:D})}constructor(E){this.type=_s.MSG_TEXT,this.content={text:E.text||""}}validateBeforeSend(){var E,h;return((h=(E=this.content)===null||E===void 0?void 0:E.text)===null||h===void 0?void 0:h.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(E){const{isMergerMessage:h=!1}=E||{},D=h?this.payload:this.content,{text:N}=D;return{MsgType:this.type,MsgContent:{Text:N}}}}var ZI=new class{constructor(){this._elementClassMap={[Wa.MSG_CUSTOM]:pI,[Wa.MSG_TEXT]:vE}}init(){Wo.getInstance().registerApi({apiName:"createCustomMessage",context:this}),Wo.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(C,E){var h;(h=E).prototype!==void 0&&"constructor"in h.prototype&&(this._elementClassMap[C]=E)}getElementClass(C){return this._elementClassMap[C]}createMessage(C){const{from:E,flow:h=li.OUT}=C,{userId:D}=ZA.store.get("login")||{};this._isSendByCurrentInstance({from:E,flow:h,currentUser:D})?this._updateWithSenderInfo(C):this._isMultiEndpointSyncMessage({from:E,flow:h,currentUser:D})&&(C.flow=li.OUT);const N=Object.assign(Object.assign({},C),{currentUser:D});return new kB(N)}createCustomMessage(C){const E=Wr(),h=this.createMessage(Object.assign(Object.assign({},C),{from:E})),D=this._elementClassMap[Wa.MSG_CUSTOM];if(!h)return null;if(D){const N=new D(C.payload);h.setElement(N)}return h}createTextMessage(C){var E;if(!C)return null;const h=typeof C.payload=="string"?C.payload:((E=C?.payload)===null||E===void 0?void 0:E.text)||"",D=new vE({text:h}),N=Wr(),O=ZA.message.messageFactory.createMessage(Object.assign(Object.assign({},C),{from:N}));return O.setElement(D),O}_updateWithSenderInfo(C){var E,h;const{nick:D,avatar:N,conversationType:O,to:Y}=C,{userId:j,tinyID:IA}=ZA.store.get("login")||{},BA=xn.getUserProfile(j);return C.nick=D||BA?.nick||"",C.avatar=N||BA?.avatar||"",C.tinyID=C.tinyID||IA||"",C.from=j,C.status=tg.UNSENT,C.flow=li.OUT,O===us.CONV_GROUP&&(C.nameCard=(h=(E=ms.getGroup(Y))===null||E===void 0?void 0:E.selfInfo)===null||h===void 0?void 0:h.nameCard),C}_isMultiEndpointSyncMessage(C){const{from:E,flow:h,currentUser:D}=C;return E===D&&h===li.IN}_isSendByCurrentInstance(C){const{from:E,flow:h,currentUser:D}=C;return E===D&&h===li.OUT}};const xc={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}},_B={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},Yc={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function XI(C,E){return Object.keys(E).forEach(h=>{const{range:D,defaultValue:N}=E[h];C[h]=D.includes(C[h])?C[h]:N}),C}function Us(C){const E=C.lastIndexOf(".");return E===-1?C:C.slice(0,E)}function fI(C){const{androidInfo:E={},androidOPPOChannelID:h=""}=C,D=E.OPPOChannelID||h,N=XI(E,_B),{sound:O="",FCMChannelID:Y=""}=N,j=Vo(N,["sound","FCMChannelID"]);return Object.assign(Object.assign({},j),{Sound:Us(O),OPPOChannelID:D,GoogleChannelID:Y})}function kC(C){const{apnsInfo:E={},ignoreIOSBadge:h=!1,disableVoipPush:D}=C,N=XI(E,Yc),{ignoreIOSBadge:O,disableVoipPush:Y,enableIOSBackgroundNotification:j}=N,IA=Vo(N,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),BA=O===!0||h===!0?1:0;let mA;return r(D)||(mA=D===!1?1:0),r(Y)||(mA=Y===!1?1:0),Object.assign(Object.assign({},IA),{BadgeMode:BA,IsVoipPush:mA,ContentAvailable:j?1:0})}function Fl(C){return ZA.utils.isPlainObject(C)?{PushFlag:C.disablePush===!0?1:0,Title:C.title||"",Desc:C.description||"",Ext:C.extension||"",ApnsInfo:kC(C),AndroidInfo:fI(C)}:xc}function Pc(C){const{From_AccountHeadurl:E,From_AccountNick:h,IsNeedReadReceipt:D,IsPeerRead:N,IsSyncMsg:O,MsgBody:Y,MsgClientTime:j,MsgLifeTime:IA,MsgRandom:BA,MsgSeq:mA,MsgTimeStamp:_A,SendMsgControl:xA,SupportMessageExtension:Qe,TinyId:Re,MsgCheckResult:Se,CloudCustomData:At,MsgVersion:at,MsgFlagBits:jt,RevokerInfo:Bi,InnerSdkCustomData:ri}=C;let St,{From_Account:eo,To_Account:to}=C;if(O===1){const Yt=to;to=eo,eo=Yt}if(Bi){const{Reason:Yt,Revoker_Account:si,Revoker_FromUin:zo}=Bi;St={reason:Yt,revoker:si,revokerFromUin:zo,userID:si}}return{from:eo,avatar:E,nick:h,needReadReceipt:D===1,isSyncMessage:O,clientTime:j,messageLifeTime:IA,random:BA,sequence:mA,time:_A,messageControlInfo:{excludedFromLastMessage:xA?.NoLastMsg===1,excludedFromUnreadCount:xA?.NoUnread===1},isSupportExtension:Qe,to,tinyID:Re,checkResult:Se,cloudCustomData:At,revokerInfo:St,messageVersion:at,messageFlagBits:jt,readReceiptSentByPeer:N,elements:za(Y),onlineOnlyFlag:IA===0,quoteInfo:Ol(ri)}}function NE(C){const{From_Account:E,MsgBody:h,MsgClientTime:D,MsgRandom:N,MsgSeq:O,MsgTimeStamp:Y,To_Account:j,MsgVersion:IA,CloudCustomData:BA,MsgCheckResult:mA}=C;return{from:E,clientTime:D,random:N,sequence:O,time:Y,to:j,elements:za(h),messageVersion:IA,cloudCustomData:BA,checkResult:mA}}function di(C){const{ClientSeq:E,From_Account:h,GroupInfo:D,MsgBody:N,MsgClientTime:O,MsgRandom:Y,MsgSeq:j,MsgTimeStamp:IA,SendMsgControl:BA,SupportMessageExtension:mA,TinyId:_A,CloudCustomData:xA,MsgVersion:Qe,MsgCheckResult:Re,NeedReadReceipt:Se,IsPlaceMsg:At,RevokerInfo:at,GroupAtInfo:jt,OnlineOnlyFlag:Bi,InnerSdkCustomData:ri}=C;let St,eo=Ds.MSG_PRIORITY_NORMAL;if(Object.keys(Ll).includes(String(C.MsgPriority))&&(eo=Ll[C.MsgPriority]),at){const{Reason:Yt,Revoker_Account:si,Revoker_FromUin:zo}=at;St={reason:Yt,revoker:si,revokerFromUin:zo,userID:si}}const to=function(Yt){const si=[];return Array.isArray(Yt)&&Yt.forEach(zo=>{zo.GroupAtAllFlag===TB?si.push(zo.GroupAt_Account):zo.GroupAtAllFlag===Vu&&si.push(vo.MSG_AT_ALL)}),si}(jt);return{clientSequence:E,from:h,groupProfile:D,clientTime:O,priority:eo,random:Y,sequence:j,time:IA,messageControlInfo:{excludedFromLastMessage:BA?.NoLastMsg===1,excludedFromUnreadCount:BA?.NoUnread===1},isSupportExtension:mA,tinyID:_A,cloudCustomData:xA,messageVersion:Qe,checkResult:Re,needReadReceipt:Se,isPlaceMessage:At,revokerInfo:St,atUserList:to,elements:za(N),to:Ul(C),onlineOnlyFlag:Bi===1,quoteInfo:Ol(ri)}}function Ul(C){const{utils:{isEmpty:E},constants:{IS_TOPIC_MESSAGE:h}}=ZA,{ToGroupId:D,GroupInfo:{MillionGroupFlag:N=0,TopicId:O}={}}=C;return N!==h||E(O)?D:O}function za(C){if(!C)return null;if(Array.isArray(C))return C.map(h=>{const D=ZA.message.messageFactory.getElementClass(h.MsgType);return D?.parseServerPushElement(h)});const E=ZA.message.messageFactory.getElementClass(C.MsgType);return E?.parseServerPushElement(C)}function TE(C){const{From_Account:E,MsgBody:h,MsgClientTime:D,MsgRandom:N,MsgSeq:O,MsgTimeStamp:Y,GroupId:j,TopicId:IA,MsgVersion:BA,CloudCustomData:mA,MsgCheckResult:_A}=C;return{from:E,clientTime:D,random:N,sequence:O,time:Y,groupID:j,topicID:IA,elements:za(h),messageVersion:BA,cloudCustomData:mA,checkResult:_A}}function Ol(C){const{utils:{isString:E,safeStringify:h},ssoLog:D}=ZA;if(!E(C))return null;try{const{messageID:N,messageTime:O,messageSequence:Y}=JSON.parse(C).businessQuote;return{msgID:N,messageTime:O,messageSequence:Y}}catch(N){return D.debug("_parseServerQuoteInfo",h(N)),null}}function Jg({conversationUpdateFields:C,message:E}){const{conversationID:h,conversationType:D,conversationSubType:N,flow:O,_isExcludedFromUnreadCount:Y,_isExcludedFromLastMessage:j}=E,IA=j?"":ME(E),BA=!Y&&O===li.IN;C.has(h)?(C.get(h).lastMessage=IA,BA&&C.get(h).unreadCount++):C.set(h,{conversationID:h,type:D,subType:N,unreadCount:BA?1:0,lastMessage:IA})}function GE(C){return C.filter(E=>{const h=!$r(E?._elements),D=E?.isPlaceMessage===1;return h||ZA.ssoLog.error("emptyMessageBody",`from:${E.from} to:${E.to} sequence:${E.sequence}`),h&&!D})}function Hg(C){const{messageDataHandler:E}=ZA.message;return!E.isInMessageList(C)&&!E.isMessageSentByCurrentInstance(C)}var Vg=Object.freeze({__proto__:null,autoIncrementIndex:GB,createAndroidPushInfo:fI,createApnsPushInfo:kC,createOfflinePushInfo:Fl,filterValidMessages:GE,getAndroidSoundName:Us,parseServerGroupMessage:di,parseServerPushC2CModifyMessage:NE,parseServerPushGroupModifyMessage:TE,parseServerPushMessage:Pc,parseServerPushMessageElement:za,shouldStoreMessage:Hg,updateConversationFields:Jg});const{isPlainObject:fa}=ZA.utils;function xl(C,E={}){const{onlineUserOnly:h,messageControlInfo:D}=E;let{offlinePushInfo:N}=E;C.conversationType===En.CONV_C2C&&h===!0&&(N?N.disablePush=!0:N={disablePush:!0});let O="";typeof C.cloudCustomData=="string"&&C.cloudCustomData.length>0&&(O=C.cloudCustomData);const Y=[];if(D&&fa(D)){const{excludedFromUnreadCount:j,excludedFromLastMessage:IA,excludedFromContentModeration:BA}=D;j===!0&&Y.push("NoUnread"),IA===!0&&Y.push("NoLastMsg"),BA===!0&&Y.push("NoMsgCheck")}return{onlineUserOnly:h,cloudCustomData:O,messageControlInfo:Y,offlinePushInfo:N}}function zn(C){const{webhookInfo:{disableCloudMessagePreHook:E=!1,disableCloudMessagePostHook:h=!1}={}}=C||{};if(!E&&!h)return;const D=[];return E&&D.push("ForbidBeforeSendMsgCallback"),h&&D.push("ForbidAfterSendMsgCallback"),D}function dr(C,E){return et(this,void 0,void 0,function*(){const h=C.conversationType===En.CONV_GROUP?function(N,O){var Y;const j=xl(N,O),{onlineUserOnly:IA,cloudCustomData:BA,messageControlInfo:mA,offlinePushInfo:_A}=j,xA=JSON.parse(JSON.stringify(N.transformElementsToServerFormat()));let Qe;return B(N._receiverList)&&N._receiverList.length>0&&(Qe=N._receiverList,N._receiverList.length>50&&(Qe=N._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:(Y=ZA.store.get("login"))===null||Y===void 0?void 0:Y.userId,GroupId:N.to,MsgBody:xA,CloudCustomData:BA,Random:N.random,MsgPriority:N.priority,ClientSeq:N.clientSequence,GroupAtInfo:N._groupAtInfoList,OnlineOnlyFlag:IA?1:0,MsgClientTime:N.clientTime,OfflinePushInfo:Fl(_A),SendMsgControl:IA?void 0:mA,NeedReadReceipt:N.needReadReceipt===!0?1:0,To_Account:Qe,SupportMessageExtension:N.isSupportExtension===!0?1:0,IsRelayMsg:N._relayFlag===!0?1:0,CustomModerationConfigID:N._cmConfigID,ForbidCallbackControl:zn(O),InnerSdkCustomData:bB(N)}}}(C,E):function(N,O){var Y;const j=xl(N,O),{onlineUserOnly:IA,cloudCustomData:BA,messageControlInfo:mA,offlinePushInfo:_A}=j,xA=IA===!0?0:void 0,Qe=JSON.parse(JSON.stringify(N.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:(Y=ZA.store.get("login"))===null||Y===void 0?void 0:Y.userId,To_Account:N.to,MsgBody:Qe,CloudCustomData:BA,MsgSeq:N.sequence,MsgRandom:N.random,MsgLifeTime:xA,From_AccountNick:N.nick,From_AccountHeadurl:N.avatar,SendMsgControl:xA!==0?mA:void 0,MsgClientTime:N.clientTime,IsNeedReadReceipt:N.needReadReceipt===!0?1:0,SupportMessageExtension:N.isSupportExtension===!0?1:0,IsRelayMsg:N._relayFlag===!0?1:0,CustomModerationConfigID:N._cmConfigID,OfflinePushInfo:Fl(_A),ForbidCallbackControl:zn(O),InnerSdkCustomData:bB(N)}}}(C,E),D=yield Ls(h);return D?{time:D.MsgTime,messageDropReason:D.MsgDropReason,sequence:D.MsgSeq}:null})}function Yn(C){return et(this,void 0,void 0,function*(){const{from:E,to:h,version:D=0,sequence:N,random:O,time:Y,type:j,cloudCustomData:IA}=C,BA={From_Account:E,To_Account:h,MsgVersion:D,MsgSeq:N,MsgRandom:O,MsgTime:Y,MsgType:j,MsgBody:C.transformElementsToServerFormat(),CloudCustomData:IA},mA=yield Ls({servcmd:"openim.modify_c2c_msg",data:BA});if(mA){const{MsgBody:_A,MsgVersion:xA,CloudCustomData:Qe}=mA;return{elements:za(_A),messageVersion:xA,cloudCustomData:Qe}}})}function qg(C){return et(this,void 0,void 0,function*(){const{to:E,version:h=0,sequence:D,cloudCustomData:N}=C,O={GroupId:E,MsgVersion:h,MsgSeq:D,MsgBody:C.transformElementsToServerFormat(),CloudCustomData:N},Y=yield Ls({servcmd:"openim.modify_group_msg",data:O});if(Y){const{MsgBody:j,MsgVersion:IA,CloudCustomData:BA}=Y;return{elements:za(j),messageVersion:IA,cloudCustomData:BA}}})}function kE(C){return et(this,void 0,void 0,function*(){const{groupID:E,count:h,messageSequence:D,messageSequenceList:N,getType:O}=C,Y={GroupId:E,ReqMsgNumber:h,WithRecalledMsg:1,Version:1,GetType:O};return D&&(Y.ReqMsgSeq=D),B(N)&&N.length>0&&(Y.ReqMsgSeqList=N),yield Ls({servcmd:"group_open_http_svc.group_msg_get",data:Y})})}function $I(C){return et(this,void 0,void 0,function*(){const{peerAccount:E,count:h,lastMessageTime:D,messageKey:N,direction:O}=C;return Ls({servcmd:"openim.getroammsg",data:{Peer_Account:E,MaxCnt:h,WithRecalledMsg:1,LastMsgTime:D,MsgKey:N,GetDirection:O}})})}function bB(C){if(ZA.utils.isObject(C.quoteInfo)){const{msgID:E,messageSequence:h,messageTime:D}=C.quoteInfo;return JSON.stringify({businessQuote:{messageID:E,messageSequence:h,messageTime:D}})}}var Ig=Object.freeze({__proto__:null,createMessagePackOptions:xl,generateForbidCallbackControl:zn,getC2CRoamingMessagesByAnchor:$I,getGroupRoamingMessagesByAnchor:kE,getRoamingMessages:function(C){return et(this,void 0,void 0,function*(){const{peerAccount:E,count:h,lastMessageTime:D,messageKey:N}=C;return(yield Ls({servcmd:"openim.getroammsg",data:{Peer_Account:E,MaxCnt:h||15,LastMsgTime:D||0,MsgKey:N,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:Yn,modifyGroupMessage:qg,sendMessage:dr});const{isPlainObject:_E}=ZA.utils,{MSG_AUDIO:LB,MSG_FILE:bE,MSG_IMAGE:qu,MSG_VIDEO:LE,MSG_MERGER:Jc}=vo;class FE{constructor(){this._sendProtocolMap=new Map}init(){Wo.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:E=>![LB,bE,qu,LE,Jc].includes(E[0].type)})}registerSendProtocol(E,h,D){this._sendProtocolMap.set(E,h.bind(D))}sendMessage(E,h){return et(this,void 0,void 0,function*(){const{TOTAL_COUNT:D,SEND_COST:N,SUCCESS_COUNT:O,FAILED_COUNT:Y}=Sc;if(!(E instanceof kB))throw new lo({code:Qa.MSG_INSTANCE_REQUIRED});const j=E.validateBeforeSend();if(!j.isValid){const{code:mA,message:_A=""}=j.error||{};throw new lo({code:mA,message:_A})}this._reportMessageSendQuality({name:D,message:E});let IA=!1;const{messageDataHandler:BA}=ZA.message||{};try{const{messageControlInfo:mA}=h||{};let _A=null;BA.addRandomOfSentMessage(E.random);const xA=Date.now(),Qe=this._getSendProtocol(E);if(E.conversationType===En.CONV_C2C?(IA=h?.onlineUserOnly===!0,_A=yield Qe(E,h)):E.conversationType===En.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(E),_A=yield Qe(E,h)),_A){const{messageDropReason:Re,sequence:Se,time:At}=_A;if(this._updateNickAndAvatarOfSentMessageByMe(E),Re&&this._logRateLimitInfo(E,Se,Re),this._reportMessageSendQuality({name:O,message:E}),this._reportMessageSendQuality({name:N,message:E,startTs:xA}),E.isResend===!0){const at=BA.findMessage(E.ID);at&&(ZA.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${at.ID}`),BA.deleteConversationMessage(at))}return E.status=tg.SUCCESS,E.time=At,E.conversationType===En.CONV_GROUP&&(E.sequence=Se),IA?E._onlineOnlyFlag=!0:(BA.storeConversationMessage(E),this._applySentMessageControlInfo(E,mA),this._emitOnlineMessageSent(E)),E.type===_s.MSG_STREAM?{code:0,data:{message:E,streamMessageID:_A.streamMessageID}}:{code:0,data:{message:E}}}}catch(mA){E.status=tg.FAIL,BA.removeRandomOfSentMessage(E.random);let{errorCode:_A}=mA||{},xA=mA?.errorInfo||mA?.message||"";throw this._hasRiskContent(_A)&&(E.hasRiskContent=!0),IA||this._isRejectedByRestApi(_A)||BA.storeConversationMessage(E),this._reportMessageSendQuality({name:Y,message:E,error:mA}),new lo({code:_A,message:xA,data:{message:E},moreMessage:`type:${E.type} from:${E.from} to:${E.to}`})}})}_hasRiskContent(E){return E===80001||E===80004}_isRejectedByRestApi(E){return E>=10100&&E<=10200||E>=120001&&E<=13e4}_emitOnlineMessageSent(E){const h=E._isExcludedFromLastMessage?"":E,{conversationID:D,conversationType:N}=E,O=ca(D)?Gt.TOPIC_NEW_MESSAGE:Gt.NEW_MESSAGE;ZA.notificationCenter.emitInnerEvent(O,{result:{conversationUpdateFieldList:[{conversationID:D,type:N,message:E,lastMessage:h,unreadCount:0}]}})}_applySentMessageControlInfo(E,h){h&&_E(h)&&(h.excludedFromLastMessage===!0&&(E._isExcludedFromLastMessage=!0),h.excludedFromUnreadCount===!0&&(E._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(E,h,D){const N=`from:${E.from} to:${E.to} sequence:${h} messageDropReason:${D}`;ZA.ssoLog.warn("messageDropReason",N)}_updateNickAndAvatarOfSentMessageByMe(E){const{messageDataHandler:h}=ZA.message||{};let D=!1;const{conversationID:N}=E,O=h.getLatestMsgSentByMe(N);if(O){const{nick:Y,avatar:j}=O;Y===E.nick&&j===E.avatar||(D=!0),D&&h.updateNickAndAvatarOfSentMessage({conversationID:N,latestNick:E.nick,latestAvatar:E.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(E){return et(this,void 0,void 0,function*(){var h,D,N;const{to:O,from:Y}=E;let j=O,IA=ms.getGroup(j);if(Ka({groupID:j})&&IA?.isSupportTopic)throw new lo({code:Qa.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(ca(O)&&([j]=O.split(_a.TOPIC),IA=ms.getGroup(j)),!IA&&typeof((h=Wo.getInstance().getApiMap())===null||h===void 0?void 0:h.getGroupProfile)=="function"){const BA=yield Wo.getInstance().getApiMap().getGroupProfile({groupID:j});if(((N=(D=BA?.data)===null||D===void 0?void 0:D.group)===null||N===void 0?void 0:N.type)===vo.GRP_AVCHATROOM){const mA=Tc({code:Qa.MSG_SEND_FAIL_NOT_IN_AV,replacement1:Y,replacement2:j});throw new lo({code:Qa.MSG_SEND_FAIL_NOT_IN_AV,message:mA})}}return!0})}_reportMessageSendQuality(E){ZA.notificationCenter.emitInnerEvent(Gt.QUALITY_STAT,{label:PI.MESSAGE_SEND_SUCCESS_RATE,data:E})}_getSendProtocol(E){return this._sendProtocolMap.get(E.type)||dr}}var FB=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){ZA.notificationCenter.subscribeInnerEvent(Gt.LOGOUT,this._reset,this),ZA.notificationCenter.subscribeInnerEvent(Gt.DESTROY,this._dispose,this)}get _messagesByConversation(){return zI.getMessages()}storeConversationMessage(C,E=!1){if(Nr)return!0;const{conversationID:h}=C;if(!h||(this._messagesByConversation.has(h)||this._messagesByConversation.set(h,new Map),this._shouldSkipStoreMessage(C,E)))return!1;const D=this._getUniqueIdOfMessage(C);return this._messagesByConversation.get(h).set(D,C),this._updateLatestMessageMap(C),!0}_updateLatestMessageMap(C){const{conversationID:E}=C;C.flow==="out"?this._setLatestMsgSentByMe(E,C):E.startsWith("C2C")&&this._setLatestMsgSentByPeer(E,C)}_shouldSkipStoreMessage(C,E){const h=this._getUniqueIdOfMessage(C),D=this._messagesByConversation.get(C.conversationID);if(D?.has(h)){const N=D?.get(h);if(!E||N?.isModified===!0)return!0}return!1}deleteConversationMessage(C){var E;const{conversationID:h=""}=C,D=this._getUniqueIdOfMessage(C);this._messagesByConversation.has(h)&&((E=this._messagesByConversation.get(h))===null||E===void 0||E.delete(D))}modifyConversationMessage(C,E){var h;if(!this._messagesByConversation.has(C)&&!this._sparseMessagesByConversation.has(C))return{isUpdated:!1,message:null};const D=this._getUniqueIdOfMessage(E),N=this._getMessageFromLocalMessage(C,D);if(N){const{messageVersion:O,elements:Y,cloudCustomData:j,checkResult:IA=0}=E,BA=IA>1;if(ZA.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${N.version} remoteVersion:${O}`),N.versionN.ID===C)||null,E)break;if(!E){const D=Array.from(this._sparseMessagesByConversation.values());for(const N of D)if(E=N.get(C)||null,E)break}return E}deleteConversationMessageList(C){this._messagesByConversation.has(C)&&(this._messagesByConversation.delete(C),this._latestMessageSentByMeMap.delete(C),this._latestMessageSentByPeerMap.delete(C)),this._sparseMessagesByConversation.has(C)&&this._sparseMessagesByConversation.delete(C)}revokeMessage({conversationID:C,sequence:E,random:h,revoker:D}){const N=this._messagesByConversation.get(C);let O=null;if(N){const Y=Array.from(N.values());if(O=this._findMessageBySequenceAndRandom({messageList:Y,random:h,sequence:E}),O){const j=this._getUniqueIdOfMessage(O);return zI.updateMessage(C,[j],{isRevoked:!0,revoker:D,operation:ka.revoke}),O}}if(this._sparseMessagesByConversation.has(C)){const Y=Array.from(this._sparseMessagesByConversation.get(C).values());if(O=this._findMessageBySequenceAndRandom({messageList:Y,random:h,sequence:E}),O)return O.isRevoked=!0,O.revoker=D,O}}_findMessageBySequenceAndRandom({messageList:C,sequence:E,random:h}){for(let D=0;D0){const Y=new Map([...N,...O.entries()]);this._messagesByConversation.set(h,Y),this._updateLatestMessageSentByMe(h),this._updateLatestMessageSentByPeer(h)}return D}storeSparseMessageList(C){if(C.length===0)return;const{conversationID:E}=C[0],h=C.length;this._sparseMessagesByConversation.has(E)||this._sparseMessagesByConversation.set(E,new Map);const D=this._sparseMessagesByConversation.get(E);for(let N=0;N=0;D--)if(h[D].flow==="out"){this._setLatestMsgSentByMe(C,h[D]);break}}}_updateLatestMessageSentByPeer(C){var E;const h=Array.from(((E=this._messagesByConversation.get(C))===null||E===void 0?void 0:E.values())||[]);if(h.length!==0&&C.startsWith("C2C")){for(let D=h.length-1;D>=0;D--)if(h[D].flow==="in"){this._setLatestMsgSentByPeer(C,h[D]);break}}}_getUniqueIdOfMessage(C){const{from:E,to:h,random:D,sequence:N,time:O}=C;return`${E}-${h}-${D}-${N}-${O}`}_setLatestMsgSentByPeer(C,E){this._latestMessageSentByPeerMap.set(C,E)}_setLatestMsgSentByMe(C,E){this._latestMessageSentByMeMap.set(C,E)}getLatestMsgSentByPeer(C){return this._latestMessageSentByPeerMap.get(C)}getLatestMsgSentByMe(C){return this._latestMessageSentByMeMap.get(C)}addRandomOfSentMessage(C){this._randomOfSentMessageList.add(C)}removeRandomOfSentMessage(C){this._randomOfSentMessageList.delete(C)}updateNickAndAvatarOfSentMessage(C){const{conversationID:E="",latestAvatar:h,latestNick:D,isSentByMe:N=!0}=C,O=this._messagesByConversation.get(E);if(!O)return;const Y=Array.from(O.values()),j=N?"out":"in";Y.forEach(IA=>{const{nick:BA,avatar:mA,flow:_A}=IA;_A===j&&(BA!==D&&(IA.nick=D),mA!==h&&(IA.avatar=h))})}isInMessageList(C){var E;const{conversationID:h}=C;if(!h||!this._messagesByConversation.has(h))return!1;const D=this._getUniqueIdOfMessage(C);return(E=this._messagesByConversation.get(h))===null||E===void 0?void 0:E.has(D)}isMessageSentByCurrentInstance(C){const{random:E}=C;return this._randomOfSentMessageList.has(E)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(C){const E=this._messagesByConversation.get(C);return E?[...E.values()]:[]}getSparseMessageList(C){const E=this._sparseMessagesByConversation.get(C);return E?[...E.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),ZA.notificationCenter.unSubscribeInnerEvent(Gt.LOGOUT,this._reset,this),ZA.notificationCenter.unSubscribeInnerEvent(Gt.DESTROY,this._dispose,this)}};function Zn(C,E){const h=Uc.getConversation(C);if(h?.lastMessage){const{lastMessage:D}=h,{lastTime:N,lastSequence:O,version:Y}=D,{time:j,sequence:IA,messageVersion:BA,elements:mA,cloudCustomData:_A}=E;N===j&&O===IA&&Y!==BA&&(D.type=mA[0].type,D.payload=mA[0].content,D.messageForShow=bc(D.type,D.payload),D.cloudCustomData=_A,D.version=BA,Uc.updateConversation(C,{lastMessage:D}))}}class Os{init(){Wo.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(E){return et(this,void 0,void 0,function*(){const{to:h,payload:D,sequence:N,conversationType:O,random:Y,time:j,from:IA,type:BA}=E;if(this._canModifyMessageElement(BA)){const mA=E?._elements||[];mA.length>=1&&(mA[0].type=BA,mA[0].content=D)}try{let mA=null,_A=null;if(O===En.CONV_C2C?mA=yield Yn(E):O===En.CONV_GROUP&&(mA=yield qg(E)),mA){let xA=`${O}${h}`;return h===Wr()&&O===En.CONV_C2C&&(xA=`${O}${IA}`),_A={conversationType:O,from:IA,to:h,time:j,random:Y,sequence:N,elements:mA?.elements,cloudCustomData:mA?.cloudCustomData,messageVersion:mA?.messageVersion,conversationID:xA},this._handleModifyMessageSuccess(_A),{code:0,data:{message:E},successLog:{message:`to:${h}`}}}}catch(mA){const{errorCode:_A}=mA||{};throw new lo({functionName:"modifyMessage",code:_A,moreMessage:`to:${h}`})}})}_handleModifyMessageSuccess(E){const{conversationID:h}=E,{isUpdated:D,message:N}=ZA.message.messageDataHandler.modifyConversationMessage(h,E);D===!0&&ZA.notificationCenter.emitOuterEvent(kr.MESSAGE_MODIFIED,{name:kr.MESSAGE_MODIFIED,data:[N]}),ZA.notificationCenter.emitInnerEvent(Gt.MESSAGE_MODIFIED,{conversationID:h,message:N}),Zn(h,E)}_canModifyMessageElement(E){return[Wa.MSG_TEXT,Wa.MSG_CUSTOM,Wa.MSG_LOCATION,Wa.MSG_FACE].includes(E)}}class Za{init(){const{notificationCenter:E}=ZA,{InnerEventSubType:h}=E;Ir.getInstance().registerWorkflowStep(cn.RECEIVE_C2C_NEW_MESSAGE,kt.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),Ir.getInstance().registerWorkflowStep(cn.RECEIVE_C2C_NEW_MESSAGE,kt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),Ir.getInstance().registerWorkflowStep(cn.SYNC_SERVER_INFO_AFTER_RE_ONLINE,kt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),E.subscribeInnerEvent(Gt.MESSAGE_PUSH,h.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),E.subscribeInnerEvent(Gt.MESSAGE_PUSH,h.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),E.subscribeInnerEvent(Gt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(E){Ir.getInstance().executeWorkflow(cn.RECEIVE_C2C_NEW_MESSAGE,E)}_handleC2CMessagePush(E){const h=E.data||{},{messageDataHandler:D}=ZA.message||{},N=[],O=new Map;return h.C2cMsgArray.forEach(Y=>{const j=this._generateC2CMessage(Y);this._updateMessageProfile(j);let IA=j.isModified===1;D.isMessageSentByCurrentInstance(j)?j.isModified=IA:IA=!1,j._onlineOnlyFlag?D.isMessageSentByCurrentInstance(j)||N.push(j):Hg(j)&&(D.storeConversationMessage(j)&&Jg({conversationUpdateFields:O,message:j}),D.isMessageSentByCurrentInstance(j)&&!IA||N.push(j))}),{conversationUpdateFieldList:[...O.values()],messages:N}}_emitMessageEventsAfterReceiveNewMessage(E){var h;const{messages:D=[]}=((h=E.result)===null||h===void 0?void 0:h[kt.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(D)}_emitMessageEventsAfterSyncUnreadMessage(E){var h;const{messages:D=[]}=((h=E.result)===null||h===void 0?void 0:h[kt.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(D)}_emitMessageEvents(E){const h=E?.filter(N=>N?.isModified===!0)||[];h.length>0&&ZA.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:h});const D=E?.filter(N=>!N?.isModified);D.length>0&&ZA.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:D})}_generateC2CMessage(E){const h=En.CONV_C2C,D=Pc(E),N=ZA.message.messageFactory.createMessage(Object.assign(Object.assign({},D),{conversationType:h,flow:li.IN})),{elements:O}=D;return N.setElement(O),N}_updateMessageProfile(E){var h;const{messageDataHandler:D}=ZA.message||{},N=(h=ZA.store.get("login"))===null||h===void 0?void 0:h.userId,{from:O,nick:Y,avatar:j,conversationID:IA=""}=E;if(O!==N){const BA=D.getLatestMsgSentByPeer(IA);if(BA){const{nick:mA,avatar:_A}=BA;r(Y)||r(j)?(E.nick=s(mA)?mA:E.nick,E.avatar=s(_A)?_A:E.avatar):Y===mA&&j===_A||(D.updateNickAndAvatarOfSentMessage({conversationID:IA,latestNick:Y,latestAvatar:j,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:IA,nick:Y,avatar:j}))}}else{const BA=D.getLatestMsgSentByMe(IA);!BA||Y===BA.nick&&j===BA.avatar||D.updateNickAndAvatarOfSentMessage({conversationID:IA,latestNick:Y,latestAvatar:j,isSentByMe:!0})}}_updateConversationUserProfile(E){const{conversationID:h,nick:D,avatar:N}=E,O=Uc.getConversation(h),{userProfile:Y={}}=O||{};Y.avatar===N&&Y.nick===D||Uc.updateConversation(h,{userProfile:Object.assign(Object.assign({},Y),{nick:D,avatar:N})})}_updateMessageListDueToModify(E){const{conversationID:h}=E,{isUpdated:D,message:N}=ZA.message.messageDataHandler.modifyConversationMessage(h,E);D===!0&&ZA.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[N]}),ZA.notificationCenter.emitInnerEvent("ModifyMessageSuccess",E),Zn(h,E)}_handleC2CMessageModify(E){E.C2cMsgModNotifys.forEach(h=>{var D;const N=En.CONV_C2C;let O=NE(h);const{to:Y,from:j}=O;let IA=`${N}${Y}`;Y===((D=ZA.store.get("login"))===null||D===void 0?void 0:D.userId)&&(IA=`${N}${j}`),O=Object.assign({conversationType:N,conversationID:IA},O),this._updateMessageListDueToModify(O)})}_dispose(){const{notificationCenter:E}=ZA,{InnerEventSubType:h}=E;ZA.notificationCenter.unSubscribeInnerEvent(Gt.MESSAGE_PUSH,h.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),ZA.notificationCenter.unSubscribeInnerEvent(Gt.MESSAGE_PUSH,h.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),ZA.notificationCenter.unSubscribeInnerEvent(Gt.DESTROY,this._dispose,this)}}class UE{init(){const{notificationCenter:E}=ZA,{InnerEventSubType:h}=E;Ir.getInstance().registerWorkflowStep(cn.RECEIVE_GROUP_NEW_MESSAGE,kt.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),Ir.getInstance().registerWorkflowStep(cn.RECEIVE_GROUP_NEW_MESSAGE,kt.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),E.subscribeInnerEvent(Gt.MESSAGE_PUSH,h.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),E.subscribeInnerEvent(Gt.MESSAGE_PUSH,h.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),E.subscribeInnerEvent(Gt.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(E){this._canExecuteReceiverNewMessageWorkFlow(E)&&Ir.getInstance().executeWorkflow(cn.RECEIVE_GROUP_NEW_MESSAGE,E)}_handleGroupMessagePush(E){const h=E.data||{},{messageDataHandler:D}=ZA.message,N=[],O=new Map,Y=h?.GroupMsgArray;return Y?.forEach(j=>{if(j.GroupInfo.NotVisible===1)return;const IA=this._generateGroupMessage(j);this.updateMessageProfile(IA);let BA=IA.isModified===1;D.isMessageSentByCurrentInstance(IA)?IA.isModified=BA:BA=!1,IA._onlineOnlyFlag?D.isMessageSentByCurrentInstance(IA)||N.push(IA):Hg(IA)&&D.storeConversationMessage(IA)&&(N.push(IA),Jg({conversationUpdateFields:O,message:IA}))}),{conversationUpdateFieldList:[...O.values()],messages:N}}_emitMessageEvents(E){var h;const{messages:D}=((h=E.result)===null||h===void 0?void 0:h[kt.HANDLE_GROUP_NEW_MESSAGE])||{},N=D?.filter(Y=>Y?.isModified===!0)||[];N.length>0&&ZA.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:N});const O=D?.filter(Y=>!Y?.isModified)||[];O.length>0&&ZA.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:O})}_generateGroupMessage(E){const h=En.CONV_GROUP,D=di(E),N=ZA.message.messageFactory.createMessage(Object.assign(Object.assign({},D),{conversationType:h,flow:li.IN})),{elements:O}=D;return N.setElement(O),N}updateMessageProfile(E){var h;const{messageDataHandler:D}=ZA.message||{},N=(h=ZA.store.get("login"))===null||h===void 0?void 0:h.userId,{from:O,nick:Y,avatar:j,conversationID:IA="",_elements:BA}=E;if(O===N){const mA=D.getLatestMsgSentByMe(IA);!mA||Y===mA.nick&&j===mA.avatar||D.updateNickAndAvatarOfSentMessage({conversationID:IA,latestNick:Y,latestAvatar:j,isSentByMe:!0})}else if(O===vo.CONV_SYSTEM){const{operationType:mA,memberInfoList:_A,operatorInfo:xA}=BA;let Qe={};if($r(_A)?$r(xA)||(Qe=xA):[Qs.JOINED,Qs.KICKED,Qs.ADMIN_SET,Qs.ADMIN_CANCELED].includes(mA)&&(Qe=Object.assign({},_A[0])),!$r(Qe)){const{nick:Re="",avatar:Se=""}=Qe;E.nick=Re,E.avatar=Se}}}_updateMessageListDueToModify(E){const{conversationID:h}=E,{isUpdated:D,message:N}=ZA.message.messageDataHandler.modifyConversationMessage(h,E);D===!0&&ZA.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[N]}),Zn(h,E)}_handleGroupMessageModify(E){E.GroupMsgModNotifys.forEach(h=>{const D=En.CONV_GROUP;let N=TE(h);const{topicID:O,groupID:Y}=N,j=O||Y,IA=`${D}${j}`;N=Object.assign({conversationType:D,conversationID:IA,to:j},N),this._updateMessageListDueToModify(N)})}_dispose(){const{notificationCenter:E}=ZA,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:h,GROUP_MESSAGE_MODIFIED:D}}=E;E.unSubscribeInnerEvent(Gt.MESSAGE_PUSH,h,this._handleGroupMessagePush,this),E.unSubscribeInnerEvent(Gt.MESSAGE_PUSH,D,this._handleGroupMessageModify,this),E.unSubscribeInnerEvent(Gt.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(E){var h,D;const{GroupId:N,GroupType:O}=((D=(h=E?.GroupMsgArray)===null||h===void 0?void 0:h[0])===null||D===void 0?void 0:D.GroupInfo)||{},Y=O===yl.GRP_AVCHATROOM;return!(!ms.getGroup(N)&&Y)}}var Yl=new class{constructor(){this.c2cMessageReceiver=new Za,this.groupMessageReceiver=new UE}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const OE={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:C=>!(!C.startsWith("C2C")&&!C.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:C=>function(E){var h;return typeof E?.text!="string"||typeof E.text=="string"&&((h=E?.text)===null||h===void 0?void 0:h.length)===0?"payload.text must be a string":!0}(C)}}},xE={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var Ac=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(C){return et(this,void 0,void 0,function*(){try{const{conversationID:E,count:h,direction:D,sequence:N,messageSequenceList:O,shouldMarkCompleted:Y=!1,getType:j}=C,IA=E.replace(us.CONV_GROUP,""),BA=[];let mA=N;if(D===wc.BACKWARD){if(typeof N!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};mA=N+h-1}const _A=yield kE({groupID:IA,count:h,messageSequence:mA,messageSequenceList:O,getType:j});if(_A){const{RspMsgList:xA=[],NextReqMsgSeq:Qe=0,IsFinished:Re,InvisibleMsgSeq:Se}=_A,At=`groupID:${IA} sequence:${N} reqSeq:${mA} direction:${D} complete:${Re} nextSequence:${Qe} remoteMsgCount:${xA.length} invisibleSequenceList:${Se}`,at=[];for(let ri=0;ri=N),jt&&Y&&this.completedHistoryConversations.add(E);const Bi=GE(at);return ZA.ssoLog.info("getGroupRoamingMessagesByAnchor",At),{messageList:Bi,invisibleSequenceList:Se,nextReqMessageIDFromServer:Qe,hasNoMoreHistoryMessage:jt,serverGroupTipList:BA}}}catch(E){const{errorCode:h,errorInfo:D}=E||{};throw new lo({code:h,message:D})}})}clearHistoryMessageListFetchAnchors(C){this._historyMessageListFetchAnchors.delete(C)}isHistoryMessageFetchCompleted(C){return this.completedHistoryConversations.has(C)}_parseMessage(C){var E;const h=us.CONV_GROUP;C.Event===4&&(C.MsgBody.MsgType=vo.MSG_GRP_TIP);const D=di(C),N=ZI.createMessage(Object.assign(Object.assign({},D),{conversationType:h,flow:"in"}));return WI(((E=D.elements)===null||E===void 0?void 0:E.content)||{},N),N.setElement(D.elements),N}getC2CRoamingMessagesByAnchor(C){return et(this,void 0,void 0,function*(){var E;try{const{conversationID:h,count:D,messageID:N,time:O,direction:Y,shouldMarkCompleted:j=!1}=C;let IA=O,BA="";if(!O){const xA=N?ZA.message.messageDataHandler.findMessage(N):null;if(IA=xA?.time||0,N&&this._historyMessageListFetchAnchors.has(h)){const Qe=this._historyMessageListFetchAnchors.get(h);IA=Qe.lastMessageTime,BA=Qe.messageKey}}const mA=h.replace(us.CONV_C2C,""),_A=yield $I({count:D,lastMessageTime:IA,messageKey:BA,peerAccount:mA,direction:Y});if(_A){const{MsgList:xA=[],Complete:Qe,MsgKey:Re,LastMsgTime:Se}=_A;this._historyMessageListFetchAnchors.set(h,{messageKey:Re,lastMessageTime:Se});const At=[];for(let ri=0;ri{const{tag:N,value:O}=D;N&&N.indexOf(ys)>-1?h.profileCustomField.push({key:N,value:O}):Hc.has(N)&&(h[Hc.get(N)]=O)}),Object.assign(Object.assign({},Rs),h)}parseProfileItem(C=[]){const E=[];return C.forEach(h=>{E.push({tag:h.Tag,value:h.Value})}),E}parseProfileList(C=[]){const E=[];return C.forEach(h=>{E.push({tag:h.Tag,value:h.ValueBytes})}),E}convertParamsToProfile(C){const E=[];return Object.keys(C).forEach(h=>{h!==ln&&E.push({tag:kn[h.toUpperCase()],value:C[h]})}),C.profileCustomField&&B(C.profileCustomField)&&C.profileCustomField.forEach(h=>{E.push({tag:h.key,value:h.value})}),E}normalizeProfileFields(C){const E={},h=[];return C.forEach(D=>{const{tag:N,value:O}=D;if(N&&N.indexOf(ys)>-1&&h.push({key:N,value:O}),Hc.has(N)&&O!==void 0){const Y=Hc.get(N);E[Y]=O}}),h.length>0&&(E.profileCustomField=h),E}};const{generateProtocolData:Vc}=ZA.common;function Pl(C){return et(this,void 0,void 0,function*(){const E="profile.portrait_get_all",h={From_Account:Wr(),UserItem:[]};C.forEach(Y=>{h.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:Y})});const D=Vc({servcmd:E,data:h}),N=`${D.head.seq}${E}`,O=yield ZA.channel.sendPacket(D,{requestId:N});if(O)return function(Y){const{ActionStatus:j,ErrorCode:IA,ErrorDisplay:BA,ErrorInfo:mA,UserProfileItem:_A}=Y,xA=[];return _A.map(Qe=>{const{To_Account:Re,CustomSequence:Se,ResultCode:At,ResultInfo:at,StandardSequence:jt,ProfileItem:Bi}=Qe,ri=Ms.parseProfileItem(Bi);xA.push({userId:Re,customSequence:Se,resultCode:At,resultInfo:at,standardSequence:jt,profileItem:ri})}),{actionStatus:j,errorCode:IA,errorDisplay:BA,errorInfo:mA,userProfile:xA}}(O)})}function ma(C){return xn.getFriendMap().has(C)}const{isEmpty:tc}=ZA.utils;class UB{constructor(){this._strangerProfileMap=new Map}init(){Wo.getInstance().registerApi({apiName:"getMyProfile",context:this}),Wo.getInstance().registerApi({apiName:"getUserProfile",context:this}),Wo.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=Ms.createProfile.bind(Ms);const{notificationCenter:E}=ZA;Ir.getInstance().registerWorkflowStep(cn.SYNC_SERVER_INFO_AFTER_LOGIN,kt.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),E.subscribeInnerEvent(Gt.MESSAGE_PUSH,E.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),E.subscribeInnerEvent(Gt.LOGOUT,this._reset,this),E.subscribeInnerEvent(Gt.DESTROY,this._dispose,this)}getMyProfile(){return et(this,void 0,void 0,function*(){try{const E=Wr(),h=yield Pl([E]);if(h){const D=this._handleProfileFormResponse(h)[0];return xn.getUserProfileMap().set(E,D),{code:0,data:D}}}catch(E){const{errorCode:h,errorInfo:D}=E;throw new lo({functionName:"getMyProfile",code:h,message:D})}})}getUserProfile(E){return et(this,void 0,void 0,function*(){try{let{userIDList:h}=E;const{userIdListToRequest:D,profileFromCache:N}=this._filterRequestAndCacheUsers(h);if(D.length===0)return{code:0,data:N,successLog:{message:`userIDList.length:${h.length}`}};D.length>cg&&(ZA.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),D.length=cg);const{data:O,error:Y}=yield this._batchFetchUserProfiles(D),j=D.length,IA=O.length,BA=j-IA;if(N.length===0&&j===BA&&!tc(Y))throw Y;if(B(O))return O.forEach(_A=>{ma(_A.userID)?xn.getUserProfileMap().set(_A.userID,_A):this._strangerProfileMap.set(_A.userID,_A)}),{code:0,data:O.concat(N),successLog:{message:`getUserProfile query:${j} success:${IA} fail:${BA} from cache:${N.length}`}}}catch(h){throw new lo(h)}})}getMyProfileCacheThenServer(){return et(this,void 0,void 0,function*(){const E=Wr(),h=xn.getUserProfileMap().has(E);return h?{code:0,data:h}:this.getMyProfile()})}updateMyProfile(E){return et(this,void 0,void 0,function*(){const h=Wr(),D={};for(const O in E)E[O]!==void 0&&(D[O]=E[O]);const N=Ms.convertParamsToProfile(D);try{yield function(BA){return et(this,void 0,void 0,function*(){const mA="profile.portrait_set",_A=Vc({servcmd:mA,data:BA}),xA=`${_A.head.seq}${mA}`,Qe=yield ZA.channel.sendPacket(_A,{requestId:xA});if(Qe){const{ActionStatus:Re,ErrorCode:Se,ErrorDisplay:At,ErrorInfo:at}=Qe;return{actionStatus:Re,errorCode:Se,errorDisplay:At,errorInfo:at}}})}({From_Account:h,ProfileItem:N});const Y=xn.getUserProfile(h);let j;j=Y?Object.assign(Object.assign({},Y),D):Ms.createProfile(h,N);const IA=!cI(Y,j,["lastUpdatedTime"]);return j.lastUpdatedTime=Date.now(),xn.getUserProfileMap().set(h,j),IA&&this._emitProfileUpdated(j),{code:0,data:j,successLog:{message:`profileArray: ${ZA.utils.safeStringify(N)}`}}}catch(O){const{errorCode:Y,errorInfo:j}=O;throw new lo({functionName:"updateMyProfile",code:Y,message:j,moreMessage:`params: ${ZA.utils.safeStringify(E)}`})}})}updateMyNickAndAvatar(E){return et(this,void 0,void 0,function*(){const h=Wr(),D=Date.now(),N=xn.getUserProfile(h);let O={};O=N?Object.assign(N,E):Ms.createProfile(h,E),O.lastUpdatedTime=D,xn.getUserProfileMap().set(h,O)})}_onProfileDataModify(E){const h=function(O){const{Profile_Account:Y,PushType:j,ProfileList:IA}=O;return{userId:Y,pushType:j,profileList:Ms.parseProfileList(IA)}}(E.ProfileDataMod[0]);if(tc(h))return;const{isProfileUpdated:D,profile:N}=this._handleProfileModified(h);D&&this._emitProfileUpdated(N)}_emitProfileUpdated(E){ZA.notificationCenter.emitInnerEvent(Gt.PROFILE_UPDATE,{name:Gt.PROFILE_UPDATE,data:[E]}),ZA.notificationCenter.emitOuterEvent(kr.PROFILE_UPDATED,{name:kr.PROFILE_UPDATED,data:[E]}),Uc.updateConversation(`C2C${E?.userID}`,{userProfile:E})}_dispose(){const{notificationCenter:E}=ZA;E.unSubscribeInnerEvent(Gt.LOGOUT,this._reset,this),E.unSubscribeInnerEvent(Gt.MESSAGE_PUSH,E.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),E.unSubscribeInnerEvent(Gt.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(E){const{userId:h,profileList:D}=E,N=xn.getUserProfile(h);if(!(Wr()===h||ma(h)&&N))return{isProfileUpdated:!1,profile:null};const O=Ms.normalizeProfileFields(D),Y=Object.keys(O).some(mA=>mA===ln?this._isCustomFieldChanged(N.profileCustomField,O.profileCustomField):N[mA]!==O[mA]);if(!Y)return{isProfileUpdated:!1,profile:N};const j=Date.now(),IA=Object.prototype.hasOwnProperty.call(O,ln)?this._mergeProfileCustomField(N.profileCustomField,O.profileCustomField):N.profileCustomField,BA=Object.assign(Object.assign(Object.assign({},N),O),{profileCustomField:IA,lastUpdatedTime:j});return xn.getUserProfileMap().set(h,BA),{isProfileUpdated:Y,profile:BA}}_filterRequestAndCacheUsers(E){const h=[],D=[];return E.forEach(N=>{const O=xn.getUserProfileMap().has(N);ma(N)&&O?D.push(xn.getUserProfile(N)):this._isStrangerAndProfileValid(N)?D.push(this._strangerProfileMap.get(N)):h.push(N)}),{userIdListToRequest:h,profileFromCache:D}}_handleProfileFormResponse(E){const{userProfile:h}=E;if(!Array.isArray(h))return[];const D=h.filter(O=>O.userId!=="@TLS#NOT_FOUND"&&O.userId!==""&&!tc(O.profileItem)),N=Date.now();return D.map(O=>{const Y=Ms.createProfile(O.userId,O.profileItem);return Y.lastUpdatedTime=N,Y})}_isStrangerAndProfileValid(E){var h;if(!ma(E)){const{lastUpdatedTime:D=0}=this._strangerProfileMap.get(E)||{},N=((h=ZA.store.get("cloudConfig"))===null||h===void 0?void 0:h.stranger_profile_expiration_time)||6e5;return Date.now()-D<=N}return!1}_chunkUserIDList(E,h){return Array.from({length:Math.ceil(E.length/h)},(D,N)=>E.slice(N*h,(N+1)*h))}_batchFetchUserProfiles(E){return et(this,void 0,void 0,function*(){const h=[],D=[];let N={};return this._chunkUserIDList(E,100).forEach(O=>{h.push(Pl(O))}),(yield Promise.allSettled(h)).forEach(O=>{if(O.status==="fulfilled"){const Y=O.value,j=this._handleProfileFormResponse(Y);B(j)&&D.push(...j)}else if(O.status==="rejected"){const{code:Y,message:j}=O.reason||{};N={errorCode:Y,message:j}}}),{data:D,error:N}})}_isCustomFieldChanged(E=[],h=[]){if(!B(h)||h.length===0)return!1;if(!B(E)||E.length===0)return!0;const D=new Map(E.map(N=>[N.key,N.value]));return h.some(N=>D.get(N.key)!==N.value)}_mergeProfileCustomField(E=[],h=[]){const D=B(E)?E.map(N=>Object.assign({},N)):[];return B(h)&&h.length!==0&&h.forEach(({key:N,value:O})=>{const Y=D.find(j=>j.key===N);Y?Y.value=O:D.push({key:N,value:O})}),D}_reset(){xn.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const Jl=new Map,Hl=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let C=0,E=Hl.length;C>(-2*O&6)):0)N="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(N);try{return decodeURIComponent(escape(h))}catch(D){return console.warn(D),""}}const{isEmpty:YE}=ZA.utils,{generateProtocolData:Ci}=ZA.common;function Vl(C){return et(this,void 0,void 0,function*(){const E="im_open_status.ws_get_user_status",h=Ci({servcmd:E,data:{To_Account:C}}),D=`${h.head.seq}${E}`,N=yield ZA.channel.sendPacket(h,{requestId:D});if(N)return function(O){const{ErrorCode:Y,ErrorInfo:j,ErrorList:IA=[],UserStatusList:BA=[]}=O,mA=BA.map(xA=>{const{To_Account:Qe,Status:Re,CustomStatus:Se,Detail:At=[]}=xA;return{userID:Qe,statusType:Re,customStatus:qc(Se),onlineDevices:PE(At)}}),_A=IA.map(xA=>{const{To_Account:Qe,Invalid_Account:Re,ErrorCode:Se,ErrorInfo:At}=xA;return{userID:YE(Re)?Qe:Re,code:Se,message:At}});return{errorCode:Y,errorInfo:j,successUserList:mA,failureUserList:_A}}(N)})}function PE(C){const E=[];return C?.forEach(h=>{const{Platform:D,Status:N}=h;N==="Online"&&E.push(D)}),E}class OB{constructor(){this._customStatus=""}init(){const{notificationCenter:E}=ZA;Wo.getInstance().registerApi({apiName:"getUserStatus",context:this}),Wo.getInstance().registerApi({apiName:"setSelfStatus",context:this}),Wo.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),Wo.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),Ir.getInstance().registerWorkflowStep(cn.SYNC_SERVER_INFO_AFTER_RE_ONLINE,kt.USER_STATUS_UPDATE,this._onReOnline,this),E.subscribeInnerEvent(Gt.MESSAGE_PUSH,E.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),E.subscribeInnerEvent(Gt.LOGOUT,this._reset,this),E.subscribeInnerEvent(Gt.DESTROY,this._dispose,this)}setSelfStatus(E){return et(this,void 0,void 0,function*(){const h=Wr(),{customStatus:D}=E;try{return yield function(N){return et(this,void 0,void 0,function*(){const O="im_open_status.ws_set_custom_status",Y=Ci({servcmd:O,data:{CustomStatus:N}}),j=`${Y.head.seq}${O}`,IA=yield ZA.channel.sendPacket(Y,{requestId:j});if(IA){const{ErrorCode:BA,ErrorInfo:mA}=IA;return{errorCode:BA,errorInfo:mA}}})}(D),this._customStatus=D,{code:0,data:{userID:h,statusType:Kg,customStatus:D},successLog:{message:`customStatus: ${D}`}}}catch(N){const{errorCode:O,errorInfo:Y}=N;throw new lo({functionName:"setSelfStatus",code:O,message:Y})}})}getUserStatus(E){return et(this,void 0,void 0,function*(){const{userIDList:h=[]}=E;if(this._isOnlyMeInArray(h))return this._getMyStatus();const D=yield this._getUserStatus(h);return Object.assign(Object.assign({},D),{successLog:{message:`userIDList length: ${h.length}`}})})}setCustomStatus(E){const h=qc(E);this._customStatus=h}subscribeUserStatus(E){return et(this,void 0,void 0,function*(){try{const{userIDList:h=[]}=E;this._checkBusinessCapabilityBits("subscribeUserStatus");const D=this._getMaxUserCount("subscribe"),N=this._sliceUserIDList(h,D),O=yield function(j){return et(this,void 0,void 0,function*(){const{channel:IA}=ZA,BA="im_open_status.ws_status_subscribe",mA=Ci({servcmd:BA,data:{To_Account:j}}),_A=`${mA.head.seq}${BA}`;return yield IA.sendPacket(mA,{requestId:_A})})}(N),Y=this._parseResponse(O);return{code:0,data:{failureUserList:Y},successLog:{message:`userID length:${h.length} failCount: ${Y.length}`}}}catch(h){const{errorCode:D}=h;throw new lo({functionName:"subscribeUserStatus",code:D})}})}unsubscribeUserStatus(E){return et(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:h=[]}=E,D=this._getMaxUserCount("unsubscribe"),N=this._sliceUserIDList(h,D),O=yield function(j){return et(this,void 0,void 0,function*(){const{channel:IA}=ZA,BA="im_open_status.ws_status_unsubscribe";let mA={};mA=j.length===0?{UnsubscribeAll:1}:{To_Account:j};const _A=Ci({servcmd:BA,data:mA}),xA=`${_A.head.seq}${BA}`;return yield IA.sendPacket(_A,{requestId:xA})})}(N),Y=this._parseResponse(O);return{code:0,data:{failureUserList:Y},successLog:{message:`userID length:${h.length} failCount: ${Y.length}`}}}catch(h){const{errorCode:D}=h;throw new lo({functionName:"unsubscribeUserStatus",code:D})}})}_onUserStatusUpdate(E){const{UserStatusList:h=[]}=E||{},D=h.map(N=>{const{To_Account:O,Status:Y,CustomStatus:j,Platform:IA}=N,BA={userID:O,statusType:Y,customStatus:qc(j)};return IA&&(BA.onlineDevices=IA),BA});this._emitUserStatusUpdatedEvent(D)}_onReOnline(E){const h=qc(E.data.customStatus);if(this._customStatus===h)return;this._customStatus=h;const D={userID:Wr(),statusType:Kg,customStatus:h};this._emitUserStatusUpdatedEvent(D)}_emitUserStatusUpdatedEvent(E){ZA.notificationCenter.emitOuterEvent(kr.USER_STATUS_UPDATED,{name:kr.USER_STATUS_UPDATED,data:E})}_sliceUserIDList(E,h){return E.slice(0,h)}_parseResponse(E){const{ErrorList:h=[]}=E;return h.map(D=>{const{To_Account:N,Invalid_Account:O,ErrorCode:Y,ErrorInfo:j}=D;return{userID:ZA.utils.isEmpty(O)?N:O,code:Y,message:j}})}_checkBusinessCapabilityBits(E){if(!ZA.store.get("commercialConfig").get(wn))throw new lo({functionName:E,code:Qa.NO_USE,replacement1:E})}_getMaxUserCount(E){const h=ZA.store.get("cloudConfig")||{},D={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}},{key:N,default:O}=D[E],Y=h[N]||O;return parseInt(Y,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:Wr(),statusType:Kg,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(E){return et(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const h=this._getMaxUserCount("query"),D=this._sliceUserIDList(E,h),N=yield Vl(D),{successUserList:O,failureUserList:Y}=N||{};return{code:0,data:{successUserList:O,failureUserList:Y}}}catch(h){const{errorCode:D}=h;throw new lo({functionName:"getUserStatus",code:D})}})}_isOnlyMeInArray(E){const h=Wr();return E.length===1&&E.indexOf(h)>-1}_dispose(){const{notificationCenter:E}=ZA;E.unSubscribeInnerEvent(Gt.MESSAGE_PUSH,E.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),E.unSubscribeInnerEvent(Gt.DESTROY,this._dispose,this),E.unSubscribeInnerEvent(Gt.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const L={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(C){for(const E of C){if(typeof E!="object")return"Each item in profileCustomField must be an object";if(typeof E?.key!="string")return"Each item.key in profileCustomField must be a string";if(!E?.key.startsWith(ys))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}}},w={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class q{constructor(){this.userProfile=new UB,this.userStatus=new OB,this.userProfile.init(),this.userStatus.init(),Lg({auth:w,params:L})}}function y(C){const E=[];if(!s(C))return E;const h=C.length;if(h===0)return E;for(let D=h-1;D>=0;D--)C[D]==="1"&&E.push(2**(h-D-1));return E}var T,V,$;(function(C){C.NOT_START="notStart",C.PENDING="pending",C.RESOLVED="resolved",C.REJECTED="rejected"})(T||(T={})),function(C){C[C.C2C=1]="C2C",C[C.GROUP=2]="GROUP"}(V||(V={})),function(C){C[C.C2C=8]="C2C",C[C.GROUP=2]="GROUP"}($||($={}));class CA{constructor(){this._name="SyncConversationHandler",this._pagingStatus=T.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:E}=ZA;Ir.getInstance().registerWorkflowStep(cn.SYNC_SERVER_INFO_AFTER_RE_ONLINE,kt.CONVERSATION_RECOVER,this._syncConversationList,this),Ir.getInstance().registerWorkflowStep(cn.SYNC_SERVER_INFO_AFTER_LOGIN,kt.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),E.subscribeInnerEvent(Gt.LOGOUT,this._reset,this),E.subscribeInnerEvent(Gt.DESTROY,this._dispose,this),ZA.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===T.RESOLVED}_syncConversationListAfterLogin(){return et(this,void 0,void 0,function*(){return this._pagingStatus=T.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return et(this,void 0,void 0,function*(){const{ssoLog:E,utils:{safeStringify:h}}=ZA;E.debug("_syncConversationList","start");try{const D=yield this._pagingGetConversationList(!0);this._pagingStatus=T.RESOLVED;const{conversationList:N=[]}=D||{};return E.info("_syncConversationList",`success count:${N.length}`),D}catch(D){const N=new lo(D);E.error("_syncConversationList",`fail ${h(D)}`,{error:N})}})}_pagingGetConversationList(E){return et(this,void 0,void 0,function*(){try{const h=[];this._pagingStatus=T.PENDING;const D=yield function(_A){return et(this,void 0,void 0,function*(){const{fromAccount:xA,pagingTimeStamp:Qe,pagingStartIndex:Re,pagingPinnedTimeStamp:Se,pagingPinnedStartIndex:At}=_A;return Ls({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:xA,StartIndex:Re,TimeStamp:Qe,TopStartIndex:At,TopTimeStamp:Se}})})}({fromAccount:Wr(),pagingTimeStamp:E?this._pagingTimeStamp:0,pagingStartIndex:E?this._pagingStartIndex:0,pagingPinnedTimeStamp:E?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:E?this._pagingPinnedStartIndex:0}),{CompleteFlag:N,SessionItem:O=[],TimeStamp:Y,StartIndex:j,TopTimeStamp:IA,TopStartIndex:BA}=D||{};let mA=[];if(N===1&&(this._pagingStatus=T.RESOLVED),O.length>0&&(mA=this._getConversationOptions(O),h.push(...mA)),ZA.notificationCenter.emitInnerEvent(Gt.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:mA}),this._pagingTimeStamp=Y,this._pagingStartIndex=j,this._pagingPinnedTimeStamp=IA,this._pagingPinnedStartIndex=BA,N!==1){const{conversationList:_A}=yield this._pagingGetConversationList(E);h.push(..._A)}return{conversationList:h}}catch(h){throw h}})}_getConversationOptions(E){const{utils:{isUndefined:h}}=ZA,D=this._convertConversationKey(E);return this._filterValidConversations(D).map(N=>(h(N.lastMsg)&&(N.lastMsg={elements:[]}),N.type===V.C2C?this._assembleC2COption(N):this._assembleGroupOption(N)))}_filterValidConversations(E){return E.filter(({type:h,userID:D})=>h===V.C2C&&!function(N){let O;return N.startsWith(vo.CONV_C2C)&&(O=N.replace(vo.CONV_C2C,"")),O==="@TLS#ERROR"||O==="@TLS#NOT_FOUND"}(D)||h===2)}_assembleC2COption(E){var h,D,N,O,Y,j,IA,BA;const mA=this._createUserprofile(E);return{conversationID:`${vo.CONV_C2C}${E.userID}`,type:vo.CONV_C2C,lastMessage:{lastTime:E.time,lastSequence:E.sequence,fromAccount:E.lastC2CMsgFromAccount,type:!((h=E.lastMsg)===null||h===void 0)&&h.elements[0]?(D=E.lastMsg)===null||D===void 0?void 0:D.elements[0].type:null,payload:!((N=E.lastMsg)===null||N===void 0)&&N.elements[0]?this._amendLayersOverLimitProp(E.lastMsg.elements[0].content):null,cloudCustomData:((j=(Y=(O=E.lastMsg)===null||O===void 0?void 0:O.elements)===null||Y===void 0?void 0:Y[0])===null||j===void 0?void 0:j.cloudCustomData)||"",isRevoked:E.lastMessageFlag===$.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(E),revoker:((BA=(IA=E.lastMsg)===null||IA===void 0?void 0:IA.revokerInfo)===null||BA===void 0?void 0:BA.revoker)||null},unreadCount:0,userProfile:mA,peerReadTime:E.peerReadTime,isPinned:E.isPinned===1,customData:E.customMark||"",markList:y(E.standardMark),conversationGroupList:[],remark:E.friendRemark||"",messageRemindType:this._transMsgRemindType(E.messageRemindType)}}_createUserprofile(E){var h;const{userID:D,nick:N,peerAvatar:O}=E,Y=[{tag:"Tag_Profile_IM_Nick",value:N},{tag:"Tag_Profile_IM_Image",value:O}];return(h=ZA.user.userProfile)===null||h===void 0?void 0:h.createProfile(D,Y)}_computeIsPeerRead(E){const h=Wr(),{lastC2CMsgFromAccount:D,time:N,c2cPeerReadTime:O}=E;return D===h&&N<=O}_assembleGroupOption(E){var h,D,N,O,Y;return{conversationID:`${vo.CONV_GROUP}${E.groupID}`,type:vo.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:E.time,lastSequence:E.sequence,fromAccount:E.msgGroupFromAccount},this._patchTypeAndPayload(E)),{cloudCustomData:((N=(D=(h=E.lastMsg)===null||h===void 0?void 0:h.elements)===null||D===void 0?void 0:D[0])===null||N===void 0?void 0:N.cloudCustomData)||"",isRevoked:E.lastMessageFlag===$.GROUP,onlineOnlyFlag:!1,nick:E.msgGroupFromNickName||"",nameCard:E.msgGroupFromCardName||"",revoker:((Y=(O=E.lastMsg)===null||O===void 0?void 0:O.revokerInfo)===null||Y===void 0?void 0:Y.revoker)||null}),groupProfile:{groupID:E.groupID,name:E.groupNick,avatar:E.groupImage,type:E.groupType,nextMessageSeq:E.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(E),peerReadTime:0,isPinned:E.isPinned===1,version:0,customData:E.customMark||"",markList:y(E.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(E.messageRemindType),subType:E.groupType}}_convertConversationKey(E){return E.map(h=>({type:h.Type,userID:h.To_Account,nick:h.C2cNick,peerAvatar:h.C2cImage,time:h.MsgTimeStamp,sequence:h.MsgSeq,lastC2CMsgFromAccount:h.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(h.LastMsg),lastMessageFlag:h.LastMsgFlags,c2cPeerReadTime:h.C2cPeerReadTime,peerReadTime:h.C2cPeerReadTime,friendRemark:h.C2cRemark,isPinned:h.TopFlags,standardMark:h.StandardMark,customMark:h.CustomMark,messageRemindType:h.MsgRecvOption,groupID:h.ToAccount,groupNick:h.GroupNick,groupImage:h.GroupImage,groupType:h.GroupType,nextMessageSeq:h.GroupNextMsgSeq,msgGroupFromAccount:h.MsgGroupFrom_Account,msgGroupFromNickName:h.MsgGroupFromNickName,msgGroupFromCardName:h.MsgGroupFromCardName,unreadCount:h.UnreadMsgCount,noUnreadCount:h.GroupIgnoredUnreadSeqCount}))}_convertLastMsgKey(E){var h,D,N;const{utils:{isEmpty:O}}=ZA;if(O(E))return null;let Y="",j=null;if(!O(E.GroupTips)){const{From_Account:IA,GroupName:BA}=((h=E.GroupTips)===null||h===void 0?void 0:h.GroupInfo)||{};Y=vo.MSG_GRP_TIP,j=Object.assign(Object.assign({},this._parseContent(Y,E.GroupTips.MsgBody)),{groupProfile:{from:IA,groupName:BA}})}return E.MsgBody&&(Y=(D=E.MsgBody[0])===null||D===void 0?void 0:D.MsgType,j=this._parseContent(Y,E.MsgBody[0])),{event:E.Event,elements:[{type:Y,content:j,cloudCustomData:E.CloudCustomData}],revokerInfo:{revoker:(N=E.RevokerInfo)===null||N===void 0?void 0:N.Revoker_Account}}}_parseContent(E,h){var D;if(!h)return h;const N=ZA.message.messageFactory.getElementClass(E);return N?(D=N.parseServerPushElement(h))===null||D===void 0?void 0:D.content:h}_amendLayersOverLimitProp(E){const{LayersOverLimit:h}=E;return Vo(E,["LayersOverLimit"]).layersOverLimit=h===1,E}_transMsgRemindType(E){let h="";return E===0?h=vo.MSG_REMIND_ACPT_AND_NOTE:E===1?h=vo.MSG_REMIND_DISCARD:E===2?h=vo.MSG_REMIND_ACPT_NOT_NOTE:E===3&&(h=vo.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),h}_patchTypeAndPayload(E){var h;const{utils:{isUndefined:D}}=ZA,{event:N,elements:O=[]}=E.lastMsg||{};return D(N)?{type:O[0]?O[0].type:null,payload:O[0]?this._amendLayersOverLimitProp(O[0].content):null}:{type:vo.MSG_GRP_TIP,payload:((h=O?.[0])===null||h===void 0?void 0:h.content)||{}}}_computeGroupUnreadCount(E){const{unreadCount:h=0,noUnreadCount:D=0}=E,N=h-D;return N>0?N:0}_reset(){this._pagingStatus=T.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:E}=ZA;E.unSubscribeInnerEvent(Gt.LOGOUT,this._reset,this),E.unSubscribeInnerEvent(Gt.DESTROY,this._dispose,this)}}class NA{constructor(){this.syncConversationHandler=new CA,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Ia}`);var KA={create:function(C){var E,h;const{SDKAppID:D,testEnv:N=!1,devMode:O=!1,unlimitedAVChatRoom:Y=!1,scene:j="",oversea:IA=!1,instance:BA,disableIndependentDomain:mA=!1,proxyServer:_A=""}=C;let xA=D;if(!function(Re){if(typeof Re=="number")return!0;const Se=Number(Re);return!Number.isNaN(Se)}(xA))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(xA=Number(xA),og.has(xA))return og.get(xA);let Qe=null;if(BA)Qe=BA,Qe._workflowManager&&Ir.setInstance(Qe._workflowManager),Qe._pluginManager&&Qe._pluginManager.installBuiltInPlugin(Mn),BA.isReady()&&((h=(E=Ir.getInstance()).executeWorkflow)===null||h===void 0||h.call(E,cn.SYNC_SERVER_INFO_AFTER_LOGIN));else{const Re=function(){function ri(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${ri()+ri()}${ri()}${ri()}${ri()}${ri()}${ri()}${ri()}`}();ZA.init({sdkAppId:xA,instanceId:Re,testEnv:N,devMode:O,unlimitedAVChatRoom:Y,disableIndependentDomain:mA,scene:j,oversea:IA,sdkEdition:bl,version:Ia,proxyServer:_A}),Ir.getInstance().init(),ZA.message=new ec,ZA.user=new q,ZA.login=new gg,ZA.conversation=new NA,fs.getInstance().installBuiltInPlugin(Mn),Qe=Wo.getInstance().exposeApiForClient(),Qe._workflowManager=Ir.getInstance(),Qe._pluginManager=fs.getInstance();const{utils:{IS_WORKER_AVAILABLE:Se,USER_AGENT:At,getPlatformType:at,isIOSWebView:jt}}=ZA,Bi=`instanceID:${Re} SDKAppID:${D} platform:${MA} host:${at()} isIOSWebView:${jt} workerAvailable:${Se} UserAgent:${At}`;ZA.ssoLog.info("sdkConstruct",Bi)}return og.set(xA,Qe),Qe},TSignaling:Dl,EVENT:kr,VERSION:Ia,TYPES:vo};return KA})}(R2)),R2.exports}var RG={exports:{}},M2={exports:{}},xrA=M2.exports,d5;function c6(){return d5||(d5=1,function(t,i){(function(r,s){t.exports=s()})(xrA,function(){function r(A,e){return e.forEach(function(o){o&&typeof o!="string"&&!Array.isArray(o)&&Object.keys(o).forEach(function(n){if(n!=="default"&&!(n in A)){var a=Object.getOwnPropertyDescriptor(o,n);Object.defineProperty(A,n,a.get?a:{enumerable:!0,get:function(){return o[n]}})}})}),Object.freeze(A)}var s=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof bI<"u"?bI:typeof self<"u"?self:{};function g(A){return A&&A.__esModule&&Object.prototype.hasOwnProperty.call(A,"default")?A.default:A}var B=function(A){return A&&A.Math===Math&&A},Q=B(typeof globalThis=="object"&&globalThis)||B(typeof window=="object"&&window)||B(typeof self=="object"&&self)||B(typeof s=="object"&&s)||B(typeof s=="object"&&s)||function(){return this}()||Function("return this")(),f={},m=function(A){try{return!!A()}catch{return!0}},M=!m(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),v=!m(function(){var A=function(){}.bind();return typeof A!="function"||A.hasOwnProperty("prototype")}),U=v,AA=Function.prototype.call,z=U?AA.bind(AA):function(){return AA.apply(AA,arguments)},sA={},eA={}.propertyIsEnumerable,X=Object.getOwnPropertyDescriptor,QA=X&&!eA.call({1:2},1);sA.f=QA?function(A){var e=X(this,A);return!!e&&e.enumerable}:eA;var wA,HA,qA=function(A,e){return{enumerable:!(1&A),configurable:!(2&A),writable:!(4&A),value:e}},ue=v,jA=Function.prototype,Ve=jA.call,ze=ue&&jA.bind.bind(Ve,Ve),Me=ue?ze:function(A){return function(){return Ve.apply(A,arguments)}},qe=Me,Et=qe({}.toString),Je=qe("".slice),$e=function(A){return Je(Et(A),8,-1)},Dt=m,Zi=$e,bi=Object,qt=Me("".split),ai=Dt(function(){return!bi("z").propertyIsEnumerable(0)})?function(A){return Zi(A)==="String"?qt(A,""):bi(A)}:bi,Ki=function(A){return A==null},Ur=Ki,Er=TypeError,no=function(A){if(Ur(A))throw new Er("Can't call method on "+A);return A},Kn=ai,Xi=no,yr=function(A){return Kn(Xi(A))},lr=typeof document=="object"&&document.all,Ni=lr===void 0&&lr!==void 0?function(A){return typeof A=="function"||A===lr}:function(A){return typeof A=="function"},wt=Ni,Ji=function(A){return typeof A=="object"?A!==null:wt(A)},Di=Q,ar=Ni,MA=function(A,e){return arguments.length<2?(o=Di[A],ar(o)?o:void 0):Di[A]&&Di[A][e];var o},YA=Me({}.isPrototypeOf),pe=Q.navigator,st=pe&&pe.userAgent,Te=st?String(st):"",be=Q,yt=Te,ht=be.process,ae=be.Deno,ye=ht&&ht.versions||ae&&ae.version,Xe=ye&&ye.v8;Xe&&(HA=(wA=Xe.split("."))[0]>0&&wA[0]<4?1:+(wA[0]+wA[1])),!HA&&yt&&(!(wA=yt.match(/Edge\/(\d+)/))||wA[1]>=74)&&(wA=yt.match(/Chrome\/(\d+)/))&&(HA=+wA[1]);var ot=HA,zt=ot,yi=m,Hi=Q.String,Ei=!!Object.getOwnPropertySymbols&&!yi(function(){var A=Symbol("symbol detection");return!Hi(A)||!(Object(A)instanceof Symbol)||!Symbol.sham&&zt&&zt<41}),ji=Ei&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Xo=MA,sr=Ni,Lo=YA,Nr=Object,Vo=ji?function(A){return typeof A=="symbol"}:function(A){var e=Xo("Symbol");return sr(e)&&Lo(e.prototype,Nr(A))},et=String,Kr=function(A){try{return et(A)}catch{return"Object"}},Qn=Ni,ho=Kr,jn=TypeError,$t=function(A){if(Qn(A))return A;throw new jn(ho(A)+" is not a function")},$r=$t,On=Ki,An=function(A,e){var o=A[e];return On(o)?void 0:$r(o)},Tr=z,ei=Ni,Es=Ji,jr=TypeError,Gr={exports:{}},$o=Q,sn=Object.defineProperty,dn=function(A,e){try{sn($o,A,{value:e,configurable:!0,writable:!0})}catch{$o[A]=e}return e},hn=Q,Gi=dn,pn="__core-js_shared__",nI=Gr.exports=hn[pn]||Gi(pn,{});(nI.versions||(nI.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 gr=Gr.exports,gn=gr,Yo=function(A,e){return gn[A]||(gn[A]=e||{})},Tg=no,So=Object,ao=function(A){return So(Tg(A))},lE=ao,Ta=Me({}.hasOwnProperty),po=Object.hasOwn||function(A,e){return Ta(lE(A),e)},Ja=Me,Mc=0,Qr=Math.random(),Fo=Ja(1.1.toString),$s=function(A){return"Symbol("+(A===void 0?"":A)+")_"+Fo(++Mc+Qr,36)},Ha=Yo,Gs=po,Ga=$s,Rr=Ei,Ia=ji,fo=Q.Symbol,aI=Ha("wks"),en=Ia?fo.for||fo:fo&&fo.withoutSetter||Ga,qo=function(A){return Gs(aI,A)||(aI[A]=Rr&&Gs(fo,A)?fo[A]:en("Symbol."+A)),aI[A]},Gg=z,kg=Ji,fn=Vo,ls=An,Or=function(A,e){var o,n;if(e==="string"&&ei(o=A.toString)&&!Es(n=Tr(o,A))||ei(o=A.valueOf)&&!Es(n=Tr(o,A))||e!=="string"&&ei(o=A.toString)&&!Es(n=Tr(o,A)))return n;throw new jr("Can't convert object to primitive value")},Po=TypeError,Ba=qo("toPrimitive"),Mr=function(A,e){if(!kg(A)||fn(A))return A;var o,n=ls(A,Ba);if(n){if(e===void 0&&(e="default"),o=Gg(n,A,e),!kg(o)||fn(o))return o;throw new Po("Can't convert object to primitive value")}return e===void 0&&(e="number"),Or(A,e)},Cs=Mr,Va=Vo,P=function(A){var e=Cs(A,"string");return Va(e)?e:e+""},F=Ji,EA=Q.document,RA=F(EA)&&F(EA.createElement),GA=function(A){return RA?EA.createElement(A):{}},WA=GA,Ce=!M&&!m(function(){return Object.defineProperty(WA("div"),"a",{get:function(){return 7}}).a!==7}),ge=M,we=z,_e=sA,Ke=qA,Bt=yr,Rt=P,Ye=po,nt=Ce,ii=Object.getOwnPropertyDescriptor;f.f=ge?ii:function(A,e){if(A=Bt(A),e=Rt(e),nt)try{return ii(A,e)}catch{}if(Ye(A,e))return Ke(!we(_e.f,A,e),A[e])};var oi={},Ko=M&&m(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),Kt=Ji,ro=String,ks=TypeError,Zr=function(A){if(Kt(A))return A;throw new ks(ro(A)+" is not an object")},In=M,xr=Ce,sI=Ko,jo=Zr,OI=P,_g=TypeError,gI=Object.defineProperty,ml=Object.getOwnPropertyDescriptor,ua="enumerable",II="configurable",ZA="writable";oi.f=In?sI?function(A,e,o){if(jo(A),e=OI(e),jo(o),typeof A=="function"&&e==="prototype"&&"value"in o&&ZA in o&&!o[ZA]){var n=ml(A,e);n&&n[ZA]&&(A[e]=o.value,o={configurable:II in o?o[II]:n[II],enumerable:ua in o?o[ua]:n[ua],writable:!1})}return gI(A,e,o)}:gI:function(A,e,o){if(jo(A),e=OI(e),jo(o),xr)try{return gI(A,e,o)}catch{}if("get"in o||"set"in o)throw new _g("Accessors not supported");return"value"in o&&(A[e]=o.value),A};var Ag=oi,cI=qA,Bs=M?function(A,e,o){return Ag.f(A,e,cI(1,o))}:function(A,e,o){return A[e]=o,A},eg={exports:{}},kr=M,EI=po,Gt=Function.prototype,Dl=kr&&Object.getOwnPropertyDescriptor,xI=EI(Gt,"name"),_s={PROPER:xI&&function(){}.name==="something",CONFIGURABLE:xI&&(!kr||kr&&Dl(Gt,"name").configurable)},tg=Ni,ka=gr,wc=Me(Function.toString);tg(ka.inspectSource)||(ka.inspectSource=function(A){return wc(A)});var CE,qa,BE,yC=ka.inspectSource,us=Ni,lI=Q.WeakMap,ig=us(lI)&&/native code/.test(String(lI)),yl=$s,_a=Yo("keys"),Qs=function(A){return _a[A]||(_a[A]=yl(A))},Rl={},YI=ig,vo=Q,Qa=Ji,uE=Bs,cn=po,kt=gr,Gn=Qs,PI=Rl,Sc="Object already initialized",tn=vo.TypeError,Ml=vo.WeakMap;if(YI||kt.state){var ba=kt.state||(kt.state=new Ml);ba.get=ba.get,ba.has=ba.has,ba.set=ba.set,CE=function(A,e){if(ba.has(A))throw new tn(Sc);return e.facade=A,ba.set(A,e),e},qa=function(A){return ba.get(A)||{}},BE=function(A){return ba.has(A)}}else{var da=Gn("state");PI[da]=!0,CE=function(A,e){if(cn(A,da))throw new tn(Sc);return e.facade=A,uE(A,da,e),e},qa=function(A){return cn(A,da)?A[da]:{}},BE=function(A){return cn(A,da)}}var on={set:CE,get:qa,has:BE,enforce:function(A){return BE(A)?qa(A):CE(A,{})},getterFor:function(A){return function(e){var o;if(!Qa(e)||(o=qa(e)).type!==A)throw new tn("Incompatible receiver, "+A+" required");return o}}},Xr=Me,wl=m,bs=Ni,vc=po,CI=M,QE=_s.CONFIGURABLE,RC=yC,Nc=on.enforce,Sl=on.get,JI=String,bg=Object.defineProperty,dE=Xr("".slice),vl=Xr("".replace),Tc=Xr([].join),lo=CI&&!wl(function(){return bg(function(){},"length",{value:8}).length!==8}),ds=String(String).split("String"),pB=eg.exports=function(A,e,o){dE(JI(e),0,7)==="Symbol("&&(e="["+vl(JI(e),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),o&&o.getter&&(e="get "+e),o&&o.setter&&(e="set "+e),(!vc(A,"name")||QE&&A.name!==e)&&(CI?bg(A,"name",{value:e,configurable:!0}):A.name=e),lo&&o&&vc(o,"arity")&&A.length!==o.arity&&bg(A,"length",{value:o.arity});try{o&&vc(o,"constructor")&&o.constructor?CI&&bg(A,"prototype",{writable:!1}):A.prototype&&(A.prototype=void 0)}catch{}var n=Nc(A);return vc(n,"source")||(n.source=Tc(ds,typeof e=="string"?e:"")),A};Function.prototype.toString=pB(function(){return bs(this)&&Sl(this).source||RC(this)},"toString");var Gc=eg.exports,kc=Ni,MC=oi,fB=Gc,HI=dn,mn=function(A,e,o,n){n||(n={});var a=n.enumerable,I=n.name!==void 0?n.name:e;if(kc(o)&&fB(o,I,n),n.global)a?A[e]=o:HI(e,o);else{try{n.unsafe?A[e]&&(a=!0):delete A[e]}catch{}a?A[e]=o:MC.f(A,e,{value:o,enumerable:!1,configurable:!n.nonConfigurable,writable:!n.nonWritable})}return A},Lg={},hE=Math.ceil,Ir=Math.floor,og=Math.trunc||function(A){var e=+A;return(e>0?Ir:hE)(e)},Ka=og,ca=function(A){var e=+A;return e!=e||e===0?0:Ka(e)},pE=ca,wC=Math.max,Ls=Math.min,_c=function(A,e){var o=pE(A);return o<0?wC(o+e,0):Ls(o,e)},SC=ca,rg=Math.min,Wr=function(A){var e=SC(A);return e>0?rg(e,9007199254740991):0},ng=Wr,hs=function(A){return ng(A.length)},mB=yr,DB=_c,Nl=hs,bc=function(A){return function(e,o,n){var a=mB(e),I=Nl(a);if(I===0)return!A&&-1;var c,u=DB(n,I);if(A&&o!=o){for(;I>u;)if((c=a[u++])!=c)return!0}else for(;I>u;u++)if((A||u in a)&&a[u]===o)return A||u||0;return!A&&-1}},VI={includes:bc(!0),indexOf:bc(!1)},BI=po,fE=yr,Lc=VI.indexOf,uI=Rl,Fg=Me([].push),ja=function(A,e){var o,n=fE(A),a=0,I=[];for(o in n)!BI(uI,o)&&BI(n,o)&&Fg(I,o);for(;e.length>a;)BI(n,o=e[a++])&&(~Lc(I,o)||Fg(I,o));return I},Fs=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],No=ja,Fc=Fs.concat("length","prototype");Lg.f=Object.getOwnPropertyNames||function(A){return No(A,Fc)};var Ug={};Ug.f=Object.getOwnPropertySymbols;var vC=MA,mE=Lg,Tl=Ug,Pu=Zr,yB=Me([].concat),Ju=vC("Reflect","ownKeys")||function(A){var e=mE.f(Pu(A)),o=Tl.f;return o?yB(e,o(A)):e},Og=po,QI=Ju,pi=f,RB=oi,Gl=function(A,e,o){for(var n=QI(e),a=RB.f,I=pi.f,c=0;cc;)xc.f(A,o=a[c++],n[o]);return A};var Us,fI=MA("document","documentElement"),kC=Zr,Fl=hI,Pc=Fs,NE=Rl,di=fI,Ul=GA,za="prototype",TE="script",Ol=Qs("IE_PROTO"),Jg=function(){},GE=function(A){return"<"+TE+">"+A+""},Hg=function(A){A.write(GE("")),A.close();var e=A.parentWindow.Object;return A=null,e},Vg=function(){try{Us=new ActiveXObject("htmlfile")}catch{}Vg=typeof document<"u"?document.domain&&Us?Hg(Us):function(){var e,o=Ul("iframe"),n="java"+TE+":";return o.style.display="none",di.appendChild(o),o.src=String(n),(e=o.contentWindow.document).open(),e.write(GE("document.F=Object")),e.close(),e.F}():Hg(Us);for(var A=Pc.length;A--;)delete Vg[za][Pc[A]];return Vg()};NE[Ol]=!0;var fa=Object.create||function(A,e){var o;return A!==null?(Jg[za]=kC(A),o=new Jg,Jg[za]=null,o[Ol]=A):o=Vg(),e===void 0?o:Fl.f(o,e)},xl=qo,zn=fa,dr=oi.f,Yn=xl("unscopables"),qg=Array.prototype;qg[Yn]===void 0&&dr(qg,Yn,{configurable:!0,value:zn(null)});var kE=function(A){qg[Yn][A]=!0},$I=VI.includes,bB=kE;wr({target:"Array",proto:!0,forced:m(function(){return!Array(1).includes()})},{includes:function(A){return $I(this,A,arguments.length>1?arguments[1]:void 0)}}),bB("includes");var Ig,_E,LB,bE={},qu=!m(function(){function A(){}return A.prototype.constructor=null,Object.getPrototypeOf(new A)!==A.prototype}),LE=po,Jc=Ni,FE=ao,FB=qu,Zn=Qs("IE_PROTO"),Os=Object,Za=Os.prototype,UE=FB?Os.getPrototypeOf:function(A){var e=FE(A);if(LE(e,Zn))return e[Zn];var o=e.constructor;return Jc(o)&&e instanceof o?o.prototype:e instanceof Os?Za:null},Yl=m,OE=Ni,xE=Ji,Ac=UE,ec=mn,Xn=qo("iterator"),kn=!1;[].keys&&("next"in(LB=[].keys())?(_E=Ac(Ac(LB)))!==Object.prototype&&(Ig=_E):kn=!0);var ys=!xE(Ig)||Yl(function(){var A={};return Ig[Xn].call(A)!==A});ys&&(Ig={}),OE(Ig[Xn])||ec(Ig,Xn,function(){return this});var ln={IteratorPrototype:Ig,BUGGY_SAFARI_ITERATORS:kn},wn=oi.f,Kg=po,cg=qo("toStringTag"),Rs=function(A,e,o){A&&!o&&(A=A.prototype),A&&!Kg(A,cg)&&wn(A,cg,{configurable:!0,value:e})},Hc=ln.IteratorPrototype,Ms=fa,Vc=qA,Pl=Rs,ma=bE,tc=function(){return this},UB=function(A,e,o,n){var a=e+" Iterator";return A.prototype=Ms(Hc,{next:Vc(+!n,o)}),Pl(A,a,!1),ma[a]=tc,A},Jl=Me,Hl=$t,qc=Ji,YE=function(A){return qc(A)||A===null},Ci=String,Vl=TypeError,PE=function(A,e,o){try{return Jl(Hl(Object.getOwnPropertyDescriptor(A,e)[o]))}catch{}},OB=Ji,L=no,w=function(A){if(YE(A))return A;throw new Vl("Can't set "+Ci(A)+" as a prototype")},q=Object.setPrototypeOf||("__proto__"in{}?function(){var A,e=!1,o={};try{(A=PE(Object.prototype,"__proto__","set"))(o,[]),e=o instanceof Array}catch{}return function(n,a){return L(n),w(a),OB(n)&&(e?A(n,a):n.__proto__=a),n}}():void 0),y=wr,T=z,V=Ni,$=UB,CA=UE,NA=q,KA=Rs,C=Bs,E=mn,h=bE,D=_s.PROPER,N=_s.CONFIGURABLE,O=ln.IteratorPrototype,Y=ln.BUGGY_SAFARI_ITERATORS,j=qo("iterator"),IA="keys",BA="values",mA="entries",_A=function(){return this},xA=function(A,e,o,n,a,I,c){$(o,e,n);var u,d,R,k=function(Ie){if(Ie===a&&TA)return TA;if(!Y&&Ie&&Ie in iA)return iA[Ie];switch(Ie){case IA:case BA:case mA:return function(){return new o(this,Ie)}}return function(){return new o(this)}},_=e+" Iterator",Z=!1,iA=A.prototype,cA=iA[j]||iA["@@iterator"]||a&&iA[a],TA=!Y&&cA||k(a),JA=e==="Array"&&iA.entries||cA;if(JA&&(u=CA(JA.call(new A)))!==Object.prototype&&u.next&&(CA(u)!==O&&(NA?NA(u,O):V(u[j])||E(u,j,_A)),KA(u,_,!0)),D&&a===BA&&cA&&cA.name!==BA&&(N?C(iA,"name",BA):(Z=!0,TA=function(){return T(cA,this)})),a)if(d={values:k(BA),keys:I?TA:k(IA),entries:k(mA)},c)for(R in d)(Y||Z||!(R in iA))&&E(iA,R,d[R]);else y({target:e,proto:!0,forced:Y||Z},d);return iA[j]!==TA&&E(iA,j,TA,{name:a}),h[e]=TA,d},Qe=function(A,e){return{value:A,done:e}},Re=yr,Se=kE,At=bE,at=on,jt=oi.f,Bi=xA,ri=Qe,St=M,eo="Array Iterator",to=at.set,Yt=at.getterFor(eo),si=Bi(Array,"Array",function(A,e){to(this,{type:eo,target:Re(A),index:0,kind:e})},function(){var A=Yt(this),e=A.target,o=A.index++;if(!e||o>=e.length)return A.target=null,ri(void 0,!0);switch(A.kind){case"keys":return ri(o,!1);case"values":return ri(e[o],!1)}return ri([o,e[o]],!1)},"values"),zo=At.Arguments=At.Array;if(Se("keys"),Se("values"),Se("entries"),St&&zo.name!=="values")try{jt(zo,"name",{value:"values"})}catch{}var te=$t,je=ao,dA=ai,ut=hs,Cr=TypeError,lt="Reduce of empty array with no initial value",Co=function(A){return function(e,o,n,a){var I=je(e),c=dA(I),u=ut(I);if(te(o),u===0&&n<2)throw new Cr(lt);var d=A?u-1:0,R=A?-1:1;if(n<2)for(;;){if(d in c){a=c[d],d+=R;break}if(d+=R,A?d<0:u<=d)throw new Cr(lt)}for(;A?d>=0:u>d;d+=R)d in c&&(a=o(a,c[d],d,I));return a}},Jt={left:Co(!1),right:Co(!0)},mo=m,Fe=function(A,e){var o=[][A];return!!o&&mo(function(){o.call(null,e||function(){return 1},1)})},Oe=Q,xs=Te,Zo=$e,ti=function(A){return xs.slice(0,A.length)===A},_n=ti("Bun/")?"BUN":ti("Cloudflare-Workers")?"CLOUDFLARE":ti("Deno/")?"DENO":ti("Node.js/")?"NODE":Oe.Bun&&typeof Bun.version=="string"?"BUN":Oe.Deno&&typeof Deno.version=="object"?"DENO":Zo(Oe.process)==="process"?"NODE":Oe.window&&Oe.document?"BROWSER":"REST",Eg=_n==="NODE",Bo=Jt.left;wr({target:"Array",proto:!0,forced:!Eg&&ot>79&&ot<83||!Fe("reduce")},{reduce:function(A){var e=arguments.length;return Bo(this,A,e,e>1?arguments[1]:void 0)}});var Da=Jt.right;wr({target:"Array",proto:!0,forced:!Eg&&ot>79&&ot<83||!Fe("reduceRight")},{reduceRight:function(A){return Da(this,A,arguments.length,arguments.length>1?arguments[1]:void 0)}});var Xa=$e,ia=Array.isArray||function(A){return Xa(A)==="Array"},b=wr,rA=ia,gA=Me([].reverse),pA=[1,2];b({target:"Array",proto:!0,forced:String(pA)===String(pA.reverse())},{reverse:function(){return rA(this)&&(this.length=this.length),gA(this)}});var vA=Kr,Ae=TypeError,UA=Me([].slice),re=UA,LA=Math.floor,se=function(A,e){var o=A.length;if(o<8)for(var n,a,I=1;I0;)A[a]=A[--a];a!==I++&&(A[a]=n)}else for(var c=LA(o/2),u=se(re(A,0,c),e),d=se(re(A,c),e),R=u.length,k=d.length,_=0,Z=0;_3)){if(yD)return!0;if(Qt)return Qt<603;var A,e,o,n,a="";for(A=65;A<76;A++){switch(e=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(n=0;n<47;n++)Ti.push({k:e+n,v:o})}for(Ti.sort(function(I,c){return c.v-I.v}),n=0;n$a(d)?1:-1}}(A)),o=$i(a),n=0;no||d!=d?1/0*c:c*d},Jk=Math.fround||function(A){return Pk(A,11920928955078125e-23,34028234663852886e22,11754943508222875e-54)},PY=Array,JY=Math.abs,bC=Math.pow,HY=Math.floor,Hk=Math.log,VY=Math.LN2,xw={pack:function(A,e,o){var n,a,I,c=PY(o),u=8*o-e-1,d=(1<>1,k=e===23?bC(2,-24)-bC(2,-77):0,_=A<0||A===0&&1/A<0?1:0,Z=0;for((A=JY(A))!=A||A===1/0?(a=A!=A?1:0,n=d):(n=HY(Hk(A)/VY),A*(I=bC(2,-n))<1&&(n--,I*=2),(A+=n+R>=1?k/I:k*bC(2,1-R))*I>=2&&(n++,I/=2),n+R>=d?(a=0,n=d):n+R>=1?(a=(A*I-1)*bC(2,e),n+=R):(a=A*bC(2,R-1)*bC(2,e),n=0));e>=8;)c[Z++]=255&a,a/=256,e-=8;for(n=n<0;)c[Z++]=255&n,n/=256,u-=8;return c[Z-1]|=128*_,c},unpack:function(A,e){var o,n=A.length,a=8*n-e-1,I=(1<>1,u=a-7,d=n-1,R=A[d--],k=127&R;for(R>>=7;u>0;)k=256*k+A[d--],u-=8;for(o=k&(1<<-u)-1,k>>=-u,u+=e;u>0;)o=256*o+A[d--],u-=8;if(k===0)k=1-c;else{if(k===I)return o?NaN:R?-1/0:1/0;o+=bC(2,e),k-=c}return(R?-1:1)*o*bC(2,k-e)}},qY=ao,Vk=_c,KY=hs,qk=function(A){for(var e=qY(this),o=KY(e),n=arguments.length,a=Vk(n>1?arguments[1]:void 0,o),I=n>2?arguments[2]:void 0,c=I===void 0?o:Vk(I,o);c>a;)e[a++]=A;return e},jY=Ni,WY=Ji,Yw=q,Pw=function(A,e,o){var n,a;return Yw&&jY(n=e.constructor)&&n!==o&&WY(a=n.prototype)&&a!==o.prototype&&Yw(A,a),A},Gp=Q,SD=Me,vD=M,xB=Cn,zY=Bs,ZY=dI,ND=HE,Jw=m,Ku=oc,XY=ca,$Y=Wr,TD=RD,Kk=Jk,Hw=xw,jk=UE,Wk=q,AP=qk,eP=UA,tP=Pw,zk=Gl,Zk=Rs,GD=on,ju=_s.PROPER,Vw=_s.CONFIGURABLE,Wu="ArrayBuffer",zu="DataView",ud="prototype",qw="Wrong index",Kw=GD.getterFor(Wu),kp=GD.getterFor(zu),Xk=GD.set,VE=Gp[Wu],qE=VE,Qd=qE&&qE[ud],KE=Gp[zu],YB=KE&&KE[ud],LC=Object.prototype,kD=Gp.Array,dd=Gp.RangeError,iP=SD(AP),oP=SD([].reverse),_D=Hw.pack,bD=Hw.unpack,$k=function(A){return[255&A]},A_=function(A){return[255&A,A>>8&255]},jw=function(A){return[255&A,A>>8&255,A>>16&255,A>>24&255]},Ww=function(A){return A[3]<<24|A[2]<<16|A[1]<<8|A[0]},zw=function(A){return _D(Kk(A),23,4)},e_=function(A){return _D(A,52,8)},_p=function(A,e,o){ZY(A[ud],e,{configurable:!0,get:function(){return o(this)[e]}})},FC=function(A,e,o,n){var a=kp(A),I=TD(o),c=!!n;if(I+e>a.byteLength)throw new dd(qw);var u=a.bytes,d=I+a.byteOffset,R=eP(u,d,d+e);return c?R:oP(R)},PB=function(A,e,o,n,a,I){var c=kp(A),u=TD(o),d=n(+a),R=!!I;if(u+e>c.byteLength)throw new dd(qw);for(var k=c.bytes,_=u+c.byteOffset,Z=0;Z>24)},setUint8:function(A,e){Zw(this,A,e<<24>>24)}},{unsafe:!0})}else Qd=(qE=function(A){Ku(this,Qd);var e=TD(A);Xk(this,{type:Wu,bytes:iP(kD(e),0),byteLength:e}),vD||(this.byteLength=e,this.detached=!1)})[ud],YB=(KE=function(A,e,o){Ku(this,YB),Ku(A,Qd);var n=Kw(A),a=n.byteLength,I=XY(e);if(I<0||I>a)throw new dd("Wrong offset");if(I+(o=o===void 0?a-I:$Y(o))>a)throw new dd("Wrong length");Xk(this,{type:zu,buffer:A,byteLength:o,byteOffset:I,bytes:n.bytes}),vD||(this.buffer=A,this.byteLength=o,this.byteOffset=I)})[ud],vD&&(_p(qE,"byteLength",Kw),_p(KE,"buffer",kp),_p(KE,"byteLength",kp),_p(KE,"byteOffset",kp)),ND(YB,{getInt8:function(A){return FC(this,1,A)[0]<<24>>24},getUint8:function(A){return FC(this,1,A)[0]},getInt16:function(A){var e=FC(this,2,A,arguments.length>1&&arguments[1]);return(e[1]<<8|e[0])<<16>>16},getUint16:function(A){var e=FC(this,2,A,arguments.length>1&&arguments[1]);return e[1]<<8|e[0]},getInt32:function(A){return Ww(FC(this,4,A,arguments.length>1&&arguments[1]))},getUint32:function(A){return Ww(FC(this,4,A,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(A){return bD(FC(this,4,A,arguments.length>1&&arguments[1]),23)},getFloat64:function(A){return bD(FC(this,8,A,arguments.length>1&&arguments[1]),52)},setInt8:function(A,e){PB(this,1,A,$k,e)},setUint8:function(A,e){PB(this,1,A,$k,e)},setInt16:function(A,e){PB(this,2,A,A_,e,arguments.length>2&&arguments[2])},setUint16:function(A,e){PB(this,2,A,A_,e,arguments.length>2&&arguments[2])},setInt32:function(A,e){PB(this,4,A,jw,e,arguments.length>2&&arguments[2])},setUint32:function(A,e){PB(this,4,A,jw,e,arguments.length>2&&arguments[2])},setFloat32:function(A,e){PB(this,4,A,zw,e,arguments.length>2&&arguments[2])},setFloat64:function(A,e){PB(this,8,A,e_,e,arguments.length>2&&arguments[2])}});Zk(qE,Wu),Zk(KE,zu);var LD={ArrayBuffer:qE,DataView:KE},rP=MA,nP=dI,FD=M,i_=qo("species"),UD=function(A){var e=rP(A);FD&&e&&!e[i_]&&nP(e,i_,{configurable:!0,get:function(){return this}})},aP=UD,Xw="ArrayBuffer",o_=LD[Xw];wr({global:!0,constructor:!0,forced:Q[Xw]!==o_},{ArrayBuffer:o_}),aP(Xw);var sP=$e,UC=Me,jl=function(A){if(sP(A)==="Function")return UC(A)},r_=wr,hd=jl,gP=m,n_=Zr,a_=_c,IP=Wr,$w=LD.ArrayBuffer,AS=LD.DataView,s_=AS.prototype,eS=hd($w.prototype.slice),cP=hd(s_.getUint8),EP=hd(s_.setUint8);r_({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:gP(function(){return!new $w(2).slice(1,void 0).byteLength})},{slice:function(A,e){if(eS&&e===void 0)return eS(n_(this),A);for(var o=n_(this).byteLength,n=a_(A,o),a=a_(e===void 0?o:e,o),I=new $w(IP(a-n)),c=new AS(this),u=new AS(I),d=0;nI;I++)if((u=Ie(A[I]))&&US(Gd,u))return u;return new Vp(!1)}n=a1(A,a)}for(d=Z?A.next:n.next;!(R=i1(d,n)).done;){try{u=Ie(R.value)}catch(XA){Ib(n,"throw",XA)}if(typeof u=="object"&&u&&US(Gd,u))return u}return new Vp(!1)},xS=qo("iterator"),YS=!1;try{var I1=0,PS={next:function(){return{done:!!I1++}},return:function(){YS=!0}};PS[xS]=function(){return this},Array.from(PS,function(){throw 2})}catch{}var kd=function(A,e){try{if(!e&&!YS)return!1}catch{return!1}var o=!1;try{var n={};n[xS]=function(){return{next:function(){return{done:o=!0}}}},A(n)}catch{}return o},_d=xp,JS=AQ.CONSTRUCTOR||!kd(function(A){_d.all(A).then(void 0,function(){})}),HS=z,qp=$t,c1=Md,E1=mS,oy=OS;wr({target:"Promise",stat:!0,forced:JS},{all:function(A){var e=this,o=c1.f(e),n=o.resolve,a=o.reject,I=E1(function(){var c=qp(e.resolve),u=[],d=0,R=1;oy(A,function(k){var _=d++,Z=!1;R++,HS(c,e,k).then(function(iA){Z||(Z=!0,u[_]=iA,--R||n(u))},a)}),--R||n(u)});return I.error&&a(I.value),o.promise}});var VS=wr,qS=AQ.CONSTRUCTOR,KS=xp,l1=MA,C1=Ni,cb=mn,bd=KS&&KS.prototype;if(VS({target:"Promise",proto:!0,forced:qS,real:!0},{catch:function(A){return this.then(void 0,A)}}),C1(KS)){var Eb=l1("Promise").prototype.catch;bd.catch!==Eb&&cb(bd,"catch",Eb,{unsafe:!0})}var B1=z,Kp=$t,u1=Md,Q1=mS,d1=OS;wr({target:"Promise",stat:!0,forced:JS},{race:function(A){var e=this,o=u1.f(e),n=o.reject,a=Q1(function(){var I=Kp(e.resolve);d1(A,function(c){B1(I,e,c).then(o.resolve,n)})});return a.error&&n(a.value),o.promise}});var lb=Md;wr({target:"Promise",stat:!0,forced:AQ.CONSTRUCTOR},{reject:function(A){var e=lb.f(this);return(0,e.reject)(A),e.promise}});var Cb=Zr,h1=Ji,p1=Md,Bb=function(A,e){if(Cb(A),h1(e)&&e.constructor===A)return e;var o=p1.f(A);return(0,o.resolve)(e),o.promise},f1=wr,ub=AQ.CONSTRUCTOR,Qb=Bb;MA("Promise"),f1({target:"Promise",stat:!0,forced:ub},{resolve:function(A){return Qb(this,A)}});var nc=wr,ry=xp,m1=m,jS=MA,db=Ni,hb=u_,WS=Bb,D1=mn,ny=ry&&ry.prototype;if(nc({target:"Promise",proto:!0,real:!0,forced:!!ry&&m1(function(){ny.finally.call({then:function(){}},function(){})})},{finally:function(A){var e=hb(this,jS("Promise")),o=db(A);return this.then(o?function(n){return WS(e,A()).then(function(){return n})}:A,o?function(n){return WS(e,A()).then(function(){throw n})}:A)}}),db(ry)){var pb=jS("Promise").prototype.finally;ny.finally!==pb&&D1(ny,"finally",pb,{unsafe:!0})}var y1=Ji,R1=$e,zS=qo("match"),ZS=function(A){var e;return y1(A)&&((e=A[zS])!==void 0?!!e:R1(A)==="RegExp")},M1=m,ay=Q.RegExp,w1=!M1(function(){var A=!0;try{ay(".","d")}catch{A=!1}var e={},o="",n=A?"dgimsy":"gimsy",a=function(u,d){Object.defineProperty(e,u,{get:function(){return o+=d,!0}})},I={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var c in A&&(I.hasIndices="d"),I)a(c,I[c]);return Object.getOwnPropertyDescriptor(ay.prototype,"flags").get.call(e)!==n||o!==n}),fb=Zr,mb=function(){var A=fb(this),e="";return A.hasIndices&&(e+="d"),A.global&&(e+="g"),A.ignoreCase&&(e+="i"),A.multiline&&(e+="m"),A.dotAll&&(e+="s"),A.unicode&&(e+="u"),A.unicodeSets&&(e+="v"),A.sticky&&(e+="y"),e},XS=z,jp=po,Db=YA,sy={correct:w1},$S=mb,yb=RegExp.prototype,gy=sy.correct?function(A){return A.flags}:function(A){return sy.correct||!Db(yb,A)||jp(A,"flags")?A.flags:XS($S,A)},Iy=m,cy=Q.RegExp,A0=Iy(function(){var A=cy("a","y");return A.lastIndex=2,A.exec("abcd")!==null}),S1=A0||Iy(function(){return!cy("a","y").sticky}),Rb=A0||Iy(function(){var A=cy("^r","gy");return A.lastIndex=2,A.exec("str")!==null}),rQ={BROKEN_CARET:Rb,MISSED_STICKY:S1,UNSUPPORTED_Y:A0},e0=oi.f,t0=m,i0=Q.RegExp,o0=t0(function(){var A=i0(".","s");return!(A.dotAll&&A.test(` +`)&&A.flags==="s")}),Mb=m,v1=Q.RegExp,wb=Mb(function(){var A=v1("(?b)","g");return A.exec("b").groups.a!=="b"||"b".replace(A,"$c")!=="bc"}),Ld=M,r0=Q,Fd=Me,n0=Rn,N1=Pw,T1=Bs,G1=fa,k1=Lg.f,Ey=YA,Sb=ZS,a0=Mn,vb=gy,Wp=rQ,s0=function(A,e,o){o in A||e0(A,o,{configurable:!0,get:function(){return e[o]},set:function(n){e[o]=n}})},ly=mn,Cy=m,_1=po,g0=on.enforce,By=UD,Nb=o0,Ud=wb,b1=qo("match"),HB=r0.RegExp,Od=HB.prototype,L1=r0.SyntaxError,Tb=Fd(Od.exec),xd=Fd("".charAt),Gb=Fd("".replace),I0=Fd("".indexOf),c0=Fd("".slice),F1=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,ac=/a/g,VB=/a/g,kb=new HB(ac)!==ac,_b=Wp.MISSED_STICKY,U1=Wp.UNSUPPORTED_Y,E0=Ld&&(!kb||_b||Nb||Ud||Cy(function(){return VB[b1]=!1,HB(ac)!==ac||HB(VB)===VB||String(HB(ac,"i"))!=="/a/i"}));if(n0("RegExp",E0)){for(var qB=function(A,e){var o,n,a,I,c,u,d=Ey(Od,this),R=Sb(A),k=e===void 0,_=[],Z=A;if(!d&&R&&k&&A.constructor===qB)return A;if((R||Ey(Od,A))&&(A=A.source,k&&(e=vb(Z))),A=A===void 0?"":a0(A),e=e===void 0?"":a0(e),Z=A,Nb&&"dotAll"in ac&&(n=!!e&&I0(e,"s")>-1)&&(e=Gb(e,/s/g,"")),o=e,_b&&"sticky"in ac&&(a=!!e&&I0(e,"y")>-1)&&U1&&(e=Gb(e,/y/g,"")),Ud&&(I=function(iA){for(var cA,TA=iA.length,JA=0,Ie="",XA=[],Ft=G1(null),ie=!1,ke=!1,Nt=0,Ut="";JA<=TA;JA++){if((cA=xd(iA,JA))==="\\")cA+=xd(iA,++JA);else if(cA==="]")ie=!1;else if(!ie)switch(!0){case cA==="[":ie=!0;break;case cA==="(":if(Ie+=cA,c0(iA,JA+1,JA+3)==="?:")continue;Tb(F1,c0(iA,JA+1))&&(JA+=2,ke=!0),Nt++;continue;case(cA===">"&&ke):if(Ut===""||_1(Ft,Ut))throw new L1("Invalid capture group name");Ft[Ut]=!0,XA[XA.length]=[Ut,Nt],ke=!1,Ut="";continue}ke?Ut+=cA:Ie+=cA}return[Ie,XA]}(A),A=I[0],_=I[1]),c=N1(HB(A,e),d?this:Od,qB),(n||a||_.length)&&(u=g0(c),n&&(u.dotAll=!0,u.raw=qB(function(iA){for(var cA,TA=iA.length,JA=0,Ie="",XA=!1;JA<=TA;JA++)(cA=xd(iA,JA))!=="\\"?XA||cA!=="."?(cA==="["?XA=!0:cA==="]"&&(XA=!1),Ie+=cA):Ie+="[\\s\\S]":Ie+=cA+xd(iA,++JA);return Ie}(A),o)),a&&(u.sticky=!0),_.length&&(u.groups=_)),A!==Z)try{T1(c,"source",Z===""?"(?:)":Z)}catch{}return c},l0=k1(HB),C0=0;l0.length>C0;)s0(qB,HB,l0[C0++]);Od.constructor=qB,qB.prototype=Od,ly(r0,"RegExp",qB,{constructor:!0})}By("RegExp");var Yd=z,nQ=Me,KB=Mn,O1=mb,Pd=rQ,bb=fa,Lb=on.get,x1=o0,Y1=wb,P1=Yo("native-string-replace",String.prototype.replace),aQ=RegExp.prototype.exec,B0=aQ,J1=nQ("".charAt),H1=nQ("".indexOf),Fb=nQ("".replace),zp=nQ("".slice),u0=function(){var A=/a/,e=/b*/g;return Yd(aQ,A,"a"),Yd(aQ,e,"a"),A.lastIndex!==0||e.lastIndex!==0}(),Ub=Pd.BROKEN_CARET,Q0=/()??/.exec("")[1]!==void 0;(u0||Q0||Ub||x1||Y1)&&(B0=function(A){var e,o,n,a,I,c,u,d=this,R=Lb(d),k=KB(A),_=R.raw;if(_)return _.lastIndex=d.lastIndex,e=Yd(B0,_,k),d.lastIndex=_.lastIndex,e;var Z=R.groups,iA=Ub&&d.sticky,cA=Yd(O1,d),TA=d.source,JA=0,Ie=k;if(iA&&(cA=Fb(cA,"y",""),H1(cA,"g")===-1&&(cA+="g"),Ie=zp(k,d.lastIndex),d.lastIndex>0&&(!d.multiline||d.multiline&&J1(k,d.lastIndex-1)!==` +`)&&(TA="(?: "+TA+")",Ie=" "+Ie,JA++),o=new RegExp("^(?:"+TA+")",cA)),Q0&&(o=new RegExp("^"+TA+"$(?!\\s)",cA)),u0&&(n=d.lastIndex),a=Yd(aQ,iA?o:d,Ie),iA?a?(a.input=zp(a.input,JA),a[0]=zp(a[0],JA),a.index=d.lastIndex,d.lastIndex+=a[0].length):d.lastIndex=0:u0&&a&&(d.lastIndex=d.global?a.index+a[0].length:n),Q0&&a&&a.length>1&&Yd(P1,a[0],o,function(){for(I=1;I0;(n>>>=1)&&(e+=e))1&n&&(o+=e);return o},Jd=no,Hd=Yb(q1),hy=Yb("".slice),Pb=Math.ceil,d0=function(A){return function(e,o,n){var a,I,c=dy(Jd(e)),u=V1(o),d=c.length,R=n===void 0?" ":dy(n);return u<=d||R===""?c:((I=Hd(R,Pb((a=u-d)/R.length))).length>a&&(I=hy(I,0,a)),A?c+I:I+c)}},h0={start:d0(!1)},p0=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Te),K1=h0.start;wr({target:"String",proto:!0,forced:p0},{padStart:function(A){return K1(this,A,arguments.length>1?arguments[1]:void 0)}});var Jb=z,f0=mn,Hb=Zp,m0=m,D0=qo,j1=D0("species"),Vb=RegExp.prototype,py=Me,W1=ca,Vd=Mn,qd=no,y0=py("".charAt),qb=py("".charCodeAt),z1=py("".slice),Kb=function(A){return function(e,o){var n,a,I=Vd(qd(e)),c=W1(o),u=I.length;return c<0||c>=u?A?"":void 0:(n=qb(I,c))<55296||n>56319||c+1===u||(a=qb(I,c+1))<56320||a>57343?A?y0(I,c):n:A?z1(I,c,c+2):a-56320+(n-55296<<10)+65536}},fy={codeAt:Kb(!1),charAt:Kb(!0)},Z1=fy.charAt,Dy=Me,X1=ao,$1=Math.floor,R0=Dy("".charAt),M0=Dy("".replace),w0=Dy("".slice),AJ=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,eJ=/\$([$&'`]|\d{1,2})/g,jb=function(A,e,o,n,a,I){var c=o+A.length,u=n.length,d=eJ;return a!==void 0&&(a=X1(a),d=AJ),M0(I,d,function(R,k){var _;switch(R0(k,0)){case"$":return"$";case"&":return A;case"`":return w0(e,0,o);case"'":return w0(e,c);case"<":_=a[w0(k,1,-1)];break;default:var Z=+k;if(Z===0)return R;if(Z>u){var iA=$1(Z/10);return iA===0?R:iA<=u?n[iA-1]===void 0?R0(k,1):n[iA-1]+R0(k,1):R}_=n[Z-1]}return _===void 0?"":_})},Wb=z,tJ=Zr,zb=Ni,iJ=$e,Zb=Zp,oJ=TypeError,rJ=OC,Xb=z,yy=Me,nJ=function(A,e,o,n){var a=D0(A),I=!m0(function(){var R={};return R[a]=function(){return 7},""[A](R)!==7}),c=I&&!m0(function(){var R=!1,k=/a/,_;return k.exec=function(){return R=!0,null},k[a](""),!R});if(!I||!c||o){var u=/./[a],d=e(a,""[A],function(R,k,_,Z,iA){var cA=k.exec;return cA===Hb||cA===Vb.exec?I&&!iA?{done:!0,value:Jb(u,k,_,Z)}:{done:!0,value:Jb(R,_,k,Z)}:{done:!1}});f0(String.prototype,A,d[0]),f0(Vb,a,d[1])}},aJ=m,sJ=Zr,$b=Ni,gJ=Ji,IJ=ca,AL=Wr,sQ=Mn,Ry=no,eL=function(A,e,o){return e+(o?Z1(A,e).length:1)},My=An,tL=jb,iL=gy,cJ=function(A,e){var o=A.exec;if(zb(o)){var n=Wb(o,A,e);return n!==null&&tJ(n),n}if(iJ(A)==="RegExp")return Wb(Zb,A,e);throw new oJ("RegExp#exec called on incompatible receiver")},wy=qo("replace"),S0=Math.max,EJ=Math.min,oL=yy([].concat),v0=yy([].push),Sy=yy("".indexOf),rL=yy("".slice),lJ=function(A){return A===void 0?A:String(A)},CJ="a".replace(/./,"$0")==="$0",nL=!!/./[wy]&&/./[wy]("a","$0")==="",BJ=!aJ(function(){var A=/./;return A.exec=function(){var e=[];return e.groups={a:"7"},e},"".replace(A,"$")!=="7"});nJ("replace",function(A,e,o){var n=nL?"$":"$0";return[function(a,I){var c=Ry(this),u=gJ(a)?My(a,wy):void 0;return u?Xb(u,a,c,I):Xb(e,sQ(c),a,I)},function(a,I){var c=sJ(this),u=sQ(a);if(typeof I=="string"&&Sy(I,n)===-1&&Sy(I,"$<")===-1){var d=o(e,c,u,I);if(d.done)return d.value}var R=$b(I);R||(I=sQ(I));var k,_=sQ(iL(c)),Z=Sy(_,"g")!==-1;Z&&(k=Sy(_,"u")!==-1,c.lastIndex=0);for(var iA,cA=[];(iA=cJ(c,u))!==null&&(v0(cA,iA),Z);)sQ(iA[0])===""&&(c.lastIndex=eL(u,AL(c.lastIndex),k));for(var TA="",JA=0,Ie=0;Ie=JA&&(TA+=rL(u,JA,ie)+XA,JA=ie+Ft.length)}return TA+rL(u,JA)}]},!BJ||!CJ||nL);var vy=` +\v\f\r                 \u2028\u2029\uFEFF`,uJ=no,QJ=Mn,N0=vy,T0=Me("".replace),aL=RegExp("^["+N0+"]+"),dJ=RegExp("(^|[^"+N0+"])["+N0+"]+$"),hJ=function(A){return function(e){var o=QJ(uJ(e));return 1&A&&(o=T0(o,aL,"")),2&A&&(o=T0(o,dJ,"$1")),o}},pJ={trim:hJ(3)},fJ=_s.PROPER,mJ=m,sL=vy,DJ=pJ.trim;wr({target:"String",proto:!0,forced:function(A){return mJ(function(){return!!sL[A]()||"​…᠎"[A]()!=="​…᠎"||fJ&&sL[A].name!==A})}("trim")},{trim:function(){return DJ(this)}});var mI,Kd,Ny,G0={exports:{}},yJ=Cn,k0=M,Wg=Q,gL=Ni,IL=Ji,Wd=po,Ty=sg,_0=Kr,b0=Bs,L0=mn,cL=dI,RJ=YA,F0=UE,gQ=q,MJ=qo,wJ=$s,U0=on.enforce,PC=Wg.Int8Array,zd=PC&&PC.prototype,EL=Wg.Uint8ClampedArray,lL=EL&&EL.prototype,Wl=PC&&F0(PC),WE=zd&&F0(zd),SJ=Object.prototype,O0=Wg.TypeError,CL=MJ("toStringTag"),x0=wJ("TYPED_ARRAY_TAG"),Xp="TypedArrayConstructor",zE=yJ&&!!gQ&&Ty(Wg.opera)!=="Opera",BL=!1,jB={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},uL={BigInt64Array:8,BigUint64Array:8},Gy=function(A){if(!IL(A))return!1;var e=Ty(A);return Wd(jB,e)||Wd(uL,e)};for(mI in jB)(Ny=(Kd=Wg[mI])&&Kd.prototype)?U0(Ny)[Xp]=Kd:zE=!1;for(mI in uL)(Ny=(Kd=Wg[mI])&&Kd.prototype)&&(U0(Ny)[Xp]=Kd);if((!zE||!gL(Wl)||Wl===Function.prototype)&&(Wl=function(){throw new O0("Incorrect invocation")},zE))for(mI in jB)Wg[mI]&&gQ(Wg[mI],Wl);if((!zE||!WE||WE===SJ)&&(WE=Wl.prototype,zE))for(mI in jB)Wg[mI]&&gQ(Wg[mI].prototype,WE);if(zE&&F0(lL)!==WE&&gQ(lL,WE),k0&&!Wd(WE,CL))for(mI in BL=!0,cL(WE,CL,{configurable:!0,get:function(){return IL(this)?this[x0]:void 0}}),jB)Wg[mI]&&b0(Wg[mI],x0,mI);var ZE={NATIVE_ARRAY_BUFFER_VIEWS:zE,TYPED_ARRAY_TAG:BL&&x0,aTypedArray:function(A){if(Gy(A))return A;throw new O0("Target is not a typed array")},aTypedArrayConstructor:function(A){if(gL(A)&&(!gQ||RJ(Wl,A)))return A;throw new O0(_0(A)+" is not a typed array constructor")},exportTypedArrayMethod:function(A,e,o,n){if(k0){if(o)for(var a in jB){var I=Wg[a];if(I&&Wd(I.prototype,A))try{delete I.prototype[A]}catch{try{I.prototype[A]=e}catch{}}}WE[A]&&!o||L0(WE,A,o?e:zE&&zd[A]||e,n)}},exportTypedArrayStaticMethod:function(A,e,o){var n,a;if(k0){if(gQ){if(o){for(n in jB)if((a=Wg[n])&&Wd(a,A))try{delete a[A]}catch{}}if(Wl[A]&&!o)return;try{return L0(Wl,A,o?e:zE&&Wl[A]||e)}catch{}}for(n in jB)!(a=Wg[n])||a[A]&&!o||L0(a,A,e)}},isTypedArray:Gy,TypedArray:Wl,TypedArrayPrototype:WE},Y0=Q,$p=m,ky=kd,vJ=ZE.NATIVE_ARRAY_BUFFER_VIEWS,QL=Y0.ArrayBuffer,IQ=Y0.Int8Array,dL=!vJ||!$p(function(){IQ(1)})||!$p(function(){new IQ(-1)})||!ky(function(A){new IQ,new IQ(null),new IQ(1.5),new IQ(A)},!0)||$p(function(){return new IQ(new QL(2),1,void 0).length!==1}),NJ=Ji,TJ=Math.floor,hL=Number.isInteger||function(A){return!NJ(A)&&isFinite(A)&&TJ(A)===A},GJ=ca,kJ=RangeError,_y=function(A){var e=GJ(A);if(e<0)throw new kJ("The argument can't be less than 0");return e},_J=RangeError,pL=function(A,e){var o=_y(A);if(o%e)throw new _J("Wrong offset");return o},bJ=Math.round,fL=sg,LJ=Mr,FJ=TypeError,by=function(A){var e=LJ(A,"number");if(typeof e=="number")throw new FJ("Can't convert number to bigint");return BigInt(e)},mL=jc,DL=z,UJ=C_,OJ=ao,yL=hs,RL=oQ,xJ=Hp,ML=LS,wL=function(A){var e=fL(A);return e==="BigInt64Array"||e==="BigUint64Array"},YJ=ZE.aTypedArrayConstructor,PJ=by,Ly=function(A){var e,o,n,a,I,c,u,d,R=UJ(this),k=OJ(A),_=arguments.length,Z=_>1?arguments[1]:void 0,iA=Z!==void 0,cA=xJ(k);if(cA&&!ML(cA))for(d=(u=RL(k,cA)).next,k=[];!(c=DL(d,u)).done;)k.push(c.value);for(iA&&_>2&&(Z=mL(Z,arguments[2])),o=yL(k),n=new(YJ(R))(o),a=wL(n),e=0;o>e;e++)I=iA?Z(k[e],e):k[e],n[e]=a?PJ(I):+I;return n},P0=ia,J0=rS,JJ=Ji,HJ=qo("species"),SL=Array,VJ=function(A){var e;return P0(A)&&(e=A.constructor,(J0(e)&&(e===SL||P0(e.prototype))||JJ(e)&&(e=e[HJ])===null)&&(e=void 0)),e===void 0?SL:e},vL=jc,qJ=ai,KJ=ao,NL=hs,jJ=function(A,e){return new(VJ(A))(e===0?0:e)},H0=Me([].push),TL=function(A){var e=A===1,o=A===2,n=A===3,a=A===4,I=A===6,c=A===7,u=A===5||I;return function(d,R,k,_){for(var Z,iA,cA=KJ(d),TA=qJ(cA),JA=NL(TA),Ie=vL(R,k),XA=0,Ft=_||jJ,ie=e?Ft(d,JA):o||c?Ft(d,0):void 0;JA>XA;XA++)if((u||XA in TA)&&(iA=Ie(Z=TA[XA],XA,cA),A))if(e)ie[XA]=iA;else if(iA)switch(A){case 3:return!0;case 5:return Z;case 6:return XA;case 2:H0(ie,Z)}else switch(A){case 4:return!1;case 7:H0(ie,Z)}return I?-1:n||a?a:ie}},GL={forEach:TL(0)},WJ=hs,kL=wr,_L=Q,bL=z,LL=M,zJ=dL,Af=ZE,FL=LD,UL=oc,ZJ=qA,WB=Bs,XJ=hL,$J=Wr,OL=RD,V0=pL,xL=function(A){var e=bJ(A);return e<0?0:e>255?255:255&e},q0=P,cQ=po,AH=sg,K0=Ji,j0=Vo,eH=fa,W0=YA,Fy=q,tH=Lg.f,YL=Ly,PL=GL.forEach,Uy=UD,iH=dI,JL=oi,HL=f,VL=function(A,e,o){for(var n=0,a=arguments.length>2?o:WJ(e),I=new A(a);a>n;)I[n]=e[n++];return I},oH=Pw,z0=on.get,rH=on.set,EQ=on.enforce,qL=JL.f,nH=HL.f,Z0=_L.RangeError,KL=FL.ArrayBuffer,aH=KL.prototype,sH=FL.DataView,Zd=Af.NATIVE_ARRAY_BUFFER_VIEWS,jL=Af.TYPED_ARRAY_TAG,WL=Af.TypedArray,ef=Af.TypedArrayPrototype,tf=Af.isTypedArray,lQ="BYTES_PER_ELEMENT",Oy="Wrong length",xy=function(A,e){iH(A,e,{configurable:!0,get:function(){return z0(this)[e]}})},zL=function(A){var e;return W0(aH,A)||(e=AH(A))==="ArrayBuffer"||e==="SharedArrayBuffer"},X0=function(A,e){return tf(A)&&!j0(e)&&e in A&&XJ(+e)&&e>=0},Yy=function(A,e){return e=q0(e),X0(A,e)?ZJ(2,A[e]):nH(A,e)},ZL=function(A,e,o){return e=q0(e),!(X0(A,e)&&K0(o)&&cQ(o,"value"))||cQ(o,"get")||cQ(o,"set")||o.configurable||cQ(o,"writable")&&!o.writable||cQ(o,"enumerable")&&!o.enumerable?qL(A,e,o):(A[e]=o.value,A)};LL?(Zd||(HL.f=Yy,JL.f=ZL,xy(ef,"buffer"),xy(ef,"byteOffset"),xy(ef,"byteLength"),xy(ef,"length")),kL({target:"Object",stat:!0,forced:!Zd},{getOwnPropertyDescriptor:Yy,defineProperty:ZL}),G0.exports=function(A,e,o){var n=A.match(/\d+/)[0]/8,a=A+(o?"Clamped":"")+"Array",I="get"+A,c="set"+A,u=_L[a],d=u,R=d&&d.prototype,k={},_=function(iA,cA){qL(iA,cA,{get:function(){return function(TA,JA){var Ie=z0(TA);return Ie.view[I](JA*n+Ie.byteOffset,!0)}(this,cA)},set:function(TA){return function(JA,Ie,XA){var Ft=z0(JA);Ft.view[c](Ie*n+Ft.byteOffset,o?xL(XA):XA,!0)}(this,cA,TA)},enumerable:!0})};Zd?zJ&&(d=e(function(iA,cA,TA,JA){return UL(iA,R),oH(K0(cA)?zL(cA)?JA!==void 0?new u(cA,V0(TA,n),JA):TA!==void 0?new u(cA,V0(TA,n)):new u(cA):tf(cA)?VL(d,cA):bL(YL,d,cA):new u(OL(cA)),iA,d)}),Fy&&Fy(d,WL),PL(tH(u),function(iA){iA in d||WB(d,iA,u[iA])}),d.prototype=R):(d=e(function(iA,cA,TA,JA){UL(iA,R);var Ie,XA,Ft,ie=0,ke=0;if(K0(cA)){if(!zL(cA))return tf(cA)?VL(d,cA):bL(YL,d,cA);Ie=cA,ke=V0(TA,n);var Nt=cA.byteLength;if(JA===void 0){if(Nt%n)throw new Z0(Oy);if((XA=Nt-ke)<0)throw new Z0(Oy)}else if((XA=$J(JA)*n)+ke>Nt)throw new Z0(Oy);Ft=XA/n}else Ft=OL(cA),Ie=new KL(XA=Ft*n);for(rH(iA,{buffer:Ie,byteOffset:ke,byteLength:XA,length:Ft,view:new sH(Ie)});ie1?arguments[1]:void 0,e>2?arguments[2]:void 0)},$0(function(){var A=0;return new Int8Array(2).fill({valueOf:function(){return A++}}),A!==1})),(0,ZE.exportTypedArrayStaticMethod)("from",Ly,dL);var AF=Q,eF=z,ev=ZE,tF=hs,CH=pL,BH=ao,iF=m,uH=AF.RangeError,tv=AF.Int8Array,iv=tv&&tv.prototype,ov=iv&&iv.set,rv=ev.aTypedArray,oF=ev.exportTypedArrayMethod,Py=!iF(function(){var A=new Uint8ClampedArray(2);return eF(ov,A,{length:1,0:3},1),A[1]!==3}),rF=Py&&ev.NATIVE_ARRAY_BUFFER_VIEWS&&iF(function(){var A=new tv(2);return A.set(1),A.set("2",1),A[0]!==0||A[1]!==2});oF("set",function(A){rv(this);var e=CH(arguments.length>1?arguments[1]:void 0,1),o=BH(A);if(Py)return eF(ov,this,o,e);var n=this.length,a=tF(o),I=0;if(a+e>n)throw new uH("Wrong length");for(;I0&&1/n<0?1:-1:o>n}}(A))},!Jy||Ev);var aF=wr,lv=z,rf=Me,Cv=no,Bv=Ni,hH=Ji,sF=ZS,nf=Mn,pH=An,af=gy,gF=jb,fH=qo("replace"),IF=TypeError,XE=rf("".indexOf);rf("".replace);var sf=rf("".slice),mH=Math.max;aF({target:"String",proto:!0},{replaceAll:function(A,e){var o,n,a,I,c,u,d,R,k,_=Cv(this),Z=0,iA="";if(hH(A)){if(sF(A)&&(o=nf(Cv(af(A))),!~XE(o,"g")))throw new IF("`.replaceAll` does not allow non-global regexes");if(n=pH(A,fH))return lv(n,A,_,e)}for(a=nf(_),I=nf(A),(c=Bv(e))||(e=nf(e)),u=I.length,d=mH(1,u),R=XE(a,I);R!==-1;)k=c?nf(e(I,R,a)):gF(I,a,R,[],void 0,e),iA+=sf(a,Z,R)+k,Z=R+u,R=R+d>a.length?-1:XE(a,I,R+d);return Z1?arguments[1]:void 0)},EF=Q,lF=uv,RH=Qv,Vy=yH,MH=Bs,CF=function(A){if(A&&A.forEach!==Vy)try{MH(A,"forEach",Vy)}catch{A.forEach=Vy}};for(var dv in lF)lF[dv]&&CF(EF[dv]&&EF[dv].prototype);CF(RH);var qy=Q,BF=uv,wH=Qv,gf=si,If=Bs,SH=Rs,hv=qo("iterator"),pv=gf.values,uF=function(A,e){if(A){if(A[hv]!==pv)try{If(A,hv,pv)}catch{A[hv]=pv}if(SH(A,e,!0),BF[e]){for(var o in gf)if(A[o]!==gf[o])try{If(A,o,gf[o])}catch{A[o]=gf[o]}}}};for(var fv in BF)uF(qy[fv]&&qy[fv].prototype,fv);uF(wH,"DOMTokenList");var mv=qD.clear;wr({global:!0,bind:!0,enumerable:!0,forced:Q.clearImmediate!==mv},{clearImmediate:mv});var cf=Q,vH=OC,NH=Ni,TH=_n,GH=Te,kH=UA,_H=JD,Dv=cf.Function,bH=/MSIE .\./.test(GH)||TH==="BUN"&&function(){var A=cf.Bun.version.split(".");return A.length<3||A[0]==="0"&&(A[1]<3||A[1]==="3"&&A[2]==="0")}(),QF=wr,dF=Q,Ky=qD.set,LH=function(A,e){var o=1;return bH?function(n,a){var I=_H(arguments.length,1)>o,c=NH(n)?n:Dv(n),u=I?kH(arguments,o):[],d=I?function(){vH(c,this,u)}:c;return A(d)}:A},yv=dF.setImmediate?LH(Ky):Ky;QF({global:!0,bind:!0,enumerable:!0,forced:dF.setImmediate!==yv},{setImmediate:yv});var JC=fy.charAt,FH=Mn,jy=on,UH=xA,hF=Qe,pF="String Iterator",OH=jy.set,fF=jy.getterFor(pF);UH(String,"String",function(A){OH(this,{type:pF,string:FH(A),index:0})},function(){var A,e=fF(this),o=e.string,n=e.index;return n>=o.length?hF(void 0,!0):(A=JC(o,n),e.index+=A.length,hF(A,!1))});var xH=m,YH=M,PH=qo("iterator"),mF=!xH(function(){var A=new URL("b?a=1&b=2&c=3","https://a"),e=A.searchParams,o=new URLSearchParams("a=1&a=2&b=3"),n="";return A.pathname="c%20d",e.forEach(function(a,I){e.delete("b"),n+=I+a}),o.delete("a",2),o.delete("b",void 0),!e.size&&!YH||!e.sort||A.href!=="https://a/c%20d?a=1&c=3"||e.get("c")!=="3"||String(new URLSearchParams("?a=1"))!=="a=1"||!e[PH]||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"||n!=="a1c3"||new URL("https://x",void 0).host!=="x"}),DF=M,JH=Me,Rv=z,Mv=m,wv=pI,HH=Ug,VH=sA,qH=ao,yF=ai,CQ=Object.assign,RF=Object.defineProperty,MF=JH([].concat),KH=!CQ||Mv(function(){if(DF&&CQ({b:1},CQ(RF({},"a",{enumerable:!0,get:function(){RF(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var A={},e={},o=Symbol("assign detection"),n="abcdefghijklmnopqrst";return A[o]=7,n.split("").forEach(function(a){e[a]=a}),CQ({},A)[o]!==7||wv(CQ({},e)).join("")!==n})?function(A,e){for(var o=qH(A),n=arguments.length,a=1,I=HH.f,c=VH.f;n>a;)for(var u,d=yF(arguments[a++]),R=I?MF(wv(d),I(d)):wv(d),k=R.length,_=0;k>_;)u=R[_++],DF&&!Rv(c,d,u)||(o[u]=d[u]);return o}:CQ,jH=Zr,WH=ab,zH=M,ZH=oi,wF=qA,XH=jc,Ef=z,SF=ao,vF=function(A,e,o,n){try{return n?e(jH(o)[0],o[1]):e(o)}catch(a){WH(A,"throw",a)}},Sv=LS,$H=rS,AV=hs,lf=function(A,e,o){zH?ZH.f(A,e,wF(0,o)):A[e]=o},vv=oQ,eV=Hp,NF=Array,zB=Me,Nv=2147483647,TF=/[^\0-\u007E]/,Tv=/[.\u3002\uFF0E\uFF61]/g,GF="Overflow: input needs wider integers to process",kF=RangeError,tV=zB(Tv.exec),ZB=Math.floor,Wy=String.fromCharCode,zy=zB("".charCodeAt),sc=zB([].join),XB=zB([].push),Pn=zB("".replace),_F=zB("".split),iV=zB("".toLowerCase),bF=function(A){return A+22+75*(A<26)},Gv=function(A,e,o){var n=0;for(A=o?ZB(A/700):A>>1,A+=ZB(A/e);A>455;)A=ZB(A/35),n+=36;return ZB(n+36*A/(A+38))},oV=function(A){var e=[];A=function(Ie){for(var XA=[],Ft=0,ie=Ie.length;Ft=55296&&ke<=56319&&Ft=I&&nZB((Nv-c)/_))throw new kF(GF);for(c+=(k-I)*_,I=k,o=0;oNv)throw new kF(GF);if(n===I){for(var Z=c,iA=36;;){var cA=iA<=u?1:iA>=u+26?26:iA-u;if(Za;){if(e=+arguments[a++],rV(e,1114111)!==e)throw new nV(e+" is not a valid code point");o[a]=e<65536?HC(e):HC(55296+((e-=65536)>>10),e%1024+56320)}return Bf(o,"")}});var BQ=wr,Ah=Q,uQ=T_,kv=MA,To=z,gc=Me,eh=M,_v=mF,FF=mn,aV=dI,sV=HE,gV=Rs,IV=UB,uf=on,UF=oc,bv=Ni,cV=po,EV=jc,lV=sg,CV=Zr,OF=Ji,Bg=Mn,BV=fa,xF=qA,YF=oQ,uV=Hp,Zy=Qe,th=JD,QV=He,dV=qo("iterator"),QQ="URLSearchParams",Lv=QQ+"Iterator",PF=uf.set,Ps=uf.getterFor(QQ),VC=uf.getterFor(Lv),JF=uQ("fetch"),ih=uQ("Request"),Qf=uQ("Headers"),Fv=ih&&ih.prototype,HF=Qf&&Qf.prototype,VF=Ah.TypeError,hV=Ah.encodeURIComponent,pV=String.fromCharCode,fV=kv("String","fromCodePoint"),mV=parseInt,Xy=gc("".charAt),$y=gc([].join),qC=gc([].push),qF=gc("".replace),DV=gc([].shift),KF=gc([].splice),jF=gc("".split),WF=gc("".slice),Uv=gc(/./.exec),zF=/\+/g,yV=/^[0-9a-f]+$/i,ZF=function(A,e){var o=WF(A,e,e+2);return Uv(yV,o)?mV(o,16):NaN},RV=function(A){for(var e=0,o=128;o>0&&A&o;o>>=1)e++;return e},MV=function(A){var e=null;switch(A.length){case 1:e=A[0];break;case 2:e=(31&A[0])<<6|63&A[1];break;case 3:e=(15&A[0])<<12|(63&A[1])<<6|63&A[2];break;case 4:e=(7&A[0])<<18|(63&A[1])<<12|(63&A[2])<<6|63&A[3]}return e>1114111?null:e},XF=function(A){for(var e=(A=qF(A,zF," ")).length,o="",n=0;ne){o+="%",n++;continue}var I=ZF(A,n+1);if(I!=I){o+=a,n++;continue}n+=2;var c=RV(I);if(c===0)a=pV(I);else{if(c===1||c>4){o+="�",n++;continue}for(var u=[I],d=1;de||Xy(A,n)!=="%");){var R=ZF(A,n+1);if(R!=R){n+=3;break}if(R>191||R<128)break;qC(u,R),n+=2,d++}if(u.length!==c){o+="�";continue}var k=MV(u);k===null?o+="�":a=fV(k)}}o+=a,n++}return o},wV=/[!'()~]|%20/g,SV={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},vV=function(A){return SV[A]},$F=function(A){return qF(hV(A),wV,vV)},Ov=IV(function(A,e){PF(this,{type:Lv,target:Ps(A).entries,index:0,kind:e})},QQ,function(){var A=VC(this),e=A.target,o=A.index++;if(!e||o>=e.length)return A.target=null,Zy(void 0,!0);var n=e[o];switch(A.kind){case"keys":return Zy(n.key,!1);case"values":return Zy(n.value,!1)}return Zy([n.key,n.value],!1)},!0),AU=function(A){this.entries=[],this.url=null,A!==void 0&&(OF(A)?this.parseObject(A):this.parseQuery(typeof A=="string"?Xy(A,0)==="?"?WF(A,1):A:Bg(A)))};AU.prototype={type:QQ,bindURL:function(A){this.url=A,this.update()},parseObject:function(A){var e,o,n,a,I,c,u,d=this.entries,R=uV(A);if(R)for(o=(e=YF(A,R)).next;!(n=To(o,e)).done;){if(I=(a=YF(CV(n.value))).next,(c=To(I,a)).done||(u=To(I,a)).done||!To(I,a).done)throw new VF("Expected sequence with length 2");qC(d,{key:Bg(c.value),value:Bg(u.value)})}else for(var k in A)cV(A,k)&&qC(d,{key:k,value:Bg(A[k])})},parseQuery:function(A){if(A)for(var e,o,n=this.entries,a=jF(A,"&"),I=0;I0?arguments[0]:void 0));eh||(this.size=A.entries.length)},dQ=oh.prototype;if(sV(dQ,{append:function(A,e){var o=Ps(this);th(arguments.length,2),qC(o.entries,{key:Bg(A),value:Bg(e)}),eh||this.size++,o.updateURL()},delete:function(A){for(var e=Ps(this),o=th(arguments.length,1),n=e.entries,a=Bg(A),I=o<2?void 0:arguments[1],c=I===void 0?I:Bg(I),u=0;uo.key?1:-1}),A.updateURL()},forEach:function(A){for(var e,o=Ps(this).entries,n=EV(A,arguments.length>1?arguments[1]:void 0),a=0;a1?eU(arguments[1]):{})}}),bv(ih)){var Yv=function(A){return UF(this,Fv),new ih(A,arguments.length>1?eU(arguments[1]):{})};Fv.constructor=Yv,Yv.prototype=Fv,BQ({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:Yv})}}var Ic,TV=wr,Pv=M,tU=mF,Jv=Q,iU=jc,Wc=Me,AR=mn,zc=dI,GV=oc,Hv=po,Vv=KH,$B=function(A){var e=SF(A),o=$H(this),n=arguments.length,a=n>1?arguments[1]:void 0,I=a!==void 0;I&&(a=XH(a,n>2?arguments[2]:void 0));var c,u,d,R,k,_,Z=eV(e),iA=0;if(!Z||this===NF&&Sv(Z))for(c=AV(e),u=o?new this(c):NF(c);c>iA;iA++)_=I?a(e[iA],iA):e[iA],lf(u,iA,_);else for(u=o?new this:[],k=(R=vv(e,Z)).next;!(d=Ef(k,R)).done;iA++)_=I?vF(R,a,[d.value,iA],!0):d.value,lf(u,iA,_);return u.length=iA,u},$E=UA,qv=fy.codeAt,kV=function(A){var e,o,n=[],a=_F(Pn(iV(A),Tv,"."),".");for(e=0;e?@[\\\]^|]/,PV=/[\0\t\n\r #/:<>?@[\\\]^|]/,JV=/^[\u0000-\u0020]+/,HV=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,VV=/[\t\n\r]/g,ah=function(A){var e,o,n,a;if(typeof A=="number"){for(e=[],o=0;o<4;o++)OV(e,A%256),A=jC(A/256);return df(e,".")}if(typeof A=="object"){for(e="",n=function(I){for(var c=null,u=1,d=null,R=0,k=0;k<8;k++)I[k]!==0?(R>u&&(c=d,u=R),d=null,R=0):(d===null&&(d=k),++R);return R>u?d:c}(A),o=0;o<8;o++)a&&A[o]===0||(a&&(a=!1),n===o?(e+=o?":":"::",a=!0):(e+=UV(A[o],16),o<7&&(e+=":")));return"["+e+"]"}return A},sh={},cU=Vv({},sh,{" ":1,'"':1,"<":1,">":1,"`":1}),Xv=Vv({},cU,{"#":1,"?":1,"{":1,"}":1}),eu=Vv({},Xv,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),el=function(A,e){var o=qv(A,0);return o>32&&o<127&&!Hv(e,A)?A:encodeURIComponent(A)},WC={ftp:21,file:null,http:80,https:443,ws:80,wss:443},gh=function(A,e){var o;return A.length===2&&Al(hf,Zc(A,0))&&((o=Zc(A,1))===":"||!e&&o==="|")},$v=function(A){var e;return A.length>1&&gh(hQ(A,0,2))&&(A.length===2||(e=Zc(A,2))==="/"||e==="\\"||e==="?"||e==="#")},pf=function(A){return A==="."||rR(A)==="%2e"},EU=function(A){return(A=rR(A))===".."||A==="%2e."||A===".%2e"||A==="%2e%2e"},cc={},DI={},tu={},zl={},iu={},sR={},lU={},ff={},gR={},IR={},cR={},ER={},lR={},CR={},AN={},BR={},Ih={},Zl={},mf={},yI={},ug={},uR=function(A,e,o){var n,a,I,c=KC(A);if(e){if(a=this.parse(c))throw new jv(a);this.searchParams=null}else{if(o!==void 0&&(n=new uR(o,!0)),a=this.parse(c,null,n))throw new jv(a);(I=FV(new LV)).bindURL(this),this.searchParams=I}};uR.prototype={type:"URL",parse:function(A,e,o){var n,a,I,c,u=this,d=e||cc,R=0,k="",_=!1,Z=!1,iA=!1;for(A=KC(A),e||(u.scheme="",u.username="",u.password="",u.host=null,u.port=null,u.path=[],u.query=null,u.fragment=null,u.cannotBeABaseURL=!1,A=iR(A,JV,""),A=iR(A,HV,"$1")),A=iR(A,VV,""),n=$B(A);R<=n.length;){switch(a=n[R],d){case cc:if(!a||!Al(hf,a)){if(e)return zv;d=tu;continue}k+=rR(a),d=DI;break;case DI:if(a&&(Al(xV,a)||a==="+"||a==="-"||a==="."))k+=rR(a);else{if(a!==":"){if(e)return zv;k="",d=tu,R=0;continue}if(e&&(u.isSpecial()!==Hv(WC,k)||k==="file"&&(u.includesCredentials()||u.port!==null)||u.scheme==="file"&&!u.host))return;if(u.scheme=k,e)return void(u.isSpecial()&&WC[u.scheme]===u.port&&(u.port=null));k="",u.scheme==="file"?d=CR:u.isSpecial()&&o&&o.scheme===u.scheme?d=zl:u.isSpecial()?d=ff:n[R+1]==="/"?(d=iu,R++):(u.cannotBeABaseURL=!0,nh(u.path,""),d=mf)}break;case tu:if(!o||o.cannotBeABaseURL&&a!=="#")return zv;if(o.cannotBeABaseURL&&a==="#"){u.scheme=o.scheme,u.path=$E(o.path),u.query=o.query,u.fragment="",u.cannotBeABaseURL=!0,d=ug;break}d=o.scheme==="file"?CR:sR;continue;case zl:if(a!=="/"||n[R+1]!=="/"){d=sR;continue}d=gR,R++;break;case iu:if(a==="/"){d=IR;break}d=Zl;continue;case sR:if(u.scheme=o.scheme,a===Ic)u.username=o.username,u.password=o.password,u.host=o.host,u.port=o.port,u.path=$E(o.path),u.query=o.query;else if(a==="/"||a==="\\"&&u.isSpecial())d=lU;else if(a==="?")u.username=o.username,u.password=o.password,u.host=o.host,u.port=o.port,u.path=$E(o.path),u.query="",d=yI;else{if(a!=="#"){u.username=o.username,u.password=o.password,u.host=o.host,u.port=o.port,u.path=$E(o.path),u.path.length--,d=Zl;continue}u.username=o.username,u.password=o.password,u.host=o.host,u.port=o.port,u.path=$E(o.path),u.query=o.query,u.fragment="",d=ug}break;case lU:if(!u.isSpecial()||a!=="/"&&a!=="\\"){if(a!=="/"){u.username=o.username,u.password=o.password,u.host=o.host,u.port=o.port,d=Zl;continue}d=IR}else d=gR;break;case ff:if(d=gR,a!=="/"||Zc(k,R+1)!=="/")continue;R++;break;case gR:if(a!=="/"&&a!=="\\"){d=IR;continue}break;case IR:if(a==="@"){_&&(k="%40"+k),_=!0,I=$B(k);for(var cA=0;cA65535)return nR;u.port=u.isSpecial()&&Ie===WC[u.scheme]?null:Ie,k=""}if(e)return;d=Ih;continue}return nR}k+=a;break;case CR:if(u.scheme="file",a==="/"||a==="\\")d=AN;else{if(!o||o.scheme!=="file"){d=Zl;continue}switch(a){case Ic:u.host=o.host,u.path=$E(o.path),u.query=o.query;break;case"?":u.host=o.host,u.path=$E(o.path),u.query="",d=yI;break;case"#":u.host=o.host,u.path=$E(o.path),u.query=o.query,u.fragment="",d=ug;break;default:$v(df($E(n,R),""))||(u.host=o.host,u.path=$E(o.path),u.shortenPath()),d=Zl;continue}}break;case AN:if(a==="/"||a==="\\"){d=BR;break}o&&o.scheme==="file"&&!$v(df($E(n,R),""))&&(gh(o.path[0],!0)?nh(u.path,o.path[0]):u.host=o.host),d=Zl;continue;case BR:if(a===Ic||a==="/"||a==="\\"||a==="?"||a==="#"){if(!e&&gh(k))d=Zl;else if(k===""){if(u.host="",e)return;d=Ih}else{if(c=u.parseHost(k))return c;if(u.host==="localhost"&&(u.host=""),e)return;k="",d=Ih}continue}k+=a;break;case Ih:if(u.isSpecial()){if(d=Zl,a!=="/"&&a!=="\\")continue}else if(e||a!=="?")if(e||a!=="#"){if(a!==Ic&&(d=Zl,a!=="/"))continue}else u.fragment="",d=ug;else u.query="",d=yI;break;case Zl:if(a===Ic||a==="/"||a==="\\"&&u.isSpecial()||!e&&(a==="?"||a==="#")){if(EU(k)?(u.shortenPath(),a==="/"||a==="\\"&&u.isSpecial()||nh(u.path,"")):pf(k)?a==="/"||a==="\\"&&u.isSpecial()||nh(u.path,""):(u.scheme==="file"&&!u.path.length&&gh(k)&&(u.host&&(u.host=""),k=Zc(k,0)+":"),nh(u.path,k)),k="",u.scheme==="file"&&(a===Ic||a==="?"||a==="#"))for(;u.path.length>1&&u.path[0]==="";)oR(u.path);a==="?"?(u.query="",d=yI):a==="#"&&(u.fragment="",d=ug)}else k+=el(a,Xv);break;case mf:a==="?"?(u.query="",d=yI):a==="#"?(u.fragment="",d=ug):a!==Ic&&(u.path[0]+=el(a,sh));break;case yI:e||a!=="#"?a!==Ic&&(a==="'"&&u.isSpecial()?u.query+="%27":u.query+=a==="#"?"%23":el(a,sh)):(u.fragment="",d=ug);break;case ug:a!==Ic&&(u.fragment+=el(a,cU))}R++}},parseHost:function(A){var e,o,n;if(Zc(A,0)==="["){if(Zc(A,A.length-1)!=="]"||(e=function(a){var I,c,u,d,R,k,_,Z=[0,0,0,0,0,0,0,0],iA=0,cA=null,TA=0,JA=function(){return Zc(a,TA)};if(JA()===":"){if(Zc(a,1)!==":")return;TA+=2,cA=++iA}for(;JA();){if(iA===8)return;if(JA()!==":"){for(I=c=0;c<4&&Al(gU,JA());)I=16*I+tR(JA(),16),TA++,c++;if(JA()==="."){if(c===0||(TA-=c,iA>6))return;for(u=0;JA();){if(d=null,u>0){if(!(JA()==="."&&u<4))return;TA++}if(!Al(Zv,JA()))return;for(;Al(Zv,JA());){if(R=tR(JA(),10),d===null)d=R;else{if(d===0)return;d=10*d+R}if(d>255)return;TA++}Z[iA]=256*Z[iA]+d,++u!==2&&u!==4||iA++}if(u!==4)return;break}if(JA()===":"){if(TA++,!JA())return}else if(JA())return;Z[iA++]=I}else{if(cA!==null)return;TA++,cA=++iA}}if(cA!==null)for(k=iA-cA,iA=7;iA!==0&&k>0;)_=Z[iA],Z[iA--]=Z[cA+k-1],Z[cA+--k]=_;else if(iA!==8)return;return Z}(hQ(A,1,-1)),!e))return Au;this.host=e}else if(this.isSpecial()){if(A=kV(A),Al(IU,A)||(e=function(a){var I,c,u,d,R,k,_,Z=Wv(a,".");if(Z.length&&Z[Z.length-1]===""&&Z.length--,(I=Z.length)>4)return a;for(c=[],u=0;u1&&Zc(d,0)==="0"&&(R=Al(aR,d)?16:8,d=hQ(d,R===8?1:2)),d==="")k=0;else{if(!Al(R===10?sU:R===8?YV:gU,d))return a;k=tR(d,R)}nh(c,k)}for(u=0;u=nU(256,5-I))return null}else if(k>255)return null;for(_=aU(c),u=0;u1?arguments[1]:void 0,n=bV(e,new uR(A,!1,o));Pv||(e.href=n.serialize(),e.origin=n.getOrigin(),e.protocol=n.getProtocol(),e.username=n.getUsername(),e.password=n.getPassword(),e.host=n.getHost(),e.hostname=n.getHostname(),e.port=n.getPort(),e.pathname=n.getPathname(),e.search=n.getSearch(),e.searchParams=n.getSearchParams(),e.hash=n.getHash())},Qg=zC.prototype,dg=function(A,e){return{get:function(){return eR(this)[A]()},set:e&&function(o){return eR(this)[e](o)},configurable:!0,enumerable:!0}};if(Pv&&(zc(Qg,"href",dg("serialize","setHref")),zc(Qg,"origin",dg("getOrigin")),zc(Qg,"protocol",dg("getProtocol","setProtocol")),zc(Qg,"username",dg("getUsername","setUsername")),zc(Qg,"password",dg("getPassword","setPassword")),zc(Qg,"host",dg("getHost","setHost")),zc(Qg,"hostname",dg("getHostname","setHostname")),zc(Qg,"port",dg("getPort","setPort")),zc(Qg,"pathname",dg("getPathname","setPathname")),zc(Qg,"search",dg("getSearch","setSearch")),zc(Qg,"searchParams",dg("getSearchParams")),zc(Qg,"hash",dg("getHash","setHash"))),AR(Qg,"toJSON",function(){return eR(this).serialize()},{enumerable:!0}),AR(Qg,"toString",function(){return eR(this).serialize()},{enumerable:!0}),rh){var CU=rh.createObjectURL,QR=rh.revokeObjectURL;CU&&AR(zC,"createObjectURL",iU(CU,rh)),QR&&AR(zC,"revokeObjectURL",iU(QR,rh))}_V(zC,"URL"),TV({global:!0,constructor:!0,forced:!tU,sham:!Pv},{URL:zC});var BU=z;wr({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return BU(URL.prototype.toString,this)}});let uU=!0,dR=!0;function Df(A,e,o){const n=A.match(e);return n&&n.length>=o&&parseFloat(n[o],10)}function ou(A,e,o){if(!A.RTCPeerConnection)return;const n=A.RTCPeerConnection.prototype,a=n.addEventListener;n.addEventListener=function(c,u){if(c!==e)return a.apply(this,arguments);const d=R=>{const k=o(R);k&&(u.handleEvent?u.handleEvent(k):u(k))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(u,d),a.apply(this,[c,d])};const I=n.removeEventListener;n.removeEventListener=function(c,u){if(c!==e||!this._eventMap||!this._eventMap[e])return I.apply(this,arguments);if(!this._eventMap[e].has(u))return I.apply(this,arguments);const d=this._eventMap[e].get(u);return this._eventMap[e].delete(u),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,I.apply(this,[c,d])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(c){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),c&&this.addEventListener(e,this["_on"+e]=c)},enumerable:!0,configurable:!0})}function QU(A){return typeof A!="boolean"?new Error("Argument type: "+typeof A+". Please use a boolean."):(uU=A,A?"adapter.js logging disabled":"adapter.js logging enabled")}function qV(A){return typeof A!="boolean"?new Error("Argument type: "+typeof A+". Please use a boolean."):(dR=!A,"adapter.js deprecation warnings "+(A?"disabled":"enabled"))}function hR(){if(typeof window=="object"){if(uU)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function yf(A,e){dR&&console.warn(A+" is deprecated, please use "+e+" instead.")}function eN(A){return Object.prototype.toString.call(A)==="[object Object]"}function tN(A){return eN(A)?Object.keys(A).reduce(function(e,o){const n=eN(A[o]),a=n?tN(A[o]):A[o],I=n&&!Object.keys(a).length;return a===void 0||I?e:Object.assign(e,{[o]:a})},{}):A}function iN(A,e,o){e&&!o.has(e.id)&&(o.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?iN(A,A.get(e[n]),o):n.endsWith("Ids")&&e[n].forEach(a=>{iN(A,A.get(a),o)})}))}function dU(A,e,o){const n=o?"outbound-rtp":"inbound-rtp",a=new Map;if(e===null)return a;const I=[];return A.forEach(c=>{c.type==="track"&&c.trackIdentifier===e.id&&I.push(c)}),I.forEach(c=>{A.forEach(u=>{u.type===n&&u.trackId===c.id&&iN(A,u,a)})}),a}const oN=hR;function hU(A,e){const o=A&&A.navigator;if(!o.mediaDevices)return;const n=function(c){if(typeof c!="object"||c.mandatory||c.optional)return c;const u={};return Object.keys(c).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const R=typeof c[d]=="object"?c[d]:{ideal:c[d]};R.exact!==void 0&&typeof R.exact=="number"&&(R.min=R.max=R.exact);const k=function(_,Z){return _?_+Z.charAt(0).toUpperCase()+Z.slice(1):Z==="deviceId"?"sourceId":Z};if(R.ideal!==void 0){u.optional=u.optional||[];let _={};typeof R.ideal=="number"?(_[k("min",d)]=R.ideal,u.optional.push(_),_={},_[k("max",d)]=R.ideal,u.optional.push(_)):(_[k("",d)]=R.ideal,u.optional.push(_))}R.exact!==void 0&&typeof R.exact!="number"?(u.mandatory=u.mandatory||{},u.mandatory[k("",d)]=R.exact):["min","max"].forEach(_=>{R[_]!==void 0&&(u.mandatory=u.mandatory||{},u.mandatory[k(_,d)]=R[_])})}),c.advanced&&(u.optional=(u.optional||[]).concat(c.advanced)),u},a=function(c,u){if(e.version>=61)return u(c);if((c=JSON.parse(JSON.stringify(c)))&&typeof c.audio=="object"){const d=function(R,k,_){k in R&&!(_ in R)&&(R[_]=R[k],delete R[k])};d((c=JSON.parse(JSON.stringify(c))).audio,"autoGainControl","googAutoGainControl"),d(c.audio,"noiseSuppression","googNoiseSuppression"),c.audio=n(c.audio)}if(c&&typeof c.video=="object"){let d=c.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const R=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&(!o.mediaDevices.getSupportedConstraints||!o.mediaDevices.getSupportedConstraints().facingMode||R)){let k;if(delete c.video.facingMode,d.exact==="environment"||d.ideal==="environment"?k=["back","rear"]:d.exact!=="user"&&d.ideal!=="user"||(k=["front"]),k)return o.mediaDevices.enumerateDevices().then(_=>{_=_.filter(iA=>iA.kind==="videoinput");let Z=_.find(iA=>k.some(cA=>iA.label.toLowerCase().includes(cA)));return!Z&&_.length&&k.includes("back")&&(Z=_[_.length-1]),Z&&(c.video.deviceId=d.exact?{exact:Z.deviceId}:{ideal:Z.deviceId}),c.video=n(c.video),oN("chrome: "+JSON.stringify(c)),u(c)})}c.video=n(c.video)}return oN("chrome: "+JSON.stringify(c)),u(c)},I=function(c){return e.version>=64?c:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[c.name]||c.name,message:c.message,constraint:c.constraint||c.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(o.getUserMedia=function(c,u,d){a(c,R=>{o.webkitGetUserMedia(R,u,k=>{d&&d(I(k))})})}.bind(o),o.mediaDevices.getUserMedia){const c=o.mediaDevices.getUserMedia.bind(o.mediaDevices);o.mediaDevices.getUserMedia=function(u){return a(u,d=>c(d).then(R=>{if(d.audio&&!R.getAudioTracks().length||d.video&&!R.getVideoTracks().length)throw R.getTracks().forEach(k=>{k.stop()}),new DOMException("","NotFoundError");return R},R=>Promise.reject(I(R))))}}}function pU(A){A.MediaStream=A.MediaStream||A.webkitMediaStream}function fU(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 e=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=o=>{o.stream.addEventListener("addtrack",n=>{let a;a=A.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(c=>c.track&&c.track.id===n.track.id):{track:n.track};const I=new Event("track");I.track=n.track,I.receiver=a,I.transceiver={receiver:a},I.streams=[o.stream],this.dispatchEvent(I)}),o.stream.getTracks().forEach(n=>{let a;a=A.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(c=>c.track&&c.track.id===n.id):{track:n};const I=new Event("track");I.track=n,I.receiver=a,I.transceiver={receiver:a},I.streams=[o.stream],this.dispatchEvent(I)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else ou(A,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function rN(A){if(typeof A=="object"&&A.RTCPeerConnection&&!("getSenders"in A.RTCPeerConnection.prototype)&&"createDTMFSender"in A.RTCPeerConnection.prototype){const e=function(a,I){return{track:I,get dtmf(){return this._dtmf===void 0&&(I.kind==="audio"?this._dtmf=a.createDTMFSender(I):this._dtmf=null),this._dtmf},_pc:a}};if(!A.RTCPeerConnection.prototype.getSenders){A.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const a=A.RTCPeerConnection.prototype.addTrack;A.RTCPeerConnection.prototype.addTrack=function(c,u){let d=a.apply(this,arguments);return d||(d=e(this,c),this._senders.push(d)),d};const I=A.RTCPeerConnection.prototype.removeTrack;A.RTCPeerConnection.prototype.removeTrack=function(c){I.apply(this,arguments);const u=this._senders.indexOf(c);u!==-1&&this._senders.splice(u,1)}}const o=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(a){this._senders=this._senders||[],o.apply(this,[a]),a.getTracks().forEach(I=>{this._senders.push(e(this,I))})};const n=A.RTCPeerConnection.prototype.removeStream;A.RTCPeerConnection.prototype.removeStream=function(a){this._senders=this._senders||[],n.apply(this,[a]),a.getTracks().forEach(I=>{const c=this._senders.find(u=>u.track===I);c&&this._senders.splice(this._senders.indexOf(c),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 e=A.RTCPeerConnection.prototype.getSenders;A.RTCPeerConnection.prototype.getSenders=function(){const o=e.apply(this,[]);return o.forEach(n=>n._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 mU(A){if(!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){const[o,n,a]=arguments;if(arguments.length>0&&typeof o=="function")return e.apply(this,arguments);if(e.length===0&&(arguments.length===0||typeof o!="function"))return e.apply(this,[]);const I=function(u){const d={};return u.result().forEach(R=>{const k={id:R.id,timestamp:R.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[R.type]||R.type};R.names().forEach(_=>{k[_]=R.stat(_)}),d[k.id]=k}),d},c=function(u){return new Map(Object.keys(u).map(d=>[d,u[d]]))};if(arguments.length>=2){const u=function(d){n(c(I(d)))};return e.apply(this,[u,o])}return new Promise((u,d)=>{e.apply(this,[function(R){u(c(I(R)))},d])}).then(n,a)}}function nN(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 a=o.apply(this,[]);return a.forEach(I=>I._pc=this),a});const n=A.RTCPeerConnection.prototype.addTrack;n&&(A.RTCPeerConnection.prototype.addTrack=function(){const a=n.apply(this,arguments);return a._pc=this,a}),A.RTCRtpSender.prototype.getStats=function(){const a=this;return this._pc.getStats().then(I=>dU(I,a.track,!0))}}if(!("getStats"in A.RTCRtpReceiver.prototype)){const o=A.RTCPeerConnection.prototype.getReceivers;o&&(A.RTCPeerConnection.prototype.getReceivers=function(){const n=o.apply(this,[]);return n.forEach(a=>a._pc=this),n}),ou(A,"track",n=>(n.receiver._pc=n.srcElement,n)),A.RTCRtpReceiver.prototype.getStats=function(){const n=this;return this._pc.getStats().then(a=>dU(a,n.track,!1))}}if(!("getStats"in A.RTCRtpSender.prototype)||!("getStats"in A.RTCRtpReceiver.prototype))return;const e=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof A.MediaStreamTrack){const o=arguments[0];let n,a,I;return this.getSenders().forEach(c=>{c.track===o&&(n?I=!0:n=c)}),this.getReceivers().forEach(c=>(c.track===o&&(a?I=!0:a=c),c.track===o)),I||n&&a?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):n?n.getStats():a?a.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function DU(A){A.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(I=>this._shimmedLocalStreams[I][0])};const e=A.RTCPeerConnection.prototype.addTrack;A.RTCPeerConnection.prototype.addTrack=function(I,c){if(!c)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const u=e.apply(this,arguments);return this._shimmedLocalStreams[c.id]?this._shimmedLocalStreams[c.id].indexOf(u)===-1&&this._shimmedLocalStreams[c.id].push(u):this._shimmedLocalStreams[c.id]=[c,u],u};const o=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(I){this._shimmedLocalStreams=this._shimmedLocalStreams||{},I.getTracks().forEach(d=>{if(this.getSenders().find(R=>R.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const c=this.getSenders();o.apply(this,arguments);const u=this.getSenders().filter(d=>c.indexOf(d)===-1);this._shimmedLocalStreams[I.id]=[I].concat(u)};const n=A.RTCPeerConnection.prototype.removeStream;A.RTCPeerConnection.prototype.removeStream=function(I){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[I.id],n.apply(this,arguments)};const a=A.RTCPeerConnection.prototype.removeTrack;A.RTCPeerConnection.prototype.removeTrack=function(I){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},I&&Object.keys(this._shimmedLocalStreams).forEach(c=>{const u=this._shimmedLocalStreams[c].indexOf(I);u!==-1&&this._shimmedLocalStreams[c].splice(u,1),this._shimmedLocalStreams[c].length===1&&delete this._shimmedLocalStreams[c]}),a.apply(this,arguments)}}function yU(A,e){if(!A.RTCPeerConnection)return;if(A.RTCPeerConnection.prototype.addTrack&&e.version>=65)return DU(A);const o=A.RTCPeerConnection.prototype.getLocalStreams;A.RTCPeerConnection.prototype.getLocalStreams=function(){const d=o.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(R=>this._reverseStreams[R.id])};const n=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(R=>{if(this.getSenders().find(k=>k.track===R))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const R=new A.MediaStream(d.getTracks());this._streams[d.id]=R,this._reverseStreams[R.id]=d,d=R}n.apply(this,[d])};const a=A.RTCPeerConnection.prototype.removeStream;function I(d,R){let k=R.sdp;return Object.keys(d._reverseStreams||[]).forEach(_=>{const Z=d._reverseStreams[_],iA=d._streams[Z.id];k=k.replace(new RegExp(iA.id,"g"),Z.id)}),new RTCSessionDescription({type:R.type,sdp:k})}A.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},a.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},A.RTCPeerConnection.prototype.addTrack=function(d,R){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const k=[].slice.call(arguments,1);if(k.length!==1||!k[0].getTracks().find(Z=>Z===d))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(Z=>Z.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const _=this._streams[R.id];if(_)_.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const Z=new A.MediaStream([d]);this._streams[R.id]=Z,this._reverseStreams[Z.id]=R,this.addStream(Z)}return this.getSenders().find(Z=>Z.track===d)},["createOffer","createAnswer"].forEach(function(d){const R=A.RTCPeerConnection.prototype[d],k={[d](){const _=arguments;return arguments.length&&typeof arguments[0]=="function"?R.apply(this,[Z=>{const iA=I(this,Z);_[0].apply(null,[iA])},Z=>{_[1]&&_[1].apply(null,Z)},arguments[2]]):R.apply(this,arguments).then(Z=>I(this,Z))}};A.RTCPeerConnection.prototype[d]=k[d]});const c=A.RTCPeerConnection.prototype.setLocalDescription;A.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(d,R){let k=R.sdp;return Object.keys(d._reverseStreams||[]).forEach(_=>{const Z=d._reverseStreams[_],iA=d._streams[Z.id];k=k.replace(new RegExp(Z.id,"g"),iA.id)}),new RTCSessionDescription({type:R.type,sdp:k})}(this,arguments[0]),c.apply(this,arguments)):c.apply(this,arguments)};const u=Object.getOwnPropertyDescriptor(A.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(A.RTCPeerConnection.prototype,"localDescription",{get(){const d=u.get.apply(this);return d.type===""?d:I(this,d)}}),A.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(d._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let R;this._streams=this._streams||{},Object.keys(this._streams).forEach(k=>{this._streams[k].getTracks().find(_=>d.track===_)&&(R=this._streams[k])}),R&&(R.getTracks().length===1?this.removeStream(this._reverseStreams[R.id]):R.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Rf(A,e){!A.RTCPeerConnection&&A.webkitRTCPeerConnection&&(A.RTCPeerConnection=A.webkitRTCPeerConnection),A.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(o){const n=A.RTCPeerConnection.prototype[o],a={[o](){return arguments[0]=new(o==="addIceCandidate"?A.RTCIceCandidate:A.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};A.RTCPeerConnection.prototype[o]=a[o]})}function RU(A,e){ou(A,"negotiationneeded",o=>{const n=o.target;if(!(e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")||n.signalingState==="stable")return o})}var aN=Object.freeze({__proto__:null,shimMediaStream:pU,shimOnTrack:fU,shimGetSendersWithDtmf:rN,shimGetStats:mU,shimSenderReceiverGetStats:nN,shimAddTrackRemoveTrackWithNative:DU,shimAddTrackRemoveTrack:yU,shimPeerConnection:Rf,fixNegotiationNeeded:RU,shimGetUserMedia:hU,shimGetDisplayMedia:function(A,e){A.navigator.mediaDevices&&"getDisplayMedia"in A.navigator.mediaDevices||A.navigator.mediaDevices&&(typeof e=="function"?A.navigator.mediaDevices.getDisplayMedia=function(o){return e(o).then(n=>{const a=o.video&&o.video.width,I=o.video&&o.video.height,c=o.video&&o.video.frameRate;return o.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:n,maxFrameRate:c||3}},a&&(o.video.mandatory.maxWidth=a),I&&(o.video.mandatory.maxHeight=I),A.navigator.mediaDevices.getUserMedia(o)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function MU(A,e){const o=A&&A.navigator,n=A&&A.MediaStreamTrack;if(o.getUserMedia=function(a,I,c){yf("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),o.mediaDevices.getUserMedia(a).then(I,c)},!(e.version>55&&"autoGainControl"in o.mediaDevices.getSupportedConstraints())){const a=function(c,u,d){u in c&&!(d in c)&&(c[d]=c[u],delete c[u])},I=o.mediaDevices.getUserMedia.bind(o.mediaDevices);if(o.mediaDevices.getUserMedia=function(c){return typeof c=="object"&&typeof c.audio=="object"&&(c=JSON.parse(JSON.stringify(c)),a(c.audio,"autoGainControl","mozAutoGainControl"),a(c.audio,"noiseSuppression","mozNoiseSuppression")),I(c)},n&&n.prototype.getSettings){const c=n.prototype.getSettings;n.prototype.getSettings=function(){const u=c.apply(this,arguments);return a(u,"mozAutoGainControl","autoGainControl"),a(u,"mozNoiseSuppression","noiseSuppression"),u}}if(n&&n.prototype.applyConstraints){const c=n.prototype.applyConstraints;n.prototype.applyConstraints=function(u){return this.kind==="audio"&&typeof u=="object"&&(u=JSON.parse(JSON.stringify(u)),a(u,"autoGainControl","mozAutoGainControl"),a(u,"noiseSuppression","mozNoiseSuppression")),c.apply(this,[u])}}}}function wU(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 pR(A,e){if(typeof A!="object"||!A.RTCPeerConnection&&!A.mozRTCPeerConnection)return;!A.RTCPeerConnection&&A.mozRTCPeerConnection&&(A.RTCPeerConnection=A.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(a){const I=A.RTCPeerConnection.prototype[a],c={[a](){return arguments[0]=new(a==="addIceCandidate"?A.RTCIceCandidate:A.RTCSessionDescription)(arguments[0]),I.apply(this,arguments)}};A.RTCPeerConnection.prototype[a]=c[a]});const o={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){const[a,I,c]=arguments;return n.apply(this,[a||null]).then(u=>{if(e.version<53&&!I)try{u.forEach(d=>{d.type=o[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;u.forEach((R,k)=>{u.set(k,Object.assign({},R,{type:o[R.type]||R.type}))})}return u}).then(I,c)}}function SU(A){if(typeof A!="object"||!A.RTCPeerConnection||!A.RTCRtpSender||A.RTCRtpSender&&"getStats"in A.RTCRtpSender.prototype)return;const e=A.RTCPeerConnection.prototype.getSenders;e&&(A.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(a=>a._pc=this),n});const o=A.RTCPeerConnection.prototype.addTrack;o&&(A.RTCPeerConnection.prototype.addTrack=function(){const n=o.apply(this,arguments);return n._pc=this,n}),A.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function sN(A){if(typeof A!="object"||!A.RTCPeerConnection||!A.RTCRtpSender||A.RTCRtpSender&&"getStats"in A.RTCRtpReceiver.prototype)return;const e=A.RTCPeerConnection.prototype.getReceivers;e&&(A.RTCPeerConnection.prototype.getReceivers=function(){const o=e.apply(this,[]);return o.forEach(n=>n._pc=this),o}),ou(A,"track",o=>(o.receiver._pc=o.srcElement,o)),A.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function vU(A){A.RTCPeerConnection&&!("removeStream"in A.RTCPeerConnection.prototype)&&(A.RTCPeerConnection.prototype.removeStream=function(e){yf("removeStream","removeTrack"),this.getSenders().forEach(o=>{o.track&&e.getTracks().includes(o.track)&&this.removeTrack(o)})})}function gN(A){A.DataChannel&&!A.RTCDataChannel&&(A.RTCDataChannel=A.DataChannel)}function NU(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype.addTransceiver;e&&(A.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let o=arguments[1]&&arguments[1].sendEncodings;o===void 0&&(o=[]),o=[...o];const n=o.length>0;n&&o.forEach(I=>{if("rid"in I&&!/^[a-z0-9]{0,16}$/i.test(I.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in I&&!(parseFloat(I.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in I&&!(parseFloat(I.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const a=e.apply(this,arguments);if(n){const{sender:I}=a,c=I.getParameters();(!("encodings"in c)||c.encodings.length===1&&Object.keys(c.encodings[0]).length===0)&&(c.encodings=o,I.sendEncodings=o,this.setParametersPromises.push(I.setParameters(c).then(()=>{delete I.sendEncodings}).catch(()=>{delete I.sendEncodings})))}return a})}function TU(A){if(typeof A!="object"||!A.RTCRtpSender)return;const e=A.RTCRtpSender.prototype.getParameters;e&&(A.RTCRtpSender.prototype.getParameters=function(){const o=e.apply(this,arguments);return"encodings"in o||(o.encodings=[].concat(this.sendEncodings||[{}])),o})}function GU(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype.createOffer;A.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function kU(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype.createAnswer;A.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var _U=Object.freeze({__proto__:null,shimOnTrack:wU,shimPeerConnection:pR,shimSenderGetStats:SU,shimReceiverGetStats:sN,shimRemoveStream:vU,shimRTCDataChannel:gN,shimAddTransceiver:NU,shimGetParameters:TU,shimCreateOffer:GU,shimCreateAnswer:kU,shimGetUserMedia:MU,shimGetDisplayMedia:function(A,e){A.navigator.mediaDevices&&"getDisplayMedia"in A.navigator.mediaDevices||A.navigator.mediaDevices&&(A.navigator.mediaDevices.getDisplayMedia=function(o){if(!o||!o.video){const n=new DOMException("getDisplayMedia without video constraints is undefined");return n.name="NotFoundError",n.code=8,Promise.reject(n)}return o.video===!0?o.video={mediaSource:e}:o.video.mediaSource=e,A.navigator.mediaDevices.getUserMedia(o)})}});function bU(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 e=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(n=>e.call(this,n,o)),o.getVideoTracks().forEach(n=>e.call(this,n,o))},A.RTCPeerConnection.prototype.addTrack=function(o,...n){return n&&n.forEach(a=>{this._localStreams?this._localStreams.includes(a)||this._localStreams.push(a):this._localStreams=[a]}),e.apply(this,arguments)}}"removeStream"in A.RTCPeerConnection.prototype||(A.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const o=this._localStreams.indexOf(e);if(o===-1)return;this._localStreams.splice(o,1);const n=e.getTracks();this.getSenders().forEach(a=>{n.includes(a.track)&&this.removeTrack(a)})})}}function LU(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=n=>{n.streams.forEach(a=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(a))return;this._remoteStreams.push(a);const I=new Event("addstream");I.stream=a,this.dispatchEvent(I)})})}});const e=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(){const o=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(n){n.streams.forEach(a=>{if(o._remoteStreams||(o._remoteStreams=[]),o._remoteStreams.indexOf(a)>=0)return;o._remoteStreams.push(a);const I=new Event("addstream");I.stream=a,o.dispatchEvent(I)})}),e.apply(o,arguments)}}}function IN(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype,o=e.createOffer,n=e.createAnswer,a=e.setLocalDescription,I=e.setRemoteDescription,c=e.addIceCandidate;e.createOffer=function(d,R){const k=arguments.length>=2?arguments[2]:arguments[0],_=o.apply(this,[k]);return R?(_.then(d,R),Promise.resolve()):_},e.createAnswer=function(d,R){const k=arguments.length>=2?arguments[2]:arguments[0],_=n.apply(this,[k]);return R?(_.then(d,R),Promise.resolve()):_};let u=function(d,R,k){const _=a.apply(this,[d]);return k?(_.then(R,k),Promise.resolve()):_};e.setLocalDescription=u,u=function(d,R,k){const _=I.apply(this,[d]);return k?(_.then(R,k),Promise.resolve()):_},e.setRemoteDescription=u,u=function(d,R,k){const _=c.apply(this,[d]);return k?(_.then(R,k),Promise.resolve()):_},e.addIceCandidate=u}function cN(A){const e=A&&A.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const o=e.mediaDevices,n=o.getUserMedia.bind(o);e.mediaDevices.getUserMedia=a=>n(FU(a))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(o,n,a){e.mediaDevices.getUserMedia(o).then(n,a)}.bind(e))}function FU(A){return A&&A.video!==void 0?Object.assign({},A,{video:tN(A.video)}):A}function UU(A){if(!A.RTCPeerConnection)return;const e=A.RTCPeerConnection;A.RTCPeerConnection=function(o,n){if(o&&o.iceServers){const a=[];for(let I=0;Ie.generateCertificate})}function OU(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 fR(A){const e=A.RTCPeerConnection.prototype.createOffer;A.RTCPeerConnection.prototype.createOffer=function(o){if(o){o.offerToReceiveAudio!==void 0&&(o.offerToReceiveAudio=!!o.offerToReceiveAudio);const n=this.getTransceivers().find(I=>I.receiver.track.kind==="audio");o.offerToReceiveAudio===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):o.offerToReceiveAudio!==!0||n||this.addTransceiver("audio",{direction:"recvonly"}),o.offerToReceiveVideo!==void 0&&(o.offerToReceiveVideo=!!o.offerToReceiveVideo);const a=this.getTransceivers().find(I=>I.receiver.track.kind==="video");o.offerToReceiveVideo===!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.offerToReceiveVideo!==!0||a||this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function xU(A){typeof A!="object"||A.AudioContext||(A.AudioContext=A.webkitAudioContext)}var YU=Object.freeze({__proto__:null,shimLocalStreamsAPI:bU,shimRemoteStreamsAPI:LU,shimCallbacksAPI:IN,shimGetUserMedia:cN,shimConstraints:FU,shimRTCIceServerUrls:UU,shimTrackEventTransceiver:OU,shimCreateOfferLegacy:fR,shimAudioContext:xU}),PU={exports:{}};(function(A){const e={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};e.localCName=e.generateIdentifier(),e.splitLines=function(o){return o.trim().split(` `).map(n=>n.trim())},e.splitSections=function(o){return o.split(` m=`).map((n,a)=>(a>0?"m="+n:n).trim()+`\r `)},e.getDescription=function(o){const n=e.splitSections(o);return n&&n[0]},e.getMediaSections=function(o){const n=e.splitSections(o);return n.shift(),n},e.matchPrefix=function(o,n){return e.splitLines(o).filter(a=>a.indexOf(n)===0)},e.parseCandidate=function(o){let n;n=o.indexOf("a=candidate:")===0?o.substring(12).split(" "):o.substring(10).split(" ");const a={foundation:n[0],component:{1:"rtp",2:"rtcp"}[n[1]]||n[1],protocol:n[2].toLowerCase(),priority:parseInt(n[3],10),ip:n[4],address:n[4],port:parseInt(n[5],10),type:n[7]};for(let I=8;I(o.candidate&&Object.defineProperty(o,"candidate",{value:new A.RTCIceCandidate(o.candidate),writable:"false"}),o))}function sN(A){!A.RTCIceCandidate||A.RTCIceCandidate&&"relayProtocol"in A.RTCIceCandidate.prototype||eu(A,"icecandidate",e=>{if(e.candidate){const o=el.parseCandidate(e.candidate.candidate);o.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[o.priority>>24])}return e})}function mf(A,e){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,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:n}=this.getConfiguration();n==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(function(n){if(!n||!n.sdp)return!1;const a=el.splitSections(n.sdp);return a.shift(),a.some(I=>{const c=el.parseMLine(I);return c&&c.kind==="application"&&c.protocol.indexOf("SCTP")!==-1})}(arguments[0])){const n=function(d){const R=d.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(R===null||R.length<2)return-1;const k=parseInt(R[1],10);return k!=k?-1:k}(arguments[0]),a=function(d){let R=65536;return e.browser==="firefox"&&(R=e.version<57?d===-1?16384:2147483637:e.version<60?e.version===57?65535:65536:2147483637),R}(n),I=function(d,R){let k=65536;e.browser==="firefox"&&e.version===57&&(k=65535);const _=el.matchPrefix(d.sdp,"a=max-message-size:");return _.length>0?k=parseInt(_[0].substring(19),10):e.browser==="firefox"&&R!==-1&&(k=2147483637),k}(arguments[0],n);let c;c=a===0&&I===0?Number.POSITIVE_INFINITY:a===0||I===0?Math.max(a,I):Math.min(a,I);const u={};Object.defineProperty(u,"maxMessageSize",{get:()=>c}),this._sctp=u}return o.apply(this,arguments)}}function pR(A){if(!A.RTCPeerConnection||!("createDataChannel"in A.RTCPeerConnection.prototype))return;function e(n,a){const I=n.send;n.send=function(){const c=arguments[0],u=c.length||c.size||c.byteLength;if(n.readyState==="open"&&a.sctp&&u>a.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+a.sctp.maxMessageSize+" bytes)");return I.apply(n,arguments)}}const o=A.RTCPeerConnection.prototype.createDataChannel;A.RTCPeerConnection.prototype.createDataChannel=function(){const n=o.apply(this,arguments);return e(n,this),n},eu(A,"datachannel",n=>(e(n.channel,n.target),n))}function gN(A){if(!A.RTCPeerConnection||"connectionState"in A.RTCPeerConnection.prototype)return;const e=A.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"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 n=e[o];e[o]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=a=>{const I=a.target;if(I._lastConnectionState!==I.connectionState){I._lastConnectionState=I.connectionState;const c=new Event("connectionstatechange",a);I.dispatchEvent(c)}return a},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function fR(A,e){if(!A.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const o=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(n){if(n&&n.sdp&&n.sdp.indexOf(` +`},e.getDirection=function(o,n){const a=e.splitLines(o);for(let I=0;I(o.candidate&&Object.defineProperty(o,"candidate",{value:new A.RTCIceCandidate(o.candidate),writable:"false"}),o))}function EN(A){!A.RTCIceCandidate||A.RTCIceCandidate&&"relayProtocol"in A.RTCIceCandidate.prototype||ou(A,"icecandidate",e=>{if(e.candidate){const o=tl.parseCandidate(e.candidate.candidate);o.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[o.priority>>24])}return e})}function Mf(A,e){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,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:n}=this.getConfiguration();n==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(function(n){if(!n||!n.sdp)return!1;const a=tl.splitSections(n.sdp);return a.shift(),a.some(I=>{const c=tl.parseMLine(I);return c&&c.kind==="application"&&c.protocol.indexOf("SCTP")!==-1})}(arguments[0])){const n=function(d){const R=d.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(R===null||R.length<2)return-1;const k=parseInt(R[1],10);return k!=k?-1:k}(arguments[0]),a=function(d){let R=65536;return e.browser==="firefox"&&(R=e.version<57?d===-1?16384:2147483637:e.version<60?e.version===57?65535:65536:2147483637),R}(n),I=function(d,R){let k=65536;e.browser==="firefox"&&e.version===57&&(k=65535);const _=tl.matchPrefix(d.sdp,"a=max-message-size:");return _.length>0?k=parseInt(_[0].substring(19),10):e.browser==="firefox"&&R!==-1&&(k=2147483637),k}(arguments[0],n);let c;c=a===0&&I===0?Number.POSITIVE_INFINITY:a===0||I===0?Math.max(a,I):Math.min(a,I);const u={};Object.defineProperty(u,"maxMessageSize",{get:()=>c}),this._sctp=u}return o.apply(this,arguments)}}function DR(A){if(!A.RTCPeerConnection||!("createDataChannel"in A.RTCPeerConnection.prototype))return;function e(n,a){const I=n.send;n.send=function(){const c=arguments[0],u=c.length||c.size||c.byteLength;if(n.readyState==="open"&&a.sctp&&u>a.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+a.sctp.maxMessageSize+" bytes)");return I.apply(n,arguments)}}const o=A.RTCPeerConnection.prototype.createDataChannel;A.RTCPeerConnection.prototype.createDataChannel=function(){const n=o.apply(this,arguments);return e(n,this),n},ou(A,"datachannel",n=>(e(n.channel,n.target),n))}function lN(A){if(!A.RTCPeerConnection||"connectionState"in A.RTCPeerConnection.prototype)return;const e=A.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"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 n=e[o];e[o]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=a=>{const I=a.target;if(I._lastConnectionState!==I.connectionState){I._lastConnectionState=I.connectionState;const c=new Event("connectionstatechange",a);I.dispatchEvent(c)}return a},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function yR(A,e){if(!A.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const o=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(n){if(n&&n.sdp&&n.sdp.indexOf(` a=extmap-allow-mixed`)!==-1){const a=n.sdp.split(` `).filter(I=>I.trim()!=="a=extmap-allow-mixed").join(` -`);A.RTCSessionDescription&&n instanceof A.RTCSessionDescription?arguments[0]=new A.RTCSessionDescription({type:n.type,sdp:a}):n.sdp=a}return o.apply(this,arguments)}}function mR(A,e){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]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():o.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function DR(A,e){if(!A.RTCPeerConnection||!A.RTCPeerConnection.prototype)return;const o=A.RTCPeerConnection.prototype.setLocalDescription;o&&o.length!==0&&(A.RTCPeerConnection.prototype.setLocalDescription=function(){let n=arguments[0]||{};if(typeof n!="object"||n.type&&n.sdp)return o.apply(this,arguments);if(n={type:n.type,sdp:n.sdp},!n.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":n.type="offer";break;default:n.type="answer"}return n.sdp||n.type!=="offer"&&n.type!=="answer"?o.apply(this,[n]):(n.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>o.apply(this,[a]))})}var YV=Object.freeze({__proto__:null,shimRTCIceCandidate:hR,shimRTCIceCandidateRelayProtocol:sN,shimMaxMessageSize:mf,shimSendThrowTypeError:pR,shimConnectionState:gN,removeExtmapAllowMixed:fR,shimAddIceCandidateNullOrEmpty:mR,shimParameterlessSetLocalDescription:DR});(function({window:A}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const o=uR,n=function(I){const c={browser:null,version:null};if(I===void 0||!I.navigator||!I.navigator.userAgent)return c.browser="Not a browser.",c;const{navigator:u}=I;if(u.mozGetUserMedia)c.browser="firefox",c.version=parseInt(hf(u.userAgent,/Firefox\/(\d+)\./,1));else if(u.webkitGetUserMedia||I.isSecureContext===!1&&I.webkitRTCPeerConnection)c.browser="chrome",c.version=parseInt(hf(u.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!I.RTCPeerConnection||!u.userAgent.match(/AppleWebKit\/(\d+)\./))return c.browser="Not a supported browser.",c;c.browser="safari",c.version=parseInt(hf(u.userAgent,/AppleWebKit\/(\d+)\./,1)),c.supportsUnifiedPlan=I.RTCRtpTransceiver&&"currentDirection"in I.RTCRtpTransceiver.prototype,c._safariVersion=hf(u.userAgent,/Version\/(\d+(\.?\d+))/,1)}return c}(A),a={browserDetails:n,commonShim:YV,extractVersion:hf,disableLog:IU,disableWarnings:xV,sdp:FU};switch(n.browser){case"chrome":if(!iN||!ff||!e.shimChrome)return o("Chrome shim is not included in this adapter release."),a;if(n.version===null)return o("Chrome shim can not determine version, not shimming."),a;o("adapter.js shimming chrome."),a.browserShim=iN,mR(A,n),DR(A),EU(A,n),lU(A),ff(A,n),CU(A),QU(A,n),eN(A),BU(A),tN(A),dU(A,n),hR(A),sN(A),gN(A),mf(A,n),pR(A),fR(A,n);break;case"firefox":if(!wU||!QR||!e.shimFirefox)return o("Firefox shim is not included in this adapter release."),a;o("adapter.js shimming firefox."),a.browserShim=wU,mR(A,n),DR(A),hU(A,n),QR(A,n),pU(A),mU(A),fU(A),oN(A),rN(A),DU(A),yU(A),RU(A),MU(A),hR(A),gN(A),mf(A,n),pR(A);break;case"safari":if(!_U||!e.shimSafari)return o("Safari shim is not included in this adapter release."),a;o("adapter.js shimming safari."),a.browserShim=_U,mR(A,n),DR(A),TU(A),dR(A),nN(A),SU(A),vU(A),GU(A),aN(A),kU(A),hR(A),sN(A),mf(A,n),pR(A),fR(A,n);break;default:o("Unsupported browser!")}})({window:typeof window>"u"?void 0:window});var Ii,UU=Object.create,Df=Object.defineProperty,PV=Object.defineProperties,yR=Object.getOwnPropertyDescriptor,yf=Object.getOwnPropertyDescriptors,JV=Object.getOwnPropertyNames,RR=Object.getOwnPropertySymbols,OU=Object.getPrototypeOf,IN=Object.prototype.hasOwnProperty,xU=Object.prototype.propertyIsEnumerable,YU=Reflect.get,Rf=Math.pow,MR=(A,e,o)=>e in A?Df(A,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):A[e]=o,bt=(A,e)=>{for(var o in e||(e={}))IN.call(e,o)&&MR(A,o,e[o]);if(RR)for(var o of RR(e))xU.call(e,o)&&MR(A,o,e[o]);return A},fi=(A,e)=>PV(A,yf(e)),PU=(A,e)=>{var o={};for(var n in A)IN.call(A,n)&&e.indexOf(n)<0&&(o[n]=A[n]);if(A!=null&&RR)for(var n of RR(A))e.indexOf(n)<0&&xU.call(A,n)&&(o[n]=A[n]);return o},ZC=(A,e)=>()=>(e||A((e={exports:{}}).exports,e),e.exports),XC=(A,e)=>{for(var o in e)Df(A,o,{get:e[o],enumerable:!0})},es=(A,e,o)=>(o=A!=null?UU(OU(A)):{},((n,a,I,c)=>{if(a&&typeof a=="object"||typeof a=="function")for(let u of JV(a))!IN.call(n,u)&&u!==I&&Df(n,u,{get:()=>a[u],enumerable:!(c=yR(a,u))||c.enumerable});return n})(!e&&A&&A.__esModule?o:Df(o,"default",{value:A,enumerable:!0}),A)),vt=(A,e,o,n)=>{for(var a,I=yR(e,o),c=A.length-1;c>=0;c--)(a=A[c])&&(I=a(e,o,I)||I);return I&&Df(e,o,I),I},G=(A,e,o)=>MR(A,typeof e!="symbol"?e+"":e,o),zg=(A,e,o)=>YU(OU(A),o,e),DA=(A,e,o)=>new Promise((n,a)=>{var I=d=>{try{u(o.next(d))}catch(R){a(R)}},c=d=>{try{u(o.throw(d))}catch(R){a(R)}},u=d=>d.done?n(d.value):Promise.resolve(d.value).then(I,c);u((o=o.apply(A,e)).next())}),hg=ZC((A,e)=>{var o=Object.prototype.hasOwnProperty,n="~";function a(){}function I(R,k,_){this.fn=R,this.context=k,this.once=_||!1}function c(R,k,_,Z,iA){if(typeof _!="function")throw new TypeError("The listener must be a function");var cA=new I(_,Z||R,iA),TA=n?n+k:k;return R._events[TA]?R._events[TA].fn?R._events[TA]=[R._events[TA],cA]:R._events[TA].push(cA):(R._events[TA]=cA,R._eventsCount++),R}function u(R,k){--R._eventsCount===0?R._events=new a:delete R._events[k]}function d(){this._events=new a,this._eventsCount=0}Object.create&&(a.prototype=Object.create(null),new a().__proto__||(n=!1)),d.prototype.eventNames=function(){var R,k,_=[];if(this._eventsCount===0)return _;for(k in R=this._events)o.call(R,k)&&_.push(n?k.slice(1):k);return Object.getOwnPropertySymbols?_.concat(Object.getOwnPropertySymbols(R)):_},d.prototype.listeners=function(R){var k=n?n+R:R,_=this._events[k];if(!_)return[];if(_.fn)return[_.fn];for(var Z=0,iA=_.length,cA=new Array(iA);Z{var o=e.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(n){return n.encoding?"rtpmap:%d %s/%s/%s":n.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(n){return n.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(n){return n.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(n){return"extmap:%d"+(n.direction?"/%s":"%v")+(n["encrypt-uri"]?" %s":"%v")+" %s"+(n.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(n){return n.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(n){var a="candidate:%s %d %s %d %s %d typ %s";return a+=n.raddr!=null?" raddr %s rport %d":"%v%v",a+=n.tcptype!=null?" tcptype %s":"%v",n.generation!=null&&(a+=" generation %d"),a+=n["network-id"]!=null?" network-id %d":"%v",a+=n["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(n){var a="ssrc:%d";return n.attribute!=null&&(a+=" %s",n.value!=null&&(a+=":%s")),a}},{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(n){return n.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(n){return n.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(n){return"imageattr:%s %s %s"+(n.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(n){return"simulcast:%s %s"+(n.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(n){return"ts-refclk:%s"+(n.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(n){var a="mediaclk:";return a+=n.id!=null?"id=%s %s":"%v%s",a+=n.mediaClockValue!=null?"=%s":"",a+=n.rateNumerator!=null?" rate=%s":"",a+=n.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(n){o[n].forEach(function(a){a.reg||(a.reg=/(.*)/),a.format||(a.format="%s")})})}),sh=ZC(A=>{var e=function(c){return String(Number(c))===c?Number(c):c},o=function(c,u,d){var R=c.name&&c.names;c.push&&!u[c.push]?u[c.push]=[]:R&&!u[c.name]&&(u[c.name]={});var k=c.push?{}:R?u[c.name]:u;(function(_,Z,iA,cA){if(cA&&!iA)Z[cA]=e(_[1]);else for(var TA=0;TA1&&(c[d[0]]=void 0),c};A.parseParams=function(c){return c.split(/;\s?/).reduce(I,{})},A.parseFmtpConfig=A.parseParams,A.parsePayloads=function(c){return c.toString().split(" ").map(Number)},A.parseRemoteCandidates=function(c){for(var u=[],d=c.split(" ").map(e),R=0;R{var o=Xl(),n=/%[sdv%]/g,a=function(d){var R=1,k=arguments,_=k.length;return d.replace(n,function(Z){if(R>=_)return Z;var iA=k[R];switch(R+=1,Z){case"%%":return"%";case"%s":return String(iA);case"%d":return Number(iA);case"%v":return""}})},I=function(d,R,k){var _=[d+"="+(R.format instanceof Function?R.format(R.push?k:k[R.name]):R.format)];if(R.names)for(var Z=0;Zo.apply(this,[a]))})}var KV=Object.freeze({__proto__:null,shimRTCIceCandidate:mR,shimRTCIceCandidateRelayProtocol:EN,shimMaxMessageSize:Mf,shimSendThrowTypeError:DR,shimConnectionState:lN,removeExtmapAllowMixed:yR,shimAddIceCandidateNullOrEmpty:RR,shimParameterlessSetLocalDescription:MR});(function({window:A}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const o=hR,n=function(I){const c={browser:null,version:null};if(I===void 0||!I.navigator||!I.navigator.userAgent)return c.browser="Not a browser.",c;const{navigator:u}=I;if(u.mozGetUserMedia)c.browser="firefox",c.version=parseInt(Df(u.userAgent,/Firefox\/(\d+)\./,1));else if(u.webkitGetUserMedia||I.isSecureContext===!1&&I.webkitRTCPeerConnection)c.browser="chrome",c.version=parseInt(Df(u.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!I.RTCPeerConnection||!u.userAgent.match(/AppleWebKit\/(\d+)\./))return c.browser="Not a supported browser.",c;c.browser="safari",c.version=parseInt(Df(u.userAgent,/AppleWebKit\/(\d+)\./,1)),c.supportsUnifiedPlan=I.RTCRtpTransceiver&&"currentDirection"in I.RTCRtpTransceiver.prototype,c._safariVersion=Df(u.userAgent,/Version\/(\d+(\.?\d+))/,1)}return c}(A),a={browserDetails:n,commonShim:KV,extractVersion:Df,disableLog:QU,disableWarnings:qV,sdp:HU};switch(n.browser){case"chrome":if(!aN||!Rf||!e.shimChrome)return o("Chrome shim is not included in this adapter release."),a;if(n.version===null)return o("Chrome shim can not determine version, not shimming."),a;o("adapter.js shimming chrome."),a.browserShim=aN,RR(A,n),MR(A),hU(A,n),pU(A),Rf(A,n),fU(A),yU(A,n),rN(A),mU(A),nN(A),RU(A,n),mR(A),EN(A),lN(A),Mf(A,n),DR(A),yR(A,n);break;case"firefox":if(!_U||!pR||!e.shimFirefox)return o("Firefox shim is not included in this adapter release."),a;o("adapter.js shimming firefox."),a.browserShim=_U,RR(A,n),MR(A),MU(A,n),pR(A,n),wU(A),vU(A),SU(A),sN(A),gN(A),NU(A),TU(A),GU(A),kU(A),mR(A),lN(A),Mf(A,n),DR(A);break;case"safari":if(!YU||!e.shimSafari)return o("Safari shim is not included in this adapter release."),a;o("adapter.js shimming safari."),a.browserShim=YU,RR(A,n),MR(A),UU(A),fR(A),IN(A),bU(A),LU(A),OU(A),cN(A),xU(A),mR(A),EN(A),Mf(A,n),DR(A),yR(A,n);break;default:o("Unsupported browser!")}})({window:typeof window>"u"?void 0:window});var Ii,VU=Object.create,wf=Object.defineProperty,jV=Object.defineProperties,wR=Object.getOwnPropertyDescriptor,Sf=Object.getOwnPropertyDescriptors,WV=Object.getOwnPropertyNames,SR=Object.getOwnPropertySymbols,qU=Object.getPrototypeOf,CN=Object.prototype.hasOwnProperty,KU=Object.prototype.propertyIsEnumerable,jU=Reflect.get,vf=Math.pow,vR=(A,e,o)=>e in A?wf(A,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):A[e]=o,bt=(A,e)=>{for(var o in e||(e={}))CN.call(e,o)&&vR(A,o,e[o]);if(SR)for(var o of SR(e))KU.call(e,o)&&vR(A,o,e[o]);return A},fi=(A,e)=>jV(A,Sf(e)),WU=(A,e)=>{var o={};for(var n in A)CN.call(A,n)&&e.indexOf(n)<0&&(o[n]=A[n]);if(A!=null&&SR)for(var n of SR(A))e.indexOf(n)<0&&KU.call(A,n)&&(o[n]=A[n]);return o},ZC=(A,e)=>()=>(e||A((e={exports:{}}).exports,e),e.exports),XC=(A,e)=>{for(var o in e)wf(A,o,{get:e[o],enumerable:!0})},es=(A,e,o)=>(o=A!=null?VU(qU(A)):{},((n,a,I,c)=>{if(a&&typeof a=="object"||typeof a=="function")for(let u of WV(a))!CN.call(n,u)&&u!==I&&wf(n,u,{get:()=>a[u],enumerable:!(c=wR(a,u))||c.enumerable});return n})(!e&&A&&A.__esModule?o:wf(o,"default",{value:A,enumerable:!0}),A)),vt=(A,e,o,n)=>{for(var a,I=wR(e,o),c=A.length-1;c>=0;c--)(a=A[c])&&(I=a(e,o,I)||I);return I&&wf(e,o,I),I},G=(A,e,o)=>vR(A,typeof e!="symbol"?e+"":e,o),zg=(A,e,o)=>jU(qU(A),o,e),DA=(A,e,o)=>new Promise((n,a)=>{var I=d=>{try{u(o.next(d))}catch(R){a(R)}},c=d=>{try{u(o.throw(d))}catch(R){a(R)}},u=d=>d.done?n(d.value):Promise.resolve(d.value).then(I,c);u((o=o.apply(A,e)).next())}),hg=ZC((A,e)=>{var o=Object.prototype.hasOwnProperty,n="~";function a(){}function I(R,k,_){this.fn=R,this.context=k,this.once=_||!1}function c(R,k,_,Z,iA){if(typeof _!="function")throw new TypeError("The listener must be a function");var cA=new I(_,Z||R,iA),TA=n?n+k:k;return R._events[TA]?R._events[TA].fn?R._events[TA]=[R._events[TA],cA]:R._events[TA].push(cA):(R._events[TA]=cA,R._eventsCount++),R}function u(R,k){--R._eventsCount===0?R._events=new a:delete R._events[k]}function d(){this._events=new a,this._eventsCount=0}Object.create&&(a.prototype=Object.create(null),new a().__proto__||(n=!1)),d.prototype.eventNames=function(){var R,k,_=[];if(this._eventsCount===0)return _;for(k in R=this._events)o.call(R,k)&&_.push(n?k.slice(1):k);return Object.getOwnPropertySymbols?_.concat(Object.getOwnPropertySymbols(R)):_},d.prototype.listeners=function(R){var k=n?n+R:R,_=this._events[k];if(!_)return[];if(_.fn)return[_.fn];for(var Z=0,iA=_.length,cA=new Array(iA);Z{var o=e.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(n){return n.encoding?"rtpmap:%d %s/%s/%s":n.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(n){return n.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(n){return n.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(n){return"extmap:%d"+(n.direction?"/%s":"%v")+(n["encrypt-uri"]?" %s":"%v")+" %s"+(n.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(n){return n.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(n){var a="candidate:%s %d %s %d %s %d typ %s";return a+=n.raddr!=null?" raddr %s rport %d":"%v%v",a+=n.tcptype!=null?" tcptype %s":"%v",n.generation!=null&&(a+=" generation %d"),a+=n["network-id"]!=null?" network-id %d":"%v",a+=n["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(n){var a="ssrc:%d";return n.attribute!=null&&(a+=" %s",n.value!=null&&(a+=":%s")),a}},{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(n){return n.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(n){return n.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(n){return"imageattr:%s %s %s"+(n.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(n){return"simulcast:%s %s"+(n.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(n){return"ts-refclk:%s"+(n.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(n){var a="mediaclk:";return a+=n.id!=null?"id=%s %s":"%v%s",a+=n.mediaClockValue!=null?"=%s":"",a+=n.rateNumerator!=null?" rate=%s":"",a+=n.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(n){o[n].forEach(function(a){a.reg||(a.reg=/(.*)/),a.format||(a.format="%s")})})}),ch=ZC(A=>{var e=function(c){return String(Number(c))===c?Number(c):c},o=function(c,u,d){var R=c.name&&c.names;c.push&&!u[c.push]?u[c.push]=[]:R&&!u[c.name]&&(u[c.name]={});var k=c.push?{}:R?u[c.name]:u;(function(_,Z,iA,cA){if(cA&&!iA)Z[cA]=e(_[1]);else for(var TA=0;TA1&&(c[d[0]]=void 0),c};A.parseParams=function(c){return c.split(/;\s?/).reduce(I,{})},A.parseFmtpConfig=A.parseParams,A.parsePayloads=function(c){return c.toString().split(" ").map(Number)},A.parseRemoteCandidates=function(c){for(var u=[],d=c.split(" ").map(e),R=0;R{var o=Xl(),n=/%[sdv%]/g,a=function(d){var R=1,k=arguments,_=k.length;return d.replace(n,function(Z){if(R>=_)return Z;var iA=k[R];switch(R+=1,Z){case"%%":return"%";case"%s":return String(iA);case"%d":return Number(iA);case"%v":return""}})},I=function(d,R,k){var _=[d+"="+(R.format instanceof Function?R.format(R.push?k:k[R.name]):R.format)];if(R.names)for(var Z=0;Z{var e=sh(),o=HV(),n=Xl();A.grammar=n,A.write=o,A.parse=e.parse,A.parseParams=e.parseParams,A.parseFmtpConfig=e.parseFmtpConfig,A.parsePayloads=e.parsePayloads,A.parseRemoteCandidates=e.parseRemoteCandidates,A.parseImageAttributes=e.parseImageAttributes,A.parseSimulcastStreamList=e.parseSimulcastStreamList}),Mf=ZC((A,e)=>{var o=e.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(n){return n.encoding?"rtpmap:%d %s/%s/%s":n.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(n){return n.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(n){return n.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(n){return"extmap:%d"+(n.direction?"/%s":"%v")+(n["encrypt-uri"]?" %s":"%v")+" %s"+(n.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(n){return n.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(n){var a="candidate:%s %d %s %d %s %d typ %s";return a+=n.raddr!=null?" raddr %s rport %d":"%v%v",a+=n.tcptype!=null?" tcptype %s":"%v",n.generation!=null&&(a+=" generation %d"),a+=n["network-id"]!=null?" network-id %d":"%v",a+=n["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(n){var a="ssrc:%d";return n.attribute!=null&&(a+=" %s",n.value!=null&&(a+=":%s")),a}},{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(n){return n.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(n){return n.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(n){return"imageattr:%s %s %s"+(n.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(n){return"simulcast:%s %s"+(n.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(n){return"ts-refclk:%s"+(n.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(n){var a="mediaclk:";return a+=n.id!=null?"id=%s %s":"%v%s",a+=n.mediaClockValue!=null?"=%s":"",a+=n.rateNumerator!=null?" rate=%s":"",a+=n.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(n){o[n].forEach(function(a){a.reg||(a.reg=/(.*)/),a.format||(a.format="%s")})})}),JU=ZC(A=>{var e=function(c){return String(Number(c))===c?Number(c):c},o=function(c,u,d){var R=c.name&&c.names;c.push&&!u[c.push]?u[c.push]=[]:R&&!u[c.name]&&(u[c.name]={});var k=c.push?{}:R?u[c.name]:u;(function(_,Z,iA,cA){if(cA&&!iA)Z[cA]=e(_[1]);else for(var TA=0;TA1&&(c[d[0]]=void 0),c};A.parseParams=function(c){return c.split(/;\s?/).reduce(I,{})},A.parseFmtpConfig=A.parseParams,A.parsePayloads=function(c){return c.toString().split(" ").map(Number)},A.parseRemoteCandidates=function(c){for(var u=[],d=c.split(" ").map(e),R=0;R{var o=Mf(),n=/%[sdv%]/g,a=function(d){var R=1,k=arguments,_=k.length;return d.replace(n,function(Z){if(R>=_)return Z;var iA=k[R];switch(R+=1,Z){case"%%":return"%";case"%s":return String(iA);case"%d":return Number(iA);case"%v":return""}})},I=function(d,R,k){var _=[d+"="+(R.format instanceof Function?R.format(R.push?k:k[R.name]):R.format)];if(R.names)for(var Z=0;Z{var e=ch(),o=zV(),n=Xl();A.grammar=n,A.write=o,A.parse=e.parse,A.parseParams=e.parseParams,A.parseFmtpConfig=e.parseFmtpConfig,A.parsePayloads=e.parsePayloads,A.parseRemoteCandidates=e.parseRemoteCandidates,A.parseImageAttributes=e.parseImageAttributes,A.parseSimulcastStreamList=e.parseSimulcastStreamList}),Nf=ZC((A,e)=>{var o=e.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(n){return n.encoding?"rtpmap:%d %s/%s/%s":n.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(n){return n.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(n){return n.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(n){return"extmap:%d"+(n.direction?"/%s":"%v")+(n["encrypt-uri"]?" %s":"%v")+" %s"+(n.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(n){return n.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(n){var a="candidate:%s %d %s %d %s %d typ %s";return a+=n.raddr!=null?" raddr %s rport %d":"%v%v",a+=n.tcptype!=null?" tcptype %s":"%v",n.generation!=null&&(a+=" generation %d"),a+=n["network-id"]!=null?" network-id %d":"%v",a+=n["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(n){var a="ssrc:%d";return n.attribute!=null&&(a+=" %s",n.value!=null&&(a+=":%s")),a}},{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(n){return n.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(n){return n.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(n){return"imageattr:%s %s %s"+(n.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(n){return"simulcast:%s %s"+(n.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(n){return"ts-refclk:%s"+(n.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(n){var a="mediaclk:";return a+=n.id!=null?"id=%s %s":"%v%s",a+=n.mediaClockValue!=null?"=%s":"",a+=n.rateNumerator!=null?" rate=%s":"",a+=n.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(n){o[n].forEach(function(a){a.reg||(a.reg=/(.*)/),a.format||(a.format="%s")})})}),zU=ZC(A=>{var e=function(c){return String(Number(c))===c?Number(c):c},o=function(c,u,d){var R=c.name&&c.names;c.push&&!u[c.push]?u[c.push]=[]:R&&!u[c.name]&&(u[c.name]={});var k=c.push?{}:R?u[c.name]:u;(function(_,Z,iA,cA){if(cA&&!iA)Z[cA]=e(_[1]);else for(var TA=0;TA1&&(c[d[0]]=void 0),c};A.parseParams=function(c){return c.split(/;\s?/).reduce(I,{})},A.parseFmtpConfig=A.parseParams,A.parsePayloads=function(c){return c.toString().split(" ").map(Number)},A.parseRemoteCandidates=function(c){for(var u=[],d=c.split(" ").map(e),R=0;R{var o=Nf(),n=/%[sdv%]/g,a=function(d){var R=1,k=arguments,_=k.length;return d.replace(n,function(Z){if(R>=_)return Z;var iA=k[R];switch(R+=1,Z){case"%%":return"%";case"%s":return String(iA);case"%d":return Number(iA);case"%v":return""}})},I=function(d,R,k){var _=[d+"="+(R.format instanceof Function?R.format(R.push?k:k[R.name]):R.format)];if(R.names)for(var Z=0;Z{var e=JU(),o=HU();A.write=o,A.parse=e.parse,A.parseParams=e.parseParams,A.parseFmtpConfig=e.parseFmtpConfig,A.parsePayloads=e.parsePayloads,A.parseRemoteCandidates=e.parseRemoteCandidates,A.parseImageAttributes=e.parseImageAttributes,A.parseSimulcastStreamList=e.parseSimulcastStreamList}),qV=es(hg()),tu=((Ii=tu||{})[Ii.INVALID_PARAMETER=4096]="INVALID_PARAMETER",Ii[Ii.INVALID_OPERATION=4097]="INVALID_OPERATION",Ii[Ii.NOT_SUPPORTED=4098]="NOT_SUPPORTED",Ii[Ii.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",Ii[Ii.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",Ii[Ii.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",Ii[Ii.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",Ii[Ii.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",Ii[Ii.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",Ii[Ii.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",Ii[Ii.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",Ii[Ii.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",Ii[Ii.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",Ii[Ii.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",Ii[Ii.CLIENT_BANNED=16448]="CLIENT_BANNED",Ii[Ii.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",Ii[Ii.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",Ii[Ii.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",Ii[Ii.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",Ii[Ii.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",Ii[Ii.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",Ii[Ii.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",Ii[Ii.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",Ii[Ii.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",Ii[Ii.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",Ii[Ii.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",Ii[Ii.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",Ii[Ii.API_CALL_ABORTED=16461]="API_CALL_ABORTED",Ii[Ii.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",Ii[Ii.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",Ii[Ii.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",Ii[Ii.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",Ii[Ii.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",Ii[Ii.UNKNOWN=65535]="UNKNOWN",Ii),Ge=tu,VU=class extends Error{constructor(A){let{name:e="RtcError",message:o,code:n=Ge.UNKNOWN,extraCode:a=0,constraint:I}=A,c="<".concat(function(d){for(let R in Ge)if(Ge[R]===d)return R;return"UNKNOWN"}(n)," 0x").concat(n.toString(16),">"),u="".concat(o).concat(I?" constraint: ".concat(I):"").concat(o!=null&&o.includes(c)?"":" ".concat(c));super(u),G(this,"code"),G(this,"extraCode"),G(this,"message"),G(this,"originMessage"),G(this,"name"),G(this,"constraint"),this.code=n,this.extraCode=a,this.name=e,this.message=u,this.constraint=I,this.originMessage=o}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},Ct=VU,EN=0,qU=!0,iu=function(A){EN=A;let e=new Date;e.setTime(e.getTime()+A),nA[qU?"info":"debug"]("baseTime from server: ".concat(e," offset: ").concat(A)),qU=!1},KU=function(){return EN},gh=function(){return Date.now()+EN},jU=function(){let A=new Date;return A.setTime(gh()),A.toLocaleString()},lN=function(A){let e=String(A.getMilliseconds());return"padStart"in String.prototype&&(e=e.toString().padStart(3,"0")),"".concat(A.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(e)},tl={};XC(tl,{REPORT_TYPE:()=>eM,buildSSOPackage:()=>Iu,bytes2ms:()=>jR,calculateScaleResolutionDownNumber:()=>AM,concatArrayBuffers:()=>qf,convertObjectNumberToInt:()=>$R,copyProperties:()=>dO,deepClone:()=>Dh,deepCloneBasic:()=>yh,deepMerge:()=>tB,delay:()=>AC,fibonacci:()=>ph,formatedTime:()=>MO,getConstructorName:()=>Yf,getContainerFromElement:()=>LN,getEnv:()=>BO,getFirst16Bits:()=>SO,getInternalVersion:()=>yO,getLast16Bits:()=>tM,getLoggerUrl:()=>dh,getMediaStreamTrackInfo:()=>YN,getMuteStateFromFlag:()=>mQ,getNetworkType:()=>qR,getNumNetworkType:()=>hh,getReconnectionTimeout:()=>fQ,getStringByteLength:()=>XR,getTestSignalDomain:()=>uO,getTurnServer:()=>RO,getUint32Version:()=>UN,getValueType:()=>ya,getViewListFromView:()=>Hf,glog:()=>pO,ipv4ToUint32:()=>Jf,isArray:()=>Aa,isAudioWorkletSupported:()=>fO,isBoolean:()=>rn,isConstructor:()=>mh,isEmpty:()=>zR,isFunction:()=>$n,isLangChinese:()=>rl,isMediaStreamTrack:()=>_N,isNumber:()=>hr,isObject:()=>Xc,isOverseaSdkAppId:()=>ol,isPlainObject:()=>Cc,isPortrait:()=>FN,isPromise:()=>fh,isRemoteTrack:()=>bN,isRotate90Or270:()=>gu,isSetSinkIdSupported:()=>mO,isString:()=>Sr,isUndefined:()=>Ee,isVideoMixerOutputTrack:()=>DQ,loadImage:()=>Vf,loadVideo:()=>wO,ms2bytes:()=>hO,ms2samples:()=>WR,normalizeUrl:()=>xN,performanceNow:()=>ki,promiseAny:()=>Pf,samples2ms:()=>kN,setNetworkTypeFromWebRTC:()=>KR,stringify:()=>nl,stringifyIncludeValue:()=>ZR,throttlePromise:()=>ON});var WU={};XC(WU,{ASR_ROBOT_FROM_TYPE:()=>xR,AUDIO_MUTE_BIT:()=>Eh,AUDIO_STAT_BIT:()=>Gf,AUX_STAT_BIT:()=>Tf,AUX_STREAM_MSID:()=>tO,BACKEND_ENV:()=>Ih,BASE_DOC_URL:()=>$C,BASE_HOST:()=>ZU,CAPABILITIES_KEYS:()=>RN,CLASS_NAME:()=>eq,CLOUD_CONSOLE_URL:()=>WV,CROSS_ROOM_BIT:()=>hN,DATA_CHANNEL_FROM_TYPE_BIT:()=>nu,DATA_FREEZE_TIMING:()=>DN,DOC_BILLING_CN:()=>NR,DOC_BILLING_OVERSEA:()=>uN,DOC_URL:()=>zV,DTLS_STATE_UNKNOWN:()=>AB,ENV_NAME:()=>ou,EXCHANGE_SDP_TIMEOUT:()=>aO,IS_WORKER:()=>SR,IS_WORKLET:()=>vR,KIBANA_EVENT:()=>oa,LOCAL_STREAM_PUBLISH_STATE:()=>sO,LOGGER_CMD_TYPE:()=>Xg,LOGGER_DOMAIN:()=>Zg,LOGGER_DOMAIN_OVERSEA:()=>QQ,LOG_LEVEL:()=>ru,LOG_LEVEL_NAME:()=>iq,MAIN_STREAM_MSID:()=>RI,MAX_RTT:()=>OR,MICROPHONE_COMMUNICATIONS:()=>tq,MICROPHONE_DEFAULT:()=>bf,MUTE_ALL_BIT:()=>eO,NAME:()=>fA,NETWORK_TYPE:()=>TR,NOT_SUPPORTED_H264:()=>FR,PAUSED_RETRY_COUNT:()=>pQ,PEERCONNECTION_CONNECTING_TIMEOUT:()=>yN,PEER_CONNECTION_STATE:()=>hi,PEER_LEAVE_REASON:()=>cO,RECOVER_CAPTURE_INTERVAL:()=>Ff,REMOTE_STREAM_TYPE_AUX:()=>pN,REMOTE_STREAM_TYPE_MAIN:()=>kR,RENDER_FREEZE_TIMING:()=>gO,SCHEDULE_DOMAIN:()=>su,SCHEDULE_TIMEOUT:()=>IO,SDP_SEMANTICS_PLAN_B:()=>LR,SDP_SEMANTICS_UNIFIED_PLAN:()=>_f,SECOND_HOST:()=>XU,SIGNAL_PING_PONG_INTERVAL:()=>lc,SIGNAL_PING_TIMEOUT:()=>$U,SIGNAL_RECONNECTION_COUNT:()=>ZV,SMALL_STAT_BIT:()=>dN,SPEAKER_DEFAULT:()=>UR,STORAGE_EXPIRES_TIME:()=>GR,STREAM_TYPE_BIG:()=>$V,STREAM_TYPE_SMALL:()=>Aq,SUBSCRIBE_SMALL_RETRY_COUNT:()=>Lf,SYNC_USER_LIST_INTERVAL:()=>XV,Scene:()=>ch,THIRD_HOST:()=>jV,TRANSPORT_DIRECTION:()=>_r,TRTC_ERROR_ASSISTANCE:()=>Sf,TRTC_QUALITY_BAD:()=>lh,TRTC_QUALITY_DISCONNECTED:()=>rO,TRTC_QUALITY_EXCELLENT:()=>_R,TRTC_QUALITY_GOOD:()=>au,TRTC_QUALITY_POOR:()=>iO,TRTC_QUALITY_UNKNOWN:()=>fN,TRTC_QUALITY_VERY_BAD:()=>oO,UPDATE_OFFER_TIMEOUT:()=>nO,VIDEO_MUTE_BIT:()=>kf,VIDEO_STAT_BIT:()=>Nf,WEBGL_ATTRIBUTES:()=>MN,audioProfileMap:()=>dQ,defaultBigVideoProfile:()=>vf,defaultSmallVideoProfile:()=>AO,getRetryCount:()=>Ch,getScriptDir:()=>KV,innerVersion:()=>wR,loggerProxy:()=>BN,screenProfileMap:()=>QN,setLoggerProxy:()=>wf,setRetryCount:()=>bR,setVersion:()=>zU,version:()=>il,videoProfileMap:()=>$l});var wR="4.15.00.1600",il="5.0.0";function zU(A){il=A;let[e,o,n]=A.split(".").map(a=>parseInt(a,10));wR="".concat(e,".").concat(Math.min(15,o),".").concat(Math.min(15,n),".").concat(o.toString().padStart(2,"0")).concat(n.toString().padStart(2,"0"))}var CN,Ec,SR=typeof importScripts<"u",vR=typeof registerProcessor<"u",KV=()=>{let A=SR?self.location.href:document.currentScript.src;return A.substring(0,A.lastIndexOf("/")+1)},BN="",wf=A=>BN=A,ZU="web.sdk.qcloud.com",XU="web.sdk.tencent.cn",jV="web.sdk.cloud.tencent.cn",WV="https://console.cloud.tencent.com/trtc",$C="https://".concat(ZU,"/trtc/webrtc/doc"),zV="".concat($C,"/zh-cn/"),NR="https://cloud.tencent.com/document/product/647/85386",uN="https://trtc.io/document/56025",Zg="https://yun.tim.qq.com",QQ="https://apisgp.my-imcloud.com",Sf="trtc_error_assistance",Xg={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},ou={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},ru=((Ec=ru||{})[Ec.TRACE=0]="TRACE",Ec[Ec.DEBUG=1]="DEBUG",Ec[Ec.INFO=2]="INFO",Ec[Ec.WARN=3]="WARN",Ec[Ec.ERROR=4]="ERROR",Ec[Ec.NONE=5]="NONE",Ec),$U=18e3,lc=2e3,TR={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},GR=6048e5,dQ={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}},$l={"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}},vf=$l["480p_2"],AO=$l["120p_2"],QN={"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}},fA={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"},_r={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Ih={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},ch=((CN=ch||{}).LIVE="live",CN.RTC="rtc",CN),Nf=1,dN=2,Tf=4,Gf=8,Eh=64,kf=16,eO=112,hN=128,nu=256,RI="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",tO="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",kR=fA.MAIN,pN=fA.AUXILIARY,fN=0,_R=1,au=2,iO=3,lh=4,oO=5,rO=6,AB="unknown",hi={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},mN=1/0;function bR(A){mN=A}function Ch(){return mN}var hQ,ZV=30,oa={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"},XV=1e4,nO=1e4,aO=1e4,_f="unified-plan",LR="plan-b",FR=1028,sO=((hQ=sO||{})[hQ.UNPUBLISH=-1]="UNPUBLISH",hQ[hQ.PUBLISHING=0]="PUBLISHING",hQ[hQ.PUBLISHED=1]="PUBLISHED",hQ),DN=500,gO=1e3,$V=fA.BIG,Aq=fA.SMALL,yN=1e4,su={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"},IO=2e3,eq={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},pQ=5,bf="default",UR=bf,tq="communications",iq=Object.keys(ru),cO=["normal leave","timeout leave","kick","role change"],Lf=10,Ff=2e3,RN=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],OR=1e4,xR=14,MN={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},EO=function(A,e,o,n){return new(o||(o=Promise))(function(a,I){function c(R){try{d(n.next(R))}catch(k){I(k)}}function u(R){try{d(n.throw(R))}catch(k){I(k)}}function d(R){R.done?a(R.value):function(k){return k instanceof o?k:new o(function(_){_(k)})}(R.value).then(c,u)}d((n=n.apply(A,[])).next())})},YR=Symbol(32),PR=Symbol(16),wN=Symbol(8),Bh=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,e){return e&&this.consume(),this.need=A,this.flush()}read(A){return EO(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((e,o)=>{var n;this.reject=o,this.resolve=a=>{delete this.lastReadPromise,delete this.resolve,delete this.need,e(a)},this.demand(A,!0)||(n=this.pull)===null||n===void 0||n.call(this,A)})})}readU32(){return this.read(YR)}readU16(){return this.read(PR)}readU8(){return this.read(wN)}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,e=this.buffer.subarray(this.consumed),o=0,n=a=>e.length<(o=a);if(typeof this.need=="number"){if(n(this.need))return;A=e.subarray(0,o)}else if(this.need===YR){if(n(4))return;A=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===PR){if(n(2))return;A=e[0]<<8|e[1]}else if(this.need===wN){if(n(1))return;A=e[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(n(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(e.subarray(0,o)),A=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(n(this.need.byteLength))return;new Uint8Array(this.need).set(e.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(e=>this.pull=e);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 e=this.buffer.length,o=e+A;if(o<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,o);else{let n=new Uint8Array(o);n.set(this.buffer),this.buffer=n}return this.buffer.subarray(e,o)}return this.buffer=new Uint8Array(A),this.buffer}};Bh.U32=YR,Bh.U16=PR,Bh.U8=wN;var Uf=128;function JR(A){let e=new Bh;for(;A>=128;)e.malloc(1)[0]=255&A|Uf,A>>>=7;return e.malloc(1)[0]=255&A,e.buffer||new Uint8Array(0)}function HR(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=new Bh,n=e<<3;switch(typeof A){case"boolean":let a=o.malloc(2);a[0]=n,a[1]=A?1:0;break;case"number":o.malloc(1)[0]=n,o.write(JR(A));break;case"string":o.malloc(1)[0]=2|n;let I=new TextEncoder().encode(A);o.write(JR(I.length));let c=o.malloc(I.length);for(let d=0;d>>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 e=0;e>>24&255,A[o+1]=e>>>16&255,A[o+2]=e>>>8&255,A[o+3]=255&e}function MI(A,e){return A[e]<<24|A[e+1]<<16|A[e+2]<<8|A[e+3]}function CO(A,e){return A[e]}function Qh(A,e,o){return new TextDecoder().decode(function(n,a,I){return n.slice(a,a+I)}(A,e,o))}var Of=0,SN=2654435769,VR=16,eB=2,xf=7;function vN(A,e){let o=new lO,n=function(XA,Ft,ie){let ke=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:ie,appId:XA,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:ke,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:Ft}}(e,A,Of);Of=Of+1&2147483647,o.writeInt32(0),o.writeInt32(n.version),o.writeByte(n.encryption);let a=new TextEncoder().encode(n.d2);o.writeInt32(a.length+4),a&&o.writeBytes(a),o.writeByte(n.uinType);let I=new TextEncoder().encode(n.uin);o.writeInt32(I.length+4),I.length&&o.writeBytes(I);let c=new lO;c.writeInt32(0),c.writeInt32(n.reqHead.seqNumber),c.writeInt32(n.reqHead.appId),c.writeByte(n.reqHead.appId>>>24&255),c.writeByte(n.reqHead.appId>>>16&255),c.writeByte(n.reqHead.appId>>>8&255),c.writeByte(255&n.reqHead.appId);for(let XA=4;XA<16;XA++)c.writeByte(0);let u=new TextEncoder().encode(n.reqHead.a2);c.writeInt32(u.length+4),u.length&&c.writeBytes(u);let d=new TextEncoder().encode(n.reqHead.serviceCmd);c.writeInt32(d.length+4),d.length&&c.writeBytes(d);let R=new TextEncoder().encode(n.reqHead.cookie);c.writeInt32(R.length+4),R.length&&c.writeBytes(R);let k=new TextEncoder().encode(n.reqHead.imei);c.writeInt32(k.length+4),k.length&&c.writeBytes(k);let _=new TextEncoder().encode(n.reqHead.ksid);c.writeInt32(_.length+4),_.length&&c.writeBytes(_);let Z=new TextEncoder().encode(n.reqHead.clientVersionInfo);c.writeInt16(Z.length+2),Z.length&&c.writeBytes(Z);let iA=c.length;c.data[0]=iA>>>24&255,c.data[1]=iA>>>16&255,c.data[2]=iA>>>8&255,c.data[3]=255&iA,Sr(A)&&(A=new TextEncoder().encode(A)),c.writeInt32(A.length+4),A.length&&c.writeBytes(A);let cA=new Uint8Array(c.data),TA=null;n.encryption===1?TA=new TextEncoder().encode(n.uin):n.encryption===2&&(TA=new Uint8Array(16)),TA&&(cA=function(XA,Ft){let ie=XA.length,ke=(ie+1+eB+xf)%8;ke&&(ke=8-ke);let Nt=ie+1+eB+xf+ke,Ut=new Uint8Array(Nt),Ui=0,Oi=new Uint8Array(8),or=new Uint8Array(8),xi=new Uint8Array(8),yo=0;Oi[0]=248&Math.floor(256*Math.random())|ke,yo=1;for(let Vn=0;Vn>>24&255,JA[1]=Ie>>>16&255,JA[2]=Ie>>>8&255,JA[3]=255&Ie,JA}function NN(A,e,o,n,a,I){for(let c=0;c<8;c++)A[c]^=n[c];(function(c,u,d,R){let k=MI(c,0),_=MI(c,4),Z=[];for(let cA=0;cA<4;cA++)Z[cA]=MI(u,4*cA);let iA=0;for(let cA=0;cA>>=0,k+=(_<<4)+Z[0]^_+iA^(_>>>5)+Z[1],k>>>=0,_+=(k<<4)+Z[2]^k+iA^(k>>>5)+Z[3],_>>>=0;uh(d,k,R),uh(d,_,R+4)})(A,e,a,I);for(let c=0;c<8;c++)a[I+c]^=o[c];for(let c=0;c<8;c++)o[c]=A[c]}var BO=function(){return new URLSearchParams(location.search).get("trtc_env")||""},uO=function(A){return A.includes(".")?A:"".concat(A).concat(".rtc.qq.com")},ol=A=>Number(A)<14e8,dh=function(A,e){let o;o=BN||(ol(A)?QQ:Zg);let n=Math.floor(Math.random()*Rf(2,31));return"".concat(o,"/v5/AVQualityReportSvc/C2S?random=").concat(n,"&sdkappid=").concat(A,"&cmdtype=").concat(e)},TN="unknown";function qR(){(function(){var I;QO||(QO=!0,(I=navigator.connection)==null||I.addEventListener("typechange",oq))})();let{userAgent:A,connection:e}=navigator,o=(A.match(/NetType\/\S+/)||[])[0]||"";o=o.toLowerCase().replace("nettype/",""),o==="3gnet"&&(o="3g");let n=e&&e.type&&e.type.toLowerCase(),a=e&&e.effectiveType&&e.effectiveType.toLowerCase();return a==="slow-2"&&(a="2g"),n?GN(n,a):TN}function oq(){nA.warn("netType changed",qR())}var QO=!1;function GN(A,e){if(TR[A])return A;switch(A){case"cellular":case"wimax":return e||"unknown";case"ethernet":return"wired";default:return"unknown"}}function KR(A){TN=GN(A)}function hh(){return TR[qR()]}function dO(A,e){for(let o of Reflect.ownKeys(e))if(o!=="constructor"&&o!=="prototype"&&o!=="name"){let n=Object.getOwnPropertyDescriptor(e,o)||"";Object.defineProperty(A,o,n)}return A}function jR(A){return kN(A/4,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function kN(A){return 1e3*A/(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function hO(A){return 4*WR(A,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function WR(A){return A*(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)/1e3}var pO=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},rl=()=>{let A=navigator.language;return A=A.substring(0,2),A==="zh"},Cc=function(A){if(!A||typeof A!="object"||Object.prototype.toString.call(A)!="[object Object]")return!1;let e=Object.getPrototypeOf(A);if(e===null)return!0;let o=Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor;return typeof o=="function"&&o instanceof o&&Function.prototype.toString.call(o)===Function.prototype.toString.call(Object)};function ph(A){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;return A<=1?e:ph(A-1,e,(arguments.length>1&&arguments[1]!==void 0?arguments[1]:1)+e)}function fQ(A){return A>8?3e4:1e3*ph(A)}function ya(A){return Reflect.apply(Object.prototype.toString,A,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var $n=A=>typeof A=="function",Ee=A=>A===void 0,Sr=A=>typeof A=="string",hr=A=>typeof A=="number",rn=A=>typeof A=="boolean",Xc=A=>ya(A)==="object",Aa=A=>ya(A)==="array",_N=A=>ya(A)==="MediaStreamTrack".toLowerCase(),bN=A=>A.isRemote,fh=A=>ya(A)==="promise",mh=A=>$n(A)&&A.prototype.constructor===A,Yf=A=>mh(A)?A.prototype.constructor.name:"",fO=typeof AudioWorkletNode<"u",mO=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype;function Pf(A){return new Promise((e,o)=>{let n=[];A.forEach(a=>{a.then(e).catch(I=>{n.push(I),n.length===A.length&&o(n)})})})}function ki(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var DO=A=>+A<10?"0".concat(A):A,yO=A=>{let e=A.match(/^\d+\.\d+\.\d+/)[0];if(!e)return A;let o=e.split("."),n=DO(o[1])+DO(o[2]);return o[1]-15>0&&(o[1]="15"),o[2]-15>0&&(o[2]="15"),"".concat(o.join("."),".").concat(n)},rq=Object.prototype.hasOwnProperty;function zR(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(Cc(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 e in A)if(rq.call(A,e))return!1;return!0}return!1}function mQ(A,e){return{userId:e,hasAudio:!!(A&Gf),hasVideo:!!(A&Nf),hasAuxiliary:!!(A&Tf),hasSmall:!!(A&dN),audioMuted:!!(A&Eh),videoMuted:!!(A&kf),audioAvailable:!(!(A&Gf)||A&Eh),videoAvailable:!(!(A&Nf)||A&kf),hasDatachannel:!!(A&nu)}}function RO(A){let e={urls:A.url.startsWith("turn:")||A.url.startsWith("turns:")?A.url:"turn:".concat(A.url)};return!Ee(A.username)&&!Ee(A.credential)&&(e.username=A.username,e.credential=A.credential,e.credentialType="password",Ee(A.credentialType)||(e.credentialType=A.credentialType)),e}function Jf(A){let e=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(!Sr(A))return 0;let o=A.split(".");return e?(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 tB=function(A,e,o,n){if(!Xc(A)||!Xc(e))return 0;let a,I=0,c=Object.keys(e);for(let u=0,d=c.length;u{e[n]=Dh(o)}),e}if(Xc(A)){let e={};return Object.keys(A).forEach(o=>{e[o]=Dh(A[o])}),e}return A}var Hf=A=>{let e=[];if(Aa(A))e=[...A];else if(Sr(A)){let o=document.getElementById(A);o&&e.push(o)}else A&&e.push(A);return e},LN=A=>Sr(A)?document.getElementById(A):A,MO=()=>(A=>{let e=d=>d<10?"0".concat(d):"".concat(d),o=A.getFullYear(),n=A.getMonth()+1,a=A.getDate(),I=e(A.getHours()),c=e(A.getMinutes()),u=e(A.getSeconds());return"".concat(o,"/").concat(n,"/").concat(a," ").concat(I,":").concat(c,":").concat(u)})(new Date);function nl(A,e){let{keysToInclude:o,keysToExclude:n}=e;try{if(Aa(A))return"[".concat(A.map(u=>nl(u,{keysToInclude:o,keysToExclude:n})).join(","),"]");if(!Cc(A)||!Aa(o)&&!Aa(n))return JSON.stringify(A);let a={},I=new Set(o),c=new Set(n);return Object.keys(A).forEach(u=>{(c.size===0&&I.has(u)||I.size===0&&!c.has(u))&&(a[u]=Cc(A[u])||Aa(A[u])?JSON.parse(nl(A[u],{keysToExclude:n,keysToInclude:o})):A[u])}),JSON.stringify(a)}catch{return"{}"}}function ZR(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1],o=[];return Object.keys(A).forEach(n=>{e===A[n]&&o.push(n)}),nl(A,{keysToInclude:o})}function XR(A){return A.replace(/[\u4e00-\u9fa5]/g,"aa").length}var FN=()=>{var A,e,o,n;return(A=window.screen)!=null&&A.orientation?!((n=(o=(e=window.screen)==null?void 0:e.orientation)==null?void 0:o.type)==null||!n.includes("portrait")):window.orientation===0||window.orientation===180},Vf=A=>DA(null,null,function*(){return new Promise((e,o)=>{let n;if(Sr(A))n=new Image,n.crossOrigin="anonymous",n.src=A;else if(n=A,n.complete)return void e(n);n.onload=()=>e(n),n.onerror=()=>{o(new Ct({code:Ge.INVALID_PARAMETER,message:"load image failed, url: ".concat(A)}))}})}),UN=A=>{let e=A.split(".");return+e[0]<<24|+e[1]<<16|+e[2]<<8|+e[3]},$R=A=>(Object.keys(A).forEach(e=>{hr(A[e])&&(e.startsWith("uint")||e.startsWith("int"))?A[e]=Math.floor(A[e]):(Cc(A[e])||Aa(A[e]))&&$R(A[e])}),A);function AC(A,e){return new Promise(o=>{let n=setTimeout(o,A);e&&e(n)})}function ON(A,e){let o=null;return function(){for(var n=arguments.length,a=new Array(n),I=0;Io=null),o)}}function xN(A){return A.replace(/(^|[^:])\/{2,}/g,"$1/")}function YN(A){var e;try{let{width:o,height:n,frameRate:a,sampleRate:I,sampleSize:c,channelCount:u}=(e=A.getSettings)==null?void 0:e.call(A),d=A.kind===fA.AUDIO?"".concat(I,"x").concat(c,"@").concat(u):"".concat(o,"x").concat(n,"@").concat(a),R=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(d).concat(R)}catch{return""}}function AM(A,e){return A.width*A.height===e.width*e.height?1:FN()&&e.width>e.height&&A.height>e.width?Math.max(A.width/e.height,A.height/e.width,1):Math.max(A.width/e.width,A.height/e.height,1)}function gu(A){return A===90||A===270}function wO(A){return DA(this,null,function*(){return new Promise((e,o)=>{let n=document.createElement("video");n.crossOrigin="anonymous",n.src=A,n.muted=!0,n.loop=!0,n.playsInline=!0,n.play().then(()=>e(n)),n.onerror=()=>{o(n.error)}})})}function yh(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:new WeakMap;if(typeof A!="object"||A===null)return A;if(e.has(A))return e.get(A);if(Array.isArray(A)){let o=[];return e.set(A,o),A.forEach((n,a)=>{o[a]=yh(n,e)}),o}if(Object.prototype.toString.call(A)==="[object Object]"){let o={};return e.set(A,o),Reflect.ownKeys(A).forEach(n=>{o[n]=yh(A[n],e)}),o}return A}var eM=(A=>(A[A.END_REPORT=2001]="END_REPORT",A[A.LOG=2002]="LOG",A[A.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",A))(eM||{});function Iu(A,e,o,n){try{let a=function(I,c,u,d){let R={data:I,random:Math.floor(2147483648*Math.random()),sdkAppId:u};return Ee(d)||(R=fi(bt({},R),{gzip:+d})),{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:c,bytes_report_data:JSON.stringify(R)}}}(A,e,o,n);return vN(HR(a),o)}catch{return JSON.stringify(A)}}function qf(A,e){let o=new Uint8Array(A.byteLength+e.byteLength);return o.set(new Uint8Array(A),0),o.set(new Uint8Array(e),A.byteLength),o.buffer}function tM(A){return(65535&A)>>>0}function SO(A){return(4294901760&A)>>>0}function DQ(A){return!!(A&&A instanceof CanvasCaptureMediaStreamTrack&&A.canvas.id.includes("trtc_mix"))}function nq(A){let e=function(o){try{let n={},a=0;n.totalLength=MI(o,a),a+=4,n.version=MI(o,a),a+=4,n.encryption=CO(o,a),a+=1,n.uinType=CO(o,a),a+=1,n.uinLength=MI(o,a),a+=4,n.uin=n.uinLength>4?Qh(o,a,n.uinLength-4):"",a+=n.uinLength-4;let I=o.slice(a);return n.encryption===2?(o=function(c,u){let d=0,R=new Uint8Array(8).fill(0),k=new Uint8Array(c.slice(0,8)),_=iM(k,u),Z=7&_[0],iA=c.length-1-Z-eB-xf,cA=new Uint8Array(iA),TA=0,JA=R,Ie=c.slice(0,8);d=8;let XA=1;XA+=Z;for(let ie=1;ie<=eB;)if(XA<8)XA++,ie++;else if(XA===8){let ke=Rh(c,d,JA,Ie,_,u);JA=ke.ivPreCrypt,Ie=ke.ivCurCrypt,_=ke.debiBuf,d=ke.bufPos,XA=0}let Ft=iA;for(;Ft>0;)if(XA<8)cA[TA++]=_[XA]^JA[XA],XA++,Ft--;else if(XA===8){let ie=Rh(c,d,JA,Ie,_,u);JA=ie.ivPreCrypt,Ie=ie.ivCurCrypt,_=ie.debiBuf,d=ie.bufPos,XA=0}for(let ie=1;ie<=xf;)if(XA<8)_[XA],JA[XA],XA++,ie++;else if(XA===8){if(d>=c.length)break;let ke=Rh(c,d,JA,Ie,_,u);if(!ke.success)break;JA=ke.ivPreCrypt,Ie=ke.ivCurCrypt,_=ke.debiBuf,d=ke.bufPos,XA=0}return cA}(I,new Uint8Array(16).fill(0)),n.decrypted=!0,a=0):(o=I,a=0),n.rspHeadLength=MI(o,a),a+=4,n.seqNo=MI(o,a),a+=4,n.retCode=MI(o,a),a+=4,n.retStrLength=MI(o,a),a+=4,n.retStr=n.retStrLength?Qh(o,a,n.retStrLength-4):"",a+=n.retStrLength-4,n.serviceCmdLength=MI(o,a),a+=4,n.serviceCmd=n.serviceCmdLength?Qh(o,a,n.serviceCmdLength-4):"",a+=n.serviceCmdLength-4,n.cookieLength=MI(o,a),a+=4,n.cookie=n.cookieLength?Qh(o,a,n.cookieLength-4):"",a+=n.cookieLength-4,n.flag=MI(o,a),a+=4,n.busiBuffLength=MI(o,a),a+=4,n.busiBuff=n.busiBuffLength?Qh(o,a,n.busiBuffLength-4):"",a+=n.busiBuffLength-4,n}catch{}}(A);return e?.busiBuff}function iM(A,e){let o=A[0]<<24|A[1]<<16|A[2]<<8|A[3],n=A[4]<<24|A[5]<<16|A[6]<<8|A[7];o>>>=0,n>>>=0;let a=SN*VR>>>0;for(let I=0;I>>5)+e[3],n>>>=0,o-=(n<<4)+e[0]^n+a^(n>>>5)+e[1],o>>>=0,a-=SN,a>>>=0;return new Uint8Array([o>>>24&255,o>>>16&255,o>>>8&255,255&o,n>>>24&255,n>>>16&255,n>>>8&255,255&n])}function Rh(A,e,o,n,a,I){if(e+8>A.length)return{success:!1};let c=new Uint8Array(n),u=A.slice(e,e+8),d=new Uint8Array(8);for(let R=0;R<8;R++)d[R]=a[R]^u[R];return{success:!0,ivPreCrypt:c,ivCurCrypt:u,debiBuf:iM(d,I),bufPos:e+8}}var yQ=typeof TextDecoder<"u"?new TextDecoder:void 0;function cu(A){let{url:e,body:o,method:n="POST",timeout:a,priority:I}=A;return new Promise((c,u)=>{if("fetch"in window)return fetch(e,{method:n,body:o,priority:I}).then(R=>R.clone().json().then(k=>({data:k}),()=>R.arrayBuffer().then(k=>({data:nq(new Uint8Array(k))||(yQ?yQ.decode(k):k)})))).then(c,u);let d=new XMLHttpRequest;d.onreadystatechange=()=>{if(d.readyState===4)if(d.status>=200&&d.status<300)try{let R=JSON.parse(d.response);c({data:R})}catch{c({data:d.response})}else u({status:d.status,statusText:d.statusText||"request failed!"})},d.timeout=a||5e3,d.open(n,e,!0),d.send(o)})}function PN(A){return DA(this,null,function*(){let e=ki(),o=JSON.stringify(A);try{if(!CompressionStream||o.length<=2800)return o;let n=new Blob([o],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(n)).blob()).arrayBuffer();return nA.debug("compressJSON ".concat(o.length," -> ").concat(a.byteLength," ").concat(ki()-e,"ms")),a}catch{return o}})}var vO=Object.prototype.hasOwnProperty,RQ=A=>typeof A=="function",$c=A=>A===void 0,JN=A=>typeof A=="string",NO=A=>typeof A=="boolean",HN=A=>A.isRemote,TO=function(A){if(!A||typeof A!="object"||Object.prototype.toString.call(A)!="[object Object]")return!1;let e=Object.getPrototypeOf(A);if(e===null)return!0;let o=Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor;return typeof o=="function"&&o instanceof o&&Function.prototype.toString.call(o)===Function.prototype.toString.call(Object)},Kf=function(A){let{retryFunction:e,settings:o,onError:n,onRetrying:a,onRetryFailed:I,onRetrySuccess:c,context:u}=A;return function(){for(var d=arguments.length,R=new Array(d),k=0;kDA(this,null,function*(){let Ft=u||this;try{let ie=yield e.apply(Ft,R);iA>0&&c&&c.call(this,iA),iA=0,Ie(ie)}catch(ie){let ke=()=>{clearTimeout(cA),iA=0,TA=2,XA(ie)},Nt=()=>{TA!==2&&iA<(RQ(_)?_():_)?(iA++,TA=1,RQ(a)&&a.call(this,iA,ke),cA=window.setTimeout(()=>{cA=-1,JA(Ie,XA)},RQ(Z)?Z(iA):Z)):(ke(),RQ(I)&&I.call(this,ie))};RQ(n)?n.call(this,{error:ie,retry:Nt,reject:XA,retryFuncArgs:R,retriedCount:iA}):Nt()}});return new Promise(JA)}},VN=class qZ{constructor(e){G(this,"_parentPath"),G(this,"userId"),G(this,"remoteUserId"),G(this,"id"),G(this,"sdkAppId"),G(this,"type"),G(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!NO(e.isLocal)||e.isLocal,this.type=this.isLocal?"":e.type}getFullId(){return this._parentPath&&this.id?"".concat(this._parentPath,"-").concat(this.id):this._parentPath?this._parentPath:this.id}createChild(e){let o=new qZ({id:e.id,userId:$c(e.userId)?this.userId:e.userId,sdkAppId:$c(e.sdkAppId)?this.sdkAppId:e.sdkAppId,type:$c(e.type)?this.type:e.type,isLocal:$c(e.isLocal)?this.isLocal:e.isLocal,remoteUserId:$c(e.remoteUserId)?this.remoteUserId:e.remoteUserId});return o.bindParent(this),o}bindParent(e){let o=e.getFullId();this._parentPath!==o&&(this.debug("bind logger parent: ".concat(e.id)),this._parentPath=o,this.userId=e.userId||this.userId,this.sdkAppId=e.sdkAppId||this.sdkAppId)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,o){let n=this.isLocal?this.userId:this.remoteUserId,a=this.getFullId();o.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&this.type!=="main"?"*":"").concat(a).concat(n?"|".concat(n):"","]")),nA.log(e,o,$c(this.userId)||function(I){if(I==null)return!0;if(typeof I=="boolean")return!1;if(typeof I=="number")return I===0;if(typeof I=="string"||typeof I=="function"||Array.isArray(I))return I.length===0;if(I instanceof Error)return I.message==="";if(TO(I))switch(Object.prototype.toString.call(I)){case"[object File]":case"[object Map]":case"[object Set]":return I.size===0;case"[object Object]":for(let c in I)if(vO.call(I,c))return!1;return!0}return!1}(this.userId),this.userId,this.sdkAppId)}info(){for(var e=arguments.length,o=new Array(e),n=0;nnM,CHROME_MAJOR_VERSION:()=>tE,CHROME_VERSION:()=>uM,EDGE_VERSION:()=>KN,EDG_MAJOR_VERSION:()=>sM,EDG_VERSION:()=>jN,ELECTRON_MAJOR_VERSION:()=>OO,FIREFOX_MAJOR_VERSION:()=>aM,FIREFOX_VERSION:()=>Wf,HUAWEI_VERSION:()=>rT,IE_VERSION:()=>gq,IOS_MAIN_VERSION:()=>al,IOS_VERSION:()=>$g,IPADQQB_VERSION:()=>$f,IS_ANDROID:()=>ra,IS_ANDROID_WEBVIEW:()=>sT,IS_ANY_SAFARI:()=>TQ,IS_CHROME:()=>BM,IS_CHROME_OS:()=>eT,IS_CHROMIUM_128_TO_143:()=>Gh,IS_CHROMIUM_BASE:()=>Bc,IS_DESKTOP_IOS_CHROME:()=>PO,IS_EDG:()=>wh,IS_EDGE:()=>Mh,IS_ELECTRON:()=>Iq,IS_FIREFOX:()=>Yr,IS_HEADLESS_CHROME:()=>UO,IS_HONOR:()=>oT,IS_HUAWEI:()=>iT,IS_HUAWEIBROWSER:()=>iB,IS_IE:()=>LO,IS_IE8:()=>sq,IS_IOS:()=>Ea,IS_IOS_13_OR_14:()=>YO,IS_IOS_15_1:()=>xO,IS_IOS_CHROME:()=>rm,IS_IPAD:()=>MQ,IS_IPADQQB:()=>EM,IS_IPAD_PRO:()=>rM,IS_IPHONE:()=>wQ,IS_IPOD:()=>_O,IS_LINUX:()=>Nh,IS_LOCAL:()=>GQ,IS_MAC:()=>lu,IS_MACQQB:()=>Xf,IS_MIBROWSER:()=>lM,IS_MQQB:()=>Zf,IS_NATIVE_ANDROID:()=>bO,IS_OLD_ANDROID:()=>aq,IS_OPENHARMONY:()=>Th,IS_OPPOBROWSER:()=>em,IS_SAFARI:()=>Ma,IS_SAFARI_15_1:()=>cq,IS_SAMSUNGBROWSER:()=>Am,IS_SOGOU:()=>IM,IS_SOGOUM:()=>zf,IS_TBS:()=>eE,IS_UCBROWSER:()=>tT,IS_VIVOBROWSER:()=>tm,IS_WECHAT:()=>Eu,IS_WIN:()=>vh,IS_WQQB:()=>cM,IS_WX:()=>FO,IS_X5MQQB:()=>vQ,IS_XWEB:()=>SQ,MACQQB_VERSION:()=>AT,MI_VERSION:()=>NQ,MQQB_VERSION:()=>Sh,OPENHARMONY_VERSION:()=>CM,OPPO_VERSION:()=>aT,SAFARI_VERSION:()=>Cu,SAMSUNG_VERSION:()=>nT,SOGOUM_VERSION:()=>gM,SOGOU_VERSION:()=>WN,TBS_VERSION:()=>zN,UA_DATA_STRING:()=>eC,USER_AGENT:()=>AE,VIVO_VERSION:()=>im,WECHAT_VERSION:()=>XN,WQQB_VERSION:()=>$N,XWEB_VERSION:()=>ZN,browserInfo:()=>uu,getBrowserCoreNumber:()=>pg,getBrowserInfo:()=>IT,getChromeMajorVersion:()=>om,getDeviceModel:()=>Qu,getDeviceModelFromUA:()=>cT,getGPUInfo:()=>kQ,getOSName:()=>Js,getOSNumber:()=>_Q,getOSString:()=>bQ,getOSType:()=>l,getTerminalType:()=>er,getUserAgentData:()=>nm,isAMDGPU:()=>_h,isAppleSiliconGPU:()=>Eq,isLocalStorageEnabled:()=>Bu,isMobile:()=>QM,isNvidiaGPU:()=>JO,isRealIOS:()=>jf,isVersionLargerThan:()=>kh,isVersionSmallerThan:()=>gT});var AE=typeof navigator>"u"?"":navigator.userAgent,Do=A=>new RegExp(A,"i").test(AE),Ra=A=>{if(Do(A)){let e=new RegExp("".concat(A,"\\/([\\d.]+)")),o=AE.match(e);if(o&&o[1])return o[1]}return""},oM=A=>{if(Do(A)){let e=new RegExp("".concat(A,"\\/(\\d+)")),o=AE.match(e);if(o&&o[1])return parseFloat(o[1])}return NaN},qN=/AppleWebKit\/([\d.]+)/i.exec(AE),kO=qN?parseFloat(qN[1]):NaN,MQ=Do("iPad"),rM=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Do("Macintosh"),wQ=Do("iPhone")&&!MQ,_O=Do("iPod"),Ea=wQ||MQ||_O||rM,jf=()=>{try{return Ea&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch{return Ea}},ra=Do("Android"),nM=function(){if(ra){let A=AE.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(A){let e=A[1]&&parseFloat(A[1]),o=A[2]&&parseFloat(A[2]);if(e&&o)return parseFloat("".concat(A[1],".").concat(A[2]));if(e)return e}}return NaN}(),aq=ra&&Do("webkit")&&nM<2.3,bO=ra&&nM<5&&kO<537,Yr=Do("Firefox"),Wf=Ra("Firefox"),aM=oM("Firefox"),Mh=Do("Edge"),KN=Ra("Edge"),wh=Do("Edg"),jN=Ra("Edg"),sM=oM("Edg"),zf=Do("SogouMobileBrowser"),gM=Ra("SogouMobileBrowser"),IM=Do("MetaSr\\s"),WN=Ra("MetaSr\\s"),eE=Do("TBS"),zN=Ra("TBS"),SQ=Do("XWEB"),ZN=Ra("XWEB"),sq=Do("MSIE\\s8\\.0"),LO=Do("MSIE\\/\\d+"),gq=function(){if(LO){let A=/MSIE\s(\d+)\.\d/.exec(AE),e=A&&parseFloat(A[1]);return!e&&/Trident\/7.0/i.test(AE)&&/rv:11.0/.test(AE)&&(e=11),e}return NaN}(),Eu=Do("(micromessenger|webbrowser)"),XN=Ra("MicroMessenger"),vQ=!eE&&Do("MQQBrowser")&&Do("COVC"),Zf=!eE&&Do("MQQBrowser")&&!Do("COVC"),Sh=Zf||vQ?Ra("MQQBrowser"):"",cM=!eE&&Do(" QQBrowser"),$N=Ra(" QQBrowser"),Xf=!eE&&Do("QQBrowserLite"),AT=Ra("QQBrowserLite"),EM=!eE&&Do("MQBHD"),$f=Ra("MQBHD"),vh=Do("Windows"),lu=!Ea&&Do("MAC OS X"),Nh=!ra&&Do("Linux"),eT=Do("CrOS"),FO=Do("MicroMessenger"),tT=Do("UCBrowser"),Iq=Do("Electron"),lM=Do("MiuiBrowser"),NQ=Ra("MiuiBrowser"),iB=Do("HuaweiBrowser"),iT=Do("Huawei")||Do("HUAWEI"),oT=Do("Honor")||Do("HONOR"),rT=Ra("HuaweiBrowser"),Am=Do("SamsungBrowser"),nT=Ra("SamsungBrowser"),em=Do("HeyTapBrowser"),aT=Ra("HeyTapBrowser"),tm=Do("VivoBrowser"),im=Ra("VivoBrowser"),Th=Do("OpenHarmony"),CM=Ra("OpenHarmony"),om=()=>oM("Chrome"),rm=Do("CriOS"),Bc=Do("Chrome"),BM=!Mh&&!IM&&!zf&&!eE&&!SQ&&!wh&&!cM&&!lM&&!iB&&!Am&&!em&&!tm&&Bc,UO=Do("HeadlessChrome"),tE=om(),Gh=Bc&&tE>=128&&tE<=143,uM=Ra("Chrome"),OO=oM("Electron"),Ma=!Bc&&!Zf&&!vQ&&!Xf&&!EM&&Do("Safari"),TQ=Ma||Ea,Cu=Ra("Version"),sT=/Android.*(wv|.0.0.0)/.test(AE),$g=(()=>{if(rM)return Cu;if(Ea){let A=AE.match(/OS (\d+)_(\d+)/i);if(A&&A[1]){let e=A[1];return A[2]&&(e+=".".concat(A[2])),e}}return""})();function gT(A,e){let o=A.split(".").map(a=>Number(a)),n=e.split(".").map(a=>Number(a));for(let a=0;ac)return!1}return!1}function kh(A,e){let o=arguments.length>2&&arguments[2]!==void 0&&arguments[2],n=A.split(".").map(I=>Number(I)),a=e.split(".").map(I=>Number(I));for(let I=0;Iu)return!0;if(c{let A=Number($g.split(".")[0]);return A===14||A===13})(),PO=rm&&Cu==="11.1.1",GQ=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),Bu=(()=>{let A;return()=>{if(A===void 0)try{A=!!window.localStorage}catch{A=!1}return A}})(),uu=IT();function IT(){let A=new Map([[Yr,["Firefox",Wf]],[wh,["Edg",jN]],[BM,["Chrome",uM]],[rm,["ChiOS",Ra("CriOS")]],[Ma&&!rm,["Safari",Cu]],[eE,["TBS",zN]],[SQ,["XWEB",ZN]],[Eu&&wQ,["WeChat",XN]],[cM,["QQ(Win)",$N]],[Zf,["QQ(Mobile)",Sh]],[vQ,["QQ(Mobile X5)",Sh]],[Xf,["QQ(Mac)",AT]],[EM,["QQ(iPad)",$f]],[lM,["MI",NQ]],[iB,["HW",rT]],[Am,["Samsung",nT]],[em,["OPPO",aT]],[tm,["VIVO",im]],[Mh,["EDGE",KN]],[zf,["SogouMobile",gM]],[IM,["Sogou",WN]]]),e="unknown",o="unknown";return A.has(!0)&&([e,o]=A.get(!0)),{name:e,version:o}}var Bn=null;function QM(){return Bn&&typeof Bn.mobile=="boolean"?Bn.mobile:ra||Ea||wQ||MQ||Th}var eC="";function nm(){return DA(this,null,function*(){if(Bn)return Bn;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return(Bn=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!eC&&(eC="UAData: ".concat(Bn.platform,"/").concat(Bn.platformVersion),Bn.architecture&&Bn.bitness&&(eC+=" ".concat(Bn.architecture,"/").concat(Bn.bitness)),Bn.mobile&&(eC+=" mobile"),Bn.model&&(eC+=" model: ".concat(Bn.model.replace(/\s+/g,"/"))),Bn.fullVersionList&&(eC+=" ".concat(Bn.fullVersionList.filter(A=>A.brand!=="Not/A)Brand").map(A=>"".concat(A.brand,"/").concat(A.version)).join(",")))),Bn}catch{return null}})}var am="";function kQ(){try{if(am)return am;let A=document.createElement("canvas"),e=A.getContext("webgl")||A.getContext("experimental-webgl");if(!e)return"";let o=e.getExtension("WEBGL_debug_renderer_info");if(o){let n=e.getParameter(o.UNMASKED_VENDOR_WEBGL),a=e.getParameter(o.UNMASKED_RENDERER_WEBGL);return am="".concat(n," ").concat(a)}return""}catch{return""}}function _h(){try{let A=kQ();return A.includes("AMD")||A.includes("ATI")}catch{return!1}}function JO(){try{let A=kQ();return A.includes("NVIDIA")||A.includes("GeForce")}catch{return!1}}function Eq(){try{return kQ().includes("Apple M")}catch{return!1}}function Qu(){return Bn?.model||cT()||""}function cT(){let A=AE.match(/;\s*([^;)]+)\s+Build\//);return A!=null&&A[1]?A[1].trim():null}var HO=new Map([[ra,"Android"],[Ea,"iOS"],[vh,"Windows"],[lu,"MacOS"],[Nh,"Linux"],[eT,"ChromeOS"]]),Js=function(){return HO.get(!0)?HO.get(!0):Bn?Bn.platform:"unknown"};function _Q(){return vh?1:ra?2:lu?3:Ea?4:Nh?5:eT?6:Th?7:0}function pg(){return Eu||SQ?4:Bc?1:Ma?2:Yr?3:0}var bQ=()=>{let A=Js();return Bn!=null&&Bn.platformVersion?A+="/".concat(Bn.platformVersion):Ea?A+="/".concat($g):ra&&(A+="/".concat(nM)),A+="/".concat(uu.name,"/").concat(Ma&&!rm?uu.version:uu.version.split(".")[0]),Bn!=null&&Bn.architecture&&(A+="/".concat(Bn.architecture)),A};function er(){return ra?4:wQ?2:MQ?3:lu?12:vh?5:Nh?13:Th?22:1}function l(){return ra?"Android":wQ?"iPhone":MQ?"iPad":lu?"Mac":vh?"Windows":Nh?"Linux":"unknown"}var p,S=new(es(hg(),1)).default,H=((p=H||{}).ROOM_DESTROY="1",p.JOIN_START="21",p.JOIN_SCHEDULE_SUCCESS="22",p.JOIN_SIGNAL_CONNECTION_START="23",p.JOIN_SIGNAL_CONNECTION_END="24",p.JOIN_SEND_CMD="25",p.JOIN_RECEIVED_CMD_RES="26",p.JOIN_SUCCESS="27",p.JOIN_FAILED="28",p.LEAVE_START="51",p.LEAVE_SEND_CMD="52",p.LEAVE_SUCCESS="53",p.PUBLISH_START="61",p.SEND_FIRST_VIDEO_FRAME="62",p.PUBLISH_FAILED="63",p.SUBSCRIBE_START="81",p.SUBSCRIBE_SUCCESS="82",p.SUBSCRIBE_FAILED="84",p.UNSUBSCRIBE_SUCCESS="83",p.LOCAL_TRACK_CAPTURE_START="101",p.LOCAL_TRACK_CAPTURE_SUCCESS="102",p.LOCAL_TRACK_CAPTURE_FAILED="103",p.LOCAL_TRACK_PUBLISHED="104",p.LOCAL_TRACK_UNPUBLISHED="105",p.LOCAL_TRACK_REPLACED="106",p.SWITCH_DEVICE_SUCCESS="107",p.TRACK_MUTED="108",p.TRACK_UNMUTED="109",p.REMOTE_TRACK_SUBSCRIBED="110",p.REMOTE_TRACK_UNSUBSCRIBED="111",p.LOCAL_TRACK_RECAPTURE="112",p.LOCAL_AUDIO_STARTED="113",p.LOCAL_AUDIO_STOPPED="114",p.REMOTE_AUDIO_STARTED="115",p.REMOTE_AUDIO_STOPPED="116",p.LOCAL_TRACK_STOPPED="117",p.LOCAL_VIDEO_TRACK_PREPROCESSED="118",p.PLAY_TRACK_START="151",p.PLAYER_STATE_CHANGED="152",p.VIDEO_LOADED_DATA="153",p.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",p.AUDIO_CONTEXT_LONG_SUSPENDED="155",p.REMOTE_VIDEO_PLAY_START="156",p.REMOTE_VIDEO_PLAY_FINISH="157",p.SIGNAL_CONNECTION_STATE_CHANGED="201",p.PEER_CONNECTION_STATE_CHANGED="202",p.SINGLE_CONNECTION_STAT="203",p.SPC_RECONNECTED="204",p.HEARTBEAT_REPORT="251",p.RECEIVED_PUBLISHED_USER_LIST="252",p.REMOTE_PUBLISH_STATE_CHANGED="253",p.AUDIO_LEVEL_INTERVAL="260",p.NETWORK_QUALITY="261",p.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",p.QUALITY_LIMITATION_CHANGED="263",p.LOG="264",p.AUDIO_PROCESSOR_DEBUG="265",p.SSO_SWITCH="266",p.SEI_MESSAGE="267",p.USER_PAUSE_IN_PIP="268",p.USER_RESUME_IN_PIP="269",p.ENTER_PICTURE_IN_PICTURE="270",p.LEAVE_PICTURE_IN_PICTURE="271",p.SWITCH_ROOM_START="401",p.SWITCH_ROOM_SUCCESS="407",p.SWITCH_ROOM_FAILED="408",p),K=H,lA=new class{constructor(){G(this,"enable",!1),G(this,"ssoFailCount",0),S.on("22",A=>{let{schedule:e}=A;var o;(o=e?.config)!=null&&o.sso&&S.emit("266",{enable:!0})}),S.on("266",A=>{let{enable:e}=A;this.enable=e})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&S.emit("266",{enable:!1})}},SA=class KZ{constructor(){G(this,"_isEnableUploadLog",!0),G(this,"_localJoinedUser",new Map),G(this,"_queue",[]),G(this,"_timeoutId",-1),G(this,"_logLevel",1),G(this,"_logLevelToUpload",2),!SR&&!vR&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){S.on(K.JOIN_SCHEDULE_SUCCESS,e=>{let{schedule:o}=e;var n;(n=o?.config)!=null&&n.logLevelToUpload&&ru[o.config.logLevelToUpload]&&(this._logLevelToUpload=o.config.logLevelToUpload)}),S.on(K.JOIN_START,e=>{let{params:o}=e;this.addJoinedUser({userId:o.userId,sdkAppId:o.sdkAppId}),this.startUpload()}),S.on(K.LEAVE_SUCCESS,e=>{let{room:o}=e;this.deleteJoinedUser(o.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}deleteJoinedUser(e){this._localJoinedUser.delete(e)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let e={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return e;let o=0;for(;o{let{userId:I,sdkAppId:c}=a;e.map.has(I)?e.map.get(I).logs.push(n):e.map.set(I,{userId:I,sdkAppId:c,logs:[n]})});else if(Sr(n.userId)&&hr(n.sdkAppId)){let{userId:a,sdkAppId:I}=n;e.map.has(a)?e.map.get(a).logs.push(n):e.map.set(a,{userId:a,sdkAppId:I,logs:[n]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,o)),e}upload(){return DA(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:e,splicedQueue:o}=this.getLogsToUpload();if(e.size===0)return;try{let a=[...e.values()];for(let I=0;IZ.log).join(` -`)},k=JSON.stringify(R),_=lA.enable?Iu(R,2002,u):k;yield this.uploadLogWithRetry(_,u,_ instanceof Uint8Array,k),d.forEach(Z=>Z.uploaded=!0)}}catch{}let n=o.filter(a=>!a.uploaded);n.length>0&&(this._queue=n.concat(this._queue))})}uploadLogWithRetry(e,o,n,a){return Kf({retryFunction:()=>cu({url:dh(o,Xg.LOG),body:e,timeout:5e3,priority:"low"}).then(I=>{n&&I.data!=="ok"&&(lA.handleUploadFailed(),this.uploadLogWithRetry(a,o,!1,a))}),settings:{retries:3,timeout:2e3},onError:I=>{let{retry:c}=I;c()}})()}getPrefix(e){let o=new Date;return o.setTime(gh()),"[".concat(lN(o),"] <").concat(ru[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){Ee(ru[e])||(this._logLevel!==e&&this.info("setLogLevel",e),this._logLevel=e)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(e){if(Sr(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch{return""}}addLogToQueue(e,o){let n=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],a=arguments.length>3?arguments[3]:void 0,I=arguments.length>4?arguments[4]:void 0,c={log:o.reduce((u,d)=>"".concat(u," ").concat(this.logChunkToString(d)).trim(),""),level:e,userId:a,sdkAppId:I,forAllJoinedClients:n};S.emit(K.LOG,{log:c}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(c)}log(e,o){let n=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],a=arguments.length>3?arguments[3]:void 0,I=arguments.length>4?arguments[4]:void 0;var c;if(o.unshift(this.getPrefix(e)),this.addLogToQueue(e,o,n,a,I),e{let e=16*Math.random()|0;return(A=="x"?e:3&e|8).toString(16)})},yA=new class{constructor(){G(this,"_prefix","TRTC"),G(this,"_queue",new Map)}getRealKey(A){return"".concat(this._prefix,"_").concat(A)}checkStorage(){Bu()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(A=>{if(A.startsWith(this._prefix))try{let e=localStorage.getItem(A);if(!e)return!1;let o=JSON.parse(e);if(o&&o.expiresInlocalStorage.removeItem(A)))}doFlush(){if(Bu())try{for(let[A,e]of this._queue)localStorage.setItem(A,JSON.stringify(e))}catch(A){nA.warn(A)}}getItem(A){if(!Bu())return null;try{let e=localStorage.getItem(this.getRealKey(A));if(!e)return null;let o=JSON.parse(e);return o&&o.expiresIn>=Date.now()?o.value:null}catch(e){nA.warn(e)}}setItem(A,e){if(Bu())try{let o={expiresIn:Date.now()+GR,value:e};this._queue.set(this.getRealKey(A),o)}catch(o){nA.warn(o)}}deleteItem(A){if(!Bu())return!1;try{return A=this.getRealKey(A),this._queue.delete(A),localStorage.removeItem(A),!0}catch(e){return nA.warn(e),!1}}clear(){if(Bu())try{localStorage.clear()}catch(A){nA.warn(A)}}},kA={};XC(kA,{HTTPS_API:()=>MT,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>Ax,IS_GET_CAPABILITIES_SUPPORTED:()=>$O,IS_GET_SETTINGS_SUPPORTED:()=>Jh,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>GT,IS_INSERTABLE_STREAM_SUPPORTED:()=>xQ,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>Du,IS_RTC_RTP_SENDER_SUPPORTED:()=>tC,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>MM,IS_SEI_SUPPORTED:()=>kT,IS_SPC_SUPPORTED:()=>Qm,basis:()=>tx,capabilityCheck:()=>LT,checkSystemRequirementsInternal:()=>yT,decodeSupportStatus:()=>DT,detectH264SupportedByFakeStreaming:()=>ZO,detectVideoCodecCapabilities:()=>hm,detectVideoDecoderCapabilities:()=>UT,detectVideoEncoderCapabilities:()=>FT,encodeSupportStatus:()=>lm,getBrowserInfo:()=>cm,getDisplayResolution:()=>rE,getH264ProfileLevelIds:()=>rx,isAddTransceiverSupported:()=>sl,isBrowserSupported:()=>fT,isCanvasCaptureStreamAPISupported:()=>Bm,isCanvasSmallStreamSupported:()=>RM,isGetReceiversSupported:()=>Ph,isGetSendersSupported:()=>AI,isGetTransceiversSupported:()=>mu,isGetUserMediaSupported:()=>wT,isMediaDevicesSupported:()=>mT,isMediaSessionSupported:()=>ex,isMediaStreamTrackGeneratorSupported:()=>Bq,isMediaStreamTrackProcessorSupported:()=>Em,isReplaceTrackSupported:()=>XO,isRequestVideoFrameCallbackSupported:()=>YQ,isSIMDSupported:()=>dm,isScaleResolutionDownBySupported:()=>vT,isScreenCaptureApiAvailable:()=>OQ,isSelectedCandidatePair:()=>Cm,isSetParametersSupported:()=>TT,isSetSinkIdSupported:()=>Qq,isSmallStreamSupported:()=>um,isStopTransceiverSupported:()=>vn,isTRTCSupported:()=>uq,isUnifiedPlanDefault:()=>NT,isUsedInHttpProtocol:()=>wI,isWebAudioSupported:()=>ST,isWebCodecSupported:()=>wM,isWebCodecsSupported:()=>yM,isWebRTCSupported:()=>Hh,isWebTransportSupported:()=>Vh});var oe={};XC(oe,{AUDIO_LEVEL_SCALE:()=>iE,AlphaStitchingType:()=>Oh,AudioCodecPipelineType:()=>fu,AudioDecoderDowngradeState:()=>sm,AudioPlayerMode:()=>pM,AudioType:()=>VO,BASIC_TYPE:()=>uT,BannedReason:()=>wa,CONNECTION_CLOSED_REASON:()=>it,CheckPermissionType:()=>Hr,ClientEvent:()=>de,CodecType:()=>gm,ConnectionEvent:()=>Li,ConnectionState:()=>bh,DECODE_FAILED_ERROR_CODE:()=>Im,DenoiserMode:()=>LQ,DeviceType:()=>QT,FacingMode:()=>lT,FrameWorkType:()=>ni,LeaveReason:()=>CT,LocalTrackEvent:()=>Ri,MULTI_VIDEO_DATA_TYPE:()=>Uh,MediaType:()=>dM,MediaTypeLabel:()=>lq,MonitorEventId:()=>Hs,MutedFlag:()=>br,NetworkQualityValue:()=>uc,PlayerState:()=>ui,ReceiveMode:()=>fg,RemoteStreamType:()=>Fh,RemoteTrackEvent:()=>tr,RoomEvent:()=>ci,SMALL_MODE:()=>UQ,SceneNumber:()=>na,StreamEvent:()=>xt,StreamType:()=>pu,SubscribeMediaType:()=>BT,TIMER_TYPE:()=>mM,TRACK_ACTION:()=>ET,TRACK_KIND:()=>du,TrackEvent:()=>Fi,UserRole:()=>ws,UserRoleNumber:()=>zi,VideoCodec:()=>Vs,VideoCodecPipelineType:()=>FQ,VideoContentHint:()=>fM,VideoDecoderDowngradeState:()=>Lh,VideoPlayerMode:()=>hM,VideoType:()=>hu});var ee,PA,ve,dt,fe,Be,tA,Le,he,Zt,pt,ni=(A=>(A[A.WEBRTC=30]="WEBRTC",A[A.WASM=37]="WASM",A))(ni||{}),Li=((pt=Li||{}).TRACK_ADDED="track-added",pt.TRACK_UPDATED="track-updated",pt.TRACK_SUBSCRIBED="track-subscribed",pt.STREAM_ADDED="stream-added",pt.STREAM_REMOVED="stream-removed",pt.STREAM_UPDATED="stream-updated",pt.STREAM_PUBLISHED="stream-published",pt.STREAM_SUBSCRIBED="stream-subscribed",pt.STREAM_UNSUBSCRIBED="stream-unsubscribed",pt.STATE_CHANGED="state-changed",pt.ERROR="error",pt.CONNECTION_STATE_CHANGED="connection-state-changed",pt.FIREWALL_RESTRICTION="firewall-restriction",pt.SEI_MESSAGE="sei-message",pt.CLOSED="closed",pt),it=(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))(it||{}),de=((Zt=de||{}).STREAM_ADDED="stream-added",Zt.STREAM_REMOVED="stream-removed",Zt.STREAM_UPDATED="stream-updated",Zt.STREAM_SUBSCRIBED="stream-subscribed",Zt.CONNECTION_STATE_CHANGED="connection-state-changed",Zt.PEER_JOIN="peer-join",Zt.PEER_LEAVE="peer-leave",Zt.MUTE_AUDIO="mute-audio",Zt.MUTE_VIDEO="mute-video",Zt.UNMUTE_AUDIO="unmute-audio",Zt.UNMUTE_VIDEO="unmute-video",Zt.CLIENT_BANNED="client-banned",Zt.NETWORK_QUALITY="network-quality",Zt.AUDIO_VOLUME="audio-volume",Zt.SEI_MESSAGE="sei-message",Zt.ERROR="error",Zt),xt=((he=xt||{}).PLAYER_STATE_CHANGED="player-state-changed",he.SCREEN_SHARING_STOPPED="screen-sharing-stopped",he.CONNECTION_STATE_CHANGED="connection-state-changed",he.DEVICE_AUTO_RECOVERED="device-auto-recovered",he.ERROR="error",he),Ri=((Le=Ri||{}).DEVICE_AUTO_RECOVERED="1",Le.DEVICE_RECOVER_FAILED="5",Le.DEVICE_CHANGED="2",Le.ERROR="3",Le.PUBLISH_STATE_CHANGED="4",Le.ENCODE_FAILED="6",Le.TRACK_ENDED="7",Le.RENDER="render",Le),ui=(A=>(A.PAUSED="PAUSED",A.PLAYING="PLAYING",A.STOPPED="STOPPED",A))(ui||{}),ci=((tA=ci||{}).PEER_JOIN="peer-join",tA.PEER_LEAVE="peer-leave",tA.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",tA.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",tA.BANNED="banned",tA.NETWORK_QUALITY="network-quality",tA.AUDIO_VOLUME="audio-volume",tA.SEI_MESSAGE="sei-message",tA.ERROR="error",tA.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",tA.REMOTE_PUBLISHED="remote-published",tA.REMOTE_UNPUBLISHED="remote-unpublished",tA.FIREWALL_RESTRICTION="firewall-restriction",tA.HEARTBEAT_REPORT="heartbeat-report",tA.CUSTOM_MESSAGE="custom-message",tA.LAYER_DATA="layerData",tA.FIRST_VIDEO_FRAME="first-video-frame",tA.FIRST_FRAME_RENDER="first-frame-render",tA.DUMP="dump",tA.AUDIO_FRAME="audio-frame",tA.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",tA.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",tA.NTP_TIME_UPDATED="ntp-time-updated",tA.DATA_CHANNEL_MESSAGE="data-channel-message",tA.ASR_ROBOT_PEER_JOIN="asr-robot-peer-join",tA.ASR_ROBOT_PEER_LEAVE="asr-robot-peer-leave",tA),Fi=((Be=Fi||{}).PLAYER_STATE_CHANGED="player-state-changed",Be.MUTE="mute",Be.UNMUTE="unmute",Be.ERROR="error",Be.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",Be.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",Be.FIRST_VIDEO_FRAME="first-video-frame",Be.FIRST_FRAME_RENDER="first-frame-render",Be.VIDEO_SIZE_CHANGED="video-size-changed",Be),tr=(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))(tr||{}),br=((fe=br||{})[fe.VIDEO=1]="VIDEO",fe[fe.SMALL=2]="SMALL",fe[fe.AUX=4]="AUX",fe[fe.AUDIO=8]="AUDIO",fe[fe.VIDEO_MUTE=16]="VIDEO_MUTE",fe[fe.AUX_MUTE=32]="AUX_MUTE",fe[fe.AUDIO_MUTE=64]="AUDIO_MUTE",fe),na=(A=>(A[A.RTC=1]="RTC",A[A.LIVE=2]="LIVE",A))(na||{}),zi=(A=>(A[A.ANCHOR=20]="ANCHOR",A[A.AUDIENCE=21]="AUDIENCE",A))(zi||{}),ws=(A=>(A.ANCHOR="anchor",A.AUDIENCE="audience",A))(ws||{}),bh=(A=>(A.CONNECTED="CONNECTED",A.DISCONNECTED="DISCONNECTED",A.CONNECTING="CONNECTING",A.RECONNECTED="RECONNECTED",A.RECONNECTING="RECONNECTING",A))(bh||{}),sm=((dt=sm||{}).INITIALIZED="INITIALIZED",dt.STARTING="STARTING",dt.STARTED="STARTED",dt.FAILED="FAILED",dt),Lh=(A=>(A.INITIALIZED="INITIALIZED",A.STARTING="STARTING",A.STARTED="STARTED",A.FAILED="FAILED",A))(Lh||{}),du=(A=>(A.AUDIO="audio",A.VIDEO="video",A.AUXILIARY="auxVideo",A))(du||{}),ET=(A=>(A.ADD="add",A.REMOVE="remove",A))(ET||{}),dM=(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))(dM||{}),lq={1:"audio",2:"auxVideo",4:"video"},VO=((ve=VO||{})[ve.opus=111]="opus",ve),hu=(A=>(A[A.h264=100]="h264",A[A.vp8=101]="vp8",A))(hu||{}),pu=(A=>(A.Big="big",A.Small="small",A))(pu||{}),Fh=(A=>(A.Main="main",A.Aux="auxiliary",A))(Fh||{}),Uh=(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))(Uh||{}),Hs=((PA=Hs||{})[PA.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",PA[PA.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",PA[PA.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",PA[PA.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",PA[PA.MUTE_AUDIO=32772]="MUTE_AUDIO",PA[PA.MUTE_VIDEO=32773]="MUTE_VIDEO",PA[PA.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",PA[PA.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",PA[PA.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",PA[PA.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",PA[PA.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",PA[PA.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",PA[PA.SWITCH_CAMERA=32780]="SWITCH_CAMERA",PA[PA.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",PA[PA.REPLACE_VIDEO=32782]="REPLACE_VIDEO",PA[PA.REPLACE_AUDIO=32783]="REPLACE_AUDIO",PA[PA.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",PA[PA.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",PA[PA.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",PA[PA.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",PA[PA.JOIN=32788]="JOIN",PA[PA.LEAVE=32789]="LEAVE",PA[PA.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",PA[PA.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",PA[PA.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",PA[PA.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",PA[PA.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",PA[PA.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",PA[PA.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",PA[PA.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",PA[PA.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",PA[PA.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",PA[PA.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",PA[PA.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",PA[PA.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",PA[PA.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",PA[PA.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",PA[PA.PUBLISH_AUX=32805]="PUBLISH_AUX",PA[PA.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",PA[PA.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",PA[PA.VIDEO_ENCODER=4004]="VIDEO_ENCODER",PA[PA.VIDEO_DECODER=4005]="VIDEO_DECODER",PA),uc=(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))(uc||{}),fg=(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))(fg||{}),lT=(A=>(A.user="user",A.environment="environment",A))(lT||{}),hM=(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))(hM||{}),pM=(A=>(A[A.ELEMENT=0]="ELEMENT",A[A.CONTEXT=1]="CONTEXT",A))(pM||{}),wa=(A=>(A.BANNED="banned",A.KICK="kick",A.USER_TIME_OUT="user_time_out",A.ROOM_DISBAND="room_disband",A))(wa||{}),CT=(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))(CT||{}),iE=1e8,LQ=(A=>(A[A.NORMAL=0]="NORMAL",A[A.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",A))(LQ||{}),BT=class{constructor(){G(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)}},uT=(A=>(A.String="string",A.Number="number",A.Boolean="boolean",A.Array="array",A.Object="object",A))(uT||{}),Vs=(A=>(A.H264="h264",A.H265="h265",A.VP8="vp8",A.VP9="vp9",A.AV1="av1",A))(Vs||{}),FQ=(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))(FQ||{}),fu=(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))(fu||{}),gm=(A=>(A.WebRTC="webrtc",A.WebCodecs="webcodecs",A.WebAssembly="webassembly",A))(gm||{}),Im=((ee=Im||{})[ee.SUCCESS=0]="SUCCESS",ee[ee.FAILED=1]="FAILED",ee[ee.WEBCODEC_INIT=2]="WEBCODEC_INIT",ee[ee.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",ee[ee.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",ee[ee.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",ee[ee.WASM_INIT=6]="WASM_INIT",ee[ee.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",ee[ee.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",ee[ee.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",ee[ee.TEST=10]="TEST",ee[ee.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",ee),fM=(A=>(A.NONE="",A.DETAIL="detail",A.MOTION="motion",A.TEXT="text",A))(fM||{}),mM=(A=>(A.INTERVAL="interval",A.TIMEOUT="timeout",A.RAF="raf",A.RIC="ric",A.INTERVAL_IN_WORKER="intervalInWorker",A))(mM||{}),UQ=(A=>(A.CANVAS="canvas",A.API="api",A))(UQ||{}),Hr=(A=>(A[A.NONE=0]="NONE",A[A.MICROPHONE=1]="MICROPHONE",A[A.CAMERA=2]="CAMERA",A[A.BOTH=3]="BOTH",A))(Hr||{}),QT=(A=>(A.CAMERA="camera",A.MICROPHONE="microphone",A))(QT||{}),Oh=(A=>(A[A.none=0]="none",A[A.horizontal=1]="horizontal",A[A.vertical=2]="vertical",A))(Oh||{}),Mi={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"},ts={AVOID_REPEATED_CALL:A=>"previous ".concat(A.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(A){let{key:e,rule:o,fnName:n,value:a}=A;return"'".concat(e||o.name,"' is a required param when calling ").concat(n,"(), received: ").concat(a,".")},INVALID_PARAMETER_TYPE(A){let{key:e,rule:o,fnName:n,value:a}=A,I="".concat(e||o.name),c="";return c=Array.isArray(o.type)?o.type.join("|"):o.type,"'".concat(I,"' must be type of ").concat(c," when calling ").concat(n,"(), received type: ").concat(ya(a),".")},INVALID_PARAMETER_EMPTY(A){let{key:e,rule:o,fnName:n,value:a}=A;return"'".concat(e||o.name,"' cannot be '").concat(a,"' when calling ").concat(n,"().")},INVALID_PARAMETER_INSTANCE(A){let{key:e,rule:o,fnName:n,value:a}=A,I="".concat(e||o.name),c="".concat(o.instanceOf.name||o.instanceOf);return"'".concat(I,"' must be instanceof ").concat(c," when calling ").concat(n,"(), received type: ").concat(ya(a),".")},INVALID_PARAMETER_RANGE(A){let{key:e,rule:o,fnName:n,value:a}=A;return"'".concat(e||o.name,"' must be one of ").concat(o.values.join("|")," when calling ").concat(n,"(), received: ").concat(a,".")},INVALID_PARAMETER_MIN(A){let{key:e,rule:o,fnName:n,value:a}=A;return"the min value of ".concat(e||o.name," is ").concat(o.min,", received: ").concat(a,".")},INVALID_PARAMETER_MAX(A){let{key:e,rule:o,fnName:n,value:a}=A;return"the max value of ".concat(e||o.name," is ").concat(o.max,", received: ").concat(a,".")},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 e="".concat(A.type," failed");return A.message&&(e="".concat(e,": ").concat(A.message,".")),e},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:e,code:o}=A;return"Failed to join room - ".concat(e," 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:e,userId:o,streamType:n}=A;return"failed to subscribe ".concat(o," ").concat(n," stream, reason: ").concat(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: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:e,rule:o,fnName:n,value:a}=A;return"'".concat(e||o.name,"' cannot be less than 0 when calling ").concat(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: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:e,fnName:o}=A;return"'".concat(e,"' is not found in the document object when calling ").concat(o,"().")},INVALID_ELEMENT_ID_TYPE:A=>{let{key:e,fnName:o,type:n}=A;return"the element corresponding to '".concat(e,"' must be instanceof HTMLElement when calling ").concat(o,"(), received: ").concat(n,".")},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:e,event:o}=A;return"an error was caught in ".concat(e,".on('").concat(o,"', handler), please check your code in 'handler'.")},API_NOT_EXIST(A){let{name:e}=A;return"experimental api ".concat(e," 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:e}=A;return"failed to call ".concat(e,"() 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:e,name:o,timesInSecond:n,maxSizeInSecond:a}=A;return"api ".concat(o," call ").concat(e?"size":"times"," is over ").concat(e?"".concat(a," bytes"):n," in a second.")},CONNECTION_ABORTED:A=>"connection aborted due to: ".concat(A),API_CALL_ABORTED(A){let e;return e=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),e},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,".")},qO=(A,e)=>e?"".concat($C,"/").concat(A,"/").concat(e):"".concat($C,"/").concat(A,"/index.html"),dT=()=>{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(Sf);if(A){A=JSON.parse(A);let e=document.createElement("script");e.type="text/javascript",e.text=A.message,document.body.appendChild(e);let o=window.TRTC_ERROR_INFO,n=window.TRTC_ERROR_LINK;return document.body.removeChild(e),{TRTC_ERROR_INFO:o,TRTC_ERROR_LINK:n}}return{}};function Wi(A){let{key:e,data:o,link:n,addDocLink:a=!0}=A,I="",c="",u="";$n(ts[e])?I=ts[e](o):Sr(ts[e])&&(I=ts[e]);let{TRTC_ERROR_INFO:d,TRTC_ERROR_LINK:R}=dT();n?u="".concat(n.className,".html#").concat(n.fnName):R&&R[e]&&($n(R[e])?u=R[e](o):Sr(R[e])&&(u=R[e]));let k=I;return rl()&&(d&&d[e]&&($n(d[e])?c=d[e](o):Sr(d[e])&&(c=d[e])),c&&(k=a?"".concat(c,` -请查看文档: `).concat(qO("zh-cn",u),` +`}}),BN=ZC(A=>{var e=zU(),o=ZU();A.write=o,A.parse=e.parse,A.parseParams=e.parseParams,A.parseFmtpConfig=e.parseFmtpConfig,A.parsePayloads=e.parsePayloads,A.parseRemoteCandidates=e.parseRemoteCandidates,A.parseImageAttributes=e.parseImageAttributes,A.parseSimulcastStreamList=e.parseSimulcastStreamList}),XV=es(hg()),ru=((Ii=ru||{})[Ii.INVALID_PARAMETER=4096]="INVALID_PARAMETER",Ii[Ii.INVALID_OPERATION=4097]="INVALID_OPERATION",Ii[Ii.NOT_SUPPORTED=4098]="NOT_SUPPORTED",Ii[Ii.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",Ii[Ii.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",Ii[Ii.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",Ii[Ii.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",Ii[Ii.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",Ii[Ii.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",Ii[Ii.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",Ii[Ii.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",Ii[Ii.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",Ii[Ii.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",Ii[Ii.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",Ii[Ii.CLIENT_BANNED=16448]="CLIENT_BANNED",Ii[Ii.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",Ii[Ii.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",Ii[Ii.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",Ii[Ii.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",Ii[Ii.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",Ii[Ii.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",Ii[Ii.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",Ii[Ii.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",Ii[Ii.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",Ii[Ii.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",Ii[Ii.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",Ii[Ii.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",Ii[Ii.API_CALL_ABORTED=16461]="API_CALL_ABORTED",Ii[Ii.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",Ii[Ii.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",Ii[Ii.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",Ii[Ii.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",Ii[Ii.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",Ii[Ii.UNKNOWN=65535]="UNKNOWN",Ii),Ge=ru,XU=class extends Error{constructor(A){let{name:e="RtcError",message:o,code:n=Ge.UNKNOWN,extraCode:a=0,constraint:I}=A,c="<".concat(function(d){for(let R in Ge)if(Ge[R]===d)return R;return"UNKNOWN"}(n)," 0x").concat(n.toString(16),">"),u="".concat(o).concat(I?" constraint: ".concat(I):"").concat(o!=null&&o.includes(c)?"":" ".concat(c));super(u),G(this,"code"),G(this,"extraCode"),G(this,"message"),G(this,"originMessage"),G(this,"name"),G(this,"constraint"),this.code=n,this.extraCode=a,this.name=e,this.message=u,this.constraint=I,this.originMessage=o}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},Ct=XU,uN=0,$U=!0,nu=function(A){uN=A;let e=new Date;e.setTime(e.getTime()+A),nA[$U?"info":"debug"]("baseTime from server: ".concat(e," offset: ").concat(A)),$U=!1},AO=function(){return uN},Eh=function(){return Date.now()+uN},eO=function(){let A=new Date;return A.setTime(Eh()),A.toLocaleString()},QN=function(A){let e=String(A.getMilliseconds());return"padStart"in String.prototype&&(e=e.toString().padStart(3,"0")),"".concat(A.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(e)},il={};XC(il,{REPORT_TYPE:()=>oM,buildSSOPackage:()=>lu,bytes2ms:()=>ZR,calculateScaleResolutionDownNumber:()=>iM,concatArrayBuffers:()=>zf,convertObjectNumberToInt:()=>tM,copyProperties:()=>RO,deepClone:()=>Mh,deepCloneBasic:()=>wh,deepMerge:()=>tB,delay:()=>AC,fibonacci:()=>Dh,formatedTime:()=>kO,getConstructorName:()=>Vf,getContainerFromElement:()=>xN,getEnv:()=>mO,getFirst16Bits:()=>bO,getInternalVersion:()=>TO,getLast16Bits:()=>rM,getLoggerUrl:()=>fh,getMediaStreamTrackInfo:()=>VN,getMuteStateFromFlag:()=>RQ,getNetworkType:()=>WR,getNumNetworkType:()=>mh,getReconnectionTimeout:()=>yQ,getStringByteLength:()=>eM,getTestSignalDomain:()=>DO,getTurnServer:()=>GO,getUint32Version:()=>PN,getValueType:()=>ya,getViewListFromView:()=>jf,glog:()=>wO,ipv4ToUint32:()=>Kf,isArray:()=>Aa,isAudioWorkletSupported:()=>SO,isBoolean:()=>rn,isConstructor:()=>Rh,isEmpty:()=>$R,isFunction:()=>$n,isLangChinese:()=>nl,isMediaStreamTrack:()=>UN,isNumber:()=>hr,isObject:()=>Xc,isOverseaSdkAppId:()=>rl,isPlainObject:()=>Cc,isPortrait:()=>YN,isPromise:()=>yh,isRemoteTrack:()=>ON,isRotate90Or270:()=>Eu,isSetSinkIdSupported:()=>vO,isString:()=>Sr,isUndefined:()=>Ee,isVideoMixerOutputTrack:()=>MQ,loadImage:()=>Wf,loadVideo:()=>_O,ms2bytes:()=>MO,ms2samples:()=>XR,normalizeUrl:()=>HN,performanceNow:()=>ki,promiseAny:()=>qf,samples2ms:()=>FN,setNetworkTypeFromWebRTC:()=>zR,stringify:()=>al,stringifyIncludeValue:()=>AM,throttlePromise:()=>JN});var tO={};XC(tO,{ASR_ROBOT_FROM_TYPE:()=>JR,AUDIO_MUTE_BIT:()=>Bh,AUDIO_STAT_BIT:()=>Lf,AUX_STAT_BIT:()=>bf,AUX_STREAM_MSID:()=>gO,BACKEND_ENV:()=>lh,BASE_DOC_URL:()=>$C,BASE_HOST:()=>oO,CAPABILITIES_KEYS:()=>vN,CLASS_NAME:()=>aq,CLOUD_CONSOLE_URL:()=>eq,CROSS_ROOM_BIT:()=>DN,DATA_CHANNEL_FROM_TYPE_BIT:()=>gu,DATA_FREEZE_TIMING:()=>wN,DOC_BILLING_CN:()=>kR,DOC_BILLING_OVERSEA:()=>pN,DOC_URL:()=>tq,DTLS_STATE_UNKNOWN:()=>AB,ENV_NAME:()=>au,EXCHANGE_SDP_TIMEOUT:()=>CO,IS_WORKER:()=>TR,IS_WORKLET:()=>GR,KIBANA_EVENT:()=>oa,LOCAL_STREAM_PUBLISH_STATE:()=>BO,LOGGER_CMD_TYPE:()=>Xg,LOGGER_DOMAIN:()=>Zg,LOGGER_DOMAIN_OVERSEA:()=>pQ,LOG_LEVEL:()=>su,LOG_LEVEL_NAME:()=>gq,MAIN_STREAM_MSID:()=>RI,MAX_RTT:()=>PR,MICROPHONE_COMMUNICATIONS:()=>sq,MICROPHONE_DEFAULT:()=>Of,MUTE_ALL_BIT:()=>sO,NAME:()=>fA,NETWORK_TYPE:()=>_R,NOT_SUPPORTED_H264:()=>xR,PAUSED_RETRY_COUNT:()=>DQ,PEERCONNECTION_CONNECTING_TIMEOUT:()=>SN,PEER_CONNECTION_STATE:()=>hi,PEER_LEAVE_REASON:()=>dO,RECOVER_CAPTURE_INTERVAL:()=>Yf,REMOTE_STREAM_TYPE_AUX:()=>yN,REMOTE_STREAM_TYPE_MAIN:()=>LR,RENDER_FREEZE_TIMING:()=>uO,SCHEDULE_DOMAIN:()=>cu,SCHEDULE_TIMEOUT:()=>QO,SDP_SEMANTICS_PLAN_B:()=>OR,SDP_SEMANTICS_UNIFIED_PLAN:()=>Uf,SECOND_HOST:()=>rO,SIGNAL_PING_PONG_INTERVAL:()=>lc,SIGNAL_PING_TIMEOUT:()=>nO,SIGNAL_RECONNECTION_COUNT:()=>iq,SMALL_STAT_BIT:()=>mN,SPEAKER_DEFAULT:()=>YR,STORAGE_EXPIRES_TIME:()=>bR,STREAM_TYPE_BIG:()=>rq,STREAM_TYPE_SMALL:()=>nq,SUBSCRIBE_SMALL_RETRY_COUNT:()=>xf,SYNC_USER_LIST_INTERVAL:()=>oq,Scene:()=>Ch,THIRD_HOST:()=>Aq,TRANSPORT_DIRECTION:()=>_r,TRTC_ERROR_ASSISTANCE:()=>Gf,TRTC_QUALITY_BAD:()=>uh,TRTC_QUALITY_DISCONNECTED:()=>EO,TRTC_QUALITY_EXCELLENT:()=>FR,TRTC_QUALITY_GOOD:()=>Iu,TRTC_QUALITY_POOR:()=>IO,TRTC_QUALITY_UNKNOWN:()=>RN,TRTC_QUALITY_VERY_BAD:()=>cO,UPDATE_OFFER_TIMEOUT:()=>lO,VIDEO_MUTE_BIT:()=>Ff,VIDEO_STAT_BIT:()=>_f,WEBGL_ATTRIBUTES:()=>NN,audioProfileMap:()=>fQ,defaultBigVideoProfile:()=>kf,defaultSmallVideoProfile:()=>aO,getRetryCount:()=>Qh,getScriptDir:()=>$V,innerVersion:()=>NR,loggerProxy:()=>hN,screenProfileMap:()=>fN,setLoggerProxy:()=>Tf,setRetryCount:()=>UR,setVersion:()=>iO,version:()=>ol,videoProfileMap:()=>$l});var NR="4.15.00.1600",ol="5.0.0";function iO(A){ol=A;let[e,o,n]=A.split(".").map(a=>parseInt(a,10));NR="".concat(e,".").concat(Math.min(15,o),".").concat(Math.min(15,n),".").concat(o.toString().padStart(2,"0")).concat(n.toString().padStart(2,"0"))}var dN,Ec,TR=typeof importScripts<"u",GR=typeof registerProcessor<"u",$V=()=>{let A=TR?self.location.href:document.currentScript.src;return A.substring(0,A.lastIndexOf("/")+1)},hN="",Tf=A=>hN=A,oO="web.sdk.qcloud.com",rO="web.sdk.tencent.cn",Aq="web.sdk.cloud.tencent.cn",eq="https://console.cloud.tencent.com/trtc",$C="https://".concat(oO,"/trtc/webrtc/doc"),tq="".concat($C,"/zh-cn/"),kR="https://cloud.tencent.com/document/product/647/85386",pN="https://trtc.io/document/56025",Zg="https://yun.tim.qq.com",pQ="https://apisgp.my-imcloud.com",Gf="trtc_error_assistance",Xg={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},au={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},su=((Ec=su||{})[Ec.TRACE=0]="TRACE",Ec[Ec.DEBUG=1]="DEBUG",Ec[Ec.INFO=2]="INFO",Ec[Ec.WARN=3]="WARN",Ec[Ec.ERROR=4]="ERROR",Ec[Ec.NONE=5]="NONE",Ec),nO=18e3,lc=2e3,_R={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},bR=6048e5,fQ={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}},$l={"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}},kf=$l["480p_2"],aO=$l["120p_2"],fN={"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}},fA={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"},_r={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},lh={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Ch=((dN=Ch||{}).LIVE="live",dN.RTC="rtc",dN),_f=1,mN=2,bf=4,Lf=8,Bh=64,Ff=16,sO=112,DN=128,gu=256,RI="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",gO="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",LR=fA.MAIN,yN=fA.AUXILIARY,RN=0,FR=1,Iu=2,IO=3,uh=4,cO=5,EO=6,AB="unknown",hi={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},MN=1/0;function UR(A){MN=A}function Qh(){return MN}var mQ,iq=30,oa={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"},oq=1e4,lO=1e4,CO=1e4,Uf="unified-plan",OR="plan-b",xR=1028,BO=((mQ=BO||{})[mQ.UNPUBLISH=-1]="UNPUBLISH",mQ[mQ.PUBLISHING=0]="PUBLISHING",mQ[mQ.PUBLISHED=1]="PUBLISHED",mQ),wN=500,uO=1e3,rq=fA.BIG,nq=fA.SMALL,SN=1e4,cu={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"},QO=2e3,aq={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},DQ=5,Of="default",YR=Of,sq="communications",gq=Object.keys(su),dO=["normal leave","timeout leave","kick","role change"],xf=10,Yf=2e3,vN=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],PR=1e4,JR=14,NN={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},hO=function(A,e,o,n){return new(o||(o=Promise))(function(a,I){function c(R){try{d(n.next(R))}catch(k){I(k)}}function u(R){try{d(n.throw(R))}catch(k){I(k)}}function d(R){R.done?a(R.value):function(k){return k instanceof o?k:new o(function(_){_(k)})}(R.value).then(c,u)}d((n=n.apply(A,[])).next())})},HR=Symbol(32),VR=Symbol(16),TN=Symbol(8),dh=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,e){return e&&this.consume(),this.need=A,this.flush()}read(A){return hO(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((e,o)=>{var n;this.reject=o,this.resolve=a=>{delete this.lastReadPromise,delete this.resolve,delete this.need,e(a)},this.demand(A,!0)||(n=this.pull)===null||n===void 0||n.call(this,A)})})}readU32(){return this.read(HR)}readU16(){return this.read(VR)}readU8(){return this.read(TN)}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,e=this.buffer.subarray(this.consumed),o=0,n=a=>e.length<(o=a);if(typeof this.need=="number"){if(n(this.need))return;A=e.subarray(0,o)}else if(this.need===HR){if(n(4))return;A=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===VR){if(n(2))return;A=e[0]<<8|e[1]}else if(this.need===TN){if(n(1))return;A=e[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(n(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(e.subarray(0,o)),A=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(n(this.need.byteLength))return;new Uint8Array(this.need).set(e.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(e=>this.pull=e);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 e=this.buffer.length,o=e+A;if(o<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,o);else{let n=new Uint8Array(o);n.set(this.buffer),this.buffer=n}return this.buffer.subarray(e,o)}return this.buffer=new Uint8Array(A),this.buffer}};dh.U32=HR,dh.U16=VR,dh.U8=TN;var Pf=128;function qR(A){let e=new dh;for(;A>=128;)e.malloc(1)[0]=255&A|Pf,A>>>=7;return e.malloc(1)[0]=255&A,e.buffer||new Uint8Array(0)}function KR(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=new dh,n=e<<3;switch(typeof A){case"boolean":let a=o.malloc(2);a[0]=n,a[1]=A?1:0;break;case"number":o.malloc(1)[0]=n,o.write(qR(A));break;case"string":o.malloc(1)[0]=2|n;let I=new TextEncoder().encode(A);o.write(qR(I.length));let c=o.malloc(I.length);for(let d=0;d>>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 e=0;e>>24&255,A[o+1]=e>>>16&255,A[o+2]=e>>>8&255,A[o+3]=255&e}function MI(A,e){return A[e]<<24|A[e+1]<<16|A[e+2]<<8|A[e+3]}function fO(A,e){return A[e]}function ph(A,e,o){return new TextDecoder().decode(function(n,a,I){return n.slice(a,a+I)}(A,e,o))}var Jf=0,GN=2654435769,jR=16,eB=2,Hf=7;function kN(A,e){let o=new pO,n=function(XA,Ft,ie){let ke=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:ie,appId:XA,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:ke,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:Ft}}(e,A,Jf);Jf=Jf+1&2147483647,o.writeInt32(0),o.writeInt32(n.version),o.writeByte(n.encryption);let a=new TextEncoder().encode(n.d2);o.writeInt32(a.length+4),a&&o.writeBytes(a),o.writeByte(n.uinType);let I=new TextEncoder().encode(n.uin);o.writeInt32(I.length+4),I.length&&o.writeBytes(I);let c=new pO;c.writeInt32(0),c.writeInt32(n.reqHead.seqNumber),c.writeInt32(n.reqHead.appId),c.writeByte(n.reqHead.appId>>>24&255),c.writeByte(n.reqHead.appId>>>16&255),c.writeByte(n.reqHead.appId>>>8&255),c.writeByte(255&n.reqHead.appId);for(let XA=4;XA<16;XA++)c.writeByte(0);let u=new TextEncoder().encode(n.reqHead.a2);c.writeInt32(u.length+4),u.length&&c.writeBytes(u);let d=new TextEncoder().encode(n.reqHead.serviceCmd);c.writeInt32(d.length+4),d.length&&c.writeBytes(d);let R=new TextEncoder().encode(n.reqHead.cookie);c.writeInt32(R.length+4),R.length&&c.writeBytes(R);let k=new TextEncoder().encode(n.reqHead.imei);c.writeInt32(k.length+4),k.length&&c.writeBytes(k);let _=new TextEncoder().encode(n.reqHead.ksid);c.writeInt32(_.length+4),_.length&&c.writeBytes(_);let Z=new TextEncoder().encode(n.reqHead.clientVersionInfo);c.writeInt16(Z.length+2),Z.length&&c.writeBytes(Z);let iA=c.length;c.data[0]=iA>>>24&255,c.data[1]=iA>>>16&255,c.data[2]=iA>>>8&255,c.data[3]=255&iA,Sr(A)&&(A=new TextEncoder().encode(A)),c.writeInt32(A.length+4),A.length&&c.writeBytes(A);let cA=new Uint8Array(c.data),TA=null;n.encryption===1?TA=new TextEncoder().encode(n.uin):n.encryption===2&&(TA=new Uint8Array(16)),TA&&(cA=function(XA,Ft){let ie=XA.length,ke=(ie+1+eB+Hf)%8;ke&&(ke=8-ke);let Nt=ie+1+eB+Hf+ke,Ut=new Uint8Array(Nt),Ui=0,Oi=new Uint8Array(8),or=new Uint8Array(8),xi=new Uint8Array(8),yo=0;Oi[0]=248&Math.floor(256*Math.random())|ke,yo=1;for(let Vn=0;Vn>>24&255,JA[1]=Ie>>>16&255,JA[2]=Ie>>>8&255,JA[3]=255&Ie,JA}function _N(A,e,o,n,a,I){for(let c=0;c<8;c++)A[c]^=n[c];(function(c,u,d,R){let k=MI(c,0),_=MI(c,4),Z=[];for(let cA=0;cA<4;cA++)Z[cA]=MI(u,4*cA);let iA=0;for(let cA=0;cA>>=0,k+=(_<<4)+Z[0]^_+iA^(_>>>5)+Z[1],k>>>=0,_+=(k<<4)+Z[2]^k+iA^(k>>>5)+Z[3],_>>>=0;hh(d,k,R),hh(d,_,R+4)})(A,e,a,I);for(let c=0;c<8;c++)a[I+c]^=o[c];for(let c=0;c<8;c++)o[c]=A[c]}var mO=function(){return new URLSearchParams(location.search).get("trtc_env")||""},DO=function(A){return A.includes(".")?A:"".concat(A).concat(".rtc.qq.com")},rl=A=>Number(A)<14e8,fh=function(A,e){let o;o=hN||(rl(A)?pQ:Zg);let n=Math.floor(Math.random()*vf(2,31));return"".concat(o,"/v5/AVQualityReportSvc/C2S?random=").concat(n,"&sdkappid=").concat(A,"&cmdtype=").concat(e)},bN="unknown";function WR(){(function(){var I;yO||(yO=!0,(I=navigator.connection)==null||I.addEventListener("typechange",Iq))})();let{userAgent:A,connection:e}=navigator,o=(A.match(/NetType\/\S+/)||[])[0]||"";o=o.toLowerCase().replace("nettype/",""),o==="3gnet"&&(o="3g");let n=e&&e.type&&e.type.toLowerCase(),a=e&&e.effectiveType&&e.effectiveType.toLowerCase();return a==="slow-2"&&(a="2g"),n?LN(n,a):bN}function Iq(){nA.warn("netType changed",WR())}var yO=!1;function LN(A,e){if(_R[A])return A;switch(A){case"cellular":case"wimax":return e||"unknown";case"ethernet":return"wired";default:return"unknown"}}function zR(A){bN=LN(A)}function mh(){return _R[WR()]}function RO(A,e){for(let o of Reflect.ownKeys(e))if(o!=="constructor"&&o!=="prototype"&&o!=="name"){let n=Object.getOwnPropertyDescriptor(e,o)||"";Object.defineProperty(A,o,n)}return A}function ZR(A){return FN(A/4,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function FN(A){return 1e3*A/(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function MO(A){return 4*XR(A,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function XR(A){return A*(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)/1e3}var wO=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},nl=()=>{let A=navigator.language;return A=A.substring(0,2),A==="zh"},Cc=function(A){if(!A||typeof A!="object"||Object.prototype.toString.call(A)!="[object Object]")return!1;let e=Object.getPrototypeOf(A);if(e===null)return!0;let o=Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor;return typeof o=="function"&&o instanceof o&&Function.prototype.toString.call(o)===Function.prototype.toString.call(Object)};function Dh(A){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;return A<=1?e:Dh(A-1,e,(arguments.length>1&&arguments[1]!==void 0?arguments[1]:1)+e)}function yQ(A){return A>8?3e4:1e3*Dh(A)}function ya(A){return Reflect.apply(Object.prototype.toString,A,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var $n=A=>typeof A=="function",Ee=A=>A===void 0,Sr=A=>typeof A=="string",hr=A=>typeof A=="number",rn=A=>typeof A=="boolean",Xc=A=>ya(A)==="object",Aa=A=>ya(A)==="array",UN=A=>ya(A)==="MediaStreamTrack".toLowerCase(),ON=A=>A.isRemote,yh=A=>ya(A)==="promise",Rh=A=>$n(A)&&A.prototype.constructor===A,Vf=A=>Rh(A)?A.prototype.constructor.name:"",SO=typeof AudioWorkletNode<"u",vO=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype;function qf(A){return new Promise((e,o)=>{let n=[];A.forEach(a=>{a.then(e).catch(I=>{n.push(I),n.length===A.length&&o(n)})})})}function ki(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var NO=A=>+A<10?"0".concat(A):A,TO=A=>{let e=A.match(/^\d+\.\d+\.\d+/)[0];if(!e)return A;let o=e.split("."),n=NO(o[1])+NO(o[2]);return o[1]-15>0&&(o[1]="15"),o[2]-15>0&&(o[2]="15"),"".concat(o.join("."),".").concat(n)},cq=Object.prototype.hasOwnProperty;function $R(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(Cc(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 e in A)if(cq.call(A,e))return!1;return!0}return!1}function RQ(A,e){return{userId:e,hasAudio:!!(A&Lf),hasVideo:!!(A&_f),hasAuxiliary:!!(A&bf),hasSmall:!!(A&mN),audioMuted:!!(A&Bh),videoMuted:!!(A&Ff),audioAvailable:!(!(A&Lf)||A&Bh),videoAvailable:!(!(A&_f)||A&Ff),hasDatachannel:!!(A&gu)}}function GO(A){let e={urls:A.url.startsWith("turn:")||A.url.startsWith("turns:")?A.url:"turn:".concat(A.url)};return!Ee(A.username)&&!Ee(A.credential)&&(e.username=A.username,e.credential=A.credential,e.credentialType="password",Ee(A.credentialType)||(e.credentialType=A.credentialType)),e}function Kf(A){let e=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(!Sr(A))return 0;let o=A.split(".");return e?(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 tB=function(A,e,o,n){if(!Xc(A)||!Xc(e))return 0;let a,I=0,c=Object.keys(e);for(let u=0,d=c.length;u{e[n]=Mh(o)}),e}if(Xc(A)){let e={};return Object.keys(A).forEach(o=>{e[o]=Mh(A[o])}),e}return A}var jf=A=>{let e=[];if(Aa(A))e=[...A];else if(Sr(A)){let o=document.getElementById(A);o&&e.push(o)}else A&&e.push(A);return e},xN=A=>Sr(A)?document.getElementById(A):A,kO=()=>(A=>{let e=d=>d<10?"0".concat(d):"".concat(d),o=A.getFullYear(),n=A.getMonth()+1,a=A.getDate(),I=e(A.getHours()),c=e(A.getMinutes()),u=e(A.getSeconds());return"".concat(o,"/").concat(n,"/").concat(a," ").concat(I,":").concat(c,":").concat(u)})(new Date);function al(A,e){let{keysToInclude:o,keysToExclude:n}=e;try{if(Aa(A))return"[".concat(A.map(u=>al(u,{keysToInclude:o,keysToExclude:n})).join(","),"]");if(!Cc(A)||!Aa(o)&&!Aa(n))return JSON.stringify(A);let a={},I=new Set(o),c=new Set(n);return Object.keys(A).forEach(u=>{(c.size===0&&I.has(u)||I.size===0&&!c.has(u))&&(a[u]=Cc(A[u])||Aa(A[u])?JSON.parse(al(A[u],{keysToExclude:n,keysToInclude:o})):A[u])}),JSON.stringify(a)}catch{return"{}"}}function AM(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1],o=[];return Object.keys(A).forEach(n=>{e===A[n]&&o.push(n)}),al(A,{keysToInclude:o})}function eM(A){return A.replace(/[\u4e00-\u9fa5]/g,"aa").length}var YN=()=>{var A,e,o,n;return(A=window.screen)!=null&&A.orientation?!((n=(o=(e=window.screen)==null?void 0:e.orientation)==null?void 0:o.type)==null||!n.includes("portrait")):window.orientation===0||window.orientation===180},Wf=A=>DA(null,null,function*(){return new Promise((e,o)=>{let n;if(Sr(A))n=new Image,n.crossOrigin="anonymous",n.src=A;else if(n=A,n.complete)return void e(n);n.onload=()=>e(n),n.onerror=()=>{o(new Ct({code:Ge.INVALID_PARAMETER,message:"load image failed, url: ".concat(A)}))}})}),PN=A=>{let e=A.split(".");return+e[0]<<24|+e[1]<<16|+e[2]<<8|+e[3]},tM=A=>(Object.keys(A).forEach(e=>{hr(A[e])&&(e.startsWith("uint")||e.startsWith("int"))?A[e]=Math.floor(A[e]):(Cc(A[e])||Aa(A[e]))&&tM(A[e])}),A);function AC(A,e){return new Promise(o=>{let n=setTimeout(o,A);e&&e(n)})}function JN(A,e){let o=null;return function(){for(var n=arguments.length,a=new Array(n),I=0;Io=null),o)}}function HN(A){return A.replace(/(^|[^:])\/{2,}/g,"$1/")}function VN(A){var e;try{let{width:o,height:n,frameRate:a,sampleRate:I,sampleSize:c,channelCount:u}=(e=A.getSettings)==null?void 0:e.call(A),d=A.kind===fA.AUDIO?"".concat(I,"x").concat(c,"@").concat(u):"".concat(o,"x").concat(n,"@").concat(a),R=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(d).concat(R)}catch{return""}}function iM(A,e){return A.width*A.height===e.width*e.height?1:YN()&&e.width>e.height&&A.height>e.width?Math.max(A.width/e.height,A.height/e.width,1):Math.max(A.width/e.width,A.height/e.height,1)}function Eu(A){return A===90||A===270}function _O(A){return DA(this,null,function*(){return new Promise((e,o)=>{let n=document.createElement("video");n.crossOrigin="anonymous",n.src=A,n.muted=!0,n.loop=!0,n.playsInline=!0,n.play().then(()=>e(n)),n.onerror=()=>{o(n.error)}})})}function wh(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:new WeakMap;if(typeof A!="object"||A===null)return A;if(e.has(A))return e.get(A);if(Array.isArray(A)){let o=[];return e.set(A,o),A.forEach((n,a)=>{o[a]=wh(n,e)}),o}if(Object.prototype.toString.call(A)==="[object Object]"){let o={};return e.set(A,o),Reflect.ownKeys(A).forEach(n=>{o[n]=wh(A[n],e)}),o}return A}var oM=(A=>(A[A.END_REPORT=2001]="END_REPORT",A[A.LOG=2002]="LOG",A[A.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",A))(oM||{});function lu(A,e,o,n){try{let a=function(I,c,u,d){let R={data:I,random:Math.floor(2147483648*Math.random()),sdkAppId:u};return Ee(d)||(R=fi(bt({},R),{gzip:+d})),{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:c,bytes_report_data:JSON.stringify(R)}}}(A,e,o,n);return kN(KR(a),o)}catch{return JSON.stringify(A)}}function zf(A,e){let o=new Uint8Array(A.byteLength+e.byteLength);return o.set(new Uint8Array(A),0),o.set(new Uint8Array(e),A.byteLength),o.buffer}function rM(A){return(65535&A)>>>0}function bO(A){return(4294901760&A)>>>0}function MQ(A){return!!(A&&A instanceof CanvasCaptureMediaStreamTrack&&A.canvas.id.includes("trtc_mix"))}function Eq(A){let e=function(o){try{let n={},a=0;n.totalLength=MI(o,a),a+=4,n.version=MI(o,a),a+=4,n.encryption=fO(o,a),a+=1,n.uinType=fO(o,a),a+=1,n.uinLength=MI(o,a),a+=4,n.uin=n.uinLength>4?ph(o,a,n.uinLength-4):"",a+=n.uinLength-4;let I=o.slice(a);return n.encryption===2?(o=function(c,u){let d=0,R=new Uint8Array(8).fill(0),k=new Uint8Array(c.slice(0,8)),_=nM(k,u),Z=7&_[0],iA=c.length-1-Z-eB-Hf,cA=new Uint8Array(iA),TA=0,JA=R,Ie=c.slice(0,8);d=8;let XA=1;XA+=Z;for(let ie=1;ie<=eB;)if(XA<8)XA++,ie++;else if(XA===8){let ke=Sh(c,d,JA,Ie,_,u);JA=ke.ivPreCrypt,Ie=ke.ivCurCrypt,_=ke.debiBuf,d=ke.bufPos,XA=0}let Ft=iA;for(;Ft>0;)if(XA<8)cA[TA++]=_[XA]^JA[XA],XA++,Ft--;else if(XA===8){let ie=Sh(c,d,JA,Ie,_,u);JA=ie.ivPreCrypt,Ie=ie.ivCurCrypt,_=ie.debiBuf,d=ie.bufPos,XA=0}for(let ie=1;ie<=Hf;)if(XA<8)_[XA],JA[XA],XA++,ie++;else if(XA===8){if(d>=c.length)break;let ke=Sh(c,d,JA,Ie,_,u);if(!ke.success)break;JA=ke.ivPreCrypt,Ie=ke.ivCurCrypt,_=ke.debiBuf,d=ke.bufPos,XA=0}return cA}(I,new Uint8Array(16).fill(0)),n.decrypted=!0,a=0):(o=I,a=0),n.rspHeadLength=MI(o,a),a+=4,n.seqNo=MI(o,a),a+=4,n.retCode=MI(o,a),a+=4,n.retStrLength=MI(o,a),a+=4,n.retStr=n.retStrLength?ph(o,a,n.retStrLength-4):"",a+=n.retStrLength-4,n.serviceCmdLength=MI(o,a),a+=4,n.serviceCmd=n.serviceCmdLength?ph(o,a,n.serviceCmdLength-4):"",a+=n.serviceCmdLength-4,n.cookieLength=MI(o,a),a+=4,n.cookie=n.cookieLength?ph(o,a,n.cookieLength-4):"",a+=n.cookieLength-4,n.flag=MI(o,a),a+=4,n.busiBuffLength=MI(o,a),a+=4,n.busiBuff=n.busiBuffLength?ph(o,a,n.busiBuffLength-4):"",a+=n.busiBuffLength-4,n}catch{}}(A);return e?.busiBuff}function nM(A,e){let o=A[0]<<24|A[1]<<16|A[2]<<8|A[3],n=A[4]<<24|A[5]<<16|A[6]<<8|A[7];o>>>=0,n>>>=0;let a=GN*jR>>>0;for(let I=0;I>>5)+e[3],n>>>=0,o-=(n<<4)+e[0]^n+a^(n>>>5)+e[1],o>>>=0,a-=GN,a>>>=0;return new Uint8Array([o>>>24&255,o>>>16&255,o>>>8&255,255&o,n>>>24&255,n>>>16&255,n>>>8&255,255&n])}function Sh(A,e,o,n,a,I){if(e+8>A.length)return{success:!1};let c=new Uint8Array(n),u=A.slice(e,e+8),d=new Uint8Array(8);for(let R=0;R<8;R++)d[R]=a[R]^u[R];return{success:!0,ivPreCrypt:c,ivCurCrypt:u,debiBuf:nM(d,I),bufPos:e+8}}var wQ=typeof TextDecoder<"u"?new TextDecoder:void 0;function Cu(A){let{url:e,body:o,method:n="POST",timeout:a,priority:I}=A;return new Promise((c,u)=>{if("fetch"in window)return fetch(e,{method:n,body:o,priority:I}).then(R=>R.clone().json().then(k=>({data:k}),()=>R.arrayBuffer().then(k=>({data:Eq(new Uint8Array(k))||(wQ?wQ.decode(k):k)})))).then(c,u);let d=new XMLHttpRequest;d.onreadystatechange=()=>{if(d.readyState===4)if(d.status>=200&&d.status<300)try{let R=JSON.parse(d.response);c({data:R})}catch{c({data:d.response})}else u({status:d.status,statusText:d.statusText||"request failed!"})},d.timeout=a||5e3,d.open(n,e,!0),d.send(o)})}function qN(A){return DA(this,null,function*(){let e=ki(),o=JSON.stringify(A);try{if(!CompressionStream||o.length<=2800)return o;let n=new Blob([o],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),a=yield(yield(yield new Response(n)).blob()).arrayBuffer();return nA.debug("compressJSON ".concat(o.length," -> ").concat(a.byteLength," ").concat(ki()-e,"ms")),a}catch{return o}})}var LO=Object.prototype.hasOwnProperty,SQ=A=>typeof A=="function",$c=A=>A===void 0,KN=A=>typeof A=="string",FO=A=>typeof A=="boolean",jN=A=>A.isRemote,UO=function(A){if(!A||typeof A!="object"||Object.prototype.toString.call(A)!="[object Object]")return!1;let e=Object.getPrototypeOf(A);if(e===null)return!0;let o=Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor;return typeof o=="function"&&o instanceof o&&Function.prototype.toString.call(o)===Function.prototype.toString.call(Object)},Zf=function(A){let{retryFunction:e,settings:o,onError:n,onRetrying:a,onRetryFailed:I,onRetrySuccess:c,context:u}=A;return function(){for(var d=arguments.length,R=new Array(d),k=0;kDA(this,null,function*(){let Ft=u||this;try{let ie=yield e.apply(Ft,R);iA>0&&c&&c.call(this,iA),iA=0,Ie(ie)}catch(ie){let ke=()=>{clearTimeout(cA),iA=0,TA=2,XA(ie)},Nt=()=>{TA!==2&&iA<(SQ(_)?_():_)?(iA++,TA=1,SQ(a)&&a.call(this,iA,ke),cA=window.setTimeout(()=>{cA=-1,JA(Ie,XA)},SQ(Z)?Z(iA):Z)):(ke(),SQ(I)&&I.call(this,ie))};SQ(n)?n.call(this,{error:ie,retry:Nt,reject:XA,retryFuncArgs:R,retriedCount:iA}):Nt()}});return new Promise(JA)}},WN=class A6{constructor(e){G(this,"_parentPath"),G(this,"userId"),G(this,"remoteUserId"),G(this,"id"),G(this,"sdkAppId"),G(this,"type"),G(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!FO(e.isLocal)||e.isLocal,this.type=this.isLocal?"":e.type}getFullId(){return this._parentPath&&this.id?"".concat(this._parentPath,"-").concat(this.id):this._parentPath?this._parentPath:this.id}createChild(e){let o=new A6({id:e.id,userId:$c(e.userId)?this.userId:e.userId,sdkAppId:$c(e.sdkAppId)?this.sdkAppId:e.sdkAppId,type:$c(e.type)?this.type:e.type,isLocal:$c(e.isLocal)?this.isLocal:e.isLocal,remoteUserId:$c(e.remoteUserId)?this.remoteUserId:e.remoteUserId});return o.bindParent(this),o}bindParent(e){let o=e.getFullId();this._parentPath!==o&&(this.debug("bind logger parent: ".concat(e.id)),this._parentPath=o,this.userId=e.userId||this.userId,this.sdkAppId=e.sdkAppId||this.sdkAppId)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,o){let n=this.isLocal?this.userId:this.remoteUserId,a=this.getFullId();o.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&this.type!=="main"?"*":"").concat(a).concat(n?"|".concat(n):"","]")),nA.log(e,o,$c(this.userId)||function(I){if(I==null)return!0;if(typeof I=="boolean")return!1;if(typeof I=="number")return I===0;if(typeof I=="string"||typeof I=="function"||Array.isArray(I))return I.length===0;if(I instanceof Error)return I.message==="";if(UO(I))switch(Object.prototype.toString.call(I)){case"[object File]":case"[object Map]":case"[object Set]":return I.size===0;case"[object Object]":for(let c in I)if(LO.call(I,c))return!1;return!0}return!1}(this.userId),this.userId,this.sdkAppId)}info(){for(var e=arguments.length,o=new Array(e),n=0;ngM,CHROME_MAJOR_VERSION:()=>tE,CHROME_VERSION:()=>hM,EDGE_VERSION:()=>ZN,EDG_MAJOR_VERSION:()=>cM,EDG_VERSION:()=>XN,ELECTRON_MAJOR_VERSION:()=>qO,FIREFOX_MAJOR_VERSION:()=>IM,FIREFOX_VERSION:()=>$f,HUAWEI_VERSION:()=>gT,IE_VERSION:()=>Bq,IOS_MAIN_VERSION:()=>sl,IOS_VERSION:()=>$g,IPADQQB_VERSION:()=>im,IS_ANDROID:()=>ra,IS_ANDROID_WEBVIEW:()=>ET,IS_ANY_SAFARI:()=>_Q,IS_CHROME:()=>dM,IS_CHROME_OS:()=>rT,IS_CHROMIUM_128_TO_143:()=>bh,IS_CHROMIUM_BASE:()=>Bc,IS_DESKTOP_IOS_CHROME:()=>WO,IS_EDG:()=>Nh,IS_EDGE:()=>vh,IS_ELECTRON:()=>uq,IS_FIREFOX:()=>Yr,IS_HEADLESS_CHROME:()=>VO,IS_HONOR:()=>sT,IS_HUAWEI:()=>aT,IS_HUAWEIBROWSER:()=>iB,IS_IE:()=>JO,IS_IE8:()=>Cq,IS_IOS:()=>Ea,IS_IOS_13_OR_14:()=>jO,IS_IOS_15_1:()=>KO,IS_IOS_CHROME:()=>gm,IS_IPAD:()=>vQ,IS_IPADQQB:()=>BM,IS_IPAD_PRO:()=>sM,IS_IPHONE:()=>NQ,IS_IPOD:()=>YO,IS_LINUX:()=>kh,IS_LOCAL:()=>bQ,IS_MAC:()=>uu,IS_MACQQB:()=>tm,IS_MIBROWSER:()=>uM,IS_MQQB:()=>em,IS_NATIVE_ANDROID:()=>PO,IS_OLD_ANDROID:()=>lq,IS_OPENHARMONY:()=>_h,IS_OPPOBROWSER:()=>rm,IS_SAFARI:()=>Ma,IS_SAFARI_15_1:()=>Qq,IS_SAMSUNGBROWSER:()=>om,IS_SOGOU:()=>lM,IS_SOGOUM:()=>Am,IS_TBS:()=>eE,IS_UCBROWSER:()=>nT,IS_VIVOBROWSER:()=>nm,IS_WECHAT:()=>Bu,IS_WIN:()=>Gh,IS_WQQB:()=>CM,IS_WX:()=>HO,IS_X5MQQB:()=>GQ,IS_XWEB:()=>TQ,MACQQB_VERSION:()=>oT,MI_VERSION:()=>kQ,MQQB_VERSION:()=>Th,OPENHARMONY_VERSION:()=>QM,OPPO_VERSION:()=>cT,SAFARI_VERSION:()=>Qu,SAMSUNG_VERSION:()=>IT,SOGOUM_VERSION:()=>EM,SOGOU_VERSION:()=>$N,TBS_VERSION:()=>AT,UA_DATA_STRING:()=>eC,USER_AGENT:()=>AE,VIVO_VERSION:()=>am,WECHAT_VERSION:()=>tT,WQQB_VERSION:()=>iT,XWEB_VERSION:()=>eT,browserInfo:()=>hu,getBrowserCoreNumber:()=>pg,getBrowserInfo:()=>CT,getChromeMajorVersion:()=>sm,getDeviceModel:()=>pu,getDeviceModelFromUA:()=>BT,getGPUInfo:()=>LQ,getOSName:()=>Js,getOSNumber:()=>FQ,getOSString:()=>UQ,getOSType:()=>l,getTerminalType:()=>er,getUserAgentData:()=>Im,isAMDGPU:()=>Fh,isAppleSiliconGPU:()=>dq,isLocalStorageEnabled:()=>du,isMobile:()=>pM,isNvidiaGPU:()=>zO,isRealIOS:()=>Xf,isVersionLargerThan:()=>Lh,isVersionSmallerThan:()=>lT});var AE=typeof navigator>"u"?"":navigator.userAgent,Do=A=>new RegExp(A,"i").test(AE),Ra=A=>{if(Do(A)){let e=new RegExp("".concat(A,"\\/([\\d.]+)")),o=AE.match(e);if(o&&o[1])return o[1]}return""},aM=A=>{if(Do(A)){let e=new RegExp("".concat(A,"\\/(\\d+)")),o=AE.match(e);if(o&&o[1])return parseFloat(o[1])}return NaN},zN=/AppleWebKit\/([\d.]+)/i.exec(AE),xO=zN?parseFloat(zN[1]):NaN,vQ=Do("iPad"),sM=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Do("Macintosh"),NQ=Do("iPhone")&&!vQ,YO=Do("iPod"),Ea=NQ||vQ||YO||sM,Xf=()=>{try{return Ea&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch{return Ea}},ra=Do("Android"),gM=function(){if(ra){let A=AE.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(A){let e=A[1]&&parseFloat(A[1]),o=A[2]&&parseFloat(A[2]);if(e&&o)return parseFloat("".concat(A[1],".").concat(A[2]));if(e)return e}}return NaN}(),lq=ra&&Do("webkit")&&gM<2.3,PO=ra&&gM<5&&xO<537,Yr=Do("Firefox"),$f=Ra("Firefox"),IM=aM("Firefox"),vh=Do("Edge"),ZN=Ra("Edge"),Nh=Do("Edg"),XN=Ra("Edg"),cM=aM("Edg"),Am=Do("SogouMobileBrowser"),EM=Ra("SogouMobileBrowser"),lM=Do("MetaSr\\s"),$N=Ra("MetaSr\\s"),eE=Do("TBS"),AT=Ra("TBS"),TQ=Do("XWEB"),eT=Ra("XWEB"),Cq=Do("MSIE\\s8\\.0"),JO=Do("MSIE\\/\\d+"),Bq=function(){if(JO){let A=/MSIE\s(\d+)\.\d/.exec(AE),e=A&&parseFloat(A[1]);return!e&&/Trident\/7.0/i.test(AE)&&/rv:11.0/.test(AE)&&(e=11),e}return NaN}(),Bu=Do("(micromessenger|webbrowser)"),tT=Ra("MicroMessenger"),GQ=!eE&&Do("MQQBrowser")&&Do("COVC"),em=!eE&&Do("MQQBrowser")&&!Do("COVC"),Th=em||GQ?Ra("MQQBrowser"):"",CM=!eE&&Do(" QQBrowser"),iT=Ra(" QQBrowser"),tm=!eE&&Do("QQBrowserLite"),oT=Ra("QQBrowserLite"),BM=!eE&&Do("MQBHD"),im=Ra("MQBHD"),Gh=Do("Windows"),uu=!Ea&&Do("MAC OS X"),kh=!ra&&Do("Linux"),rT=Do("CrOS"),HO=Do("MicroMessenger"),nT=Do("UCBrowser"),uq=Do("Electron"),uM=Do("MiuiBrowser"),kQ=Ra("MiuiBrowser"),iB=Do("HuaweiBrowser"),aT=Do("Huawei")||Do("HUAWEI"),sT=Do("Honor")||Do("HONOR"),gT=Ra("HuaweiBrowser"),om=Do("SamsungBrowser"),IT=Ra("SamsungBrowser"),rm=Do("HeyTapBrowser"),cT=Ra("HeyTapBrowser"),nm=Do("VivoBrowser"),am=Ra("VivoBrowser"),_h=Do("OpenHarmony"),QM=Ra("OpenHarmony"),sm=()=>aM("Chrome"),gm=Do("CriOS"),Bc=Do("Chrome"),dM=!vh&&!lM&&!Am&&!eE&&!TQ&&!Nh&&!CM&&!uM&&!iB&&!om&&!rm&&!nm&&Bc,VO=Do("HeadlessChrome"),tE=sm(),bh=Bc&&tE>=128&&tE<=143,hM=Ra("Chrome"),qO=aM("Electron"),Ma=!Bc&&!em&&!GQ&&!tm&&!BM&&Do("Safari"),_Q=Ma||Ea,Qu=Ra("Version"),ET=/Android.*(wv|.0.0.0)/.test(AE),$g=(()=>{if(sM)return Qu;if(Ea){let A=AE.match(/OS (\d+)_(\d+)/i);if(A&&A[1]){let e=A[1];return A[2]&&(e+=".".concat(A[2])),e}}return""})();function lT(A,e){let o=A.split(".").map(a=>Number(a)),n=e.split(".").map(a=>Number(a));for(let a=0;ac)return!1}return!1}function Lh(A,e){let o=arguments.length>2&&arguments[2]!==void 0&&arguments[2],n=A.split(".").map(I=>Number(I)),a=e.split(".").map(I=>Number(I));for(let I=0;Iu)return!0;if(c{let A=Number($g.split(".")[0]);return A===14||A===13})(),WO=gm&&Qu==="11.1.1",bQ=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),du=(()=>{let A;return()=>{if(A===void 0)try{A=!!window.localStorage}catch{A=!1}return A}})(),hu=CT();function CT(){let A=new Map([[Yr,["Firefox",$f]],[Nh,["Edg",XN]],[dM,["Chrome",hM]],[gm,["ChiOS",Ra("CriOS")]],[Ma&&!gm,["Safari",Qu]],[eE,["TBS",AT]],[TQ,["XWEB",eT]],[Bu&&NQ,["WeChat",tT]],[CM,["QQ(Win)",iT]],[em,["QQ(Mobile)",Th]],[GQ,["QQ(Mobile X5)",Th]],[tm,["QQ(Mac)",oT]],[BM,["QQ(iPad)",im]],[uM,["MI",kQ]],[iB,["HW",gT]],[om,["Samsung",IT]],[rm,["OPPO",cT]],[nm,["VIVO",am]],[vh,["EDGE",ZN]],[Am,["SogouMobile",EM]],[lM,["Sogou",$N]]]),e="unknown",o="unknown";return A.has(!0)&&([e,o]=A.get(!0)),{name:e,version:o}}var Bn=null;function pM(){return Bn&&typeof Bn.mobile=="boolean"?Bn.mobile:ra||Ea||NQ||vQ||_h}var eC="";function Im(){return DA(this,null,function*(){if(Bn)return Bn;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return(Bn=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!eC&&(eC="UAData: ".concat(Bn.platform,"/").concat(Bn.platformVersion),Bn.architecture&&Bn.bitness&&(eC+=" ".concat(Bn.architecture,"/").concat(Bn.bitness)),Bn.mobile&&(eC+=" mobile"),Bn.model&&(eC+=" model: ".concat(Bn.model.replace(/\s+/g,"/"))),Bn.fullVersionList&&(eC+=" ".concat(Bn.fullVersionList.filter(A=>A.brand!=="Not/A)Brand").map(A=>"".concat(A.brand,"/").concat(A.version)).join(",")))),Bn}catch{return null}})}var cm="";function LQ(){try{if(cm)return cm;let A=document.createElement("canvas"),e=A.getContext("webgl")||A.getContext("experimental-webgl");if(!e)return"";let o=e.getExtension("WEBGL_debug_renderer_info");if(o){let n=e.getParameter(o.UNMASKED_VENDOR_WEBGL),a=e.getParameter(o.UNMASKED_RENDERER_WEBGL);return cm="".concat(n," ").concat(a)}return""}catch{return""}}function Fh(){try{let A=LQ();return A.includes("AMD")||A.includes("ATI")}catch{return!1}}function zO(){try{let A=LQ();return A.includes("NVIDIA")||A.includes("GeForce")}catch{return!1}}function dq(){try{return LQ().includes("Apple M")}catch{return!1}}function pu(){return Bn?.model||BT()||""}function BT(){let A=AE.match(/;\s*([^;)]+)\s+Build\//);return A!=null&&A[1]?A[1].trim():null}var ZO=new Map([[ra,"Android"],[Ea,"iOS"],[Gh,"Windows"],[uu,"MacOS"],[kh,"Linux"],[rT,"ChromeOS"]]),Js=function(){return ZO.get(!0)?ZO.get(!0):Bn?Bn.platform:"unknown"};function FQ(){return Gh?1:ra?2:uu?3:Ea?4:kh?5:rT?6:_h?7:0}function pg(){return Bu||TQ?4:Bc?1:Ma?2:Yr?3:0}var UQ=()=>{let A=Js();return Bn!=null&&Bn.platformVersion?A+="/".concat(Bn.platformVersion):Ea?A+="/".concat($g):ra&&(A+="/".concat(gM)),A+="/".concat(hu.name,"/").concat(Ma&&!gm?hu.version:hu.version.split(".")[0]),Bn!=null&&Bn.architecture&&(A+="/".concat(Bn.architecture)),A};function er(){return ra?4:NQ?2:vQ?3:uu?12:Gh?5:kh?13:_h?22:1}function l(){return ra?"Android":NQ?"iPhone":vQ?"iPad":uu?"Mac":Gh?"Windows":kh?"Linux":"unknown"}var p,S=new(es(hg(),1)).default,H=((p=H||{}).ROOM_DESTROY="1",p.JOIN_START="21",p.JOIN_SCHEDULE_SUCCESS="22",p.JOIN_SIGNAL_CONNECTION_START="23",p.JOIN_SIGNAL_CONNECTION_END="24",p.JOIN_SEND_CMD="25",p.JOIN_RECEIVED_CMD_RES="26",p.JOIN_SUCCESS="27",p.JOIN_FAILED="28",p.LEAVE_START="51",p.LEAVE_SEND_CMD="52",p.LEAVE_SUCCESS="53",p.PUBLISH_START="61",p.SEND_FIRST_VIDEO_FRAME="62",p.PUBLISH_FAILED="63",p.SUBSCRIBE_START="81",p.SUBSCRIBE_SUCCESS="82",p.SUBSCRIBE_FAILED="84",p.UNSUBSCRIBE_SUCCESS="83",p.LOCAL_TRACK_CAPTURE_START="101",p.LOCAL_TRACK_CAPTURE_SUCCESS="102",p.LOCAL_TRACK_CAPTURE_FAILED="103",p.LOCAL_TRACK_PUBLISHED="104",p.LOCAL_TRACK_UNPUBLISHED="105",p.LOCAL_TRACK_REPLACED="106",p.SWITCH_DEVICE_SUCCESS="107",p.TRACK_MUTED="108",p.TRACK_UNMUTED="109",p.REMOTE_TRACK_SUBSCRIBED="110",p.REMOTE_TRACK_UNSUBSCRIBED="111",p.LOCAL_TRACK_RECAPTURE="112",p.LOCAL_AUDIO_STARTED="113",p.LOCAL_AUDIO_STOPPED="114",p.REMOTE_AUDIO_STARTED="115",p.REMOTE_AUDIO_STOPPED="116",p.LOCAL_TRACK_STOPPED="117",p.LOCAL_VIDEO_TRACK_PREPROCESSED="118",p.PLAY_TRACK_START="151",p.PLAYER_STATE_CHANGED="152",p.VIDEO_LOADED_DATA="153",p.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",p.AUDIO_CONTEXT_LONG_SUSPENDED="155",p.REMOTE_VIDEO_PLAY_START="156",p.REMOTE_VIDEO_PLAY_FINISH="157",p.SIGNAL_CONNECTION_STATE_CHANGED="201",p.PEER_CONNECTION_STATE_CHANGED="202",p.SINGLE_CONNECTION_STAT="203",p.SPC_RECONNECTED="204",p.HEARTBEAT_REPORT="251",p.RECEIVED_PUBLISHED_USER_LIST="252",p.REMOTE_PUBLISH_STATE_CHANGED="253",p.AUDIO_LEVEL_INTERVAL="260",p.NETWORK_QUALITY="261",p.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",p.QUALITY_LIMITATION_CHANGED="263",p.LOG="264",p.AUDIO_PROCESSOR_DEBUG="265",p.SSO_SWITCH="266",p.SEI_MESSAGE="267",p.USER_PAUSE_IN_PIP="268",p.USER_RESUME_IN_PIP="269",p.ENTER_PICTURE_IN_PICTURE="270",p.LEAVE_PICTURE_IN_PICTURE="271",p.SWITCH_ROOM_START="401",p.SWITCH_ROOM_SUCCESS="407",p.SWITCH_ROOM_FAILED="408",p),K=H,lA=new class{constructor(){G(this,"enable",!1),G(this,"ssoFailCount",0),S.on("22",A=>{let{schedule:e}=A;var o;(o=e?.config)!=null&&o.sso&&S.emit("266",{enable:!0})}),S.on("266",A=>{let{enable:e}=A;this.enable=e})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&S.emit("266",{enable:!1})}},SA=class e6{constructor(){G(this,"_isEnableUploadLog",!0),G(this,"_localJoinedUser",new Map),G(this,"_queue",[]),G(this,"_timeoutId",-1),G(this,"_logLevel",1),G(this,"_logLevelToUpload",2),!TR&&!GR&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){S.on(K.JOIN_SCHEDULE_SUCCESS,e=>{let{schedule:o}=e;var n;(n=o?.config)!=null&&n.logLevelToUpload&&su[o.config.logLevelToUpload]&&(this._logLevelToUpload=o.config.logLevelToUpload)}),S.on(K.JOIN_START,e=>{let{params:o}=e;this.addJoinedUser({userId:o.userId,sdkAppId:o.sdkAppId}),this.startUpload()}),S.on(K.LEAVE_SUCCESS,e=>{let{room:o}=e;this.deleteJoinedUser(o.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}deleteJoinedUser(e){this._localJoinedUser.delete(e)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let e={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return e;let o=0;for(;o{let{userId:I,sdkAppId:c}=a;e.map.has(I)?e.map.get(I).logs.push(n):e.map.set(I,{userId:I,sdkAppId:c,logs:[n]})});else if(Sr(n.userId)&&hr(n.sdkAppId)){let{userId:a,sdkAppId:I}=n;e.map.has(a)?e.map.get(a).logs.push(n):e.map.set(a,{userId:a,sdkAppId:I,logs:[n]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,o)),e}upload(){return DA(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:e,splicedQueue:o}=this.getLogsToUpload();if(e.size===0)return;try{let a=[...e.values()];for(let I=0;IZ.log).join(` +`)},k=JSON.stringify(R),_=lA.enable?lu(R,2002,u):k;yield this.uploadLogWithRetry(_,u,_ instanceof Uint8Array,k),d.forEach(Z=>Z.uploaded=!0)}}catch{}let n=o.filter(a=>!a.uploaded);n.length>0&&(this._queue=n.concat(this._queue))})}uploadLogWithRetry(e,o,n,a){return Zf({retryFunction:()=>Cu({url:fh(o,Xg.LOG),body:e,timeout:5e3,priority:"low"}).then(I=>{n&&I.data!=="ok"&&(lA.handleUploadFailed(),this.uploadLogWithRetry(a,o,!1,a))}),settings:{retries:3,timeout:2e3},onError:I=>{let{retry:c}=I;c()}})()}getPrefix(e){let o=new Date;return o.setTime(Eh()),"[".concat(QN(o),"] <").concat(su[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){Ee(su[e])||(this._logLevel!==e&&this.info("setLogLevel",e),this._logLevel=e)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(e){if(Sr(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch{return""}}addLogToQueue(e,o){let n=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],a=arguments.length>3?arguments[3]:void 0,I=arguments.length>4?arguments[4]:void 0,c={log:o.reduce((u,d)=>"".concat(u," ").concat(this.logChunkToString(d)).trim(),""),level:e,userId:a,sdkAppId:I,forAllJoinedClients:n};S.emit(K.LOG,{log:c}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(c)}log(e,o){let n=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],a=arguments.length>3?arguments[3]:void 0,I=arguments.length>4?arguments[4]:void 0;var c;if(o.unshift(this.getPrefix(e)),this.addLogToQueue(e,o,n,a,I),e{let e=16*Math.random()|0;return(A=="x"?e:3&e|8).toString(16)})},yA=new class{constructor(){G(this,"_prefix","TRTC"),G(this,"_queue",new Map)}getRealKey(A){return"".concat(this._prefix,"_").concat(A)}checkStorage(){du()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(A=>{if(A.startsWith(this._prefix))try{let e=localStorage.getItem(A);if(!e)return!1;let o=JSON.parse(e);if(o&&o.expiresInlocalStorage.removeItem(A)))}doFlush(){if(du())try{for(let[A,e]of this._queue)localStorage.setItem(A,JSON.stringify(e))}catch(A){nA.warn(A)}}getItem(A){if(!du())return null;try{let e=localStorage.getItem(this.getRealKey(A));if(!e)return null;let o=JSON.parse(e);return o&&o.expiresIn>=Date.now()?o.value:null}catch(e){nA.warn(e)}}setItem(A,e){if(du())try{let o={expiresIn:Date.now()+bR,value:e};this._queue.set(this.getRealKey(A),o)}catch(o){nA.warn(o)}}deleteItem(A){if(!du())return!1;try{return A=this.getRealKey(A),this._queue.delete(A),localStorage.removeItem(A),!0}catch(e){return nA.warn(e),!1}}clear(){if(du())try{localStorage.clear()}catch(A){nA.warn(A)}}},kA={};XC(kA,{HTTPS_API:()=>NT,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>ax,IS_GET_CAPABILITIES_SUPPORTED:()=>nx,IS_GET_SETTINGS_SUPPORTED:()=>qh,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>LT,IS_INSERTABLE_STREAM_SUPPORTED:()=>JQ,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>Mu,IS_RTC_RTP_SENDER_SUPPORTED:()=>tC,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>vM,IS_SEI_SUPPORTED:()=>FT,IS_SPC_SUPPORTED:()=>fm,basis:()=>gx,capabilityCheck:()=>xT,checkSystemRequirementsInternal:()=>ST,decodeSupportStatus:()=>wT,detectH264SupportedByFakeStreaming:()=>ox,detectVideoCodecCapabilities:()=>Dm,detectVideoDecoderCapabilities:()=>PT,detectVideoEncoderCapabilities:()=>YT,encodeSupportStatus:()=>Qm,getBrowserInfo:()=>Bm,getDisplayResolution:()=>rE,getH264ProfileLevelIds:()=>Ex,isAddTransceiverSupported:()=>gl,isBrowserSupported:()=>RT,isCanvasCaptureStreamAPISupported:()=>hm,isCanvasSmallStreamSupported:()=>SM,isGetReceiversSupported:()=>Vh,isGetSendersSupported:()=>AI,isGetTransceiversSupported:()=>Ru,isGetUserMediaSupported:()=>TT,isMediaDevicesSupported:()=>MT,isMediaSessionSupported:()=>sx,isMediaStreamTrackGeneratorSupported:()=>fq,isMediaStreamTrackProcessorSupported:()=>um,isReplaceTrackSupported:()=>rx,isRequestVideoFrameCallbackSupported:()=>HQ,isSIMDSupported:()=>mm,isScaleResolutionDownBySupported:()=>kT,isScreenCaptureApiAvailable:()=>PQ,isSelectedCandidatePair:()=>dm,isSetParametersSupported:()=>bT,isSetSinkIdSupported:()=>Dq,isSmallStreamSupported:()=>pm,isStopTransceiverSupported:()=>vn,isTRTCSupported:()=>mq,isUnifiedPlanDefault:()=>_T,isUsedInHttpProtocol:()=>wI,isWebAudioSupported:()=>GT,isWebCodecSupported:()=>NM,isWebCodecsSupported:()=>wM,isWebRTCSupported:()=>Kh,isWebTransportSupported:()=>jh});var oe={};XC(oe,{AUDIO_LEVEL_SCALE:()=>iE,AlphaStitchingType:()=>Ph,AudioCodecPipelineType:()=>yu,AudioDecoderDowngradeState:()=>Em,AudioPlayerMode:()=>DM,AudioType:()=>XO,BASIC_TYPE:()=>pT,BannedReason:()=>wa,CONNECTION_CLOSED_REASON:()=>it,CheckPermissionType:()=>Hr,ClientEvent:()=>de,CodecType:()=>lm,ConnectionEvent:()=>Li,ConnectionState:()=>Uh,DECODE_FAILED_ERROR_CODE:()=>Cm,DenoiserMode:()=>OQ,DeviceType:()=>fT,FacingMode:()=>QT,FrameWorkType:()=>ni,LeaveReason:()=>dT,LocalTrackEvent:()=>Ri,MULTI_VIDEO_DATA_TYPE:()=>Yh,MediaType:()=>fM,MediaTypeLabel:()=>hq,MonitorEventId:()=>Hs,MutedFlag:()=>br,NetworkQualityValue:()=>uc,PlayerState:()=>ui,ReceiveMode:()=>fg,RemoteStreamType:()=>xh,RemoteTrackEvent:()=>tr,RoomEvent:()=>ci,SMALL_MODE:()=>YQ,SceneNumber:()=>na,StreamEvent:()=>xt,StreamType:()=>Du,SubscribeMediaType:()=>hT,TIMER_TYPE:()=>RM,TRACK_ACTION:()=>uT,TRACK_KIND:()=>fu,TrackEvent:()=>Fi,UserRole:()=>ws,UserRoleNumber:()=>zi,VideoCodec:()=>Vs,VideoCodecPipelineType:()=>xQ,VideoContentHint:()=>yM,VideoDecoderDowngradeState:()=>Oh,VideoPlayerMode:()=>mM,VideoType:()=>mu});var ee,PA,ve,dt,fe,Be,tA,Le,he,Zt,pt,ni=(A=>(A[A.WEBRTC=30]="WEBRTC",A[A.WASM=37]="WASM",A))(ni||{}),Li=((pt=Li||{}).TRACK_ADDED="track-added",pt.TRACK_UPDATED="track-updated",pt.TRACK_SUBSCRIBED="track-subscribed",pt.STREAM_ADDED="stream-added",pt.STREAM_REMOVED="stream-removed",pt.STREAM_UPDATED="stream-updated",pt.STREAM_PUBLISHED="stream-published",pt.STREAM_SUBSCRIBED="stream-subscribed",pt.STREAM_UNSUBSCRIBED="stream-unsubscribed",pt.STATE_CHANGED="state-changed",pt.ERROR="error",pt.CONNECTION_STATE_CHANGED="connection-state-changed",pt.FIREWALL_RESTRICTION="firewall-restriction",pt.SEI_MESSAGE="sei-message",pt.CLOSED="closed",pt),it=(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))(it||{}),de=((Zt=de||{}).STREAM_ADDED="stream-added",Zt.STREAM_REMOVED="stream-removed",Zt.STREAM_UPDATED="stream-updated",Zt.STREAM_SUBSCRIBED="stream-subscribed",Zt.CONNECTION_STATE_CHANGED="connection-state-changed",Zt.PEER_JOIN="peer-join",Zt.PEER_LEAVE="peer-leave",Zt.MUTE_AUDIO="mute-audio",Zt.MUTE_VIDEO="mute-video",Zt.UNMUTE_AUDIO="unmute-audio",Zt.UNMUTE_VIDEO="unmute-video",Zt.CLIENT_BANNED="client-banned",Zt.NETWORK_QUALITY="network-quality",Zt.AUDIO_VOLUME="audio-volume",Zt.SEI_MESSAGE="sei-message",Zt.ERROR="error",Zt),xt=((he=xt||{}).PLAYER_STATE_CHANGED="player-state-changed",he.SCREEN_SHARING_STOPPED="screen-sharing-stopped",he.CONNECTION_STATE_CHANGED="connection-state-changed",he.DEVICE_AUTO_RECOVERED="device-auto-recovered",he.ERROR="error",he),Ri=((Le=Ri||{}).DEVICE_AUTO_RECOVERED="1",Le.DEVICE_RECOVER_FAILED="5",Le.DEVICE_CHANGED="2",Le.ERROR="3",Le.PUBLISH_STATE_CHANGED="4",Le.ENCODE_FAILED="6",Le.TRACK_ENDED="7",Le.RENDER="render",Le),ui=(A=>(A.PAUSED="PAUSED",A.PLAYING="PLAYING",A.STOPPED="STOPPED",A))(ui||{}),ci=((tA=ci||{}).PEER_JOIN="peer-join",tA.PEER_LEAVE="peer-leave",tA.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",tA.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",tA.BANNED="banned",tA.NETWORK_QUALITY="network-quality",tA.AUDIO_VOLUME="audio-volume",tA.SEI_MESSAGE="sei-message",tA.ERROR="error",tA.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",tA.REMOTE_PUBLISHED="remote-published",tA.REMOTE_UNPUBLISHED="remote-unpublished",tA.FIREWALL_RESTRICTION="firewall-restriction",tA.HEARTBEAT_REPORT="heartbeat-report",tA.CUSTOM_MESSAGE="custom-message",tA.LAYER_DATA="layerData",tA.FIRST_VIDEO_FRAME="first-video-frame",tA.FIRST_FRAME_RENDER="first-frame-render",tA.DUMP="dump",tA.AUDIO_FRAME="audio-frame",tA.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",tA.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",tA.NTP_TIME_UPDATED="ntp-time-updated",tA.DATA_CHANNEL_MESSAGE="data-channel-message",tA.ASR_ROBOT_PEER_JOIN="asr-robot-peer-join",tA.ASR_ROBOT_PEER_LEAVE="asr-robot-peer-leave",tA),Fi=((Be=Fi||{}).PLAYER_STATE_CHANGED="player-state-changed",Be.MUTE="mute",Be.UNMUTE="unmute",Be.ERROR="error",Be.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",Be.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",Be.FIRST_VIDEO_FRAME="first-video-frame",Be.FIRST_FRAME_RENDER="first-frame-render",Be.VIDEO_SIZE_CHANGED="video-size-changed",Be),tr=(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))(tr||{}),br=((fe=br||{})[fe.VIDEO=1]="VIDEO",fe[fe.SMALL=2]="SMALL",fe[fe.AUX=4]="AUX",fe[fe.AUDIO=8]="AUDIO",fe[fe.VIDEO_MUTE=16]="VIDEO_MUTE",fe[fe.AUX_MUTE=32]="AUX_MUTE",fe[fe.AUDIO_MUTE=64]="AUDIO_MUTE",fe),na=(A=>(A[A.RTC=1]="RTC",A[A.LIVE=2]="LIVE",A))(na||{}),zi=(A=>(A[A.ANCHOR=20]="ANCHOR",A[A.AUDIENCE=21]="AUDIENCE",A))(zi||{}),ws=(A=>(A.ANCHOR="anchor",A.AUDIENCE="audience",A))(ws||{}),Uh=(A=>(A.CONNECTED="CONNECTED",A.DISCONNECTED="DISCONNECTED",A.CONNECTING="CONNECTING",A.RECONNECTED="RECONNECTED",A.RECONNECTING="RECONNECTING",A))(Uh||{}),Em=((dt=Em||{}).INITIALIZED="INITIALIZED",dt.STARTING="STARTING",dt.STARTED="STARTED",dt.FAILED="FAILED",dt),Oh=(A=>(A.INITIALIZED="INITIALIZED",A.STARTING="STARTING",A.STARTED="STARTED",A.FAILED="FAILED",A))(Oh||{}),fu=(A=>(A.AUDIO="audio",A.VIDEO="video",A.AUXILIARY="auxVideo",A))(fu||{}),uT=(A=>(A.ADD="add",A.REMOVE="remove",A))(uT||{}),fM=(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))(fM||{}),hq={1:"audio",2:"auxVideo",4:"video"},XO=((ve=XO||{})[ve.opus=111]="opus",ve),mu=(A=>(A[A.h264=100]="h264",A[A.vp8=101]="vp8",A))(mu||{}),Du=(A=>(A.Big="big",A.Small="small",A))(Du||{}),xh=(A=>(A.Main="main",A.Aux="auxiliary",A))(xh||{}),Yh=(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))(Yh||{}),Hs=((PA=Hs||{})[PA.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",PA[PA.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",PA[PA.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",PA[PA.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",PA[PA.MUTE_AUDIO=32772]="MUTE_AUDIO",PA[PA.MUTE_VIDEO=32773]="MUTE_VIDEO",PA[PA.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",PA[PA.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",PA[PA.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",PA[PA.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",PA[PA.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",PA[PA.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",PA[PA.SWITCH_CAMERA=32780]="SWITCH_CAMERA",PA[PA.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",PA[PA.REPLACE_VIDEO=32782]="REPLACE_VIDEO",PA[PA.REPLACE_AUDIO=32783]="REPLACE_AUDIO",PA[PA.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",PA[PA.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",PA[PA.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",PA[PA.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",PA[PA.JOIN=32788]="JOIN",PA[PA.LEAVE=32789]="LEAVE",PA[PA.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",PA[PA.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",PA[PA.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",PA[PA.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",PA[PA.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",PA[PA.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",PA[PA.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",PA[PA.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",PA[PA.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",PA[PA.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",PA[PA.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",PA[PA.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",PA[PA.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",PA[PA.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",PA[PA.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",PA[PA.PUBLISH_AUX=32805]="PUBLISH_AUX",PA[PA.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",PA[PA.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",PA[PA.VIDEO_ENCODER=4004]="VIDEO_ENCODER",PA[PA.VIDEO_DECODER=4005]="VIDEO_DECODER",PA),uc=(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))(uc||{}),fg=(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))(fg||{}),QT=(A=>(A.user="user",A.environment="environment",A))(QT||{}),mM=(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))(mM||{}),DM=(A=>(A[A.ELEMENT=0]="ELEMENT",A[A.CONTEXT=1]="CONTEXT",A))(DM||{}),wa=(A=>(A.BANNED="banned",A.KICK="kick",A.USER_TIME_OUT="user_time_out",A.ROOM_DISBAND="room_disband",A))(wa||{}),dT=(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))(dT||{}),iE=1e8,OQ=(A=>(A[A.NORMAL=0]="NORMAL",A[A.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",A))(OQ||{}),hT=class{constructor(){G(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)}},pT=(A=>(A.String="string",A.Number="number",A.Boolean="boolean",A.Array="array",A.Object="object",A))(pT||{}),Vs=(A=>(A.H264="h264",A.H265="h265",A.VP8="vp8",A.VP9="vp9",A.AV1="av1",A))(Vs||{}),xQ=(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))(xQ||{}),yu=(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))(yu||{}),lm=(A=>(A.WebRTC="webrtc",A.WebCodecs="webcodecs",A.WebAssembly="webassembly",A))(lm||{}),Cm=((ee=Cm||{})[ee.SUCCESS=0]="SUCCESS",ee[ee.FAILED=1]="FAILED",ee[ee.WEBCODEC_INIT=2]="WEBCODEC_INIT",ee[ee.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",ee[ee.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",ee[ee.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",ee[ee.WASM_INIT=6]="WASM_INIT",ee[ee.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",ee[ee.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",ee[ee.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",ee[ee.TEST=10]="TEST",ee[ee.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",ee),yM=(A=>(A.NONE="",A.DETAIL="detail",A.MOTION="motion",A.TEXT="text",A))(yM||{}),RM=(A=>(A.INTERVAL="interval",A.TIMEOUT="timeout",A.RAF="raf",A.RIC="ric",A.INTERVAL_IN_WORKER="intervalInWorker",A))(RM||{}),YQ=(A=>(A.CANVAS="canvas",A.API="api",A))(YQ||{}),Hr=(A=>(A[A.NONE=0]="NONE",A[A.MICROPHONE=1]="MICROPHONE",A[A.CAMERA=2]="CAMERA",A[A.BOTH=3]="BOTH",A))(Hr||{}),fT=(A=>(A.CAMERA="camera",A.MICROPHONE="microphone",A))(fT||{}),Ph=(A=>(A[A.none=0]="none",A[A.horizontal=1]="horizontal",A[A.vertical=2]="vertical",A))(Ph||{}),Mi={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"},ts={AVOID_REPEATED_CALL:A=>"previous ".concat(A.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(A){let{key:e,rule:o,fnName:n,value:a}=A;return"'".concat(e||o.name,"' is a required param when calling ").concat(n,"(), received: ").concat(a,".")},INVALID_PARAMETER_TYPE(A){let{key:e,rule:o,fnName:n,value:a}=A,I="".concat(e||o.name),c="";return c=Array.isArray(o.type)?o.type.join("|"):o.type,"'".concat(I,"' must be type of ").concat(c," when calling ").concat(n,"(), received type: ").concat(ya(a),".")},INVALID_PARAMETER_EMPTY(A){let{key:e,rule:o,fnName:n,value:a}=A;return"'".concat(e||o.name,"' cannot be '").concat(a,"' when calling ").concat(n,"().")},INVALID_PARAMETER_INSTANCE(A){let{key:e,rule:o,fnName:n,value:a}=A,I="".concat(e||o.name),c="".concat(o.instanceOf.name||o.instanceOf);return"'".concat(I,"' must be instanceof ").concat(c," when calling ").concat(n,"(), received type: ").concat(ya(a),".")},INVALID_PARAMETER_RANGE(A){let{key:e,rule:o,fnName:n,value:a}=A;return"'".concat(e||o.name,"' must be one of ").concat(o.values.join("|")," when calling ").concat(n,"(), received: ").concat(a,".")},INVALID_PARAMETER_MIN(A){let{key:e,rule:o,fnName:n,value:a}=A;return"the min value of ".concat(e||o.name," is ").concat(o.min,", received: ").concat(a,".")},INVALID_PARAMETER_MAX(A){let{key:e,rule:o,fnName:n,value:a}=A;return"the max value of ".concat(e||o.name," is ").concat(o.max,", received: ").concat(a,".")},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 e="".concat(A.type," failed");return A.message&&(e="".concat(e,": ").concat(A.message,".")),e},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:e,code:o}=A;return"Failed to join room - ".concat(e," 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:e,userId:o,streamType:n}=A;return"failed to subscribe ".concat(o," ").concat(n," stream, reason: ").concat(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: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:e,rule:o,fnName:n,value:a}=A;return"'".concat(e||o.name,"' cannot be less than 0 when calling ").concat(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: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:e,fnName:o}=A;return"'".concat(e,"' is not found in the document object when calling ").concat(o,"().")},INVALID_ELEMENT_ID_TYPE:A=>{let{key:e,fnName:o,type:n}=A;return"the element corresponding to '".concat(e,"' must be instanceof HTMLElement when calling ").concat(o,"(), received: ").concat(n,".")},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:e,event:o}=A;return"an error was caught in ".concat(e,".on('").concat(o,"', handler), please check your code in 'handler'.")},API_NOT_EXIST(A){let{name:e}=A;return"experimental api ".concat(e," 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:e}=A;return"failed to call ".concat(e,"() 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:e,name:o,timesInSecond:n,maxSizeInSecond:a}=A;return"api ".concat(o," call ").concat(e?"size":"times"," is over ").concat(e?"".concat(a," bytes"):n," in a second.")},CONNECTION_ABORTED:A=>"connection aborted due to: ".concat(A),API_CALL_ABORTED(A){let e;return e=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),e},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,".")},$O=(A,e)=>e?"".concat($C,"/").concat(A,"/").concat(e):"".concat($C,"/").concat(A,"/index.html"),mT=()=>{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(Gf);if(A){A=JSON.parse(A);let e=document.createElement("script");e.type="text/javascript",e.text=A.message,document.body.appendChild(e);let o=window.TRTC_ERROR_INFO,n=window.TRTC_ERROR_LINK;return document.body.removeChild(e),{TRTC_ERROR_INFO:o,TRTC_ERROR_LINK:n}}return{}};function Wi(A){let{key:e,data:o,link:n,addDocLink:a=!0}=A,I="",c="",u="";$n(ts[e])?I=ts[e](o):Sr(ts[e])&&(I=ts[e]);let{TRTC_ERROR_INFO:d,TRTC_ERROR_LINK:R}=mT();n?u="".concat(n.className,".html#").concat(n.fnName):R&&R[e]&&($n(R[e])?u=R[e](o):Sr(R[e])&&(u=R[e]));let k=I;return nl()&&(d&&d[e]&&($n(d[e])?c=d[e](o):Sr(d[e])&&(c=d[e])),c&&(k=a?"".concat(c,` +请查看文档: `).concat($O("zh-cn",u),` `):"".concat(c,` `),k+=I)),a&&(k+=` -Refer to: `.concat(qO("en",u),` -`)),k}var Io,ir,hT=es(VV(),1),pT=class{constructor(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];G(this,"countMap",new Map),G(this,"distributionMap",new Map),G(this,"version"),G(this,"log",nA.createLogger({id:"kv"})),A&&(S.on("102",e=>{let{track:o,cost:n}=e;this.addSuccessEvent({key:o.kind===fA.AUDIO?501700:511700,cost:n})}),S.on("103",e=>{let{track:o,error:n}=e;this.addFailedEvent({key:o.kind===fA.AUDIO?501700:511700,error:n})}),S.on("266",e=>{let{enable:o}=e;this.log.info("".concat(o?"enable":"disable"," sso")),o?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(A,e){let o={msg_sdk_basic_info:{uint32_sdk_version:UN(this.version||il),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(n=>{let[a,I]=n;return{uint32_key:a,uint32_count:I}}),stats_distribution:[...this.distributionMap.entries()].map(n=>{let[a,I]=n;return{uint32_key:a,distribution_items:[...I.entries()].map(c=>{let[u,d]=c;return{uint32_item_key:u,uint32_item_value:d}})}}),str_user_sig:A,bytes_report_token:e};return this.countMap.clear(),this.distributionMap.clear(),o}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(A){let e=+String(A).slice(-3);return e>=700&&e<799}isErrorCodeKey(A){let e=+String(A).slice(-3);return e>=600&&e<699}isCountKey(A){let e=+String(A).slice(-3);return e>=0&&e<599}isNumberKey(A){let e=+String(A).slice(-3);return e>=800&&e<899}addCount(A){let{key:e,useUV:o=!1}=A;this.isCountKey(e)?o&&this.countMap.has(e)||this.countMap.set(e,(this.countMap.get(e)||0)+1):this.log.debug("".concat(e," is not count key, last 3 number should be 0~599"))}addEnum(A){let{key:e,value:o,useUV:n=!0}=A;var a;if(!this.isEnumKey(e))return this.log.debug("".concat(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);let I=((a=this.distributionMap)==null?void 0:a.get(e))||new Map;I.set(o,(I.get(o)||0)+1),this.distributionMap.set(e,I)}addNumber(A){let{key:e,value:o,split:n=100,useUV:a=!1,max:I=5e3}=A;var c;if(!this.isNumberKey(e))return this.log.debug("".concat(e," is not number key, last 3 number should be 800~899"));if(a&&this.countMap.has(e))return;o>I&&(o=I),this.countMap.set(e,(this.countMap.get(e)||0)+1);let u=((c=this.distributionMap)==null?void 0:c.get(e))||new Map,d=0;if(hr(n))d=Math.floor(o/n);else for(let R=n.length-1;R>0;R--)if(o>n[R]){d=R;break}u.set(d,(u.get(d)||0)+1),this.distributionMap.set(e,u)}addSuccessEvent(A){let{key:e,cost:o,timeKey:n,split:a}=A;if(e&&(this.addEnum({key:e,value:1,useUV:!1}),o)){let I=+String(e).slice(-3);I<800&&I>=700?this.addNumber({key:n||e+100,value:o,split:a}):n||this.log.debug("time stat ignored, ".concat(e))}}addFailedEvent(A){let{key:e,error:o}=A;if(!e)return;let n=Ge.UNKNOWN;o&&(hr(o)?n=o:(!Ee(o.extraCode)||!Ee(o.code))&&(n=o.extraCode||o.code)),this.addEnum({key:e,value:0,useUV:!1}),this.addEnum({key:e,value:Math.abs(n),useUV:!1})}},KO=((Io=KO||{})[Io.enterRoom=500700]="enterRoom",Io[Io.exitRoom=500701]="exitRoom",Io[Io.switchRole=500702]="switchRole",Io[Io.destroy=500703]="destroy",Io[Io.startLocalAudio=500704]="startLocalAudio",Io[Io.updateLocalAudio=500705]="updateLocalAudio",Io[Io.stopLocalAudio=500706]="stopLocalAudio",Io[Io.startLocalVideo=500707]="startLocalVideo",Io[Io.updateLocalVideo=500708]="updateLocalVideo",Io[Io.stopLocalVideo=500709]="stopLocalVideo",Io[Io.startScreenShare=500710]="startScreenShare",Io[Io.updateScreenShare=500711]="updateScreenShare",Io[Io.stopScreenShare=500712]="stopScreenShare",Io[Io.startRemoteVideo=500713]="startRemoteVideo",Io[Io.updateRemoteVideo=500714]="updateRemoteVideo",Io[Io.stopRemoteVideo=500715]="stopRemoteVideo",Io[Io.muteRemoteAudio=500716]="muteRemoteAudio",Io[Io.setRemoteAudioVolume=500717]="setRemoteAudioVolume",Io[Io.use=500718]="use",Io[Io.switchRoom=500719]="switchRoom",Io[Io.getPermissions=500720]="getPermissions",Io[Io.sendSEIMessage=5e5]="sendSEIMessage",Io[Io.sendCustomMessage=500001]="sendCustomMessage",Io),jO=(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))(jO||{}),xh=(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))(xh||{}),DM=(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))(DM||{}),Yh=((ir=Yh||{})[ir.DECODER_TYPE=514700]="DECODER_TYPE",ir[ir.DECODER_HW_SW=514701]="DECODER_HW_SW",ir[ir.DECODE_RESULT=514702]="DECODE_RESULT",ir[ir.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",ir[ir.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",ir[ir.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",ir[ir.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",ir[ir.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",ir[ir.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",ir[ir.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",ir[ir.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",ir[ir.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",ir[ir.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",ir[ir.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",ir[ir.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",ir[ir.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",ir[ir.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",ir[ir.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",ir[ir.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",ir),Cq=new pT(!0),oB=new pT(!1),ct=Cq,co={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}},WO=new Map([[Yr,["Firefox",Wf]],[wh,["Edg",jN]],[BM,["Chrome",uM]],[Ma,["Safari",Cu]],[eE,["TBS",zN]],[SQ,["XWEB",ZN]],[Eu&&wQ,["WeChat",XN]],[cM,["QQ(Win)",$N]],[Zf,["QQ(Mobile)",Sh]],[vQ,["QQ(Mobile X5)",Sh]],[Xf,["QQ(Mac)",AT]],[EM,["QQ(iPad)",$f]],[lM,["MI",NQ]],[iB,["HW",rT]],[Am,["Samsung",nT]],[em,["OPPO",aT]],[tm,["VIVO",im]],[Mh,["EDGE",KN]],[zf,["SogouMobile",gM]],[IM,["Sogou",WN]]]);function cm(){let A=WO.get(!0);return{browserName:A?A[0]:"unknown",browserVersion:A?A[1]:"unknown"}}var fT=function(){return!(tT||Mh||wh&&sM<80||Yr&&aM<56)},yM=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(A=>A in window)},mT=function(){if(!navigator.mediaDevices)return wI()||nA.error(ts.NOT_SUPPORTED_MEDIA),!1;let A=["getUserMedia","enumerateDevices"];return A.filter(e=>e in navigator.mediaDevices).length===A.length},zO=!1;function wI(){return location.protocol==="http:"&&!GQ&&(zO||nA.error(Wi({key:Mi.NOT_SUPPORTED_HTTP})),zO=!0,!0)}var Em=function(){return window?.OffscreenCanvas&&window?.MediaStreamTrackProcessor&&window?.MediaStreamTrackGenerator},Bq=function(){return!(window==null||!window.MediaStreamTrackGenerator)},lm=function(){return DA(this,null,function*(){var A,e,o;if(co.detail.isH264EncodeSupported&&co.detail.isVp8EncodeSupported)return{isH264EncodeSupported:co.detail.isH264EncodeSupported,isVp8EncodeSupported:co.detail.isVp8EncodeSupported,isH265EncodeSupported:co.detail.isH265EncodeSupported};let n,a=!1,I=!1,c=!1;try{let u=new RTCPeerConnection,d=document.createElement(fA.CANVAS);d.getContext("2d");let R=d.captureStream(0);return u.addTrack(R.getVideoTracks()[0],R),n=yield u.createOffer(),a=((A=n.sdp)==null?void 0:A.toLowerCase().indexOf("h264"))!==-1,I=((e=n.sdp)==null?void 0:e.toLowerCase().indexOf("vp8"))!==-1,c=((o=n.sdp)==null?void 0:o.toLowerCase().indexOf("h265"))!==-1,u.close(),{isH264EncodeSupported:a,isVp8EncodeSupported:I,isH265EncodeSupported:c}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},DT=function(){return DA(this,null,function*(){var A;if(co.detail.isH264DecodeSupported&&co.detail.isVp8DecodeSupported)return{isH264DecodeSupported:co.detail.isH264DecodeSupported,isVp8DecodeSupported:co.detail.isVp8DecodeSupported,isH265DecodeSupported:co.detail.isH265DecodeSupported};let e,o=!1,n=!1;try{let a=new RTCPeerConnection;sl()?(a.addTransceiver(fA.VIDEO,{direction:"recvonly"}),e=yield a.createOffer()):e=yield a.createOffer({offerToReceiveVideo:!0}),e.sdp.toLowerCase().indexOf("h264")!==-1&&(o=!0),e.sdp.toLowerCase().indexOf("vp8")!==-1&&(n=!0);let I=((A=e.sdp)==null?void 0:A.toLowerCase().indexOf("h265"))!==-1;return a.close(),{isH264DecodeSupported:o,isVp8DecodeSupported:n,isH265DecodeSupported:I}}catch{return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})},yT=ON(A=>DA(null,null,function*(){let e=Date.now(),o=Hh(),n=mT(),a=yM();if(co.detail.isWebRTCSupported=o,co.detail.isMediaDevicesSupported=n,co.detail.isWebCodecsSupported=a,co.detail.isScreenShareSupported=OQ(),co.detail.isSmallStreamSupported=um(),A===37)return Object.assign(co.detail,yield function(){return DA(this,null,function*(){return oE||(oE=new Promise(cA=>DA(null,null,function*(){let TA={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!yM())return void cA(TA);let JA=null,Ie=null,XA=null,Ft=()=>{XA&&clearTimeout(XA),JA=null,Ie=null};try{JA=document.createElement("canvas"),Ie=JA.getContext("2d"),JA.width=320,JA.height=240;let ie=0,ke=()=>{!Ie||!JA||(Ie.fillStyle="hsl(".concat(ie%360,", 50%, 50%)"),Ie.fillRect(0,0,JA.width,JA.height),Ie.fillStyle="white",Ie.font="20px Arial",Ie.fillText("Frame ".concat(ie),10,30),ie++)};XA=setTimeout(()=>{Ft(),cA(TA)},5e3);let Nt=[{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(Nt.map(Ut=>DA(null,null,function*(){let Ui,Oi={type:Ut.type,encodeSupported:!1,decodeSupported:!1};try{Ui=yield new Promise((or,xi)=>DA(null,null,function*(){try{let yo=new VideoEncoder({output:Vn=>{or(Vn),Oi.encodeSupported=!0},error:xi});yo.configure(Ut.encodeConfig),ke();let Sa=new VideoFrame(JA,{timestamp:0});yo.encode(Sa,{keyFrame:!0}),Sa.close(),yield yo.flush(),yo.close()}catch(yo){xi(yo)}}))}catch(or){return nA.warn("".concat(Ut.type," encoder error:"),or),Oi}try{yield new Promise((or,xi)=>DA(null,null,function*(){try{let yo=new VideoDecoder({output:Sa=>{Oi.decodeSupported=!0,or(0),Sa.close()},error:xi});yo.configure(Ut.decodeConfig),yo.decode(Ui),yield yo.flush(),yo.close()}catch(yo){xi(yo)}}))}catch(or){nA.warn("".concat(Ut.type," decoder error:"),or)}return Oi})))).forEach(Ut=>{Ut.type==="h264"?(TA.isH264EncodeSupported=Ut.encodeSupported,TA.isH264DecodeSupported=Ut.decodeSupported):Ut.type==="vp8"&&(TA.isVp8EncodeSupported=Ut.encodeSupported,TA.isVp8DecodeSupported=Ut.decodeSupported)}),Ft(),cA(TA)}catch(ie){Ft(),nA.warn("detectWebCodecsSupported failed:",ie),cA(TA)}})),oE)})}()),co.detail.isBrowserSupported=a,co.result=n&&a,co.result||nA.error("".concat(navigator.userAgent," ").concat(ZR(co.detail,!1))),bT(A),ct.addNumber({key:523800,value:Date.now()-e}),co;if(co.result&&co.detail.isH264EncodeSupported&&co.detail.isVp8EncodeSupported&&co.detail.isH265EncodeSupported&&co.detail.isH264DecodeSupported&&co.detail.isVp8DecodeSupported&&co.detail.isH265DecodeSupported)return co;let I=fT(),{encode:c,decode:u}=yield function(){return DA(this,null,function*(){let[cA,TA]=yield Promise.all([lm(),DT()]);return{encode:{h264:cA.isH264EncodeSupported,vp8:cA.isVp8EncodeSupported,h265:cA.isH265EncodeSupported},decode:{h264:TA.isH264DecodeSupported,vp8:TA.isVp8DecodeSupported,h265:TA.isH265DecodeSupported}}})}(),{h264:d,vp8:R}=c,{h264:k}=u,{h265:_}=c,{vp8:Z,h265:iA}=u;if(!d||!R){let cA=yield lm();nA.warn("detect encode again h264:".concat(d," vp8:").concat(R," result: ").concat(JSON.stringify(cA))),d=cA.isH264EncodeSupported,R=cA.isVp8EncodeSupported}if(d&&k&&ra&&Bc&&!SQ&&!eE&&(!em||tE!==115)){let{encode:cA,decode:TA}=yield ZO();d=cA,k=TA}return co.result=I&&o&&n&&(d||R)&&(k||Z),co.detail.isBrowserSupported=I,co.detail.isWebRTCSupported=o,co.detail.isH264EncodeSupported=d,co.detail.isVp8EncodeSupported=R,co.detail.isH265EncodeSupported=_,co.detail.isH264DecodeSupported=k,co.detail.isVp8DecodeSupported=Z,co.detail.isH265DecodeSupported=iA,co.result||nA.error("".concat(navigator.userAgent," ").concat(ZR(co.detail,!1))),bT(),ct.addNumber({key:523800,value:Date.now()-e}),co})),uq=function(){return co.result},OQ=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},Qq=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype,RT=null;function ZO(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;return DA(this,null,function*(){return RT||(RT=new Promise(e=>DA(null,null,function*(){let o={encode:!1,decode:!1},n=()=>{};try{let a=document.createElement("canvas"),I=a.getContext("2d");a.width=640,a.height=480;let c=setInterval(()=>{I.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))},66),u=-1,d=-1;n=()=>{clearInterval(u),clearInterval(c),clearTimeout(d),k.close(),_.close(),R.getTracks().forEach(JA=>JA.stop())},d=setTimeout(()=>{n(),e(o)},A);let R=a.captureStream(),k=new RTCPeerConnection({}),_=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});k.addEventListener("icecandidate",JA=>_.addIceCandidate(JA.candidate)),_.addEventListener("icecandidate",JA=>k.addIceCandidate(JA.candidate)),k.addTrack(R.getVideoTracks()[0],R);let Z=yield k.createOffer();yield k.setLocalDescription(Z),yield _.setRemoteDescription(Z);let iA=yield _.createAnswer(),cA=hT.default.parse(iA.sdp),TA=cA.media[0].rtp.findIndex(JA=>JA.codec==="H264");cA.media[0].rtp=[cA.media[0].rtp[TA]],cA.media[0].fmtp=cA.media[0].fmtp.filter(JA=>JA.payload===cA.media[0].rtp[0].payload),cA.media[0].rtcpFb&&(cA.media[0].rtcpFb=cA.media[0].rtcpFb.filter(JA=>JA.payload===cA.media[0].rtp[0].payload)),iA.sdp=hT.default.write(cA),yield _.setLocalDescription(iA),yield k.setRemoteDescription(iA),u=setInterval(()=>DA(null,null,function*(){o.encode&&o.decode&&(n(),e(o));let[JA,Ie]=yield Promise.all([k.getSenders()[0].getStats(),_.getReceivers()[0].getStats()]);o.encode||JA.forEach(XA=>{XA.type==="outbound-rtp"&&(XA.mediaType===fA.VIDEO||XA.kind===fA.VIDEO)&&XA.bytesSent>0&&(o.encode=!0)}),o.decode||Ie.forEach(XA=>{XA.type==="inbound-rtp"&&(XA.mediaType===fA.VIDEO||XA.kind===fA.VIDEO)&&XA.bytesReceived>0&&(o.decode=!0)})}),100)}catch(a){n(),nA.warn("detectH264Supported failed",a),e({encode:!0,decode:!0})}})).then(e=>(e.encode||(e.decode=!0),(!e.encode||!e.decode)&&nA.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(eC)),e)),RT)})}var oE=null,MT=(A,e,o)=>{location.protocol==="http:"&&!GQ&&(A[e]=()=>{throw new Ct({code:Ge.INVALID_OPERATION,message:ts.NOT_SUPPORTED_HTTP})})},Cm=function(A){return!(A.type!=="candidate-pair"||!A.nominated||A.state!=="in-progress"&&A.state!=="succeeded")&&!(rn(A.selected)&&!A.selected)};function rE(){let A="";if(screen.width){let e=screen.width?screen.width*window.devicePixelRatio:"",o=screen.height?screen.height*window.devicePixelRatio:"";A+="".concat(e," * ").concat(o)}return A}function wT(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function ST(){let A={isSupported:!1},e=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let o=0;o=86,MM="RTCRtpScriptTransform"in window,kT=tC&&(xQ||MM),Hh=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(A=>A in window).length>0};function wM(){let A={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return Ee(window.AudioDecoder)||(A.AudioDecoder=!0),Ee(window.AudioEncoder)||(A.AudioEncoder=!0),Ee(window.VideoDecoder)||(A.VideoDecoder=!0),Ee(window.VideoEncoder)||(A.VideoEncoder=!0),Ee(window.ImageDecoder)||(A.ImageDecoder=!0),A}function ex(){return"mediaSession"in navigator&&!Ee(navigator.mediaSession.setActionHandler)}function Vh(){return!Ee(window.WebTransport)}function dm(){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 tx(){let A={browser:"".concat(uu.name,"/").concat(uu.version),os:Js(),displayResolution:rE(),isScreenShareSupported:OQ(),isWebRTCSupported:Hh(),isGetUserMediaSupported:wT(),isWebAudioSupported:ST(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:wM(),isMediaSessionSupported:ex(),isWebTransportSupported:Vh()};return navigator.userAgent.includes("miniProgram")&&(A.browser="mini/".concat(A.browser)),A}var _T="checkResult";function bT(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30;yA.setItem(_T+A,{ua:navigator.userAgent,checkResult:co})}function LT(A){wI();let e=yA.getItem(_T+A);e&&e.ua===navigator.userAgent&&e.checkResult&&function(o,n){return!!Xc(o)&&Object.keys(n).every(a=>a in o)}(e.checkResult.detail,co.detail)&&(co=e.checkResult),yT(A)}function YQ(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var Du="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function ix(A){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[A]}var ox=!1;function hm(){return DA(this,null,function*(){var A;try{if(ox||(A=navigator?.mediaCapabilities)==null||!A.encodingInfo)return;let e=_Q(),o=pg();if(e===0||o===0)return;ox=!0;let n=["H264","VP8","VP9","AV1","H265"],[a,I]=yield Promise.all([FT(n),UT(n)]);a&&Object.keys(a).forEach(d=>{let R=ix(d.toLowerCase());ct.addEnum({key:513707,value:+"".concat(R).concat(+a[d].supported).concat(+a[d].powerEfficient).concat(e).concat(o),useUV:!1})}),I&&Object.keys(I).forEach(d=>{let R=ix(d.toLowerCase());ct.addEnum({key:514713,value:+"".concat(R).concat(+I[d].supported).concat(+I[d].powerEfficient).concat(e).concat(o),useUV:!1})});let{sender:c,receiver:u}=rx();ct.addEnum({key:513708,value:+"".concat(e).concat(o).concat(+c.high),useUV:!1}),ct.addEnum({key:513709,value:+"".concat(e).concat(o).concat(+c.main),useUV:!1}),ct.addEnum({key:514714,value:+"".concat(e).concat(o).concat(+u.high),useUV:!1}),ct.addEnum({key:514715,value:+"".concat(e).concat(o).concat(+u.main),useUV:!1})}catch(e){nA.info("detectVideoCodecCapabilities failed",e)}})}function FT(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1920,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1080,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:30,a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:3e3;return DA(this,null,function*(){let I={};try{for(let c of A){let u=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:"video/".concat(c),width:e,height:o,bitrate:a,framerate:n}});I[c]=u}}catch{}return I})}function UT(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1920,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1080,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:30,a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:3e3;return DA(this,null,function*(){let I={};try{for(let c of A){let u=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:"video/".concat(c),width:e,height:o,bitrate:a,framerate:n}});I[c]=u}}catch{}return I})}function rx(){let A={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){let e=RTCRtpSender.getCapabilities("video");e&&e.codecs&&e.codecs.filter(o=>o.mimeType.toLowerCase()==="video/h264").forEach(o=>{if(o.sdpFmtpLine){let n=o.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(n&&n[1])switch(n[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 e=RTCRtpReceiver.getCapabilities("video");e&&e.codecs&&e.codecs.filter(o=>o.mimeType.toLowerCase()==="video/h264").forEach(o=>{if(o.sdpFmtpLine){let n=o.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(n&&n[1])switch(n[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(e){nA.warn("get H264 profile levelId failed",e)}return A}var dq=es(hg(),1),pm=Symbol("instance"),fm=Symbol("cacheResult"),iC=class{constructor(A,e,o){this.oldState=A,this.newState=e,this.action=o,this.aborted=!1}abort(A){this.aborted=!0,PQ.call(A,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},SM=class extends Error{constructor(A,e,o){super(e),this.state=A,this.message=e,this.cause=o}},mm=new Map;function is(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(n,a,I)=>{let c=o.action||a;if(!o.context){let d=mm.get(n)||[];mm.has(n)||mm.set(n,d),d.push({from:A,to:e,action:c})}let u=I.value;I.value=function(){let d=this;for(var R=arguments.length,k=new Array(R),_=0;_{if(o.fail&&o.fail.call(this,XA),o.sync){if(o.ignoreError)return XA;throw XA}return o.ignoreError?Promise.resolve(XA):Promise.reject(XA)};if(Z)return iA(Z);let cA=d.state,TA=new iC(cA,e,c);PQ.call(d,TA);let JA=XA=>{var Ft;return d[fm]=XA,TA.aborted||(PQ.call(d,e),(Ft=o.success)===null||Ft===void 0||Ft.call(this,d[fm])),XA},Ie=XA=>(PQ.call(d,cA,XA),iA(XA));try{let XA=u.apply(this,k);return function(Ft){return typeof Ft=="object"&&Ft&&"then"in Ft}(XA)?XA.then(JA).catch(Ie):o.sync?JA(XA):Promise.resolve(JA(XA))}catch(XA){return Ie(new SM(d._state,"".concat(d.name," ").concat(c," from ").concat(A," to ").concat(e," failed: ").concat(XA),XA instanceof Error?XA:new Error(String(XA))))}}}}var vM=typeof window<"u"&&window.__AFSM__?(A,e)=>{window.dispatchEvent(new CustomEvent(A,{detail:e}))}:typeof importScripts<"u"?(A,e)=>{postMessage({type:A,payload:e})}:()=>{};function PQ(A,e){let o=this._state;this._state=A;let n=A.toString();A&&this.emit(n,o),this.emit(Uo.STATECHANGED,A,o,e),this.updateDevTools({value:A,old:o,err:e instanceof Error?e.message:String(e)})}var Uo=class cC extends dq.default{constructor(e,o,n){super(),this.name=e,this.groupName=o,this._state=cC.INIT,e||(e=Date.now().toString(36)),n?Object.setPrototypeOf(this,n):n=Object.getPrototypeOf(this),o||(this.groupName=this.constructor.name);let a=n[pm];a?this.name=a.name+"-"+a.count++:n[pm]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),o=mm.get(e)||[],n=new Set,a=[],I=[],c=new Set,u=Object.getPrototypeOf(e);mm.has(u)&&(u.stateDiagram.forEach(R=>n.add(R)),u.allStates.forEach(R=>c.add(R))),o.forEach(R=>{let{from:k,to:_,action:Z}=R;typeof k=="string"?a.push({from:k,to:_,action:Z}):k.length?k.forEach(iA=>{a.push({from:iA,to:_,action:Z})}):I.push({to:_,action:Z})}),a.forEach(R=>{let{from:k,to:_,action:Z}=R;c.add(k),c.add(_),c.add(Z+"ing"),n.add("".concat(k," --> ").concat(Z,"ing : ").concat(Z)),n.add("".concat(Z,"ing --> ").concat(_," : ").concat(Z," 🟢")),n.add("".concat(Z,"ing --> ").concat(k," : ").concat(Z," 🔴"))}),I.forEach(R=>{let{to:k,action:_}=R;n.add("".concat(_,"ing --> ").concat(k," : ").concat(_," 🟢")),c.forEach(Z=>{Z!==k&&n.add("".concat(Z," --> ").concat(_,"ing : ").concat(_))})});let d=[...n];return Object.defineProperties(e,{stateDiagram:{value:d},allStates:{value:c}}),d}static get(e){let o;return typeof e=="string"?(o=cC.instances.get(e),o||cC.instances.set(e,o=new cC(e,void 0,Object.create(cC.prototype)))):(o=cC.instances2.get(e),o||cC.instances2.set(e,o=new cC(e.constructor.name,void 0,Object.create(cC.prototype)))),o}static getState(e){var o;return(o=cC.get(e))===null||o===void 0?void 0:o.state}updateDevTools(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};vM(cC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){PQ.call(this,e)}};Uo.STATECHANGED="stateChanged",Uo.UPDATEAFSM="updateAFSM",Uo.INIT="[*]",Uo.ON="on",Uo.OFF="off",Uo.instances=new Map,Uo.instances2=new WeakMap;var NM=typeof window<"u",OT=NM&&window.requestIdleCallback||function(A){let e=Date.now();return setTimeout(()=>{A({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-e))})},1e3)},qs=NM&&window.cancelIdleCallback||function(A){clearTimeout(A)},JQ=NM&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),qh=class hc{static generateTaskID(){return this.currentTaskID++}static run(e,o,n){n!=null&&n.fps&&(n.delay=n.delay||Number((1e3/n.fps).toFixed(2))),n=bt(e==="interval"?{delay:2e3,count:0,backgroundTask:!0}:e==="ric"?{delay:1e4,count:0}:e==="raf"?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},n);let a=fi(bt({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:o},n),{delay:n.delay});return this.taskMap.set(a.taskID,a),this[e](a),a.taskID}static interval(e){return e.intervalID=setInterval(()=>{e.callback(),e.loopCount+=1,hc.isBreakLoop(e)},e.delay)}static intervalInWorker(e){hc.sharedWorker||(hc.sharedWorker=new Worker(URL.createObjectURL(new Blob([` +Refer to: `.concat($O("en",u),` +`)),k}var Io,ir,DT=es(ZV(),1),yT=class{constructor(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];G(this,"countMap",new Map),G(this,"distributionMap",new Map),G(this,"version"),G(this,"log",nA.createLogger({id:"kv"})),A&&(S.on("102",e=>{let{track:o,cost:n}=e;this.addSuccessEvent({key:o.kind===fA.AUDIO?501700:511700,cost:n})}),S.on("103",e=>{let{track:o,error:n}=e;this.addFailedEvent({key:o.kind===fA.AUDIO?501700:511700,error:n})}),S.on("266",e=>{let{enable:o}=e;this.log.info("".concat(o?"enable":"disable"," sso")),o?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(A,e){let o={msg_sdk_basic_info:{uint32_sdk_version:PN(this.version||ol),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(n=>{let[a,I]=n;return{uint32_key:a,uint32_count:I}}),stats_distribution:[...this.distributionMap.entries()].map(n=>{let[a,I]=n;return{uint32_key:a,distribution_items:[...I.entries()].map(c=>{let[u,d]=c;return{uint32_item_key:u,uint32_item_value:d}})}}),str_user_sig:A,bytes_report_token:e};return this.countMap.clear(),this.distributionMap.clear(),o}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(A){let e=+String(A).slice(-3);return e>=700&&e<799}isErrorCodeKey(A){let e=+String(A).slice(-3);return e>=600&&e<699}isCountKey(A){let e=+String(A).slice(-3);return e>=0&&e<599}isNumberKey(A){let e=+String(A).slice(-3);return e>=800&&e<899}addCount(A){let{key:e,useUV:o=!1}=A;this.isCountKey(e)?o&&this.countMap.has(e)||this.countMap.set(e,(this.countMap.get(e)||0)+1):this.log.debug("".concat(e," is not count key, last 3 number should be 0~599"))}addEnum(A){let{key:e,value:o,useUV:n=!0}=A;var a;if(!this.isEnumKey(e))return this.log.debug("".concat(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);let I=((a=this.distributionMap)==null?void 0:a.get(e))||new Map;I.set(o,(I.get(o)||0)+1),this.distributionMap.set(e,I)}addNumber(A){let{key:e,value:o,split:n=100,useUV:a=!1,max:I=5e3}=A;var c;if(!this.isNumberKey(e))return this.log.debug("".concat(e," is not number key, last 3 number should be 800~899"));if(a&&this.countMap.has(e))return;o>I&&(o=I),this.countMap.set(e,(this.countMap.get(e)||0)+1);let u=((c=this.distributionMap)==null?void 0:c.get(e))||new Map,d=0;if(hr(n))d=Math.floor(o/n);else for(let R=n.length-1;R>0;R--)if(o>n[R]){d=R;break}u.set(d,(u.get(d)||0)+1),this.distributionMap.set(e,u)}addSuccessEvent(A){let{key:e,cost:o,timeKey:n,split:a}=A;if(e&&(this.addEnum({key:e,value:1,useUV:!1}),o)){let I=+String(e).slice(-3);I<800&&I>=700?this.addNumber({key:n||e+100,value:o,split:a}):n||this.log.debug("time stat ignored, ".concat(e))}}addFailedEvent(A){let{key:e,error:o}=A;if(!e)return;let n=Ge.UNKNOWN;o&&(hr(o)?n=o:(!Ee(o.extraCode)||!Ee(o.code))&&(n=o.extraCode||o.code)),this.addEnum({key:e,value:0,useUV:!1}),this.addEnum({key:e,value:Math.abs(n),useUV:!1})}},Ax=((Io=Ax||{})[Io.enterRoom=500700]="enterRoom",Io[Io.exitRoom=500701]="exitRoom",Io[Io.switchRole=500702]="switchRole",Io[Io.destroy=500703]="destroy",Io[Io.startLocalAudio=500704]="startLocalAudio",Io[Io.updateLocalAudio=500705]="updateLocalAudio",Io[Io.stopLocalAudio=500706]="stopLocalAudio",Io[Io.startLocalVideo=500707]="startLocalVideo",Io[Io.updateLocalVideo=500708]="updateLocalVideo",Io[Io.stopLocalVideo=500709]="stopLocalVideo",Io[Io.startScreenShare=500710]="startScreenShare",Io[Io.updateScreenShare=500711]="updateScreenShare",Io[Io.stopScreenShare=500712]="stopScreenShare",Io[Io.startRemoteVideo=500713]="startRemoteVideo",Io[Io.updateRemoteVideo=500714]="updateRemoteVideo",Io[Io.stopRemoteVideo=500715]="stopRemoteVideo",Io[Io.muteRemoteAudio=500716]="muteRemoteAudio",Io[Io.setRemoteAudioVolume=500717]="setRemoteAudioVolume",Io[Io.use=500718]="use",Io[Io.switchRoom=500719]="switchRoom",Io[Io.getPermissions=500720]="getPermissions",Io[Io.sendSEIMessage=5e5]="sendSEIMessage",Io[Io.sendCustomMessage=500001]="sendCustomMessage",Io),ex=(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))(ex||{}),Jh=(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))(Jh||{}),MM=(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))(MM||{}),Hh=((ir=Hh||{})[ir.DECODER_TYPE=514700]="DECODER_TYPE",ir[ir.DECODER_HW_SW=514701]="DECODER_HW_SW",ir[ir.DECODE_RESULT=514702]="DECODE_RESULT",ir[ir.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",ir[ir.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",ir[ir.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",ir[ir.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",ir[ir.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",ir[ir.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",ir[ir.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",ir[ir.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",ir[ir.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",ir[ir.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",ir[ir.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",ir[ir.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",ir[ir.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",ir[ir.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",ir[ir.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",ir[ir.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",ir),pq=new yT(!0),oB=new yT(!1),ct=pq,co={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}},tx=new Map([[Yr,["Firefox",$f]],[Nh,["Edg",XN]],[dM,["Chrome",hM]],[Ma,["Safari",Qu]],[eE,["TBS",AT]],[TQ,["XWEB",eT]],[Bu&&NQ,["WeChat",tT]],[CM,["QQ(Win)",iT]],[em,["QQ(Mobile)",Th]],[GQ,["QQ(Mobile X5)",Th]],[tm,["QQ(Mac)",oT]],[BM,["QQ(iPad)",im]],[uM,["MI",kQ]],[iB,["HW",gT]],[om,["Samsung",IT]],[rm,["OPPO",cT]],[nm,["VIVO",am]],[vh,["EDGE",ZN]],[Am,["SogouMobile",EM]],[lM,["Sogou",$N]]]);function Bm(){let A=tx.get(!0);return{browserName:A?A[0]:"unknown",browserVersion:A?A[1]:"unknown"}}var RT=function(){return!(nT||vh||Nh&&cM<80||Yr&&IM<56)},wM=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(A=>A in window)},MT=function(){if(!navigator.mediaDevices)return wI()||nA.error(ts.NOT_SUPPORTED_MEDIA),!1;let A=["getUserMedia","enumerateDevices"];return A.filter(e=>e in navigator.mediaDevices).length===A.length},ix=!1;function wI(){return location.protocol==="http:"&&!bQ&&(ix||nA.error(Wi({key:Mi.NOT_SUPPORTED_HTTP})),ix=!0,!0)}var um=function(){return window?.OffscreenCanvas&&window?.MediaStreamTrackProcessor&&window?.MediaStreamTrackGenerator},fq=function(){return!(window==null||!window.MediaStreamTrackGenerator)},Qm=function(){return DA(this,null,function*(){var A,e,o;if(co.detail.isH264EncodeSupported&&co.detail.isVp8EncodeSupported)return{isH264EncodeSupported:co.detail.isH264EncodeSupported,isVp8EncodeSupported:co.detail.isVp8EncodeSupported,isH265EncodeSupported:co.detail.isH265EncodeSupported};let n,a=!1,I=!1,c=!1;try{let u=new RTCPeerConnection,d=document.createElement(fA.CANVAS);d.getContext("2d");let R=d.captureStream(0);return u.addTrack(R.getVideoTracks()[0],R),n=yield u.createOffer(),a=((A=n.sdp)==null?void 0:A.toLowerCase().indexOf("h264"))!==-1,I=((e=n.sdp)==null?void 0:e.toLowerCase().indexOf("vp8"))!==-1,c=((o=n.sdp)==null?void 0:o.toLowerCase().indexOf("h265"))!==-1,u.close(),{isH264EncodeSupported:a,isVp8EncodeSupported:I,isH265EncodeSupported:c}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},wT=function(){return DA(this,null,function*(){var A;if(co.detail.isH264DecodeSupported&&co.detail.isVp8DecodeSupported)return{isH264DecodeSupported:co.detail.isH264DecodeSupported,isVp8DecodeSupported:co.detail.isVp8DecodeSupported,isH265DecodeSupported:co.detail.isH265DecodeSupported};let e,o=!1,n=!1;try{let a=new RTCPeerConnection;gl()?(a.addTransceiver(fA.VIDEO,{direction:"recvonly"}),e=yield a.createOffer()):e=yield a.createOffer({offerToReceiveVideo:!0}),e.sdp.toLowerCase().indexOf("h264")!==-1&&(o=!0),e.sdp.toLowerCase().indexOf("vp8")!==-1&&(n=!0);let I=((A=e.sdp)==null?void 0:A.toLowerCase().indexOf("h265"))!==-1;return a.close(),{isH264DecodeSupported:o,isVp8DecodeSupported:n,isH265DecodeSupported:I}}catch{return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})},ST=JN(A=>DA(null,null,function*(){let e=Date.now(),o=Kh(),n=MT(),a=wM();if(co.detail.isWebRTCSupported=o,co.detail.isMediaDevicesSupported=n,co.detail.isWebCodecsSupported=a,co.detail.isScreenShareSupported=PQ(),co.detail.isSmallStreamSupported=pm(),A===37)return Object.assign(co.detail,yield function(){return DA(this,null,function*(){return oE||(oE=new Promise(cA=>DA(null,null,function*(){let TA={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!wM())return void cA(TA);let JA=null,Ie=null,XA=null,Ft=()=>{XA&&clearTimeout(XA),JA=null,Ie=null};try{JA=document.createElement("canvas"),Ie=JA.getContext("2d"),JA.width=320,JA.height=240;let ie=0,ke=()=>{!Ie||!JA||(Ie.fillStyle="hsl(".concat(ie%360,", 50%, 50%)"),Ie.fillRect(0,0,JA.width,JA.height),Ie.fillStyle="white",Ie.font="20px Arial",Ie.fillText("Frame ".concat(ie),10,30),ie++)};XA=setTimeout(()=>{Ft(),cA(TA)},5e3);let Nt=[{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(Nt.map(Ut=>DA(null,null,function*(){let Ui,Oi={type:Ut.type,encodeSupported:!1,decodeSupported:!1};try{Ui=yield new Promise((or,xi)=>DA(null,null,function*(){try{let yo=new VideoEncoder({output:Vn=>{or(Vn),Oi.encodeSupported=!0},error:xi});yo.configure(Ut.encodeConfig),ke();let Sa=new VideoFrame(JA,{timestamp:0});yo.encode(Sa,{keyFrame:!0}),Sa.close(),yield yo.flush(),yo.close()}catch(yo){xi(yo)}}))}catch(or){return nA.warn("".concat(Ut.type," encoder error:"),or),Oi}try{yield new Promise((or,xi)=>DA(null,null,function*(){try{let yo=new VideoDecoder({output:Sa=>{Oi.decodeSupported=!0,or(0),Sa.close()},error:xi});yo.configure(Ut.decodeConfig),yo.decode(Ui),yield yo.flush(),yo.close()}catch(yo){xi(yo)}}))}catch(or){nA.warn("".concat(Ut.type," decoder error:"),or)}return Oi})))).forEach(Ut=>{Ut.type==="h264"?(TA.isH264EncodeSupported=Ut.encodeSupported,TA.isH264DecodeSupported=Ut.decodeSupported):Ut.type==="vp8"&&(TA.isVp8EncodeSupported=Ut.encodeSupported,TA.isVp8DecodeSupported=Ut.decodeSupported)}),Ft(),cA(TA)}catch(ie){Ft(),nA.warn("detectWebCodecsSupported failed:",ie),cA(TA)}})),oE)})}()),co.detail.isBrowserSupported=a,co.result=n&&a,co.result||nA.error("".concat(navigator.userAgent," ").concat(AM(co.detail,!1))),OT(A),ct.addNumber({key:523800,value:Date.now()-e}),co;if(co.result&&co.detail.isH264EncodeSupported&&co.detail.isVp8EncodeSupported&&co.detail.isH265EncodeSupported&&co.detail.isH264DecodeSupported&&co.detail.isVp8DecodeSupported&&co.detail.isH265DecodeSupported)return co;let I=RT(),{encode:c,decode:u}=yield function(){return DA(this,null,function*(){let[cA,TA]=yield Promise.all([Qm(),wT()]);return{encode:{h264:cA.isH264EncodeSupported,vp8:cA.isVp8EncodeSupported,h265:cA.isH265EncodeSupported},decode:{h264:TA.isH264DecodeSupported,vp8:TA.isVp8DecodeSupported,h265:TA.isH265DecodeSupported}}})}(),{h264:d,vp8:R}=c,{h264:k}=u,{h265:_}=c,{vp8:Z,h265:iA}=u;if(!d||!R){let cA=yield Qm();nA.warn("detect encode again h264:".concat(d," vp8:").concat(R," result: ").concat(JSON.stringify(cA))),d=cA.isH264EncodeSupported,R=cA.isVp8EncodeSupported}if(d&&k&&ra&&Bc&&!TQ&&!eE&&(!rm||tE!==115)){let{encode:cA,decode:TA}=yield ox();d=cA,k=TA}return co.result=I&&o&&n&&(d||R)&&(k||Z),co.detail.isBrowserSupported=I,co.detail.isWebRTCSupported=o,co.detail.isH264EncodeSupported=d,co.detail.isVp8EncodeSupported=R,co.detail.isH265EncodeSupported=_,co.detail.isH264DecodeSupported=k,co.detail.isVp8DecodeSupported=Z,co.detail.isH265DecodeSupported=iA,co.result||nA.error("".concat(navigator.userAgent," ").concat(AM(co.detail,!1))),OT(),ct.addNumber({key:523800,value:Date.now()-e}),co})),mq=function(){return co.result},PQ=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},Dq=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype,vT=null;function ox(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;return DA(this,null,function*(){return vT||(vT=new Promise(e=>DA(null,null,function*(){let o={encode:!1,decode:!1},n=()=>{};try{let a=document.createElement("canvas"),I=a.getContext("2d");a.width=640,a.height=480;let c=setInterval(()=>{I.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))},66),u=-1,d=-1;n=()=>{clearInterval(u),clearInterval(c),clearTimeout(d),k.close(),_.close(),R.getTracks().forEach(JA=>JA.stop())},d=setTimeout(()=>{n(),e(o)},A);let R=a.captureStream(),k=new RTCPeerConnection({}),_=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});k.addEventListener("icecandidate",JA=>_.addIceCandidate(JA.candidate)),_.addEventListener("icecandidate",JA=>k.addIceCandidate(JA.candidate)),k.addTrack(R.getVideoTracks()[0],R);let Z=yield k.createOffer();yield k.setLocalDescription(Z),yield _.setRemoteDescription(Z);let iA=yield _.createAnswer(),cA=DT.default.parse(iA.sdp),TA=cA.media[0].rtp.findIndex(JA=>JA.codec==="H264");cA.media[0].rtp=[cA.media[0].rtp[TA]],cA.media[0].fmtp=cA.media[0].fmtp.filter(JA=>JA.payload===cA.media[0].rtp[0].payload),cA.media[0].rtcpFb&&(cA.media[0].rtcpFb=cA.media[0].rtcpFb.filter(JA=>JA.payload===cA.media[0].rtp[0].payload)),iA.sdp=DT.default.write(cA),yield _.setLocalDescription(iA),yield k.setRemoteDescription(iA),u=setInterval(()=>DA(null,null,function*(){o.encode&&o.decode&&(n(),e(o));let[JA,Ie]=yield Promise.all([k.getSenders()[0].getStats(),_.getReceivers()[0].getStats()]);o.encode||JA.forEach(XA=>{XA.type==="outbound-rtp"&&(XA.mediaType===fA.VIDEO||XA.kind===fA.VIDEO)&&XA.bytesSent>0&&(o.encode=!0)}),o.decode||Ie.forEach(XA=>{XA.type==="inbound-rtp"&&(XA.mediaType===fA.VIDEO||XA.kind===fA.VIDEO)&&XA.bytesReceived>0&&(o.decode=!0)})}),100)}catch(a){n(),nA.warn("detectH264Supported failed",a),e({encode:!0,decode:!0})}})).then(e=>(e.encode||(e.decode=!0),(!e.encode||!e.decode)&&nA.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(eC)),e)),vT)})}var oE=null,NT=(A,e,o)=>{location.protocol==="http:"&&!bQ&&(A[e]=()=>{throw new Ct({code:Ge.INVALID_OPERATION,message:ts.NOT_SUPPORTED_HTTP})})},dm=function(A){return!(A.type!=="candidate-pair"||!A.nominated||A.state!=="in-progress"&&A.state!=="succeeded")&&!(rn(A.selected)&&!A.selected)};function rE(){let A="";if(screen.width){let e=screen.width?screen.width*window.devicePixelRatio:"",o=screen.height?screen.height*window.devicePixelRatio:"";A+="".concat(e," * ").concat(o)}return A}function TT(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function GT(){let A={isSupported:!1},e=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let o=0;o=86,vM="RTCRtpScriptTransform"in window,FT=tC&&(JQ||vM),Kh=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(A=>A in window).length>0};function NM(){let A={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return Ee(window.AudioDecoder)||(A.AudioDecoder=!0),Ee(window.AudioEncoder)||(A.AudioEncoder=!0),Ee(window.VideoDecoder)||(A.VideoDecoder=!0),Ee(window.VideoEncoder)||(A.VideoEncoder=!0),Ee(window.ImageDecoder)||(A.ImageDecoder=!0),A}function sx(){return"mediaSession"in navigator&&!Ee(navigator.mediaSession.setActionHandler)}function jh(){return!Ee(window.WebTransport)}function mm(){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 gx(){let A={browser:"".concat(hu.name,"/").concat(hu.version),os:Js(),displayResolution:rE(),isScreenShareSupported:PQ(),isWebRTCSupported:Kh(),isGetUserMediaSupported:TT(),isWebAudioSupported:GT(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:NM(),isMediaSessionSupported:sx(),isWebTransportSupported:jh()};return navigator.userAgent.includes("miniProgram")&&(A.browser="mini/".concat(A.browser)),A}var UT="checkResult";function OT(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30;yA.setItem(UT+A,{ua:navigator.userAgent,checkResult:co})}function xT(A){wI();let e=yA.getItem(UT+A);e&&e.ua===navigator.userAgent&&e.checkResult&&function(o,n){return!!Xc(o)&&Object.keys(n).every(a=>a in o)}(e.checkResult.detail,co.detail)&&(co=e.checkResult),ST(A)}function HQ(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var Mu="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function Ix(A){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[A]}var cx=!1;function Dm(){return DA(this,null,function*(){var A;try{if(cx||(A=navigator?.mediaCapabilities)==null||!A.encodingInfo)return;let e=FQ(),o=pg();if(e===0||o===0)return;cx=!0;let n=["H264","VP8","VP9","AV1","H265"],[a,I]=yield Promise.all([YT(n),PT(n)]);a&&Object.keys(a).forEach(d=>{let R=Ix(d.toLowerCase());ct.addEnum({key:513707,value:+"".concat(R).concat(+a[d].supported).concat(+a[d].powerEfficient).concat(e).concat(o),useUV:!1})}),I&&Object.keys(I).forEach(d=>{let R=Ix(d.toLowerCase());ct.addEnum({key:514713,value:+"".concat(R).concat(+I[d].supported).concat(+I[d].powerEfficient).concat(e).concat(o),useUV:!1})});let{sender:c,receiver:u}=Ex();ct.addEnum({key:513708,value:+"".concat(e).concat(o).concat(+c.high),useUV:!1}),ct.addEnum({key:513709,value:+"".concat(e).concat(o).concat(+c.main),useUV:!1}),ct.addEnum({key:514714,value:+"".concat(e).concat(o).concat(+u.high),useUV:!1}),ct.addEnum({key:514715,value:+"".concat(e).concat(o).concat(+u.main),useUV:!1})}catch(e){nA.info("detectVideoCodecCapabilities failed",e)}})}function YT(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1920,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1080,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:30,a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:3e3;return DA(this,null,function*(){let I={};try{for(let c of A){let u=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:"video/".concat(c),width:e,height:o,bitrate:a,framerate:n}});I[c]=u}}catch{}return I})}function PT(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1920,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1080,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:30,a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:3e3;return DA(this,null,function*(){let I={};try{for(let c of A){let u=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:"video/".concat(c),width:e,height:o,bitrate:a,framerate:n}});I[c]=u}}catch{}return I})}function Ex(){let A={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){let e=RTCRtpSender.getCapabilities("video");e&&e.codecs&&e.codecs.filter(o=>o.mimeType.toLowerCase()==="video/h264").forEach(o=>{if(o.sdpFmtpLine){let n=o.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(n&&n[1])switch(n[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 e=RTCRtpReceiver.getCapabilities("video");e&&e.codecs&&e.codecs.filter(o=>o.mimeType.toLowerCase()==="video/h264").forEach(o=>{if(o.sdpFmtpLine){let n=o.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(n&&n[1])switch(n[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(e){nA.warn("get H264 profile levelId failed",e)}return A}var yq=es(hg(),1),ym=Symbol("instance"),Rm=Symbol("cacheResult"),iC=class{constructor(A,e,o){this.oldState=A,this.newState=e,this.action=o,this.aborted=!1}abort(A){this.aborted=!0,VQ.call(A,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},TM=class extends Error{constructor(A,e,o){super(e),this.state=A,this.message=e,this.cause=o}},Mm=new Map;function is(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(n,a,I)=>{let c=o.action||a;if(!o.context){let d=Mm.get(n)||[];Mm.has(n)||Mm.set(n,d),d.push({from:A,to:e,action:c})}let u=I.value;I.value=function(){let d=this;for(var R=arguments.length,k=new Array(R),_=0;_{if(o.fail&&o.fail.call(this,XA),o.sync){if(o.ignoreError)return XA;throw XA}return o.ignoreError?Promise.resolve(XA):Promise.reject(XA)};if(Z)return iA(Z);let cA=d.state,TA=new iC(cA,e,c);VQ.call(d,TA);let JA=XA=>{var Ft;return d[Rm]=XA,TA.aborted||(VQ.call(d,e),(Ft=o.success)===null||Ft===void 0||Ft.call(this,d[Rm])),XA},Ie=XA=>(VQ.call(d,cA,XA),iA(XA));try{let XA=u.apply(this,k);return function(Ft){return typeof Ft=="object"&&Ft&&"then"in Ft}(XA)?XA.then(JA).catch(Ie):o.sync?JA(XA):Promise.resolve(JA(XA))}catch(XA){return Ie(new TM(d._state,"".concat(d.name," ").concat(c," from ").concat(A," to ").concat(e," failed: ").concat(XA),XA instanceof Error?XA:new Error(String(XA))))}}}}var GM=typeof window<"u"&&window.__AFSM__?(A,e)=>{window.dispatchEvent(new CustomEvent(A,{detail:e}))}:typeof importScripts<"u"?(A,e)=>{postMessage({type:A,payload:e})}:()=>{};function VQ(A,e){let o=this._state;this._state=A;let n=A.toString();A&&this.emit(n,o),this.emit(Uo.STATECHANGED,A,o,e),this.updateDevTools({value:A,old:o,err:e instanceof Error?e.message:String(e)})}var Uo=class cC extends yq.default{constructor(e,o,n){super(),this.name=e,this.groupName=o,this._state=cC.INIT,e||(e=Date.now().toString(36)),n?Object.setPrototypeOf(this,n):n=Object.getPrototypeOf(this),o||(this.groupName=this.constructor.name);let a=n[ym];a?this.name=a.name+"-"+a.count++:n[ym]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),o=Mm.get(e)||[],n=new Set,a=[],I=[],c=new Set,u=Object.getPrototypeOf(e);Mm.has(u)&&(u.stateDiagram.forEach(R=>n.add(R)),u.allStates.forEach(R=>c.add(R))),o.forEach(R=>{let{from:k,to:_,action:Z}=R;typeof k=="string"?a.push({from:k,to:_,action:Z}):k.length?k.forEach(iA=>{a.push({from:iA,to:_,action:Z})}):I.push({to:_,action:Z})}),a.forEach(R=>{let{from:k,to:_,action:Z}=R;c.add(k),c.add(_),c.add(Z+"ing"),n.add("".concat(k," --> ").concat(Z,"ing : ").concat(Z)),n.add("".concat(Z,"ing --> ").concat(_," : ").concat(Z," 🟢")),n.add("".concat(Z,"ing --> ").concat(k," : ").concat(Z," 🔴"))}),I.forEach(R=>{let{to:k,action:_}=R;n.add("".concat(_,"ing --> ").concat(k," : ").concat(_," 🟢")),c.forEach(Z=>{Z!==k&&n.add("".concat(Z," --> ").concat(_,"ing : ").concat(_))})});let d=[...n];return Object.defineProperties(e,{stateDiagram:{value:d},allStates:{value:c}}),d}static get(e){let o;return typeof e=="string"?(o=cC.instances.get(e),o||cC.instances.set(e,o=new cC(e,void 0,Object.create(cC.prototype)))):(o=cC.instances2.get(e),o||cC.instances2.set(e,o=new cC(e.constructor.name,void 0,Object.create(cC.prototype)))),o}static getState(e){var o;return(o=cC.get(e))===null||o===void 0?void 0:o.state}updateDevTools(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};GM(cC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){VQ.call(this,e)}};Uo.STATECHANGED="stateChanged",Uo.UPDATEAFSM="updateAFSM",Uo.INIT="[*]",Uo.ON="on",Uo.OFF="off",Uo.instances=new Map,Uo.instances2=new WeakMap;var kM=typeof window<"u",JT=kM&&window.requestIdleCallback||function(A){let e=Date.now();return setTimeout(()=>{A({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-e))})},1e3)},qs=kM&&window.cancelIdleCallback||function(A){clearTimeout(A)},qQ=kM&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),Wh=class hc{static generateTaskID(){return this.currentTaskID++}static run(e,o,n){n!=null&&n.fps&&(n.delay=n.delay||Number((1e3/n.fps).toFixed(2))),n=bt(e==="interval"?{delay:2e3,count:0,backgroundTask:!0}:e==="ric"?{delay:1e4,count:0}:e==="raf"?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},n);let a=fi(bt({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:o},n),{delay:n.delay});return this.taskMap.set(a.taskID,a),this[e](a),a.taskID}static interval(e){return e.intervalID=setInterval(()=>{e.callback(),e.loopCount+=1,hc.isBreakLoop(e)},e.delay)}static intervalInWorker(e){hc.sharedWorker||(hc.sharedWorker=new Worker(URL.createObjectURL(new Blob([` const timers = new Map(); self.onmessage = function(e) { const { taskId, delay, type } = e.data; @@ -174,15 +174,15 @@ Refer to: `.concat(qO("en",u),` timers.delete(taskId); } }; - `],{type:"application/javascript"}))),hc.sharedWorker.onmessage=o=>{var n;if(o.data.type==="tick"){let a=hc.workerTasks.get(o.data.taskId);a&&(hc.isBreakLoop(a)?((n=hc.sharedWorker)==null||n.postMessage({type:"stop",taskId:a.taskID}),hc.workerTasks.delete(a.taskID)):(a.callback(),a.loopCount+=1))}}),hc.workerTasks.set(e.taskID,e),hc.sharedWorker.postMessage({taskId:e.taskID,delay:e.delay,type:"start"})}static timeout(e){let o=()=>{if(e.callback(),e.loopCount+=1,!hc.isBreakLoop(e))return e.timeoutID=setTimeout(o,e.delay)};return e.timeoutID=setTimeout(o,e.delay)}static ric(e){let o,n=ki(),a=()=>{if(o=ki()-n,o>=e.delay&&(n=ki()-Math.floor(o%e.delay),e.callback(),e.loopCount+=1),!hc.isBreakLoop(e))return e.ricID=OT(a,{timeout:e.delay})};return e.ricID=OT(a,{timeout:e.delay})}static raf(e){let o,n=ki(),a=()=>document.hidden&&e.backgroundTask?(o=ki()-n,n=ki(),e.callback(),e.loopCount+=1,hc.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(a,e.delay-Math.floor(o%e.delay))):(o=ki()-n,o>=e.delay&&(n=ki()-Math.floor(o%e.delay),e.callback(),e.loopCount+=1),hc.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(a));if(e.rafID=requestAnimationFrame(a),e.backgroundTask){let I=()=>{if(document.hidden){let c=ki()-n;c>=e.delay?a():e.timeoutID=setTimeout(a,e.delay-c)}};document.addEventListener("visibilitychange",I),e.onVisibilitychange=I,document.hidden&&I()}return e.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;let{intervalID:o,timeoutID:n,rafID:a,ricID:I,onVisibilitychange:c}=this.taskMap.get(e);return o&&clearInterval(o),n&&clearTimeout(n),a&&JQ&&JQ(a),I&&qs(I),c&&document.removeEventListener("visibilitychange",c),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.hasTask(e.taskID)||e.count!==0&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};G(qh,"taskMap",new Map),G(qh,"currentTaskID",1),G(qh,"sharedWorker",null),G(qh,"workerTasks",new Map);var nn=qh,mi={LOAD_START:fA.LOADSTART,LOADED_DATA:fA.LOADEDDATA,LOADED_META_DATA:fA.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:fA.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:fA.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:fA.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"},xT={};XC(xT,{create:()=>nE,remove:()=>pr});var rB=new WeakMap;function nE(A,e){rB.has(A)||rB.set(A,[]);let o=rB.get(A),n={add:(a,I)=>("addEventListener"in e?(o.push(e.removeEventListener.bind(e,a,I)),e.addEventListener(a,I)):(o.push(e.off.bind(e,a,I)),e.on(a,I)),n)};return n}function pr(A){let e=rB.get(A);e&&(e.forEach(o=>o()),rB.delete(A))}var Jo=new class{constructor(){G(this,"_roomIdMap",new Map),G(this,"_configs"),typeof registerProcessor>"u"&&(this._configs={sdkAppId:"",userId:"",version:il,env:ou.QCLOUD,browserVersion:uu.name+uu.version,ua:navigator.userAgent})}setConfig(A){let{sdkAppId:e,env:o,userId:n,roomId:a}=A;e!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(e)),this._configs.env=o,this._configs.userId=n,this._roomIdMap.set(n,String(a))}logSuccessEvent(A){GQ||!nA.isAbleToUpload||this._configs.env===ou.QCLOUD&&this.uploadEventToKibana(fi(bt({},A),{result:"success"}))}logFailedEvent(A){if(GQ||!nA.isAbleToUpload)return;let{eventType:e,code:o,error:n,userId:a}=A,I={roomId:this._roomIdMap.get(a||this._configs.userId),userId:a,eventType:e,result:"failed",code:o||n?.extraCode||n?.code||Ge.UNKNOWN};this._configs.env===ou.QCLOUD&&this.uploadEventToKibana(fi(bt({},I),{error:n}))}uploadEventToKibana(A){let e="stat-".concat(A.eventType,"-").concat(A.result);(A.eventType==="delta-join"||A.eventType==="delta-leave"||A.eventType==="delta-publish")&&(e="".concat(A.eventType,":").concat(A.delta)),this.uploadEvent({log:e,userId:A.userId}),A.result==="failed"&&(e="stat-".concat(A.eventType,"-").concat(A.result,"-").concat(A.code),this.uploadEvent({log:e,userId:A.userId,error:A.error}))}uploadEvent(A){let{log:e,userId:o,error:n}=A,a={timestamp:jU(),sdkAppId:this._configs.sdkAppId,userId:o||this._configs.userId,version:il,log:e};n&&(a.errorInfo=n.message,n.stack&&(a.errorInfo+=` -`.concat(n.stack)));let I=lA.enable?Iu(a,2002,Number(this._configs.sdkAppId)):JSON.stringify(a);this.sendRequest(dh(this._configs.sdkAppId,Xg.LOG),I)}sendRequest(A,e){setTimeout(()=>cu({url:A,body:e,priority:"low"}).catch(()=>{}),2e3)}},oC=new WeakMap;function nB(A){let{settings:e={retries:5,timeout:2e3},onError:o,onRetrying:n,onRetryFailed:a}=A;return function(I,c,u){let d=Kf({retryFunction:u.value,settings:e,onError(R){let{error:k,retry:_,reject:Z,retryFuncArgs:iA}=R;var cA;o?o.call(this,k,()=>{var TA;(TA=oC.get(I))!=null&&TA.has(c)?_():Z(k)},Z,iA):(cA=oC.get(I))!=null&&cA.has(c)?_():Z(k)},onRetrying(R,k){var _;RQ(n)&&n.call(this,R,k),(_=oC.get(I))!=null&&_.has(c)&&(oC.get(I).get(c).stopRetry=k)},onRetryFailed:a});return u.value=function(){let R=oC.get(I);for(var k=arguments.length,_=new Array(k),Z=0;Z{var iA;return(iA=oC.get(I))==null?void 0:iA.delete(c)})},u}}function TM(A){let{fnName:e,callback:o,validateArgs:n=!0}=A;return function(a,I,c){let u=c.value;return c.value=function(){for(var d,R,k=arguments.length,_=new Array(k),Z=0;ZIe===JA)){TA=!1;break}}TA&&(o&&o.apply(this,_),iA&&iA(),(R=oC.get(a))==null||R.delete(e))}return u.apply(this,_)},c}}var rC=class extends Uo{constructor(A,e){super(A.id,"".concat(e,"-player")),this.options=A,this.kind=e,G(this,"id"),G(this,"element",null),G(this,"track"),G(this,"url"),G(this,"attr"),G(this,"mode"),G(this,"muted"),G(this,"_log"),G(this,"isPausedByUserCall",!1),G(this,"_pausedRetryCount"),G(this,"_isElementPlayingFired",!1),G(this,"_interval"),G(this,"_delayDestroyTimeoutId",0),G(this,"_playSuccessResolve"),G(this,"_isReplayByRecreateMediaStreamCalled",!1),G(this,"isPlayCalled",!1),G(this,"isInAutoPlayFailedState",!1),G(this,"isBindAutoPlayEvent",!1),this.id=A.id,this._log=A.log,this.track=A.track,this.muted=A.muted,this._pausedRetryCount=pQ,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(e,"-player ").concat(this.id))}get isPlaying(){var A;return this._state==="PLAYING"&&((A=this.element)==null?void 0:A.paused)===!1}get isPaused(){var A;return this._state==="PAUSED"||((A=this.element)==null?void 0:A.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(A){this.attr=A}setUrl(A){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),A!==this.url&&(this.url=A,A!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=A))}play(){return DA(this,null,function*(){if(!this.isPlaying)try{this.isPlayCalled=!0,this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((A,e)=>{this._playSuccessResolve=A,this.element.play().then(A,e)})}catch(A){let e=Wi({key:Mi.PLAY_FAILED,data:{media:this.kind,error:A}});if(this._log.warn(A),e.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new Ct({code:Ge.PLAY_NOT_ALLOWED,message:e})}})}stop(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;var e;this.isPlayCalled=!1,this.isPausedByUserCall=!1,this._isElementPlayingFired=!1,this.unbindEvents(),A>0&&!TQ?this._delayDestroyTimeoutId||((e=this.element)==null||e.remove(),this._log.info("destroy element after 3 * ".concat(A)),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*A)):this.destroyElement(),this.handleStopped(fA.ENDED),this._interval>0&&nn.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 A;(A=this.element)==null||A.pause()}resume(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this.isPausedByUserCall=!1,this.doResume(A)}doResume(){return this._log.info("resume"),this.isPausedByUserCall||this.isPlaying?Promise.resolve():xO?this.replay():this.play().catch(()=>{})}setMuted(A){this.element&&(this.element.muted=A),this.muted=A}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let A=this.handleElementEvent.bind(this);return nE(this.element,this.element).add(fA.PLAYING,A).add(fA.ENDED,A).add(fA.PAUSE,A).add(fA.ERROR,A).add(fA.LOADSTART,A).add(fA.LOADEDDATA,A).add(fA.LOADEDMETADATA,A)}}bindTrackEvents(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.track;if(A){let e=this.handleTrackEvent.bind(this);xT?.create(A,A).add(fA.ENDED,e).add(fA.MUTE,e).add(fA.UNMUTE,e),A.readyState===fA.ENDED&&this.handleTrackEvent({type:fA.ENDED}),A.muted&&this.handleTrackEvent({type:fA.MUTE})}}bindAutoPlayEvent(){this.isBindAutoPlayEvent||(this._log.warn("bindAutoPlayEvent"),S.on(K.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!0)}unbindTrackEvents(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.track;A&&pr(A)}unbindEvents(){this.element&&pr(this.element),this.unbindTrackEvents(),S.off(K.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!1}handleElementEvent(A){switch(A.type){case fA.PLAYING:Lt()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(fA.PLAYING),this._interval&&(nn.clearTask(this._interval),this._interval=-1);break;case fA.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(fA.ENDED);break;case fA.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(fA.PAUSE);break;case fA.ERROR:if(this.element&&this.element.error){this.handlePaused(fA.ERROR);let{code:e,message:o}=this.element.error;this._log.error("".concat(this.kind," ").concat(this._log.isLocal?"local":"remote"," MediaError code: ").concat(e," message: ").concat(o," userAgent: ").concat(navigator.userAgent)),Jo.uploadEvent({log:"stat-".concat(this.kind,"-").concat(oa.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),oT||iT?this.emit(mi.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case fA.LOADEDDATA:this.kind===fA.VIDEO&&this.emit(mi.LOADED_DATA);break;case fA.LOADEDMETADATA:this.kind===fA.VIDEO&&this.emit(mi.LOADED_META_DATA);break;case fA.LOADSTART:this.emit(mi.LOAD_START)}}replayByRecreateMediaStream(A){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),Jo.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),ct.addSuccessEvent({key:this.kind===fA.AUDIO?506700:516700})}).catch(()=>{var e;this._log.error("replayByRecreateMediaStream failed"),Jo.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),ct.addFailedEvent({key:this.kind===fA.AUDIO?506700:516700,error:(e=this.element)==null?void 0:e.error}),this.emit(mi.ERROR,A)})}doReplayByRecreateMediaStream(A){return this._log.warn("delay ".concat(A,"ms to recreate mediaStream")),new Promise((e,o)=>{AC(A).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var n,a,I;this._log.warn("element onerror ".concat((a=(n=this.element)==null?void 0:n.error)==null?void 0:a.code," fired after recreated mediaStream")),o((I=this.element)==null?void 0:I.error)}),AC(5e3).then(()=>{var n,a;(!this.isPlaying||(n=this.element)!=null&&n.error)&&o((a=this.element)==null?void 0:a.error),e()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(A){return DA(this,null,function*(){let e=A.type;switch(this.options.enableLogTrackState&&this._log[e===fA.UNMUTE?"info":"warn"]("track ".concat(e)),e){case fA.ENDED:this.handleStopped(fA.ENDED);break;case fA.MUTE:this.handlePaused(fA.MUTE);break;case fA.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"),yield this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(fA.UNMUTE))}})}handlePlaying(A){var e;return this._log.debug("handlePlaying",A),(e=this._playSuccessResolve)==null||e.call(this,A),A}handlePaused(A){return this._log.debug("handlePaused",A),A}handleStopped(A){return this._log.debug("handleStopped",A),A}getElement(){return this.element}};G(rC,"PlayerEvent",mi),vt([nB({settings:{retries:2,timeout:0},onError(A,e,o,n){n[0]=(n[0]||1e3)+1e3,e()}})],rC.prototype,"doReplayByRecreateMediaStream"),vt([is([],"PLAYING",{sync:!0,success(A){this.emit(mi.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:A})}})],rC.prototype,"handlePlaying"),vt([is("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(A){this.emit(mi.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:A})}})],rC.prototype,"handlePaused"),vt([is([],"STOPPED",{sync:!0,success(A){this.emit(mi.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:A})}})],rC.prototype,"handleStopped");var aB="trtc_autoplay",YT="".concat(aB,"_mask"),Dm="".concat(aB,"_wrapper"),ym="".concat(aB,"_header"),Rm="".concat(aB,"_content"),GM="".concat(aB,"_action_wrapper"),J="".concat(aB,"_question"),x="".concat(aB,"_collapse"),oA="".concat(aB,"_action_confirm"),uA="".concat(aB,"_detail"),FA="#2473E8",zA="dialog",$A="".concat(zA,"-show"),ne="".concat(zA,"-1"),De="".concat(zA,"-2"),le=!1,We=!1,Lt=()=>We,Pt="".concat($C,"/").concat(rl()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),uo="
").concat(rl()?"其他方案?":"Any other solution?",""),Br="".concat(rl()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(uo):"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. ".concat(uo)),Nn=class{constructor(){if(G(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),G(this,"_dialogNode",null),G(this,"_bodyPosition",""),G(this,"_showDetail",!1),G(this,"_isCollapseClicked",!1),G(this,"_isQuestionClicked",!1),rl()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!le){let A=document.createElement("style");A.innerHTML=".".concat(YT,"{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;}.").concat(YT," div:not(.").concat(GM,"){display:block !important;}.").concat(Dm,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(Dm," a{color:").concat(FA,";}.").concat(ym,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(Rm,"{margin:8px 0;}.").concat(GM,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(x,"{margin-right:auto;cursor:pointer}.").concat(J,"{height:100%;line-height:16px;cursor:pointer;}.").concat(oA,"{margin-left:8px;color:#fff;background:").concat(FA,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(oA,":hover{opacity:0.9;}.").concat(x,",.").concat(oA,",.").concat(Rm,",.").concat(J,"{font-size:14px;}@media screen and (max-width:750px){.").concat(Dm,"{width:80vw;}}"),document.head.appendChild(A),le=!0}this.addDiaLog()}createDiaLog(){let A=document.createElement("template");A.innerHTML='
").concat(location.host,"
").concat(this.content,"
").trim();let e=document.createElement("button");e.className=oA,e.innerText=rl()?"恢复播放":"Resume",e.onclick=this.onConfirm.bind(this);let o=document.createElement("div");o.className=J,o.innerHTML=` + `],{type:"application/javascript"}))),hc.sharedWorker.onmessage=o=>{var n;if(o.data.type==="tick"){let a=hc.workerTasks.get(o.data.taskId);a&&(hc.isBreakLoop(a)?((n=hc.sharedWorker)==null||n.postMessage({type:"stop",taskId:a.taskID}),hc.workerTasks.delete(a.taskID)):(a.callback(),a.loopCount+=1))}}),hc.workerTasks.set(e.taskID,e),hc.sharedWorker.postMessage({taskId:e.taskID,delay:e.delay,type:"start"})}static timeout(e){let o=()=>{if(e.callback(),e.loopCount+=1,!hc.isBreakLoop(e))return e.timeoutID=setTimeout(o,e.delay)};return e.timeoutID=setTimeout(o,e.delay)}static ric(e){let o,n=ki(),a=()=>{if(o=ki()-n,o>=e.delay&&(n=ki()-Math.floor(o%e.delay),e.callback(),e.loopCount+=1),!hc.isBreakLoop(e))return e.ricID=JT(a,{timeout:e.delay})};return e.ricID=JT(a,{timeout:e.delay})}static raf(e){let o,n=ki(),a=()=>document.hidden&&e.backgroundTask?(o=ki()-n,n=ki(),e.callback(),e.loopCount+=1,hc.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(a,e.delay-Math.floor(o%e.delay))):(o=ki()-n,o>=e.delay&&(n=ki()-Math.floor(o%e.delay),e.callback(),e.loopCount+=1),hc.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(a));if(e.rafID=requestAnimationFrame(a),e.backgroundTask){let I=()=>{if(document.hidden){let c=ki()-n;c>=e.delay?a():e.timeoutID=setTimeout(a,e.delay-c)}};document.addEventListener("visibilitychange",I),e.onVisibilitychange=I,document.hidden&&I()}return e.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;let{intervalID:o,timeoutID:n,rafID:a,ricID:I,onVisibilitychange:c}=this.taskMap.get(e);return o&&clearInterval(o),n&&clearTimeout(n),a&&qQ&&qQ(a),I&&qs(I),c&&document.removeEventListener("visibilitychange",c),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.hasTask(e.taskID)||e.count!==0&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};G(Wh,"taskMap",new Map),G(Wh,"currentTaskID",1),G(Wh,"sharedWorker",null),G(Wh,"workerTasks",new Map);var nn=Wh,mi={LOAD_START:fA.LOADSTART,LOADED_DATA:fA.LOADEDDATA,LOADED_META_DATA:fA.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:fA.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:fA.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:fA.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"},HT={};XC(HT,{create:()=>nE,remove:()=>pr});var rB=new WeakMap;function nE(A,e){rB.has(A)||rB.set(A,[]);let o=rB.get(A),n={add:(a,I)=>("addEventListener"in e?(o.push(e.removeEventListener.bind(e,a,I)),e.addEventListener(a,I)):(o.push(e.off.bind(e,a,I)),e.on(a,I)),n)};return n}function pr(A){let e=rB.get(A);e&&(e.forEach(o=>o()),rB.delete(A))}var Jo=new class{constructor(){G(this,"_roomIdMap",new Map),G(this,"_configs"),typeof registerProcessor>"u"&&(this._configs={sdkAppId:"",userId:"",version:ol,env:au.QCLOUD,browserVersion:hu.name+hu.version,ua:navigator.userAgent})}setConfig(A){let{sdkAppId:e,env:o,userId:n,roomId:a}=A;e!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(e)),this._configs.env=o,this._configs.userId=n,this._roomIdMap.set(n,String(a))}logSuccessEvent(A){bQ||!nA.isAbleToUpload||this._configs.env===au.QCLOUD&&this.uploadEventToKibana(fi(bt({},A),{result:"success"}))}logFailedEvent(A){if(bQ||!nA.isAbleToUpload)return;let{eventType:e,code:o,error:n,userId:a}=A,I={roomId:this._roomIdMap.get(a||this._configs.userId),userId:a,eventType:e,result:"failed",code:o||n?.extraCode||n?.code||Ge.UNKNOWN};this._configs.env===au.QCLOUD&&this.uploadEventToKibana(fi(bt({},I),{error:n}))}uploadEventToKibana(A){let e="stat-".concat(A.eventType,"-").concat(A.result);(A.eventType==="delta-join"||A.eventType==="delta-leave"||A.eventType==="delta-publish")&&(e="".concat(A.eventType,":").concat(A.delta)),this.uploadEvent({log:e,userId:A.userId}),A.result==="failed"&&(e="stat-".concat(A.eventType,"-").concat(A.result,"-").concat(A.code),this.uploadEvent({log:e,userId:A.userId,error:A.error}))}uploadEvent(A){let{log:e,userId:o,error:n}=A,a={timestamp:eO(),sdkAppId:this._configs.sdkAppId,userId:o||this._configs.userId,version:ol,log:e};n&&(a.errorInfo=n.message,n.stack&&(a.errorInfo+=` +`.concat(n.stack)));let I=lA.enable?lu(a,2002,Number(this._configs.sdkAppId)):JSON.stringify(a);this.sendRequest(fh(this._configs.sdkAppId,Xg.LOG),I)}sendRequest(A,e){setTimeout(()=>Cu({url:A,body:e,priority:"low"}).catch(()=>{}),2e3)}},oC=new WeakMap;function nB(A){let{settings:e={retries:5,timeout:2e3},onError:o,onRetrying:n,onRetryFailed:a}=A;return function(I,c,u){let d=Zf({retryFunction:u.value,settings:e,onError(R){let{error:k,retry:_,reject:Z,retryFuncArgs:iA}=R;var cA;o?o.call(this,k,()=>{var TA;(TA=oC.get(I))!=null&&TA.has(c)?_():Z(k)},Z,iA):(cA=oC.get(I))!=null&&cA.has(c)?_():Z(k)},onRetrying(R,k){var _;SQ(n)&&n.call(this,R,k),(_=oC.get(I))!=null&&_.has(c)&&(oC.get(I).get(c).stopRetry=k)},onRetryFailed:a});return u.value=function(){let R=oC.get(I);for(var k=arguments.length,_=new Array(k),Z=0;Z{var iA;return(iA=oC.get(I))==null?void 0:iA.delete(c)})},u}}function _M(A){let{fnName:e,callback:o,validateArgs:n=!0}=A;return function(a,I,c){let u=c.value;return c.value=function(){for(var d,R,k=arguments.length,_=new Array(k),Z=0;ZIe===JA)){TA=!1;break}}TA&&(o&&o.apply(this,_),iA&&iA(),(R=oC.get(a))==null||R.delete(e))}return u.apply(this,_)},c}}var rC=class extends Uo{constructor(A,e){super(A.id,"".concat(e,"-player")),this.options=A,this.kind=e,G(this,"id"),G(this,"element",null),G(this,"track"),G(this,"url"),G(this,"attr"),G(this,"mode"),G(this,"muted"),G(this,"_log"),G(this,"isPausedByUserCall",!1),G(this,"_pausedRetryCount"),G(this,"_isElementPlayingFired",!1),G(this,"_interval"),G(this,"_delayDestroyTimeoutId",0),G(this,"_playSuccessResolve"),G(this,"_isReplayByRecreateMediaStreamCalled",!1),G(this,"isPlayCalled",!1),G(this,"isInAutoPlayFailedState",!1),G(this,"isBindAutoPlayEvent",!1),this.id=A.id,this._log=A.log,this.track=A.track,this.muted=A.muted,this._pausedRetryCount=DQ,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(e,"-player ").concat(this.id))}get isPlaying(){var A;return this._state==="PLAYING"&&((A=this.element)==null?void 0:A.paused)===!1}get isPaused(){var A;return this._state==="PAUSED"||((A=this.element)==null?void 0:A.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(A){this.attr=A}setUrl(A){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),A!==this.url&&(this.url=A,A!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=A))}play(){return DA(this,null,function*(){if(!this.isPlaying)try{this.isPlayCalled=!0,this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((A,e)=>{this._playSuccessResolve=A,this.element.play().then(A,e)})}catch(A){let e=Wi({key:Mi.PLAY_FAILED,data:{media:this.kind,error:A}});if(this._log.warn(A),e.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new Ct({code:Ge.PLAY_NOT_ALLOWED,message:e})}})}stop(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;var e;this.isPlayCalled=!1,this.isPausedByUserCall=!1,this._isElementPlayingFired=!1,this.unbindEvents(),A>0&&!_Q?this._delayDestroyTimeoutId||((e=this.element)==null||e.remove(),this._log.info("destroy element after 3 * ".concat(A)),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*A)):this.destroyElement(),this.handleStopped(fA.ENDED),this._interval>0&&nn.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 A;(A=this.element)==null||A.pause()}resume(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this.isPausedByUserCall=!1,this.doResume(A)}doResume(){return this._log.info("resume"),this.isPausedByUserCall||this.isPlaying?Promise.resolve():KO?this.replay():this.play().catch(()=>{})}setMuted(A){this.element&&(this.element.muted=A),this.muted=A}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let A=this.handleElementEvent.bind(this);return nE(this.element,this.element).add(fA.PLAYING,A).add(fA.ENDED,A).add(fA.PAUSE,A).add(fA.ERROR,A).add(fA.LOADSTART,A).add(fA.LOADEDDATA,A).add(fA.LOADEDMETADATA,A)}}bindTrackEvents(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.track;if(A){let e=this.handleTrackEvent.bind(this);HT?.create(A,A).add(fA.ENDED,e).add(fA.MUTE,e).add(fA.UNMUTE,e),A.readyState===fA.ENDED&&this.handleTrackEvent({type:fA.ENDED}),A.muted&&this.handleTrackEvent({type:fA.MUTE})}}bindAutoPlayEvent(){this.isBindAutoPlayEvent||(this._log.warn("bindAutoPlayEvent"),S.on(K.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!0)}unbindTrackEvents(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.track;A&&pr(A)}unbindEvents(){this.element&&pr(this.element),this.unbindTrackEvents(),S.off(K.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!1}handleElementEvent(A){switch(A.type){case fA.PLAYING:Lt()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(fA.PLAYING),this._interval&&(nn.clearTask(this._interval),this._interval=-1);break;case fA.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(fA.ENDED);break;case fA.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(fA.PAUSE);break;case fA.ERROR:if(this.element&&this.element.error){this.handlePaused(fA.ERROR);let{code:e,message:o}=this.element.error;this._log.error("".concat(this.kind," ").concat(this._log.isLocal?"local":"remote"," MediaError code: ").concat(e," message: ").concat(o," userAgent: ").concat(navigator.userAgent)),Jo.uploadEvent({log:"stat-".concat(this.kind,"-").concat(oa.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),sT||aT?this.emit(mi.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case fA.LOADEDDATA:this.kind===fA.VIDEO&&this.emit(mi.LOADED_DATA);break;case fA.LOADEDMETADATA:this.kind===fA.VIDEO&&this.emit(mi.LOADED_META_DATA);break;case fA.LOADSTART:this.emit(mi.LOAD_START)}}replayByRecreateMediaStream(A){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),Jo.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),ct.addSuccessEvent({key:this.kind===fA.AUDIO?506700:516700})}).catch(()=>{var e;this._log.error("replayByRecreateMediaStream failed"),Jo.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),ct.addFailedEvent({key:this.kind===fA.AUDIO?506700:516700,error:(e=this.element)==null?void 0:e.error}),this.emit(mi.ERROR,A)})}doReplayByRecreateMediaStream(A){return this._log.warn("delay ".concat(A,"ms to recreate mediaStream")),new Promise((e,o)=>{AC(A).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var n,a,I;this._log.warn("element onerror ".concat((a=(n=this.element)==null?void 0:n.error)==null?void 0:a.code," fired after recreated mediaStream")),o((I=this.element)==null?void 0:I.error)}),AC(5e3).then(()=>{var n,a;(!this.isPlaying||(n=this.element)!=null&&n.error)&&o((a=this.element)==null?void 0:a.error),e()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(A){return DA(this,null,function*(){let e=A.type;switch(this.options.enableLogTrackState&&this._log[e===fA.UNMUTE?"info":"warn"]("track ".concat(e)),e){case fA.ENDED:this.handleStopped(fA.ENDED);break;case fA.MUTE:this.handlePaused(fA.MUTE);break;case fA.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"),yield this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(fA.UNMUTE))}})}handlePlaying(A){var e;return this._log.debug("handlePlaying",A),(e=this._playSuccessResolve)==null||e.call(this,A),A}handlePaused(A){return this._log.debug("handlePaused",A),A}handleStopped(A){return this._log.debug("handleStopped",A),A}getElement(){return this.element}};G(rC,"PlayerEvent",mi),vt([nB({settings:{retries:2,timeout:0},onError(A,e,o,n){n[0]=(n[0]||1e3)+1e3,e()}})],rC.prototype,"doReplayByRecreateMediaStream"),vt([is([],"PLAYING",{sync:!0,success(A){this.emit(mi.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:A})}})],rC.prototype,"handlePlaying"),vt([is("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(A){this.emit(mi.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:A})}})],rC.prototype,"handlePaused"),vt([is([],"STOPPED",{sync:!0,success(A){this.emit(mi.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:A})}})],rC.prototype,"handleStopped");var aB="trtc_autoplay",VT="".concat(aB,"_mask"),wm="".concat(aB,"_wrapper"),Sm="".concat(aB,"_header"),vm="".concat(aB,"_content"),bM="".concat(aB,"_action_wrapper"),J="".concat(aB,"_question"),x="".concat(aB,"_collapse"),oA="".concat(aB,"_action_confirm"),uA="".concat(aB,"_detail"),FA="#2473E8",zA="dialog",$A="".concat(zA,"-show"),ne="".concat(zA,"-1"),De="".concat(zA,"-2"),le=!1,We=!1,Lt=()=>We,Pt="".concat($C,"/").concat(nl()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),uo="
").concat(nl()?"其他方案?":"Any other solution?",""),Br="".concat(nl()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(uo):"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. ".concat(uo)),Nn=class{constructor(){if(G(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),G(this,"_dialogNode",null),G(this,"_bodyPosition",""),G(this,"_showDetail",!1),G(this,"_isCollapseClicked",!1),G(this,"_isQuestionClicked",!1),nl()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!le){let A=document.createElement("style");A.innerHTML=".".concat(VT,"{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;}.").concat(VT," div:not(.").concat(bM,"){display:block !important;}.").concat(wm,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(wm," a{color:").concat(FA,";}.").concat(Sm,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(vm,"{margin:8px 0;}.").concat(bM,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(x,"{margin-right:auto;cursor:pointer}.").concat(J,"{height:100%;line-height:16px;cursor:pointer;}.").concat(oA,"{margin-left:8px;color:#fff;background:").concat(FA,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(oA,":hover{opacity:0.9;}.").concat(x,",.").concat(oA,",.").concat(vm,",.").concat(J,"{font-size:14px;}@media screen and (max-width:750px){.").concat(wm,"{width:80vw;}}"),document.head.appendChild(A),le=!0}this.addDiaLog()}createDiaLog(){let A=document.createElement("template");A.innerHTML='
").concat(location.host,"
").concat(this.content,"
").trim();let e=document.createElement("button");e.className=oA,e.innerText=nl()?"恢复播放":"Resume",e.onclick=this.onConfirm.bind(this);let o=document.createElement("div");o.className=J,o.innerHTML=` - `,o.onclick=this.onQuestionClick.bind(this);let n=document.createElement("div");n.className=x,n.innerText="".concat(rl()?"详情 >":"Detail >"),n.onclick=this.onCollapseClick.bind(this);let a=A.content.firstChild,I=a.querySelector(".".concat(GM));return I.appendChild(n),I.appendChild(o),I.appendChild(e),a}addDiaLog(){Lt()||(We=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(Dm)).onclick=A=>A.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",nA.info("show autoplay dialog"),Jo.uploadEvent({log:$A}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,We=!1),Ss=null}onConfirm(){nA.warn("confirm clicked, try resume stream"),S.emit(K.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let A=this._dialogNode.querySelector(".".concat(uA));A.style.visibility="".concat(this._showDetail?"hidden":"visible"),A.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||Jo.uploadEvent({log:ne}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Pt,"_blank"),this._isQuestionClicked||Jo.uploadEvent({log:De}),this._isQuestionClicked=!0}},Ss=null;function nC(){Ss||(Ss=new Nn)}var Mt,wi=class jZ extends rC{constructor(e){super(e,fA.VIDEO),G(this,"stat",{}),G(this,"_calculateTimeout",-1),G(this,"viewMirror",!1),G(this,"objectFit","cover"),G(this,"container"),G(this,"canvas"),G(this,"shouldRenderAlpha",!1),G(this,"_preSize",{width:0,height:0}),G(this,"posterImg"),G(this,"pipWindow"),G(this,"enterPIPPromise"),G(this,"_originContainerPosition"),G(this,"_isResettingSrcObject",!1),G(this,"_wrapper",null),G(this,"_useWrapper",!1),G(this,"_isFirstFrameRenderEmitted",!1),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,Ee(e.viewMirror)||(this.viewMirror=e.viewMirror),Ee(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(){let e=document.createElement(fA.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id","video_".concat(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,ra&&(e.poster="data:,"),this._appendToWrapper(),this.bindElementEvents(),this.calculateStat(),this._bindFirstFrameRenderEvent(e)}_bindFirstFrameRenderEvent(e){let o=()=>{if(this._isFirstFrameRenderEmitted)return;this._isFirstFrameRenderEmitted=!0;let n=e.videoWidth||0,a=e.videoHeight||0;this._log.info("first frame render: ".concat(n,"x").concat(a)),this.emit(mi.FIRST_FRAME_RENDER,{width:n,height:a})};typeof e.requestVideoFrameCallback=="function"?e.requestVideoFrameCallback(o):e.addEventListener("loadeddata",o,{once:!0})}get styleAttribute(){let e=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&&(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){let o=this._getOrCreateWrapper();o.insertBefore(this.elementToRender,o.firstChild)}else this.container.appendChild(this.elementToRender),this._cleanupWrapper()}setContainer(e){if(this.container===e)return;let o=this._wrapper,n=this.container;this.container=e,this._pausedRetryCount=pQ,this.track&&this.elementToRender&&this._appendToWrapper(),o&&n&&n!==this.container&&o.isConnected&&o.children.length===0&&o.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){let o=e??this.elementToRender;if(this.container&&o)if(this._useWrapper){let n=this._getOrCreateWrapper();n.insertBefore(o,n.firstChild)}else this.container.appendChild(o)}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),this.handleFullscreenChange=this.handleFullscreenChange.bind(this),this.handleVolumeChange=this.handleVolumeChange.bind(this),e&&e.add(fA.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(fA.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(fA.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener(fA.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 o;return e.type===fA.MUTE&&((o=this.stat)!=null&&o.fps&&(this.stat.fps=0),this.isFullscreen()&&this.resetSrcObjectToReplay()),super.handleTrackEvent(e)}handleFullscreenChange(){this.isFullscreen()?(this._log.info("enter fullscreen"),this.emit(mi.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(mi.LEAVE_FULL_SCREEN))}handleVolumeChange(){var e;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(mi.VOLUME_CHANGE,{muted:(e=this.element)==null?void 0:e.muted})}handleElementEvent(e){var o,n,a,I,c,u;if(this.mode===2)return;super.handleElementEvent(e);let d=e.type,R=this.isPictureInPicture(),k=this.isFullscreen(),_=e.isTrusted&&(R&&Ma||k);if(d===fA.PLAYING&&_&&!this._isResettingSrcObject&&(this._log.warn("user resume in ".concat(k?"fullscreen":"pip")),this.emit(mi.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),d===fA.PAUSE&&(_&&(this._log.warn("user pause in ".concat(k?"fullscreen":"pip")),this.emit(mi.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)),AC(500).then(()=>{var Z;(Z=this.container)!=null&&Z.isConnected&&(this._pausedRetryCount=pQ,this._log.info("view container ".concat(this.container.id," is in dom, reset pausedRetryCount")))})),this._pausedRetryCount>0&&!Lt()&&!this.isPausedByUserCall&&!_&&(this._log.info("[".concat(pQ-this._pausedRetryCount+1,"/").concat(pQ,"] ").concat(this.kind," player auto resume when paused")),this.doResume(),this._pausedRetryCount--),Ea&&!_&&(this._interval=nn.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 Z=this.element.style.transform;d===fA.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=Z.replace("scaleX(-1)",""):d===fA.LEAVE_PICTURE_IN_PICTURE&&!Z.includes("scaleX")&&(this.element.style.transform="".concat(Z," scaleX(-1)"))}d===fA.RESIZE&&(this._preSize.height!==((o=this.element)==null?void 0:o.videoHeight)||this._preSize.width!==((n=this.element)==null?void 0:n.videoWidth))&&(this._log.info("video size changed to ".concat((a=this.element)==null?void 0:a.videoWidth,"x").concat((I=this.element)==null?void 0:I.videoHeight)),this._preSize.height=((c=this.element)==null?void 0:c.videoHeight)||0,this._preSize.width=((u=this.element)==null?void 0:u.videoWidth)||0,this.emit(mi.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height})),d===fA.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(mi.LEAVE_PICTURE_IN_PICTURE)),d===fA.ENTER_PICTURE_IN_PICTURE&&this.emit(mi.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){ra&&Gh&&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){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;var n,a;this.canvas!==e&&((n=this.canvas)==null||n.remove(),e?.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?o:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((a=this.element)==null||a.remove(),this._appendToWrapper(e)):this.element&&this._appendToWrapper(this.element))}setAttr(e){let o=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);o.style=Object.assign({width:"100%",height:"100%"},o.style),super.setAttr(o)}get mirror(){return this.viewMirror}setRect(e,o){this.elementToRender&&(this.elementToRender.style.width="".concat(e,"px"),this.elementToRender.style.height="".concat(o,"px"))}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(e)),this.objectFit=e}setPoster(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[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,!o||!Ma&&!Yr))return n();if(e==="")return this.removePosterImg(),n();if(this.posterImg)return n();let a=document.createElement("img");a.src=e;let I=window.getComputedStyle(this.element),c=I.objectFit||this.objectFit,u=1;if(this._useWrapper){let d=parseInt(I.zIndex,10);isNaN(d)||(u=d+1)}a.style.cssText=this._useWrapper?"grid-area:1/1;z-index:".concat(u,";width:100%;height:100%;object-fit:").concat(c,";"):"position:absolute;top:0;left:0;width:100%;height:100%;object-fit:".concat(c,";"),a.onload=()=>DA(this,null,function*(){try{a.decode&&(yield a.decode()),this.container&&!this._useWrapper&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=a;let d=this._useWrapper?this._wrapper:this.container;d?.appendChild(a),jf()&&al<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(d){this._log.warn("decode poster image error",d)}return n()}),a.onerror=()=>(this._log.warn("load poster image error"),n())})}removePosterImg(){this.posterImg&&(jf()&&al<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),!this._useWrapper&&this.container&&!Ee(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"))}pause(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return DA(this,null,function*(){zg(jZ.prototype,this,"pause").call(this),!this.isPictureInPicture()&&!this.hasPoster&&(Gh||e&&(Yr||Ma))&&(yield this.setPoster(this.getVideoFrame(),!0))})}resume(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return super.resume(e).then(()=>{var o;(this.posterImg||(o=this.element)!=null&&o.poster)&&this.setPoster("",!0)})}doResume(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this.isPaused&&e&&this.element&&this.track&&Gh&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;var o;this.isPictureInPicture()&&this.exitPictureInPicture().catch(n=>{}),this.isFullscreen()&&this.exitFullscreen().catch(n=>{}),this.element&&(this.element.removeEventListener(fA.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),(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(e){if(Ee(e?.isLiveStream)||this.setLiveMode(e.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(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(mi.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"";let 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(YQ()&&this.element&&this._calculateTimeout<0){let e=0,o=null,n=(a,I)=>{this.stat.width=I.width,this.stat.height=I.height,o&&(this.stat.fps=Math.round((I.presentedFrames-o.presentedFrames)/(a-e)*1e3)),e=a,o=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)}}enterFullscreen(){return DA(this,null,function*(){let e=this.elementToRender;if(!e)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");if(Ea&&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(e.requestFullscreen)yield e.requestFullscreen();else if(e.webkitRequestFullscreen)yield e.webkitRequestFullscreen();else if(e.webkitEnterFullscreen)yield e.webkitEnterFullscreen();else if(e.mozRequestFullScreen)yield e.mozRequestFullScreen();else{if(!e.msRequestFullscreen)throw new Error("Fullscreen API not supported");yield e.msRequestFullscreen()}this._log.info("entered fullscreen mode")}catch(o){throw this._log.error("failed to enter fullscreen:",o),o}})}exitFullscreen(){return DA(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(e){throw this._log.error("failed to exit fullscreen:",e),e}})}isFullscreen(){let e=this.elementToRender;return!!e&&(this.element&&this.element.webkitDisplayingFullscreen?!this.isPictureInPicture():(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===e)}toggleFullscreen(){return DA(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return DA(this,null,function*(){this.enterPIPPromise=this._enterPictureInPicture();try{return yield this.enterPIPPromise}finally{delete this.enterPIPPromise}})}_enterPictureInPicture(){return DA(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:e}=this;if(e.requestPictureInPicture){this._log.info("requestPictureInPicture");let o=yield e.requestPictureInPicture();return this.pipWindow=o,this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),this._appendToWrapper(this.element)),o}if(e.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield 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}})}exitPictureInPicture(){return DA(this,null,function*(){var e;try{if(!this.isPictureInPicture())return;if(delete this.pipWindow,document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this.elementToRender===this.canvas&&((e=this.element)==null||e.remove(),this._pausedRetryCount=pQ,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:e}=this;return document.pictureInPictureElement?document.pictureInPictureElement===e:!!e.webkitPresentationMode&&e.webkitPresentationMode==="picture-in-picture"}togglePictureInPicture(){return DA(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function Fa(A,e){return DA(this,null,function*(){if(!A.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield A.audioWorklet.addModule(e),nA.info("worklet addModule success")}catch(o){throw nA.info("worklet addModule catch error. ".concat(o.message)),o}})}typeof AudioContext<"u"?Mt=AudioContext:typeof webkitAudioContext<"u"?Mt=webkitAudioContext:typeof mozAudioContext<"u"&&(Mt=mozAudioContext);var fr,SI=1500,gl=-1,HQ=0,aE=-1,eI=!1,nx=0,kM=-1,PT=-1;(function A(){try{if(fr)return;(fr=new Mt({sampleRate:48e3})).onstatechange=()=>{nA.info("context state: ".concat(fr.state).concat(fr.state!=="running"?" visibilityState: ".concat(document.visibilityState):"")),_M()},clearTimeout(gl)}catch(e){nA.error("initAudioContext failed: ".concat(e," typeof AudioContextClass: ").concat(typeof Mt)),gl=setTimeout(A,1e3)}})();var _M=()=>{fr.state==="suspended"?(HQ=ki(),aE===-1&&(aE=setTimeout(()=>{fr.state==="suspended"&&(eI=!0,S.emit("155",{isSuspended:!0}))},SI)),JT(),document.addEventListener("click",_M)):fr.state==="interrupted"?JT():(HQ&&(ct.addNumber({key:507800,value:ki()-HQ,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),HQ=0),aE!==-1&&(clearTimeout(aE),aE=-1,eI&&(eI=!1,S.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",_M),document.removeEventListener("click",_M))},hq=0,pq=-1;function JT(){return new Promise((A,e)=>{if(fr.state==="running")return A();Date.now()-hq<1e3?(clearTimeout(pq),pq=setTimeout(()=>{hq=Date.now(),fr.resume().then(A,e)},1e3)):(clearTimeout(pq),hq=Date.now(),fr.resume().then(A,e))}).catch(A=>{nA.warn("context resume failed: ".concat(A)),document.addEventListener("visibilitychange",_M)})}document.addEventListener("click",_M);var tI=A=>fr,iI=class{constructor(A){this.name=A,G(this,"node"),G(this,"node2"),G(this,"pre",new Set),G(this,"next",new Set),G(this,"context"),G(this,"connectedNodes",new Set),G(this,"nextInputChannelMap",new Map),G(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(e=>e.channelCount=A)}setChannelCount(A,e){!A||A instanceof ScriptProcessorNode||(A.channelCountMode="explicit",A.channelCount=e||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 e;if(A!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=A,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(o){nA.error(o)}}setNode(A,e){var o;if(!this.node)try{(o=this.context)==null||o.addMixWeight(),this.node=A,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),ct.addSuccessEvent({key:502701})}catch(n){nA.error(n),ct.addFailedEvent({key:502701,error:n})}}deleteNode(){var A;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(A=this.context)==null||A.reduceMixWeight(),this.preNodeReconnect(),ct.addSuccessEvent({key:502702})}catch(e){nA.error(e),ct.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(A=>{A.node?A.reconnect():A.preNodeReconnect()})}connectNext(A){this.next.forEach(e=>{let o=this.nextInputChannelMap.get(e);A._connect(e.node,o)||e.connectNext(A)})}_connect(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return!(!this.node||!A)&&((this.node2||this.node).connect(A,0,e),this.connectedNodes.add(A),!0)}_disconnect(){this.connectedNodes.forEach(A=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(A)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return this.next.add(A),A.pre.add(this),this.nextInputChannelMap.set(A,e),A}},Q$=class extends iI{constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:256;super(),this.fftSize=A,G(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(),e=0,o=0,n="M".concat(e,",").concat(o);for(let a=0;a0&&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]}},dW=new WeakMap;function ax(A){try{let e=dW.get(A);if(e)return e;let o=tI();if(A instanceof HTMLAudioElement)e=o.createMediaElementSource(A);else{if(!(A instanceof MediaStreamTrack))return A;e=o.createMediaStreamSource(new MediaStream([A]))}return dW.set(A,e),e}catch(e){if(!(Yr&&e instanceof Error&&e.name==="NotSupportedError"))throw e;nA.warn(e)}}var sx=class XQ{constructor(e){G(this,"_volume",0),G(this,"_volumeDb",0),G(this,"_log"),G(this,"_scriptProcessorNode",null),G(this,"_audioWorkletNode",null),G(this,"_interval",200),G(this,"ready",this.preload());let{log:o}=e;this._log=o,S.on(K.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-XQ.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!XQ.workletReady){let e='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);';XQ.workletReady=Fa(XQ.audioContext,URL.createObjectURL(new Blob([e],{type:"application/javascript"})))}return XQ.workletReady.then(()=>this.initAudioWorklet()).catch(e=>(this._log.error("volumeMeter preload error: ".concat(e)),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(XQ.audioContext,"volume-meter");let e=!1;this._audioWorkletNode.port.onmessage=o=>{XQ.lastMessageTime=Date.now(),this._volume=o.data.volume||0,this._volumeDb=o.data.volumeDb||0,!e&&o.data.cacheLen&&o.data.outputLen&&(this._log.warn("worklet play success"),e=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(e){this._log.error("volumeMeter init audio worklet error: ".concat(e)),Jo.logFailedEvent({userId:this._log.userId,eventType:oa.LOAD_WORKLET,error:e}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=tI().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{XQ.lastMessageTime=Date.now();let o=e.inputBuffer.getChannelData(0),n=0;for(let a=0;a>2);A.copyTo(o,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:o},[o.buffer]),A.close()}}},gx=hW,h$=es(hg(),1),fW=A=>e=>e.deviceId===A,fq=class{constructor(A,e){G(this,"kind"),G(this,"type"),G(this,"devices",[]),this.kind=A,this.type=e}update(A,e){let o=A.filter(n=>n.kind==="".concat(this.kind).concat(this.type.toLocaleLowerCase()));this.devices.length===1&&HT(this.devices[0])||e&&(o.forEach(n=>{if(n.deviceId&&!this.devices.find(fW(n.deviceId))){let a="".concat(this.kind).concat(this.type,"Added");nA.warn("".concat(a,": ").concat(JSON.stringify(n))),e.emit(a,n)}}),this.devices.forEach(n=>{if(n.deviceId&&!o.find(fW(n.deviceId))){let a="".concat(this.kind).concat(this.type,"Removed");nA.warn("".concat(a,": ").concat(JSON.stringify(n))),e.emit(a,n)}})),this.devices=o}hasDevice(A){return!!this.devices.find(e=>e.deviceId===A)}},p$=class extends h$.EventEmitter{constructor(){super(),G(this,"audioInputs",new fq(fA.AUDIO,"Input")),G(this,"videoInputs",new fq(fA.VIDEO,"Input")),G(this,"audioOutputs",new fq(fA.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||nn.run("interval",()=>{this.update()},{delay:1e4}))}init(){Ix().then(A=>{this.audioInputs.update(A),this.videoInputs.update(A),this.audioOutputs.update(A)})}update(){return DA(this,arguments,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function*(){let o=yield Ix(e);return A.audioInputs.update(o,A),A.videoInputs.update(o,A),A.audioOutputs.update(o,A),A}()})}hasBlueTooth(){var A;if(1e3*((A=tI())==null?void 0:A.outputLatency)>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(o=>e.some(n=>o.label.toLowerCase().includes(n)))||this.audioInputs.devices.some(o=>e.some(n=>o.label.toLowerCase().includes(n)))}},vs=vR||SR?null:new p$;function HT(A){return A.deviceId===A.groupId&&A.groupId===""}function Ix(){return DA(this,arguments,function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function*(){if(wI()||!mT())return[];let e=yield navigator.mediaDevices.enumerateDevices();if(A!==0){let o={audio:!1,video:!1};if(e.forEach(n=>{HT(n)&&(n.kind===fA.AUDIO_INPUT?o.audio=!0:n.kind===fA.VIDEO_INPUT&&(o.video=!0))}),A===2&&(o.audio=!1),A===1&&(o.video=!1),o.audio||o.video){let n;try{n=yield navigator.mediaDevices.getUserMedia(o),o.audio&&JT()}catch(a){nA.debug("capture before getDevices failed: ",a)}e=yield navigator.mediaDevices.enumerateDevices(),n?.getTracks().forEach(a=>a.stop())}}return e.map((o,n)=>{let a={kind:o.kind,deviceId:o.deviceId,groupId:o.groupId,label:o.label||"".concat(o.kind,"_").concat(n)};return o.deviceId.length>0&&mq.add("".concat(o.deviceId,"_").concat(o.kind)),o.getCapabilities&&(a.getCapabilities=()=>o.getCapabilities()),a})}()})}function VQ(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return vs.update(A?1:0).then(e=>e.audioInputs.devices)}function qQ(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return vs.update(A?2:0).then(e=>e.videoInputs.devices)}var mW=!1;function Mm(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return DA(this,null,function*(){return(Ea||Ma)&&(A=!1),vs.update(A?1:0).then(e=>e.audioOutputs.devices)})}var mq=new Set;function DW(A,e){return DA(this,null,function*(){let o=(yield VQ()).find(n=>n.deviceId===bf);return!e&&o?.groupId===A||o?.groupId===A&&o.label===e})}var cx,f$=class extends uW{constructor(A){super(),this.log=A,G(this,"volumeMeter"),G(this,"volumeMeterAfter3A"),G(this,"volumeDestination"),G(this,"analyser",new Q$),this.volumeMeter=new pW({log:this.log}),this.volumeMeterAfter3A=new pW({log:this.log}),this.volumeDestination=new iI,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},Dq=class WZ extends rC{constructor(e){super(e,fA.AUDIO),G(this,"_outputDeviceId"),G(this,"_floatVolume",1),G(this,"_destination"),G(this,"pipeline"),G(this,"volumeMeterMode","worklet"),G(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new f$(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(($g==="15.2"||$g==="15.3"||$g==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");this._log.info("audio player initializeElement");let o=cx||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(hr(e)?e/100:this._floatVolume),o===cx&&(cx=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(mi.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return DA(this,null,function*(){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&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(tI().createAnalyser()),function(){DA(this,null,function*(){try{mW||(mW=!0,nA.info("speakers:".concat((yield Mm()).map(o=>" ".concat(o.deviceId.slice(0,8),": ").concat(o.label)))))}catch{}})}()}catch(o){throw this._log.warn("audio play error: ".concat(o)),kh($g,"18.7",!0)&&this.bindAutoPlayEvent(),o}return zg(WZ.prototype,this,"play").call(this)}})}stop(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.pipeline.destroy(),super.stop(e)}setVolume(e){this._floatVolume=e,this.element&&(this.element.volume=e)}setSinkId(e){return DA(this,null,function*(){var o,n;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(n=(o=this.element).setSinkId)==null?void 0:n.call(o,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()}},m$=class extends Dq{setTrack(A){this.track!==A&&(this.unbindTrackEvents(),this.track=A,this.emit(mi.MEDIA_TRACK_CHANGED,A),A&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([A]))))}},yW=class extends Dq{constructor(A){super(A),G(this,"_sourceElement"),G(this,"_output",new iI),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(tI().destination)}write(A){this.pipeline.volumeMeter.write(A)}setTrack(A){var e,o,n;((o=(e=this.element)==null?void 0:e.error)==null?void 0:o.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==A&&(this.unbindTrackEvents(),this.track=A,this.emit(mi.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=((n=A.getSettings())==null?void 0:n.channelCount)||1,this.pipeline.replaceSource(A)):this.pipeline.source.deleteNode())}setVolume(A){var e;let o=A<=1&&!jf();if(this._floatVolume!==A||!(o&&((e=this.element)==null?void 0:e.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(jf()){if(!this.enableVolumeControlInIOS)return;(function(){if(!Ea||PT!==-1)return;let n=()=>{ki()-nx<500||(fr&&fr.state==="running"&&fr.currentTime===kM&&(nA.warn("context is fake running, auto resume"),fr.suspend().catch(a=>{nA.warn("context suspend failed: ".concat(a))})),kM=fr.currentTime,nx=ki())};PT=setInterval(()=>{n()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&n()})})()}if(Yr&&!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=tI().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),pr(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(n=>{this.emit(mi.AUTOPLAY_FAILED,n)}))}}stop(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.pipeline.destroy();let e=this._sourceElement||this.element;e&&TQ&&(cx=e),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(A)}},yq=class extends Uo{constructor(A){let{userId:e,sdkAppId:o,mediaType:n,room:a,PlayerClass:I=n===1?yW:wi}=A;var c;super(),G(this,"id",hA()),G(this,"userId",""),G(this,"isRemote"),G(this,"mediaType"),G(this,"room"),G(this,"user"),G(this,"_log"),G(this,"_inputTrack"),G(this,"_outputTrack"),G(this,"isPlayCalled"),G(this,"container",null),G(this,"player"),G(this,"subVideoPlayerMap"),G(this,"muted",!1),G(this,"abortCtrl"),G(this,"objectFit","cover"),G(this,"mirror"),G(this,"rotation"),G(this,"isScreen",!1),G(this,"manager"),G(this,"trackSettings"),G(this,"isFirstVideoFrameEmitted",!1),this.userId=e||"",this.mediaType=n,this._log=nA.createLogger({parent:a?.getLogger(),id:"".concat(this.kind[0],"t"),userId:(c=a||this.room)==null?void 0:c.userId,remoteUserId:this instanceof ZT?void 0:this.userId,sdkAppId:o,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof ZT}),this.player=new I({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:a?.enableVolumeControlInIOS}),this.player.on(mi.PLAYER_STATE_CHANGED,u=>{if(S.emit(K.PLAYER_STATE_CHANGED,bt({track:this},u)),this.emit("player-state-changed",u),u.state==="PLAYING"&&this.room){let d=!0;for(let{remoteAudioTrack:R,remoteVideoTrack:k,remoteAuxiliaryTrack:_}of[...this.room.remotePublishedUserMap.values()])if(R.isAvailable&&!R.player.isPlaying||k.isAvailable&&!k.player.isPlaying||_.isAvailable&&!_.player.isPlaying){d=!1;break}d&&Lt()&&Ss&&Ss.deleteDialog()}}),this.kind===fA.VIDEO&&(this.player.on(mi.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(mi.LOADED_DATA),S.emit(K.VIDEO_LOADED_DATA,{track:this})}),this.player.on(mi.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(mi.LOADED_META_DATA)}),this.player.on(mi.MEDIA_TRACK_CHANGED,u=>{var d;(d=this.subVideoPlayerMap)==null||d.forEach(R=>R.setTrack(u))}),this.player.on(mi.RESIZE,u=>{this.emitFirstVideoFrameEvent(mi.RESIZE),this.emit("video-size-changed",bt({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},u))}),this.player.on(mi.FIRST_FRAME_RENDER,u=>{this.emit("first-frame-render",fi(bt({},u),{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(mi.ERROR,this.onPlayerError.bind(this)),this.player.on(mi.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||nA}get kind(){return this.mediaType===1?fA.AUDIO:fA.VIDEO}get isAudio(){return this.kind===fA.AUDIO}get strMediaType(){return this.mediaType===4?fA.VIDEO:this.mediaType===2?fA.SCREEN:fA.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,e){return DA(this,null,function*(){let o=Aa(A)?A[0]:A;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(e))),e&&!Ee(e.muted)&&this.setPlayerMute(e.muted),e&&!Ee(e.objectFit)&&(this.objectFit=e.objectFit),void(this.player instanceof wi&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(Aa(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))),Aa(A)&&A.length>=1&&(yield this.playSubContainer(A.slice(1),e))));if(e&&!Ee(e.muted)?this.setPlayerMute(e.muted):(!this.isRemote||this.kind===fA.VIDEO)&&this.setPlayerMute(!0),e&&!Ee(e.objectFit)&&(this.objectFit=e.objectFit),this.player instanceof wi&&(Ee(e?.isLiveStream)||this.player.setLiveMode(e.isLiveStream),this.player.setObjectFit(this.objectFit),e&&!Ee(e.poster)&&this.player.setPoster(e.poster)),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof wi&&this.player.setContainer(o)),S.emit(K.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info("play with options: ".concat(JSON.stringify(e)));try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(e),Aa(A)&&A.length>1&&(yield this.playSubContainer(A.slice(1),e))}catch(n){throw this.handleAutoPlayFailed(n),n}}else this.log.info("play has not mediaTrack, abort")})}setMirror(A,e){if(this.isScreen||this.kind!==fA.VIDEO||Ee(A)||A===this.mirror)return;this.mirror=A;let o=this.player;e&&(o=e);let n=this.manager;if(rn(this.mirror))return o.setViewMirror(this.mirror),void(!this.isRemote&&n&&(n.mirror=!1));switch(this.mirror){case"view":n&&(n.mirror=!1),o.setViewMirror(!0);break;case"publish":n&&(n.mirror=!0),o.setViewMirror(!0);break;case"both":n&&(n.mirror=!0),o.setViewMirror(!1)}}playSubContainer(A,e){return DA(this,null,function*(){if(!this._outputTrack||this.kind===fA.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((n,a)=>{var I;A.find(c=>a===c)||(n.stop(),(I=this.subVideoPlayerMap)==null||I.delete(a))});for(let[n,a]of A.entries()){let I=this.subVideoPlayerMap.get(a);I?e&&(Ee(e.objectFit)||I.setObjectFit(e.objectFit)):this.subVideoPlayerMap.set(a,new wi({id:this.userId||this.id,track:this.playerMediaTrack,container:a,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(n+1)})}))}let o=[...this.subVideoPlayerMap.values()];for(let n of o)n.setViewMirror(this.player.mirror),yield n.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(HN(this)&&!A?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop()}),this.container=null)}resume(){return DA(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),S.emit(A?K.TRACK_MUTED:K.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){nE(A,A).add(fA.MUTE,this.onTrackMuted).add(fA.UNMUTE,this.onTrackUnmuted).add(fA.ENDED,this.onTrackEnded),A.muted&&this.onTrackMuted(),A.readyState===fA.ENDED&&this.onTrackEnded()}uninstallTrackEvent(A){pr(A)}setInputMediaStreamTrack(A){var e;let o=this._inputTrack;if(A!==o)return this._inputTrack=A,this.trackSettings=(e=A.getSettings)==null?void 0:e.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 e;let o=this._outputTrack;this instanceof Ru&&DQ(o)||A!==o&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",A.label):this.log.info("setOutputMediaStreamTrack",(e=A.getSettings)==null?void 0:e.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 e,o;if(this.isPlayCalled){if(A){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch(n=>this.handleAutoPlayFailed(n)),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return HN(this)&&this.isAudio&&(e=this.user)!=null&&e.muteState.hasAudio&&(o=this.user)!=null&&o.muteState.audioMuted?void 0:(this.player.stop(HN(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 DA(this,null,function*(){var e;this.log.warn("handleAutoPlayFailed",A);let o=()=>{this.resume().then(()=>{document.removeEventListener("click",o,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((SQ||Eu)&&(yield AC(100),(e=this.player)!=null&&e.isPlaying))return;nC()}else document.addEventListener("click",o,!0);S.once(K.LOCAL_TRACK_CAPTURE_SUCCESS,n=>{let{track:a}=n;a.kind==="audio"&&Lt()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&o()}),this.emit("error",A)})}getVideoFrame(){return this.player instanceof wi?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(A){var e,o,n;if(this.isFirstVideoFrameEmitted)return;let a=(e=this.mediaTrack)==null?void 0:e.getSettings(),I=a?.width||((o=this.player.element)==null?void 0:o.videoWidth)||0,c=a?.height||((n=this.player.element)==null?void 0:n.videoHeight)||0;A===mi.RESIZE&&!I&&!c||A===mi.LOADED_META_DATA&&!I&&!c||(A===mi.LOADED_DATA&&!I&&!c&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,gu(this.rotation)&&([I,c]=[c,I]),this.emit("first-video-frame",{width:I,height:c,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"))}};vt([is([],Uo.INIT,{sync:!0})],yq.prototype,"_toInitState");var D$=Object.prototype.hasOwnProperty,KQ=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(Cc(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 e in A)if(D$.call(A,e))return!1;return!0}return!1},y$=Kf({retryFunction:function(A){return DA(this,null,function*(){let e=function(I){return{audio:R$(I),video:M$(I)}}(A);nA.info("getUserMedia with constraints: ".concat(JSON.stringify(e)));let o=[],n=[],a=["label","deviceId","groupId"];if(e.audio&&(o=yield VQ(),nA.info("microphones: ".concat(nl(o.map(I=>fi(bt({},I),{groupId:I.groupId.substring(0,8)})),{keysToInclude:a})))),e.video&&(n=yield qQ(),nA.info("cameras: ".concat(nl(n,{keysToInclude:a}))),!rn(e.video)&&e.video.facingMode==="user"&&!e.video.deviceId)){let I=n.filter(c=>!c.label.includes("infrared")).find(c=>c.label.includes("facing front"));I&&(e.video.deviceId=I.deviceId,nA.info("exclude infrared camera: ".concat(JSON.stringify(e))))}try{let I=yield navigator.mediaDevices.getUserMedia(e);return $O&&I.getTracks().forEach(c=>{var u;let d=c.getCapabilities();nA.info("".concat(c.kind," capabilities: ").concat(nl(d,{keysToInclude:RN}))),!Ee(A.echoCancellation)&&((u=d.echoCancellation)==null?void 0:u.indexOf(A.echoCancellation))===-1&&nA.warn("Invalid argument for 'echoCancellation'. Expected one of [".concat(JSON.stringify(d.echoCancellation),"], but received '").concat(A.echoCancellation,"'"))}),e.audio&&JT(),I}catch(I){let{message:c}=I;throw I.name==="NotFoundError"&&(A.video&&n&&n.length===0&&(c=Wi({key:Mi.CAMERA_NOT_FOUND})),A.audio&&o&&o.length===0&&(c=Wi({key:Mi.MICROPHONE_NOT_FOUND}))),new Ct({code:Ge.INITIALIZE_FAILED,name:I.name,message:c,constraint:I.constraint})}})},settings:{retries:3,timeout:500},onError:A=>{let{error:e,retry:o,reject:n,retryFuncArgs:a,retriedCount:I}=A,c=I+1;e.name==="NotReadableError"||e.name==="OverconstrainedError"||e.name==="AbortError"?(c===1?(a[0].video&&(a[0].maxResolution=!1,(!Ma||a[0].width*a[0].height<=2073600)&&a[0].frameRate&&(a[0].frameRate=a[0].frameRate>10?10:5)),a[0].retryWhenExactFailed&&a[0].useExactDeviceId&&(a[0].useExactDeviceId=!1)):c===2?a[0].useDeviceIdOnly=!0:c===3&&!a[0].useExactDeviceId&&(a[0].useTrueAsConstraint=!0),o()):n(e),a[0].microphoneId&&RW(a[0].microphoneId,!1),a[0].cameraId&&RW(a[0].cameraId,!0)},onRetrying:A=>{nA.warn("getUserMedia NotReadableError observed, retrying [".concat(A,"/3]"))},onRetryFailed:A=>{Jo.logFailedEvent({eventType:oa.GET_USER_MEDIA_RETRY,error:A})},onRetrySuccess:A=>{Jo.logSuccessEvent({eventType:oa.GET_USER_MEDIA_RETRY}),Jo.uploadEvent({log:"stat-".concat(oa.GET_USER_MEDIA_RETRY,"-success-").concat(A)})}});function RW(A,e){return DA(this,null,function*(){let o=(e?yield qQ():yield VQ()).find(n=>n.deviceId===A);o&&$n(o.getCapabilities)&&nA.warn(nl(o.getCapabilities(),{keysToInclude:RN}))})}function R$(A){if(!A.audio)return!1;if(A.useTrueAsConstraint)return!0;let e={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:A.sampleRate};return!KQ(A.microphoneId)&&(e.deviceId=A.useExactDeviceId?{exact:A.microphoneId}:A.microphoneId,A.useDeviceIdOnly)?e:(hr(A.channelCount)&&(e.channelCount=A.channelCount),(rn(A.echoCancellation)||A.echoCancellation==="remote-only"||A.echoCancellation==="all")&&(e.echoCancellation=A.echoCancellation),rn(A.noiseSuppression)&&!A.noiseSuppression&&(e.noiseSuppression=!1),rn(A.autoGainControl)&&!A.autoGainControl&&(e.autoGainControl=!1),!!KQ(e)||e)}function M$(A){if(!A.video)return!1;if(A.useTrueAsConstraint)return!0;let{maxResolution:e=!0}=A,o={};return A.cameraId?o.deviceId=A.useExactDeviceId?{exact:A.cameraId}:A.cameraId:A.facingMode&&(o.facingMode=A.facingMode),A.useDeviceIdOnly&&!KQ(o)?o:(A.width&&(o.width={ideal:A.width},e&&!Yr&&(o.width.max=A.width)),A.height&&(o.height={ideal:A.height},e&&!Yr&&(o.height.max=A.height)),Yr&&lu&&A.width&&A.height&&A.width*A.height<101376&&(o.width=A.width,o.height=A.height),A.frameRate&&(o.frameRate=A.frameRate),!!KQ(o)||o)}var w$=y$;function MW(A){return Dn((e,o)=>function(){for(var n=arguments.length,a=new Array(n),I=0;Ifunction(){for(var n=arguments.length,a=new Array(n),I=0;Ifunction(){for(var n=arguments.length,a=new Array(n),I=0;I{let A=!1,e=document.visibilityState;return()=>{document.visibilityState!==e&&nA.info("visibility change: ".concat(document.visibilityState)),!A&&(document.addEventListener("visibilitychange",()=>{nA.info("visibility change: ".concat(document.visibilityState)),e=document.visibilityState}),A=!0)}})(),v$=0,SW=class{constructor(A){G(this,"log"),G(this,"isRunning",!1),G(this,"queue",[]);let e="fq".concat(++v$);A&&(e+="|".concat(A)),this.log=nA.createLogger({id:e})}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var o,n;let a=bt({},A),I=new Promise((c,u)=>{a.resolve=c,a.reject=u});return a.promise=I,e?this.length<=1?this.queue.push(a):(n=(o=this.lastQueueItem)==null?void 0:o.promise)==null||n.then(a.resolve,a.reject):this.queue.push(a),this.log.debug("push ".concat(this.length),A.funcName,A.args),this.isRunning||this.callNext(),I}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:e,context:o,resolve:n,reject:a,funcName:I}=this.queue[0];this.log.debug("callNext",this.length,I,e),this.isRunning=!0,A.apply(o,e).then(n,a).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},Ex=new WeakMap,lx=new WeakMap;function VT(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return function(e,o,n){let a=n.value;return n.value=function(){let I=Ex.get(this)||new SW;for(var c=arguments.length,u=new Array(c),d=0;dd.push(Z)),(u=lx.get(this))==null||u.forEach(Z=>Z?.queue.forEach(iA=>d.push(iA))),d.forEach(Z=>{Z.reject(new Ct({code:Ge.API_CALL_ABORTED,message:A}))}),Ex.delete(this),lx.delete(this),a.apply(this,k)},n}}function Kh(A,e){return function(o,n,a){let I=a.value,c=u=>A(...u);return a.value=function(){for(var u=arguments.length,d=new Array(u),R=0;Rfunction(){let a=A;try{for(var I=arguments.length,c=new Array(I),u=0;u(e?ct.addSuccessEvent({key:a,cost:ki()-R}):ct.addSuccessEvent({key:a}),k)).catch(k=>{throw ct.addFailedEvent({key:a,error:k}),k}):(ct.addSuccessEvent({key:a}),d)}catch(d){throw ct.addFailedEvent({key:a,error:d}),d}})}var NW={};function la(){}XC(NW,{Events:()=>os,Inspect:()=>Wh,LastSink:()=>Cx,Sink:()=>Go,Subscribe:()=>Bx,TimeoutError:()=>kW,audit:()=>CAA,bindCallback:()=>Z$,bindNodeCallback:()=>X$,buffer:()=>O$,bufferCount:()=>U$,bufferTime:()=>FAA,call:()=>TW,catchError:()=>XW,combineLatest:()=>LW,concat:()=>k$,concatMap:()=>wAA,concatMapTo:()=>SAA,count:()=>eAA,create:()=>Vr,debounce:()=>uAA,debounceTime:()=>QAA,defer:()=>FW,delay:()=>UAA,deliver:()=>ko,dispose:()=>Rq,elementAt:()=>dAA,empty:()=>Nq,every:()=>DAA,exhaustMap:()=>kAA,exhaustMapTo:()=>_AA,expand:()=>xAA,filter:()=>Sm,find:()=>hAA,findIndex:()=>pAA,first:()=>fAA,fromAnimationFrame:()=>W$,fromArray:()=>J$,fromEvent:()=>Ln,fromEventPattern:()=>H$,fromFetch:()=>V$,fromIterable:()=>q$,fromPromise:()=>YW,fromReadableStream:()=>j$,fromReader:()=>K$,groupBy:()=>bAA,identity:()=>N$,ignoreElements:()=>rAA,iif:()=>b$,inspect:()=>GW,interval:()=>xW,last:()=>mAA,map:()=>Gq,mapTo:()=>RAA,max:()=>tAA,merge:()=>Mq,mergeMap:()=>NAA,mergeMapTo:()=>TAA,min:()=>iAA,never:()=>$$,nothing:()=>la,of:()=>P$,pairwise:()=>yAA,pipe:()=>Jn,race:()=>bW,range:()=>z$,reduce:()=>PW,retry:()=>HAA,scan:()=>VW,setAsapScheduler:()=>Y$,share:()=>qT,shareReplay:()=>_$,skip:()=>sAA,skipUntil:()=>gAA,skipWhile:()=>Tq,startWith:()=>wq,subject:()=>yu,subscribe:()=>Ks,sum:()=>oAA,switchMap:()=>Qx,switchMapTo:()=>hx,take:()=>LM,takeLast:()=>aAA,takeUntil:()=>Qc,takeWhile:()=>nAA,tap:()=>kq,throttle:()=>EAA,throwError:()=>AAA,timeInterval:()=>LAA,timeout:()=>JAA,timer:()=>vq,toPromise:()=>YAA,toReadableStream:()=>PAA,withLatestFrom:()=>F$,zip:()=>L$});var TW=A=>A(),N$=A=>A;function Rq(){this.dispose()}var GW=()=>typeof __FASTRX_DEVTOOLS__<"u",T$=1,Wh=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(A){let e=new G$(A,this,this.streamId++);return os.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},Cx=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=la,this.error=la,this.next=la,this.dispose=la,this.subscribe=la,this.doDefer()}subscribe(A){return A instanceof Wh?A.subscribe(this):A(this),this}get bindSubscribe(){return A=>this.subscribe(A)}doDefer(){this.defers.forEach(TW),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}},Go=class extends Cx{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)}},Bx=class extends Cx{constructor(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:la,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:la,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:la;if(super(),this._next=e,this._error=o,this._complete=n,this.then=la,A instanceof Wh){let a={toString:()=>"subscribe",id:0,source:A};this.defer(()=>{os.defer(a,0)}),os.create(a),os.pipe(a),this.sourceId=a.id,this.subscribe(A),os.subscribe({id:a.id,end:!0}),e==la?this._next=I=>os.next(a,0,I):this.next=I=>{os.next(a,0,I),e(I)},n==la?this._complete=()=>os.complete(a,0):this.complete=()=>{this.dispose(),os.complete(a,0),n()},o==la?this._error=I=>os.complete(a,0,I):this.error=I=>{this.dispose(),os.complete(a,0,I),o(I)}}else this.subscribe(A)}next(A){this._next(A)}complete(){this.dispose(),this._complete()}error(A){this.dispose(),this._error(A)}};function Jn(A){for(var e=arguments.length,o=new Array(e>1?e-1:0),n=1;nI(a),A)}function Vr(A,e,o){if(GW()){let n=Object.defineProperties(Object.setPrototypeOf(A,Wh.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:e,writable:!0,configurable:!0},args:{value:o,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});os.create(n);for(let a=0;a{if(I instanceof Wh){let c=Vr(u=>{let d=new A(u,...n);d.sourceId=c.id,d.subscribe(I)},e,arguments);return c.source=I,os.pipe(c),c}return c=>I(new A(c,...n))}}}function zh(A,e){window.postMessage({source:"fastrx-devtools-backend",payload:{event:A,payload:e}})}var G$=class extends Go{constructor(A,e,o){super(A),this.source=e,this.id=o,this.sourceId=A.sourceId,this.defer(()=>{os.defer(this.source,this.id)})}next(A){os.next(this.source,this.id,A),this.sink.next(A)}complete(){os.complete(this.source,this.id),this.sink.complete()}error(A){os.complete(this.source,this.id,A),this.sink.error(A)}},os={addSource(A,e){zh("addSource",{id:A.id,name:A.toString(),source:{id:e.id,name:e.toString()}})},next(A,e,o){zh("next",{id:A.id,streamId:e,data:o&&o.toString()})},subscribe(A,e){let{id:o,end:n}=A;zh("subscribe",{id:o,end:n,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(A,e,o){zh("complete",{id:A.id,streamId:e,err:o?o.toString():null})},defer(A,e){zh("defer",{id:A.id,streamId:e})},pipe(A){zh("pipe",{name:A.toString(),id:A.id,source:{id:A.source.id,name:A.source.toString()}})},update(A){zh("update",{id:A.id,name:A.toString()})},create(A){A.id||(A.id=T$++),zh("create",{name:A.toString(),id:A.id})}},kW=class extends Error{constructor(A){super("timeout after ".concat(A,"ms")),this.timeout=A}},_W=class extends Cx{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(e=>e.next(A))}complete(){this.sinks.forEach(A=>A.complete()),this.sinks.clear()}error(A){this.sinks.forEach(e=>e.error(A)),this.sinks.clear()}};function qT(){return A=>{let e=new _W(A);if(A instanceof Wh){let o=Vr(n=>{e.add(n)},"share",arguments);return e.sourceId=o.id,o.source=A,os.pipe(o),o}return Vr(e.add.bind(e),"share",arguments)}}function Mq(){for(var A=arguments.length,e=new Array(A),o=0;o{let a=new Go(n),I=e.length;a.complete=()=>{--I===0&&n.complete()},e.forEach(a.bindSubscribe)},"merge",arguments)}function bW(){for(var A=arguments.length,e=new Array(A),o=0;o{let a=new Map;e.forEach(I=>{let c=new Go(n);a.set(I,c),c.complete=()=>{a.delete(I),a.size===0?n.complete():c.dispose()},c.next=u=>{a.delete(I),a.forEach(d=>d.dispose()),c.resetNext(),c.resetComplete(),c.next(u)}}),e.forEach(I=>a.get(I).subscribe(I))},"race",arguments)}function k$(){for(var A=arguments.length,e=new Array(A),o=0;o{let a=0,I=e.length,c=new Go(n);c.complete=()=>{a{let o=new _W(e),n=[];return o.next=function(a){n.push(a),n.length>A&&n.shift(),this.sinks.forEach(I=>I.next(a))},Vr(a=>{a.defer(()=>o.remove(a)),n.forEach(I=>a.next(I)),o.add(a)},"shareReplay",arguments)}}function b$(A,e,o){return Vr(n=>A()?e(n):o(n),"iif",arguments)}function LW(){for(var A=arguments.length,e=new Array(A),o=0;o{let a=e.length,I=a,c=a,u=new Array(a),d=()=>{--c===0&&n.complete()};e.forEach((R,k)=>{let _=new Go(n);_.next=Z=>{I--,_.next=iA=>{u[k]=iA,I===0&&n.next(u)},_.next(Z)},_.complete=d,_.subscribe(R)})},"combineLatest",arguments)}function L$(){for(var A=arguments.length,e=new Array(A),o=0;o{let a=e.length,I=a,c=new Array(a),u=()=>{--I===0&&n.complete()};e.forEach((d,R)=>{let k=new Go(n),_=[];c[R]=_,k.next=Z=>{_.push(Z),c.every(iA=>iA.length)&&n.next(c.map(iA=>iA.shift()))},k.complete=u,k.subscribe(d)})},"zip",arguments)}function wq(){for(var A=arguments.length,e=new Array(A),o=0;oVr(function(a){let I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,c=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length;for(;I1?o-1:0),a=1;athis.buffer=I,e.complete=la,e.subscribe(LW(...n))}next(A){this.buffer&&this.sink.next([A,...this.buffer])}},"withLatestFrom"),U$=ko(class extends Go{constructor(A,e,o){super(A),this.bufferSize=e,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(e=>{e.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"),O$=ko(class extends Go{constructor(A,e){super(A),this.buffer=[];let o=new Go(A);o.next=n=>{A.next(this.buffer),this.buffer=[]},o.complete=la,o.subscribe(e)}next(A){this.buffer.push(A)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),x$=function(A,e,o,n){return new(o||(o=Promise))(function(a,I){function c(R){try{d(n.next(R))}catch(k){I(k)}}function u(R){try{d(n.throw(R))}catch(k){I(k)}}function d(R){R.done?a(R.value):function(k){return k instanceof o?k:new o(function(_){_(k)})}(R.value).then(c,u)}d((n=n.apply(A,[])).next())})};function yu(A){let e=arguments,o=qT()(Vr(n=>{o.next=a=>n.next(a),o.complete=()=>n.complete(),o.error=a=>n.error(a),A&&n.subscribe(A)},"subject",e));return o.next=la,o.complete=la,o.error=la,o}function FW(A){return Vr(e=>e.subscribe(A()),"defer",arguments)}var bM={promise:A=>{Promise.resolve().then(A)},setImmediate:typeof setImmediate<"u"?A=>setImmediate(A):null,setTimeout:A=>setTimeout(A,0)},Sq=typeof Promise<"u"?bM.promise:bM.setImmediate?bM.setImmediate:bM.setTimeout,UW=A=>e=>{Sq(()=>A(e))},Y$=A=>{typeof A=="function"?Sq=A:bM[A]&&(Sq=bM[A])},OW=A=>UW(e=>{for(let o=0;!e.disposed&&o{let o=0,n=setInterval(()=>e.next(o++),A);return e.defer(()=>{clearInterval(n)}),"interval"},"interval",arguments)}function vq(A,e){return Vr(o=>{let n=0,a=setTimeout(()=>{if(o.removeDefer(I),o.next(n++),e){let c=setInterval(()=>o.next(n++),e);o.defer(()=>{clearInterval(c)})}else o.complete()},A),I=()=>clearTimeout(a);o.defer(I)},"timer",arguments)}function ux(A,e){return o=>{let n=a=>o.next(a);o.defer(()=>e(n)),A(n)}}function H$(A,e){return Vr(ux(A,e),"fromEventPattern",arguments)}function Ln(A,e){if("on"in A&&"off"in A)return Vr(ux(o=>A.on(e,o),o=>A.off(e,o)),"fromEvent",arguments);if("addListener"in A&&"removeListener"in A)return Vr(ux(o=>A.addListener(e,o),o=>A.removeListener(e,o)),"fromEvent",arguments);if("addEventListener"in A)return Vr(ux(o=>A.addEventListener(e,o),o=>A.removeEventListener(e,o)),"fromEvent",arguments);throw"target is not a EventDispachter"}function YW(A){return Vr(e=>{A.then(o=>{e.next(o),e.complete()},e.error.bind(e))},"fromPromise",arguments)}function V$(A,e){return Vr(FW(()=>YW(fetch(A,e))),"fromFetch",arguments)}function q$(A){return Vr(UW(e=>{try{for(let o of A){if(e.disposed)return;e.next(o)}e.complete()}catch(o){e.error(o)}}),"fromIterable",arguments)}function K$(A){let e=o=>x$(this,void 0,void 0,function*(){try{if(o.disposed)return;let{done:n,value:a}=yield A.read();if(n)return void o.complete();o.next(a),e(o)}catch(n){o.error(n)}});return Vr(o=>{e(o)},"fromReader",arguments)}function j$(A){return Vr(e=>{let o=new AbortController,n=o.signal;e.defer(()=>o.abort("cancelled")),A.pipeTo(new WritableStream({write(a){e.next(a)},close(){e.complete()},abort(a){e.error(a)}}),{signal:n}).then(()=>e.complete(),a=>e.error(a))},"fromReadableStream",arguments)}function W$(){return Vr(A=>{let e=requestAnimationFrame(function o(n){A.disposed||(A.next(n),e=requestAnimationFrame(o))});A.defer(()=>cancelAnimationFrame(e))},"fromAnimationFrame",arguments)}function z$(A,e){return Vr(function(o){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:A,a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e+A;for(;n2?o-2:0),a=2;a{let c=n.concat(u=>(I.next(u),I.complete()));A.apply(e,c)},"bindCallback",arguments)}function X$(A,e){for(var o=arguments.length,n=new Array(o>2?o-2:0),a=2;a{let c=n.concat((u,d)=>u?I.error(u):(I.next(d),I.complete()));A.apply(e,c)},"bindNodeCallback",arguments)}function $$(){return Vr(()=>{},"never",arguments)}function AAA(A){return Vr(e=>e.error(A),"throwError",arguments)}function Nq(){return Vr(A=>A.complete(),"empty",arguments)}var KT=class extends Go{constructor(A,e,o){super(A),this.f=e;let n=()=>{this.sink.next(this.acc),this.sink.complete()};o===void 0?this.next=a=>{this.acc=a,this.complete=n,this.resetNext()}:(this.acc=o,this.complete=n)}next(A){this.acc=this.f(this.acc,A)}},PW=ko(KT,"reduce"),eAA=A=>ko(KT,"count")((e,o)=>A(o)?e+1:e,0),tAA=()=>ko(KT,"max")(Math.max),iAA=()=>ko(KT,"min")(Math.min),oAA=()=>ko(KT,"sum")((A,e)=>A+e,0),Sm=ko(class extends Go{constructor(A,e,o){super(A),this.filter=e,this.thisArg=o}next(A){this.filter.call(this.thisArg,A)&&this.sink.next(A)}},"filter"),rAA=ko(class extends Go{next(A){}},"ignoreElements"),LM=ko(class extends Go{constructor(A,e){super(A),this.count=e}next(A){this.sink.next(A),--this.count===0&&(this.doDefer(),this.complete())}},"take"),Qc=ko(class extends Go{constructor(A,e){super(A);let o=new Go(A);o.next=()=>{o.doDefer(),A.complete()},o.complete=Rq,o.subscribe(e)}},"takeUntil"),nAA=ko(class extends Go{constructor(A,e){super(A),this.f=e}next(A){this.f(A)?this.sink.next(A):(this.doDefer(),this.complete())}},"takeWhile"),aAA=A=>PW((e,o)=>(e.push(o),e.length>A&&e.shift(),e),[]),sAA=ko(class extends Go{constructor(A,e){super(A),this.count=e}next(A){--this.count===0&&(this.next=super.next)}},"skip"),gAA=ko(class extends Go{constructor(A,e){super(A),A.next=la;let o=new Go(A);o.next=()=>{o.doDefer(),A.resetNext()},o.complete=Rq,o.subscribe(e)}},"skipUntil"),Tq=ko(class extends Go{constructor(A,e){super(A),this.f=e}next(A){this.f(A)||(this.next=super.next,this.next(A))}},"skipWhile"),IAA={leading:!0,trailing:!1},cAA=class extends Go{constructor(A,e,o){super(A),this.durationSelector=e,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)}},JW=class extends Go{constructor(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:IAA;super(A),this.durationSelector=e,this.config=o,this._throttle=new cAA(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=la,this._throttle.complete(),super.complete()}},EAA=ko(JW,"throttle"),lAA={leading:!1,trailing:!0},CAA=A=>ko(JW,"audit")(A,lAA),BAA=class extends Go{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},HW=class extends Go{constructor(A,e){super(A),this.durationSelector=e,this._debounce=new BAA(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()}},uAA=ko(HW,"debounce"),QAA=A=>ko(HW,"debounceTime")(e=>vq(A)),dAA=ko(class extends Go{constructor(A,e,o){super(A),this.count=e,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"),hAA=A=>e=>LM(1)(Tq(o=>!A(o))(e)),pAA=ko(class extends Go{constructor(A,e){super(A),this.f=e,this.i=0}next(A){this.f(A)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},"findIndex"),fAA=ko(class extends Go{constructor(A,e,o){super(A),this.f=e,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"),mAA=ko(class extends Go{constructor(A,e,o){super(A),this.f=e,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"),DAA=ko(class extends Go{constructor(A,e){super(A),this.predicate=e,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"),VW=ko(class extends Go{constructor(A,e,o){super(A),this.f=e,o===void 0?this.next=n=>{this.acc=n,this.resetNext(),this.sink.next(this.acc)}:this.acc=o}next(A){this.sink.next(this.acc=this.f(this.acc,A))}},"scan"),yAA=ko(class extends Go{constructor(){super(...arguments),this.hasLast=!1}next(A){this.hasLast?this.sink.next([this.last,A]):this.hasLast=!0,this.last=A}},"pairwise"),qW=class extends Go{constructor(A,e,o){super(A),this.mapper=e,this.thisArg=o}next(A){super.next(this.mapper.call(this.thisArg,A))}},Gq=ko(qW,"map"),RAA=A=>ko(qW,"mapTo")(e=>A),jT=class extends Go{constructor(A,e,o){super(A),this.data=e,this.context=o}next(A){let e=this.context.combineResults;e?this.sink.next(e(this.data,A)):this.sink.next(A)}tryComplete(){this.context.resetComplete(),this.dispose()}},WT=class zZ extends Go{constructor(e,o,n){super(e),this.makeSource=o,this.combineResults=n,this.index=0}subInner(e,o){let n=this.currentSink=new o(this.sink,e,this);this.complete===zZ.prototype.complete&&(this.complete=this.tryComplete),n.complete=n.tryComplete,n.subscribe(this.makeSource(e,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},KW=class extends jT{},jW=class extends WT{next(A){this.subInner(A,KW),this.next=e=>{this.currentSink.dispose(),this.subInner(e,KW)}}},Qx=ko(jW,"switchMap");function dx(A){return(e,o)=>A(()=>e,o)}var hx=dx(ko(jW,"switchMapTo")),MAA=class extends jT{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},WW=class extends WT{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(),MAA),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},wAA=ko(WW,"concatMap"),SAA=dx(ko(WW,"concatMapTo")),vAA=class extends jT{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},zW=class extends WT{constructor(){super(...arguments),this.inners=new Set}next(A){this.subInner(A,vAA),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(A=>A.resetComplete()):this.dispose()}},NAA=ko(zW,"mergeMap"),TAA=dx(ko(zW,"mergeMapTo")),GAA=class extends jT{dispose(){this.context.resetNext(),super.dispose()}},ZW=class extends WT{next(A){this.next=la,this.subInner(A,GAA)}},kAA=ko(ZW,"exhaustMap"),_AA=dx(ko(ZW,"exhaustMapTo")),bAA=ko(class extends Go{constructor(A,e){super(A),this.f=e,this.groups=new Map}next(A){let e=this.f(A),o=this.groups.get(e);o===void 0&&(o=yu(),o.key=e,this.groups.set(e,o),super.next(o)),o.next(A)}complete(){this.groups.forEach(A=>A.complete()),super.complete()}error(A){this.groups.forEach(e=>e.error(A)),super.error(A)}},"groupBy"),LAA=ko(class extends Go{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"),FAA=ko(class extends Go{constructor(A,e){super(A),this.miniseconds=e,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"),UAA=ko(class extends Go{constructor(A,e){super(A),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(A){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:o,data:n}=e;super.next(n),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"),XW=ko(class extends Go{constructor(A,e){super(A),this.selector=e}error(A){this.dispose(),this.selector(A)(this.sink)}},"catchError"),OAA=class extends jT{tryComplete(){let A=this.context.inners.delete(this);super.dispose(),A&&this.context.checkComplete()}next(A){this.sink.next(A),this.context.expandValue(A)}},xAA=ko(class extends WT{constructor(A,e){super(A,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(A){this.sink.next(A),this.expandValue(A)}expandValue(A){let e=new OAA(this.sink,A,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.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"),YAA=()=>A=>new Promise((e,o)=>{let n;new Bx(A,a=>n=a,o,()=>e(n))}),PAA=()=>A=>{let e;return new ReadableStream({start(o){e=new Bx(A,o.enqueue.bind(o),o.error.bind(o),o.close.bind(o))},cancel(){e.dispose()}})},Ks=function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:la,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:la,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:la;return n=>new Bx(n,A,e,o)},kq=ko(class extends Go{constructor(A,e){super(A),e instanceof Function?this.next=o=>{e(o),A.next(o)}:(e.next&&(this.next=o=>{e.next(o),A.next(o)}),e.complete&&(this.complete=()=>{e.complete(),A.complete()}),e.error&&(this.error=o=>{e.error(o),A.error(o)}))}},"tap"),JAA=ko(class extends Go{constructor(A,e){super(A),this.timeout=e,this.id=setTimeout(()=>this.error(new kW(this.timeout)),this.timeout)}next(A){super.next(A),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),HAA=function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1/0;return e=>{if(e instanceof Wh){let o=Vr(n=>{let a=A,I=new Go(n);I.error=c=>{a-- >0?I.subscribe(e):n.error(c)},I.sourceId=o.id,I.subscribe(e)},"retry",[A]);return o.source=e,os.pipe(o),o}return o=>{let n=A,a=new Go(o);a.error=I=>{n-- >0?e(a):o.error(I)},e(a)}}},_q=(A=>(A[A.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",A[A.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",A))(_q||{}),zT=class ZZ extends yq{constructor(e,o){super({mediaType:e,PlayerClass:o}),G(this,"isRemote",!1),G(this,"deviceId"),G(this,"groupId",""),G(this,"label",""),G(this,"sourceTrack"),G(this,"enableAutoSwitchWhenRecapturing",!0),G(this,"_isRecapturing",!1),G(this,"_lastRecaptureTime",0),G(this,"_onMuteTimeoutId",-1),G(this,"_encodeCheckTimeoutId",-1),G(this,"recaptureMode",0),G(this,"profile"),G(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,o){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(fA.MUTE,this.onTrackMuted),e.addEventListener(fA.UNMUTE,this.onTrackUnmuted),e.addEventListener(fA.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===fA.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(fA.MUTE,this.onTrackMuted),e.removeEventListener(fA.UNMUTE,this.onTrackUnmuted),e.removeEventListener(fA.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return DA(this,null,function*(){var n,a;let I=this.sourceTrack;try{let c,u=ki();S.emit(K.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(c=new MediaStream,c.addTrack(e.customSource)):(o||(n=this.sourceTrack)==null||n.stop(),c=yield w$(e));let d=c.getTracks()[0];return yield this.setInputMediaStreamTrack(d),e.customSource||(this.sourceTrack=d,this.updateDeviceIdInUse(),this.listenDeviceChange()),S.emit(K.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:ki()-u,profile:this.profile,room:(a=this.manager)==null?void 0:a.room}),c}catch(c){throw S.emit(K.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:c}),this.log.error("getUserMedia error observed ".concat(c)),c}finally{o&&I?.stop()}})}setOutputMediaStreamTrack(e){var o;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(o=this.room)==null?void 0:o.replaceTrack(this)}get hasFlag(){var e,o;let n=mQ(((e=this.room)==null?void 0:e.localPublishFlag)||0,((o=this.room)==null?void 0:o.userId)||"");return this.mediaType===4&&n.hasVideo||this.mediaType===1&&n.hasAudio||this.mediaType===2&&n.hasAuxiliary}publish(e,o){return DA(this,null,function*(){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()),yield o,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((o,n)=>DA(this,null,function*(){var a,I,c,u,d;let R=()=>n(new Ct({code:Ge.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?o():((this.state===Uo.INIT||this.state==="ready")&&R(),Jn(Ln(e,"local-publish-flag-changed"),Sm(()=>this.hasFlag),Qc(Mq(Ln(this,Uo.INIT),Ln(this,"ready"))),Ks(o,n,R))),(c=(I=(a=this.room)==null?void 0:a.networkQuality)==null?void 0:I.hadRecentBadUplink)!=null&&c.call(I,2))return o();let k=e.heartbeatCount,_=((d=(u=this.mediaTrack)==null?void 0:u.stats)==null?void 0:d.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>DA(this,null,function*(){var Z,iA,cA,TA,JA,Ie,XA,Ft;if((cA=(iA=(Z=this.room)==null?void 0:Z.networkQuality)==null?void 0:iA.hadRecentBadUplink)!=null&&cA.call(iA,2)||e.heartbeatCount-k<3)return o();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((TA=this.mediaTrack)!=null&&TA.stats){let Nt=this.mediaTrack.stats.totalFrames||0;Nt-_===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",Nt)}let ie=this.kind===fA.AUDIO,ke=this.stat.bytesSent>0;if(ct[ke?"addSuccessEvent":"addFailedEvent"]({key:ie?503700:513702}),!ie){let Nt={H264:513704,H265:513705,VP8:513706}[((Ie=(JA=this.room)==null?void 0:JA.videoCodec)==null?void 0:Ie.toUpperCase())||"H264"];Nt&&ct[ke?"addSuccessEvent":"addFailedEvent"]({key:Nt})}if(!ke){if(ct.addEnum({key:ie?503701:513703,value:_Q()}),Jo.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(Qu()||bQ()),userId:this.userId}),this.log.warn(ie?"encode failed":"".concat((Ft=(XA=this.room)==null?void 0:XA.videoCodec)==null?void 0:Ft.toUpperCase()," encode failed")),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield AC(5e3),this.stat.bytesSent>0||this.hasFlag)))return o();this.emit("6",this),n(new Ct({message:"".concat(this.strMediaType," encode failed"),code:ie?Ge.AUDIO_ENCODE_FAILED:Ge.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),S.emit(K.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return DA(this,null,function*(){if(this.sourceTrack&&Jh){let{deviceId:e,groupId:o}=this.sourceTrack.getSettings(),{label:n}=this.sourceTrack;(yield function(a){return DA(this,arguments,function(I){let{newDeviceId:c,oldDeviceId:u,oldGroupId:d,oldLabel:R,kind:k}=I;return function*(){return c===u&&(k!==fA.AUDIO||c!==bf||(yield DW(d,R)))}()})}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=n,o&&(this.groupId=o),Ix().then(a=>{let I=a.find(c=>{let u=c.deviceId===e;return o&&(u=u&&c.groupId===o),u});I&&this.emit("2",I)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return!(!this.deviceId||!this.sourceTrack||this.kind===fA.AUDIO&&!function(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let n=o.label.toLocaleLowerCase();if(n.includes("mic")||n.includes("麦克风"))return!0;let a="".concat((o?.getSettings()||{}).deviceId,"_").concat(fA.AUDIO_INPUT);return!!mq.has(a)}(this.sourceTrack)||this.kind===fA.VIDEO&&!function(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let n=o.label.toLocaleLowerCase();if(n.includes("camera")||n.includes("webcam"))return!0;let a="".concat((o?.getSettings()||{}).deviceId,"_").concat(fA.VIDEO_INPUT);return!!mq.has(a)}(this.sourceTrack)||this._isRecapturing||e&&lu&&Ma)}onTrackMuted(){if(super.onTrackMuted(),S$(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTimethis.onTrackMuted(),Ff);this._onMuteTimeoutId=setTimeout(()=>DA(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((Ea||ra)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return DA(this,null,function*(){if(zg(ZZ.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTimethis.onTrackEnded(),Ff);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return DA(this,null,function*(){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let a=this.sourceTrack;o||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let I={useExactDeviceId:!0};if(e==="user"||e==="environment")I.facingMode=e;else{let c;(this.kind==="audio"?yield VQ():yield qQ()).find(u=>u.deviceId===e)&&(c=e),I.deviceId=c}return this.capture(I,o).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),S.emit(K.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(c=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(c.message)),this.emit("5",c),S.emit(K.LOCAL_TRACK_RECAPTURE,{track:this,error:c})}).finally(()=>{o&&a?.stop()})})}getRecoverCaptureDeviceId(){return DA(this,null,function*(){let e=this instanceof Ru;if(e&&this.facingMode)return this.facingMode;let{deviceId:o}=this;if(o){let n=(XT.get(o)||0)+1;if(XT.set(o,n),n>=3&&this.enableAutoSwitchWhenRecapturing){let a=e?(yield qQ()).find(I=>!XT.has(I.deviceId)):(yield VQ()).find(I=>!XT.has(I.deviceId));a&&(this.log.warn("".concat(o," capture fail ").concat(n," times, change new ").concat(a.deviceId)),o=a.deviceId)}}return o})}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),S.emit(K.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()}};vt([is(Uo.INIT,"ready",{ignoreError:!0,sync:!0})],zT.prototype,"setStateToReady"),vt([VT()],zT.prototype,"capture"),vt([is("ready","publish",{ignoreError:!0,success(){S.emit(K.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 e;(e=this.room)==null||e.localTracks.delete(this);let o="error",n=A instanceof Ct?A:A.cause instanceof Ct?A.cause:A,a=!1;n instanceof Ct&&(n.message.includes("timeout")?o="timeout":n.code===Ge.API_CALL_ABORTED&&(a=!0,o="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:o,error:n}),this.log[a?"info":"error"]("publish failed",n)}}),jh(521714,!1)],zT.prototype,"publish"),vt([Dn(A=>function(){return DA(this,null,function*(){let e=this.state==="publish"?"started":"starting";A.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:e,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),is([],"ready",{sync:!0})],zT.prototype,"unpublish");var ZT=zT,XT=new Map;S.on(K.SWITCH_DEVICE_SUCCESS,A=>{A.track.deviceId&&XT.delete(A.track.deviceId)});var vm=class mG extends ZT{constructor(e){super(1,m$),G(this,"mediaType",1),G(this,"volume",0),G(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),G(this,"playerMuted",!0),G(this,"pipeline"),G(this,"earMonitorGainNode",new iI),G(this,"_output",new iI),G(this,"codecPipeline",[]),G(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),G(this,"mixedAudioReferenceMap",new Map),G(this,"isAudioContextLongSuspended",!1),G(this,"after3aSilenceStartTime",0),G(this,"_micMuted",!1),G(this,"_volumeDetectionTrack",null),G(this,"_volumeDetectionSource",new iI),this.manager=e,this.pipeline=new QW(e),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),S.on(K.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return gx.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.isProcessEnabled)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){Ee(e)||(e!==0||this.after3aSilenceStartTime?e>0&&(this.after3aSilenceStartTime=0):this.after3aSilenceStartTime=ki())}setInputMediaStreamTrack(e){return DA(this,null,function*(){let o=this.trackSettings||{};ct.addEnum({key:501701,value:o.channelCount||0,useUV:!1}),ct.addEnum({key:501702,value:o.sampleRate||0,useUV:!1}),ct.addEnum({key:502700,value:0});let{sampleRate:n,channelCount:a}=o;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:n,channelCount:a}))),this.pipeline.source.channelCount=a||1,this.pipeline.replaceSource(e),yield zg(mG.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(e){return DA(this,arguments,function(o){var n=this;let{deviceId:a,customSource:I,useExactDeviceId:c=!0,retryWhenExactFailed:u}=o,d=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return function*(){let R=yield zg(mG.prototype,n,"capture").call(n,{video:!1,audio:!0,microphoneId:a,echoCancellation:n.profile.echoCancellation,autoGainControl:n.profile.autoGainControl,noiseSuppression:n.profile.noiseSuppression,sampleRate:n.profile.sampleRate,channelCount:n.profile.channelCount,useExactDeviceId:c,retryWhenExactFailed:u,customSource:I},d);return JT(),R}()})}switchDevice(e){return DA(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource&&(e!==bf||(yield DW(this.groupId,this.label))))return;try{this.log.info("switchDevice audio to: ".concat(e)),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),S.emit(K.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(){vs&&!vs.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&vs.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return DA(this,null,function*(){if(e.deviceId===this.deviceId){let o=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(_q[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(e))),this.recaptureMode===0){Ua(this.userId,{eventId:2003,param1:6,streamType:1});let n=yield VQ();n[0]?this.recapture(n[0].deviceId):o=!0}o&&vs.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(vs.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))}update3A(e){return DA(this,arguments,function(o){var n=this;let{echoCancellation:a,noiseSuppression:I,autoGainControl:c}=o;return function*(){let u=n.sourceTrack||n.mediaTrack;if(!u)return;let d=u.getConstraints(),R=!1;!Ee(a)&&a!==n.profile.echoCancellation&&(n.profile.echoCancellation=a,d.echoCancellation=a,R=!0),!Ee(I)&&I!==n.profile.noiseSuppression&&(n.profile.noiseSuppression=I,d.noiseSuppression=I,R=!0),!Ee(c)&&c!==n.profile.autoGainControl&&(n.profile.autoGainControl=c,d.autoGainControl=c,R=!0),R&&(Yr||Ma?yield u.applyConstraints(d).catch(k=>n._log.warn("update3A failed: ",k)):n.deviceId&&(yield n.recapture(n.deviceId,!0)))}()})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&ct.addEnum({key:502700,value:2})}setMute(e,o){var n;this._cleanupVolumeDetectionTrack(),e==="microphone"?(this._micMuted=!0,this.sourceTrack&&(this.sourceTrack.enabled=!1),o&&this._setupVolumeDetectionTrack(),((n=this.manager)==null?void 0:n.mixWeight)<=1?(this.muted=!0,this._inputTrack&&(this._inputTrack.enabled=!1),this._outputTrack&&(this._outputTrack.enabled=!1),this.emit("mute",this),S.emit(K.TRACK_MUTED,{track:this})):this._outputTrack&&(this._outputTrack.enabled=!0)):e===!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),S.emit(K.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),S.emit(K.TRACK_UNMUTED,{track:this}))}_setupVolumeDetectionTrack(){let e=this.sourceTrack||this.mediaTrack;if(!e)return;this._volumeDetectionTrack=e.clone(),this._volumeDetectionTrack.enabled=!0;let o=ax(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(e){super.setAudioVolume(0),Ea&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(tI().createGain()),this._output.setNode(tI().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!Ma&&!Ea)return this.update3A({echoCancellation:e})}addDenoiser(e){var o;tE<=92&&((o=this.trackSettings)==null?void 0:o.sampleRate)!==48e3?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(ct.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1))}mixAudioReference(e,o){if(this.mixedAudioReferenceMap.has(o))return;this.log.info("mixAudioReference() => ".concat(o));let n=ax(e);if(!n)return;let a=new iI,I=tI().createGain();I.gain.value=1;let c=new iI;a.pipeTo(c).pipeTo(this.pipeline.mixNode),a.setNode(n),c.setNode(I),this.mixedAudioReferenceMap.set(o,[a,c])}unMixAudioReference(e){let[o,n]=this.mixedAudioReferenceMap.get(e)||[];o&&(this.log.info("unMixAudioReference() => ".concat(e)),o.deleteNode(),n?.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,o){let[n,a]=this.mixedAudioReferenceMap.get(e)||[];a!=null&&a.node&&(a.node.gain.value=o/100,this.log.info("setAudioReferenceVolume() => ".concat(e," ").concat(a.node.gain.value)))}addAudioProcessor(e,o,n){this.pipeline.silentNode.setNode(n),this.pipeline.mixNode.setNode(o),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this._cleanupVolumeDetectionTrack(),this.mixedAudioReferenceMap.forEach(e=>{let[o,n]=e;o.deleteNode(),n.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),vs.off("audioInputAdded",this.handleMicrophoneAdded,this),vs.off("audioInputRemoved",this.handleMicrophoneRemoved,this),S.off(K.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return DA(this,null,function*(){try{yield zg(mG.prototype,this,"recapture").call(this,e,o)}catch(n){let a=(yield VQ()).find(I=>I.deviceId!==e);if(!a)throw n;yield zg(mG.prototype,this,"recapture").call(this,a.deviceId)}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((o,n)=>n?n({frame:o,ntp:gh()}):o,e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(e=>e)}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended(e){let{isSuspended:o}=e;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(TQ?"":", non-Safari"));let n=this.sourceTrack||this.mediaTrack;n&&this.setOutputMediaStreamTrack(n)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let o=this.sourceTrack||this.mediaTrack;o&&(e=o)}super.setOutputMediaStreamTrack(e)}};function px(A,e){return e+4<=A.byteLength&&A.getUint8(e)===0&&A.getUint8(e+1)===0&&A.getUint8(e+2)===0&&A.getUint8(e+3)===1?4:e+3<=A.byteLength&&A.getUint8(e)===0&&A.getUint8(e+1)===0&&A.getUint8(e+2)===1?3:0}function $W(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1],o=new DataView(A),n=[],a=0;for(;a0){c=_;break}let u=c===-1?o.byteLength:c,d=u-a,R=new ArrayBuffer(d),k=new DataView(R);for(let _=0;_1&&arguments[1]!==void 0&&arguments[1];this.dataView=A,this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let{seiPayloadStartIndex:A}=this,e=this.dataView.byteLength-2,o=[],n=0;for(let I=A;I<=e;I++){let c=this.dataView.getInt8(I);switch(c){case 0:case 1:case 2:case 3:n===2&&(o.push(3),n=0),c===0?n+=1:n=0,o.push(c);break;default:n=0,o.push(c)}}o.push(this.dataView.getInt8(this.dataView.byteLength-1));let a=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,A),...o]).buffer);this.dataView=a}removePreventionByte(){let{seiPayloadStartIndex:A}=this,e=this.dataView.byteLength-1,o=[],n=0;for(let I=A;I<=e;I++)switch(this.dataView.getInt8(I)){case 0:n++,o.push(this.dataView.getInt8(I));break;case 3:n!==2&&o.push(this.dataView.getInt8(I)),n=0;break;default:o.push(this.dataView.getInt8(I)),n=0}let a=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,A),...o]).buffer);this.dataView=a}get seiPayloadStartIndex(){let A=6;for(let e=6;e=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}},VAA=class{constructor(){G(this,"_seiMessageList",[]),G(this,"_smallSeiMessageList",[]),G(this,"_seiPayloadType",243)}encodeSEINalu(A){let e=A.byteLength,o=parseInt(String(e/255),10),n=e%255,a=[];a.push(0,0,0,1,6,this._seiPayloadType);for(let c=0;c0&&A.data.byteLength>0){let n=9-this.getNaluCount(A.data);if(n<=0)return 0;let a=o.splice(0,n).reverse().map(this.encodeSEINalu.bind(this)),I=a.reduce((k,_)=>k+_.dataView.byteLength,0),c=new ArrayBuffer(I+A.data.byteLength),u=new DataView(c),d=new DataView(A.data),R=0;for(let k=0;k1&&arguments[1]!==void 0?arguments[1]:4,wi),G(this,"profile",bt({},vf)),G(this,"avoidCropping",!1),G(this,"_scaleResolutionDownBy"),G(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0}),G(this,"small"),G(this,"isNeedToSetBandwidth"),G(this,"muteImage"),G(this,"manager"),G(this,"_seiCodec",new VAA),this.manager=e;let o=()=>{var n;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let a=ol(((n=this.room)==null?void 0:n.sdkAppId)||0)?uN:NR;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(a)),this.setProfile(fi(bt({},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(Jh&&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)}setMute(e){return DA(this,null,function*(){var o,n,a;if(Sr(e)){if(this.muteImage===e)return;yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),yield(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,zg($M.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(a=this.manager)==null?void 0:a.deleteWatermark("mute"),this.muteImage=void 0),zg($M.prototype,this,"setMute").call(this,e)})}capture(e){return DA(this,arguments,function(o){var n=this;let{deviceId:a,facingMode:I,useExactDeviceId:c=!0,customSource:u,retryWhenExactFailed:d=!0}=o;return function*(){let R={audio:!1,video:!0,facingMode:I||n.facingMode,cameraId:a,width:n.profile.width,height:n.profile.height,frameRate:n.profile.frameRate,useExactDeviceId:c,retryWhenExactFailed:d,customSource:u};if(R.facingMode==="environment"){let k=yield n.getDeviceIdWhenUsingBackCamera();k&&(R.cameraId=k)}return zg($M.prototype,n,"capture").call(n,R)}()})}setProfile(e){var o;let n=this.fallbackProfile(e);if(n.bitrate&&(this.isNeedToSetBandwidth=n.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(n);else{let a=ol(((o=this.room)==null?void 0:o.sdkAppId)||0)?uN:NR;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(a)),super.setProfile(fi(bt({},this.profile),{width:1920,height:1080}))}}applyProfile(){return DA(this,null,function*(){var e,o;if(!this.mediaTrack)return;let{width:n=0,height:a=0}=(this.sourceTrack||this.mediaTrack).getSettings(),I=n*a,c=this.settings,u=c.height!==this.profile.height||c.width!==this.profile.width||c.frameRate!==this.profile.frameRate;if(u&&(al===16&&this.deviceId?yield this.recapture(this.deviceId):(DQ(this.outMediaTrack)?yield(e=this.outMediaTrack)==null?void 0:e.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:d=0,height:R=0}=(this.sourceTrack||this.mediaTrack).getSettings(),k=d*R;return u&&k&&I&&k===I?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:fA.VIDEO,videoType:fA.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},o=this.sourceTrack||this.mediaTrack;return Jh&&o&&Object.assign(e,o.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:AM(this.settings,this.profile)}isAllowed2k4k(e){var o;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||((o=this.room.scheduleResult.trtcAutoConf)==null?void 0:o["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return DA(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let o={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?o.facingMode=e:o.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(o),S.emit(K.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 DA(this,null,function*(){let e;try{if(iT&&!Th&&Ax){let o=(yield qQ(!0)).map(a=>{var I;return fi(bt({},a),{capabilities:(I=a.getCapabilities)==null?void 0:I.call(a)})}).filter(a=>{var I,c;return(c=(I=a.capabilities)==null?void 0:I.facingMode)==null?void 0:c.includes("environment")}),n=o[0];o.forEach(a=>{var I,c,u,d;let{capabilities:R}=a;((I=R.width)!=null&&I.max&&(c=R.height)!=null&&c.max?R.width.max*R.height.max:0)>((u=n.capabilities.width)!=null&&u.max&&(d=n.capabilities.height)!=null&&d.max?n.capabilities.width.max*n.capabilities.height.max:0)&&(n=a)}),n!=null&&n.capabilities&&(this._log.info("use max resolution back camera",n),e=n.deviceId)}}catch(o){this._log.warn("get max res camera failed",o)}return e})}updateSmallConfig(e){return DA(this,null,function*(){var o,n;this._log.info("update small stream config: ".concat(JSON.stringify(e)));let a=!this.small;this.small=this.fallbackProfile(e,!0),yield(o=this.manager)==null?void 0:o.update(),a&&(yield(n=this.room)==null?void 0:n.enableSmall(!0)),this.log.info("update small stream config success")})}fallbackProfile(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1],n=e.width>e.height,a=bt({},e);return e.width*e.height<=19200&&ra&&Bc&&(this.log.warn("".concat(o?"small ":"","resolution is ").concat(e.width,"*").concat(e.height,", fallback to 240*180 for android chrome")),a.width=n?240:180,a.height=n?180:240,a.bitrate=Math.max(e.bitrate,150)),e.width*e.height>921600&&YO&&(a.width=n?1280:720,a.height=n?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),gT($g,"14.3")&&kh($g,"14.0",!0)&&this.on("7",()=>{let 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"))}),!o&&this.avoidCropping&&(Bc||Yr)&&!QM()&&e.width*e.height<=230400&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,a.width=1280,a.height=720,this.log.warn("capture 720p, scale: ".concat(this._scaleResolutionDownBy))),a}stopSmall(){var e,o;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(o=this.room)==null||o.enableSmall(!1))}listenDeviceChange(){vs&&!vs.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&vs.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return DA(this,null,function*(){if(e.deviceId===this.deviceId){let o=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(_q[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(e))),this.recaptureMode===0){Ua(this.userId,{eventId:2003,param1:7,streamType:2});let n=yield qQ();n[0]?this.recapture(n[0].deviceId):o=!0}o&&vs.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return DA(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(vs.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))})}encodeFrame(e,o){if(!this.manager)return e;let n=o?8:this.mediaType;return this.manager.encodePipeline.reduceRight((a,I)=>I?I({frame:a,mediaType:n}):a,e)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(e=>e)}play(e,o){return Ee(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,o)}close(){vs.off("videoInputAdded",this.handleCameraAdded,this),vs.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return DA(this,null,function*(){try{yield zg($M.prototype,this,"recapture").call(this,e)}catch(o){let n=(yield qQ()).find(a=>a.deviceId!==e);if(!n)throw o;yield zg($M.prototype,this,"recapture").call(this,n.deviceId)}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info("setContentHint ".concat(e)),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||Ee(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};vt([wm(function(A){this.setContentHint(A.contentHint||"motion")})],A4.prototype,"capture");var Ru=A4,e4={};XC(e4,{REPORT_TYPE:()=>eM,buildSSOPackage:()=>Iu,bytes2ms:()=>jR,calculateScaleResolutionDownNumber:()=>AM,concatArrayBuffers:()=>qf,convertObjectNumberToInt:()=>$R,copyProperties:()=>dO,deepClone:()=>Dh,deepCloneBasic:()=>yh,deepMerge:()=>tB,delay:()=>AC,fibonacci:()=>ph,formatedTime:()=>MO,getConstructorName:()=>Yf,getContainerFromElement:()=>LN,getEnv:()=>BO,getFirst16Bits:()=>SO,getInternalVersion:()=>yO,getLast16Bits:()=>tM,getLoggerUrl:()=>dh,getMediaStreamTrackInfo:()=>YN,getMuteStateFromFlag:()=>mQ,getNetworkType:()=>qR,getNumNetworkType:()=>hh,getReconnectionTimeout:()=>fQ,getStringByteLength:()=>XR,getTestSignalDomain:()=>uO,getTurnServer:()=>RO,getUint32Version:()=>UN,getValueType:()=>ya,getViewListFromView:()=>Hf,glog:()=>pO,ipv4ToUint32:()=>Jf,isArray:()=>Aa,isAudioWorkletSupported:()=>fO,isBoolean:()=>rn,isConstructor:()=>mh,isEmpty:()=>zR,isFunction:()=>$n,isLangChinese:()=>rl,isMediaStreamTrack:()=>_N,isNumber:()=>hr,isObject:()=>Xc,isOverseaSdkAppId:()=>ol,isPlainObject:()=>Cc,isPortrait:()=>FN,isPromise:()=>fh,isRemoteTrack:()=>bN,isRotate90Or270:()=>gu,isSetSinkIdSupported:()=>mO,isString:()=>Sr,isUndefined:()=>Ee,isVideoMixerOutputTrack:()=>DQ,loadImage:()=>Vf,loadVideo:()=>wO,ms2bytes:()=>hO,ms2samples:()=>WR,normalizeUrl:()=>xN,performanceNow:()=>ki,promiseAny:()=>Pf,samples2ms:()=>kN,setNetworkTypeFromWebRTC:()=>KR,stringify:()=>nl,stringifyIncludeValue:()=>ZR,throttlePromise:()=>ON});var qAA=[-1,-1,1,-1,-1,1,1,1],KAA=[0,0,1,0,0,1,1,1],$T=class mj extends Uo{constructor(e,o){if(super(),this.context=e,G(this,"name"),G(this,"input"),G(this,"output"),G(this,"texture"),G(this,"ctx2d",null),G(this,"fbo"),G(this,"width",0),G(this,"height",0),G(this,"x",0),G(this,"y",0),G(this,"program"),G(this,"vertexShader"),G(this,"fragmentShader"),G(this,"totalFrames",0),G(this,"dropFrames",0),G(this,"matchInputSize",!0),G(this,"texCoordBuffer"),G(this,"positionBuffer"),G(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),G(this,"cost",0),G(this,"_canvas",null),G(this,"_image"),G(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||e.width,this.height=o.height||e.height,this._image=o.image,e instanceof Mu)e.ctx&&o.create2d&&(typeof OffscreenCanvas=="function"&&al!==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 n=e.ctx;this.texCoordBuffer=this.createBuffer(KAA),this.positionBuffer=this.createBuffer(qAA),o.createTexture!==!1&&(this.texture=n.createTexture(),this.useTexture(),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)),o.useFbo&&(this.fbo=n.createFramebuffer(),this.useBufferFrame(),this.useTexture(),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,this.width,this.height,0,n.RGBA,n.UNSIGNED_BYTE,null),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,this.texture,0)),o.useDefaultProgram?this.program=e.defaultProgam:(o.vertexShaderSource||o.fragmentShaderSource)&&(this.vertexShader=o.vertexShaderSource?e.createShader(n.VERTEX_SHADER,o.vertexShaderSource):e.defaultVShader,this.fragmentShader=o.fragmentShaderSource?e.createShader(n.FRAGMENT_SHADER,o.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(n){this.context.destroy(new Ct({code:Ge.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(n.message||n)}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let o=this.context.ctx,n=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,n),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,e,0),n}connect(e){for(var o=arguments.length,n=new Array(o>1?o-1:0),a=1;a0&&arguments[0]!==void 0?arguments[0]:0;var o;(o=this.output)==null||o.update(e)}disconnect(){for(var e,o=arguments.length,n=new Array(o),a=0;a{I&&(e.activeTexture(e.TEXTURE0+c),e.bindTexture(e.TEXTURE_2D,I))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let o=this.context.ctx,n=o.createBuffer();return o.bindBuffer(o.ARRAY_BUFFER,n),o.bufferData(o.ARRAY_BUFFER,new Float32Array(e),o.STATIC_DRAW),n}setTexBuffer(e){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,this.texCoordBuffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array(e),o.STATIC_DRAW)}setPosBuffer(e){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,this.positionBuffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array(e),o.STATIC_DRAW)}changeBufferData(e,o){let n=this.context.ctx;n.bindBuffer(n.ARRAY_BUFFER,e),n.bufferData(n.ARRAY_BUFFER,new Float32Array(o),n.STATIC_DRAW)}setAttributes(){let e=this.context.ctx;for(var o=arguments.length,n=new Array(o),a=0;a{e.enableVertexAttribArray(c),e.bindBuffer(e.ARRAY_BUFFER,I),e.vertexAttribPointer(c,2,e.FLOAT,!1,0,0)})}getVertexPoint(e,o){return[e/this.width*2-1,o/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,o){if(this.width!==e||this.height!==o){if(this.width=e,this.height=o,this._canvas&&(this._canvas.width=e,this._canvas.height=o),this.texture&&this.fbo){this.useTexture();let n=this.context.ctx;n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e,o,0,n.RGBA,n.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,o)}}draw(e,o){this.setAttributes(e||this.positionBuffer,o||this.texCoordBuffer);let n=this.context.ctx;n.drawArrays(n.TRIANGLE_STRIP,0,4)}draw2d(e,o,n,a,I,c,u,d,R){let k=!(Ee(c)||Ee(u)||Ee(d)||Ee(R));return!(!this.ctx2d||!e)&&(e instanceof ImageData?(k?this.ctx2d.putImageData(e,o,n,c,u,d,R):this.ctx2d.putImageData(e,o,n),this.emit(mj.RENDER,this.ctx2d.canvas)):(k?this.ctx2d.drawImage(e,c,u,d,R,o,n,a,I):this.ctx2d.drawImage(e,o,n,a,I),this.emit(mj.RENDER,e)),typeof VideoFrame<"u"&&e instanceof VideoFrame&&e.close(),!0)}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var e;let{totalFrames:o,x:n,y:a,width:I,height:c,name:u,cost:d}=this,R=Date.now(),k=(o-this.lastInfo.totalFrames)/((R-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:o,x:n,y:a,width:I,height:c,timestamp:R,fps:k,name:u,cost:d},bt({parent:(e=this.input)==null?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let o=this.context.ctx,n=o.createTexture();return this.useTextures(n),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,e),n}};G($T,"RENDER","render"),vt([is(Uo.INIT,"connected",{sync:!0})],$T.prototype,"connect"),vt([is("connected",Uo.INIT,{ignoreError:!0,sync:!0})],$T.prototype,"disconnect"),vt([is([],"closed",{sync:!0})],$T.prototype,"close");var Il=$T,jAA=Jn(xW(250),Gq(()=>performance.now()),qT()),WAA=[0,1,1,1,0,0,1,0],bq=class extends Il{constructor(A,e){super(A,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},e)),G(this,"_intervalId",0),G(this,"_sequence",0),G(this,"checkGLError",!1),G(this,"checkVisibilityChange"),A instanceof Mu?this.ctx2d=A.ctx||null:A.available&&e!=null&&e.mirrorUpAndDown&&this.setTexBuffer(WAA)}start(A){this.log.info("".concat(this.name," start render ").concat(A," fps")),nn.clearTask(this._intervalId),this._intervalId=nn.run("intervalInWorker",()=>{if(A!==this.context.frameRate&&(nn.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof aC){let e=this.context.ctx.getError();e&&this.context.destroy(new Ct({code:Ge.VIDEO_MANAGER_ERROR,extraCode:5,message:"".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)}))}},{fps:this.context.frameRate})}render(A){var e;return!((e=this.input)==null||!e.requestFrame(A))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(Il.RENDER,this.context._canvas),!0)}addInput(A){for(var e=arguments.length,o=new Array(e>1?e-1:0),n=1;n0&&arguments[0]!==void 0?arguments[0]:0;this.state!=="closed"&&(this._intervalId&&(nn.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),nn.clearTask(this._intervalId)}resize(A,e){super.resize(A,e),this.context.setSize(A,e)}close(){super.close(),nn.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},Lq=class extends bq{constructor(A,e){super(A,e),G(this,"_videoTrack"),G(this,"_muteOb"),G(this,"_closedOb",Ln(this,"closed")),G(this,"_subscription"),G(this,"_canvasContainer"),Number(Cu)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=A.canvas.captureStream().getVideoTracks(),this._muteOb=Ln(this._videoTrack,"mute"),Jn(Ln(this._videoTrack,"ended"),Qc(this._closedOb),Ks(()=>{this.context.destroy(new Ct({code:Ge.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){var A;this._subscription=Jn(this._muteOb,Qc(this._closedOb),hx((A=5e3,e=>{let o=performance.now();Jn(jAA,Tq(n=>n-o{var e;return!((e=this._videoTrack)==null||!e.muted||document.hidden)}),Ks(()=>{this.context.destroy(new Ct({code:Ge.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,e;super.close(),(A=this._videoTrack)==null||A.stop(),delete this._videoTrack,(e=this._canvasContainer)==null||e.remove()}},zAA=class extends Lq{render(A){var e;let o=!((e=this.input)==null||!e.requestFrame(A));if(this.context._canvas2d){let n=this.context._canvas2d.getContext("2d");n.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),n.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height),this.emit(Il.RENDER,this.context._canvas2d)}else this.emit(Il.RENDER,this.context._canvas);return o}},ZAA=class extends Lq{constructor(A,e,o){super(A,{name:"smallDestination",logger:o}),this.resolution=e}resize(A,e){let o,n=A*e,a=this.resolution.width*this.resolution.height;this.log.info("big res: ".concat(A,"*").concat(e," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),n>a?o=n/a:(this.log.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(A," * ").concat(e," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),o=n/19200),super.resize(A/Math.sqrt(o),e/Math.sqrt(o))}},t4=class extends Il{constructor(A,e){super(A,bt({name:"imageSource"},e)),G(this,"_lastImage"),G(this,"_totalFrames",0),G(this,"_autoResize",!1),G(this,"_canvasRendered"),G(this,"videoCallbackId",0),G(this,"waitingFirstFrame",!0),G(this,"shouldUpdate",!0),this._autoResize=e?.autoResize!==!1,al===16&&(this._canvasRendered=yu(),Jn(this._canvasRendered,wq(this._image),Qx(o=>o instanceof HTMLCanvasElement?Ln(o,"rendered"):Nq()),Qc(Ln(this,"closed")),Ks(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let A=this.image;this.videoCallbackId&&A.cancelVideoFrameCallback(this.videoCallbackId),YQ()&&!document.hidden&&(this.videoCallbackId=A.requestVideoFrameCallback((e,o)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=o.presentedFrames,this.update(1))}))}_render(A,e){var o;let{width:n,height:a}=this,{image:I}=this;if(I instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:n,videoHeight:a}=I,!n||!a)return!1;I.width=n,I.height=a}else if(I instanceof HTMLImageElement||I instanceof ImageData||I instanceof ImageBitmap){if({width:n,height:a}=I,I!==this._lastImage)this._lastImage=I;else if(n===this.width&&a===this.height)return!0}else I instanceof HTMLCanvasElement||I instanceof OffscreenCanvas?({width:n,height:a}=I,this._lastImage=I):typeof VideoFrame<"u"&&I instanceof VideoFrame&&({displayWidth:n,displayHeight:a}=I,(o=this._lastImage)==null||o.close(),this._lastImage=I);if(!this._autoResize)return!0;if(this.width===n&&this.height===a&&this.totalFrames){if(e){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,I)}}else{if(e){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,I)}this.resize(n,a)}return!0}get image(){return this._image}set image(A){var e;(e=this._canvasRendered)==null||e.next(A),this._image=A}render(A){return this._render(A,!0)}render2d(A){return this._render(A,!1)}},i4=class extends t4{constructor(A,e,o){super(A,o),this._player=e,this.name="videoPlayerSource",Jn(Ln(this._player,mi.PLAYER_STATE_CHANGED),Qc(Ln(this,"closed")),Sm(n=>{let{state:a}=n;return a==="PLAYING"}),Ks(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},FM=class extends i4{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(A,e,o){super(A,new wi({id:o.name,track:e,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()}},XAA=class extends Il{constructor(A,e,o){super(A,fi(bt({name:"textSource"},o),{create2d:!0})),G(this,"hasChange",!0),G(this,"content",""),this.ctx2d.textBaseline="top",this.content=e.content||"",e.font&&(this.font=e.font),e.color&&(this.color=e.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,e){if(!this.ctx2d)return;let{color:o,font:n}=this;super.resize(A,e),this.color=o,this.font=n}drawMultilineText(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=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 n=this.ctx2d.measureText(this.content);e+=n.fontBoundingBoxAscent||n.actualBoundingBoxAscent||0;let a=this.font.match(/(\d+)px/),I=(a?parseInt(a[1],10):16)*o,c=this.content.split(` -`);for(let u=0;u0&&arguments[0]!==void 0&&arguments[0];if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(AG._ids++)),A&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",MN),!this.ctx)throw new Ct({code:Ge.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,` + `,o.onclick=this.onQuestionClick.bind(this);let n=document.createElement("div");n.className=x,n.innerText="".concat(nl()?"详情 >":"Detail >"),n.onclick=this.onCollapseClick.bind(this);let a=A.content.firstChild,I=a.querySelector(".".concat(bM));return I.appendChild(n),I.appendChild(o),I.appendChild(e),a}addDiaLog(){Lt()||(We=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(wm)).onclick=A=>A.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",nA.info("show autoplay dialog"),Jo.uploadEvent({log:$A}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,We=!1),Ss=null}onConfirm(){nA.warn("confirm clicked, try resume stream"),S.emit(K.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let A=this._dialogNode.querySelector(".".concat(uA));A.style.visibility="".concat(this._showDetail?"hidden":"visible"),A.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||Jo.uploadEvent({log:ne}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Pt,"_blank"),this._isQuestionClicked||Jo.uploadEvent({log:De}),this._isQuestionClicked=!0}},Ss=null;function nC(){Ss||(Ss=new Nn)}var Mt,wi=class t6 extends rC{constructor(e){super(e,fA.VIDEO),G(this,"stat",{}),G(this,"_calculateTimeout",-1),G(this,"viewMirror",!1),G(this,"objectFit","cover"),G(this,"container"),G(this,"canvas"),G(this,"shouldRenderAlpha",!1),G(this,"_preSize",{width:0,height:0}),G(this,"posterImg"),G(this,"pipWindow"),G(this,"enterPIPPromise"),G(this,"_originContainerPosition"),G(this,"_isResettingSrcObject",!1),G(this,"_wrapper",null),G(this,"_useWrapper",!1),G(this,"_isFirstFrameRenderEmitted",!1),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,Ee(e.viewMirror)||(this.viewMirror=e.viewMirror),Ee(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(){let e=document.createElement(fA.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id","video_".concat(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,ra&&(e.poster="data:,"),this._appendToWrapper(),this.bindElementEvents(),this.calculateStat(),this._bindFirstFrameRenderEvent(e)}_bindFirstFrameRenderEvent(e){let o=()=>{if(this._isFirstFrameRenderEmitted)return;this._isFirstFrameRenderEmitted=!0;let n=e.videoWidth||0,a=e.videoHeight||0;this._log.info("first frame render: ".concat(n,"x").concat(a)),this.emit(mi.FIRST_FRAME_RENDER,{width:n,height:a})};typeof e.requestVideoFrameCallback=="function"?e.requestVideoFrameCallback(o):e.addEventListener("loadeddata",o,{once:!0})}get styleAttribute(){let e=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&&(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){let o=this._getOrCreateWrapper();o.insertBefore(this.elementToRender,o.firstChild)}else this.container.appendChild(this.elementToRender),this._cleanupWrapper()}setContainer(e){if(this.container===e)return;let o=this._wrapper,n=this.container;this.container=e,this._pausedRetryCount=DQ,this.track&&this.elementToRender&&this._appendToWrapper(),o&&n&&n!==this.container&&o.isConnected&&o.children.length===0&&o.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){let o=e??this.elementToRender;if(this.container&&o)if(this._useWrapper){let n=this._getOrCreateWrapper();n.insertBefore(o,n.firstChild)}else this.container.appendChild(o)}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),this.handleFullscreenChange=this.handleFullscreenChange.bind(this),this.handleVolumeChange=this.handleVolumeChange.bind(this),e&&e.add(fA.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(fA.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(fA.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener(fA.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 o;return e.type===fA.MUTE&&((o=this.stat)!=null&&o.fps&&(this.stat.fps=0),this.isFullscreen()&&this.resetSrcObjectToReplay()),super.handleTrackEvent(e)}handleFullscreenChange(){this.isFullscreen()?(this._log.info("enter fullscreen"),this.emit(mi.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(mi.LEAVE_FULL_SCREEN))}handleVolumeChange(){var e;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(mi.VOLUME_CHANGE,{muted:(e=this.element)==null?void 0:e.muted})}handleElementEvent(e){var o,n,a,I,c,u;if(this.mode===2)return;super.handleElementEvent(e);let d=e.type,R=this.isPictureInPicture(),k=this.isFullscreen(),_=e.isTrusted&&(R&&Ma||k);if(d===fA.PLAYING&&_&&!this._isResettingSrcObject&&(this._log.warn("user resume in ".concat(k?"fullscreen":"pip")),this.emit(mi.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),d===fA.PAUSE&&(_&&(this._log.warn("user pause in ".concat(k?"fullscreen":"pip")),this.emit(mi.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)),AC(500).then(()=>{var Z;(Z=this.container)!=null&&Z.isConnected&&(this._pausedRetryCount=DQ,this._log.info("view container ".concat(this.container.id," is in dom, reset pausedRetryCount")))})),this._pausedRetryCount>0&&!Lt()&&!this.isPausedByUserCall&&!_&&(this._log.info("[".concat(DQ-this._pausedRetryCount+1,"/").concat(DQ,"] ").concat(this.kind," player auto resume when paused")),this.doResume(),this._pausedRetryCount--),Ea&&!_&&(this._interval=nn.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 Z=this.element.style.transform;d===fA.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=Z.replace("scaleX(-1)",""):d===fA.LEAVE_PICTURE_IN_PICTURE&&!Z.includes("scaleX")&&(this.element.style.transform="".concat(Z," scaleX(-1)"))}d===fA.RESIZE&&(this._preSize.height!==((o=this.element)==null?void 0:o.videoHeight)||this._preSize.width!==((n=this.element)==null?void 0:n.videoWidth))&&(this._log.info("video size changed to ".concat((a=this.element)==null?void 0:a.videoWidth,"x").concat((I=this.element)==null?void 0:I.videoHeight)),this._preSize.height=((c=this.element)==null?void 0:c.videoHeight)||0,this._preSize.width=((u=this.element)==null?void 0:u.videoWidth)||0,this.emit(mi.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height})),d===fA.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(mi.LEAVE_PICTURE_IN_PICTURE)),d===fA.ENTER_PICTURE_IN_PICTURE&&this.emit(mi.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){ra&&bh&&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){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;var n,a;this.canvas!==e&&((n=this.canvas)==null||n.remove(),e?.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?o:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((a=this.element)==null||a.remove(),this._appendToWrapper(e)):this.element&&this._appendToWrapper(this.element))}setAttr(e){let o=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);o.style=Object.assign({width:"100%",height:"100%"},o.style),super.setAttr(o)}get mirror(){return this.viewMirror}setRect(e,o){this.elementToRender&&(this.elementToRender.style.width="".concat(e,"px"),this.elementToRender.style.height="".concat(o,"px"))}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(e)),this.objectFit=e}setPoster(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[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,!o||!Ma&&!Yr))return n();if(e==="")return this.removePosterImg(),n();if(this.posterImg)return n();let a=document.createElement("img");a.src=e;let I=window.getComputedStyle(this.element),c=I.objectFit||this.objectFit,u=1;if(this._useWrapper){let d=parseInt(I.zIndex,10);isNaN(d)||(u=d+1)}a.style.cssText=this._useWrapper?"grid-area:1/1;z-index:".concat(u,";width:100%;height:100%;object-fit:").concat(c,";"):"position:absolute;top:0;left:0;width:100%;height:100%;object-fit:".concat(c,";"),a.onload=()=>DA(this,null,function*(){try{a.decode&&(yield a.decode()),this.container&&!this._useWrapper&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=a;let d=this._useWrapper?this._wrapper:this.container;d?.appendChild(a),Xf()&&sl<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(d){this._log.warn("decode poster image error",d)}return n()}),a.onerror=()=>(this._log.warn("load poster image error"),n())})}removePosterImg(){this.posterImg&&(Xf()&&sl<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),!this._useWrapper&&this.container&&!Ee(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"))}pause(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return DA(this,null,function*(){zg(t6.prototype,this,"pause").call(this),!this.isPictureInPicture()&&!this.hasPoster&&(bh||e&&(Yr||Ma))&&(yield this.setPoster(this.getVideoFrame(),!0))})}resume(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return super.resume(e).then(()=>{var o;(this.posterImg||(o=this.element)!=null&&o.poster)&&this.setPoster("",!0)})}doResume(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this.isPaused&&e&&this.element&&this.track&&bh&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;var o;this.isPictureInPicture()&&this.exitPictureInPicture().catch(n=>{}),this.isFullscreen()&&this.exitFullscreen().catch(n=>{}),this.element&&(this.element.removeEventListener(fA.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),(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(e){if(Ee(e?.isLiveStream)||this.setLiveMode(e.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(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(mi.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"";let 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(HQ()&&this.element&&this._calculateTimeout<0){let e=0,o=null,n=(a,I)=>{this.stat.width=I.width,this.stat.height=I.height,o&&(this.stat.fps=Math.round((I.presentedFrames-o.presentedFrames)/(a-e)*1e3)),e=a,o=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)}}enterFullscreen(){return DA(this,null,function*(){let e=this.elementToRender;if(!e)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");if(Ea&&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(e.requestFullscreen)yield e.requestFullscreen();else if(e.webkitRequestFullscreen)yield e.webkitRequestFullscreen();else if(e.webkitEnterFullscreen)yield e.webkitEnterFullscreen();else if(e.mozRequestFullScreen)yield e.mozRequestFullScreen();else{if(!e.msRequestFullscreen)throw new Error("Fullscreen API not supported");yield e.msRequestFullscreen()}this._log.info("entered fullscreen mode")}catch(o){throw this._log.error("failed to enter fullscreen:",o),o}})}exitFullscreen(){return DA(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(e){throw this._log.error("failed to exit fullscreen:",e),e}})}isFullscreen(){let e=this.elementToRender;return!!e&&(this.element&&this.element.webkitDisplayingFullscreen?!this.isPictureInPicture():(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===e)}toggleFullscreen(){return DA(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return DA(this,null,function*(){this.enterPIPPromise=this._enterPictureInPicture();try{return yield this.enterPIPPromise}finally{delete this.enterPIPPromise}})}_enterPictureInPicture(){return DA(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:e}=this;if(e.requestPictureInPicture){this._log.info("requestPictureInPicture");let o=yield e.requestPictureInPicture();return this.pipWindow=o,this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),this._appendToWrapper(this.element)),o}if(e.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield 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}})}exitPictureInPicture(){return DA(this,null,function*(){var e;try{if(!this.isPictureInPicture())return;if(delete this.pipWindow,document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this.elementToRender===this.canvas&&((e=this.element)==null||e.remove(),this._pausedRetryCount=DQ,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:e}=this;return document.pictureInPictureElement?document.pictureInPictureElement===e:!!e.webkitPresentationMode&&e.webkitPresentationMode==="picture-in-picture"}togglePictureInPicture(){return DA(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function Fa(A,e){return DA(this,null,function*(){if(!A.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield A.audioWorklet.addModule(e),nA.info("worklet addModule success")}catch(o){throw nA.info("worklet addModule catch error. ".concat(o.message)),o}})}typeof AudioContext<"u"?Mt=AudioContext:typeof webkitAudioContext<"u"?Mt=webkitAudioContext:typeof mozAudioContext<"u"&&(Mt=mozAudioContext);var fr,SI=1500,Il=-1,KQ=0,aE=-1,eI=!1,lx=0,LM=-1,qT=-1;(function A(){try{if(fr)return;(fr=new Mt({sampleRate:48e3})).onstatechange=()=>{nA.info("context state: ".concat(fr.state).concat(fr.state!=="running"?" visibilityState: ".concat(document.visibilityState):"")),FM()},clearTimeout(Il)}catch(e){nA.error("initAudioContext failed: ".concat(e," typeof AudioContextClass: ").concat(typeof Mt)),Il=setTimeout(A,1e3)}})();var FM=()=>{fr.state==="suspended"?(KQ=ki(),aE===-1&&(aE=setTimeout(()=>{fr.state==="suspended"&&(eI=!0,S.emit("155",{isSuspended:!0}))},SI)),KT(),document.addEventListener("click",FM)):fr.state==="interrupted"?KT():(KQ&&(ct.addNumber({key:507800,value:ki()-KQ,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),KQ=0),aE!==-1&&(clearTimeout(aE),aE=-1,eI&&(eI=!1,S.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",FM),document.removeEventListener("click",FM))},Rq=0,Mq=-1;function KT(){return new Promise((A,e)=>{if(fr.state==="running")return A();Date.now()-Rq<1e3?(clearTimeout(Mq),Mq=setTimeout(()=>{Rq=Date.now(),fr.resume().then(A,e)},1e3)):(clearTimeout(Mq),Rq=Date.now(),fr.resume().then(A,e))}).catch(A=>{nA.warn("context resume failed: ".concat(A)),document.addEventListener("visibilitychange",FM)})}document.addEventListener("click",FM);var tI=A=>fr,iI=class{constructor(A){this.name=A,G(this,"node"),G(this,"node2"),G(this,"pre",new Set),G(this,"next",new Set),G(this,"context"),G(this,"connectedNodes",new Set),G(this,"nextInputChannelMap",new Map),G(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(e=>e.channelCount=A)}setChannelCount(A,e){!A||A instanceof ScriptProcessorNode||(A.channelCountMode="explicit",A.channelCount=e||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 e;if(A!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=A,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(o){nA.error(o)}}setNode(A,e){var o;if(!this.node)try{(o=this.context)==null||o.addMixWeight(),this.node=A,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),ct.addSuccessEvent({key:502701})}catch(n){nA.error(n),ct.addFailedEvent({key:502701,error:n})}}deleteNode(){var A;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(A=this.context)==null||A.reduceMixWeight(),this.preNodeReconnect(),ct.addSuccessEvent({key:502702})}catch(e){nA.error(e),ct.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(A=>{A.node?A.reconnect():A.preNodeReconnect()})}connectNext(A){this.next.forEach(e=>{let o=this.nextInputChannelMap.get(e);A._connect(e.node,o)||e.connectNext(A)})}_connect(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return!(!this.node||!A)&&((this.node2||this.node).connect(A,0,e),this.connectedNodes.add(A),!0)}_disconnect(){this.connectedNodes.forEach(A=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(A)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return this.next.add(A),A.pre.add(this),this.nextInputChannelMap.set(A,e),A}},N$=class extends iI{constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:256;super(),this.fftSize=A,G(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(),e=0,o=0,n="M".concat(e,",").concat(o);for(let a=0;a0&&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]}},RW=new WeakMap;function Cx(A){try{let e=RW.get(A);if(e)return e;let o=tI();if(A instanceof HTMLAudioElement)e=o.createMediaElementSource(A);else{if(!(A instanceof MediaStreamTrack))return A;e=o.createMediaStreamSource(new MediaStream([A]))}return RW.set(A,e),e}catch(e){if(!(Yr&&e instanceof Error&&e.name==="NotSupportedError"))throw e;nA.warn(e)}}var Bx=class ed{constructor(e){G(this,"_volume",0),G(this,"_volumeDb",0),G(this,"_log"),G(this,"_scriptProcessorNode",null),G(this,"_audioWorkletNode",null),G(this,"_interval",200),G(this,"ready",this.preload());let{log:o}=e;this._log=o,S.on(K.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-ed.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!ed.workletReady){let e='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);';ed.workletReady=Fa(ed.audioContext,URL.createObjectURL(new Blob([e],{type:"application/javascript"})))}return ed.workletReady.then(()=>this.initAudioWorklet()).catch(e=>(this._log.error("volumeMeter preload error: ".concat(e)),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(ed.audioContext,"volume-meter");let e=!1;this._audioWorkletNode.port.onmessage=o=>{ed.lastMessageTime=Date.now(),this._volume=o.data.volume||0,this._volumeDb=o.data.volumeDb||0,!e&&o.data.cacheLen&&o.data.outputLen&&(this._log.warn("worklet play success"),e=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(e){this._log.error("volumeMeter init audio worklet error: ".concat(e)),Jo.logFailedEvent({userId:this._log.userId,eventType:oa.LOAD_WORKLET,error:e}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=tI().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{ed.lastMessageTime=Date.now();let o=e.inputBuffer.getChannelData(0),n=0;for(let a=0;a>2);A.copyTo(o,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:o},[o.buffer]),A.close()}}},ux=MW,G$=es(hg(),1),SW=A=>e=>e.deviceId===A,wq=class{constructor(A,e){G(this,"kind"),G(this,"type"),G(this,"devices",[]),this.kind=A,this.type=e}update(A,e){let o=A.filter(n=>n.kind==="".concat(this.kind).concat(this.type.toLocaleLowerCase()));this.devices.length===1&&jT(this.devices[0])||e&&(o.forEach(n=>{if(n.deviceId&&!this.devices.find(SW(n.deviceId))){let a="".concat(this.kind).concat(this.type,"Added");nA.warn("".concat(a,": ").concat(JSON.stringify(n))),e.emit(a,n)}}),this.devices.forEach(n=>{if(n.deviceId&&!o.find(SW(n.deviceId))){let a="".concat(this.kind).concat(this.type,"Removed");nA.warn("".concat(a,": ").concat(JSON.stringify(n))),e.emit(a,n)}})),this.devices=o}hasDevice(A){return!!this.devices.find(e=>e.deviceId===A)}},k$=class extends G$.EventEmitter{constructor(){super(),G(this,"audioInputs",new wq(fA.AUDIO,"Input")),G(this,"videoInputs",new wq(fA.VIDEO,"Input")),G(this,"audioOutputs",new wq(fA.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||nn.run("interval",()=>{this.update()},{delay:1e4}))}init(){Qx().then(A=>{this.audioInputs.update(A),this.videoInputs.update(A),this.audioOutputs.update(A)})}update(){return DA(this,arguments,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function*(){let o=yield Qx(e);return A.audioInputs.update(o,A),A.videoInputs.update(o,A),A.audioOutputs.update(o,A),A}()})}hasBlueTooth(){var A;if(1e3*((A=tI())==null?void 0:A.outputLatency)>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(o=>e.some(n=>o.label.toLowerCase().includes(n)))||this.audioInputs.devices.some(o=>e.some(n=>o.label.toLowerCase().includes(n)))}},vs=GR||TR?null:new k$;function jT(A){return A.deviceId===A.groupId&&A.groupId===""}function Qx(){return DA(this,arguments,function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function*(){if(wI()||!MT())return[];let e=yield navigator.mediaDevices.enumerateDevices();if(A!==0){let o={audio:!1,video:!1};if(e.forEach(n=>{jT(n)&&(n.kind===fA.AUDIO_INPUT?o.audio=!0:n.kind===fA.VIDEO_INPUT&&(o.video=!0))}),A===2&&(o.audio=!1),A===1&&(o.video=!1),o.audio||o.video){let n;try{n=yield navigator.mediaDevices.getUserMedia(o),o.audio&&KT()}catch(a){nA.debug("capture before getDevices failed: ",a)}e=yield navigator.mediaDevices.enumerateDevices(),n?.getTracks().forEach(a=>a.stop())}}return e.map((o,n)=>{let a={kind:o.kind,deviceId:o.deviceId,groupId:o.groupId,label:o.label||"".concat(o.kind,"_").concat(n)};return o.deviceId.length>0&&Sq.add("".concat(o.deviceId,"_").concat(o.kind)),o.getCapabilities&&(a.getCapabilities=()=>o.getCapabilities()),a})}()})}function jQ(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return vs.update(A?1:0).then(e=>e.audioInputs.devices)}function WQ(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return vs.update(A?2:0).then(e=>e.videoInputs.devices)}var vW=!1;function Nm(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return DA(this,null,function*(){return(Ea||Ma)&&(A=!1),vs.update(A?1:0).then(e=>e.audioOutputs.devices)})}var Sq=new Set;function NW(A,e){return DA(this,null,function*(){let o=(yield jQ()).find(n=>n.deviceId===Of);return!e&&o?.groupId===A||o?.groupId===A&&o.label===e})}var dx,_$=class extends DW{constructor(A){super(),this.log=A,G(this,"volumeMeter"),G(this,"volumeMeterAfter3A"),G(this,"volumeDestination"),G(this,"analyser",new N$),this.volumeMeter=new wW({log:this.log}),this.volumeMeterAfter3A=new wW({log:this.log}),this.volumeDestination=new iI,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},vq=class i6 extends rC{constructor(e){super(e,fA.AUDIO),G(this,"_outputDeviceId"),G(this,"_floatVolume",1),G(this,"_destination"),G(this,"pipeline"),G(this,"volumeMeterMode","worklet"),G(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new _$(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(($g==="15.2"||$g==="15.3"||$g==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");this._log.info("audio player initializeElement");let o=dx||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(hr(e)?e/100:this._floatVolume),o===dx&&(dx=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(mi.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return DA(this,null,function*(){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&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(tI().createAnalyser()),function(){DA(this,null,function*(){try{vW||(vW=!0,nA.info("speakers:".concat((yield Nm()).map(o=>" ".concat(o.deviceId.slice(0,8),": ").concat(o.label)))))}catch{}})}()}catch(o){throw this._log.warn("audio play error: ".concat(o)),Lh($g,"18.7",!0)&&this.bindAutoPlayEvent(),o}return zg(i6.prototype,this,"play").call(this)}})}stop(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.pipeline.destroy(),super.stop(e)}setVolume(e){this._floatVolume=e,this.element&&(this.element.volume=e)}setSinkId(e){return DA(this,null,function*(){var o,n;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(n=(o=this.element).setSinkId)==null?void 0:n.call(o,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()}},b$=class extends vq{setTrack(A){this.track!==A&&(this.unbindTrackEvents(),this.track=A,this.emit(mi.MEDIA_TRACK_CHANGED,A),A&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([A]))))}},TW=class extends vq{constructor(A){super(A),G(this,"_sourceElement"),G(this,"_output",new iI),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(tI().destination)}write(A){this.pipeline.volumeMeter.write(A)}setTrack(A){var e,o,n;((o=(e=this.element)==null?void 0:e.error)==null?void 0:o.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==A&&(this.unbindTrackEvents(),this.track=A,this.emit(mi.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=((n=A.getSettings())==null?void 0:n.channelCount)||1,this.pipeline.replaceSource(A)):this.pipeline.source.deleteNode())}setVolume(A){var e;let o=A<=1&&!Xf();if(this._floatVolume!==A||!(o&&((e=this.element)==null?void 0:e.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(Xf()){if(!this.enableVolumeControlInIOS)return;(function(){if(!Ea||qT!==-1)return;let n=()=>{ki()-lx<500||(fr&&fr.state==="running"&&fr.currentTime===LM&&(nA.warn("context is fake running, auto resume"),fr.suspend().catch(a=>{nA.warn("context suspend failed: ".concat(a))})),LM=fr.currentTime,lx=ki())};qT=setInterval(()=>{n()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&n()})})()}if(Yr&&!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=tI().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),pr(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(n=>{this.emit(mi.AUTOPLAY_FAILED,n)}))}}stop(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.pipeline.destroy();let e=this._sourceElement||this.element;e&&_Q&&(dx=e),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(A)}},Nq=class extends Uo{constructor(A){let{userId:e,sdkAppId:o,mediaType:n,room:a,PlayerClass:I=n===1?TW:wi}=A;var c;super(),G(this,"id",hA()),G(this,"userId",""),G(this,"isRemote"),G(this,"mediaType"),G(this,"room"),G(this,"user"),G(this,"_log"),G(this,"_inputTrack"),G(this,"_outputTrack"),G(this,"isPlayCalled"),G(this,"container",null),G(this,"player"),G(this,"subVideoPlayerMap"),G(this,"muted",!1),G(this,"abortCtrl"),G(this,"objectFit","cover"),G(this,"mirror"),G(this,"rotation"),G(this,"isScreen",!1),G(this,"manager"),G(this,"trackSettings"),G(this,"isFirstVideoFrameEmitted",!1),this.userId=e||"",this.mediaType=n,this._log=nA.createLogger({parent:a?.getLogger(),id:"".concat(this.kind[0],"t"),userId:(c=a||this.room)==null?void 0:c.userId,remoteUserId:this instanceof eG?void 0:this.userId,sdkAppId:o,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof eG}),this.player=new I({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:a?.enableVolumeControlInIOS}),this.player.on(mi.PLAYER_STATE_CHANGED,u=>{if(S.emit(K.PLAYER_STATE_CHANGED,bt({track:this},u)),this.emit("player-state-changed",u),u.state==="PLAYING"&&this.room){let d=!0;for(let{remoteAudioTrack:R,remoteVideoTrack:k,remoteAuxiliaryTrack:_}of[...this.room.remotePublishedUserMap.values()])if(R.isAvailable&&!R.player.isPlaying||k.isAvailable&&!k.player.isPlaying||_.isAvailable&&!_.player.isPlaying){d=!1;break}d&&Lt()&&Ss&&Ss.deleteDialog()}}),this.kind===fA.VIDEO&&(this.player.on(mi.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(mi.LOADED_DATA),S.emit(K.VIDEO_LOADED_DATA,{track:this})}),this.player.on(mi.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(mi.LOADED_META_DATA)}),this.player.on(mi.MEDIA_TRACK_CHANGED,u=>{var d;(d=this.subVideoPlayerMap)==null||d.forEach(R=>R.setTrack(u))}),this.player.on(mi.RESIZE,u=>{this.emitFirstVideoFrameEvent(mi.RESIZE),this.emit("video-size-changed",bt({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},u))}),this.player.on(mi.FIRST_FRAME_RENDER,u=>{this.emit("first-frame-render",fi(bt({},u),{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(mi.ERROR,this.onPlayerError.bind(this)),this.player.on(mi.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||nA}get kind(){return this.mediaType===1?fA.AUDIO:fA.VIDEO}get isAudio(){return this.kind===fA.AUDIO}get strMediaType(){return this.mediaType===4?fA.VIDEO:this.mediaType===2?fA.SCREEN:fA.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,e){return DA(this,null,function*(){let o=Aa(A)?A[0]:A;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(e))),e&&!Ee(e.muted)&&this.setPlayerMute(e.muted),e&&!Ee(e.objectFit)&&(this.objectFit=e.objectFit),void(this.player instanceof wi&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(Aa(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))),Aa(A)&&A.length>=1&&(yield this.playSubContainer(A.slice(1),e))));if(e&&!Ee(e.muted)?this.setPlayerMute(e.muted):(!this.isRemote||this.kind===fA.VIDEO)&&this.setPlayerMute(!0),e&&!Ee(e.objectFit)&&(this.objectFit=e.objectFit),this.player instanceof wi&&(Ee(e?.isLiveStream)||this.player.setLiveMode(e.isLiveStream),this.player.setObjectFit(this.objectFit),e&&!Ee(e.poster)&&this.player.setPoster(e.poster)),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof wi&&this.player.setContainer(o)),S.emit(K.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info("play with options: ".concat(JSON.stringify(e)));try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(e),Aa(A)&&A.length>1&&(yield this.playSubContainer(A.slice(1),e))}catch(n){throw this.handleAutoPlayFailed(n),n}}else this.log.info("play has not mediaTrack, abort")})}setMirror(A,e){if(this.isScreen||this.kind!==fA.VIDEO||Ee(A)||A===this.mirror)return;this.mirror=A;let o=this.player;e&&(o=e);let n=this.manager;if(rn(this.mirror))return o.setViewMirror(this.mirror),void(!this.isRemote&&n&&(n.mirror=!1));switch(this.mirror){case"view":n&&(n.mirror=!1),o.setViewMirror(!0);break;case"publish":n&&(n.mirror=!0),o.setViewMirror(!0);break;case"both":n&&(n.mirror=!0),o.setViewMirror(!1)}}playSubContainer(A,e){return DA(this,null,function*(){if(!this._outputTrack||this.kind===fA.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((n,a)=>{var I;A.find(c=>a===c)||(n.stop(),(I=this.subVideoPlayerMap)==null||I.delete(a))});for(let[n,a]of A.entries()){let I=this.subVideoPlayerMap.get(a);I?e&&(Ee(e.objectFit)||I.setObjectFit(e.objectFit)):this.subVideoPlayerMap.set(a,new wi({id:this.userId||this.id,track:this.playerMediaTrack,container:a,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(n+1)})}))}let o=[...this.subVideoPlayerMap.values()];for(let n of o)n.setViewMirror(this.player.mirror),yield n.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(jN(this)&&!A?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop()}),this.container=null)}resume(){return DA(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),S.emit(A?K.TRACK_MUTED:K.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){nE(A,A).add(fA.MUTE,this.onTrackMuted).add(fA.UNMUTE,this.onTrackUnmuted).add(fA.ENDED,this.onTrackEnded),A.muted&&this.onTrackMuted(),A.readyState===fA.ENDED&&this.onTrackEnded()}uninstallTrackEvent(A){pr(A)}setInputMediaStreamTrack(A){var e;let o=this._inputTrack;if(A!==o)return this._inputTrack=A,this.trackSettings=(e=A.getSettings)==null?void 0:e.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 e;let o=this._outputTrack;this instanceof Su&&MQ(o)||A!==o&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",A.label):this.log.info("setOutputMediaStreamTrack",(e=A.getSettings)==null?void 0:e.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 e,o;if(this.isPlayCalled){if(A){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch(n=>this.handleAutoPlayFailed(n)),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return jN(this)&&this.isAudio&&(e=this.user)!=null&&e.muteState.hasAudio&&(o=this.user)!=null&&o.muteState.audioMuted?void 0:(this.player.stop(jN(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 DA(this,null,function*(){var e;this.log.warn("handleAutoPlayFailed",A);let o=()=>{this.resume().then(()=>{document.removeEventListener("click",o,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((TQ||Bu)&&(yield AC(100),(e=this.player)!=null&&e.isPlaying))return;nC()}else document.addEventListener("click",o,!0);S.once(K.LOCAL_TRACK_CAPTURE_SUCCESS,n=>{let{track:a}=n;a.kind==="audio"&&Lt()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&o()}),this.emit("error",A)})}getVideoFrame(){return this.player instanceof wi?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(A){var e,o,n;if(this.isFirstVideoFrameEmitted)return;let a=(e=this.mediaTrack)==null?void 0:e.getSettings(),I=a?.width||((o=this.player.element)==null?void 0:o.videoWidth)||0,c=a?.height||((n=this.player.element)==null?void 0:n.videoHeight)||0;A===mi.RESIZE&&!I&&!c||A===mi.LOADED_META_DATA&&!I&&!c||(A===mi.LOADED_DATA&&!I&&!c&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,Eu(this.rotation)&&([I,c]=[c,I]),this.emit("first-video-frame",{width:I,height:c,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"))}};vt([is([],Uo.INIT,{sync:!0})],Nq.prototype,"_toInitState");var L$=Object.prototype.hasOwnProperty,zQ=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(Cc(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 e in A)if(L$.call(A,e))return!1;return!0}return!1},F$=Zf({retryFunction:function(A){return DA(this,null,function*(){let e=function(I){return{audio:U$(I),video:O$(I)}}(A);nA.info("getUserMedia with constraints: ".concat(JSON.stringify(e)));let o=[],n=[],a=["label","deviceId","groupId"];if(e.audio&&(o=yield jQ(),nA.info("microphones: ".concat(al(o.map(I=>fi(bt({},I),{groupId:I.groupId.substring(0,8)})),{keysToInclude:a})))),e.video&&(n=yield WQ(),nA.info("cameras: ".concat(al(n,{keysToInclude:a}))),!rn(e.video)&&e.video.facingMode==="user"&&!e.video.deviceId)){let I=n.filter(c=>!c.label.includes("infrared")).find(c=>c.label.includes("facing front"));I&&(e.video.deviceId=I.deviceId,nA.info("exclude infrared camera: ".concat(JSON.stringify(e))))}try{let I=yield navigator.mediaDevices.getUserMedia(e);return nx&&I.getTracks().forEach(c=>{var u;let d=c.getCapabilities();nA.info("".concat(c.kind," capabilities: ").concat(al(d,{keysToInclude:vN}))),!Ee(A.echoCancellation)&&((u=d.echoCancellation)==null?void 0:u.indexOf(A.echoCancellation))===-1&&nA.warn("Invalid argument for 'echoCancellation'. Expected one of [".concat(JSON.stringify(d.echoCancellation),"], but received '").concat(A.echoCancellation,"'"))}),e.audio&&KT(),I}catch(I){let{message:c}=I;throw I.name==="NotFoundError"&&(A.video&&n&&n.length===0&&(c=Wi({key:Mi.CAMERA_NOT_FOUND})),A.audio&&o&&o.length===0&&(c=Wi({key:Mi.MICROPHONE_NOT_FOUND}))),new Ct({code:Ge.INITIALIZE_FAILED,name:I.name,message:c,constraint:I.constraint})}})},settings:{retries:3,timeout:500},onError:A=>{let{error:e,retry:o,reject:n,retryFuncArgs:a,retriedCount:I}=A,c=I+1;e.name==="NotReadableError"||e.name==="OverconstrainedError"||e.name==="AbortError"?(c===1?(a[0].video&&(a[0].maxResolution=!1,(!Ma||a[0].width*a[0].height<=2073600)&&a[0].frameRate&&(a[0].frameRate=a[0].frameRate>10?10:5)),a[0].retryWhenExactFailed&&a[0].useExactDeviceId&&(a[0].useExactDeviceId=!1)):c===2?a[0].useDeviceIdOnly=!0:c===3&&!a[0].useExactDeviceId&&(a[0].useTrueAsConstraint=!0),o()):n(e),a[0].microphoneId&&GW(a[0].microphoneId,!1),a[0].cameraId&&GW(a[0].cameraId,!0)},onRetrying:A=>{nA.warn("getUserMedia NotReadableError observed, retrying [".concat(A,"/3]"))},onRetryFailed:A=>{Jo.logFailedEvent({eventType:oa.GET_USER_MEDIA_RETRY,error:A})},onRetrySuccess:A=>{Jo.logSuccessEvent({eventType:oa.GET_USER_MEDIA_RETRY}),Jo.uploadEvent({log:"stat-".concat(oa.GET_USER_MEDIA_RETRY,"-success-").concat(A)})}});function GW(A,e){return DA(this,null,function*(){let o=(e?yield WQ():yield jQ()).find(n=>n.deviceId===A);o&&$n(o.getCapabilities)&&nA.warn(al(o.getCapabilities(),{keysToInclude:vN}))})}function U$(A){if(!A.audio)return!1;if(A.useTrueAsConstraint)return!0;let e={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:A.sampleRate};return!zQ(A.microphoneId)&&(e.deviceId=A.useExactDeviceId?{exact:A.microphoneId}:A.microphoneId,A.useDeviceIdOnly)?e:(hr(A.channelCount)&&(e.channelCount=A.channelCount),(rn(A.echoCancellation)||A.echoCancellation==="remote-only"||A.echoCancellation==="all")&&(e.echoCancellation=A.echoCancellation),rn(A.noiseSuppression)&&!A.noiseSuppression&&(e.noiseSuppression=!1),rn(A.autoGainControl)&&!A.autoGainControl&&(e.autoGainControl=!1),!!zQ(e)||e)}function O$(A){if(!A.video)return!1;if(A.useTrueAsConstraint)return!0;let{maxResolution:e=!0}=A,o={};return A.cameraId?o.deviceId=A.useExactDeviceId?{exact:A.cameraId}:A.cameraId:A.facingMode&&(o.facingMode=A.facingMode),A.useDeviceIdOnly&&!zQ(o)?o:(A.width&&(o.width={ideal:A.width},e&&!Yr&&(o.width.max=A.width)),A.height&&(o.height={ideal:A.height},e&&!Yr&&(o.height.max=A.height)),Yr&&uu&&A.width&&A.height&&A.width*A.height<101376&&(o.width=A.width,o.height=A.height),A.frameRate&&(o.frameRate=A.frameRate),!!zQ(o)||o)}var x$=F$;function kW(A){return Dn((e,o)=>function(){for(var n=arguments.length,a=new Array(n),I=0;Ifunction(){for(var n=arguments.length,a=new Array(n),I=0;Ifunction(){for(var n=arguments.length,a=new Array(n),I=0;I{let A=!1,e=document.visibilityState;return()=>{document.visibilityState!==e&&nA.info("visibility change: ".concat(document.visibilityState)),!A&&(document.addEventListener("visibilitychange",()=>{nA.info("visibility change: ".concat(document.visibilityState)),e=document.visibilityState}),A=!0)}})(),P$=0,bW=class{constructor(A){G(this,"log"),G(this,"isRunning",!1),G(this,"queue",[]);let e="fq".concat(++P$);A&&(e+="|".concat(A)),this.log=nA.createLogger({id:e})}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var o,n;let a=bt({},A),I=new Promise((c,u)=>{a.resolve=c,a.reject=u});return a.promise=I,e?this.length<=1?this.queue.push(a):(n=(o=this.lastQueueItem)==null?void 0:o.promise)==null||n.then(a.resolve,a.reject):this.queue.push(a),this.log.debug("push ".concat(this.length),A.funcName,A.args),this.isRunning||this.callNext(),I}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:e,context:o,resolve:n,reject:a,funcName:I}=this.queue[0];this.log.debug("callNext",this.length,I,e),this.isRunning=!0,A.apply(o,e).then(n,a).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},hx=new WeakMap,px=new WeakMap;function WT(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return function(e,o,n){let a=n.value;return n.value=function(){let I=hx.get(this)||new bW;for(var c=arguments.length,u=new Array(c),d=0;dd.push(Z)),(u=px.get(this))==null||u.forEach(Z=>Z?.queue.forEach(iA=>d.push(iA))),d.forEach(Z=>{Z.reject(new Ct({code:Ge.API_CALL_ABORTED,message:A}))}),hx.delete(this),px.delete(this),a.apply(this,k)},n}}function zh(A,e){return function(o,n,a){let I=a.value,c=u=>A(...u);return a.value=function(){for(var u=arguments.length,d=new Array(u),R=0;Rfunction(){let a=A;try{for(var I=arguments.length,c=new Array(I),u=0;u(e?ct.addSuccessEvent({key:a,cost:ki()-R}):ct.addSuccessEvent({key:a}),k)).catch(k=>{throw ct.addFailedEvent({key:a,error:k}),k}):(ct.addSuccessEvent({key:a}),d)}catch(d){throw ct.addFailedEvent({key:a,error:d}),d}})}var FW={};function la(){}XC(FW,{Events:()=>os,Inspect:()=>Xh,LastSink:()=>fx,Sink:()=>Go,Subscribe:()=>mx,TimeoutError:()=>xW,audit:()=>wAA,bindCallback:()=>IAA,bindNodeCallback:()=>cAA,buffer:()=>X$,bufferCount:()=>Z$,bufferTime:()=>zAA,call:()=>UW,catchError:()=>r4,combineLatest:()=>JW,concat:()=>q$,concatMap:()=>xAA,concatMapTo:()=>YAA,count:()=>CAA,create:()=>Vr,debounce:()=>vAA,debounceTime:()=>NAA,defer:()=>HW,delay:()=>ZAA,deliver:()=>ko,dispose:()=>Tq,elementAt:()=>TAA,empty:()=>Lq,every:()=>LAA,exhaustMap:()=>qAA,exhaustMapTo:()=>KAA,expand:()=>$AA,filter:()=>Gm,find:()=>GAA,findIndex:()=>kAA,first:()=>_AA,fromAnimationFrame:()=>sAA,fromArray:()=>tAA,fromEvent:()=>Ln,fromEventPattern:()=>iAA,fromFetch:()=>oAA,fromIterable:()=>rAA,fromPromise:()=>jW,fromReadableStream:()=>aAA,fromReader:()=>nAA,groupBy:()=>jAA,identity:()=>J$,ignoreElements:()=>dAA,iif:()=>j$,inspect:()=>OW,interval:()=>KW,last:()=>bAA,map:()=>Uq,mapTo:()=>UAA,max:()=>BAA,merge:()=>Gq,mergeMap:()=>JAA,mergeMapTo:()=>HAA,min:()=>uAA,never:()=>EAA,nothing:()=>la,of:()=>eAA,pairwise:()=>FAA,pipe:()=>Jn,race:()=>PW,range:()=>gAA,reduce:()=>WW,retry:()=>ieA,scan:()=>XW,setAsapScheduler:()=>AAA,share:()=>zT,shareReplay:()=>K$,skip:()=>fAA,skipUntil:()=>mAA,skipWhile:()=>Fq,startWith:()=>kq,subject:()=>wu,subscribe:()=>Ks,sum:()=>QAA,switchMap:()=>yx,switchMapTo:()=>Mx,take:()=>OM,takeLast:()=>pAA,takeUntil:()=>Qc,takeWhile:()=>hAA,tap:()=>Oq,throttle:()=>RAA,throwError:()=>lAA,timeInterval:()=>WAA,timeout:()=>teA,timer:()=>bq,toPromise:()=>AeA,toReadableStream:()=>eeA,withLatestFrom:()=>z$,zip:()=>W$});var UW=A=>A(),J$=A=>A;function Tq(){this.dispose()}var OW=()=>typeof __FASTRX_DEVTOOLS__<"u",H$=1,Xh=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(A){let e=new V$(A,this,this.streamId++);return os.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},fx=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=la,this.error=la,this.next=la,this.dispose=la,this.subscribe=la,this.doDefer()}subscribe(A){return A instanceof Xh?A.subscribe(this):A(this),this}get bindSubscribe(){return A=>this.subscribe(A)}doDefer(){this.defers.forEach(UW),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}},Go=class extends fx{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)}},mx=class extends fx{constructor(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:la,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:la,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:la;if(super(),this._next=e,this._error=o,this._complete=n,this.then=la,A instanceof Xh){let a={toString:()=>"subscribe",id:0,source:A};this.defer(()=>{os.defer(a,0)}),os.create(a),os.pipe(a),this.sourceId=a.id,this.subscribe(A),os.subscribe({id:a.id,end:!0}),e==la?this._next=I=>os.next(a,0,I):this.next=I=>{os.next(a,0,I),e(I)},n==la?this._complete=()=>os.complete(a,0):this.complete=()=>{this.dispose(),os.complete(a,0),n()},o==la?this._error=I=>os.complete(a,0,I):this.error=I=>{this.dispose(),os.complete(a,0,I),o(I)}}else this.subscribe(A)}next(A){this._next(A)}complete(){this.dispose(),this._complete()}error(A){this.dispose(),this._error(A)}};function Jn(A){for(var e=arguments.length,o=new Array(e>1?e-1:0),n=1;nI(a),A)}function Vr(A,e,o){if(OW()){let n=Object.defineProperties(Object.setPrototypeOf(A,Xh.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:e,writable:!0,configurable:!0},args:{value:o,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});os.create(n);for(let a=0;a{if(I instanceof Xh){let c=Vr(u=>{let d=new A(u,...n);d.sourceId=c.id,d.subscribe(I)},e,arguments);return c.source=I,os.pipe(c),c}return c=>I(new A(c,...n))}}}function $h(A,e){window.postMessage({source:"fastrx-devtools-backend",payload:{event:A,payload:e}})}var V$=class extends Go{constructor(A,e,o){super(A),this.source=e,this.id=o,this.sourceId=A.sourceId,this.defer(()=>{os.defer(this.source,this.id)})}next(A){os.next(this.source,this.id,A),this.sink.next(A)}complete(){os.complete(this.source,this.id),this.sink.complete()}error(A){os.complete(this.source,this.id,A),this.sink.error(A)}},os={addSource(A,e){$h("addSource",{id:A.id,name:A.toString(),source:{id:e.id,name:e.toString()}})},next(A,e,o){$h("next",{id:A.id,streamId:e,data:o&&o.toString()})},subscribe(A,e){let{id:o,end:n}=A;$h("subscribe",{id:o,end:n,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(A,e,o){$h("complete",{id:A.id,streamId:e,err:o?o.toString():null})},defer(A,e){$h("defer",{id:A.id,streamId:e})},pipe(A){$h("pipe",{name:A.toString(),id:A.id,source:{id:A.source.id,name:A.source.toString()}})},update(A){$h("update",{id:A.id,name:A.toString()})},create(A){A.id||(A.id=H$++),$h("create",{name:A.toString(),id:A.id})}},xW=class extends Error{constructor(A){super("timeout after ".concat(A,"ms")),this.timeout=A}},YW=class extends fx{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(e=>e.next(A))}complete(){this.sinks.forEach(A=>A.complete()),this.sinks.clear()}error(A){this.sinks.forEach(e=>e.error(A)),this.sinks.clear()}};function zT(){return A=>{let e=new YW(A);if(A instanceof Xh){let o=Vr(n=>{e.add(n)},"share",arguments);return e.sourceId=o.id,o.source=A,os.pipe(o),o}return Vr(e.add.bind(e),"share",arguments)}}function Gq(){for(var A=arguments.length,e=new Array(A),o=0;o{let a=new Go(n),I=e.length;a.complete=()=>{--I===0&&n.complete()},e.forEach(a.bindSubscribe)},"merge",arguments)}function PW(){for(var A=arguments.length,e=new Array(A),o=0;o{let a=new Map;e.forEach(I=>{let c=new Go(n);a.set(I,c),c.complete=()=>{a.delete(I),a.size===0?n.complete():c.dispose()},c.next=u=>{a.delete(I),a.forEach(d=>d.dispose()),c.resetNext(),c.resetComplete(),c.next(u)}}),e.forEach(I=>a.get(I).subscribe(I))},"race",arguments)}function q$(){for(var A=arguments.length,e=new Array(A),o=0;o{let a=0,I=e.length,c=new Go(n);c.complete=()=>{a{let o=new YW(e),n=[];return o.next=function(a){n.push(a),n.length>A&&n.shift(),this.sinks.forEach(I=>I.next(a))},Vr(a=>{a.defer(()=>o.remove(a)),n.forEach(I=>a.next(I)),o.add(a)},"shareReplay",arguments)}}function j$(A,e,o){return Vr(n=>A()?e(n):o(n),"iif",arguments)}function JW(){for(var A=arguments.length,e=new Array(A),o=0;o{let a=e.length,I=a,c=a,u=new Array(a),d=()=>{--c===0&&n.complete()};e.forEach((R,k)=>{let _=new Go(n);_.next=Z=>{I--,_.next=iA=>{u[k]=iA,I===0&&n.next(u)},_.next(Z)},_.complete=d,_.subscribe(R)})},"combineLatest",arguments)}function W$(){for(var A=arguments.length,e=new Array(A),o=0;o{let a=e.length,I=a,c=new Array(a),u=()=>{--I===0&&n.complete()};e.forEach((d,R)=>{let k=new Go(n),_=[];c[R]=_,k.next=Z=>{_.push(Z),c.every(iA=>iA.length)&&n.next(c.map(iA=>iA.shift()))},k.complete=u,k.subscribe(d)})},"zip",arguments)}function kq(){for(var A=arguments.length,e=new Array(A),o=0;oVr(function(a){let I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,c=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length;for(;I1?o-1:0),a=1;athis.buffer=I,e.complete=la,e.subscribe(JW(...n))}next(A){this.buffer&&this.sink.next([A,...this.buffer])}},"withLatestFrom"),Z$=ko(class extends Go{constructor(A,e,o){super(A),this.bufferSize=e,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(e=>{e.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"),X$=ko(class extends Go{constructor(A,e){super(A),this.buffer=[];let o=new Go(A);o.next=n=>{A.next(this.buffer),this.buffer=[]},o.complete=la,o.subscribe(e)}next(A){this.buffer.push(A)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),$$=function(A,e,o,n){return new(o||(o=Promise))(function(a,I){function c(R){try{d(n.next(R))}catch(k){I(k)}}function u(R){try{d(n.throw(R))}catch(k){I(k)}}function d(R){R.done?a(R.value):function(k){return k instanceof o?k:new o(function(_){_(k)})}(R.value).then(c,u)}d((n=n.apply(A,[])).next())})};function wu(A){let e=arguments,o=zT()(Vr(n=>{o.next=a=>n.next(a),o.complete=()=>n.complete(),o.error=a=>n.error(a),A&&n.subscribe(A)},"subject",e));return o.next=la,o.complete=la,o.error=la,o}function HW(A){return Vr(e=>e.subscribe(A()),"defer",arguments)}var UM={promise:A=>{Promise.resolve().then(A)},setImmediate:typeof setImmediate<"u"?A=>setImmediate(A):null,setTimeout:A=>setTimeout(A,0)},_q=typeof Promise<"u"?UM.promise:UM.setImmediate?UM.setImmediate:UM.setTimeout,VW=A=>e=>{_q(()=>A(e))},AAA=A=>{typeof A=="function"?_q=A:UM[A]&&(_q=UM[A])},qW=A=>VW(e=>{for(let o=0;!e.disposed&&o{let o=0,n=setInterval(()=>e.next(o++),A);return e.defer(()=>{clearInterval(n)}),"interval"},"interval",arguments)}function bq(A,e){return Vr(o=>{let n=0,a=setTimeout(()=>{if(o.removeDefer(I),o.next(n++),e){let c=setInterval(()=>o.next(n++),e);o.defer(()=>{clearInterval(c)})}else o.complete()},A),I=()=>clearTimeout(a);o.defer(I)},"timer",arguments)}function Dx(A,e){return o=>{let n=a=>o.next(a);o.defer(()=>e(n)),A(n)}}function iAA(A,e){return Vr(Dx(A,e),"fromEventPattern",arguments)}function Ln(A,e){if("on"in A&&"off"in A)return Vr(Dx(o=>A.on(e,o),o=>A.off(e,o)),"fromEvent",arguments);if("addListener"in A&&"removeListener"in A)return Vr(Dx(o=>A.addListener(e,o),o=>A.removeListener(e,o)),"fromEvent",arguments);if("addEventListener"in A)return Vr(Dx(o=>A.addEventListener(e,o),o=>A.removeEventListener(e,o)),"fromEvent",arguments);throw"target is not a EventDispachter"}function jW(A){return Vr(e=>{A.then(o=>{e.next(o),e.complete()},e.error.bind(e))},"fromPromise",arguments)}function oAA(A,e){return Vr(HW(()=>jW(fetch(A,e))),"fromFetch",arguments)}function rAA(A){return Vr(VW(e=>{try{for(let o of A){if(e.disposed)return;e.next(o)}e.complete()}catch(o){e.error(o)}}),"fromIterable",arguments)}function nAA(A){let e=o=>$$(this,void 0,void 0,function*(){try{if(o.disposed)return;let{done:n,value:a}=yield A.read();if(n)return void o.complete();o.next(a),e(o)}catch(n){o.error(n)}});return Vr(o=>{e(o)},"fromReader",arguments)}function aAA(A){return Vr(e=>{let o=new AbortController,n=o.signal;e.defer(()=>o.abort("cancelled")),A.pipeTo(new WritableStream({write(a){e.next(a)},close(){e.complete()},abort(a){e.error(a)}}),{signal:n}).then(()=>e.complete(),a=>e.error(a))},"fromReadableStream",arguments)}function sAA(){return Vr(A=>{let e=requestAnimationFrame(function o(n){A.disposed||(A.next(n),e=requestAnimationFrame(o))});A.defer(()=>cancelAnimationFrame(e))},"fromAnimationFrame",arguments)}function gAA(A,e){return Vr(function(o){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:A,a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e+A;for(;n2?o-2:0),a=2;a{let c=n.concat(u=>(I.next(u),I.complete()));A.apply(e,c)},"bindCallback",arguments)}function cAA(A,e){for(var o=arguments.length,n=new Array(o>2?o-2:0),a=2;a{let c=n.concat((u,d)=>u?I.error(u):(I.next(d),I.complete()));A.apply(e,c)},"bindNodeCallback",arguments)}function EAA(){return Vr(()=>{},"never",arguments)}function lAA(A){return Vr(e=>e.error(A),"throwError",arguments)}function Lq(){return Vr(A=>A.complete(),"empty",arguments)}var ZT=class extends Go{constructor(A,e,o){super(A),this.f=e;let n=()=>{this.sink.next(this.acc),this.sink.complete()};o===void 0?this.next=a=>{this.acc=a,this.complete=n,this.resetNext()}:(this.acc=o,this.complete=n)}next(A){this.acc=this.f(this.acc,A)}},WW=ko(ZT,"reduce"),CAA=A=>ko(ZT,"count")((e,o)=>A(o)?e+1:e,0),BAA=()=>ko(ZT,"max")(Math.max),uAA=()=>ko(ZT,"min")(Math.min),QAA=()=>ko(ZT,"sum")((A,e)=>A+e,0),Gm=ko(class extends Go{constructor(A,e,o){super(A),this.filter=e,this.thisArg=o}next(A){this.filter.call(this.thisArg,A)&&this.sink.next(A)}},"filter"),dAA=ko(class extends Go{next(A){}},"ignoreElements"),OM=ko(class extends Go{constructor(A,e){super(A),this.count=e}next(A){this.sink.next(A),--this.count===0&&(this.doDefer(),this.complete())}},"take"),Qc=ko(class extends Go{constructor(A,e){super(A);let o=new Go(A);o.next=()=>{o.doDefer(),A.complete()},o.complete=Tq,o.subscribe(e)}},"takeUntil"),hAA=ko(class extends Go{constructor(A,e){super(A),this.f=e}next(A){this.f(A)?this.sink.next(A):(this.doDefer(),this.complete())}},"takeWhile"),pAA=A=>WW((e,o)=>(e.push(o),e.length>A&&e.shift(),e),[]),fAA=ko(class extends Go{constructor(A,e){super(A),this.count=e}next(A){--this.count===0&&(this.next=super.next)}},"skip"),mAA=ko(class extends Go{constructor(A,e){super(A),A.next=la;let o=new Go(A);o.next=()=>{o.doDefer(),A.resetNext()},o.complete=Tq,o.subscribe(e)}},"skipUntil"),Fq=ko(class extends Go{constructor(A,e){super(A),this.f=e}next(A){this.f(A)||(this.next=super.next,this.next(A))}},"skipWhile"),DAA={leading:!0,trailing:!1},yAA=class extends Go{constructor(A,e,o){super(A),this.durationSelector=e,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)}},zW=class extends Go{constructor(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:DAA;super(A),this.durationSelector=e,this.config=o,this._throttle=new yAA(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=la,this._throttle.complete(),super.complete()}},RAA=ko(zW,"throttle"),MAA={leading:!1,trailing:!0},wAA=A=>ko(zW,"audit")(A,MAA),SAA=class extends Go{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},ZW=class extends Go{constructor(A,e){super(A),this.durationSelector=e,this._debounce=new SAA(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()}},vAA=ko(ZW,"debounce"),NAA=A=>ko(ZW,"debounceTime")(e=>bq(A)),TAA=ko(class extends Go{constructor(A,e,o){super(A),this.count=e,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"),GAA=A=>e=>OM(1)(Fq(o=>!A(o))(e)),kAA=ko(class extends Go{constructor(A,e){super(A),this.f=e,this.i=0}next(A){this.f(A)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},"findIndex"),_AA=ko(class extends Go{constructor(A,e,o){super(A),this.f=e,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"),bAA=ko(class extends Go{constructor(A,e,o){super(A),this.f=e,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"),LAA=ko(class extends Go{constructor(A,e){super(A),this.predicate=e,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"),XW=ko(class extends Go{constructor(A,e,o){super(A),this.f=e,o===void 0?this.next=n=>{this.acc=n,this.resetNext(),this.sink.next(this.acc)}:this.acc=o}next(A){this.sink.next(this.acc=this.f(this.acc,A))}},"scan"),FAA=ko(class extends Go{constructor(){super(...arguments),this.hasLast=!1}next(A){this.hasLast?this.sink.next([this.last,A]):this.hasLast=!0,this.last=A}},"pairwise"),$W=class extends Go{constructor(A,e,o){super(A),this.mapper=e,this.thisArg=o}next(A){super.next(this.mapper.call(this.thisArg,A))}},Uq=ko($W,"map"),UAA=A=>ko($W,"mapTo")(e=>A),XT=class extends Go{constructor(A,e,o){super(A),this.data=e,this.context=o}next(A){let e=this.context.combineResults;e?this.sink.next(e(this.data,A)):this.sink.next(A)}tryComplete(){this.context.resetComplete(),this.dispose()}},$T=class o6 extends Go{constructor(e,o,n){super(e),this.makeSource=o,this.combineResults=n,this.index=0}subInner(e,o){let n=this.currentSink=new o(this.sink,e,this);this.complete===o6.prototype.complete&&(this.complete=this.tryComplete),n.complete=n.tryComplete,n.subscribe(this.makeSource(e,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},A4=class extends XT{},e4=class extends $T{next(A){this.subInner(A,A4),this.next=e=>{this.currentSink.dispose(),this.subInner(e,A4)}}},yx=ko(e4,"switchMap");function Rx(A){return(e,o)=>A(()=>e,o)}var Mx=Rx(ko(e4,"switchMapTo")),OAA=class extends XT{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},t4=class extends $T{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(),OAA),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},xAA=ko(t4,"concatMap"),YAA=Rx(ko(t4,"concatMapTo")),PAA=class extends XT{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},i4=class extends $T{constructor(){super(...arguments),this.inners=new Set}next(A){this.subInner(A,PAA),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(A=>A.resetComplete()):this.dispose()}},JAA=ko(i4,"mergeMap"),HAA=Rx(ko(i4,"mergeMapTo")),VAA=class extends XT{dispose(){this.context.resetNext(),super.dispose()}},o4=class extends $T{next(A){this.next=la,this.subInner(A,VAA)}},qAA=ko(o4,"exhaustMap"),KAA=Rx(ko(o4,"exhaustMapTo")),jAA=ko(class extends Go{constructor(A,e){super(A),this.f=e,this.groups=new Map}next(A){let e=this.f(A),o=this.groups.get(e);o===void 0&&(o=wu(),o.key=e,this.groups.set(e,o),super.next(o)),o.next(A)}complete(){this.groups.forEach(A=>A.complete()),super.complete()}error(A){this.groups.forEach(e=>e.error(A)),super.error(A)}},"groupBy"),WAA=ko(class extends Go{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"),zAA=ko(class extends Go{constructor(A,e){super(A),this.miniseconds=e,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"),ZAA=ko(class extends Go{constructor(A,e){super(A),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(A){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:o,data:n}=e;super.next(n),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"),r4=ko(class extends Go{constructor(A,e){super(A),this.selector=e}error(A){this.dispose(),this.selector(A)(this.sink)}},"catchError"),XAA=class extends XT{tryComplete(){let A=this.context.inners.delete(this);super.dispose(),A&&this.context.checkComplete()}next(A){this.sink.next(A),this.context.expandValue(A)}},$AA=ko(class extends $T{constructor(A,e){super(A,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(A){this.sink.next(A),this.expandValue(A)}expandValue(A){let e=new XAA(this.sink,A,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.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"),AeA=()=>A=>new Promise((e,o)=>{let n;new mx(A,a=>n=a,o,()=>e(n))}),eeA=()=>A=>{let e;return new ReadableStream({start(o){e=new mx(A,o.enqueue.bind(o),o.error.bind(o),o.close.bind(o))},cancel(){e.dispose()}})},Ks=function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:la,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:la,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:la;return n=>new mx(n,A,e,o)},Oq=ko(class extends Go{constructor(A,e){super(A),e instanceof Function?this.next=o=>{e(o),A.next(o)}:(e.next&&(this.next=o=>{e.next(o),A.next(o)}),e.complete&&(this.complete=()=>{e.complete(),A.complete()}),e.error&&(this.error=o=>{e.error(o),A.error(o)}))}},"tap"),teA=ko(class extends Go{constructor(A,e){super(A),this.timeout=e,this.id=setTimeout(()=>this.error(new xW(this.timeout)),this.timeout)}next(A){super.next(A),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),ieA=function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1/0;return e=>{if(e instanceof Xh){let o=Vr(n=>{let a=A,I=new Go(n);I.error=c=>{a-- >0?I.subscribe(e):n.error(c)},I.sourceId=o.id,I.subscribe(e)},"retry",[A]);return o.source=e,os.pipe(o),o}return o=>{let n=A,a=new Go(o);a.error=I=>{n-- >0?e(a):o.error(I)},e(a)}}},xq=(A=>(A[A.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",A[A.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",A))(xq||{}),AG=class r6 extends Nq{constructor(e,o){super({mediaType:e,PlayerClass:o}),G(this,"isRemote",!1),G(this,"deviceId"),G(this,"groupId",""),G(this,"label",""),G(this,"sourceTrack"),G(this,"enableAutoSwitchWhenRecapturing",!0),G(this,"_isRecapturing",!1),G(this,"_lastRecaptureTime",0),G(this,"_onMuteTimeoutId",-1),G(this,"_encodeCheckTimeoutId",-1),G(this,"recaptureMode",0),G(this,"profile"),G(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,o){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(fA.MUTE,this.onTrackMuted),e.addEventListener(fA.UNMUTE,this.onTrackUnmuted),e.addEventListener(fA.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===fA.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(fA.MUTE,this.onTrackMuted),e.removeEventListener(fA.UNMUTE,this.onTrackUnmuted),e.removeEventListener(fA.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return DA(this,null,function*(){var n,a;let I=this.sourceTrack;try{let c,u=ki();S.emit(K.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(c=new MediaStream,c.addTrack(e.customSource)):(o||(n=this.sourceTrack)==null||n.stop(),c=yield x$(e));let d=c.getTracks()[0];return yield this.setInputMediaStreamTrack(d),e.customSource||(this.sourceTrack=d,this.updateDeviceIdInUse(),this.listenDeviceChange()),S.emit(K.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:ki()-u,profile:this.profile,room:(a=this.manager)==null?void 0:a.room}),c}catch(c){throw S.emit(K.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:c}),this.log.error("getUserMedia error observed ".concat(c)),c}finally{o&&I?.stop()}})}setOutputMediaStreamTrack(e){var o;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(o=this.room)==null?void 0:o.replaceTrack(this)}get hasFlag(){var e,o;let n=RQ(((e=this.room)==null?void 0:e.localPublishFlag)||0,((o=this.room)==null?void 0:o.userId)||"");return this.mediaType===4&&n.hasVideo||this.mediaType===1&&n.hasAudio||this.mediaType===2&&n.hasAuxiliary}publish(e,o){return DA(this,null,function*(){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()),yield o,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((o,n)=>DA(this,null,function*(){var a,I,c,u,d;let R=()=>n(new Ct({code:Ge.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?o():((this.state===Uo.INIT||this.state==="ready")&&R(),Jn(Ln(e,"local-publish-flag-changed"),Gm(()=>this.hasFlag),Qc(Gq(Ln(this,Uo.INIT),Ln(this,"ready"))),Ks(o,n,R))),(c=(I=(a=this.room)==null?void 0:a.networkQuality)==null?void 0:I.hadRecentBadUplink)!=null&&c.call(I,2))return o();let k=e.heartbeatCount,_=((d=(u=this.mediaTrack)==null?void 0:u.stats)==null?void 0:d.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>DA(this,null,function*(){var Z,iA,cA,TA,JA,Ie,XA,Ft;if((cA=(iA=(Z=this.room)==null?void 0:Z.networkQuality)==null?void 0:iA.hadRecentBadUplink)!=null&&cA.call(iA,2)||e.heartbeatCount-k<3)return o();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((TA=this.mediaTrack)!=null&&TA.stats){let Nt=this.mediaTrack.stats.totalFrames||0;Nt-_===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",Nt)}let ie=this.kind===fA.AUDIO,ke=this.stat.bytesSent>0;if(ct[ke?"addSuccessEvent":"addFailedEvent"]({key:ie?503700:513702}),!ie){let Nt={H264:513704,H265:513705,VP8:513706}[((Ie=(JA=this.room)==null?void 0:JA.videoCodec)==null?void 0:Ie.toUpperCase())||"H264"];Nt&&ct[ke?"addSuccessEvent":"addFailedEvent"]({key:Nt})}if(!ke){if(ct.addEnum({key:ie?503701:513703,value:FQ()}),Jo.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(pu()||UQ()),userId:this.userId}),this.log.warn(ie?"encode failed":"".concat((Ft=(XA=this.room)==null?void 0:XA.videoCodec)==null?void 0:Ft.toUpperCase()," encode failed")),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield AC(5e3),this.stat.bytesSent>0||this.hasFlag)))return o();this.emit("6",this),n(new Ct({message:"".concat(this.strMediaType," encode failed"),code:ie?Ge.AUDIO_ENCODE_FAILED:Ge.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),S.emit(K.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return DA(this,null,function*(){if(this.sourceTrack&&qh){let{deviceId:e,groupId:o}=this.sourceTrack.getSettings(),{label:n}=this.sourceTrack;(yield function(a){return DA(this,arguments,function(I){let{newDeviceId:c,oldDeviceId:u,oldGroupId:d,oldLabel:R,kind:k}=I;return function*(){return c===u&&(k!==fA.AUDIO||c!==Of||(yield NW(d,R)))}()})}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=n,o&&(this.groupId=o),Qx().then(a=>{let I=a.find(c=>{let u=c.deviceId===e;return o&&(u=u&&c.groupId===o),u});I&&this.emit("2",I)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return!(!this.deviceId||!this.sourceTrack||this.kind===fA.AUDIO&&!function(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let n=o.label.toLocaleLowerCase();if(n.includes("mic")||n.includes("麦克风"))return!0;let a="".concat((o?.getSettings()||{}).deviceId,"_").concat(fA.AUDIO_INPUT);return!!Sq.has(a)}(this.sourceTrack)||this.kind===fA.VIDEO&&!function(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let n=o.label.toLocaleLowerCase();if(n.includes("camera")||n.includes("webcam"))return!0;let a="".concat((o?.getSettings()||{}).deviceId,"_").concat(fA.VIDEO_INPUT);return!!Sq.has(a)}(this.sourceTrack)||this._isRecapturing||e&&uu&&Ma)}onTrackMuted(){if(super.onTrackMuted(),Y$(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTimethis.onTrackMuted(),Yf);this._onMuteTimeoutId=setTimeout(()=>DA(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((Ea||ra)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return DA(this,null,function*(){if(zg(r6.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTimethis.onTrackEnded(),Yf);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return DA(this,null,function*(){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let a=this.sourceTrack;o||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let I={useExactDeviceId:!0};if(e==="user"||e==="environment")I.facingMode=e;else{let c;(this.kind==="audio"?yield jQ():yield WQ()).find(u=>u.deviceId===e)&&(c=e),I.deviceId=c}return this.capture(I,o).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),S.emit(K.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(c=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(c.message)),this.emit("5",c),S.emit(K.LOCAL_TRACK_RECAPTURE,{track:this,error:c})}).finally(()=>{o&&a?.stop()})})}getRecoverCaptureDeviceId(){return DA(this,null,function*(){let e=this instanceof Su;if(e&&this.facingMode)return this.facingMode;let{deviceId:o}=this;if(o){let n=(tG.get(o)||0)+1;if(tG.set(o,n),n>=3&&this.enableAutoSwitchWhenRecapturing){let a=e?(yield WQ()).find(I=>!tG.has(I.deviceId)):(yield jQ()).find(I=>!tG.has(I.deviceId));a&&(this.log.warn("".concat(o," capture fail ").concat(n," times, change new ").concat(a.deviceId)),o=a.deviceId)}}return o})}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),S.emit(K.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()}};vt([is(Uo.INIT,"ready",{ignoreError:!0,sync:!0})],AG.prototype,"setStateToReady"),vt([WT()],AG.prototype,"capture"),vt([is("ready","publish",{ignoreError:!0,success(){S.emit(K.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 e;(e=this.room)==null||e.localTracks.delete(this);let o="error",n=A instanceof Ct?A:A.cause instanceof Ct?A.cause:A,a=!1;n instanceof Ct&&(n.message.includes("timeout")?o="timeout":n.code===Ge.API_CALL_ABORTED&&(a=!0,o="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:o,error:n}),this.log[a?"info":"error"]("publish failed",n)}}),Zh(521714,!1)],AG.prototype,"publish"),vt([Dn(A=>function(){return DA(this,null,function*(){let e=this.state==="publish"?"started":"starting";A.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:e,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),is([],"ready",{sync:!0})],AG.prototype,"unpublish");var eG=AG,tG=new Map;S.on(K.SWITCH_DEVICE_SUCCESS,A=>{A.track.deviceId&&tG.delete(A.track.deviceId)});var km=class MG extends eG{constructor(e){super(1,b$),G(this,"mediaType",1),G(this,"volume",0),G(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),G(this,"playerMuted",!0),G(this,"pipeline"),G(this,"earMonitorGainNode",new iI),G(this,"_output",new iI),G(this,"codecPipeline",[]),G(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),G(this,"mixedAudioReferenceMap",new Map),G(this,"isAudioContextLongSuspended",!1),G(this,"after3aSilenceStartTime",0),G(this,"_micMuted",!1),G(this,"_volumeDetectionTrack",null),G(this,"_volumeDetectionSource",new iI),this.manager=e,this.pipeline=new yW(e),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),S.on(K.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return ux.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.isProcessEnabled)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){Ee(e)||(e!==0||this.after3aSilenceStartTime?e>0&&(this.after3aSilenceStartTime=0):this.after3aSilenceStartTime=ki())}setInputMediaStreamTrack(e){return DA(this,null,function*(){let o=this.trackSettings||{};ct.addEnum({key:501701,value:o.channelCount||0,useUV:!1}),ct.addEnum({key:501702,value:o.sampleRate||0,useUV:!1}),ct.addEnum({key:502700,value:0});let{sampleRate:n,channelCount:a}=o;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:n,channelCount:a}))),this.pipeline.source.channelCount=a||1,this.pipeline.replaceSource(e),yield zg(MG.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(e){return DA(this,arguments,function(o){var n=this;let{deviceId:a,customSource:I,useExactDeviceId:c=!0,retryWhenExactFailed:u}=o,d=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return function*(){let R=yield zg(MG.prototype,n,"capture").call(n,{video:!1,audio:!0,microphoneId:a,echoCancellation:n.profile.echoCancellation,autoGainControl:n.profile.autoGainControl,noiseSuppression:n.profile.noiseSuppression,sampleRate:n.profile.sampleRate,channelCount:n.profile.channelCount,useExactDeviceId:c,retryWhenExactFailed:u,customSource:I},d);return KT(),R}()})}switchDevice(e){return DA(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource&&(e!==Of||(yield NW(this.groupId,this.label))))return;try{this.log.info("switchDevice audio to: ".concat(e)),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),S.emit(K.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(){vs&&!vs.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&vs.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return DA(this,null,function*(){if(e.deviceId===this.deviceId){let o=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(xq[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(e))),this.recaptureMode===0){Ua(this.userId,{eventId:2003,param1:6,streamType:1});let n=yield jQ();n[0]?this.recapture(n[0].deviceId):o=!0}o&&vs.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(vs.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))}update3A(e){return DA(this,arguments,function(o){var n=this;let{echoCancellation:a,noiseSuppression:I,autoGainControl:c}=o;return function*(){let u=n.sourceTrack||n.mediaTrack;if(!u)return;let d=u.getConstraints(),R=!1;!Ee(a)&&a!==n.profile.echoCancellation&&(n.profile.echoCancellation=a,d.echoCancellation=a,R=!0),!Ee(I)&&I!==n.profile.noiseSuppression&&(n.profile.noiseSuppression=I,d.noiseSuppression=I,R=!0),!Ee(c)&&c!==n.profile.autoGainControl&&(n.profile.autoGainControl=c,d.autoGainControl=c,R=!0),R&&(Yr||Ma?yield u.applyConstraints(d).catch(k=>n._log.warn("update3A failed: ",k)):n.deviceId&&(yield n.recapture(n.deviceId,!0)))}()})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&ct.addEnum({key:502700,value:2})}setMute(e,o){var n;this._cleanupVolumeDetectionTrack(),e==="microphone"?(this._micMuted=!0,this.sourceTrack&&(this.sourceTrack.enabled=!1),o&&this._setupVolumeDetectionTrack(),((n=this.manager)==null?void 0:n.mixWeight)<=1?(this.muted=!0,this._inputTrack&&(this._inputTrack.enabled=!1),this._outputTrack&&(this._outputTrack.enabled=!1),this.emit("mute",this),S.emit(K.TRACK_MUTED,{track:this})):this._outputTrack&&(this._outputTrack.enabled=!0)):e===!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),S.emit(K.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),S.emit(K.TRACK_UNMUTED,{track:this}))}_setupVolumeDetectionTrack(){let e=this.sourceTrack||this.mediaTrack;if(!e)return;this._volumeDetectionTrack=e.clone(),this._volumeDetectionTrack.enabled=!0;let o=Cx(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(e){super.setAudioVolume(0),Ea&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(tI().createGain()),this._output.setNode(tI().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!Ma&&!Ea)return this.update3A({echoCancellation:e})}addDenoiser(e){var o;tE<=92&&((o=this.trackSettings)==null?void 0:o.sampleRate)!==48e3?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(ct.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1))}mixAudioReference(e,o){if(this.mixedAudioReferenceMap.has(o))return;this.log.info("mixAudioReference() => ".concat(o));let n=Cx(e);if(!n)return;let a=new iI,I=tI().createGain();I.gain.value=1;let c=new iI;a.pipeTo(c).pipeTo(this.pipeline.mixNode),a.setNode(n),c.setNode(I),this.mixedAudioReferenceMap.set(o,[a,c])}unMixAudioReference(e){let[o,n]=this.mixedAudioReferenceMap.get(e)||[];o&&(this.log.info("unMixAudioReference() => ".concat(e)),o.deleteNode(),n?.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,o){let[n,a]=this.mixedAudioReferenceMap.get(e)||[];a!=null&&a.node&&(a.node.gain.value=o/100,this.log.info("setAudioReferenceVolume() => ".concat(e," ").concat(a.node.gain.value)))}addAudioProcessor(e,o,n){this.pipeline.silentNode.setNode(n),this.pipeline.mixNode.setNode(o),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this._cleanupVolumeDetectionTrack(),this.mixedAudioReferenceMap.forEach(e=>{let[o,n]=e;o.deleteNode(),n.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),vs.off("audioInputAdded",this.handleMicrophoneAdded,this),vs.off("audioInputRemoved",this.handleMicrophoneRemoved,this),S.off(K.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return DA(this,null,function*(){try{yield zg(MG.prototype,this,"recapture").call(this,e,o)}catch(n){let a=(yield jQ()).find(I=>I.deviceId!==e);if(!a)throw n;yield zg(MG.prototype,this,"recapture").call(this,a.deviceId)}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((o,n)=>n?n({frame:o,ntp:Eh()}):o,e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(e=>e)}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended(e){let{isSuspended:o}=e;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(_Q?"":", non-Safari"));let n=this.sourceTrack||this.mediaTrack;n&&this.setOutputMediaStreamTrack(n)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let o=this.sourceTrack||this.mediaTrack;o&&(e=o)}super.setOutputMediaStreamTrack(e)}};function Sx(A,e){return e+4<=A.byteLength&&A.getUint8(e)===0&&A.getUint8(e+1)===0&&A.getUint8(e+2)===0&&A.getUint8(e+3)===1?4:e+3<=A.byteLength&&A.getUint8(e)===0&&A.getUint8(e+1)===0&&A.getUint8(e+2)===1?3:0}function n4(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1],o=new DataView(A),n=[],a=0;for(;a0){c=_;break}let u=c===-1?o.byteLength:c,d=u-a,R=new ArrayBuffer(d),k=new DataView(R);for(let _=0;_1&&arguments[1]!==void 0&&arguments[1];this.dataView=A,this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let{seiPayloadStartIndex:A}=this,e=this.dataView.byteLength-2,o=[],n=0;for(let I=A;I<=e;I++){let c=this.dataView.getInt8(I);switch(c){case 0:case 1:case 2:case 3:n===2&&(o.push(3),n=0),c===0?n+=1:n=0,o.push(c);break;default:n=0,o.push(c)}}o.push(this.dataView.getInt8(this.dataView.byteLength-1));let a=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,A),...o]).buffer);this.dataView=a}removePreventionByte(){let{seiPayloadStartIndex:A}=this,e=this.dataView.byteLength-1,o=[],n=0;for(let I=A;I<=e;I++)switch(this.dataView.getInt8(I)){case 0:n++,o.push(this.dataView.getInt8(I));break;case 3:n!==2&&o.push(this.dataView.getInt8(I)),n=0;break;default:o.push(this.dataView.getInt8(I)),n=0}let a=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,A),...o]).buffer);this.dataView=a}get seiPayloadStartIndex(){let A=6;for(let e=6;e=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}},oeA=class{constructor(){G(this,"_seiMessageList",[]),G(this,"_smallSeiMessageList",[]),G(this,"_seiPayloadType",243)}encodeSEINalu(A){let e=A.byteLength,o=parseInt(String(e/255),10),n=e%255,a=[];a.push(0,0,0,1,6,this._seiPayloadType);for(let c=0;c0&&A.data.byteLength>0){let n=9-this.getNaluCount(A.data);if(n<=0)return 0;let a=o.splice(0,n).reverse().map(this.encodeSEINalu.bind(this)),I=a.reduce((k,_)=>k+_.dataView.byteLength,0),c=new ArrayBuffer(I+A.data.byteLength),u=new DataView(c),d=new DataView(A.data),R=0;for(let k=0;k1&&arguments[1]!==void 0?arguments[1]:4,wi),G(this,"profile",bt({},kf)),G(this,"avoidCropping",!1),G(this,"_scaleResolutionDownBy"),G(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0}),G(this,"small"),G(this,"isNeedToSetBandwidth"),G(this,"muteImage"),G(this,"manager"),G(this,"_seiCodec",new oeA),this.manager=e;let o=()=>{var n;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let a=rl(((n=this.room)==null?void 0:n.sdkAppId)||0)?pN:kR;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(a)),this.setProfile(fi(bt({},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(qh&&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)}setMute(e){return DA(this,null,function*(){var o,n,a;if(Sr(e)){if(this.muteImage===e)return;yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),yield(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,zg(tw.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(a=this.manager)==null?void 0:a.deleteWatermark("mute"),this.muteImage=void 0),zg(tw.prototype,this,"setMute").call(this,e)})}capture(e){return DA(this,arguments,function(o){var n=this;let{deviceId:a,facingMode:I,useExactDeviceId:c=!0,customSource:u,retryWhenExactFailed:d=!0}=o;return function*(){let R={audio:!1,video:!0,facingMode:I||n.facingMode,cameraId:a,width:n.profile.width,height:n.profile.height,frameRate:n.profile.frameRate,useExactDeviceId:c,retryWhenExactFailed:d,customSource:u};if(R.facingMode==="environment"){let k=yield n.getDeviceIdWhenUsingBackCamera();k&&(R.cameraId=k)}return zg(tw.prototype,n,"capture").call(n,R)}()})}setProfile(e){var o;let n=this.fallbackProfile(e);if(n.bitrate&&(this.isNeedToSetBandwidth=n.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(n);else{let a=rl(((o=this.room)==null?void 0:o.sdkAppId)||0)?pN:kR;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(a)),super.setProfile(fi(bt({},this.profile),{width:1920,height:1080}))}}applyProfile(){return DA(this,null,function*(){var e,o;if(!this.mediaTrack)return;let{width:n=0,height:a=0}=(this.sourceTrack||this.mediaTrack).getSettings(),I=n*a,c=this.settings,u=c.height!==this.profile.height||c.width!==this.profile.width||c.frameRate!==this.profile.frameRate;if(u&&(sl===16&&this.deviceId?yield this.recapture(this.deviceId):(MQ(this.outMediaTrack)?yield(e=this.outMediaTrack)==null?void 0:e.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:d=0,height:R=0}=(this.sourceTrack||this.mediaTrack).getSettings(),k=d*R;return u&&k&&I&&k===I?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:fA.VIDEO,videoType:fA.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},o=this.sourceTrack||this.mediaTrack;return qh&&o&&Object.assign(e,o.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:iM(this.settings,this.profile)}isAllowed2k4k(e){var o;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||((o=this.room.scheduleResult.trtcAutoConf)==null?void 0:o["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return DA(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let o={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?o.facingMode=e:o.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(o),S.emit(K.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 DA(this,null,function*(){let e;try{if(aT&&!_h&&ax){let o=(yield WQ(!0)).map(a=>{var I;return fi(bt({},a),{capabilities:(I=a.getCapabilities)==null?void 0:I.call(a)})}).filter(a=>{var I,c;return(c=(I=a.capabilities)==null?void 0:I.facingMode)==null?void 0:c.includes("environment")}),n=o[0];o.forEach(a=>{var I,c,u,d;let{capabilities:R}=a;((I=R.width)!=null&&I.max&&(c=R.height)!=null&&c.max?R.width.max*R.height.max:0)>((u=n.capabilities.width)!=null&&u.max&&(d=n.capabilities.height)!=null&&d.max?n.capabilities.width.max*n.capabilities.height.max:0)&&(n=a)}),n!=null&&n.capabilities&&(this._log.info("use max resolution back camera",n),e=n.deviceId)}}catch(o){this._log.warn("get max res camera failed",o)}return e})}updateSmallConfig(e){return DA(this,null,function*(){var o,n;this._log.info("update small stream config: ".concat(JSON.stringify(e)));let a=!this.small;this.small=this.fallbackProfile(e,!0),yield(o=this.manager)==null?void 0:o.update(),a&&(yield(n=this.room)==null?void 0:n.enableSmall(!0)),this.log.info("update small stream config success")})}fallbackProfile(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1],n=e.width>e.height,a=bt({},e);return e.width*e.height<=19200&&ra&&Bc&&(this.log.warn("".concat(o?"small ":"","resolution is ").concat(e.width,"*").concat(e.height,", fallback to 240*180 for android chrome")),a.width=n?240:180,a.height=n?180:240,a.bitrate=Math.max(e.bitrate,150)),e.width*e.height>921600&&jO&&(a.width=n?1280:720,a.height=n?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),lT($g,"14.3")&&Lh($g,"14.0",!0)&&this.on("7",()=>{let 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"))}),!o&&this.avoidCropping&&(Bc||Yr)&&!pM()&&e.width*e.height<=230400&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,a.width=1280,a.height=720,this.log.warn("capture 720p, scale: ".concat(this._scaleResolutionDownBy))),a}stopSmall(){var e,o;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(o=this.room)==null||o.enableSmall(!1))}listenDeviceChange(){vs&&!vs.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&vs.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return DA(this,null,function*(){if(e.deviceId===this.deviceId){let o=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(xq[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(e))),this.recaptureMode===0){Ua(this.userId,{eventId:2003,param1:7,streamType:2});let n=yield WQ();n[0]?this.recapture(n[0].deviceId):o=!0}o&&vs.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return DA(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(vs.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))})}encodeFrame(e,o){if(!this.manager)return e;let n=o?8:this.mediaType;return this.manager.encodePipeline.reduceRight((a,I)=>I?I({frame:a,mediaType:n}):a,e)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(e=>e)}play(e,o){return Ee(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,o)}close(){vs.off("videoInputAdded",this.handleCameraAdded,this),vs.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return DA(this,null,function*(){try{yield zg(tw.prototype,this,"recapture").call(this,e)}catch(o){let n=(yield WQ()).find(a=>a.deviceId!==e);if(!n)throw o;yield zg(tw.prototype,this,"recapture").call(this,n.deviceId)}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info("setContentHint ".concat(e)),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||Ee(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};vt([Tm(function(A){this.setContentHint(A.contentHint||"motion")})],a4.prototype,"capture");var Su=a4,s4={};XC(s4,{REPORT_TYPE:()=>oM,buildSSOPackage:()=>lu,bytes2ms:()=>ZR,calculateScaleResolutionDownNumber:()=>iM,concatArrayBuffers:()=>zf,convertObjectNumberToInt:()=>tM,copyProperties:()=>RO,deepClone:()=>Mh,deepCloneBasic:()=>wh,deepMerge:()=>tB,delay:()=>AC,fibonacci:()=>Dh,formatedTime:()=>kO,getConstructorName:()=>Vf,getContainerFromElement:()=>xN,getEnv:()=>mO,getFirst16Bits:()=>bO,getInternalVersion:()=>TO,getLast16Bits:()=>rM,getLoggerUrl:()=>fh,getMediaStreamTrackInfo:()=>VN,getMuteStateFromFlag:()=>RQ,getNetworkType:()=>WR,getNumNetworkType:()=>mh,getReconnectionTimeout:()=>yQ,getStringByteLength:()=>eM,getTestSignalDomain:()=>DO,getTurnServer:()=>GO,getUint32Version:()=>PN,getValueType:()=>ya,getViewListFromView:()=>jf,glog:()=>wO,ipv4ToUint32:()=>Kf,isArray:()=>Aa,isAudioWorkletSupported:()=>SO,isBoolean:()=>rn,isConstructor:()=>Rh,isEmpty:()=>$R,isFunction:()=>$n,isLangChinese:()=>nl,isMediaStreamTrack:()=>UN,isNumber:()=>hr,isObject:()=>Xc,isOverseaSdkAppId:()=>rl,isPlainObject:()=>Cc,isPortrait:()=>YN,isPromise:()=>yh,isRemoteTrack:()=>ON,isRotate90Or270:()=>Eu,isSetSinkIdSupported:()=>vO,isString:()=>Sr,isUndefined:()=>Ee,isVideoMixerOutputTrack:()=>MQ,loadImage:()=>Wf,loadVideo:()=>_O,ms2bytes:()=>MO,ms2samples:()=>XR,normalizeUrl:()=>HN,performanceNow:()=>ki,promiseAny:()=>qf,samples2ms:()=>FN,setNetworkTypeFromWebRTC:()=>zR,stringify:()=>al,stringifyIncludeValue:()=>AM,throttlePromise:()=>JN});var reA=[-1,-1,1,-1,-1,1,1,1],neA=[0,0,1,0,0,1,1,1],iG=class Sj extends Uo{constructor(e,o){if(super(),this.context=e,G(this,"name"),G(this,"input"),G(this,"output"),G(this,"texture"),G(this,"ctx2d",null),G(this,"fbo"),G(this,"width",0),G(this,"height",0),G(this,"x",0),G(this,"y",0),G(this,"program"),G(this,"vertexShader"),G(this,"fragmentShader"),G(this,"totalFrames",0),G(this,"dropFrames",0),G(this,"matchInputSize",!0),G(this,"texCoordBuffer"),G(this,"positionBuffer"),G(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),G(this,"cost",0),G(this,"_canvas",null),G(this,"_image"),G(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||e.width,this.height=o.height||e.height,this._image=o.image,e instanceof vu)e.ctx&&o.create2d&&(typeof OffscreenCanvas=="function"&&sl!==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 n=e.ctx;this.texCoordBuffer=this.createBuffer(neA),this.positionBuffer=this.createBuffer(reA),o.createTexture!==!1&&(this.texture=n.createTexture(),this.useTexture(),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)),o.useFbo&&(this.fbo=n.createFramebuffer(),this.useBufferFrame(),this.useTexture(),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,this.width,this.height,0,n.RGBA,n.UNSIGNED_BYTE,null),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,this.texture,0)),o.useDefaultProgram?this.program=e.defaultProgam:(o.vertexShaderSource||o.fragmentShaderSource)&&(this.vertexShader=o.vertexShaderSource?e.createShader(n.VERTEX_SHADER,o.vertexShaderSource):e.defaultVShader,this.fragmentShader=o.fragmentShaderSource?e.createShader(n.FRAGMENT_SHADER,o.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(n){this.context.destroy(new Ct({code:Ge.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(n.message||n)}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let o=this.context.ctx,n=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,n),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,e,0),n}connect(e){for(var o=arguments.length,n=new Array(o>1?o-1:0),a=1;a0&&arguments[0]!==void 0?arguments[0]:0;var o;(o=this.output)==null||o.update(e)}disconnect(){for(var e,o=arguments.length,n=new Array(o),a=0;a{I&&(e.activeTexture(e.TEXTURE0+c),e.bindTexture(e.TEXTURE_2D,I))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let o=this.context.ctx,n=o.createBuffer();return o.bindBuffer(o.ARRAY_BUFFER,n),o.bufferData(o.ARRAY_BUFFER,new Float32Array(e),o.STATIC_DRAW),n}setTexBuffer(e){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,this.texCoordBuffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array(e),o.STATIC_DRAW)}setPosBuffer(e){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,this.positionBuffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array(e),o.STATIC_DRAW)}changeBufferData(e,o){let n=this.context.ctx;n.bindBuffer(n.ARRAY_BUFFER,e),n.bufferData(n.ARRAY_BUFFER,new Float32Array(o),n.STATIC_DRAW)}setAttributes(){let e=this.context.ctx;for(var o=arguments.length,n=new Array(o),a=0;a{e.enableVertexAttribArray(c),e.bindBuffer(e.ARRAY_BUFFER,I),e.vertexAttribPointer(c,2,e.FLOAT,!1,0,0)})}getVertexPoint(e,o){return[e/this.width*2-1,o/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,o){if(this.width!==e||this.height!==o){if(this.width=e,this.height=o,this._canvas&&(this._canvas.width=e,this._canvas.height=o),this.texture&&this.fbo){this.useTexture();let n=this.context.ctx;n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e,o,0,n.RGBA,n.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,o)}}draw(e,o){this.setAttributes(e||this.positionBuffer,o||this.texCoordBuffer);let n=this.context.ctx;n.drawArrays(n.TRIANGLE_STRIP,0,4)}draw2d(e,o,n,a,I,c,u,d,R){let k=!(Ee(c)||Ee(u)||Ee(d)||Ee(R));return!(!this.ctx2d||!e)&&(e instanceof ImageData?(k?this.ctx2d.putImageData(e,o,n,c,u,d,R):this.ctx2d.putImageData(e,o,n),this.emit(Sj.RENDER,this.ctx2d.canvas)):(k?this.ctx2d.drawImage(e,c,u,d,R,o,n,a,I):this.ctx2d.drawImage(e,o,n,a,I),this.emit(Sj.RENDER,e)),typeof VideoFrame<"u"&&e instanceof VideoFrame&&e.close(),!0)}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var e;let{totalFrames:o,x:n,y:a,width:I,height:c,name:u,cost:d}=this,R=Date.now(),k=(o-this.lastInfo.totalFrames)/((R-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:o,x:n,y:a,width:I,height:c,timestamp:R,fps:k,name:u,cost:d},bt({parent:(e=this.input)==null?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let o=this.context.ctx,n=o.createTexture();return this.useTextures(n),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,e),n}};G(iG,"RENDER","render"),vt([is(Uo.INIT,"connected",{sync:!0})],iG.prototype,"connect"),vt([is("connected",Uo.INIT,{ignoreError:!0,sync:!0})],iG.prototype,"disconnect"),vt([is([],"closed",{sync:!0})],iG.prototype,"close");var cl=iG,aeA=Jn(KW(250),Uq(()=>performance.now()),zT()),seA=[0,1,1,1,0,0,1,0],Yq=class extends cl{constructor(A,e){super(A,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},e)),G(this,"_intervalId",0),G(this,"_sequence",0),G(this,"checkGLError",!1),G(this,"checkVisibilityChange"),A instanceof vu?this.ctx2d=A.ctx||null:A.available&&e!=null&&e.mirrorUpAndDown&&this.setTexBuffer(seA)}start(A){this.log.info("".concat(this.name," start render ").concat(A," fps")),nn.clearTask(this._intervalId),this._intervalId=nn.run("intervalInWorker",()=>{if(A!==this.context.frameRate&&(nn.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof aC){let e=this.context.ctx.getError();e&&this.context.destroy(new Ct({code:Ge.VIDEO_MANAGER_ERROR,extraCode:5,message:"".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)}))}},{fps:this.context.frameRate})}render(A){var e;return!((e=this.input)==null||!e.requestFrame(A))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(cl.RENDER,this.context._canvas),!0)}addInput(A){for(var e=arguments.length,o=new Array(e>1?e-1:0),n=1;n0&&arguments[0]!==void 0?arguments[0]:0;this.state!=="closed"&&(this._intervalId&&(nn.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),nn.clearTask(this._intervalId)}resize(A,e){super.resize(A,e),this.context.setSize(A,e)}close(){super.close(),nn.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},Pq=class extends Yq{constructor(A,e){super(A,e),G(this,"_videoTrack"),G(this,"_muteOb"),G(this,"_closedOb",Ln(this,"closed")),G(this,"_subscription"),G(this,"_canvasContainer"),Number(Qu)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=A.canvas.captureStream().getVideoTracks(),this._muteOb=Ln(this._videoTrack,"mute"),Jn(Ln(this._videoTrack,"ended"),Qc(this._closedOb),Ks(()=>{this.context.destroy(new Ct({code:Ge.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){var A;this._subscription=Jn(this._muteOb,Qc(this._closedOb),Mx((A=5e3,e=>{let o=performance.now();Jn(aeA,Fq(n=>n-o{var e;return!((e=this._videoTrack)==null||!e.muted||document.hidden)}),Ks(()=>{this.context.destroy(new Ct({code:Ge.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,e;super.close(),(A=this._videoTrack)==null||A.stop(),delete this._videoTrack,(e=this._canvasContainer)==null||e.remove()}},geA=class extends Pq{render(A){var e;let o=!((e=this.input)==null||!e.requestFrame(A));if(this.context._canvas2d){let n=this.context._canvas2d.getContext("2d");n.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),n.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height),this.emit(cl.RENDER,this.context._canvas2d)}else this.emit(cl.RENDER,this.context._canvas);return o}},IeA=class extends Pq{constructor(A,e,o){super(A,{name:"smallDestination",logger:o}),this.resolution=e}resize(A,e){let o,n=A*e,a=this.resolution.width*this.resolution.height;this.log.info("big res: ".concat(A,"*").concat(e," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),n>a?o=n/a:(this.log.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(A," * ").concat(e," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),o=n/19200),super.resize(A/Math.sqrt(o),e/Math.sqrt(o))}},g4=class extends cl{constructor(A,e){super(A,bt({name:"imageSource"},e)),G(this,"_lastImage"),G(this,"_totalFrames",0),G(this,"_autoResize",!1),G(this,"_canvasRendered"),G(this,"videoCallbackId",0),G(this,"waitingFirstFrame",!0),G(this,"shouldUpdate",!0),this._autoResize=e?.autoResize!==!1,sl===16&&(this._canvasRendered=wu(),Jn(this._canvasRendered,kq(this._image),yx(o=>o instanceof HTMLCanvasElement?Ln(o,"rendered"):Lq()),Qc(Ln(this,"closed")),Ks(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let A=this.image;this.videoCallbackId&&A.cancelVideoFrameCallback(this.videoCallbackId),HQ()&&!document.hidden&&(this.videoCallbackId=A.requestVideoFrameCallback((e,o)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=o.presentedFrames,this.update(1))}))}_render(A,e){var o;let{width:n,height:a}=this,{image:I}=this;if(I instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:n,videoHeight:a}=I,!n||!a)return!1;I.width=n,I.height=a}else if(I instanceof HTMLImageElement||I instanceof ImageData||I instanceof ImageBitmap){if({width:n,height:a}=I,I!==this._lastImage)this._lastImage=I;else if(n===this.width&&a===this.height)return!0}else I instanceof HTMLCanvasElement||I instanceof OffscreenCanvas?({width:n,height:a}=I,this._lastImage=I):typeof VideoFrame<"u"&&I instanceof VideoFrame&&({displayWidth:n,displayHeight:a}=I,(o=this._lastImage)==null||o.close(),this._lastImage=I);if(!this._autoResize)return!0;if(this.width===n&&this.height===a&&this.totalFrames){if(e){this.useTexture();let c=this.context.ctx;c.texSubImage2D(c.TEXTURE_2D,0,0,0,c.RGBA,c.UNSIGNED_BYTE,I)}}else{if(e){this.useTexture();let c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,I)}this.resize(n,a)}return!0}get image(){return this._image}set image(A){var e;(e=this._canvasRendered)==null||e.next(A),this._image=A}render(A){return this._render(A,!0)}render2d(A){return this._render(A,!1)}},I4=class extends g4{constructor(A,e,o){super(A,o),this._player=e,this.name="videoPlayerSource",Jn(Ln(this._player,mi.PLAYER_STATE_CHANGED),Qc(Ln(this,"closed")),Gm(n=>{let{state:a}=n;return a==="PLAYING"}),Ks(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},xM=class extends I4{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(A,e,o){super(A,new wi({id:o.name,track:e,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()}},ceA=class extends cl{constructor(A,e,o){super(A,fi(bt({name:"textSource"},o),{create2d:!0})),G(this,"hasChange",!0),G(this,"content",""),this.ctx2d.textBaseline="top",this.content=e.content||"",e.font&&(this.font=e.font),e.color&&(this.color=e.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,e){if(!this.ctx2d)return;let{color:o,font:n}=this;super.resize(A,e),this.color=o,this.font=n}drawMultilineText(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=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 n=this.ctx2d.measureText(this.content);e+=n.fontBoundingBoxAscent||n.actualBoundingBoxAscent||0;let a=this.font.match(/(\d+)px/),I=(a?parseInt(a[1],10):16)*o,c=this.content.split(` +`);for(let u=0;u0&&arguments[0]!==void 0&&arguments[0];if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(oG._ids++)),A&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",NN),!this.ctx)throw new Ct({code:Ge.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,` // 顶点着色器 attribute vec4 a_position; attribute vec2 a_texCoord; @@ -200,27 +200,27 @@ 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 Ct({code:Ge.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(A){let e="";return A&&(e=A.message,this.error=A,ct.addFailedEvent({key:512702,error:A})),this.disconnect(),this.log.info("video context destroy".concat(e)?": ".concat(e):""),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 e;(e=this.ctx)==null||e.viewport(0,0,A,this.height),super.width=A,this._canvas2d&&(this._canvas2d.width=A)}set height(A){var e;(e=this.ctx)==null||e.viewport(0,0,this.width,A),super.height=A,this._canvas2d&&(this._canvas2d.height=A)}setSize(A,e){var o;(o=this.ctx)==null||o.viewport(0,0,A,e),super.setSize(A,e),this._canvas2d&&(this._canvas2d.width=A,this._canvas2d.height=e)}createShader(A,e){let o=this.ctx,n=o.createShader(A);return o.shaderSource(n,e),o.compileShader(n),n}createProgram(A,e){let o=this.ctx,n=o.createProgram();return o.attachShader(n,A),o.attachShader(n,e),o.linkProgram(n),o.getProgramParameter(n,o.LINK_STATUS)||this.log.error(o.getProgramInfoLog(n)),n}};G(eG,"UNAVAILABLE","unavailable"),vt([is(Uo.INIT,"created",{sync:!0,fail(A){this.log.error("video gl context create failed",A.cause),ct.addFailedEvent({key:512700,error:A.cause||A})},success(){this.log.info("video context created use webgl"),ct.addSuccessEvent({key:512700})}})],eG.prototype,"create"),vt([is("created",Uo.INIT,{ignoreError:!0,sync:!0,success(A){A&&this.emit(eG.UNAVAILABLE,A),this.removeAllListeners()}})],eG.prototype,"destroy");var aC=eG,Mu=class extends AG{constructor(){super(...arguments),G(this,"ctx")}create(A){if(this.hasAlpha=A.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(AG._ids++),this.ctx=this._canvas.getContext("2d",{alpha:A.alpha,willReadFrequently:A.willReadFrequently}),!this.ctx)throw new Ct({code:Ge.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 e="";A&&(e=A.message,this.error=A,ct.addFailedEvent({key:512703,error:A})),this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),ct.addSuccessEvent({key:512703})}};function $AA(A,e,o,n,a){arguments.length>5&&arguments[5]!==void 0&&arguments[5]&&([o,n]=[n,o]);let I={sWidth:A,sHeight:e,dWidth:o,dHeight:n,sx:0,sy:0,dx:0,dy:0};if(A===0||e===0)return I;switch(a){case void 0:case"fill":break;case"contain":{let c=Math.min(o/A,n/e);I.dWidth=A*c,I.dHeight=e*c,I.dx=(o-I.dWidth)/2,I.dy=(n-I.dHeight)/2;break}case"cover":{let c=Math.max(o/A,n/e),u=o/c,d=n/c;I.sx=(A-u)/2,I.sy=(e-d)/2,I.sWidth=u,I.sHeight=d;break}}return I}vt([is(Uo.INIT,"created",{sync:!0,fail(A){this.log.error("video 2d context create failed",A.cause),ct.addFailedEvent({key:512701,error:A.cause||A})},success(){this.log.info("video context created use 2d"),ct.addSuccessEvent({key:512701})}})],Mu.prototype,"create"),vt([is("created",Uo.INIT,{ignoreError:!0,sync:!0})],Mu.prototype,"destroy");var AeA=class{constructor(A,e){this.node=A,this.layout=e,G(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}},o4=class extends Il{constructor(A,e){super(A,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:e}),G(this,"inputs",[]),G(this,"backgroundColor","black")}addInput(A,e){let o=0,n=this.inputs.length;for(;oe.zIndex))throw new Error("input already exists at zIndex ".concat(e.zIndex));n=I}}let a=new AeA(A,e);this.inputs.splice(o,0,a)}changeInputLayout(A,e){let o=this.inputs.findIndex(Z=>Z.node===A);if(o<0)return;let{x:n,y:a,width:I,height:c,zIndex:u,fillMode:d,rotation:R,hidden:k}=e;if(!Ee(u)&&this.inputs.some(Z=>Z.layout.zIndex===u&&Z.node!==A))throw new Error("input already exists at zIndex ".concat(e.zIndex));let _=this.inputs[o];Ee(n)||(_.layout.x=n),Ee(a)||(_.layout.y=a),Ee(I)||(_.layout.width=I),Ee(c)||(_.layout.height=c),Ee(R)||(_.layout.rotation=R),Ee(k)||(_.layout.hidden=k),d&&(_.layout.fillMode=d),!Ee(u)&&u!==_.layout.zIndex&&(_.layout.zIndex=u,this.inputs.sort((Z,iA)=>Z.layout.zIndex-iA.layout.zIndex))}hasInput(A){return this.inputs.some(e=>e.node===A)}hasNoInput(){return this.inputs.length===0}resize(A,e){if(!this.matchInputSize)return void super.resize(A,e);let o=this.inputs.reduce((n,a)=>a?Object.assign(n,{width:Math.max(n.width,a.right),height:Math.max(n.height,a.bottom)}):n,{width:0,height:0});super.resize(o.width,o.height),this.context instanceof aC&&this.inputs.forEach(n=>{if(n){let a=this.layout2texCoords(n);n.positionBuffer?this.changeBufferData(n.positionBuffer,a):n.positionBuffer=this.createBuffer(a)}})}connect(A){for(var e=arguments.length,o=new Array(e>1?e-1:0),n=1;ne.node!==A),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(A){let e=this.context.ctx;if(e.clearColor(0,0,0,0),this.inputs.reduce((o,n)=>n.node.requestFrame(A)||o,!1)&&e){this.useProgram(),e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;oe.node.requestFrame(A)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let e=0;e4&&arguments[4]!==void 0&&arguments[4];this.ctx2d&&(a&&([o,n]=[n,o]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(A,e,o,n),this.ctx2d.restore())}getInfo(){let{totalFrames:A,x:e,y:o,width:n,height:a,name:I}=this,c=Date.now(),u=(A-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:A,x:e,y:o,width:n,height:a,timestamp:c,fps:u,name:I},bt({parent:this.inputs.filter(d=>d).map(d=>d.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(A=>{var e;if(A.node.disconnect(),A.positionBuffer&&this.context instanceof aC)try{(e=this.context.ctx)==null||e.deleteBuffer(A.positionBuffer)}catch{}})}close(){super.close(),this.removeAllInputs()}},eeA=[1,0,0,0,1,1,0,1],Zh=class extends Il{constructor(A,e,o,n){if(super(A,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:e}),G(this,"mirror",!1),G(this,"rotation",0),o&&(this.mirror=o),n&&(this.rotation=n),A instanceof aC)try{this.setTexBuffer(eeA)}catch(a){A.destroy(new Ct({code:Ge.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(a.message||a)}))}}draw2d(A,e,o,n,a){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(n,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(a/n,n/a)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,a),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(a/n,n/a));let I=super.draw2d(A,e,o,n,a);return this.ctx2d.restore(),I}return!1}render(A){var e;return!((e=this.input)==null||!e.requestFrame(A))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}resize(A,e){gu(this.rotation)&&([A,e]=[e,A]),super.resize(A,e)}},Fq=class extends ZT{constructor(A){super(arguments.length>1&&arguments[1]!==void 0?arguments[1]:4,wi),G(this,"inputLocalVideoTracks",new Map),G(this,"inputLocalScreenTracks",new Map),G(this,"cameraNodeMap",new Map),G(this,"screenNodeMap",new Map),G(this,"textNodeMap",new Map),G(this,"imageNodeMap",new Map),G(this,"videoNodeMap",new Map),G(this,"endedIds",new Set),G(this,"videoContext"),G(this,"mixNode"),G(this,"destination"),G(this,"manager"),G(this,"stat"),G(this,"_checkId",0),G(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(Il.RENDER,e=>{this.emit("render",e)}),this.mixNode=new o4(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=nn.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:A})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new Mu({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(A){this.autoSetFps=!1,this.videoContext.frameRate=A;for(let e of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])e.shouldUpdate=!1;setTimeout(()=>{var e;return(e=this.destination)==null?void 0:e.start(this.videoContext.frameRate)},500)}setFpsAuto(){var A;if(!this.autoSetFps)return;for(let a of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])a.shouldUpdate=!1;let e=null,o=0,n=!0;for(let[a,I]of this.inputLocalVideoTracks)if(I.profile.frameRate>o){if(this.endedIds.has(a)){let c=this.cameraNodeMap.get(a);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}o=I.profile.frameRate,e=a}for(let[a,I]of this.inputLocalScreenTracks)if(I.profile.frameRate>o){if(this.endedIds.has(a)){let c=this.screenNodeMap.get(a);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}o=I.profile.frameRate,e=a,n=!1}if(e!==null){let a=n?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);a&&(a.shouldUpdate=!0,a.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,e){var o;(o=this.mixNode)==null||o.resize(A,e)}startMix(){return DA(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),TQ&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(A=this.manager)==null||A.changeInput(this)})}addCameraSource(A,e,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 n,{mediaTrack:a}=e;if(!a)throw new Error("no mediaTrack, add cameraSource failed");e.recaptureMode=1,nE(this,vs).add("videoInputRemoved",I=>{I.deviceId===e.deviceId&&(this.endedIds.add(A),this.setFpsAuto())}),e.on("output-media-track-changed",()=>{this.endedIds.delete(A),this.updateCameraSource(A,o,e.mediaTrack)}),n=al===16&&a instanceof CanvasCaptureMediaStreamTrack?this.videoContext.createVideoImageSource(a.canvas,{name:"cameraCanvasSource",logger:this.log}):this.videoContext.createVideoTrackSource(a,"cameraNodeSource"),n.resize(e.settings.width,e.settings.height),n.shouldUpdate=!1,this._connectMix(n,o,"cover"),this.inputLocalVideoTracks.set(A,e),this.cameraNodeMap.set(A,n),this.setFpsAuto()}addScreenSource(A,e,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:n}=e;if(!n)throw new Error("no mediaTrack, add screenSource failed");e.on("output-media-track-changed",()=>{this.updateScreenSource(A,o,e.mediaTrack)});let a=this.videoContext.createVideoTrackSource(n,"screenNodeSource");a.resize(e.settings.width,e.settings.height),a.shouldUpdate=!1,this._connectMix(a,o),this.inputLocalScreenTracks.set(A,e),this.screenNodeMap.set(A,a),this.setFpsAuto()}addTextSource(A){let{id:e,content:o="",font:n,color:a,layout:I}=A;if(this.textNodeMap.has(e))throw new Error("There is already a textSource with the same ID: ".concat(e));let c=this.videoContext.createTextSource({content:o,font:n,color:a});c.resize(I.width,I.height),this._connectMix(c,I),this.textNodeMap.set(e,c)}addImageSource(A,e,o){if(this.imageNodeMap.has(A))throw new Error("There is already a imageSource with the same ID: ".concat(A));let n=this.videoContext.createVideoImageSource(e,{autoResize:!1,logger:this.log});n.resize(e.width,e.height),this._connectMix(n,o),this.imageNodeMap.set(A,n)}addVideoSource(A,e,o){if(this.videoNodeMap.has(A))throw new Error("There is already a videoSource with the same ID: ".concat(A));let n=this.videoContext.createVideoImageSource(e,{autoResize:!1,logger:this.log});n.resize(e.videoWidth,e.videoHeight),n.shouldUpdate=!1,this._connectMix(n,o),this.videoNodeMap.set(A,n)}updateCameraSource(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,n=arguments.length>3?arguments[3]:void 0,a=this.inputLocalVideoTracks.get(A);a&&o&&o!==a.mediaTrack&&(this.log.debug("updateCameraSource mixerLocalVideoTrack newTrack:",o,"oldTrack:",a.mediaTrack),a.setInputMediaStreamTrack(o));let I=this.cameraNodeMap.get(A);if(I){if(o){if(al===16&&o instanceof CanvasCaptureMediaStreamTrack)if(I instanceof FM){let d=I.output;I.close(),I=this.videoContext.createVideoImageSource(o.canvas,{name:"cameraCanvasSource",logger:this.log}),I.connect(d),this.cameraNodeMap.set(A,I)}else I.image=o.canvas;else if(I instanceof FM)I.replaceTrack(o);else{let d=I.output;I.close(),I=this.videoContext.createVideoTrackSource(o,"cameraNodeSource"),I.connect(d),this.cameraNodeMap.set(A,I)}let{width:c,height:u}=o.getSettings();c&&u&&I.resize(c,u)}n&&I.resize(n.width,n.height),(n||o)&&this.setFpsAuto(),this._changeMixLayout(I,e)}}updateScreenSource(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,n=this.inputLocalScreenTracks.get(A);this.log.debug("updateScreenSource mixerLocalScreenTrack",n,o),n&&o&&o!==n.mediaTrack&&n.setInputMediaStreamTrack(o);let a=this.screenNodeMap.get(A);a&&(o&&a.replaceTrack(o),this._changeMixLayout(a,e))}updateTextSource(A){let{id:e,content:o,font:n,color:a,layout:I}=A,c=this.textNodeMap.get(e);c&&(Ee(o)||(c.content=o),Ee(n)||(c.font=n),Ee(a)||(c.color=a),c.resize(I.width,I.height),this._changeMixLayout(c,I))}updateImageSource(A,e,o){let n=this.imageNodeMap.get(A);n&&(o&&(n.image=o,n.resize(o.width,o.height)),this._changeMixLayout(n,e))}updateVideoSource(A,e,o){let n=this.videoNodeMap.get(A);if(n){if(o){let a=n.image;a instanceof HTMLVideoElement&&this.stopVideoElement(a),n.image=o,n.resize(o.videoWidth,o.videoHeight)}this._changeMixLayout(n,e)}}_connectMix(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"contain";if(!this.mixNode)return;let{mirror:n,rotation:a}=e;A.disconnect();let I=new Zh(this.videoContext,this.log,n,a);I=A.connect(I),e.fillMode||(e.fillMode=o),I.connect(this.mixNode,e)}_changeMixLayout(A,e){if(!this.mixNode)return;let{mirror:o,rotation:n}=e,a=A.output||A;a instanceof Zh&&(Ee(o)||(a.mirror=o),Ee(n)||(a.rotation=n),a.resize(A.width,A.height)),this.mixNode.changeInputLayout(a,e)}removeCameraSource(A){let e=this.inputLocalVideoTracks.get(A);if(!e)return;e.close(),this.inputLocalVideoTracks.delete(A);let o=this.cameraNodeMap.get(A);o&&(o.output instanceof Zh&&o.output.close(),o.close(),this.cameraNodeMap.delete(A)),this.checkAfterRemove(!0)}removeScreenSource(A){let e=this.inputLocalScreenTracks.get(A);if(!e)return;e.close(),this.inputLocalScreenTracks.delete(A);let o=this.screenNodeMap.get(A);o&&(o.output instanceof Zh&&o.output.close(),o.close(),this.screenNodeMap.delete(A)),this.checkAfterRemove(!0)}removeTextSource(A){let e=this.textNodeMap.get(A);e&&(e.output instanceof Zh&&e.output.close(),e.close(),this.textNodeMap.delete(A)),this.checkAfterRemove()}removeImageSource(A){let e=this.imageNodeMap.get(A);e&&(e.output instanceof Zh&&e.output.close(),e.close(),this.imageNodeMap.delete(A)),this.checkAfterRemove()}removeVideoSource(A){let e=this.videoNodeMap.get(A);e&&(e.output instanceof Zh&&e.output.close(),e.image instanceof HTMLVideoElement&&this.stopVideoElement(e.image),e.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(),nn.clearTask(this._checkId),(A=this.videoContext)==null||A.destroy(),delete this.mixNode,delete this.destination;for(let e of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])e.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),pr(this);for(let e of this.videoNodeMap.values())e.image instanceof HTMLVideoElement&&this.stopVideoElement(e.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}},Uq=hA();if(typeof navigator<"u"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:Uq,exposeOrigin:!0,permittedOrigins:["*"]})}catch{}var teA=function(A){return DA(this,null,function*(){let e=null,o=function(I){let c={preferCurrentTab:I.preferDisplaySurface==="current-tab"||!!I.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},u={width:Ma?{max:I.width}:{ideal:I.width,max:I.width},height:Ma?{max:I.height}:{ideal:I.height,max:I.height},frameRate:I.frameRate,displaySurface:I.preferDisplaySurface||"monitor"};if(c.video=u,I.systemAudio){let{echoCancellation:d=!0,noiseSuppression:R=!1,autoGainControl:k=!1}=I;c.audio={echoCancellation:d,noiseSuppression:R,autoGainControl:k,sampleRate:48e3}}return c}(A);nA.info("getDisplayMedia with constraints: ".concat(JSON.stringify(o)));let n=yield navigator.mediaDevices.getDisplayMedia(o);A.systemAudio&&n.getAudioTracks().length===0&&(BM&&tE<74||Ma||Yr)&&nA.warn("Your browser not support capture system audio");let a=n.getVideoTracks()[0];if(a){if(A.frameRate)try{yield a.applyConstraints({frameRate:{min:A.frameRate,ideal:A.frameRate},width:A.width,height:A.height})}catch(I){nA.warn("screen applyConstraints failed: ".concat(I))}A.captureElement&&(yield function(I,c){return DA(this,null,function*(){var u;if("CropTarget"in window&&"fromElement"in CropTarget&&$n(I.cropTo))try{if(((u=I.getCaptureHandle())==null?void 0:u.handle)!==Uq)return;let d=yield CropTarget.fromElement(c);yield I.cropTo(d)}catch(d){nA.warn("cropTo target failed ".concat(d))}})}(a,A.captureElement))}if(A.audio){let I=function(c){let u={echoCancellation:c.echoCancellation,autoGainControl:c.autoGainControl,noiseSuppression:c.noiseSuppression,sampleRate:c.sampleRate,channelCount:c.channelCount};return Ee(c.microphoneId)||(u.deviceId=c.microphoneId),{audio:u,video:!1}}(A);nA.info("getUserMedia with constraints: ".concat(JSON.stringify(I))),e=yield navigator.mediaDevices.getUserMedia(I),n.addTrack(e.getAudioTracks()[0])}return n})},Nm=class extends Ru{constructor(A){super(A,2),G(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),G(this,"objectFit","contain"),G(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}get isShareCurrentTab(){var A,e;try{return Uq===((e=(A=this.mediaTrack)==null?void 0:A.getCaptureHandle())==null?void 0:e.handle)}catch{return}}capture(A){return DA(this,arguments,function(e){var o=this;let{systemAudio:n=!1,autoGainControl:a,echoCancellation:I,noiseSuppression:c,audioTrack:u,videoTrack:d,captureElement:R,preferDisplaySurface:k}=e;return function*(){var _;try{let Z,iA=ki();return d||u?(Z=new MediaStream,d&&Z.addTrack(d),u&&Z.addTrack(u)):(Z=yield teA({audio:!1,systemAudio:n,width:o.profile.width,height:o.profile.height,frameRate:o.profile.frameRate,autoGainControl:a,echoCancellation:I,noiseSuppression:c,captureElement:R,preferDisplaySurface:k}),o.sourceTrack=Z.getVideoTracks()[0]),yield o.setInputMediaStreamTrack(Z.getVideoTracks()[0]),S.emit(K.LOCAL_TRACK_CAPTURE_SUCCESS,{track:o,cost:ki()-iA,profile:o.profile,room:(_=o.manager)==null?void 0:_.room}),Z}catch(Z){throw o.log.error("getDisplayMedia error observed ".concat(Z)),Z instanceof Ct?Z:new Ct({code:Ge.INITIALIZE_FAILED,name:Z.name,message:Z.message})}}()})}switchDevice(A){return DA(this,null,function*(){throw new Error("Method not implemented.")})}};vt([wm(function(A){this.setContentHint(A.contentHint||"detail")})],Nm.prototype,"capture");var Oq,xq=class extends vm{constructor(A){super(A),this._log.id="s-".concat(this._log.id),this.isScreen=!0}addAudioProcessor(A,e,o){this.pipeline.silentNode.setNode(o),this.pipeline.mixNode.setNode(e),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 Yq(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,n=arguments.length>3?arguments[3]:void 0;return DA(this,null,function*(){let a=tI();Oq||(Oq=Fa(a,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;tu.connect(c,0,d)),new ReadableStream({start(u){c.port.onmessage=d=>{u.enqueue(d.data)}},cancel(){A.forEach(u=>u.disconnect(c)),c.port.close()}})})}var ieA=class extends d${constructor(A){super(),this.room=A,G(this,"_localAudioTrack"),G(this,"_localScreenAudioTrack"),G(this,"log"),G(this,"denoiser"),G(this,"voiceChanger"),G(this,"mixChangedDebounce"),G(this,"audioProcessor"),G(this,"encodePipeline",[]),G(this,"decodePipeline",[]),G(this,"getPCMAbortCtrlMap",new Map),G(this,"audioFrameEventConfigMap",new Map),G(this,"audioReferenceMap",new Map),G(this,"isLocalAudioNeedAudioProcess",!1),G(this,"isScreenAudioNeedAudioProcess",!1),this.log=nA.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 e,o;if(!this._localAudioTrack)return;let n=[],a=[];(e=this._localAudioPipline)!=null&&e.source.node&&(n.push(this._localAudioPipline.source.node),a.push("mic")),(o=this._localAudioPipline)!=null&&o.denoiser.node&&(n.push(this._localAudioPipline.denoiser.node),a.push("mic-processed")),this.mixWeight>1&&(n.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),a.push("mix")),this.log.info("dump audio track ".concat(a,", duration: ").concat(A));let I=new AbortController,c=[],u=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),I.abort("timeout")},1e3*A),d=()=>{for(let k=0;kk.pipeTo(new WritableStream({write(_){_.forEach((Z,iA)=>c[iA]=c[iA]?c[iA].concat(Z[0]):[Z[0]])}}),I).catch(_=>d));return{then:R.then.bind(R),download:d}}getPCM(A,e){var o,n,a;if(typeof WritableStream>"u")return void this.log.warn("getPCM failed: browser not support WritableStream");let{enable:I,sampleRate:c=48e3,channelCount:u=1,port:d}=(e===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(e)||this.audioFrameEventConfigMap.get("*"))||{};if(!I)return;this.log.info("getPCM ".concat(e||"local"));let R,k,_=Math.floor(.04*c),Z=new Float32Array(_),iA=new Float32Array(_),cA=0,TA=new AbortController,JA=e===""?(o=this._localAudioTrack)==null?void 0:o.mediaTrack:(a=(n=this.room)==null?void 0:n.remotePublishedUserMap.get(e))==null?void 0:a.remoteAudioTrack.mediaTrack;if(JA)return Yq([tI().createMediaStreamSource(new MediaStream([JA]))],c,u,d).then(Ie=>Ie.pipeTo(new WritableStream({write(XA){XA[0][0]&&(cA+XA[0][0].length>_?(Z.set(XA[0][0].subarray(0,_-cA),cA),R=XA[0][0].subarray(_-cA),XA[0][1]&&(iA.set(XA[0][1].subarray(0,_-cA),cA),k=XA[0][1].subarray(_-cA)),cA+=_-cA):(R&&(Z.set(R,cA),cA+=R.length,R=void 0),k&&(iA.set(k,cA),k=void 0),Z.set(XA[0][0],cA),XA[0][1]&&iA.set(XA[0][1],cA),cA+=XA[0][0].length),cA>=_&&(cA=0,A({userId:e,sampleRate:c,channelCount:u,data:u===1?Z:[Z,iA]}),Z=new Float32Array(_),iA=new Float32Array(_)))}}),TA).catch(XA=>this.log.warn("stop getPCM reason:".concat(XA)))),TA;this.log.info("getPCM failed: ".concat(e||"local"," has no audio track"))}get hasScreenAudioTrack(){return!Ee(this._localScreenAudioTrack)}get hasAudioTrack(){return!Ee(this._localAudioTrack)}changeInput(A){var e,o;return A instanceof xq?(this._localScreenAudioTrack=A,this.isScreenAudioNeedAudioProcess&&(e=this.audioProcessor)!=null&&e.screenAudioWorkletNode&&(A.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((n,a)=>{A.mixAudioReference(n,a)})),A.pipeline.connect(),this.mixOnChange()):A instanceof vm?(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((n,a)=>{A.mixAudioReference(n,a)})),A.pipeline.connect(),this.mixOnChange()):A instanceof Dx?A.setOutputMediaStreamTrack(A.mediaTrack):void 0}mixAudioReference(A,e){var o;(o=this._localAudioTrack)==null||o.mixAudioReference(A,e)}unMixAudioReference(A){var e;(e=this._localAudioTrack)==null||e.unMixAudioReference(A)}setAudioReferenceVolume(A,e){var o;(o=this._localAudioTrack)==null||o.setAudioReferenceVolume(A,e)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var A,e;return delete this.mixChangedDebounce,Promise.all([(A=this._localAudioTrack)==null?void 0:A.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(e=this._localScreenAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(A){A instanceof xq?delete this._localScreenAudioTrack:A instanceof vm&&delete this._localAudioTrack}addDenoiser(A){var e;this.denoiser=A,(e=this._localAudioTrack)==null||e.addDenoiser(A)}addAudioProcessor(A,e,o,n){var a;this.audioProcessor={localAudioWorkletNode:o,mixNode:A,silentNode:e,screenAudioWorkletNode:n},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&o&&(this._localAudioTrack.addAudioProcessor(o,A,e),this.audioReferenceMap.forEach((I,c)=>{var u;(u=this._localAudioTrack)==null||u.mixAudioReference(I,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&n&&((a=this._localScreenAudioTrack)==null||a.addAudioProcessor(n,A,e),this.audioReferenceMap.forEach((I,c)=>{var u;(u=this._localScreenAudioTrack)==null||u.mixAudioReference(I,c)}))}removeDenoiser(A){var e;return delete this.denoiser,(e=this._localAudioTrack)==null?void 0:e.removeDenoiser(A)}addVoiceChanger(A,e){var o;this.voiceChanger=[A,e],(o=this._localAudioTrack)==null||o.pipeline.voiceChanger.setNode(A,e)}removeVoiceChanger(){var A;delete this.voiceChanger,(A=this._localAudioTrack)==null||A.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(A,e){var o,n;delete this.audioProcessor,(o=this._localAudioTrack)==null||o.removeAudioProcessor(A),(n=this._localScreenAudioTrack)==null||n.removeAudioProcessor(e)}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:e,type:o}=A;var n;this.encodePipeline.includes(e)||(this.encodePipeline[o]=e,(n=this.room)==null||n.enableInsertableStreams())}addDecodeProcessor(A){let{processor:e,type:o}=A;var n;this.decodePipeline.includes(e)||(this.decodePipeline[o]=e,(n=this.room)==null||n.enableInsertableStreams())}removeEncodeProcessor(A){let{type:e}=A;this.encodePipeline[e]=void 0}removeDecodeProcessor(A){let{type:e}=A;this.decodePipeline[e]=void 0}handleLocalTrackStarted(A){let{room:e,userId:o}=A;var n;if(e!==this.room||this.getPCMAbortCtrlMap.get(o))return;let a=this.getPCM(I=>{var c;(c=this.room)==null||c.emit("audio-frame",I)},"");this.getPCMAbortCtrlMap.set(o,a),this.getPCMAbortCtrlMap.get(o)&&((n=this._localAudioTrack)==null||n.on("input-media-track-changed",()=>{let I=this.getPCMAbortCtrlMap.get(o);I&&(I.abort("inputMediaTrackChanged"),I=this.getPCM(c=>{var u;(u=this.room)==null||u.emit("audio-frame",c)},""),this.getPCMAbortCtrlMap.set(o,I))}))}handleLocalTrackStopped(A){let{room:e,userId:o}=A;if(e!==this.room)return;let n=this.getPCMAbortCtrlMap.get(o);n&&(n.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(o))}handleRemoteTrackStarted(A){let{room:e,userId:o}=A;if(e===this.room&&!this.getPCMAbortCtrlMap.get(o)){let n=this.room.audioManager.getPCM(a=>{var I;(I=this.room)==null||I.emit("audio-frame",a)},o);this.getPCMAbortCtrlMap.set(o,n)}}handleRemoteTrackStopped(A){let{room:e,userId:o}=A;if(e!==this.room)return;let n=this.getPCMAbortCtrlMap.get(o);n&&(n.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(o))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference(A){let{type:e,audioReference:o,refId:n,volume:a}=A;if(e==="add"){if(this.audioReferenceMap.get(n)||!o||(this.audioReferenceMap.set(n,o),!this.audioProcessor))return;this.mixAudioReference(o,n)}else if(e==="remove")this.audioReferenceMap.get(n)&&(this.audioReferenceMap.delete(n),this.unMixAudioReference(n));else if(e==="updateVolume"){if(!this.audioProcessor||Ee(a))return;this.setAudioReferenceVolume(n,a)}}};function mx(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return Dn((o,n)=>function(){for(var a=arguments.length,I=new Array(a),c=0;c{let R=setTimeout(()=>{let k=new Ct({code:Ge.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(n,"() timeout ").concat(A,"s")});(this.log||this._log||nA).warn(k),e===2?d(k):e===1&&u()},1e3*A);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(R),o.apply(this,I).then(u,d).finally(()=>{clearTimeout(R),this._checkPendingPromiseSet&&R&&this._checkPendingPromiseSet.delete(R)})})})}var Tm=class Dj extends yq{constructor(e,o,n){super({userId:o.userId,sdkAppId:e.sdkAppId,mediaType:n,room:e}),this.room=e,this.user=o,G(this,"tinyId"),G(this,"isRemote",!0),G(this,"jitterBufferDelay",0),G(this,"availableState"),G(this,"remotePublishState"),G(this,"_triggerCheckDecodeSubject",yu(Ln(this,Dj.STATE_SUBSCRIBE))),G(this,"ignoreUpdatePlayingState"),this.tinyId=o.tinyId,this.availableState=new Uo("".concat(o.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new Uo("".concat(o.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),Jn(Mq(Ln(this,Uo.STATECHANGED),Ln(this.remotePublishState,Uo.STATECHANGED)),Gq(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Ks(u=>{this.availableState.state!==(u?Uo.ON:Uo.OFF)&&(this.availableState.state=u?Uo.ON:Uo.OFF),(!this.isRemotePublished||!this.ignoreUpdatePlayingState)&&this.updatePlayingState(u)}));let a=Jn(Ln(this.player,mi.ERROR),Sm(u=>u.code===MediaError.MEDIA_ERR_DECODE)),I=Jn(vq(5e3),Sm(()=>!!(!this.ignoreDecodeError&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived&&this.isRemotePublished)&&(!this.player.isPlaying&&!(this.kind===fA.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1)))),c=Jn(bW(a,I),Qc(Ln(this,Uo.INIT)));Jn(this._triggerCheckDecodeSubject,Sm(()=>!this.ignoreDecodeError),hx(c),Ks(u=>{this.reportDecodeResult(!1,u)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var e,o,n,a;return(a=(n=(o=(e=this.room)==null?void 0:e.networkQuality)==null?void 0:o.hadRecentBadDownlink)==null?void 0:n.call(o,2))!=null&&a||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Dj.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===Uo.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,o){var n,a;let I=this.kind===fA.AUDIO;if(ct[e?"addSuccessEvent":"addFailedEvent"]({key:I?504700:514702}),!I){let c=((n=this.room)==null?void 0:n.downlinkVideoCodec.toUpperCase())||"H264";ct[e?"addSuccessEvent":"addFailedEvent"]({key:Yh["DECODE_".concat(c,"_RESULT")]}),e||this.log.warn("".concat((a=this.room)==null?void 0:a.downlinkVideoCodec," decode failed"))}e||(ct.addEnum({key:I?504701:514703,value:_Q()}),Jo.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(Qu()||bQ()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===fA.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:o}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===e){if(e&&(!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(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?Uo.ON:Uo.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};G(Tm,"STATE_SUBSCRIBE","subscribe"),vt([mx(5,1)],Tm.prototype,"waitHasMediaTrack"),vt([is(Uo.INIT,Tm.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(K.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),jh(521716,!1)],Tm.prototype,"subscribe"),vt([is(Tm.STATE_SUBSCRIBE,Uo.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(K.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],Tm.prototype,"unsubscribe");var r4=Tm,Dx=class extends r4{constructor(A,e){super(A,e,1),G(this,"volume",0),G(this,"mediaType",1),G(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=A.audioManager}get dbVolume(){return gx.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,e;return!!this.manager&&(this.manager.decodePipeline.some(o=>o)||((e=(A=this.player.element)==null?void 0:A.error)==null?void 0:e.code)===MediaError.MEDIA_ERR_DECODE&&wM().AudioDecoder&&xQ)}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(A){if(!this.manager)return A;let e=A;for(let[o,n]of this.manager.decodePipeline.entries()){if(!n)continue;let a={frame:A,track:this};if(o===1&&this.isAvailable&&this.room.role==="audience"&&(a.onAudioFrameNTPTime=I=>{let{ntp:c,frame:u,hasLeavingTag:d}=I;this.emit("audio-frame-with-ntp",{ntp:c,frame:u,hasLeavingTag:d})}),e=n(a),!e)return}return e}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}},oeA=class extends Il{constructor(A,e,o,n,a){super(A,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:e}),this.setContainer=n,G(this,"initStat",{alphaStitchingType:1}),G(this,"end",yu()),G(this,"minSize",320),G(this,"maxSize",1280),G(this,"draggable",!1),G(this,"startDragX",0),G(this,"startDragY",0),G(this,"left",0),G(this,"top",0),G(this,"baseWidth",320),G(this,"baseRatio"),G(this,"container"),this.initStat=a,this.draggable=o,this.bindDragEvents(),ct.addEnum({key:515700,value:1}),this.draggable&&ct.addEnum({key:515700,value:11})}bindDragEvents(){let A=this.context._canvas;if(A)if(this.draggable){let e=Qc(this.end);Jn(Ln(A,"mousedown"),kq(this.startDrag.bind(this)),Qx(()=>Jn(Ln(window,"mousemove"),Qc(Ln(window,"mouseup")))),e,Ks(this.doDrag.bind(this))),Jn(Ln(A,"dblclick"),e,Ks(this.resetPosition.bind(this))),Jn(Ln(A,"wheel"),e,Ks(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 e;return!((e=this.input)==null||!e.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 e=A.deltaY,o=this.context._canvas;o&&(this.baseWidth||(this.baseWidth=o.offsetWidth),this.baseWidth=e<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,e,o,n,a){var I;let{ctx2d:c}=this,u=this.context._canvas;if(!c||!u)return!1;let d=super.draw2d(A,e,o,n,a),R=c.getImageData(0,0,n,a),{data:k}=R,_=!1;if(this.initStat.alphaStitchingType===1){let Z=Math.floor(n/2);for(let iA=0;iA=100;k[TA+3]=XA?255:0}_=super.draw2d(R,0,0,0,0,Z,a),u.width=Z}else if(this.initStat.alphaStitchingType===2){let Z=Math.floor(a/2);for(let iA=0;iA=100;k[TA+3]=XA?255:0}_=super.draw2d(R,0,0,0,0,n,Z),u.height=Z}return(I=this.context.ctx)==null||I.clearRect(0,0,n,a),d&&_}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}},tG=class extends r4{constructor(A,e){super(A,e,arguments.length>2&&arguments[2]!==void 0?arguments[2]:4),G(this,"mediaType",4),G(this,"source"),G(this,"shouldRenderAlpha",!1),G(this,"alphaNode"),G(this,"shouldBeDraggable",!0),G(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0,keyFramesDecoded:0}),G(this,"_keyFrameCountLogged",!1),G(this,"_keyFrameStartTimestamp",0),G(this,"_keyFrameStartCount",0),G(this,"_keyFrameIntervals",[]),G(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 e=new Uint8Array(A.data);return e.length%3==0&&e[0]===0&&e[1]===1&&e}play(A,e){return e!=null&&e.canvasRender&&!this.source&&this.useCanvasPlayer(),super.play(A,e).then(()=>{this.player.calculateStat(),S.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(A){let e=this.isAlphaSei(A);if(e)if(this.alphaNode){let o=e[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===o)return;this.alphaNode.initStat={alphaStitchingType:o};let n=this.player.getElement();if(n){let a=n.videoWidth/n.videoHeight;a&&(this.alphaNode.baseRatio=a*(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(e[2])}generateAlphaCanvasName(A){let e=Oh[A];return"".concat("alpha","_").concat(e,"_").concat(this.userId)}useCanvasPlayer(A){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let e=new Mu({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&A?this.generateAlphaCanvasName(A):this.userId});e.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let o=new bq(e,{name:"remotePlayer",logger:this.log});if(this.source=e.createVideoPlayerSource(this.player),this.player.setCanvas(e._canvas),this.shouldRenderAlpha&&A){let n=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},a=new oeA(e,this.log,this.shouldBeDraggable,n,{alphaStitchingType:A});this.source.connect(a),a.connect(o),this.alphaNode=a}else this.source.connect(o);YQ()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(A){let e=this.decodeFPS,o=(n=e,[15,30,45,60].reduce((a,I)=>Math.abs(I-n)a.msg_user_info.str_identifier===this.userId))||{},o=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let n=e.find(a=>a.uint32_video_stream_type===o);return n?.uint32_video_dec_fps||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),S.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(A){if(!this.manager)return A;for(let e of this.manager.decodePipeline)if(e&&!(A=e({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 e=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>e){let a=A-e,I=(o-this._prevKeyFrameTimestamp)/1e3/a;this._keyFrameIntervals.push(I)}this._prevKeyFrameTimestamp=o;let n=o-this._keyFrameStartTimestamp;if(n>=16e3){let a=A-this._keyFrameStartCount,I=a>0?n/1e3/a:0,c="".concat(a," keyframes in 16s ").concat(I," [").concat(this._keyFrameIntervals.map(d=>d.toFixed(1)).join(","),"] keyFramesDecoded ").concat(A),u=I<=2.5?"debug":"info";this.log[u](c),this._keyFrameCountLogged=!0}}},n4=class extends tG{constructor(A,e){super(A,e,2),G(this,"mediaType",2),G(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},UM=new Map;function Ua(A,e){let o=fi(bt({},e),{timestamp:gh()});UM.has(A)?UM.get(A).push(o):UM.set(A,[o])}function a4(){for(var A=arguments.length,e=new Array(A),o=0;ofunction(){for(var I=arguments.length,c=new Array(I),u=0;umh(R)?Yf(R):Sr(R)?R:ya(R))},fnName:a,value:o},link:{className:I,fnName:a}})})}else if(!Ee(e.type)&&ya(o)!==e.type)throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_PARAMETER_TYPE,data:{key:n,rule:e,fnName:a,value:o},link:{className:I,fnName:a}})});if(e.allowEmpty===!1){let d=hr(o)&&(o===0||Number.isNaN(o)),R=Sr(o)&&o.trim()==="";if(d||R)throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_PARAMETER_EMPTY,data:{key:n,rule:e,fnName:a,value:o},link:{className:I,fnName:a}})})}if(e.notLessThanZero&&hr(o)&&o<0)throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.CANNOT_LESS_THAN_ZERO,data:{key:n,rule:e,fnName:a,value:o},link:{className:I,fnName:a}})});if(!Ee(e.min)&&hr(o)&&oe.max)throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_PARAMETER_MAX,data:{key:n,rule:e,fnName:a,value:o},link:{className:I,fnName:a}})});if(Sr(e.instanceOf)){if(!o||o._name!==e.instanceOf)throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_PARAMETER_INSTANCE,data:{key:n,rule:e,fnName:a,value:o},link:{className:I,fnName:a}})})}else if($n(e.instanceOf)&&!(o instanceof e.instanceOf))throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_PARAMETER_INSTANCE,data:{key:n,rule:e,fnName:a,value:o},link:{className:I,fnName:a}})});if(e.values&&!e.values.includes(o))throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_PARAMETER_RANGE,data:{key:n,rule:e,fnName:a,value:o},link:{className:I,fnName:a}})});let{properties:c}=e;Cc(c)&&Xc(o)&&Object.keys(c).forEach(d=>{yx.call(this,{rule:c[d],value:o&&o[d],key:"".concat(n,".").concat(d),fnName:a,className:I})});let{arrayItem:u}=e;Cc(u)&&Aa(o)&&o.forEach((d,R)=>{yx.call(this,{rule:u,value:d,key:"".concat(n,"[").concat(R,"]"),fnName:a,className:I})}),$n(e.validate)&&e.validate.call(this,o,n,a,I,this)}S.on(K.JOIN_SUCCESS,A=>{let{room:e}=A;Ua(e.userId,{eventId:32788})}),S.on(K.LEAVE_START,A=>{let{room:e}=A;Ua(e.userId,{eventId:32789})}),S.on(K.LOCAL_TRACK_PUBLISHED,A=>{let{track:e}=A;if(e.room){let o=32769;e.mediaType===4?o=32768:e.mediaType===2&&(o=32805),Ua(e.room.userId,{eventId:o})}}),S.on(K.LOCAL_TRACK_UNPUBLISHED,A=>{let{track:e}=A;if(e.room){let o=32771;e.mediaType===4?o=32770:e.mediaType===2&&(o=32806),Ua(e.room.userId,{eventId:o})}}),S.on(K.TRACK_MUTED,A=>{let{track:e}=A;e.room&&(e.kind===fA.AUDIO?Ua(e.room.userId,{eventId:e.isRemote?32785:32772,remoteUserId:e.isRemote?e.userId:void 0}):Ua(e.room.userId,{eventId:e.isRemote?32784:32773,remoteUserId:e.isRemote?e.userId:void 0}))}),S.on(K.TRACK_UNMUTED,A=>{let{track:e}=A;e.room&&(e.kind===fA.AUDIO?Ua(e.room.userId,{eventId:e.isRemote?32787:32774,remoteUserId:e.isRemote?e.userId:void 0}):Ua(e.room.userId,{eventId:e.isRemote?32786:32775,remoteUserId:e.isRemote?e.userId:void 0}))}),S.on(K.REMOTE_TRACK_SUBSCRIBED,A=>{let{track:e}=A;e.room&&(e.mediaType===1&&Ua(e.room.userId,{eventId:32777,remoteUserId:e.userId}),e.mediaType===4&&Ua(e.room.userId,{eventId:32776,remoteUserId:e.userId}),e.mediaType===8&&Ua(e.room.userId,{eventId:32803,remoteUserId:e.userId}))}),S.on(K.REMOTE_TRACK_UNSUBSCRIBED,A=>{let{track:e}=A;e.room&&(e.mediaType===1&&Ua(e.room.userId,{eventId:32779,remoteUserId:e.userId}),e.mediaType===4&&Ua(e.room.userId,{eventId:32778,remoteUserId:e.userId}),e.mediaType===8&&Ua(e.room.userId,{eventId:32804,remoteUserId:e.userId}))}),S.on(K.SWITCH_DEVICE_SUCCESS,A=>{let{track:e}=A;e.room&&Ua(e.room.userId,{eventId:e.kind===fA.VIDEO?32780:32781})}),S.on(K.LOCAL_TRACK_REPLACED,A=>{let{track:e}=A;e.room&&Ua(e.room.userId,{eventId:e.kind===fA.VIDEO?32782:32783})}),S.on(K.SIGNAL_CONNECTION_STATE_CHANGED,A=>{let e,{room:o,prevState:n,state:a}=A;switch(a){case"CONNECTED":e=n==="RECONNECTING"?32795:32791;break;case"DISCONNECTED":e=n==="RECONNECTING"?32796:32790;break;case"RECONNECTING":e=32794}e&&Ua(o.userId,{eventId:e})}),S.on(K.PEER_CONNECTION_STATE_CHANGED,A=>{let e,{room:o,prevState:n,state:a,remoteUserId:I}=A,c=!!I;switch(a){case"CONNECTED":e=n==="RECONNECTING"?c?32801:32798:c?32793:32792;break;case"DISCONNECTED":n==="RECONNECTING"&&(e=c?32802:32799);break;case"RECONNECTING":e=c?32800:32797}e&&Ua(o.userId,{eventId:e,remoteUserId:I})}),S.on(K.VIDEO_CODEC_IMPLEMENTATION_CHANGED,A=>{let{implementation:e,userId:o,remoteUserId:n,codec:a,isHWCodec:I,prevImplementation:c,streamType:u}=A,d=I?1:0;c||(d=I?3:2);let R={H264:0,H265:1,VP8:2}[a.toUpperCase()],k={eventId:4004,param1:d,param2:R,streamType:u||2};n&&(k.remoteUserId=n,k.eventId=4005),Ua(o,k),ct.addEnum({key:n?514701:513701,value:d}),ct.addEnum({key:n?514700:513700,value:R})}),S.on(K.LOCAL_TRACK_RECAPTURE,A=>{let{track:e,error:o}=A;if(e.userId){let n={eventId:2003,param1:0};e.kind===fA.AUDIO?(n.streamType=1,o&&(n.param1=2)):(n.streamType=e.streamType==="auxiliary"?7:2,o&&(n.param1=8)),Ua(e.userId,n)}});var neA=es(hg(),1),aeA=class extends neA.EventEmitter{constructor(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"userId";super(),this.mySelfId=A,this._log=e,this.key=o,G(this,"userMap",new Map),G(this,"remotePublishedUserMap",new Map),G(this,"asrRobotUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(A=>A.isRobot)}getPublishedUser(A){return this.remotePublishedUserMap.get(A)}addUser(A){let e=A[this.key],{userId:o,tinyId:n,role:a,fromType:I}=A;if(I===xR)return void this.addAsrRobotUser(A);if(this.userMap.has(e))return;let c={userId:o,tinyId:n,role:a===20?"anchor":"audience"};this.userMap.set(e,c),this.emit("1",c)}addAsrRobotUser(A){let e=A[this.key],{userId:o,tinyId:n,role:a}=A;if(this.asrRobotUserMap.has(e))return;let I={userId:o,tinyId:n,role:a===20?"anchor":"audience"};this.asrRobotUserMap.set(e,I),this.emit("8",I)}deleteUser(A,e){let o=this.userMap.get(A);if(!o)return;if(this.asrRobotUserMap.has(A))return void this.deleteAsrRobotUser(A);let n="peer leave [".concat(A,"]");Ee(e)||(n+=":".concat(cO[e])),this._log.info(n);let a=this.remotePublishedUserMap.get(A);if(a){let I=a.muteState;a.flag=0,this.emit("5",a.userId),this.deleteRemotePublishedUser(A),this.emit("6",{prevMuteState:I,muteState:a.muteState,flag:0})}this.userMap.delete(A),this.emit("2",{userId:o.userId,reason:e})}deleteAsrRobotUser(A){if(!this.asrRobotUserMap.has(A))return;let e=this.asrRobotUserMap.get(A);e&&(this.asrRobotUserMap.delete(A),this.emit("9",e))}setUserList(A){this.userMap.forEach(e=>{A.findIndex(o=>o[this.key]===e[this.key])<0&&this.deleteUser(e[this.key],0)}),A.forEach(e=>{!this.userMap.has(e[this.key])&&e[this.key]!==this.mySelfId&&this.addUser(e)})}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(e=>{let o=e[this.key];if(A.findIndex(n=>n[this.key]===e[this.key])<0){this._log.info("remote [".concat(o,"] unpublish"));let n=e.muteState;e.flag=0,this.emit("5",e.userId),this.deleteRemotePublishedUser(o),this.emit("6",{prevMuteState:n,muteState:e.muteState,flag:0})}}),A.forEach(e=>{var o;let n=e[this.key];if(n===this.mySelfId)return void this.emit("7",e);let{flag:a,userId:I,tinyId:c,fromType:u}=e,d=mQ(a,I),R=(o=this.remotePublishedUserMap.get(n))==null?void 0:o.muteState;if(R){let k=this.remotePublishedUserMap.get(n);k&&k.flag!==a&&(k.flag=a,this._log.info("remote publish updated: ".concat(JSON.stringify(k.muteState))),this.emit("6",{prevMuteState:R,muteState:d,flag:a}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(d))),this.addUser({userId:I,tinyId:c,role:20,fromType:u}),this.emit("3",e),this.emit("6",{prevMuteState:mQ(0,I),muteState:d,flag:a})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}},seA=es(hg(),1),geA=class extends seA.default{constructor(){super(...arguments),G(this,"_connectionTimeoutCount",0),G(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 s4(A){let{timesInSecond:e,maxSizeInSecond:o,getSize:n}=A;return Dn((a,I)=>{let c=new WeakMap;return S.on(K.ROOM_DESTROY,u=>{let{room:d}=u;return c.delete(d)}),function(){let u=c.get(this);for(var d=arguments.length,R=new Array(d),k=0;k1e3&&(u.timestamp=Date.now(),u.callCountInSecond=0,u.totalSizeInSecond=0),n&&(u.totalSizeInSecond+=n(...R)),u.timestamp!==0&&Date.now()-u.timestamp<1e3&&(u.callCountInSecond>=e||u.totalSizeInSecond>o))throw new Ct({code:Ge.INVALID_OPERATION,message:Wi({key:Mi.CALL_FREQUENCY_LIMIT,data:{isTimes:u.callCountInSecond>=e,isSize:u.totalSizeInSecond>o,name:I,timesInSecond:e,maxSizeInSecond:o}})});u.callCountInSecond++,a.call(this,...R)}})}var xe,g4=!0,iG={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"},Si={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},Rx=((xe=Rx||{})[xe.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",xe[xe.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",xe[xe.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",xe[xe.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",xe[xe.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",xe[xe.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",xe[xe.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",xe[xe.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",xe[xe.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",xe[xe.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",xe[xe.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",xe[xe.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",xe[xe.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",xe[xe.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",xe[xe.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",xe[xe.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",xe[xe.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",xe[xe.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",xe[xe.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",xe[xe.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",xe[xe.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",xe[xe.INVALID_OPERATION=5100]="INVALID_OPERATION",xe[xe.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",xe[xe.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",xe[xe.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",xe[xe.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",xe[xe.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",xe[xe.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",xe[xe.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",xe[xe.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",xe[xe.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",xe[xe.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",xe[xe.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",xe[xe.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",xe[xe.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",xe[xe.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",xe[xe.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",xe[xe.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",xe[xe.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",xe[xe.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",xe[xe.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",xe[xe.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",xe[xe.DEVICE_ERROR=5300]="DEVICE_ERROR",xe[xe.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",xe[xe.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",xe[xe.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",xe[xe.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",xe[xe.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",xe[xe.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",xe[xe.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",xe[xe.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",xe[xe.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",xe[xe.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",xe[xe.SERVER_ERROR=5400]="SERVER_ERROR",xe[xe.NEED_TO_BUY=5401]="NEED_TO_BUY",xe[xe.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",xe[xe.OPERATION_FAILED=5500]="OPERATION_FAILED",xe[xe.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",xe[xe.REJOIN_FAILED=5502]="REJOIN_FAILED",xe[xe.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",xe[xe.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",xe[xe.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",xe[xe.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",xe[xe.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",xe[xe.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",xe[xe.OPERATION_ABORT=5998]="OPERATION_ABORT",xe[xe.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",xe),I4=fi(bt({},ts),{INVALID_PARAMETER(A){let{fnName:e}=A;return"the parameters of the '".concat(e,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(A){let{key:e,rule:o,fnName:n,value:a}=A;return"'".concat(e||o.name,"' is a required param when calling ").concat(n,"(), received: ").concat(a,".")},INVALID_PARAMETER_TYPE(A){let{key:e,rule:o,fnName:n,value:a}=A,I="".concat(e||o.name),c="";return c=Array.isArray(o.type)?o.type.join("|"):o.type,"'".concat(I,"' must be type of ").concat(c," when calling ").concat(n,"(), received type: ").concat(ya(a),".")},INVALID_PARAMETER_EMPTY(A){let{key:e,rule:o,fnName:n,value:a}=A;return"'".concat(e||o.name,"' cannot be '").concat(a,"' when calling ").concat(n,"().")},INVALID_PARAMETER_INSTANCE(A){let{key:e,rule:o,fnName:n,value:a}=A,I="".concat(e||o.name),c="".concat(o.instanceOf.name||o.instanceOf);return"'".concat(I,"' must be instanceof ").concat(c," when calling ").concat(n,"(), received type: ").concat(ya(a),".")},INVALID_PARAMETER_RANGE(A){let{key:e,rule:o,fnName:n,value:a}=A;return"'".concat(e||o.name,"' must be one of ").concat(o.values.join("|")," when calling ").concat(n,"(), received: ").concat(a,".")},INVALID_PARAMETER_LESS_THAN_ZERO(A){let{key:e,rule:o,fnName:n}=A;return"'".concat(e||o.name,"' cannot be less than 0 when calling ").concat(n,"().")},INVALID_PARAMETER_MIN(A){let{key:e,rule:o,value:n}=A;return"the min value of ".concat(e||o.name," is ").concat(o.min,", received: ").concat(n,".")},INVALID_PARAMETER_MAX(A){let{key:e,rule:o,value:n}=A;return"the max value of ".concat(e||o.name," is ").concat(o.max,", received: ").concat(n,".")},INVALID_ELEMENT_ID(A){let{key:e,fnName:o}=A;return"'".concat(e,"' is not found in the document object when calling ").concat(o,"().")},INVALID_ELEMENT_ID_TYPE(A){let{key:e,fnName:o,type:n}=A;return"the element corresponding to '".concat(e,"' must be instanceof HTMLElement when calling ").concat(o,"(), received: ").concat(n,".")},INVALID_STREAM_ID(A){let{key:e}=A;return"'".concat(e,"' 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:e}=A;return"'".concat(e,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(A){let{key:e}=A;return"'".concat(e,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(A){let{key:e}=A;return"'".concat(e,"' 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:e}=A;return"The type of target roomId must match the current roomId. Current room is using '".concat(e,"', but received '").concat(e==="strRoomId"?"roomId":"strRoomId","'.")},INVALID_ROOM_ID_DUPLICATE(A){let{key:e}=A;return"the target '".concat(e,"' must not be the same as the current '").concat(e,"'.")},INVALID_STREAM_TYPE:A=>{let{fnName:e}=A;return"'streamType' is required when 'userId' is not '*', calling ".concat(e,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(A){let{fnName:e}=A;return"the API '".concat(e,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(A){let{fnName:e}=A;return"cannot ".concat(e," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(A){let{fnName:e,value:o}=A;return"cannot ".concat(e," because remote user(userId: ").concat(o.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(A){let{fnName:e,value:o}=A;return"cannot ".concat(e," because remote user(userId: ").concat(o.userId,") does not publishing ").concat(o.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(A){let{fnName:e}=A;return"you are already ".concat(e,"(), cannot repeated call '").concat(e,"'.")},INVALID_OPERATION_NEED_VIDEO(A){let{fnName:e}=A;return"cannot call '".concat(e,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(A){let{fnName:e}=A;return"cannot call '".concat(e,"' because the microphone or screen share is not turned on.")},INVALID_BUFFER_EMPTY:A=>{let{key:e}=A;return"the buffer size of paramerter '".concat(e,"' 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:e}=A;return"you need to call ".concat(e,"() after publish stream.")},ENV_NOT_SUPPORTED(A){let{fnName:e}=A;return"the current browser does not support the capability of the function '".concat(e,"' 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:e}=A;return"cannot call ".concat(e," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(A){let{fnName:e,error:o}=A;return"'".concat(e,"' got device exception").concat(o?", error: ".concat(o.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(A){let{fnName:e,deviceType:o=Gm(e),error:n}=A;return"NotFoundError, no ".concat(o," detected, please check your device and the configuration on '").concat(e,"'").concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(A){let{fnName:e,deviceType:o=Gm(e),error:n}=A;return"NotAllowedError, you have disabled ".concat(o," access, please allow the current application to use the ").concat(o).concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(A){let{fnName:e,deviceType:o=Gm(e),error:n}=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:e,deviceType:o=Gm(e),error:n}=A;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(A){let{fnName:e,deviceType:o=Gm(e),error:n}=A;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(o).concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_SECURITY_ERROR(A){let{fnName:e,deviceType:o=Gm(e),error:n}=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(n?", error: ".concat(n.toString(),"."):".")},DEVICE_ABORT_ERROR(A){let{fnName:e,deviceType:o=Gm(e),error:n}=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(n?" error: ".concat(n.toString(),"."):".")},CAMERA_RECOVER_FAILED(A){let{error:e}=A;return"camera recover capture failed ".concat(e?.name||"",": ").concat(e?.originMessage||e?.message)},MICROPHONE_RECOVER_FAILED(A){let{error:e}=A;return"microphone recover capture failed ".concat(e?.name||"",": ").concat(e?.originMessage||e?.message)},OPERATION_FAILED(A){let{fnName:e,error:o}=A;return"'".concat(e,"' 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:e}=A;return"an error was caught on trtc.on('".concat(e,"', handler), please check your code on 'handler'.")},VIDEO_CONTEXT_ERROR(A){let{reason:e,error:o}=A;return"video context error ".concat(e," ").concat(o?.name||""," ").concat(o?.message||"")},SERVER_ERROR(A){let{fnName:e,error:o}=A;return"'".concat(e,"' got server error: ").concat(o?.toString(),", please check the SDK documentation.")},NEED_TO_BUY(A){let{value:e,url:o}=A;return"You need to buy packages for ".concat(e,". Refer to: ").concat(o)},ACCOUNT_NO_MONEY:A=>{let{fnParams:e}=A;return"your TRTC account run out of credit, please recharge.".concat(e.sdkAppId?" SDKAppId: ".concat(e.sdkAppId):"")},OPERATION_ABORT(A){let{fnName:e}=A;return"'".concat(e,"' abort")},UNKNOWN_ERROR(A){let{fnName:e,error:o}=A;return"'".concat(e,"' throw unknown exception").concat(o?", error: ".concat(o.toString(),"."):".")}});function Gm(A){if(!A)return"camera";let e=A.toLowerCase();return e.includes("screen")?"screen share":e.includes("audio")?"microphone":"camera"}var IeA=class p2 extends Error{constructor(e){let{code:o,extraCode:n,message:a="",messageParams:I,fnName:c="",originError:u,data:d}=e;var R;let k;k=a||function(_){let Z,{code:iA,params:cA,enableDocLink:TA=!1}=_,JA="",Ie=Rx[iA];try{Z=I4[Ie]}catch{Z=I4.UNKNOWN_ERROR}return $n(Z)?JA=Z(cA):Sr(Z)&&(JA=Z),cA.fnName&&!JA.includes(cA.fnName)&&(JA[JA.length-1]!=="."&&(JA+="."),JA+=" thrown from ".concat(cA.fnName,"()")),TA&&(JA+=" doc:"),JA}({code:o===Si.SERVER_ERROR?o:n||o,params:bt({fnName:c,error:u},I)}),super(k),G(this,"name","RtcError"),G(this,"code"),G(this,"extraCode"),G(this,"functionName"),G(this,"message"),G(this,"data"),G(this,"handler"),G(this,"originError"),this.name=Rx[o],this.code=o,this.extraCode=n,this.functionName=c,this.originError=u,this.message=k,this.data=d,this.extraCode===5302&&(R=this.originError)!=null&&R.message.includes("system")&&(this.handler=()=>{let _=document.createElement("a");vh?_.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):lu&&(_.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),_.href.length>0&&_.click()})}static convertFrom(e,o,n){let a=e;if(e instanceof Ct){let{stack:I}=e,c={code:Si.UNKNOWN_ERROR,fnName:o,originError:e};switch(e.getCode()){case Ge.INVALID_PARAMETER:c.code=Si.INVALID_PARAMETER,c.message=e.message;break;case Ge.INVALID_OPERATION:c.code=Si.INVALID_OPERATION,c.message=e.message;break;case Ge.NOT_SUPPORTED:case Ge.NOT_SUPPORTED_H264:c.code=Si.ENV_NOT_SUPPORTED,e.getCode()===Ge.NOT_SUPPORTED_H264&&(c.extraCode=e.message.includes(ts.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case Ge.JOIN_ROOM_FAILED:c.messageParams={fnParams:n};case Ge.SERVER_TIMEOUT:case Ge.SWITCH_ROLE_FAILED:case Ge.SWITCH_ROOM_FAILED:c.code=Si.SERVER_ERROR,c.extraCode=e.getExtraCode();break;case Ge.API_CALL_ABORTED:c.code=Si.OPERATION_ABORT;break;case Ge.DEVICE_NOT_FOUND:case Ge.DEVICE_AUTO_RECOVER_FAILED:case Ge.INITIALIZE_FAILED:c.code=5300,e.name&&(c.extraCode=function(u){let d;switch(u){case"NotFoundError":d=5301;break;case"NotAllowedError":d=5302;break;case"NotReadableError":d=5303;break;case"OverconstrainedError":d=5304;break;case"InvalidStateError":d=5305;break;case"SecurityError":d=5306;break;case"AbortError":d=5307;break;default:d=5300}return d}(e.name));break;case Ge.VIDEO_ENCODE_FAILED:c.extraCode=5505;case Ge.AUDIO_ENCODE_FAILED:c.extraCode=5506,c.code=Si.OPERATION_FAILED;break;case Ge.UNKNOWN:break;default:c.code=Si.OPERATION_FAILED}a=new p2(c),I&&(a.stack+=I.substr(I.indexOf(` -`)))}else{if(e instanceof p2)return e;a=new p2({code:Si.UNKNOWN_ERROR,fnName:o,originError:e})}return a}},vi=IeA;function cl(A){return A==="sub"?"auxiliary":A==="auxiliary"?"sub":"main"}function Mx(A){return A===iG.QOS_PREFERENCE_CLEAR?"detail":A===iG.QOS_PREFERENCE_SMOOTH?"motion":""}function Sx(A,e){let o=e?AO:vf;return TO(A)?bt(bt({},o),A):$l[A]?$l[A]:o}var c4={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}}},E4={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}}},OM={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(A,e,o){if(Sr(A)&&!document.getElementById(A))throw new vi({code:Si.INVALID_PARAMETER,extraCode:5009,fnName:o,messageParams:{key:e}})}},l4={name:"userId",required:!0,type:"string"},C4={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 xM(A,e){if(!A)throw new vi({code:Si.INVALID_OPERATION,extraCode:5101,fnName:e})}function B4(A,e,o){if(!A)throw new vi({code:Si.INVALID_OPERATION,extraCode:5102,fnName:e,messageParams:{value:o}})}function u4(A,e,o){if(!(/^[1-9]\d*$/.test(String(A))&&A<4294967295))throw new vi({code:Si.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:o}})}function Q4(A,e,o){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(A))throw new vi({code:Si.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:o}})}function d4(A){var e;if((e=A?.option)==null||!e.small)return;if(!um())return nA.warn("small stream is not supported"),void delete A.option.small;let o=Sx(A.option.profile),n=Sx(A.option.small,!0);return((a,I)=>a.width*a.height>=I.width*I.height&&a.frameRate>=I.frameRate&&a.bitrate>=I.bitrate)(o,n)?void 0:(nA.warn("small stream profile must be less than big stream profile. Big: ".concat(JSON.stringify(o),", Small: ").concat(JSON.stringify(n))),void delete A.option.small)}var ceA={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,e,o){if(this._room.isJoined)throw new vi({code:Si.INVALID_OPERATION,extraCode:5104,fnName:o});if(A.roomId){if(Sr(A.roomId))throw new vi({code:Si.INVALID_PARAMETER,extraCode:5016,fnName:o,messageParams:{key:e}});u4(A.roomId,o,e)}else{if(!A.strRoomId)throw new vi({code:Si.INVALID_PARAMETER,extraCode:5015,fnName:o});Q4(A.strRoomId,o,e)}},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:OM,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:c4},validate(A){var e,o;if(((e=A?.option)==null||!e.videoTrack)&&wI())throw new vi({code:Si.ENV_NOT_SUPPORTED,extraCode:5201});(o=A?.option)!=null&&o.small&&d4(A)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:fi(bt({},OM),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:c4},validate(A){var e;(e=A?.option)!=null&&e.small&&d4(A)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:C4},validate(A){var e;if(((e=A?.option)==null||!e.audioTrack)&&wI())throw new vi({code:Si.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:C4}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:OM,publish:{type:"boolean"},option:E4},validate(A,e,o,n,a){var I;if((I=A?.option)==null||!I.videoTrack){if(wI())throw new vi({code:Si.ENV_NOT_SUPPORTED,extraCode:5201});if(!OQ())throw new vi({code:Si.ENV_NOT_SUPPORTED,fnName:o,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:OM,publish:{type:"boolean"},option:E4}},muteRemoteAudio:[l4,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[l4,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:OM,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,e,o){xM(this._room.isJoined,o);let n=this._room.remotePublishedUserMap.get(A.userId);if(B4(!!n,o,A),n&&(A.streamType==="main"&&!n.muteState.videoAvailable||A.streamType==="sub"&&!n.muteState.hasAuxiliary))throw new vi({code:Si.INVALID_OPERATION,extraCode:5103,fnName:o,messageParams:{value:A}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:fi(bt({},OM),{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,e,o){xM(this._room.isJoined,o);let n=this._room.remotePublishedUserMap.get(A.userId);if(B4(!!n,o,A),n){if(A.streamType==="main"&&!n.muteState.videoAvailable||A.streamType==="sub"&&!n.muteState.hasAuxiliary)throw new vi({code:Si.INVALID_OPERATION,extraCode:5103,fnName:o,messageParams:{value:A}});if(A.option){let a=A.streamType==="main"?n.remoteVideoTrack:n.remoteAuxiliaryTrack;if((A.option.pictureInPicture||A.option.fullScreen||A.option.fullScreen)&&(!a.isSubscribed||!a.player.isPlaying))throw new vi({code:Si.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,e,o){if(A.userId!=="*"&&Ee(A.streamType))throw new vi({code:Si.INVALID_PARAMETER,extraCode:5014,fnName:o})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(A,e,o){xM(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,e,o,n){if(!kT)throw new vi({code:Si.ENV_NOT_SUPPORTED,fnName:o,extraCode:5207});if(!this._room.enableSEI)throw new vi({code:Si.INVALID_OPERATION,fnName:o,extraCode:5108});if(A.byteLength>1e3)throw new vi({code:Si.INVALID_PARAMETER,extraCode:5018,fnName:o});if(A.byteLength===0)throw new vi({code:Si.INVALID_PARAMETER,extraCode:5017,messageParams:{key:e},fnName:o});xM(this._room.isJoined,o)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(A,e,o){if(!A&&!this._room.isMainStreamPublished||A&&!this._room.isAuxStreamPublished)throw new vi({code:Si.INVALID_OPERATION,extraCode:5109,messageParams:{key:e},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,e,o,n){if(A.byteLength>1e3)throw new vi({code:Si.INVALID_PARAMETER,extraCode:5018,fnName:o});if(A.byteLength===0)throw new vi({code:Si.INVALID_PARAMETER,extraCode:5017,fnName:o,messageParams:{key:e}})}}},validate(A,e,o){if(xM(this._room.isJoined,o),this._room.scene==="live"&&this._room.role==="audience")throw new vi({code:Si.INVALID_OPERATION,extraCode:5107,fnName:o,messageParams:{key:e}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(A,e,o){if(xM(this._room.isJoined,o),this._room.useStringRoomId&&A.strRoomId===this._room.roomId||!this._room.useStringRoomId&&A.roomId===Number(this._room.roomId))throw new vi({code:Si.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 vi({code:Si.INVALID_PARAMETER,extraCode:5019,fnName:o,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(A.roomId)u4(A.roomId,o,e);else{if(!A.strRoomId)throw new vi({code:Si.INVALID_PARAMETER,extraCode:5015,fnName:o});Q4(A.strRoomId,o,e)}},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},mg={TRTC:ceA},El=class extends Error{};function EeA(A,e){let o=Dh(A);for(let n=0;n!0),G(this,"mergeUpdate",EeA);let n=Aw.instances.get(e);n?n.set(o,this):Aw.instances.set(e,new Map([[o,this]]))}static get(e,o){if(!o)return;let n=Aw.instances.get(e);return n&&n.get(o)||new Aw(e,o)}static gets(e,o){let n=Aw.instances.get(e),a=[];return n&&n.forEach((I,c)=>{o.test(c)&&a.push(I)}),a}action(e,o,n){let a=u=>{var d;return e===0?this.started=!0:e===3&&(this.started=!1),this.ops.shift(),(d=this.currentOp)==null||d.action(),u},I=u=>{var d,R;throw this.ops.shift(),e===0&&((d=this.currentOp)==null?void 0:d.type)===2&&this.ops.shift().reject(new El("start failed")),(R=this.currentOp)==null||R.action(),u},c={type:e,action:()=>o(...c.args).then(a,I),args:n,resolve:leA,reject:CeA};try{switch(this.state){case 1:if(e===0)throw new El("already started");break;case 4:if(e===2)throw new El("not started");break;default:return this.cacheOp(c)}}catch(u){return Promise.reject(u)}return this.ops.push(c),c.promise=o(...c.args).then(a,I)}cacheOp(e){if(this.ops.length===1)switch(this.state){case 0:case 2:if(e.type===0)throw new El("already start");break;case 3:switch(e.type){case 2:throw new El("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new El("unknown state")}else switch(e.type){case 3:if(this.lastOpType===3)return this.lastOp.promise;{let n=new El("keep stop");if(this.ops.slice(1).forEach(a=>a.reject(n)),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,e.args),this.lastOp.promise;case 3:throw new El("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new El("start not allowed after update");case 0:throw new El("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new El("keep start")),new El("already start")}}e.promise=new Promise((n,a)=>{e._resolve?e._resolve.then(n):e.resolve=n,e._reject?e._reject.catch(a):e.reject=a});let{action:o}=e;return e.action=()=>o().then(e.resolve,e.reject),this.ops.push(e),e.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}};G(h4,"instances",new WeakMap);var oG=h4,vx=new WeakMap,Nx=(A,e)=>{if(e instanceof El){let{stack:o}=e;e=new vi({code:Si.OPERATION_ABORT,message:"".concat(A," abort: ").concat(e.message),fnName:A}),o&&(e.stack+=o.substr(o.indexOf(` -`)))}throw e};function km(A,e){return Dn((o,n)=>function(){for(var a=arguments.length,I=new Array(a),c=0;cfunction(){for(var c=arguments.length,u=new Array(c),d=0;d{var cA,TA;let JA=(cA=vx.get(this))==null?void 0:cA.get(_(...u));if(JA){let{timeoutId:XA,resolve:Ft}=JA;clearTimeout(XA),Ft()}let Ie=setTimeout(()=>{if(R.state===3||R.state===4)return Z();R.action(2,a.bind(this),u).catch(Nx.bind(null,I)).then(Z,iA)},k);vx.has(this)?(TA=vx.get(this))==null||TA.set(_(...u),{timeoutId:Ie,resolve:Z}):vx.set(this,new Map([[_(...u),{timeoutId:Ie,resolve:Z}]]))})}return R.action(2,a.bind(this),u).catch(Nx.bind(null,I))})}function _m(A){return Dn((e,o)=>function(){for(var n=arguments.length,a=new Array(n),I=0;Id.action(3,()=>Promise.resolve(),a))).then(()=>e.call(this,...a));let u=oG.get(this,c);return u?u.action(3,e.bind(this),a).catch(Nx.bind(null,o)):e.apply(this,a)})}function bm(){return function(A,e,o){return A.prototype[e]=function(){let n=this._log||console,a='"'.concat(e,'" is a static method. Use TRTC.').concat(e,"() instead. See: ").concat($C,"/en/TRTC.html#.").concat(e);n.warn(a)},o}}var Xt={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"},BeA=new Set([Xt.AUDIO_VOLUME,Xt.AUDIO_FRAME,Xt.NETWORK_QUALITY,Xt.STATISTICS,Xt.SEI_MESSAGE,Xt.CUSTOM_MESSAGE,Xt.LAYER_DATA]),p4={};XC(p4,{ScheduleRequestType:()=>D4,getAbilityConfig:()=>ueA,getScheduleDomain:()=>Jq,isNeedToSchedule:()=>rG,scheduleProxy:()=>jQ,sendScheduleRequest:()=>m4,setIsNeedToSchedule:()=>wu,setScheduleProxy:()=>Pq});var Tx=null,Gx=0,f4=72e5,kx="trtc_schedule_cache",rG=!0;function wu(A){rn(A)&&A!==rG&&(rG=A,nA.info("setIsNeedToSchedule ".concat(A)),A?function(){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.removeItem(kx)}catch(e){nA.error("clearScheduleCache error",e)}}():Gx=Date.now()+f4)}function m4(A){return DA(this,arguments,function(e){let{userId:o,sdkAppId:n,useStringRoomId:a,roomId:I,userSig:c,version:u,frameWorkType:d,role:R,latencyLevel:k}=e;return function*(){var _;if(!rG&&Tx&&Gx>Date.now())return{isCached:!0,result:Tx};let Z={delta:0,count:[1,1],msg:[],detail:[]};try{let iA=new FormData;iA.append("userId",String(o)),iA.append("sdkAppId",String(n)),iA.append("isStrGroupId",String(a)),iA.append("groupId",String(I)),iA.append("sdkVersion",u),iA.append("userSig",String(c));let cA=((_=yield nm())==null?void 0:_.model)||cT();cA&&iA.append("model",cA);let TA=bQ();TA&&iA.append("osString",TA);let JA=kQ();JA&&iA.append("gpu",JA),R&&iA.append("role",String(R)),k&&iA.append("latencyLevel",String(k)),d&&iA.append("frameWorkType",String(d));let Ie=ki(),XA=yield function(ie,ke,Nt){return new Promise((Ut,Ui)=>{let Oi=null;Pf([y4(or=>ke.count[0]=or+1,or=>{let{error:xi,retry:yo,retriedCount:Sa,retryFuncArgs:Vn}=or;ke.msg[0]=xi.message,Oi||(Sa>=1&&(Vn[0]=Xh(Nt,"config",fA.MAIN,!0)),yo())})(Xh(Nt,"config",fA.MAIN),ie,{get timeout(){return 1e3*ph(2+ke.count[0])}}),y4(or=>ke.count[1]=or+1,or=>{let{error:xi,retry:yo,retriedCount:Sa,retryFuncArgs:Vn}=or;ke.msg[1]=xi.message,Oi||(Sa>=2&&(Vn[0]=Xh(Nt,"config",fA.BACKUP,!0)),yo())})(Xh(Nt,"config",fA.BACKUP),ie,{get timeout(){return 1e3*ph(2+ke.count[1])}})]).then(or=>{Oi=or,Ut(Oi)}).catch(Ui)})}(iA,Z,n);XA.config&&(XA.config.loggerDomain&&wf(XA.config.loggerDomain),rn(XA.config.scheduleCache)&&wu(!XA.config.scheduleCache)),Z.delta=ki()-Ie;let Ft=function(ie,ke,Nt){let Ut={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let Ui=performance.getEntriesByType("resource"),Oi=Xh(ie,"config",fA.MAIN),or=Xh(ie,"config",fA.BACKUP);for(let xi of Ui)if(xi.startTime>=Nt&&(xi.name===Oi||xi.name===or)&&xi.transferSize>0){let yo=xi.name===Oi?fA.MAIN:fA.BACKUP,Sa=Math.round(xi.duration),Vn=Math.round(xi.domainLookupStart-xi.startTime),NI=xi.redirectStart>0?Math.round(xi.redirectEnd-xi.redirectStart):0,IG=xi.fetchStart>0?Math.round(xi.domainLookupStart-xi.fetchStart):0,qM=Math.round(xi.domainLookupEnd-xi.domainLookupStart),Dz=Math.round(xi.requestStart-xi.secureConnectionStart),yz=Math.round(xi.secureConnectionStart-xi.connectStart),Rz=Math.round(xi.responseStart-xi.requestStart),Mz=Math.round(xi.responseEnd-xi.responseStart),JtA=[qM,Dz,yz,Rz,Mz];Jo.uploadEvent({log:"stat-schedule-net:".concat(Sa,"(").concat(Vn,"(").concat(NI,"->").concat(IG,")->").concat(JtA.join("->"),") ").concat(yo),userId:ke}),Ut=fi(bt({},Ut),{totalCost:Sa,local:Vn,dns:qM,tcp:yz,tls:Dz,request:Rz,response:Mz});break}}catch(Ui){nA.error("getScheduleDetailCost error",Ui)}return Ut}(Number(n),o,Ie);return Tx=XA,function(ie){if(typeof window<"u"&&typeof localStorage<"u")try{let ke=Date.now()+f4;localStorage.setItem(kx,JSON.stringify({result:ie,expireIn:ke})),Gx=ke}catch(ke){nA.error("saveScheduleToLocalStorage error",ke)}}(XA),{isCached:!1,result:XA,detailCost:Ft}}catch(iA){let cA=Aa(iA)?iA[0]:iA,TA=hr(cA.code)?cA.code:0,JA="schedule failed".concat(cA.message?": ".concat(cA.message):""),Ie=new Ct({code:Ge.SCHEDULE_FAILED,extraCode:TA,message:Wi({key:Mi.JOIN_ROOM_FAILED,data:{error:JA,code:TA}})});throw nA.error(JA,TA),Ie}}()})}typeof document<"u"&&document.head.insertAdjacentHTML("beforeend",Object.values(su).map(A=>'')).join(`\r -`)),function(){if(typeof window<"u"&&typeof localStorage<"u")try{let A=localStorage.getItem(kx);if(A){let{result:e,expireIn:o}=JSON.parse(A);o>Date.now()?(Tx=e,Gx=o,rG=!1):localStorage.removeItem(kx)}}catch(A){nA.error("loadScheduleFromLocalStorage error",A)}}(),S.on("28",()=>wu(!0)),S.on("63",()=>wu(!0)),S.on("84",()=>wu(!0)),S.on("201",A=>{A.state==="RECONNECTING"&&wu(!0)}),S.on("202",A=>{A.state==="RECONNECTING"&&wu(!0)});var jQ={main:"",backup:""};function Pq(A){Aa(A)?(jQ.main=A[0],jQ.backup=A[1]):(jQ.main=A,jQ.backup=A)}var D4=(A=>(A.CONFIG="config",A.TRTC_AUTO_CONF="trtcAutoConf",A.AUDIO_AI_AUTH="audioAiAuth",A))(D4||{});function Xh(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:fA.MAIN,n=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return"https://".concat(jQ[o]||Jq(A,o,n),"/api/v1/").concat(e)}function ueA(A,e,o){let n=Xh(A,e),a=Xh(A,e,fA.BACKUP),I=new URLSearchParams(o).toString(),c=fetch("".concat(n,"?").concat(I)).then(d=>d.json()),u=fetch("".concat(a,"?").concat(I)).then(d=>d.json());return Pf([c,u])}function Jq(A){let e,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:fA.MAIN,n=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return e=ol(A)?n?o===fA.MAIN?su.MAIN_OVERSEA_BACKUP:su.BACKUP_OVERSEA:o===fA.MAIN?su.MAIN_OVERSEA:su.BACKUP_OVERSEA:o===fA.MAIN?su.MAIN:su.BACKUP,e}function QeA(A,e,o){return new Promise((n,a)=>{cu({url:A,body:e,timeout:o.timeout,priority:"high"}).then(I=>{I.data.code===0?n(I.data.data):a({code:I.data.code,message:I.data.msg})}).catch(a)})}var y4=(A,e)=>Kf({retryFunction:QeA,settings:{retries:3,timeout:0},onError:e,onRetrying:A}),Hq=class{constructor(){G(this,"_log"),this._log=nA.createLogger({id:"fd"})}download(A,e){return DA(this,null,function*(){let{type:o="blob"}=e||{};A=xN(A);try{let n,a=ki();if(n=$n(fetch)?yield this.downloadWithFetch(A,o):yield this.downloadWithXHR(A,o),!n||!n.data)throw new Error("data is empty");let I=ki()-a;return this._log.info("downloaded: ".concat(A,", return type: ").concat(o,", cost: ").concat(I,"ms")),ct.addSuccessEvent({key:522700,cost:ki()-a}),n.data}catch(n){throw this._log.error("failed to download: ".concat(A,", error: ").concat(n)),ct.addFailedEvent({key:522700,error:n}),n}})}downloadWithFetch(A,e){return DA(this,null,function*(){this._log.info("download with fetch: ".concat(A,", return type: ").concat(e));try{let o,n=yield fetch(A);if(!n.ok){let a=new Error("network response was not ok: ".concat(n.status));throw a.status=n.status,a}return o=e==="arraybuffer"?yield n.arrayBuffer():yield n.blob(),{data:o}}catch(o){throw o}})}downloadWithXHR(A,e){return this._log.info("download with xhr: ".concat(A,", return type: ").concat(e)),new Promise((o,n)=>{let a=new XMLHttpRequest;a.open("GET",A,!0),a.responseType=e,a.onload=()=>{if(a.status===200||a.status===0&&a.response)o({data:a.response});else{let I=new Error("XHR failed, status: ".concat(a.status));I.status=a.status,n(I)}},a.onerror=n,a.send(null)})}loadWasm(A,e){return DA(this,null,function*(){this._log.info("loadWasm ".concat(A,", importObject: ").concat(JSON.stringify(e)));let o=ki(),n=null,a=null;if($n(WebAssembly.instantiateStreaming)&&!A.startsWith("data:application/octet-stream;base64,")&&!(I=>I.startsWith("file://"))(A)&&$n(fetch))try{let I=fetch(A);n=(yield WebAssembly.instantiateStreaming(I,e)).instance}catch(I){a=I}if(!n)try{let I=yield this.download(A,{type:"arraybuffer"});n=(yield WebAssembly.instantiate(I,e)).instance}catch(I){a=I}if(n){let I=ki()-o;return this._log.info("loadedWasm ".concat(A,", cost: ").concat(I,"ms")),ct.addSuccessEvent({key:522701,cost:I}),n}throw this._log.error("failed to loadWasm ".concat(A,", error: ").concat(a)),ct.addFailedEvent({key:522701,error:a}),a})}loadScript(A){this._log.info("loadScript ".concat(A));let e=ki();return new Promise((o,n)=>{let a=document.createElement("script");a.type="text/javascript",a.onload=()=>{this._log.info("loadedScript ".concat(A,", cost: ").concat(ki()-e,"ms")),ct.addSuccessEvent({key:522702,cost:ki()-e,split:1e3}),o(a)},a.onerror=I=>{this._log.error("failed to loadScript ".concat(A,", error: ").concat(I?.message||JSON.stringify(I))),ct.addFailedEvent({key:522702}),n(I)},a.crossOrigin="anonymous",a.src=A,document.head.append?document.head.append(a):document.getElementsByTagName("head")[0].appendChild(a)})}};vt([nB({settings:{timeout:0,retries:3},onError(A,e,o){var n;A?.status===404||(n=A?.message)!=null&&n.includes("404")?(this._log.warn("download 404, stop retry"),o(A)):e()},onRetrying(A){this._log.warn("download retrying: ".concat(A))}})],Hq.prototype,"download"),vt([nB({settings:{timeout:3e3,retries:3},onRetrying(A){this._log.warn("loadScript retrying: ".concat(A))}})],Hq.prototype,"loadScript");var Vq=new Hq;function R4(A){let[e,o]=A,n=o.byteLength,a=parseInt(String(n/255),10),I=n%255,c=[];c.push(0,0,0,1,6,e);for(let d=0;dk+_.dataView.byteLength,0),c=new ArrayBuffer(I+e.data.byteLength),u=new DataView(c),d=new DataView(e.data),R=0;for(let k=0;ka.isSEI);o?.(n.reverse())}catch{}return e}function T4(A){let{seiMessageList:e,isAudio:o,getNtpTime:n,isMain:a}=A;return new TransformStream({transform(I,c){let u=I;o?audioEncodePipeline.forEach(d=>{u=d({frame:u,ntp:n(),onDump:()=>{self.postMessage({type:"dump",isAudio:o,data:u.data,userId:""})}})}):videoEncodePipeline.forEach(d=>{u=d({frame:u,seiMessageList:e,onDump:()=>{self.postMessage({type:"dump",isAudio:o,data:u.data,userId:"",streamType:a?"main":"auxiliary"})}})}),c.enqueue(u)}})}function G4(A){let{userId:e,streamType:o,isAudio:n}=A;return new TransformStream({transform(a,I){let c=a;n?(audioDecodePipeline.forEach(u=>{c=u({frame:c,onAudioFrameNTPTime:d=>{self.postMessage({type:"audio-ntp",data:d,userId:e,streamType:o})},onDump:()=>{self.postMessage({type:"dump",isAudio:n,data:c.data,userId:e})}})}),I.enqueue(c)):videoDecodePipeline.forEach(u=>{c=u({frame:c,onSEI:d=>{d.forEach(R=>{self.postMessage({type:"sei",seiPayloadType:R.seiPayloadType,data:R.seiPayload.buffer,userId:e,streamType:o})})},onDump:()=>{self.postMessage({type:"dump",isAudio:n,data:c.data,userId:e,streamType:o})}})}),I.enqueue(c)}})}function k4(A){let e=[fx],o=[S4,M4,$W,w4,R4,T4,G4,tM,qf,px],n="const videoEncodePipeline=[".concat(A.videoEncodePipeline.toString(),`]; +} `),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new Ct({code:Ge.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(A){let e="";return A&&(e=A.message,this.error=A,ct.addFailedEvent({key:512702,error:A})),this.disconnect(),this.log.info("video context destroy".concat(e)?": ".concat(e):""),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 e;(e=this.ctx)==null||e.viewport(0,0,A,this.height),super.width=A,this._canvas2d&&(this._canvas2d.width=A)}set height(A){var e;(e=this.ctx)==null||e.viewport(0,0,this.width,A),super.height=A,this._canvas2d&&(this._canvas2d.height=A)}setSize(A,e){var o;(o=this.ctx)==null||o.viewport(0,0,A,e),super.setSize(A,e),this._canvas2d&&(this._canvas2d.width=A,this._canvas2d.height=e)}createShader(A,e){let o=this.ctx,n=o.createShader(A);return o.shaderSource(n,e),o.compileShader(n),n}createProgram(A,e){let o=this.ctx,n=o.createProgram();return o.attachShader(n,A),o.attachShader(n,e),o.linkProgram(n),o.getProgramParameter(n,o.LINK_STATUS)||this.log.error(o.getProgramInfoLog(n)),n}};G(rG,"UNAVAILABLE","unavailable"),vt([is(Uo.INIT,"created",{sync:!0,fail(A){this.log.error("video gl context create failed",A.cause),ct.addFailedEvent({key:512700,error:A.cause||A})},success(){this.log.info("video context created use webgl"),ct.addSuccessEvent({key:512700})}})],rG.prototype,"create"),vt([is("created",Uo.INIT,{ignoreError:!0,sync:!0,success(A){A&&this.emit(rG.UNAVAILABLE,A),this.removeAllListeners()}})],rG.prototype,"destroy");var aC=rG,vu=class extends oG{constructor(){super(...arguments),G(this,"ctx")}create(A){if(this.hasAlpha=A.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(oG._ids++),this.ctx=this._canvas.getContext("2d",{alpha:A.alpha,willReadFrequently:A.willReadFrequently}),!this.ctx)throw new Ct({code:Ge.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 e="";A&&(e=A.message,this.error=A,ct.addFailedEvent({key:512703,error:A})),this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),ct.addSuccessEvent({key:512703})}};function EeA(A,e,o,n,a){arguments.length>5&&arguments[5]!==void 0&&arguments[5]&&([o,n]=[n,o]);let I={sWidth:A,sHeight:e,dWidth:o,dHeight:n,sx:0,sy:0,dx:0,dy:0};if(A===0||e===0)return I;switch(a){case void 0:case"fill":break;case"contain":{let c=Math.min(o/A,n/e);I.dWidth=A*c,I.dHeight=e*c,I.dx=(o-I.dWidth)/2,I.dy=(n-I.dHeight)/2;break}case"cover":{let c=Math.max(o/A,n/e),u=o/c,d=n/c;I.sx=(A-u)/2,I.sy=(e-d)/2,I.sWidth=u,I.sHeight=d;break}}return I}vt([is(Uo.INIT,"created",{sync:!0,fail(A){this.log.error("video 2d context create failed",A.cause),ct.addFailedEvent({key:512701,error:A.cause||A})},success(){this.log.info("video context created use 2d"),ct.addSuccessEvent({key:512701})}})],vu.prototype,"create"),vt([is("created",Uo.INIT,{ignoreError:!0,sync:!0})],vu.prototype,"destroy");var leA=class{constructor(A,e){this.node=A,this.layout=e,G(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}},c4=class extends cl{constructor(A,e){super(A,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:e}),G(this,"inputs",[]),G(this,"backgroundColor","black")}addInput(A,e){let o=0,n=this.inputs.length;for(;oe.zIndex))throw new Error("input already exists at zIndex ".concat(e.zIndex));n=I}}let a=new leA(A,e);this.inputs.splice(o,0,a)}changeInputLayout(A,e){let o=this.inputs.findIndex(Z=>Z.node===A);if(o<0)return;let{x:n,y:a,width:I,height:c,zIndex:u,fillMode:d,rotation:R,hidden:k}=e;if(!Ee(u)&&this.inputs.some(Z=>Z.layout.zIndex===u&&Z.node!==A))throw new Error("input already exists at zIndex ".concat(e.zIndex));let _=this.inputs[o];Ee(n)||(_.layout.x=n),Ee(a)||(_.layout.y=a),Ee(I)||(_.layout.width=I),Ee(c)||(_.layout.height=c),Ee(R)||(_.layout.rotation=R),Ee(k)||(_.layout.hidden=k),d&&(_.layout.fillMode=d),!Ee(u)&&u!==_.layout.zIndex&&(_.layout.zIndex=u,this.inputs.sort((Z,iA)=>Z.layout.zIndex-iA.layout.zIndex))}hasInput(A){return this.inputs.some(e=>e.node===A)}hasNoInput(){return this.inputs.length===0}resize(A,e){if(!this.matchInputSize)return void super.resize(A,e);let o=this.inputs.reduce((n,a)=>a?Object.assign(n,{width:Math.max(n.width,a.right),height:Math.max(n.height,a.bottom)}):n,{width:0,height:0});super.resize(o.width,o.height),this.context instanceof aC&&this.inputs.forEach(n=>{if(n){let a=this.layout2texCoords(n);n.positionBuffer?this.changeBufferData(n.positionBuffer,a):n.positionBuffer=this.createBuffer(a)}})}connect(A){for(var e=arguments.length,o=new Array(e>1?e-1:0),n=1;ne.node!==A),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(A){let e=this.context.ctx;if(e.clearColor(0,0,0,0),this.inputs.reduce((o,n)=>n.node.requestFrame(A)||o,!1)&&e){this.useProgram(),e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;oe.node.requestFrame(A)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let e=0;e4&&arguments[4]!==void 0&&arguments[4];this.ctx2d&&(a&&([o,n]=[n,o]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(A,e,o,n),this.ctx2d.restore())}getInfo(){let{totalFrames:A,x:e,y:o,width:n,height:a,name:I}=this,c=Date.now(),u=(A-this.lastInfo.totalFrames)/((c-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:A,x:e,y:o,width:n,height:a,timestamp:c,fps:u,name:I},bt({parent:this.inputs.filter(d=>d).map(d=>d.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(A=>{var e;if(A.node.disconnect(),A.positionBuffer&&this.context instanceof aC)try{(e=this.context.ctx)==null||e.deleteBuffer(A.positionBuffer)}catch{}})}close(){super.close(),this.removeAllInputs()}},CeA=[1,0,0,0,1,1,0,1],Ap=class extends cl{constructor(A,e,o,n){if(super(A,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:e}),G(this,"mirror",!1),G(this,"rotation",0),o&&(this.mirror=o),n&&(this.rotation=n),A instanceof aC)try{this.setTexBuffer(CeA)}catch(a){A.destroy(new Ct({code:Ge.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(a.message||a)}))}}draw2d(A,e,o,n,a){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(n,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(a/n,n/a)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,a),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(a/n,n/a));let I=super.draw2d(A,e,o,n,a);return this.ctx2d.restore(),I}return!1}render(A){var e;return!((e=this.input)==null||!e.requestFrame(A))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}resize(A,e){Eu(this.rotation)&&([A,e]=[e,A]),super.resize(A,e)}},Jq=class extends eG{constructor(A){super(arguments.length>1&&arguments[1]!==void 0?arguments[1]:4,wi),G(this,"inputLocalVideoTracks",new Map),G(this,"inputLocalScreenTracks",new Map),G(this,"cameraNodeMap",new Map),G(this,"screenNodeMap",new Map),G(this,"textNodeMap",new Map),G(this,"imageNodeMap",new Map),G(this,"videoNodeMap",new Map),G(this,"endedIds",new Set),G(this,"videoContext"),G(this,"mixNode"),G(this,"destination"),G(this,"manager"),G(this,"stat"),G(this,"_checkId",0),G(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(cl.RENDER,e=>{this.emit("render",e)}),this.mixNode=new c4(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=nn.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:A})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new vu({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(A){this.autoSetFps=!1,this.videoContext.frameRate=A;for(let e of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])e.shouldUpdate=!1;setTimeout(()=>{var e;return(e=this.destination)==null?void 0:e.start(this.videoContext.frameRate)},500)}setFpsAuto(){var A;if(!this.autoSetFps)return;for(let a of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])a.shouldUpdate=!1;let e=null,o=0,n=!0;for(let[a,I]of this.inputLocalVideoTracks)if(I.profile.frameRate>o){if(this.endedIds.has(a)){let c=this.cameraNodeMap.get(a);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}o=I.profile.frameRate,e=a}for(let[a,I]of this.inputLocalScreenTracks)if(I.profile.frameRate>o){if(this.endedIds.has(a)){let c=this.screenNodeMap.get(a);c&&c.image.cancelVideoFrameCallback(c.videoCallbackId);continue}o=I.profile.frameRate,e=a,n=!1}if(e!==null){let a=n?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);a&&(a.shouldUpdate=!0,a.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,e){var o;(o=this.mixNode)==null||o.resize(A,e)}startMix(){return DA(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),_Q&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(A=this.manager)==null||A.changeInput(this)})}addCameraSource(A,e,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 n,{mediaTrack:a}=e;if(!a)throw new Error("no mediaTrack, add cameraSource failed");e.recaptureMode=1,nE(this,vs).add("videoInputRemoved",I=>{I.deviceId===e.deviceId&&(this.endedIds.add(A),this.setFpsAuto())}),e.on("output-media-track-changed",()=>{this.endedIds.delete(A),this.updateCameraSource(A,o,e.mediaTrack)}),n=sl===16&&a instanceof CanvasCaptureMediaStreamTrack?this.videoContext.createVideoImageSource(a.canvas,{name:"cameraCanvasSource",logger:this.log}):this.videoContext.createVideoTrackSource(a,"cameraNodeSource"),n.resize(e.settings.width,e.settings.height),n.shouldUpdate=!1,this._connectMix(n,o,"cover"),this.inputLocalVideoTracks.set(A,e),this.cameraNodeMap.set(A,n),this.setFpsAuto()}addScreenSource(A,e,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:n}=e;if(!n)throw new Error("no mediaTrack, add screenSource failed");e.on("output-media-track-changed",()=>{this.updateScreenSource(A,o,e.mediaTrack)});let a=this.videoContext.createVideoTrackSource(n,"screenNodeSource");a.resize(e.settings.width,e.settings.height),a.shouldUpdate=!1,this._connectMix(a,o),this.inputLocalScreenTracks.set(A,e),this.screenNodeMap.set(A,a),this.setFpsAuto()}addTextSource(A){let{id:e,content:o="",font:n,color:a,layout:I}=A;if(this.textNodeMap.has(e))throw new Error("There is already a textSource with the same ID: ".concat(e));let c=this.videoContext.createTextSource({content:o,font:n,color:a});c.resize(I.width,I.height),this._connectMix(c,I),this.textNodeMap.set(e,c)}addImageSource(A,e,o){if(this.imageNodeMap.has(A))throw new Error("There is already a imageSource with the same ID: ".concat(A));let n=this.videoContext.createVideoImageSource(e,{autoResize:!1,logger:this.log});n.resize(e.width,e.height),this._connectMix(n,o),this.imageNodeMap.set(A,n)}addVideoSource(A,e,o){if(this.videoNodeMap.has(A))throw new Error("There is already a videoSource with the same ID: ".concat(A));let n=this.videoContext.createVideoImageSource(e,{autoResize:!1,logger:this.log});n.resize(e.videoWidth,e.videoHeight),n.shouldUpdate=!1,this._connectMix(n,o),this.videoNodeMap.set(A,n)}updateCameraSource(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,n=arguments.length>3?arguments[3]:void 0,a=this.inputLocalVideoTracks.get(A);a&&o&&o!==a.mediaTrack&&(this.log.debug("updateCameraSource mixerLocalVideoTrack newTrack:",o,"oldTrack:",a.mediaTrack),a.setInputMediaStreamTrack(o));let I=this.cameraNodeMap.get(A);if(I){if(o){if(sl===16&&o instanceof CanvasCaptureMediaStreamTrack)if(I instanceof xM){let d=I.output;I.close(),I=this.videoContext.createVideoImageSource(o.canvas,{name:"cameraCanvasSource",logger:this.log}),I.connect(d),this.cameraNodeMap.set(A,I)}else I.image=o.canvas;else if(I instanceof xM)I.replaceTrack(o);else{let d=I.output;I.close(),I=this.videoContext.createVideoTrackSource(o,"cameraNodeSource"),I.connect(d),this.cameraNodeMap.set(A,I)}let{width:c,height:u}=o.getSettings();c&&u&&I.resize(c,u)}n&&I.resize(n.width,n.height),(n||o)&&this.setFpsAuto(),this._changeMixLayout(I,e)}}updateScreenSource(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,n=this.inputLocalScreenTracks.get(A);this.log.debug("updateScreenSource mixerLocalScreenTrack",n,o),n&&o&&o!==n.mediaTrack&&n.setInputMediaStreamTrack(o);let a=this.screenNodeMap.get(A);a&&(o&&a.replaceTrack(o),this._changeMixLayout(a,e))}updateTextSource(A){let{id:e,content:o,font:n,color:a,layout:I}=A,c=this.textNodeMap.get(e);c&&(Ee(o)||(c.content=o),Ee(n)||(c.font=n),Ee(a)||(c.color=a),c.resize(I.width,I.height),this._changeMixLayout(c,I))}updateImageSource(A,e,o){let n=this.imageNodeMap.get(A);n&&(o&&(n.image=o,n.resize(o.width,o.height)),this._changeMixLayout(n,e))}updateVideoSource(A,e,o){let n=this.videoNodeMap.get(A);if(n){if(o){let a=n.image;a instanceof HTMLVideoElement&&this.stopVideoElement(a),n.image=o,n.resize(o.videoWidth,o.videoHeight)}this._changeMixLayout(n,e)}}_connectMix(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"contain";if(!this.mixNode)return;let{mirror:n,rotation:a}=e;A.disconnect();let I=new Ap(this.videoContext,this.log,n,a);I=A.connect(I),e.fillMode||(e.fillMode=o),I.connect(this.mixNode,e)}_changeMixLayout(A,e){if(!this.mixNode)return;let{mirror:o,rotation:n}=e,a=A.output||A;a instanceof Ap&&(Ee(o)||(a.mirror=o),Ee(n)||(a.rotation=n),a.resize(A.width,A.height)),this.mixNode.changeInputLayout(a,e)}removeCameraSource(A){let e=this.inputLocalVideoTracks.get(A);if(!e)return;e.close(),this.inputLocalVideoTracks.delete(A);let o=this.cameraNodeMap.get(A);o&&(o.output instanceof Ap&&o.output.close(),o.close(),this.cameraNodeMap.delete(A)),this.checkAfterRemove(!0)}removeScreenSource(A){let e=this.inputLocalScreenTracks.get(A);if(!e)return;e.close(),this.inputLocalScreenTracks.delete(A);let o=this.screenNodeMap.get(A);o&&(o.output instanceof Ap&&o.output.close(),o.close(),this.screenNodeMap.delete(A)),this.checkAfterRemove(!0)}removeTextSource(A){let e=this.textNodeMap.get(A);e&&(e.output instanceof Ap&&e.output.close(),e.close(),this.textNodeMap.delete(A)),this.checkAfterRemove()}removeImageSource(A){let e=this.imageNodeMap.get(A);e&&(e.output instanceof Ap&&e.output.close(),e.close(),this.imageNodeMap.delete(A)),this.checkAfterRemove()}removeVideoSource(A){let e=this.videoNodeMap.get(A);e&&(e.output instanceof Ap&&e.output.close(),e.image instanceof HTMLVideoElement&&this.stopVideoElement(e.image),e.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(),nn.clearTask(this._checkId),(A=this.videoContext)==null||A.destroy(),delete this.mixNode,delete this.destination;for(let e of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])e.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),pr(this);for(let e of this.videoNodeMap.values())e.image instanceof HTMLVideoElement&&this.stopVideoElement(e.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}},Hq=hA();if(typeof navigator<"u"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:Hq,exposeOrigin:!0,permittedOrigins:["*"]})}catch{}var BeA=function(A){return DA(this,null,function*(){let e=null,o=function(I){let c={preferCurrentTab:I.preferDisplaySurface==="current-tab"||!!I.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},u={width:Ma?{max:I.width}:{ideal:I.width,max:I.width},height:Ma?{max:I.height}:{ideal:I.height,max:I.height},frameRate:I.frameRate,displaySurface:I.preferDisplaySurface||"monitor"};if(c.video=u,I.systemAudio){let{echoCancellation:d=!0,noiseSuppression:R=!1,autoGainControl:k=!1}=I;c.audio={echoCancellation:d,noiseSuppression:R,autoGainControl:k,sampleRate:48e3}}return c}(A);nA.info("getDisplayMedia with constraints: ".concat(JSON.stringify(o)));let n=yield navigator.mediaDevices.getDisplayMedia(o);A.systemAudio&&n.getAudioTracks().length===0&&(dM&&tE<74||Ma||Yr)&&nA.warn("Your browser not support capture system audio");let a=n.getVideoTracks()[0];if(a){if(A.frameRate)try{yield a.applyConstraints({frameRate:{min:A.frameRate,ideal:A.frameRate},width:A.width,height:A.height})}catch(I){nA.warn("screen applyConstraints failed: ".concat(I))}A.captureElement&&(yield function(I,c){return DA(this,null,function*(){var u;if("CropTarget"in window&&"fromElement"in CropTarget&&$n(I.cropTo))try{if(((u=I.getCaptureHandle())==null?void 0:u.handle)!==Hq)return;let d=yield CropTarget.fromElement(c);yield I.cropTo(d)}catch(d){nA.warn("cropTo target failed ".concat(d))}})}(a,A.captureElement))}if(A.audio){let I=function(c){let u={echoCancellation:c.echoCancellation,autoGainControl:c.autoGainControl,noiseSuppression:c.noiseSuppression,sampleRate:c.sampleRate,channelCount:c.channelCount};return Ee(c.microphoneId)||(u.deviceId=c.microphoneId),{audio:u,video:!1}}(A);nA.info("getUserMedia with constraints: ".concat(JSON.stringify(I))),e=yield navigator.mediaDevices.getUserMedia(I),n.addTrack(e.getAudioTracks()[0])}return n})},_m=class extends Su{constructor(A){super(A,2),G(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),G(this,"objectFit","contain"),G(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}get isShareCurrentTab(){var A,e;try{return Hq===((e=(A=this.mediaTrack)==null?void 0:A.getCaptureHandle())==null?void 0:e.handle)}catch{return}}capture(A){return DA(this,arguments,function(e){var o=this;let{systemAudio:n=!1,autoGainControl:a,echoCancellation:I,noiseSuppression:c,audioTrack:u,videoTrack:d,captureElement:R,preferDisplaySurface:k}=e;return function*(){var _;try{let Z,iA=ki();return d||u?(Z=new MediaStream,d&&Z.addTrack(d),u&&Z.addTrack(u)):(Z=yield BeA({audio:!1,systemAudio:n,width:o.profile.width,height:o.profile.height,frameRate:o.profile.frameRate,autoGainControl:a,echoCancellation:I,noiseSuppression:c,captureElement:R,preferDisplaySurface:k}),o.sourceTrack=Z.getVideoTracks()[0]),yield o.setInputMediaStreamTrack(Z.getVideoTracks()[0]),S.emit(K.LOCAL_TRACK_CAPTURE_SUCCESS,{track:o,cost:ki()-iA,profile:o.profile,room:(_=o.manager)==null?void 0:_.room}),Z}catch(Z){throw o.log.error("getDisplayMedia error observed ".concat(Z)),Z instanceof Ct?Z:new Ct({code:Ge.INITIALIZE_FAILED,name:Z.name,message:Z.message})}}()})}switchDevice(A){return DA(this,null,function*(){throw new Error("Method not implemented.")})}};vt([Tm(function(A){this.setContentHint(A.contentHint||"detail")})],_m.prototype,"capture");var Vq,Kq=class extends km{constructor(A){super(A),this._log.id="s-".concat(this._log.id),this.isScreen=!0}addAudioProcessor(A,e,o){this.pipeline.silentNode.setNode(o),this.pipeline.mixNode.setNode(e),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 jq(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,n=arguments.length>3?arguments[3]:void 0;return DA(this,null,function*(){let a=tI();Vq||(Vq=Fa(a,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;tu.connect(c,0,d)),new ReadableStream({start(u){c.port.onmessage=d=>{u.enqueue(d.data)}},cancel(){A.forEach(u=>u.disconnect(c)),c.port.close()}})})}var ueA=class extends T${constructor(A){super(),this.room=A,G(this,"_localAudioTrack"),G(this,"_localScreenAudioTrack"),G(this,"log"),G(this,"denoiser"),G(this,"voiceChanger"),G(this,"mixChangedDebounce"),G(this,"audioProcessor"),G(this,"encodePipeline",[]),G(this,"decodePipeline",[]),G(this,"getPCMAbortCtrlMap",new Map),G(this,"audioFrameEventConfigMap",new Map),G(this,"audioReferenceMap",new Map),G(this,"isLocalAudioNeedAudioProcess",!1),G(this,"isScreenAudioNeedAudioProcess",!1),this.log=nA.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 e,o;if(!this._localAudioTrack)return;let n=[],a=[];(e=this._localAudioPipline)!=null&&e.source.node&&(n.push(this._localAudioPipline.source.node),a.push("mic")),(o=this._localAudioPipline)!=null&&o.denoiser.node&&(n.push(this._localAudioPipline.denoiser.node),a.push("mic-processed")),this.mixWeight>1&&(n.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),a.push("mix")),this.log.info("dump audio track ".concat(a,", duration: ").concat(A));let I=new AbortController,c=[],u=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),I.abort("timeout")},1e3*A),d=()=>{for(let k=0;kk.pipeTo(new WritableStream({write(_){_.forEach((Z,iA)=>c[iA]=c[iA]?c[iA].concat(Z[0]):[Z[0]])}}),I).catch(_=>d));return{then:R.then.bind(R),download:d}}getPCM(A,e){var o,n,a;if(typeof WritableStream>"u")return void this.log.warn("getPCM failed: browser not support WritableStream");let{enable:I,sampleRate:c=48e3,channelCount:u=1,port:d}=(e===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(e)||this.audioFrameEventConfigMap.get("*"))||{};if(!I)return;this.log.info("getPCM ".concat(e||"local"));let R,k,_=Math.floor(.04*c),Z=new Float32Array(_),iA=new Float32Array(_),cA=0,TA=new AbortController,JA=e===""?(o=this._localAudioTrack)==null?void 0:o.mediaTrack:(a=(n=this.room)==null?void 0:n.remotePublishedUserMap.get(e))==null?void 0:a.remoteAudioTrack.mediaTrack;if(JA)return jq([tI().createMediaStreamSource(new MediaStream([JA]))],c,u,d).then(Ie=>Ie.pipeTo(new WritableStream({write(XA){XA[0][0]&&(cA+XA[0][0].length>_?(Z.set(XA[0][0].subarray(0,_-cA),cA),R=XA[0][0].subarray(_-cA),XA[0][1]&&(iA.set(XA[0][1].subarray(0,_-cA),cA),k=XA[0][1].subarray(_-cA)),cA+=_-cA):(R&&(Z.set(R,cA),cA+=R.length,R=void 0),k&&(iA.set(k,cA),k=void 0),Z.set(XA[0][0],cA),XA[0][1]&&iA.set(XA[0][1],cA),cA+=XA[0][0].length),cA>=_&&(cA=0,A({userId:e,sampleRate:c,channelCount:u,data:u===1?Z:[Z,iA]}),Z=new Float32Array(_),iA=new Float32Array(_)))}}),TA).catch(XA=>this.log.warn("stop getPCM reason:".concat(XA)))),TA;this.log.info("getPCM failed: ".concat(e||"local"," has no audio track"))}get hasScreenAudioTrack(){return!Ee(this._localScreenAudioTrack)}get hasAudioTrack(){return!Ee(this._localAudioTrack)}changeInput(A){var e,o;return A instanceof Kq?(this._localScreenAudioTrack=A,this.isScreenAudioNeedAudioProcess&&(e=this.audioProcessor)!=null&&e.screenAudioWorkletNode&&(A.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((n,a)=>{A.mixAudioReference(n,a)})),A.pipeline.connect(),this.mixOnChange()):A instanceof km?(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((n,a)=>{A.mixAudioReference(n,a)})),A.pipeline.connect(),this.mixOnChange()):A instanceof Tx?A.setOutputMediaStreamTrack(A.mediaTrack):void 0}mixAudioReference(A,e){var o;(o=this._localAudioTrack)==null||o.mixAudioReference(A,e)}unMixAudioReference(A){var e;(e=this._localAudioTrack)==null||e.unMixAudioReference(A)}setAudioReferenceVolume(A,e){var o;(o=this._localAudioTrack)==null||o.setAudioReferenceVolume(A,e)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var A,e;return delete this.mixChangedDebounce,Promise.all([(A=this._localAudioTrack)==null?void 0:A.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(e=this._localScreenAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(A){A instanceof Kq?delete this._localScreenAudioTrack:A instanceof km&&delete this._localAudioTrack}addDenoiser(A){var e;this.denoiser=A,(e=this._localAudioTrack)==null||e.addDenoiser(A)}addAudioProcessor(A,e,o,n){var a;this.audioProcessor={localAudioWorkletNode:o,mixNode:A,silentNode:e,screenAudioWorkletNode:n},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&o&&(this._localAudioTrack.addAudioProcessor(o,A,e),this.audioReferenceMap.forEach((I,c)=>{var u;(u=this._localAudioTrack)==null||u.mixAudioReference(I,c)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&n&&((a=this._localScreenAudioTrack)==null||a.addAudioProcessor(n,A,e),this.audioReferenceMap.forEach((I,c)=>{var u;(u=this._localScreenAudioTrack)==null||u.mixAudioReference(I,c)}))}removeDenoiser(A){var e;return delete this.denoiser,(e=this._localAudioTrack)==null?void 0:e.removeDenoiser(A)}addVoiceChanger(A,e){var o;this.voiceChanger=[A,e],(o=this._localAudioTrack)==null||o.pipeline.voiceChanger.setNode(A,e)}removeVoiceChanger(){var A;delete this.voiceChanger,(A=this._localAudioTrack)==null||A.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(A,e){var o,n;delete this.audioProcessor,(o=this._localAudioTrack)==null||o.removeAudioProcessor(A),(n=this._localScreenAudioTrack)==null||n.removeAudioProcessor(e)}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:e,type:o}=A;var n;this.encodePipeline.includes(e)||(this.encodePipeline[o]=e,(n=this.room)==null||n.enableInsertableStreams())}addDecodeProcessor(A){let{processor:e,type:o}=A;var n;this.decodePipeline.includes(e)||(this.decodePipeline[o]=e,(n=this.room)==null||n.enableInsertableStreams())}removeEncodeProcessor(A){let{type:e}=A;this.encodePipeline[e]=void 0}removeDecodeProcessor(A){let{type:e}=A;this.decodePipeline[e]=void 0}handleLocalTrackStarted(A){let{room:e,userId:o}=A;var n;if(e!==this.room||this.getPCMAbortCtrlMap.get(o))return;let a=this.getPCM(I=>{var c;(c=this.room)==null||c.emit("audio-frame",I)},"");this.getPCMAbortCtrlMap.set(o,a),this.getPCMAbortCtrlMap.get(o)&&((n=this._localAudioTrack)==null||n.on("input-media-track-changed",()=>{let I=this.getPCMAbortCtrlMap.get(o);I&&(I.abort("inputMediaTrackChanged"),I=this.getPCM(c=>{var u;(u=this.room)==null||u.emit("audio-frame",c)},""),this.getPCMAbortCtrlMap.set(o,I))}))}handleLocalTrackStopped(A){let{room:e,userId:o}=A;if(e!==this.room)return;let n=this.getPCMAbortCtrlMap.get(o);n&&(n.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(o))}handleRemoteTrackStarted(A){let{room:e,userId:o}=A;if(e===this.room&&!this.getPCMAbortCtrlMap.get(o)){let n=this.room.audioManager.getPCM(a=>{var I;(I=this.room)==null||I.emit("audio-frame",a)},o);this.getPCMAbortCtrlMap.set(o,n)}}handleRemoteTrackStopped(A){let{room:e,userId:o}=A;if(e!==this.room)return;let n=this.getPCMAbortCtrlMap.get(o);n&&(n.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(o))}installEvent(){S.on("113",this.handleLocalTrackStarted,this),S.on("114",this.handleLocalTrackStopped,this),S.on("115",this.handleRemoteTrackStarted,this),S.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){S.off("113",this.handleLocalTrackStarted),S.off("114",this.handleLocalTrackStopped),S.off("115",this.handleRemoteTrackStarted),S.off("116",this.handleRemoteTrackStopped)}updateAudioReference(A){let{type:e,audioReference:o,refId:n,volume:a}=A;if(e==="add"){if(this.audioReferenceMap.get(n)||!o||(this.audioReferenceMap.set(n,o),!this.audioProcessor))return;this.mixAudioReference(o,n)}else if(e==="remove")this.audioReferenceMap.get(n)&&(this.audioReferenceMap.delete(n),this.unMixAudioReference(n));else if(e==="updateVolume"){if(!this.audioProcessor||Ee(a))return;this.setAudioReferenceVolume(n,a)}}};function Nx(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return Dn((o,n)=>function(){for(var a=arguments.length,I=new Array(a),c=0;c{let R=setTimeout(()=>{let k=new Ct({code:Ge.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(n,"() timeout ").concat(A,"s")});(this.log||this._log||nA).warn(k),e===2?d(k):e===1&&u()},1e3*A);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(R),o.apply(this,I).then(u,d).finally(()=>{clearTimeout(R),this._checkPendingPromiseSet&&R&&this._checkPendingPromiseSet.delete(R)})})})}var bm=class vj extends Nq{constructor(e,o,n){super({userId:o.userId,sdkAppId:e.sdkAppId,mediaType:n,room:e}),this.room=e,this.user=o,G(this,"tinyId"),G(this,"isRemote",!0),G(this,"jitterBufferDelay",0),G(this,"availableState"),G(this,"remotePublishState"),G(this,"_triggerCheckDecodeSubject",wu(Ln(this,vj.STATE_SUBSCRIBE))),G(this,"ignoreUpdatePlayingState"),this.tinyId=o.tinyId,this.availableState=new Uo("".concat(o.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new Uo("".concat(o.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),Jn(Gq(Ln(this,Uo.STATECHANGED),Ln(this.remotePublishState,Uo.STATECHANGED)),Uq(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Ks(u=>{this.availableState.state!==(u?Uo.ON:Uo.OFF)&&(this.availableState.state=u?Uo.ON:Uo.OFF),(!this.isRemotePublished||!this.ignoreUpdatePlayingState)&&this.updatePlayingState(u)}));let a=Jn(Ln(this.player,mi.ERROR),Gm(u=>u.code===MediaError.MEDIA_ERR_DECODE)),I=Jn(bq(5e3),Gm(()=>!!(!this.ignoreDecodeError&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived&&this.isRemotePublished)&&(!this.player.isPlaying&&!(this.kind===fA.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1)))),c=Jn(PW(a,I),Qc(Ln(this,Uo.INIT)));Jn(this._triggerCheckDecodeSubject,Gm(()=>!this.ignoreDecodeError),Mx(c),Ks(u=>{this.reportDecodeResult(!1,u)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var e,o,n,a;return(a=(n=(o=(e=this.room)==null?void 0:e.networkQuality)==null?void 0:o.hadRecentBadDownlink)==null?void 0:n.call(o,2))!=null&&a||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===vj.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===Uo.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,o){var n,a;let I=this.kind===fA.AUDIO;if(ct[e?"addSuccessEvent":"addFailedEvent"]({key:I?504700:514702}),!I){let c=((n=this.room)==null?void 0:n.downlinkVideoCodec.toUpperCase())||"H264";ct[e?"addSuccessEvent":"addFailedEvent"]({key:Hh["DECODE_".concat(c,"_RESULT")]}),e||this.log.warn("".concat((a=this.room)==null?void 0:a.downlinkVideoCodec," decode failed"))}e||(ct.addEnum({key:I?504701:514703,value:FQ()}),Jo.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(pu()||UQ()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===fA.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:o}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===e){if(e&&(!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(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?Uo.ON:Uo.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};G(bm,"STATE_SUBSCRIBE","subscribe"),vt([Nx(5,1)],bm.prototype,"waitHasMediaTrack"),vt([is(Uo.INIT,bm.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),S.emit(K.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),Zh(521716,!1)],bm.prototype,"subscribe"),vt([is(bm.STATE_SUBSCRIBE,Uo.INIT,{sync:!0,success(){this.log.info("unsubscribed"),S.emit(K.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],bm.prototype,"unsubscribe");var E4=bm,Tx=class extends E4{constructor(A,e){super(A,e,1),G(this,"volume",0),G(this,"mediaType",1),G(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=A.audioManager}get dbVolume(){return ux.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,e;return!!this.manager&&(this.manager.decodePipeline.some(o=>o)||((e=(A=this.player.element)==null?void 0:A.error)==null?void 0:e.code)===MediaError.MEDIA_ERR_DECODE&&NM().AudioDecoder&&JQ)}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(A){if(!this.manager)return A;let e=A;for(let[o,n]of this.manager.decodePipeline.entries()){if(!n)continue;let a={frame:A,track:this};if(o===1&&this.isAvailable&&this.room.role==="audience"&&(a.onAudioFrameNTPTime=I=>{let{ntp:c,frame:u,hasLeavingTag:d}=I;this.emit("audio-frame-with-ntp",{ntp:c,frame:u,hasLeavingTag:d})}),e=n(a),!e)return}return e}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}},QeA=class extends cl{constructor(A,e,o,n,a){super(A,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:e}),this.setContainer=n,G(this,"initStat",{alphaStitchingType:1}),G(this,"end",wu()),G(this,"minSize",320),G(this,"maxSize",1280),G(this,"draggable",!1),G(this,"startDragX",0),G(this,"startDragY",0),G(this,"left",0),G(this,"top",0),G(this,"baseWidth",320),G(this,"baseRatio"),G(this,"container"),this.initStat=a,this.draggable=o,this.bindDragEvents(),ct.addEnum({key:515700,value:1}),this.draggable&&ct.addEnum({key:515700,value:11})}bindDragEvents(){let A=this.context._canvas;if(A)if(this.draggable){let e=Qc(this.end);Jn(Ln(A,"mousedown"),Oq(this.startDrag.bind(this)),yx(()=>Jn(Ln(window,"mousemove"),Qc(Ln(window,"mouseup")))),e,Ks(this.doDrag.bind(this))),Jn(Ln(A,"dblclick"),e,Ks(this.resetPosition.bind(this))),Jn(Ln(A,"wheel"),e,Ks(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 e;return!((e=this.input)==null||!e.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 e=A.deltaY,o=this.context._canvas;o&&(this.baseWidth||(this.baseWidth=o.offsetWidth),this.baseWidth=e<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,e,o,n,a){var I;let{ctx2d:c}=this,u=this.context._canvas;if(!c||!u)return!1;let d=super.draw2d(A,e,o,n,a),R=c.getImageData(0,0,n,a),{data:k}=R,_=!1;if(this.initStat.alphaStitchingType===1){let Z=Math.floor(n/2);for(let iA=0;iA=100;k[TA+3]=XA?255:0}_=super.draw2d(R,0,0,0,0,Z,a),u.width=Z}else if(this.initStat.alphaStitchingType===2){let Z=Math.floor(a/2);for(let iA=0;iA=100;k[TA+3]=XA?255:0}_=super.draw2d(R,0,0,0,0,n,Z),u.height=Z}return(I=this.context.ctx)==null||I.clearRect(0,0,n,a),d&&_}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}},nG=class extends E4{constructor(A,e){super(A,e,arguments.length>2&&arguments[2]!==void 0?arguments[2]:4),G(this,"mediaType",4),G(this,"source"),G(this,"shouldRenderAlpha",!1),G(this,"alphaNode"),G(this,"shouldBeDraggable",!0),G(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0,keyFramesDecoded:0}),G(this,"_keyFrameCountLogged",!1),G(this,"_keyFrameStartTimestamp",0),G(this,"_keyFrameStartCount",0),G(this,"_keyFrameIntervals",[]),G(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 e=new Uint8Array(A.data);return e.length%3==0&&e[0]===0&&e[1]===1&&e}play(A,e){return e!=null&&e.canvasRender&&!this.source&&this.useCanvasPlayer(),super.play(A,e).then(()=>{this.player.calculateStat(),S.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(A){let e=this.isAlphaSei(A);if(e)if(this.alphaNode){let o=e[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===o)return;this.alphaNode.initStat={alphaStitchingType:o};let n=this.player.getElement();if(n){let a=n.videoWidth/n.videoHeight;a&&(this.alphaNode.baseRatio=a*(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(e[2])}generateAlphaCanvasName(A){let e=Ph[A];return"".concat("alpha","_").concat(e,"_").concat(this.userId)}useCanvasPlayer(A){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let e=new vu({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&A?this.generateAlphaCanvasName(A):this.userId});e.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let o=new Yq(e,{name:"remotePlayer",logger:this.log});if(this.source=e.createVideoPlayerSource(this.player),this.player.setCanvas(e._canvas),this.shouldRenderAlpha&&A){let n=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},a=new QeA(e,this.log,this.shouldBeDraggable,n,{alphaStitchingType:A});this.source.connect(a),a.connect(o),this.alphaNode=a}else this.source.connect(o);HQ()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(A){let e=this.decodeFPS,o=(n=e,[15,30,45,60].reduce((a,I)=>Math.abs(I-n)a.msg_user_info.str_identifier===this.userId))||{},o=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let n=e.find(a=>a.uint32_video_stream_type===o);return n?.uint32_video_dec_fps||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),S.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(A){if(!this.manager)return A;for(let e of this.manager.decodePipeline)if(e&&!(A=e({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 e=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>e){let a=A-e,I=(o-this._prevKeyFrameTimestamp)/1e3/a;this._keyFrameIntervals.push(I)}this._prevKeyFrameTimestamp=o;let n=o-this._keyFrameStartTimestamp;if(n>=16e3){let a=A-this._keyFrameStartCount,I=a>0?n/1e3/a:0,c="".concat(a," keyframes in 16s ").concat(I," [").concat(this._keyFrameIntervals.map(d=>d.toFixed(1)).join(","),"] keyFramesDecoded ").concat(A),u=I<=2.5?"debug":"info";this.log[u](c),this._keyFrameCountLogged=!0}}},l4=class extends nG{constructor(A,e){super(A,e,2),G(this,"mediaType",2),G(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},YM=new Map;function Ua(A,e){let o=fi(bt({},e),{timestamp:Eh()});YM.has(A)?YM.get(A).push(o):YM.set(A,[o])}function C4(){for(var A=arguments.length,e=new Array(A),o=0;ofunction(){for(var I=arguments.length,c=new Array(I),u=0;uRh(R)?Vf(R):Sr(R)?R:ya(R))},fnName:a,value:o},link:{className:I,fnName:a}})})}else if(!Ee(e.type)&&ya(o)!==e.type)throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_PARAMETER_TYPE,data:{key:n,rule:e,fnName:a,value:o},link:{className:I,fnName:a}})});if(e.allowEmpty===!1){let d=hr(o)&&(o===0||Number.isNaN(o)),R=Sr(o)&&o.trim()==="";if(d||R)throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_PARAMETER_EMPTY,data:{key:n,rule:e,fnName:a,value:o},link:{className:I,fnName:a}})})}if(e.notLessThanZero&&hr(o)&&o<0)throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.CANNOT_LESS_THAN_ZERO,data:{key:n,rule:e,fnName:a,value:o},link:{className:I,fnName:a}})});if(!Ee(e.min)&&hr(o)&&oe.max)throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_PARAMETER_MAX,data:{key:n,rule:e,fnName:a,value:o},link:{className:I,fnName:a}})});if(Sr(e.instanceOf)){if(!o||o._name!==e.instanceOf)throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_PARAMETER_INSTANCE,data:{key:n,rule:e,fnName:a,value:o},link:{className:I,fnName:a}})})}else if($n(e.instanceOf)&&!(o instanceof e.instanceOf))throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_PARAMETER_INSTANCE,data:{key:n,rule:e,fnName:a,value:o},link:{className:I,fnName:a}})});if(e.values&&!e.values.includes(o))throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_PARAMETER_RANGE,data:{key:n,rule:e,fnName:a,value:o},link:{className:I,fnName:a}})});let{properties:c}=e;Cc(c)&&Xc(o)&&Object.keys(c).forEach(d=>{Gx.call(this,{rule:c[d],value:o&&o[d],key:"".concat(n,".").concat(d),fnName:a,className:I})});let{arrayItem:u}=e;Cc(u)&&Aa(o)&&o.forEach((d,R)=>{Gx.call(this,{rule:u,value:d,key:"".concat(n,"[").concat(R,"]"),fnName:a,className:I})}),$n(e.validate)&&e.validate.call(this,o,n,a,I,this)}S.on(K.JOIN_SUCCESS,A=>{let{room:e}=A;Ua(e.userId,{eventId:32788})}),S.on(K.LEAVE_START,A=>{let{room:e}=A;Ua(e.userId,{eventId:32789})}),S.on(K.LOCAL_TRACK_PUBLISHED,A=>{let{track:e}=A;if(e.room){let o=32769;e.mediaType===4?o=32768:e.mediaType===2&&(o=32805),Ua(e.room.userId,{eventId:o})}}),S.on(K.LOCAL_TRACK_UNPUBLISHED,A=>{let{track:e}=A;if(e.room){let o=32771;e.mediaType===4?o=32770:e.mediaType===2&&(o=32806),Ua(e.room.userId,{eventId:o})}}),S.on(K.TRACK_MUTED,A=>{let{track:e}=A;e.room&&(e.kind===fA.AUDIO?Ua(e.room.userId,{eventId:e.isRemote?32785:32772,remoteUserId:e.isRemote?e.userId:void 0}):Ua(e.room.userId,{eventId:e.isRemote?32784:32773,remoteUserId:e.isRemote?e.userId:void 0}))}),S.on(K.TRACK_UNMUTED,A=>{let{track:e}=A;e.room&&(e.kind===fA.AUDIO?Ua(e.room.userId,{eventId:e.isRemote?32787:32774,remoteUserId:e.isRemote?e.userId:void 0}):Ua(e.room.userId,{eventId:e.isRemote?32786:32775,remoteUserId:e.isRemote?e.userId:void 0}))}),S.on(K.REMOTE_TRACK_SUBSCRIBED,A=>{let{track:e}=A;e.room&&(e.mediaType===1&&Ua(e.room.userId,{eventId:32777,remoteUserId:e.userId}),e.mediaType===4&&Ua(e.room.userId,{eventId:32776,remoteUserId:e.userId}),e.mediaType===8&&Ua(e.room.userId,{eventId:32803,remoteUserId:e.userId}))}),S.on(K.REMOTE_TRACK_UNSUBSCRIBED,A=>{let{track:e}=A;e.room&&(e.mediaType===1&&Ua(e.room.userId,{eventId:32779,remoteUserId:e.userId}),e.mediaType===4&&Ua(e.room.userId,{eventId:32778,remoteUserId:e.userId}),e.mediaType===8&&Ua(e.room.userId,{eventId:32804,remoteUserId:e.userId}))}),S.on(K.SWITCH_DEVICE_SUCCESS,A=>{let{track:e}=A;e.room&&Ua(e.room.userId,{eventId:e.kind===fA.VIDEO?32780:32781})}),S.on(K.LOCAL_TRACK_REPLACED,A=>{let{track:e}=A;e.room&&Ua(e.room.userId,{eventId:e.kind===fA.VIDEO?32782:32783})}),S.on(K.SIGNAL_CONNECTION_STATE_CHANGED,A=>{let e,{room:o,prevState:n,state:a}=A;switch(a){case"CONNECTED":e=n==="RECONNECTING"?32795:32791;break;case"DISCONNECTED":e=n==="RECONNECTING"?32796:32790;break;case"RECONNECTING":e=32794}e&&Ua(o.userId,{eventId:e})}),S.on(K.PEER_CONNECTION_STATE_CHANGED,A=>{let e,{room:o,prevState:n,state:a,remoteUserId:I}=A,c=!!I;switch(a){case"CONNECTED":e=n==="RECONNECTING"?c?32801:32798:c?32793:32792;break;case"DISCONNECTED":n==="RECONNECTING"&&(e=c?32802:32799);break;case"RECONNECTING":e=c?32800:32797}e&&Ua(o.userId,{eventId:e,remoteUserId:I})}),S.on(K.VIDEO_CODEC_IMPLEMENTATION_CHANGED,A=>{let{implementation:e,userId:o,remoteUserId:n,codec:a,isHWCodec:I,prevImplementation:c,streamType:u}=A,d=I?1:0;c||(d=I?3:2);let R={H264:0,H265:1,VP8:2}[a.toUpperCase()],k={eventId:4004,param1:d,param2:R,streamType:u||2};n&&(k.remoteUserId=n,k.eventId=4005),Ua(o,k),ct.addEnum({key:n?514701:513701,value:d}),ct.addEnum({key:n?514700:513700,value:R})}),S.on(K.LOCAL_TRACK_RECAPTURE,A=>{let{track:e,error:o}=A;if(e.userId){let n={eventId:2003,param1:0};e.kind===fA.AUDIO?(n.streamType=1,o&&(n.param1=2)):(n.streamType=e.streamType==="auxiliary"?7:2,o&&(n.param1=8)),Ua(e.userId,n)}});var heA=es(hg(),1),peA=class extends heA.EventEmitter{constructor(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"userId";super(),this.mySelfId=A,this._log=e,this.key=o,G(this,"userMap",new Map),G(this,"remotePublishedUserMap",new Map),G(this,"asrRobotUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(A=>A.isRobot)}getPublishedUser(A){return this.remotePublishedUserMap.get(A)}addUser(A){let e=A[this.key],{userId:o,tinyId:n,role:a,fromType:I}=A;if(I===JR)return void this.addAsrRobotUser(A);if(this.userMap.has(e))return;let c={userId:o,tinyId:n,role:a===20?"anchor":"audience"};this.userMap.set(e,c),this.emit("1",c)}addAsrRobotUser(A){let e=A[this.key],{userId:o,tinyId:n,role:a}=A;if(this.asrRobotUserMap.has(e))return;let I={userId:o,tinyId:n,role:a===20?"anchor":"audience"};this.asrRobotUserMap.set(e,I),this.emit("8",I)}deleteUser(A,e){let o=this.userMap.get(A);if(!o)return;if(this.asrRobotUserMap.has(A))return void this.deleteAsrRobotUser(A);let n="peer leave [".concat(A,"]");Ee(e)||(n+=":".concat(dO[e])),this._log.info(n);let a=this.remotePublishedUserMap.get(A);if(a){let I=a.muteState;a.flag=0,this.emit("5",a.userId),this.deleteRemotePublishedUser(A),this.emit("6",{prevMuteState:I,muteState:a.muteState,flag:0})}this.userMap.delete(A),this.emit("2",{userId:o.userId,reason:e})}deleteAsrRobotUser(A){if(!this.asrRobotUserMap.has(A))return;let e=this.asrRobotUserMap.get(A);e&&(this.asrRobotUserMap.delete(A),this.emit("9",e))}setUserList(A){this.userMap.forEach(e=>{A.findIndex(o=>o[this.key]===e[this.key])<0&&this.deleteUser(e[this.key],0)}),A.forEach(e=>{!this.userMap.has(e[this.key])&&e[this.key]!==this.mySelfId&&this.addUser(e)})}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(e=>{let o=e[this.key];if(A.findIndex(n=>n[this.key]===e[this.key])<0){this._log.info("remote [".concat(o,"] unpublish"));let n=e.muteState;e.flag=0,this.emit("5",e.userId),this.deleteRemotePublishedUser(o),this.emit("6",{prevMuteState:n,muteState:e.muteState,flag:0})}}),A.forEach(e=>{var o;let n=e[this.key];if(n===this.mySelfId)return void this.emit("7",e);let{flag:a,userId:I,tinyId:c,fromType:u}=e,d=RQ(a,I),R=(o=this.remotePublishedUserMap.get(n))==null?void 0:o.muteState;if(R){let k=this.remotePublishedUserMap.get(n);k&&k.flag!==a&&(k.flag=a,this._log.info("remote publish updated: ".concat(JSON.stringify(k.muteState))),this.emit("6",{prevMuteState:R,muteState:d,flag:a}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(d))),this.addUser({userId:I,tinyId:c,role:20,fromType:u}),this.emit("3",e),this.emit("6",{prevMuteState:RQ(0,I),muteState:d,flag:a})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}},feA=es(hg(),1),meA=class extends feA.default{constructor(){super(...arguments),G(this,"_connectionTimeoutCount",0),G(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 B4(A){let{timesInSecond:e,maxSizeInSecond:o,getSize:n}=A;return Dn((a,I)=>{let c=new WeakMap;return S.on(K.ROOM_DESTROY,u=>{let{room:d}=u;return c.delete(d)}),function(){let u=c.get(this);for(var d=arguments.length,R=new Array(d),k=0;k1e3&&(u.timestamp=Date.now(),u.callCountInSecond=0,u.totalSizeInSecond=0),n&&(u.totalSizeInSecond+=n(...R)),u.timestamp!==0&&Date.now()-u.timestamp<1e3&&(u.callCountInSecond>=e||u.totalSizeInSecond>o))throw new Ct({code:Ge.INVALID_OPERATION,message:Wi({key:Mi.CALL_FREQUENCY_LIMIT,data:{isTimes:u.callCountInSecond>=e,isSize:u.totalSizeInSecond>o,name:I,timesInSecond:e,maxSizeInSecond:o}})});u.callCountInSecond++,a.call(this,...R)}})}var xe,u4=!0,aG={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"},Si={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},kx=((xe=kx||{})[xe.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",xe[xe.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",xe[xe.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",xe[xe.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",xe[xe.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",xe[xe.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",xe[xe.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",xe[xe.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",xe[xe.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",xe[xe.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",xe[xe.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",xe[xe.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",xe[xe.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",xe[xe.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",xe[xe.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",xe[xe.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",xe[xe.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",xe[xe.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",xe[xe.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",xe[xe.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",xe[xe.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",xe[xe.INVALID_OPERATION=5100]="INVALID_OPERATION",xe[xe.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",xe[xe.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",xe[xe.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",xe[xe.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",xe[xe.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",xe[xe.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",xe[xe.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",xe[xe.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",xe[xe.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",xe[xe.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",xe[xe.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",xe[xe.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",xe[xe.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",xe[xe.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",xe[xe.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",xe[xe.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",xe[xe.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",xe[xe.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",xe[xe.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",xe[xe.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",xe[xe.DEVICE_ERROR=5300]="DEVICE_ERROR",xe[xe.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",xe[xe.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",xe[xe.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",xe[xe.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",xe[xe.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",xe[xe.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",xe[xe.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",xe[xe.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",xe[xe.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",xe[xe.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",xe[xe.SERVER_ERROR=5400]="SERVER_ERROR",xe[xe.NEED_TO_BUY=5401]="NEED_TO_BUY",xe[xe.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",xe[xe.OPERATION_FAILED=5500]="OPERATION_FAILED",xe[xe.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",xe[xe.REJOIN_FAILED=5502]="REJOIN_FAILED",xe[xe.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",xe[xe.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",xe[xe.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",xe[xe.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",xe[xe.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",xe[xe.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",xe[xe.OPERATION_ABORT=5998]="OPERATION_ABORT",xe[xe.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",xe),Q4=fi(bt({},ts),{INVALID_PARAMETER(A){let{fnName:e}=A;return"the parameters of the '".concat(e,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(A){let{key:e,rule:o,fnName:n,value:a}=A;return"'".concat(e||o.name,"' is a required param when calling ").concat(n,"(), received: ").concat(a,".")},INVALID_PARAMETER_TYPE(A){let{key:e,rule:o,fnName:n,value:a}=A,I="".concat(e||o.name),c="";return c=Array.isArray(o.type)?o.type.join("|"):o.type,"'".concat(I,"' must be type of ").concat(c," when calling ").concat(n,"(), received type: ").concat(ya(a),".")},INVALID_PARAMETER_EMPTY(A){let{key:e,rule:o,fnName:n,value:a}=A;return"'".concat(e||o.name,"' cannot be '").concat(a,"' when calling ").concat(n,"().")},INVALID_PARAMETER_INSTANCE(A){let{key:e,rule:o,fnName:n,value:a}=A,I="".concat(e||o.name),c="".concat(o.instanceOf.name||o.instanceOf);return"'".concat(I,"' must be instanceof ").concat(c," when calling ").concat(n,"(), received type: ").concat(ya(a),".")},INVALID_PARAMETER_RANGE(A){let{key:e,rule:o,fnName:n,value:a}=A;return"'".concat(e||o.name,"' must be one of ").concat(o.values.join("|")," when calling ").concat(n,"(), received: ").concat(a,".")},INVALID_PARAMETER_LESS_THAN_ZERO(A){let{key:e,rule:o,fnName:n}=A;return"'".concat(e||o.name,"' cannot be less than 0 when calling ").concat(n,"().")},INVALID_PARAMETER_MIN(A){let{key:e,rule:o,value:n}=A;return"the min value of ".concat(e||o.name," is ").concat(o.min,", received: ").concat(n,".")},INVALID_PARAMETER_MAX(A){let{key:e,rule:o,value:n}=A;return"the max value of ".concat(e||o.name," is ").concat(o.max,", received: ").concat(n,".")},INVALID_ELEMENT_ID(A){let{key:e,fnName:o}=A;return"'".concat(e,"' is not found in the document object when calling ").concat(o,"().")},INVALID_ELEMENT_ID_TYPE(A){let{key:e,fnName:o,type:n}=A;return"the element corresponding to '".concat(e,"' must be instanceof HTMLElement when calling ").concat(o,"(), received: ").concat(n,".")},INVALID_STREAM_ID(A){let{key:e}=A;return"'".concat(e,"' 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:e}=A;return"'".concat(e,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(A){let{key:e}=A;return"'".concat(e,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(A){let{key:e}=A;return"'".concat(e,"' 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:e}=A;return"The type of target roomId must match the current roomId. Current room is using '".concat(e,"', but received '").concat(e==="strRoomId"?"roomId":"strRoomId","'.")},INVALID_ROOM_ID_DUPLICATE(A){let{key:e}=A;return"the target '".concat(e,"' must not be the same as the current '").concat(e,"'.")},INVALID_STREAM_TYPE:A=>{let{fnName:e}=A;return"'streamType' is required when 'userId' is not '*', calling ".concat(e,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(A){let{fnName:e}=A;return"the API '".concat(e,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(A){let{fnName:e}=A;return"cannot ".concat(e," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(A){let{fnName:e,value:o}=A;return"cannot ".concat(e," because remote user(userId: ").concat(o.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(A){let{fnName:e,value:o}=A;return"cannot ".concat(e," because remote user(userId: ").concat(o.userId,") does not publishing ").concat(o.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(A){let{fnName:e}=A;return"you are already ".concat(e,"(), cannot repeated call '").concat(e,"'.")},INVALID_OPERATION_NEED_VIDEO(A){let{fnName:e}=A;return"cannot call '".concat(e,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(A){let{fnName:e}=A;return"cannot call '".concat(e,"' because the microphone or screen share is not turned on.")},INVALID_BUFFER_EMPTY:A=>{let{key:e}=A;return"the buffer size of paramerter '".concat(e,"' 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:e}=A;return"you need to call ".concat(e,"() after publish stream.")},ENV_NOT_SUPPORTED(A){let{fnName:e}=A;return"the current browser does not support the capability of the function '".concat(e,"' 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:e}=A;return"cannot call ".concat(e," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(A){let{fnName:e,error:o}=A;return"'".concat(e,"' got device exception").concat(o?", error: ".concat(o.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(A){let{fnName:e,deviceType:o=Lm(e),error:n}=A;return"NotFoundError, no ".concat(o," detected, please check your device and the configuration on '").concat(e,"'").concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(A){let{fnName:e,deviceType:o=Lm(e),error:n}=A;return"NotAllowedError, you have disabled ".concat(o," access, please allow the current application to use the ").concat(o).concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(A){let{fnName:e,deviceType:o=Lm(e),error:n}=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:e,deviceType:o=Lm(e),error:n}=A;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(A){let{fnName:e,deviceType:o=Lm(e),error:n}=A;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(o).concat(n?", error: ".concat(n.toString(),"."):".")},DEVICE_SECURITY_ERROR(A){let{fnName:e,deviceType:o=Lm(e),error:n}=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(n?", error: ".concat(n.toString(),"."):".")},DEVICE_ABORT_ERROR(A){let{fnName:e,deviceType:o=Lm(e),error:n}=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(n?" error: ".concat(n.toString(),"."):".")},CAMERA_RECOVER_FAILED(A){let{error:e}=A;return"camera recover capture failed ".concat(e?.name||"",": ").concat(e?.originMessage||e?.message)},MICROPHONE_RECOVER_FAILED(A){let{error:e}=A;return"microphone recover capture failed ".concat(e?.name||"",": ").concat(e?.originMessage||e?.message)},OPERATION_FAILED(A){let{fnName:e,error:o}=A;return"'".concat(e,"' 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:e}=A;return"an error was caught on trtc.on('".concat(e,"', handler), please check your code on 'handler'.")},VIDEO_CONTEXT_ERROR(A){let{reason:e,error:o}=A;return"video context error ".concat(e," ").concat(o?.name||""," ").concat(o?.message||"")},SERVER_ERROR(A){let{fnName:e,error:o}=A;return"'".concat(e,"' got server error: ").concat(o?.toString(),", please check the SDK documentation.")},NEED_TO_BUY(A){let{value:e,url:o}=A;return"You need to buy packages for ".concat(e,". Refer to: ").concat(o)},ACCOUNT_NO_MONEY:A=>{let{fnParams:e}=A;return"your TRTC account run out of credit, please recharge.".concat(e.sdkAppId?" SDKAppId: ".concat(e.sdkAppId):"")},OPERATION_ABORT(A){let{fnName:e}=A;return"'".concat(e,"' abort")},UNKNOWN_ERROR(A){let{fnName:e,error:o}=A;return"'".concat(e,"' throw unknown exception").concat(o?", error: ".concat(o.toString(),"."):".")}});function Lm(A){if(!A)return"camera";let e=A.toLowerCase();return e.includes("screen")?"screen share":e.includes("audio")?"microphone":"camera"}var DeA=class w2 extends Error{constructor(e){let{code:o,extraCode:n,message:a="",messageParams:I,fnName:c="",originError:u,data:d}=e;var R;let k;k=a||function(_){let Z,{code:iA,params:cA,enableDocLink:TA=!1}=_,JA="",Ie=kx[iA];try{Z=Q4[Ie]}catch{Z=Q4.UNKNOWN_ERROR}return $n(Z)?JA=Z(cA):Sr(Z)&&(JA=Z),cA.fnName&&!JA.includes(cA.fnName)&&(JA[JA.length-1]!=="."&&(JA+="."),JA+=" thrown from ".concat(cA.fnName,"()")),TA&&(JA+=" doc:"),JA}({code:o===Si.SERVER_ERROR?o:n||o,params:bt({fnName:c,error:u},I)}),super(k),G(this,"name","RtcError"),G(this,"code"),G(this,"extraCode"),G(this,"functionName"),G(this,"message"),G(this,"data"),G(this,"handler"),G(this,"originError"),this.name=kx[o],this.code=o,this.extraCode=n,this.functionName=c,this.originError=u,this.message=k,this.data=d,this.extraCode===5302&&(R=this.originError)!=null&&R.message.includes("system")&&(this.handler=()=>{let _=document.createElement("a");Gh?_.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):uu&&(_.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),_.href.length>0&&_.click()})}static convertFrom(e,o,n){let a=e;if(e instanceof Ct){let{stack:I}=e,c={code:Si.UNKNOWN_ERROR,fnName:o,originError:e};switch(e.getCode()){case Ge.INVALID_PARAMETER:c.code=Si.INVALID_PARAMETER,c.message=e.message;break;case Ge.INVALID_OPERATION:c.code=Si.INVALID_OPERATION,c.message=e.message;break;case Ge.NOT_SUPPORTED:case Ge.NOT_SUPPORTED_H264:c.code=Si.ENV_NOT_SUPPORTED,e.getCode()===Ge.NOT_SUPPORTED_H264&&(c.extraCode=e.message.includes(ts.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case Ge.JOIN_ROOM_FAILED:c.messageParams={fnParams:n};case Ge.SERVER_TIMEOUT:case Ge.SWITCH_ROLE_FAILED:case Ge.SWITCH_ROOM_FAILED:c.code=Si.SERVER_ERROR,c.extraCode=e.getExtraCode();break;case Ge.API_CALL_ABORTED:c.code=Si.OPERATION_ABORT;break;case Ge.DEVICE_NOT_FOUND:case Ge.DEVICE_AUTO_RECOVER_FAILED:case Ge.INITIALIZE_FAILED:c.code=5300,e.name&&(c.extraCode=function(u){let d;switch(u){case"NotFoundError":d=5301;break;case"NotAllowedError":d=5302;break;case"NotReadableError":d=5303;break;case"OverconstrainedError":d=5304;break;case"InvalidStateError":d=5305;break;case"SecurityError":d=5306;break;case"AbortError":d=5307;break;default:d=5300}return d}(e.name));break;case Ge.VIDEO_ENCODE_FAILED:c.extraCode=5505;case Ge.AUDIO_ENCODE_FAILED:c.extraCode=5506,c.code=Si.OPERATION_FAILED;break;case Ge.UNKNOWN:break;default:c.code=Si.OPERATION_FAILED}a=new w2(c),I&&(a.stack+=I.substr(I.indexOf(` +`)))}else{if(e instanceof w2)return e;a=new w2({code:Si.UNKNOWN_ERROR,fnName:o,originError:e})}return a}},vi=DeA;function El(A){return A==="sub"?"auxiliary":A==="auxiliary"?"sub":"main"}function _x(A){return A===aG.QOS_PREFERENCE_CLEAR?"detail":A===aG.QOS_PREFERENCE_SMOOTH?"motion":""}function bx(A,e){let o=e?aO:kf;return UO(A)?bt(bt({},o),A):$l[A]?$l[A]:o}var d4={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}}},h4={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}}},PM={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(A,e,o){if(Sr(A)&&!document.getElementById(A))throw new vi({code:Si.INVALID_PARAMETER,extraCode:5009,fnName:o,messageParams:{key:e}})}},p4={name:"userId",required:!0,type:"string"},f4={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 JM(A,e){if(!A)throw new vi({code:Si.INVALID_OPERATION,extraCode:5101,fnName:e})}function m4(A,e,o){if(!A)throw new vi({code:Si.INVALID_OPERATION,extraCode:5102,fnName:e,messageParams:{value:o}})}function D4(A,e,o){if(!(/^[1-9]\d*$/.test(String(A))&&A<4294967295))throw new vi({code:Si.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:o}})}function y4(A,e,o){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(A))throw new vi({code:Si.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:o}})}function R4(A){var e;if((e=A?.option)==null||!e.small)return;if(!pm())return nA.warn("small stream is not supported"),void delete A.option.small;let o=bx(A.option.profile),n=bx(A.option.small,!0);return((a,I)=>a.width*a.height>=I.width*I.height&&a.frameRate>=I.frameRate&&a.bitrate>=I.bitrate)(o,n)?void 0:(nA.warn("small stream profile must be less than big stream profile. Big: ".concat(JSON.stringify(o),", Small: ").concat(JSON.stringify(n))),void delete A.option.small)}var yeA={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,e,o){if(this._room.isJoined)throw new vi({code:Si.INVALID_OPERATION,extraCode:5104,fnName:o});if(A.roomId){if(Sr(A.roomId))throw new vi({code:Si.INVALID_PARAMETER,extraCode:5016,fnName:o,messageParams:{key:e}});D4(A.roomId,o,e)}else{if(!A.strRoomId)throw new vi({code:Si.INVALID_PARAMETER,extraCode:5015,fnName:o});y4(A.strRoomId,o,e)}},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:PM,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:d4},validate(A){var e,o;if(((e=A?.option)==null||!e.videoTrack)&&wI())throw new vi({code:Si.ENV_NOT_SUPPORTED,extraCode:5201});(o=A?.option)!=null&&o.small&&R4(A)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:fi(bt({},PM),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:d4},validate(A){var e;(e=A?.option)!=null&&e.small&&R4(A)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:f4},validate(A){var e;if(((e=A?.option)==null||!e.audioTrack)&&wI())throw new vi({code:Si.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:f4}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:PM,publish:{type:"boolean"},option:h4},validate(A,e,o,n,a){var I;if((I=A?.option)==null||!I.videoTrack){if(wI())throw new vi({code:Si.ENV_NOT_SUPPORTED,extraCode:5201});if(!PQ())throw new vi({code:Si.ENV_NOT_SUPPORTED,fnName:o,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:PM,publish:{type:"boolean"},option:h4}},muteRemoteAudio:[p4,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[p4,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:PM,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,e,o){JM(this._room.isJoined,o);let n=this._room.remotePublishedUserMap.get(A.userId);if(m4(!!n,o,A),n&&(A.streamType==="main"&&!n.muteState.videoAvailable||A.streamType==="sub"&&!n.muteState.hasAuxiliary))throw new vi({code:Si.INVALID_OPERATION,extraCode:5103,fnName:o,messageParams:{value:A}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:fi(bt({},PM),{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,e,o){JM(this._room.isJoined,o);let n=this._room.remotePublishedUserMap.get(A.userId);if(m4(!!n,o,A),n){if(A.streamType==="main"&&!n.muteState.videoAvailable||A.streamType==="sub"&&!n.muteState.hasAuxiliary)throw new vi({code:Si.INVALID_OPERATION,extraCode:5103,fnName:o,messageParams:{value:A}});if(A.option){let a=A.streamType==="main"?n.remoteVideoTrack:n.remoteAuxiliaryTrack;if((A.option.pictureInPicture||A.option.fullScreen||A.option.fullScreen)&&(!a.isSubscribed||!a.player.isPlaying))throw new vi({code:Si.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,e,o){if(A.userId!=="*"&&Ee(A.streamType))throw new vi({code:Si.INVALID_PARAMETER,extraCode:5014,fnName:o})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(A,e,o){JM(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,e,o,n){if(!FT)throw new vi({code:Si.ENV_NOT_SUPPORTED,fnName:o,extraCode:5207});if(!this._room.enableSEI)throw new vi({code:Si.INVALID_OPERATION,fnName:o,extraCode:5108});if(A.byteLength>1e3)throw new vi({code:Si.INVALID_PARAMETER,extraCode:5018,fnName:o});if(A.byteLength===0)throw new vi({code:Si.INVALID_PARAMETER,extraCode:5017,messageParams:{key:e},fnName:o});JM(this._room.isJoined,o)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(A,e,o){if(!A&&!this._room.isMainStreamPublished||A&&!this._room.isAuxStreamPublished)throw new vi({code:Si.INVALID_OPERATION,extraCode:5109,messageParams:{key:e},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,e,o,n){if(A.byteLength>1e3)throw new vi({code:Si.INVALID_PARAMETER,extraCode:5018,fnName:o});if(A.byteLength===0)throw new vi({code:Si.INVALID_PARAMETER,extraCode:5017,fnName:o,messageParams:{key:e}})}}},validate(A,e,o){if(JM(this._room.isJoined,o),this._room.scene==="live"&&this._room.role==="audience")throw new vi({code:Si.INVALID_OPERATION,extraCode:5107,fnName:o,messageParams:{key:e}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(A,e,o){if(JM(this._room.isJoined,o),this._room.useStringRoomId&&A.strRoomId===this._room.roomId||!this._room.useStringRoomId&&A.roomId===Number(this._room.roomId))throw new vi({code:Si.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 vi({code:Si.INVALID_PARAMETER,extraCode:5019,fnName:o,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(A.roomId)D4(A.roomId,o,e);else{if(!A.strRoomId)throw new vi({code:Si.INVALID_PARAMETER,extraCode:5015,fnName:o});y4(A.strRoomId,o,e)}},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},mg={TRTC:yeA},ll=class extends Error{};function ReA(A,e){let o=Mh(A);for(let n=0;n!0),G(this,"mergeUpdate",ReA);let n=iw.instances.get(e);n?n.set(o,this):iw.instances.set(e,new Map([[o,this]]))}static get(e,o){if(!o)return;let n=iw.instances.get(e);return n&&n.get(o)||new iw(e,o)}static gets(e,o){let n=iw.instances.get(e),a=[];return n&&n.forEach((I,c)=>{o.test(c)&&a.push(I)}),a}action(e,o,n){let a=u=>{var d;return e===0?this.started=!0:e===3&&(this.started=!1),this.ops.shift(),(d=this.currentOp)==null||d.action(),u},I=u=>{var d,R;throw this.ops.shift(),e===0&&((d=this.currentOp)==null?void 0:d.type)===2&&this.ops.shift().reject(new ll("start failed")),(R=this.currentOp)==null||R.action(),u},c={type:e,action:()=>o(...c.args).then(a,I),args:n,resolve:MeA,reject:weA};try{switch(this.state){case 1:if(e===0)throw new ll("already started");break;case 4:if(e===2)throw new ll("not started");break;default:return this.cacheOp(c)}}catch(u){return Promise.reject(u)}return this.ops.push(c),c.promise=o(...c.args).then(a,I)}cacheOp(e){if(this.ops.length===1)switch(this.state){case 0:case 2:if(e.type===0)throw new ll("already start");break;case 3:switch(e.type){case 2:throw new ll("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new ll("unknown state")}else switch(e.type){case 3:if(this.lastOpType===3)return this.lastOp.promise;{let n=new ll("keep stop");if(this.ops.slice(1).forEach(a=>a.reject(n)),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,e.args),this.lastOp.promise;case 3:throw new ll("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new ll("start not allowed after update");case 0:throw new ll("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new ll("keep start")),new ll("already start")}}e.promise=new Promise((n,a)=>{e._resolve?e._resolve.then(n):e.resolve=n,e._reject?e._reject.catch(a):e.reject=a});let{action:o}=e;return e.action=()=>o().then(e.resolve,e.reject),this.ops.push(e),e.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}};G(M4,"instances",new WeakMap);var sG=M4,Lx=new WeakMap,Fx=(A,e)=>{if(e instanceof ll){let{stack:o}=e;e=new vi({code:Si.OPERATION_ABORT,message:"".concat(A," abort: ").concat(e.message),fnName:A}),o&&(e.stack+=o.substr(o.indexOf(` +`)))}throw e};function Fm(A,e){return Dn((o,n)=>function(){for(var a=arguments.length,I=new Array(a),c=0;cfunction(){for(var c=arguments.length,u=new Array(c),d=0;d{var cA,TA;let JA=(cA=Lx.get(this))==null?void 0:cA.get(_(...u));if(JA){let{timeoutId:XA,resolve:Ft}=JA;clearTimeout(XA),Ft()}let Ie=setTimeout(()=>{if(R.state===3||R.state===4)return Z();R.action(2,a.bind(this),u).catch(Fx.bind(null,I)).then(Z,iA)},k);Lx.has(this)?(TA=Lx.get(this))==null||TA.set(_(...u),{timeoutId:Ie,resolve:Z}):Lx.set(this,new Map([[_(...u),{timeoutId:Ie,resolve:Z}]]))})}return R.action(2,a.bind(this),u).catch(Fx.bind(null,I))})}function Um(A){return Dn((e,o)=>function(){for(var n=arguments.length,a=new Array(n),I=0;Id.action(3,()=>Promise.resolve(),a))).then(()=>e.call(this,...a));let u=sG.get(this,c);return u?u.action(3,e.bind(this),a).catch(Fx.bind(null,o)):e.apply(this,a)})}function Om(){return function(A,e,o){return A.prototype[e]=function(){let n=this._log||console,a='"'.concat(e,'" is a static method. Use TRTC.').concat(e,"() instead. See: ").concat($C,"/en/TRTC.html#.").concat(e);n.warn(a)},o}}var Xt={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"},SeA=new Set([Xt.AUDIO_VOLUME,Xt.AUDIO_FRAME,Xt.NETWORK_QUALITY,Xt.STATISTICS,Xt.SEI_MESSAGE,Xt.CUSTOM_MESSAGE,Xt.LAYER_DATA]),w4={};XC(w4,{ScheduleRequestType:()=>N4,getAbilityConfig:()=>veA,getScheduleDomain:()=>zq,isNeedToSchedule:()=>gG,scheduleProxy:()=>ZQ,sendScheduleRequest:()=>v4,setIsNeedToSchedule:()=>Nu,setScheduleProxy:()=>Wq});var Ux=null,Ox=0,S4=72e5,xx="trtc_schedule_cache",gG=!0;function Nu(A){rn(A)&&A!==gG&&(gG=A,nA.info("setIsNeedToSchedule ".concat(A)),A?function(){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.removeItem(xx)}catch(e){nA.error("clearScheduleCache error",e)}}():Ox=Date.now()+S4)}function v4(A){return DA(this,arguments,function(e){let{userId:o,sdkAppId:n,useStringRoomId:a,roomId:I,userSig:c,version:u,frameWorkType:d,role:R,latencyLevel:k}=e;return function*(){var _;if(!gG&&Ux&&Ox>Date.now())return{isCached:!0,result:Ux};let Z={delta:0,count:[1,1],msg:[],detail:[]};try{let iA=new FormData;iA.append("userId",String(o)),iA.append("sdkAppId",String(n)),iA.append("isStrGroupId",String(a)),iA.append("groupId",String(I)),iA.append("sdkVersion",u),iA.append("userSig",String(c));let cA=((_=yield Im())==null?void 0:_.model)||BT();cA&&iA.append("model",cA);let TA=UQ();TA&&iA.append("osString",TA);let JA=LQ();JA&&iA.append("gpu",JA),R&&iA.append("role",String(R)),k&&iA.append("latencyLevel",String(k)),d&&iA.append("frameWorkType",String(d));let Ie=ki(),XA=yield function(ie,ke,Nt){return new Promise((Ut,Ui)=>{let Oi=null;qf([T4(or=>ke.count[0]=or+1,or=>{let{error:xi,retry:yo,retriedCount:Sa,retryFuncArgs:Vn}=or;ke.msg[0]=xi.message,Oi||(Sa>=1&&(Vn[0]=ep(Nt,"config",fA.MAIN,!0)),yo())})(ep(Nt,"config",fA.MAIN),ie,{get timeout(){return 1e3*Dh(2+ke.count[0])}}),T4(or=>ke.count[1]=or+1,or=>{let{error:xi,retry:yo,retriedCount:Sa,retryFuncArgs:Vn}=or;ke.msg[1]=xi.message,Oi||(Sa>=2&&(Vn[0]=ep(Nt,"config",fA.BACKUP,!0)),yo())})(ep(Nt,"config",fA.BACKUP),ie,{get timeout(){return 1e3*Dh(2+ke.count[1])}})]).then(or=>{Oi=or,Ut(Oi)}).catch(Ui)})}(iA,Z,n);XA.config&&(XA.config.loggerDomain&&Tf(XA.config.loggerDomain),rn(XA.config.scheduleCache)&&Nu(!XA.config.scheduleCache)),Z.delta=ki()-Ie;let Ft=function(ie,ke,Nt){let Ut={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let Ui=performance.getEntriesByType("resource"),Oi=ep(ie,"config",fA.MAIN),or=ep(ie,"config",fA.BACKUP);for(let xi of Ui)if(xi.startTime>=Nt&&(xi.name===Oi||xi.name===or)&&xi.transferSize>0){let yo=xi.name===Oi?fA.MAIN:fA.BACKUP,Sa=Math.round(xi.duration),Vn=Math.round(xi.domainLookupStart-xi.startTime),NI=xi.redirectStart>0?Math.round(xi.redirectEnd-xi.redirectStart):0,CG=xi.fetchStart>0?Math.round(xi.domainLookupStart-xi.fetchStart):0,WM=Math.round(xi.domainLookupEnd-xi.domainLookupStart),Nz=Math.round(xi.requestStart-xi.secureConnectionStart),Tz=Math.round(xi.secureConnectionStart-xi.connectStart),Gz=Math.round(xi.responseStart-xi.requestStart),kz=Math.round(xi.responseEnd-xi.responseStart),tiA=[WM,Nz,Tz,Gz,kz];Jo.uploadEvent({log:"stat-schedule-net:".concat(Sa,"(").concat(Vn,"(").concat(NI,"->").concat(CG,")->").concat(tiA.join("->"),") ").concat(yo),userId:ke}),Ut=fi(bt({},Ut),{totalCost:Sa,local:Vn,dns:WM,tcp:Tz,tls:Nz,request:Gz,response:kz});break}}catch(Ui){nA.error("getScheduleDetailCost error",Ui)}return Ut}(Number(n),o,Ie);return Ux=XA,function(ie){if(typeof window<"u"&&typeof localStorage<"u")try{let ke=Date.now()+S4;localStorage.setItem(xx,JSON.stringify({result:ie,expireIn:ke})),Ox=ke}catch(ke){nA.error("saveScheduleToLocalStorage error",ke)}}(XA),{isCached:!1,result:XA,detailCost:Ft}}catch(iA){let cA=Aa(iA)?iA[0]:iA,TA=hr(cA.code)?cA.code:0,JA="schedule failed".concat(cA.message?": ".concat(cA.message):""),Ie=new Ct({code:Ge.SCHEDULE_FAILED,extraCode:TA,message:Wi({key:Mi.JOIN_ROOM_FAILED,data:{error:JA,code:TA}})});throw nA.error(JA,TA),Ie}}()})}typeof document<"u"&&document.head.insertAdjacentHTML("beforeend",Object.values(cu).map(A=>'')).join(`\r +`)),function(){if(typeof window<"u"&&typeof localStorage<"u")try{let A=localStorage.getItem(xx);if(A){let{result:e,expireIn:o}=JSON.parse(A);o>Date.now()?(Ux=e,Ox=o,gG=!1):localStorage.removeItem(xx)}}catch(A){nA.error("loadScheduleFromLocalStorage error",A)}}(),S.on("28",()=>Nu(!0)),S.on("63",()=>Nu(!0)),S.on("84",()=>Nu(!0)),S.on("201",A=>{A.state==="RECONNECTING"&&Nu(!0)}),S.on("202",A=>{A.state==="RECONNECTING"&&Nu(!0)});var ZQ={main:"",backup:""};function Wq(A){Aa(A)?(ZQ.main=A[0],ZQ.backup=A[1]):(ZQ.main=A,ZQ.backup=A)}var N4=(A=>(A.CONFIG="config",A.TRTC_AUTO_CONF="trtcAutoConf",A.AUDIO_AI_AUTH="audioAiAuth",A))(N4||{});function ep(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:fA.MAIN,n=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return"https://".concat(ZQ[o]||zq(A,o,n),"/api/v1/").concat(e)}function veA(A,e,o){let n=ep(A,e),a=ep(A,e,fA.BACKUP),I=new URLSearchParams(o).toString(),c=fetch("".concat(n,"?").concat(I)).then(d=>d.json()),u=fetch("".concat(a,"?").concat(I)).then(d=>d.json());return qf([c,u])}function zq(A){let e,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:fA.MAIN,n=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return e=rl(A)?n?o===fA.MAIN?cu.MAIN_OVERSEA_BACKUP:cu.BACKUP_OVERSEA:o===fA.MAIN?cu.MAIN_OVERSEA:cu.BACKUP_OVERSEA:o===fA.MAIN?cu.MAIN:cu.BACKUP,e}function NeA(A,e,o){return new Promise((n,a)=>{Cu({url:A,body:e,timeout:o.timeout,priority:"high"}).then(I=>{I.data.code===0?n(I.data.data):a({code:I.data.code,message:I.data.msg})}).catch(a)})}var T4=(A,e)=>Zf({retryFunction:NeA,settings:{retries:3,timeout:0},onError:e,onRetrying:A}),Zq=class{constructor(){G(this,"_log"),this._log=nA.createLogger({id:"fd"})}download(A,e){return DA(this,null,function*(){let{type:o="blob"}=e||{};A=HN(A);try{let n,a=ki();if(n=$n(fetch)?yield this.downloadWithFetch(A,o):yield this.downloadWithXHR(A,o),!n||!n.data)throw new Error("data is empty");let I=ki()-a;return this._log.info("downloaded: ".concat(A,", return type: ").concat(o,", cost: ").concat(I,"ms")),ct.addSuccessEvent({key:522700,cost:ki()-a}),n.data}catch(n){throw this._log.error("failed to download: ".concat(A,", error: ").concat(n)),ct.addFailedEvent({key:522700,error:n}),n}})}downloadWithFetch(A,e){return DA(this,null,function*(){this._log.info("download with fetch: ".concat(A,", return type: ").concat(e));try{let o,n=yield fetch(A);if(!n.ok){let a=new Error("network response was not ok: ".concat(n.status));throw a.status=n.status,a}return o=e==="arraybuffer"?yield n.arrayBuffer():yield n.blob(),{data:o}}catch(o){throw o}})}downloadWithXHR(A,e){return this._log.info("download with xhr: ".concat(A,", return type: ").concat(e)),new Promise((o,n)=>{let a=new XMLHttpRequest;a.open("GET",A,!0),a.responseType=e,a.onload=()=>{if(a.status===200||a.status===0&&a.response)o({data:a.response});else{let I=new Error("XHR failed, status: ".concat(a.status));I.status=a.status,n(I)}},a.onerror=n,a.send(null)})}loadWasm(A,e){return DA(this,null,function*(){this._log.info("loadWasm ".concat(A,", importObject: ").concat(JSON.stringify(e)));let o=ki(),n=null,a=null;if($n(WebAssembly.instantiateStreaming)&&!A.startsWith("data:application/octet-stream;base64,")&&!(I=>I.startsWith("file://"))(A)&&$n(fetch))try{let I=fetch(A);n=(yield WebAssembly.instantiateStreaming(I,e)).instance}catch(I){a=I}if(!n)try{let I=yield this.download(A,{type:"arraybuffer"});n=(yield WebAssembly.instantiate(I,e)).instance}catch(I){a=I}if(n){let I=ki()-o;return this._log.info("loadedWasm ".concat(A,", cost: ").concat(I,"ms")),ct.addSuccessEvent({key:522701,cost:I}),n}throw this._log.error("failed to loadWasm ".concat(A,", error: ").concat(a)),ct.addFailedEvent({key:522701,error:a}),a})}loadScript(A){this._log.info("loadScript ".concat(A));let e=ki();return new Promise((o,n)=>{let a=document.createElement("script");a.type="text/javascript",a.onload=()=>{this._log.info("loadedScript ".concat(A,", cost: ").concat(ki()-e,"ms")),ct.addSuccessEvent({key:522702,cost:ki()-e,split:1e3}),o(a)},a.onerror=I=>{this._log.error("failed to loadScript ".concat(A,", error: ").concat(I?.message||JSON.stringify(I))),ct.addFailedEvent({key:522702}),n(I)},a.crossOrigin="anonymous",a.src=A,document.head.append?document.head.append(a):document.getElementsByTagName("head")[0].appendChild(a)})}};vt([nB({settings:{timeout:0,retries:3},onError(A,e,o){var n;A?.status===404||(n=A?.message)!=null&&n.includes("404")?(this._log.warn("download 404, stop retry"),o(A)):e()},onRetrying(A){this._log.warn("download retrying: ".concat(A))}})],Zq.prototype,"download"),vt([nB({settings:{timeout:3e3,retries:3},onRetrying(A){this._log.warn("loadScript retrying: ".concat(A))}})],Zq.prototype,"loadScript");var Xq=new Zq;function G4(A){let[e,o]=A,n=o.byteLength,a=parseInt(String(n/255),10),I=n%255,c=[];c.push(0,0,0,1,6,e);for(let d=0;dk+_.dataView.byteLength,0),c=new ArrayBuffer(I+e.data.byteLength),u=new DataView(c),d=new DataView(e.data),R=0;for(let k=0;ka.isSEI);o?.(n.reverse())}catch{}return e}function U4(A){let{seiMessageList:e,isAudio:o,getNtpTime:n,isMain:a}=A;return new TransformStream({transform(I,c){let u=I;o?audioEncodePipeline.forEach(d=>{u=d({frame:u,ntp:n(),onDump:()=>{self.postMessage({type:"dump",isAudio:o,data:u.data,userId:""})}})}):videoEncodePipeline.forEach(d=>{u=d({frame:u,seiMessageList:e,onDump:()=>{self.postMessage({type:"dump",isAudio:o,data:u.data,userId:"",streamType:a?"main":"auxiliary"})}})}),c.enqueue(u)}})}function O4(A){let{userId:e,streamType:o,isAudio:n}=A;return new TransformStream({transform(a,I){let c=a;n?(audioDecodePipeline.forEach(u=>{c=u({frame:c,onAudioFrameNTPTime:d=>{self.postMessage({type:"audio-ntp",data:d,userId:e,streamType:o})},onDump:()=>{self.postMessage({type:"dump",isAudio:n,data:c.data,userId:e})}})}),I.enqueue(c)):videoDecodePipeline.forEach(u=>{c=u({frame:c,onSEI:d=>{d.forEach(R=>{self.postMessage({type:"sei",seiPayloadType:R.seiPayloadType,data:R.seiPayload.buffer,userId:e,streamType:o})})},onDump:()=>{self.postMessage({type:"dump",isAudio:n,data:c.data,userId:e,streamType:o})}})}),I.enqueue(c)}})}function x4(A){let e=[vx],o=[b4,k4,n4,_4,G4,U4,O4,rM,zf,Sx],n="const videoEncodePipeline=[".concat(A.videoEncodePipeline.toString(),`]; const videoDecodePipeline=[`).concat(A.videoDecodePipeline.toString(),`]; const audioEncodePipeline = [`).concat(A.audioEncodePipeline.toString(),`]; const audioDecodePipeline = [`).concat(A.audioDecodePipeline.toString(),"];"),a="(()=>{".concat(e.map(d=>"const ".concat(d.name,"=(()=>").concat(d.toString(),")()")).join(` `),` `).concat(o.map(d=>d.toString()).join(` -`),";(").concat(()=>{let d=[],R=[],k=[],_=0;self.onmessage=Z=>{switch(Z.data.type){case"sei":Z.data.isMain?(d.push(Z.data.data),Z.data.small&&k.push(Z.data.data)):R.push(Z.data.data);break;case"ntp-offset":_=Z.data.data}},self.onrtctransform=Z=>{let{options:iA}=Z.transformer,cA=iA.isReceiver?G4({userId:iA.userId,streamType:iA.streamType,isAudio:iA.isAudio}):T4({getNtpTime:()=>Date.now()+_,isAudio:iA.isAudio,isMain:iA.isMain,seiMessageList:iA.isMain?iA.small?k:d:R});Z.transformer.readable.pipeThrough(cA).pipeTo(Z.transformer.writable)}},")();").concat(n,"})()"),I=new Blob([a],{type:"text/javascript"}),c=URL.createObjectURL(I),u=new Worker(c);return URL.revokeObjectURL(c),u}var _4,Kq=class{constructor(A){G(this,"audioPlayer"),G(this,"videoPlayer"),G(this,"log"),this.audioPlayer=A.audioPlayer,this.videoPlayer=A.videoPlayer,this.log=A.log.createChild({id:"pip"}),this.videoPlayer.on(mi.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.on(mi.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.on(mi.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(mi.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(mi.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.on(mi.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.on(mi.VOLUME_CHANGE,this.handleVolumeChange,this)}handleUserResumeInPIPOrFullScreen(){this.audioPlayer.isPaused&&(this.log.warn("resume audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doResume()),ra&&Gh&&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"),ra&&Gh?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(mi.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.off(mi.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.off(mi.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(mi.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(mi.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.off(mi.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.off(mi.VOLUME_CHANGE,this.handleVolumeChange,this)}},b4=!1;function deA(A){var e=this;let{TRTC:o,room:n,errorModule:a,assetsPath:I}=A;return{TRTC:o,LocalMixVideoTrack:Fq,LocalVideoTrack:Ru,LocalScreenTrack:Nm,room:n,assetsPath:I,fileDownloader:Vq,innerEmitter:S,INNER_EVENT:K,constants:WU,environment:GO,utils:e4,eventLogger:Jo,log:this.room.getLogger(),loggerManager:nA,errorModule:a,kvStatManager:ct,rtcDectection:kA,trtc:this,rx:NW,enums:oe,schedule:p4,getDevices:Ix,initVisionTaskRegistry:function(c,u){let d=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"/mediapipe/vision.js";return DA(e,null,function*(){!window.VisionTaskRegistry&&!b4&&(b4=!0,_4=Vq.loadScript("".concat(c,"/").concat(d).replace(/([^:]\/)\/+/g,"$1"))),yield _4,yield(yield window.VisionTaskRegistry.getInstance(c)).preloadModels(u)})},audioContext:tI(),deviceDetector:vs,AudioPlayer:Dq,RemoteAudioPlayer:yW,VideoPlayer:wi,showAutoPlayDialog:nC,Timer:nn,clearStarted:(c,u)=>{let d=c.getAlias(),R=oG.instances.get(this);if(R)if(u){let k=R.get(d+u);if(!k)return;k.started=!1}else R.forEach((k,_)=>{_.startsWith(d)&&(k.started=!1)})},startGetPCM:Yq,createAudioNode:ax,getNetworkTimeOffset:KU,validateSourceNode:()=>{var c;if(Yr&&((c=this.room.audioManager._localAudioPipline)==null||!c.source.node))throw new vi({code:Si.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:k4,AVPlayerStateSyncManager:Kq,PlayerEvent:mi}}var PM=new WeakMap,L4="5.15.3-beta.12";function vI(){for(var A=arguments.length,e=new Array(A),o=0;ofunction(){for(var I=arguments.length,c=new Array(I),u=0;ufunction(){for(var I=arguments.length,c=new Array(I),u=0;umh(k)?Yf(k):Sr(k)?k:ya(k))},value:o}})}else if(!Ee(e.type)&&ya(o)!==e.type)throw new vi(c(5002));if(e.allowEmpty===!1){let R=hr(o)&&(o===0||Number.isNaN(o)),k=Sr(o)&&o.trim()==="";if(R||k)throw new vi(c(5003))}if(e.notLessThanZero&&hr(o)&&o<0)throw new vi(c(5006));if(!Ee(e.min)&&hr(o)&&oe.max)throw new vi(c(5008));if(Sr(e.instanceOf)){if(!o||o._name!==e.instanceOf)throw new vi(c(5004))}else if($n(e.instanceOf)&&!(o instanceof e.instanceOf))throw new vi(c(5004));if(Array.isArray(e.values)&&!e.values.includes(o))throw new vi(c(5005));let{properties:u}=e;Cc(u)&&Xc(o)&&Object.keys(u).forEach(R=>{_x.call(this,{rule:u[R],value:o&&o[R],key:"".concat(R),fnName:a,className:I})});let{arrayItem:d}=e;Cc(d)&&Aa(o)&&o.forEach((R,k)=>{_x.call(this,{rule:d,value:R,key:"".concat(n,"[").concat(k,"]"),fnName:a,className:I})}),$n(e.validate)&&e.validate.call(this,o,n,a,I,this)}var heA=0;function Hn(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{getRemoteId:e=()=>"",replaceArg:o,getKVReportKey:n,ignoreLog:a,ignoreErrorLog:I}=A;return Dn((c,u)=>function(){for(var d=arguments.length,R=new Array(d),k=0;k0?TA.info("".concat(u,"() ").concat(JA," ").concat(JSON.stringify(R,(Ft,ie)=>cA(Ft,ie,["userSig","privateMapKey"])))):TA.info("".concat(u,"() ").concat(JA));let Ie=n?n(...R):KO[u],XA=I?.(...R)||!1;try{let Ft=c.apply(this,R),ie=ki();if(fh(Ft)){let ke="".concat(u.includes("Plugin")?"".concat(((Z=(_=R[0]).getName)==null?void 0:Z.call(_))||""," "):" ");return Ft.then(Nt=>(TA.info("".concat(u,"() success ").concat(JA," ").concat(ke).concat(e.call(this,...R))),ct.addSuccessEvent({key:Ie,cost:ki()-ie}),Nt)).catch(Nt=>{var Ut;let Ui=(Nt=vi.convertFrom.call(this,Nt,u,R.length===1?R[0]:R)).extraCode||Nt.code,Oi=(Ut=Nt.message)!=null&&Ut.includes(Ui)?"":" code:".concat(Ui),or=Nt?.code===Si.OPERATION_ABORT;throw XA||TA[or?"warn":"error"]("".concat(u,"() failed ").concat(JA," ").concat(ke).concat(e.call(this,...R)," ").concat(Nt).concat(Oi," params: ").concat(JSON.stringify(R,cA))),ct.addFailedEvent({key:Ie,error:Nt}),Nt})}return ct.addSuccessEvent({key:Ie}),Ft}catch(Ft){let ie=(Ft=vi.convertFrom.call(this,Ft,u)).extraCode||Ft.code,ke=(iA=Ft.message)!=null&&iA.includes(ie)?"":" code:".concat(ie),Nt=Ft?.code===Si.OPERATION_ABORT;throw XA||TA[Nt?"warn":"error"]("".concat(u,"() failed ").concat(JA," ").concat(Ft).concat(ke," params: ").concat(JSON.stringify(R,cA))),ct.addFailedEvent({key:Ie,error:Ft}),Ft}})}var Wq,zq=A=>Dn((e,o)=>function(n,a){return DA(this,null,function*(){let I=this._plugins.get(n);if(!I)throw this._log.error("plugin ".concat(String(n)," is not found")),new vi({code:Si.OPERATION_ABORT,message:"plugin ".concat(String(n)," is not found"),fnName:o});if($n(I.constructor.isSupported)&&!I.constructor.isSupported())throw this._log.error("plugin ".concat(String(n)," is not supported")),new vi({code:Si.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(n)," is not supported"),extraCode:5210,fnName:o});return jq.call(this,I.getValidateRule(A),[a],o,"TRTC"),e.call(this,I,a)})}),Zq=0,bx=class DG{constructor(e){this.core=e,G(this,"log"),G(this,"customAudioReferenceMap",new Map),G(this,"audioRefId",0),G(this,"audioContext",tI()),G(this,"localAudioWorkletNode"),G(this,"screenAudioWorkletNode"),G(this,"mixNode"),G(this,"silentNode"),Zq+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(Zq)}),this.log.info("created id=".concat(this.getAlias()).concat(Zq)),this.installEvent()}static getStartValidateRule(e){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,n,a,I){if(!e.room.audioManager.hasAudioTrack&&!e.room.audioManager.hasScreenAudioTrack)throw new vi({code:Si.INVALID_OPERATION,extraCode:5106,fnName:a})}}}preload(e){return Wq||(Wq=this.doPreload(e)),Wq}doPreload(e){return DA(this,null,function*(){let o=yield this.core.fileDownloader.download(e,{type:"blob"}),n=URL.createObjectURL(o);try{yield Fa(this.audioContext,n)}catch(a){this.log.error("preload audioProcessor failed. ".concat(a))}finally{URL.revokeObjectURL(n)}})}getName(){return DG.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(e){switch(e){case"start":return DG.getStartValidateRule(this.core);case"update":return DG.updateValidateRule;case"stop":return DG.stopValidateRule}}start(e){return DA(this,null,function*(){var o,n,a,I;let{room:c}=this.core,{sdkAppId:u,userId:d,userSig:R,assetsPath:k=this.core.assetsPath,audioReference:_,processLevel:Z,enableDump:iA,isLocalAudioNeedAudioProcess:cA=!0,isScreenAudioNeedAudioProcess:TA=!1}=e;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=cA,this.core.room.audioManager.isScreenAudioNeedAudioProcess=TA,!k)throw new vi({code:Si.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(k,"/audioProcessor-wasm.js")),cA&&!this.localAudioWorkletNode){let{sign:JA,status:Ie,timestamp:XA}=yield this.getAuthData(u,d,R);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",u,d,XA,JA,Ie,c)}if(TA&&!this.screenAudioWorkletNode){let{sign:JA,status:Ie,timestamp:XA}=yield this.getAuthData(u,d,R);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",u,d,XA,JA,Ie,c)}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"}),(n=this.screenAudioWorkletNode)==null||n.port.postMessage({type:"enable"}),c.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),Ee(_)||_.forEach(JA=>{this.customAudioReferenceMap.set(JA,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:JA,refId:"o-".concat(this.audioRefId++)})}),Ee(Z)||(a=this.localAudioWorkletNode)==null||a.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:Z}}),Ee(iA)||(I=this.localAudioWorkletNode)==null||I.port.postMessage({type:"dump",data:{enable:iA}})})}update(e){return DA(this,null,function*(){var o,n,a;let{audioReference:I,enableDump:c,processLevel:u}=e;Ee(I)||(this.customAudioReferenceMap.forEach((d,R)=>{this.customAudioReferenceMap.delete(R),this.core.room.audioManager.updateAudioReference({type:"remove",refId:d})}),I.forEach(d=>{this.customAudioReferenceMap.set(d,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:d,refId:"o-".concat(this.audioRefId++)})})),Ee(u)||(o=this.localAudioWorkletNode)==null||o.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:u}}),Ee(c)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:c}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:c}}))})}stop(){return DA(this,null,function*(){var e,o;let{room:n}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(o=this.screenAudioWorkletNode)==null||o.port.postMessage({type:"disable"}),yield n.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(e,o,n){return DA(this,null,function*(){let a=String(Date.now()).slice(0,-3),{auth:I,sign:c,status:u,message:d}=yield function(R){return DA(this,arguments,function(k){let{sdkAppId:_,userId:Z,userSig:iA,timestamp:cA}=k;return function*(){let TA="".concat(function(Ui){let Oi=arguments.length>1&&arguments[1]!==void 0?arguments[1]:fA.MAIN;return"https://".concat(jQ[Oi]||Jq(Ui,Oi),"/api/v1/audioAiAuth")}(_),"?sdkAppId=").concat(_,"&userId=").concat(Z,"&userSig=").concat(iA,"×tamp=").concat(cA),JA=yield fetch(TA),{data:{errCode:Ie,errMsg:XA,sign:Ft,status:ie}}=yield JA.json();if(ie==="1")return{auth:!0,sign:Ft,status:ie,message:XA};let ke=ol(_)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",Nt="Init RTCAudioProcessor failed.",Ut="";switch(Ie){case 1:Ut="Please check your params.";break;case 2:Ut="You need to buy packages. Refer to: ".concat(ke);break;case 3:Ut="Server is invalid. Please contact our engineer. ";break;case 4:Ut="Your packages is not active. Refer to: ".concat(ke);break;case 5:Ut="Your packages is expired. Refer to: ".concat(ke);break;case 6:Ut="Your version is not supported."}return{auth:!1,status:ie,message:XA?"".concat(Nt," Reason: ").concat(XA,". ").concat(Ut):"".concat(Nt,", ").concat(Ut)}}()})}({sdkAppId:e,userSig:n,userId:o,timestamp:a});if(!I)throw this.log.info("audioProcessor: ".concat(o," auth result: ").concat(I,". Message: ").concat(d)),new vi({code:Si.INVALID_PARAMETER,message:d});return{sign:c,status:u,timestamp:a}})}initWorkletNode(e,o,n,a,I,c,u,d){e.port.postMessage({type:"init",data:{sdkAppId:String(n),userId:a,timestamp:I,sign:c,status:u}}),e.port.onmessage=R=>{var k;let{data:_}=R;switch(_.type){case"cost":let Z=_?.value>10?"info":"debug";return void this.log[Z]("".concat(o==="localAudio"?"":"[".concat(o,"] "),"avg cost: ").concat(_.value," max: ").concat(_?.max,"(").concat(lN(new Date(_?.maxCostTimestamp)),") hist: ").concat((k=_?.hist)==null?void 0:k.join(" ")));case"log":return void this.log[_.logLevel]("".concat(o==="localAudio"?"":"[".concat(o,"] ")).concat(_.value));case"dump":return void S.emit("265",{room:d,data:_.value,type:o==="localAudio"?"dump":"dump-screen-audio"});case"detectEcho":return void this.log.warn("".concat(o==="localAudio"?"":"[".concat(o,"] "),"detect echo: ").concat(QM()?Qu():bQ()))}}}handleLocalAudioStarted(e){return DA(this,null,function*(){var o;if(this.hitTest(e.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(n){this.log.warn("audio processor auto start failed, error: ".concat(n))}})}handleLocalAudioStopped(e){return DA(this,null,function*(){var o;!this.hitTest(e.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(e){return e===this.core.room}};G(bx,"updateValidateRule",{type:"object"}),G(bx,"stopValidateRule",{type:"object"}),G(bx,"Name","AudioProcessor");var peA=bx,Xq=0,feA=class{constructor(A,e){G(this,"audioObjectURL"),G(this,"player"),G(this,"publisher"),G(this,"mixInput"),this.mixInput=new QW(e),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&&(Ee(A.volume)||(this.volume=A.volume),Ee(A.loop)||(this.loop=A.loop),Ee(A.playbackRate)||(this.playbackRate=A.playbackRate))}updateListener(A){if(this.player){if(A.onDurationChange){let{onDurationChange:e}=A;this.player.ondurationchange=o=>{e(o.target.duration)}}if(A.onTimeUpdate){let e=A.onTimeUpdate,{player:o}=this;o.ontimeupdate=()=>{e(o.currentTime,o.duration)}}A.onEnded&&(this.player.onended=A.onEnded)}}reload(A){return DA(this,null,function*(){if(A.url){let e=yield Vq.download(A.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),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,e;return Promise.all([(A=this.player)==null?void 0:A.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var A,e;(A=this.player)==null||A.pause(),(e=this.publisher)==null||e.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 JM(A,e){if(e&&typeof e!="function")throw new vi({code:Si.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(A," should be a function.")})}var nG=class yG{constructor(e){this.core=e,G(this,"log"),G(this,"mixedMusicMap",new Map),G(this,"cacheMusicMap",new Map),Xq+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(Xq)}),this.log.info("created id=".concat(this.getAlias()).concat(Xq))}getName(){return yG.Name}getAlias(){return"ax"}getGroup(e){return e?.id}getValidateRule(e){switch(e){case"start":return yG.startValidateRule;case"update":return yG.updateValidateRule;case"stop":return yG.stopValidateRule}}start(e){return DA(this,null,function*(){let{room:o}=this.core;this.core.validateSourceNode(),this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track));let{id:n,url:a}=e;if(this.mixedMusicMap.has(n))return;let I=this.cacheMusicMap.get(n);I?e.url?I.reset():(I.mixInput.replaceSource(e.track),I.mixInput.connect()):(I=new feA(e,o.audioManager),this.cacheMusicMap.set(n,I)),I.updateListener(e),I.updateSettings(e);try{yield I.play()}catch(c){yield this.handleAutoPlayFailed(I,e,c)}this.mixedMusicMap.set(n,I),I.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:I.mixInput.source.node,refId:"ax-".concat(n)}),this.log.info("start mix audio track ".concat(n," success.")),ct.addEnum({key:502700,value:3}),this.kvUpload(e)})}handleAutoPlayFailed(e,o,n){return DA(this,null,function*(){if(n.name==="NotSupportedError")this.log.error("play failed, try to reload source. error: ".concat(n)),yield e.reload(o),yield e.play();else{if(n.name!=="NotAllowedError")throw n;if(this.core.room.enableAutoPlayDialog){let a=()=>{var I;(I=e.play())==null||I.finally(()=>{S.off("154",a,this)})};S.on("154",a,this),nC()}else this.core.trtc.emit(Xt.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>DA(this,null,function*(){return e.play()})})}})}update(e){return DA(this,null,function*(){let{id:o,operation:n,seekFrom:a,playbackRate:I}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let c=this.mixedMusicMap.get(o);c?(c.updateSettings(e),c.updateListener(e),Ee(n)||c.setOperation(n),Ee(a)||c.seek(a),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(o," not found."))})}stop(e){return DA(this,arguments,function(o){var n=this;let{id:a}=o;return function*(){if(n.mixedMusicMap.has(a)){n.log.info("remove music source, music id: ".concat(a));let I=n.mixedMusicMap.get(a);I!=null&&I.mixInput.source.node&&n.core.room.audioManager.updateAudioReference({type:"remove",audioReference:I.mixInput.source.node,refId:"ax-".concat(a)}),I?.stop(),n.mixedMusicMap.delete(a)}a==="*"&&n.destroyAllMusic()}()})}kvUpload(e){let{track:o,loop:n,volume:a,playbackRate:I,operation:c,seekFrom:u,onTimeUpdate:d,onDurationChange:R,onEnded:k}=e;o&&ct.addCount({key:502009}),n&&ct.addCount({key:502001}),a&&ct.addCount({key:502002}),I&&ct.addCount({key:502003}),c&&ct.addCount({key:502004}),u&&ct.addCount({key:502005}),typeof d!="function"&&ct.addCount({key:502007}),typeof k!="function"&&ct.addCount({key:502008}),typeof R!="function"&&ct.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((e,o)=>{e!=null&&e.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:e.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()}};G(nG,"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,e,o){if(A.url&&A.url!=="*"){let n=A.url.split("?")[0],a=["mp3","ogg","wav","flac"],I=n.split(".").pop(),c=a.indexOf(I)>=0,u=n.startsWith("blob"),d=n.startsWith("data");if(!(c||u||d))throw new vi({code:Si.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:o})}if(!A.url&&!A.track)throw new vi({code:Si.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:o});JM("onTimeUpdate",A.onTimeUpdate),JM("onEnded",A.onEnded),JM("onDurationChange",A.onDurationChange)}}),G(nG,"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,e,o){JM("onTimeUpdate",A.onTimeUpdate),JM("onEnded",A.onEnded),JM("onDurationChange",A.onDurationChange)}}),G(nG,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),G(nG,"Name","AudioMixer");var $q,meA=nG,AK=0,Lx=class RG{constructor(e){this.core=e,G(this,"log"),G(this,"audioContext",tI()),G(this,"workletNode"),G(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5}),AK+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(AK)}),this.log.info("created id=".concat(this.getAlias()).concat(AK))}static startValidateRule(e){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,n,a,I){if(!e.room.audioManager.hasAudioTrack)throw new vi({code:Si.INVALID_OPERATION,extraCode:5106,fnName:a})}}}preload(e){return $q||($q=this.doPreload(e)),$q}doPreload(e){return DA(this,null,function*(){let o=yield this.core.fileDownloader.download(e,{type:"blob"}),n=URL.createObjectURL(o);try{yield Fa(this.audioContext,n)}catch(a){throw this.log.error("load worklet failed",a),a}finally{URL.revokeObjectURL(n)}})}getName(){return RG.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(e){switch(e){case"start":return RG.startValidateRule(this.core);case"update":return RG.updateValidateRule;case"stop":return RG.stopValidateRule}}start(e){return DA(this,null,function*(){let{room:o,schedule:n}=this.core,{assetsPath:a=this.core.assetsPath}=e;if(!a)throw new vi({code:Si.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(a,"/denoiser-wasm").concat(dm()?"":"-nosimd",".js")),!this.workletNode){let I=String(Date.now()).slice(0,-3),{auth:c,sign:u,status:d,message:R}=yield function(k,_){return DA(this,arguments,function(Z,iA){let{sdkAppId:cA,userId:TA,userSig:JA,timestamp:Ie}=iA;return function*(){try{let{data:{errCode:XA,errMsg:Ft,sign:ie,status:ke}}=yield Z.getAbilityConfig(cA,Z.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:cA,userId:TA,userSig:JA,timestamp:Ie});if(ke==="1")return{auth:!0,sign:ie,status:ke,message:Ft};let Nt=ol(cA)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",Ut="Init RTCAIDenoiser failed.",Ui="";switch(XA){case 1:Ui="Please check your params.";break;case 2:Ui="You need to buy packages. Refer to: ".concat(Nt);break;case 3:Ui="Server is invalid. Please contact our engineer. ";break;case 4:Ui="Your packages is not active. Refer to: ".concat(Nt);break;case 5:Ui="Your packages is expired. Refer to: ".concat(Nt);break;case 6:Ui="Your version is not supported."}return{auth:!1,status:ke,message:Ft?"".concat(Ut," Reason: ").concat(Ft,". ").concat(Ui):"".concat(Ut,", ").concat(Ui)}}catch(XA){return{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(XA)}}}()})}(n,fi(bt({},e),{timestamp:I}));if(!c)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(c,". Message: ").concat(R)),new vi({code:Si.INVALID_PARAMETER,message:R});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(e.sdkAppId),userId:e.userId,timestamp:I,sign:u,status:d}}),this.workletNode.port.onmessage=k=>{var _;let{data:Z}=k;if(Z.type==="cost"){let iA=Z?.max>20?"warn":Z?.max>10?"info":"debug";this.log[iA]("avg cost: ".concat(Z.value," max: ").concat(Z?.max,"(").concat(lN(new Date(Z?.maxCostTimestamp)),") hist: ").concat((_=Z?.hist)==null?void 0:_.join(" ")))}else Z.type==="log"&&this.log[Z.logLevel]("".concat(Z.value))}}this.updateConfig(e),this.workletNode.port.postMessage({type:"enable"}),o.audioManager.addDenoiser(this.workletNode),o.sendAbilityStatus({ai_denoise:1})})}update(e){return DA(this,null,function*(){this.updateConfig(e)})}stop(){return DA(this,null,function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)})}updateConfig(e){if(!this.workletNode)return;let o=!1;Ee(e.mode)||(e.mode===0?this.config.enableFarFieldReduce=!1:e.mode===1&&(this.config.enableFarFieldReduce=!0),o=!0),Ee(e.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=e.farFieldReduceThreshold,o=!0),o&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};G(Lx,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),G(Lx,"stopValidateRule",{type:"object"}),G(Lx,"Name","AIDenoiser");var DeA=Lx,yeA=es(hg(),1),ReA=class extends yeA.EventEmitter{constructor(){super(),G(this,"observer"),G(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 DA(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!ra&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(A){Jo.uploadEvent({log:"stat-pressure-detector-start-failed",error:A})}})}onPressureChange(A){let e=this.stateNum,o=A[A.length-1];this.state=o.state,(this.stateNum>3||e>3)&&nA.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(e){Jo.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:e})}}},U4=new ReA,eK=0,tK=class XZ{constructor(e){this.core=e,G(this,"log"),G(this,"_seiMessageList",[]),G(this,"_smallSeiMessageList",[]),G(this,"_subStreamSeiMessageList",[]),eK++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(eK)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(eK)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:o,mediaType:n}=e;try{return v4({frame:o,seiMessageList:n===8?this._smallSeiMessageList:n===2?this._subStreamSeiMessageList:this._seiMessageList})}catch(a){this.log.warn(a)}return o}decode(e){let{frame:o,track:n}=e;return N4({frame:o,onSEI:a=>{a.forEach(I=>{n!=null&&n.userId?this.core.trtc.emit(Xt.SEI_MESSAGE,{seiPayloadType:I.seiPayloadType,data:I.seiPayload.buffer,userId:n.userId,streamType:n.mediaType===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:I})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(e){switch(e){case"start":case"update":case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:xQ?this.encode:v4,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:xQ?this.decode:N4,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update(e){let{buffer:o,options:n}=e;var a;let I=[n.seiPayloadType,o],c=!!n.small;n.toSubStream?this._subStreamSeiMessageList.push(I):(this._seiMessageList.push(I),c&&this._smallSeiMessageList.push(I)),(a=this.core.room.scriptTransformWorker)==null||a.postMessage({type:"sei",data:I,isMain:!n.toSubStream,small:c})}getName(){return XZ.Name}getAlias(){return"sei"}getGroup(){return"sei"}};G(tK,"autoStart",!0),G(tK,"Name","SEI");var Fx,MeA=tK,weA=0,iK=class $Z{constructor(e){this.core=e,G(this,"_core"),G(this,"log"),G(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++weA)}),this.log.info("created")}getName(){return $Z.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(e){switch(e){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return DA(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog())})}update(e){return DA(this,arguments,function(o){var n=this;let{visible:a}=o;return function*(){a?yield n.openDebugDiaLog():n.closeDebugDiaLog()}()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return DA(this,null,function*(){var e;if(!this.dialog)try{if(Fx)yield Fx;else{let o=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_DEBUG_DIALOG_PATH"))||"https://unpkg.com/".concat("trtc-sdk-v5","@").concat(il,"/assets/debug-dialog.js");Fx=this._core.fileDownloader.loadScript(o),yield Fx}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)}};G(iK,"Name","Debug"),G(iK,"autoStart",!0);var SeA=iK,O4=A=>{switch(A){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},x4=class{constructor(A,e,o){G(this,"trackDoneOB"),G(this,"startOB"),G(this,"stopOB"),G(this,"inputFrameCount",0),G(this,"decodedFrameCount",0),G(this,"type","auto"),G(this,"config"),G(this,"decoder"),G(this,"_decodeSink");let{kvStatManager:n,trtc:a}=A;this.config=o.config,this.trackDoneOB=Ln(e,Uo.INIT),this.stopOB=yu(),this.startOB=yu(),o.type==="auto"?this.type="webCodecs":this.type=o.type;let I=yu();Jn(this.startOB,wq(0),Qx(c=>{let u=this.pipe(e);return I.next("STARTING"),e.log.info("decoder type: ".concat(this.type)),Jn(u,Qc(this.stopOB),Ks(()=>{},d=>{e.log.error(d),n.addFailedEvent({key:O4(this.type),error:d}),c>4?this.startOB.error(d):this.startOB.next(c+1)})),Jn(u,LM(1),XW(Nq))}),Qc(this.stopOB),Ks(()=>{e.player.setOutput(),I.next("STARTED")},c=>{I.next("FAILED")},()=>{n.addSuccessEvent({key:O4(this.type)}),n.addSuccessEvent({key:504702})}))}mock(A){this._decodeSink?this._decodeSink.error(A):this.startOB.next(0)}close(A){this.stopOB.next(A)}pipe(A){return qT()(e=>DA(this,null,function*(){this._decodeSink=e,e.defer(()=>{var n;(n=this.decoder)==null||n.close()});let{type:o}=this;try{o==="webCodecs"&&(this.decoder=new AudioDecoder({error:n=>{A.log.error(n),e.error(4)},output:n=>{this.decodedFrameCount++,e.next(n),A.player.write(n)}})),this.decoder.configure(this.config)}catch(n){A.log.error(n),e.error(o==="webCodecs"?2:6)}}))}decodeFrame(A){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:A.data,timestamp:A.timestamp,type:"key"}))}},veA={type:"object"},Y4=class yj{constructor(e){this.core=e,G(this,"log"),G(this,"contextMap",new Map),G(this,"decodeProcessorMap",new WeakMap),this.log=e.log.createChild({id:"".concat(this.getAlias())})}getAlias(){return yj.Name}getGroup(e){return e.track.userId+e.track.streamType}getName(){return yj.Name}getValidateRule(e){return veA}start(e){let{track:o}=e;this.decodeProcessorMap.set(o,this.decode(e)),this.core.room.audioManager.addDecodeProcessor({processor:n=>{let{frame:a,track:I}=n;return this.decodeProcessorMap.has(I)?this.decodeProcessorMap.get(I)({frame:a,track:I}):a},type:3})}decode(e){return o=>{let{frame:n,track:a}=o;if(a!==e.track)return n;if(this.contextMap.has(a))return this.contextMap.get(a).decodeFrame(n);let I=new x4(this.core,a,e);return Jn(I.trackDoneOB,LM(1),Ks(()=>{this.core.clearStarted(this,this.getGroup(e)),this.stop({track:a})})),this.contextMap.set(a,I),I.decodeFrame(n)}}stop(e){let{track:o}=e,n=this.contextMap.get(o);n&&(n.close("stop"),this.contextMap.delete(o),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(e){let o=this.contextMap.get(e.track);if(o){if(e.type==="mock")return void o.mock(10);o.close("update"),this.contextMap.set(e.track,new x4(this.core,e.track,e))}}};G(Y4,"Name","TRTCAudioDecoder");var P4=Y4,NeA={rttPoorLimit:150,lossPoorLimit:20,rttGoodLimit:100,lossGoodLimit:10,fpsPoorLimit:5,cooldownTime:1e4,poorCount:3,goodCount:5,maxUpgradeFailCount:3},TeA=class{constructor(){G(this,"log"),G(this,"autoMode",{enabled:!1,instance:null,config:NeA,sortedStreamList:[],currentQualityIndex:0}),G(this,"switchControl",{isInternal:!1,isSwitching:!1,lastSwitchTime:0,boundOnStatistics:null}),G(this,"networkMetrics",{frameRate:0,rtt:0,loss:0}),G(this,"counters",{rttUnder:0,lossUnder:0,downgradeCondition:0,upgradeFail:0}),G(this,"onStatistics",A=>{var e,o;if(!this.autoMode.instance)return;let{config:n}=this.autoMode;if(this.networkMetrics.rtt=A.rtt,this.networkMetrics.loss=A.downLoss,this.counters.rttUnder=A.rttk.userId===I);if((o=u?.video)==null||!o.length)return;let d=c==="sub"?"sub":"big",R=u.video.find(k=>k.videoType===d);R?(this.networkMetrics.frameRate=R.frameRate||0,this.checkAndSwitchQuality()):this.log.warn("onStatistics: videoStat not found for userId=".concat(I,", streamType=").concat(c))}),this.log=nA.createLogger({id:"pqs"})}getCurrentPlayingStream(A){var e,o;let n=A,a=n._playbackQualityList;if(!a||a.length===0)return this.log.warn("getCurrentPlayingStream: streamList is empty"),null;for(let I of a){let c=A.room.remotePublishedUserMap.get(I.userId);if(!c)continue;let u=(e=I.streamType)!=null?e:"main";if((u==="sub"?c.remoteAuxiliaryTrack:c.remoteVideoTrack).isPlayCalled){let d=(o=n._remoteVideoConfigMap.get("".concat(I.userId,"_").concat(u)))==null?void 0:o.config;if(d)return{userId:I.userId,streamType:u,config:d}}}return null}switchPlaybackQuality(A){return DA(this,null,function*(){var e;let{trtcInstance:o,streamList:n,quality:a}=A;this.log.info("switchPlaybackQuality quality: ".concat(a,", streamList: ").concat(JSON.stringify(n)));let I=o;if(n&&n.length>0&&(I._playbackQualityList=n.map(cA=>{var TA;return fi(bt({},cA),{streamType:(TA=cA.streamType)!=null?TA:"main"})})),a==="auto")return void(yield this.startAutoMode(o));if(this.autoMode.enabled&&a&&!this.switchControl.isInternal&&this.stopAutoMode(),!a)return;if(!I._playbackQualityList||I._playbackQualityList.length<=0)return void this.log.warn("switchPlaybackQuality: streamList is empty, please call with streamList first");let c=I._playbackQualityList.find(cA=>cA.name===a);if(!c)return void this.log.warn('switchPlaybackQuality: quality "'.concat(a,'" not found in streamList'));let u=this.getCurrentPlayingStream(o);if(this.log.info("currentPlaying userId: ".concat(u?.userId,", streamType: ").concat(u?.streamType)),!u)return;let d=(e=c.streamType)!=null?e:"main";if(u.userId===c.userId&&u.streamType===d)return void this.log.info("switchPlaybackQuality: already playing target stream");let R=bt({},u.config);R.streamType==="main"&&d==="main"&&(yield o.muteRemoteAudio(R.userId,!0));let k,_=new Promise(cA=>{k=cA}),Z=cA=>{cA.userId===c.userId&&cA.streamType===d&&cA.state==="PLAYING"&&cA.reason==="playing"&&k("success")};o.on(Xt.VIDEO_PLAY_STATE_CHANGED,Z);let iA=new Promise(cA=>setTimeout(()=>cA("timeout"),1e4));try{if(yield o.startRemoteVideo(fi(bt({},u.config),{userId:c.userId,streamType:d,option:fi(bt({},u.config.option),{isLiveStream:!0})})),(yield Promise.race([_,iA]))==="timeout"){this.log.error("switchPlaybackQuality: VIDEO_PLAY_STATE_CHANGED timeout, rollback");try{yield o.stopRemoteVideo({userId:c.userId,streamType:d})}catch(TA){this.log.warn("switchPlaybackQuality: rollback stopRemoteVideo failed",TA)}throw R.streamType==="main"&&d==="main"&&(yield o.muteRemoteAudio(R.userId,!1).catch(TA=>{this.log.warn("switchPlaybackQuality: rollback muteRemoteAudio failed",TA)})),new Ct({code:Ge.SUBSCRIPTION_TIMEOUT,message:Wi({key:Mi.SWITCH_PLAYBACK_QUALITY_TIMEOUT,data:{userId:c.userId}})})}let cA=o.stopRemoteVideo(R);R.streamType==="main"&&d==="main"?yield Promise.all([o.muteRemoteAudio(c.userId,!1).catch(TA=>{this.log.warn("muteRemoteAudio(new, false) failed",TA)}),cA]):yield cA,I._currentLiveUserId=c.userId,I._currentLiveStreamType=d}finally{o.off(Xt.VIDEO_PLAY_STATE_CHANGED,Z)}})}startAutoMode(A){return DA(this,null,function*(){if(this.autoMode.enabled)return void this.log.info("auto mode already enabled");let e=A;if(!e._playbackQualityList||e._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=e._playbackQualityList||[];this.autoMode.sortedStreamList=[...o].sort((a,I)=>I.bitrate-a.bitrate),this.log.info("auto mode streams: ".concat(this.autoMode.sortedStreamList.map(a=>"".concat(a.name,"(").concat(a.bitrate,"kbps)")).join(" > ")));let n=this.getCurrentPlayingStream(A);if(n){let{userId:a,streamType:I}=n,c=this.autoMode.sortedStreamList.findIndex(u=>{var d;return u.userId===a&&((d=u.streamType)!=null?d:"main")===I});this.autoMode.currentQualityIndex=c>=0?c:0}else this.autoMode.currentQualityIndex=0;this.switchControl.boundOnStatistics=this.onStatistics,A.on(Xt.STATISTICS,this.switchControl.boundOnStatistics),this.log.info("auto mode started")})}stopAutoMode(){this.autoMode.enabled&&(this.autoMode.instance&&this.switchControl.boundOnStatistics&&this.autoMode.instance.off(Xt.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:e}=this.autoMode,o=Date.now()-this.switchControl.lastSwitchTime0,c=this.networkMetrics.frameRate<=e.fpsPoorLimit,u=this.networkMetrics.loss>=e.lossPoorLimit||this.networkMetrics.rtt>=e.rttPoorLimit,d=c&&u;this.counters.downgradeCondition=d?this.counters.downgradeCondition+1:0;let R=this.counters.rttUnder>=e.goodCount&&this.counters.lossUnder>=e.goodCount,k=this.counters.upgradeFail{if(k.remoteAudioTrack.isAvailable){if(d.get(k.userId))return;let _=u.getPCM(Z=>{e.emit(Xt.AUDIO_FRAME,Z)},k.userId);d.set(k.userId,_)}});else{if(d.get(n))return;let k=u.getPCM(_=>{e.emit(Xt.AUDIO_FRAME,_)},n);d.set(n,k)}else if(n==="*")e.room.remotePublishedUserMap.forEach(k=>{if(k.remoteAudioTrack.isSubscribed){let{userId:_}=k,Z=d.get(_);Z?.abort("disable"),d.delete(_)}});else{let k=d.get(n);k?.abort("disable"),d.delete(n)}})}resumeRemotePlayer(A){return DA(this,null,function*(){if(A.userId==="*"){let o=[];return A.trtcInstance.room.remotePublishedUserMap.forEach(n=>{let{remoteAudioTrack:a,remoteVideoTrack:I,remoteAuxiliaryTrack:c}=n;A.streamType?A.streamType==="main"?(a.isAvailable&&o.push(a.player.resume()),I.isAvailable&&o.push(I.player.resume())):c.isAvailable&&o.push(c.player.resume()):(a.isAvailable&&o.push(a.player.resume()),I.isAvailable&&o.push(I.player.resume()),c.isAvailable&&o.push(c.player.resume()))}),Promise.all(o)}let e=A.trtcInstance.room.remotePublishedUserMap.get(A.userId);if(e)return A.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(A){if(A.userId==="*")A.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:o,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=e;A.streamType?A.streamType==="main"?(o.isAvailable&&o.player.pause(),n.isAvailable&&n.player.pause(!1)):a.isAvailable&&a.player.pause(!1):(o.isAvailable&&o.player.pause(),n.isAvailable&&n.player.pause(!1),a.isAvailable&&a.player.pause(!1))});else{let e=A.trtcInstance.room.remotePublishedUserMap.get(A.userId);e&&(A.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause(!1)):e.remoteAuxiliaryTrack.player.pause(!1))}}requestPictureInPicture(A){let e=[...A.trtcInstance.room.remotePublishedUserMap.values()].find(o=>o.remoteVideoTrack.isAvailable);return e?A.enable?e.remoteVideoTrack.player.enterPictureInPicture():e.remoteVideoTrack.player.exitPictureInPicture():Promise.reject(new Ct({code:Ge.INVALID_OPERATION,message:"no available remote video"}))}requestFullScreen(A){let e=[...A.trtcInstance.room.remotePublishedUserMap.values()].find(o=>o.remoteVideoTrack.isAvailable);return e?A.enable?e.remoteVideoTrack.player.enterFullscreen():e.remoteVideoTrack.player.exitFullscreen():Promise.reject(new Ct({code:Ge.INVALID_OPERATION,message:"no available remote video"}))}switchPlaybackQuality(A){return DA(this,null,function*(){let e=A.trtcInstance;return e._playbackQualitySwitcher||(e._playbackQualitySwitcher=new TeA),e._playbackQualitySwitcher.switchPlaybackQuality(A)})}prelink(A){return DA(this,null,function*(){let{trtcInstance:e}=A;return A.enable?e.room.prelink(A.sdkAppId,A.userId,A.userSig,sG.frameWorkType,A.roomId,A.strRoomId):e.room.closePrelink()})}};vt([a4({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"}}})],oK.prototype,"enableAudioFrameEvent"),vt([a4({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"}}})],oK.prototype,"prelink");var GeA=new oK,keA=es(hg(),1),_eA=class extends keA.EventEmitter{constructor(){super(),G(this,"states",{}),G(this,"permissionChangeHandler"),G(this,"log"),this.log=nA.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var A,e;this.emit("permission-state-change",{camera:(A=this.states.camera)==null?void 0:A.state,microphone:(e=this.states.microphone)==null?void 0:e.state})}}request(A){return DA(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(e=>e.stop())})}get(A){return DA(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(e){return this.log.error("get ".concat(A," permission failed, error: ").concat(e instanceof Error?e.message:e)),null}})}destroy(){Object.values(this.states).forEach(A=>{A?.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Ux=new _eA,J4=0,aG=new Set,Dg=null;zU(L4),yA.checkStorage();var Qo=class $Q extends qV.EventEmitter{constructor(e,o){super(),G(this,"_room"),G(this,"_eventListened",new Set),G(this,"_localVideoTrack",null),G(this,"_localAudioTrack",null),G(this,"_localScreenTrack",null),G(this,"_localScreenAudioTrack",null),G(this,"_localVideoConfig",null),G(this,"_localScreenConfig",null),G(this,"_localAudioConfig",null),G(this,"_remoteVideoConfigMap",new Map),G(this,"_remoteAudioConfigMap",new Map),G(this,"_remoteAudioVolumeMap",new Map),G(this,"_remoteAudioMuteMap",new Map),G(this,"_mediaTrackMap",new WeakMap),G(this,"_log",nA.createLogger({id:"t".concat(++J4)})),G(this,"_plugins",new Map),G(this,"_networkQuality",null),G(this,"_speakerId"),G(this,"enterRoomParams"),G(this,"_enableAutoSwitchWhenRecapturing",!0),G(this,"_autoSubscribeDataChannel",!1),G(this,"_playbackQualityList",[]),this._room=new e(bt({logger:this._log,frameWorkType:$Q.frameWorkType},o)),this._room.videoDecodeFallbackType=o.videoDecodeFallback,rn(o.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=o.enableAutoSwitchWhenRecapturing),this._log.info("create() ".concat(JSON.stringify(o,(n,a)=>n==="plugins"?a.map(I=>I.Name):a))),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(n){return this._room.audioManager.dump(n)}}}),o.plugins&&o.plugins.forEach(n=>{this._use(n,o.assetsPath)}),this._use(meA,o.assetsPath),this._use(peA,o.assetsPath),this._use(DeA,o.assetsPath),this._use(P4,o.assetsPath),this._use(SeA),o.enableSEI&&kT&&this._use(MeA),this._room.on("audio-volume",n=>{var a,I;!n.find(c=>c.userId==="")&&this._localAudioTrack&&n.push({userId:"",volume:Math.floor(100*((a=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?a:this._localAudioTrack.getAudioLevel())),floatVolume:(I=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?I:this._localAudioTrack.getInternalAudioLevel()}),o.volumeType===1&&n.forEach(c=>{var u;let d=c.userId===""?this._localAudioTrack:(u=this.room.remotePublishedUserMap.get(c.userId))==null?void 0:u.remoteAudioTrack;d&&(c.volume=d.dbVolume)}),o.enableDbVolume&&n.forEach(c=>{var u;let d=c.userId===""?this._localAudioTrack:(u=this.room.remotePublishedUserMap.get(c.userId))==null?void 0:u.remoteAudioTrack;d&&(c.volume=d.dbVolume)}),this.emit(Xt.AUDIO_VOLUME,{result:n.sort((c,u)=>u.volume-c.volume)})}),this._room.videoManager.on("error",n=>{this._log.error(new vi({code:Si.OPERATION_FAILED,extraCode:5504,message:n.message,originError:n}))}),this._listenEvents(),this._initActiveSpeaker(),((n,a)=>{let{emit:I}=n;n.emit=function(){for(var c=arguments.length,u=new Array(c),d=0;d{let d=[],R=[],k=[],_=0;self.onmessage=Z=>{switch(Z.data.type){case"sei":Z.data.isMain?(d.push(Z.data.data),Z.data.small&&k.push(Z.data.data)):R.push(Z.data.data);break;case"ntp-offset":_=Z.data.data}},self.onrtctransform=Z=>{let{options:iA}=Z.transformer,cA=iA.isReceiver?O4({userId:iA.userId,streamType:iA.streamType,isAudio:iA.isAudio}):U4({getNtpTime:()=>Date.now()+_,isAudio:iA.isAudio,isMain:iA.isMain,seiMessageList:iA.isMain?iA.small?k:d:R});Z.transformer.readable.pipeThrough(cA).pipeTo(Z.transformer.writable)}},")();").concat(n,"})()"),I=new Blob([a],{type:"text/javascript"}),c=URL.createObjectURL(I),u=new Worker(c);return URL.revokeObjectURL(c),u}var Y4,$q=class{constructor(A){G(this,"audioPlayer"),G(this,"videoPlayer"),G(this,"log"),this.audioPlayer=A.audioPlayer,this.videoPlayer=A.videoPlayer,this.log=A.log.createChild({id:"pip"}),this.videoPlayer.on(mi.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.on(mi.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.on(mi.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(mi.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(mi.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.on(mi.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.on(mi.VOLUME_CHANGE,this.handleVolumeChange,this)}handleUserResumeInPIPOrFullScreen(){this.audioPlayer.isPaused&&(this.log.warn("resume audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doResume()),ra&&bh&&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"),ra&&bh?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(mi.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.off(mi.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.off(mi.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(mi.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(mi.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.off(mi.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.off(mi.VOLUME_CHANGE,this.handleVolumeChange,this)}},P4=!1;function TeA(A){var e=this;let{TRTC:o,room:n,errorModule:a,assetsPath:I}=A;return{TRTC:o,LocalMixVideoTrack:Jq,LocalVideoTrack:Su,LocalScreenTrack:_m,room:n,assetsPath:I,fileDownloader:Xq,innerEmitter:S,INNER_EVENT:K,constants:tO,environment:OO,utils:s4,eventLogger:Jo,log:this.room.getLogger(),loggerManager:nA,errorModule:a,kvStatManager:ct,rtcDectection:kA,trtc:this,rx:FW,enums:oe,schedule:w4,getDevices:Qx,initVisionTaskRegistry:function(c,u){let d=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"/mediapipe/vision.js";return DA(e,null,function*(){!window.VisionTaskRegistry&&!P4&&(P4=!0,Y4=Xq.loadScript("".concat(c,"/").concat(d).replace(/([^:]\/)\/+/g,"$1"))),yield Y4,yield(yield window.VisionTaskRegistry.getInstance(c)).preloadModels(u)})},audioContext:tI(),deviceDetector:vs,AudioPlayer:vq,RemoteAudioPlayer:TW,VideoPlayer:wi,showAutoPlayDialog:nC,Timer:nn,clearStarted:(c,u)=>{let d=c.getAlias(),R=sG.instances.get(this);if(R)if(u){let k=R.get(d+u);if(!k)return;k.started=!1}else R.forEach((k,_)=>{_.startsWith(d)&&(k.started=!1)})},startGetPCM:jq,createAudioNode:Cx,getNetworkTimeOffset:AO,validateSourceNode:()=>{var c;if(Yr&&((c=this.room.audioManager._localAudioPipline)==null||!c.source.node))throw new vi({code:Si.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:x4,AVPlayerStateSyncManager:$q,PlayerEvent:mi}}var VM=new WeakMap,J4="5.15.3-beta.12";function vI(){for(var A=arguments.length,e=new Array(A),o=0;ofunction(){for(var I=arguments.length,c=new Array(I),u=0;ufunction(){for(var I=arguments.length,c=new Array(I),u=0;uRh(k)?Vf(k):Sr(k)?k:ya(k))},value:o}})}else if(!Ee(e.type)&&ya(o)!==e.type)throw new vi(c(5002));if(e.allowEmpty===!1){let R=hr(o)&&(o===0||Number.isNaN(o)),k=Sr(o)&&o.trim()==="";if(R||k)throw new vi(c(5003))}if(e.notLessThanZero&&hr(o)&&o<0)throw new vi(c(5006));if(!Ee(e.min)&&hr(o)&&oe.max)throw new vi(c(5008));if(Sr(e.instanceOf)){if(!o||o._name!==e.instanceOf)throw new vi(c(5004))}else if($n(e.instanceOf)&&!(o instanceof e.instanceOf))throw new vi(c(5004));if(Array.isArray(e.values)&&!e.values.includes(o))throw new vi(c(5005));let{properties:u}=e;Cc(u)&&Xc(o)&&Object.keys(u).forEach(R=>{Yx.call(this,{rule:u[R],value:o&&o[R],key:"".concat(R),fnName:a,className:I})});let{arrayItem:d}=e;Cc(d)&&Aa(o)&&o.forEach((R,k)=>{Yx.call(this,{rule:d,value:R,key:"".concat(n,"[").concat(k,"]"),fnName:a,className:I})}),$n(e.validate)&&e.validate.call(this,o,n,a,I,this)}var GeA=0;function Hn(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{getRemoteId:e=()=>"",replaceArg:o,getKVReportKey:n,ignoreLog:a,ignoreErrorLog:I}=A;return Dn((c,u)=>function(){for(var d=arguments.length,R=new Array(d),k=0;k0?TA.info("".concat(u,"() ").concat(JA," ").concat(JSON.stringify(R,(Ft,ie)=>cA(Ft,ie,["userSig","privateMapKey"])))):TA.info("".concat(u,"() ").concat(JA));let Ie=n?n(...R):Ax[u],XA=I?.(...R)||!1;try{let Ft=c.apply(this,R),ie=ki();if(yh(Ft)){let ke="".concat(u.includes("Plugin")?"".concat(((Z=(_=R[0]).getName)==null?void 0:Z.call(_))||""," "):" ");return Ft.then(Nt=>(TA.info("".concat(u,"() success ").concat(JA," ").concat(ke).concat(e.call(this,...R))),ct.addSuccessEvent({key:Ie,cost:ki()-ie}),Nt)).catch(Nt=>{var Ut;let Ui=(Nt=vi.convertFrom.call(this,Nt,u,R.length===1?R[0]:R)).extraCode||Nt.code,Oi=(Ut=Nt.message)!=null&&Ut.includes(Ui)?"":" code:".concat(Ui),or=Nt?.code===Si.OPERATION_ABORT;throw XA||TA[or?"warn":"error"]("".concat(u,"() failed ").concat(JA," ").concat(ke).concat(e.call(this,...R)," ").concat(Nt).concat(Oi," params: ").concat(JSON.stringify(R,cA))),ct.addFailedEvent({key:Ie,error:Nt}),Nt})}return ct.addSuccessEvent({key:Ie}),Ft}catch(Ft){let ie=(Ft=vi.convertFrom.call(this,Ft,u)).extraCode||Ft.code,ke=(iA=Ft.message)!=null&&iA.includes(ie)?"":" code:".concat(ie),Nt=Ft?.code===Si.OPERATION_ABORT;throw XA||TA[Nt?"warn":"error"]("".concat(u,"() failed ").concat(JA," ").concat(Ft).concat(ke," params: ").concat(JSON.stringify(R,cA))),ct.addFailedEvent({key:Ie,error:Ft}),Ft}})}var eK,tK=A=>Dn((e,o)=>function(n,a){return DA(this,null,function*(){let I=this._plugins.get(n);if(!I)throw this._log.error("plugin ".concat(String(n)," is not found")),new vi({code:Si.OPERATION_ABORT,message:"plugin ".concat(String(n)," is not found"),fnName:o});if($n(I.constructor.isSupported)&&!I.constructor.isSupported())throw this._log.error("plugin ".concat(String(n)," is not supported")),new vi({code:Si.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(n)," is not supported"),extraCode:5210,fnName:o});return AK.call(this,I.getValidateRule(A),[a],o,"TRTC"),e.call(this,I,a)})}),iK=0,Px=class wG{constructor(e){this.core=e,G(this,"log"),G(this,"customAudioReferenceMap",new Map),G(this,"audioRefId",0),G(this,"audioContext",tI()),G(this,"localAudioWorkletNode"),G(this,"screenAudioWorkletNode"),G(this,"mixNode"),G(this,"silentNode"),iK+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(iK)}),this.log.info("created id=".concat(this.getAlias()).concat(iK)),this.installEvent()}static getStartValidateRule(e){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,n,a,I){if(!e.room.audioManager.hasAudioTrack&&!e.room.audioManager.hasScreenAudioTrack)throw new vi({code:Si.INVALID_OPERATION,extraCode:5106,fnName:a})}}}preload(e){return eK||(eK=this.doPreload(e)),eK}doPreload(e){return DA(this,null,function*(){let o=yield this.core.fileDownloader.download(e,{type:"blob"}),n=URL.createObjectURL(o);try{yield Fa(this.audioContext,n)}catch(a){this.log.error("preload audioProcessor failed. ".concat(a))}finally{URL.revokeObjectURL(n)}})}getName(){return wG.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(e){switch(e){case"start":return wG.getStartValidateRule(this.core);case"update":return wG.updateValidateRule;case"stop":return wG.stopValidateRule}}start(e){return DA(this,null,function*(){var o,n,a,I;let{room:c}=this.core,{sdkAppId:u,userId:d,userSig:R,assetsPath:k=this.core.assetsPath,audioReference:_,processLevel:Z,enableDump:iA,isLocalAudioNeedAudioProcess:cA=!0,isScreenAudioNeedAudioProcess:TA=!1}=e;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=cA,this.core.room.audioManager.isScreenAudioNeedAudioProcess=TA,!k)throw new vi({code:Si.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(k,"/audioProcessor-wasm.js")),cA&&!this.localAudioWorkletNode){let{sign:JA,status:Ie,timestamp:XA}=yield this.getAuthData(u,d,R);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",u,d,XA,JA,Ie,c)}if(TA&&!this.screenAudioWorkletNode){let{sign:JA,status:Ie,timestamp:XA}=yield this.getAuthData(u,d,R);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",u,d,XA,JA,Ie,c)}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"}),(n=this.screenAudioWorkletNode)==null||n.port.postMessage({type:"enable"}),c.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),Ee(_)||_.forEach(JA=>{this.customAudioReferenceMap.set(JA,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:JA,refId:"o-".concat(this.audioRefId++)})}),Ee(Z)||(a=this.localAudioWorkletNode)==null||a.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:Z}}),Ee(iA)||(I=this.localAudioWorkletNode)==null||I.port.postMessage({type:"dump",data:{enable:iA}})})}update(e){return DA(this,null,function*(){var o,n,a;let{audioReference:I,enableDump:c,processLevel:u}=e;Ee(I)||(this.customAudioReferenceMap.forEach((d,R)=>{this.customAudioReferenceMap.delete(R),this.core.room.audioManager.updateAudioReference({type:"remove",refId:d})}),I.forEach(d=>{this.customAudioReferenceMap.set(d,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:d,refId:"o-".concat(this.audioRefId++)})})),Ee(u)||(o=this.localAudioWorkletNode)==null||o.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:u}}),Ee(c)||((n=this.localAudioWorkletNode)==null||n.port.postMessage({type:"dump",data:{enable:c}}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:c}}))})}stop(){return DA(this,null,function*(){var e,o;let{room:n}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(o=this.screenAudioWorkletNode)==null||o.port.postMessage({type:"disable"}),yield n.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(e,o,n){return DA(this,null,function*(){let a=String(Date.now()).slice(0,-3),{auth:I,sign:c,status:u,message:d}=yield function(R){return DA(this,arguments,function(k){let{sdkAppId:_,userId:Z,userSig:iA,timestamp:cA}=k;return function*(){let TA="".concat(function(Ui){let Oi=arguments.length>1&&arguments[1]!==void 0?arguments[1]:fA.MAIN;return"https://".concat(ZQ[Oi]||zq(Ui,Oi),"/api/v1/audioAiAuth")}(_),"?sdkAppId=").concat(_,"&userId=").concat(Z,"&userSig=").concat(iA,"×tamp=").concat(cA),JA=yield fetch(TA),{data:{errCode:Ie,errMsg:XA,sign:Ft,status:ie}}=yield JA.json();if(ie==="1")return{auth:!0,sign:Ft,status:ie,message:XA};let ke=rl(_)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",Nt="Init RTCAudioProcessor failed.",Ut="";switch(Ie){case 1:Ut="Please check your params.";break;case 2:Ut="You need to buy packages. Refer to: ".concat(ke);break;case 3:Ut="Server is invalid. Please contact our engineer. ";break;case 4:Ut="Your packages is not active. Refer to: ".concat(ke);break;case 5:Ut="Your packages is expired. Refer to: ".concat(ke);break;case 6:Ut="Your version is not supported."}return{auth:!1,status:ie,message:XA?"".concat(Nt," Reason: ").concat(XA,". ").concat(Ut):"".concat(Nt,", ").concat(Ut)}}()})}({sdkAppId:e,userSig:n,userId:o,timestamp:a});if(!I)throw this.log.info("audioProcessor: ".concat(o," auth result: ").concat(I,". Message: ").concat(d)),new vi({code:Si.INVALID_PARAMETER,message:d});return{sign:c,status:u,timestamp:a}})}initWorkletNode(e,o,n,a,I,c,u,d){e.port.postMessage({type:"init",data:{sdkAppId:String(n),userId:a,timestamp:I,sign:c,status:u}}),e.port.onmessage=R=>{var k;let{data:_}=R;switch(_.type){case"cost":let Z=_?.value>10?"info":"debug";return void this.log[Z]("".concat(o==="localAudio"?"":"[".concat(o,"] "),"avg cost: ").concat(_.value," max: ").concat(_?.max,"(").concat(QN(new Date(_?.maxCostTimestamp)),") hist: ").concat((k=_?.hist)==null?void 0:k.join(" ")));case"log":return void this.log[_.logLevel]("".concat(o==="localAudio"?"":"[".concat(o,"] ")).concat(_.value));case"dump":return void S.emit("265",{room:d,data:_.value,type:o==="localAudio"?"dump":"dump-screen-audio"});case"detectEcho":return void this.log.warn("".concat(o==="localAudio"?"":"[".concat(o,"] "),"detect echo: ").concat(pM()?pu():UQ()))}}}handleLocalAudioStarted(e){return DA(this,null,function*(){var o;if(this.hitTest(e.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(n){this.log.warn("audio processor auto start failed, error: ".concat(n))}})}handleLocalAudioStopped(e){return DA(this,null,function*(){var o;!this.hitTest(e.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(e){return e===this.core.room}};G(Px,"updateValidateRule",{type:"object"}),G(Px,"stopValidateRule",{type:"object"}),G(Px,"Name","AudioProcessor");var keA=Px,oK=0,_eA=class{constructor(A,e){G(this,"audioObjectURL"),G(this,"player"),G(this,"publisher"),G(this,"mixInput"),this.mixInput=new yW(e),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&&(Ee(A.volume)||(this.volume=A.volume),Ee(A.loop)||(this.loop=A.loop),Ee(A.playbackRate)||(this.playbackRate=A.playbackRate))}updateListener(A){if(this.player){if(A.onDurationChange){let{onDurationChange:e}=A;this.player.ondurationchange=o=>{e(o.target.duration)}}if(A.onTimeUpdate){let e=A.onTimeUpdate,{player:o}=this;o.ontimeupdate=()=>{e(o.currentTime,o.duration)}}A.onEnded&&(this.player.onended=A.onEnded)}}reload(A){return DA(this,null,function*(){if(A.url){let e=yield Xq.download(A.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),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,e;return Promise.all([(A=this.player)==null?void 0:A.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var A,e;(A=this.player)==null||A.pause(),(e=this.publisher)==null||e.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 qM(A,e){if(e&&typeof e!="function")throw new vi({code:Si.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(A," should be a function.")})}var IG=class SG{constructor(e){this.core=e,G(this,"log"),G(this,"mixedMusicMap",new Map),G(this,"cacheMusicMap",new Map),oK+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(oK)}),this.log.info("created id=".concat(this.getAlias()).concat(oK))}getName(){return SG.Name}getAlias(){return"ax"}getGroup(e){return e?.id}getValidateRule(e){switch(e){case"start":return SG.startValidateRule;case"update":return SG.updateValidateRule;case"stop":return SG.stopValidateRule}}start(e){return DA(this,null,function*(){let{room:o}=this.core;this.core.validateSourceNode(),this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track));let{id:n,url:a}=e;if(this.mixedMusicMap.has(n))return;let I=this.cacheMusicMap.get(n);I?e.url?I.reset():(I.mixInput.replaceSource(e.track),I.mixInput.connect()):(I=new _eA(e,o.audioManager),this.cacheMusicMap.set(n,I)),I.updateListener(e),I.updateSettings(e);try{yield I.play()}catch(c){yield this.handleAutoPlayFailed(I,e,c)}this.mixedMusicMap.set(n,I),I.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:I.mixInput.source.node,refId:"ax-".concat(n)}),this.log.info("start mix audio track ".concat(n," success.")),ct.addEnum({key:502700,value:3}),this.kvUpload(e)})}handleAutoPlayFailed(e,o,n){return DA(this,null,function*(){if(n.name==="NotSupportedError")this.log.error("play failed, try to reload source. error: ".concat(n)),yield e.reload(o),yield e.play();else{if(n.name!=="NotAllowedError")throw n;if(this.core.room.enableAutoPlayDialog){let a=()=>{var I;(I=e.play())==null||I.finally(()=>{S.off("154",a,this)})};S.on("154",a,this),nC()}else this.core.trtc.emit(Xt.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>DA(this,null,function*(){return e.play()})})}})}update(e){return DA(this,null,function*(){let{id:o,operation:n,seekFrom:a,playbackRate:I}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let c=this.mixedMusicMap.get(o);c?(c.updateSettings(e),c.updateListener(e),Ee(n)||c.setOperation(n),Ee(a)||c.seek(a),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(o," not found."))})}stop(e){return DA(this,arguments,function(o){var n=this;let{id:a}=o;return function*(){if(n.mixedMusicMap.has(a)){n.log.info("remove music source, music id: ".concat(a));let I=n.mixedMusicMap.get(a);I!=null&&I.mixInput.source.node&&n.core.room.audioManager.updateAudioReference({type:"remove",audioReference:I.mixInput.source.node,refId:"ax-".concat(a)}),I?.stop(),n.mixedMusicMap.delete(a)}a==="*"&&n.destroyAllMusic()}()})}kvUpload(e){let{track:o,loop:n,volume:a,playbackRate:I,operation:c,seekFrom:u,onTimeUpdate:d,onDurationChange:R,onEnded:k}=e;o&&ct.addCount({key:502009}),n&&ct.addCount({key:502001}),a&&ct.addCount({key:502002}),I&&ct.addCount({key:502003}),c&&ct.addCount({key:502004}),u&&ct.addCount({key:502005}),typeof d!="function"&&ct.addCount({key:502007}),typeof k!="function"&&ct.addCount({key:502008}),typeof R!="function"&&ct.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((e,o)=>{e!=null&&e.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:e.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()}};G(IG,"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,e,o){if(A.url&&A.url!=="*"){let n=A.url.split("?")[0],a=["mp3","ogg","wav","flac"],I=n.split(".").pop(),c=a.indexOf(I)>=0,u=n.startsWith("blob"),d=n.startsWith("data");if(!(c||u||d))throw new vi({code:Si.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:o})}if(!A.url&&!A.track)throw new vi({code:Si.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:o});qM("onTimeUpdate",A.onTimeUpdate),qM("onEnded",A.onEnded),qM("onDurationChange",A.onDurationChange)}}),G(IG,"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,e,o){qM("onTimeUpdate",A.onTimeUpdate),qM("onEnded",A.onEnded),qM("onDurationChange",A.onDurationChange)}}),G(IG,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),G(IG,"Name","AudioMixer");var rK,beA=IG,nK=0,Jx=class vG{constructor(e){this.core=e,G(this,"log"),G(this,"audioContext",tI()),G(this,"workletNode"),G(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5}),nK+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(nK)}),this.log.info("created id=".concat(this.getAlias()).concat(nK))}static startValidateRule(e){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,n,a,I){if(!e.room.audioManager.hasAudioTrack)throw new vi({code:Si.INVALID_OPERATION,extraCode:5106,fnName:a})}}}preload(e){return rK||(rK=this.doPreload(e)),rK}doPreload(e){return DA(this,null,function*(){let o=yield this.core.fileDownloader.download(e,{type:"blob"}),n=URL.createObjectURL(o);try{yield Fa(this.audioContext,n)}catch(a){throw this.log.error("load worklet failed",a),a}finally{URL.revokeObjectURL(n)}})}getName(){return vG.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(e){switch(e){case"start":return vG.startValidateRule(this.core);case"update":return vG.updateValidateRule;case"stop":return vG.stopValidateRule}}start(e){return DA(this,null,function*(){let{room:o,schedule:n}=this.core,{assetsPath:a=this.core.assetsPath}=e;if(!a)throw new vi({code:Si.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(a,"/denoiser-wasm").concat(mm()?"":"-nosimd",".js")),!this.workletNode){let I=String(Date.now()).slice(0,-3),{auth:c,sign:u,status:d,message:R}=yield function(k,_){return DA(this,arguments,function(Z,iA){let{sdkAppId:cA,userId:TA,userSig:JA,timestamp:Ie}=iA;return function*(){try{let{data:{errCode:XA,errMsg:Ft,sign:ie,status:ke}}=yield Z.getAbilityConfig(cA,Z.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:cA,userId:TA,userSig:JA,timestamp:Ie});if(ke==="1")return{auth:!0,sign:ie,status:ke,message:Ft};let Nt=rl(cA)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",Ut="Init RTCAIDenoiser failed.",Ui="";switch(XA){case 1:Ui="Please check your params.";break;case 2:Ui="You need to buy packages. Refer to: ".concat(Nt);break;case 3:Ui="Server is invalid. Please contact our engineer. ";break;case 4:Ui="Your packages is not active. Refer to: ".concat(Nt);break;case 5:Ui="Your packages is expired. Refer to: ".concat(Nt);break;case 6:Ui="Your version is not supported."}return{auth:!1,status:ke,message:Ft?"".concat(Ut," Reason: ").concat(Ft,". ").concat(Ui):"".concat(Ut,", ").concat(Ui)}}catch(XA){return{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(XA)}}}()})}(n,fi(bt({},e),{timestamp:I}));if(!c)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(c,". Message: ").concat(R)),new vi({code:Si.INVALID_PARAMETER,message:R});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(e.sdkAppId),userId:e.userId,timestamp:I,sign:u,status:d}}),this.workletNode.port.onmessage=k=>{var _;let{data:Z}=k;if(Z.type==="cost"){let iA=Z?.max>20?"warn":Z?.max>10?"info":"debug";this.log[iA]("avg cost: ".concat(Z.value," max: ").concat(Z?.max,"(").concat(QN(new Date(Z?.maxCostTimestamp)),") hist: ").concat((_=Z?.hist)==null?void 0:_.join(" ")))}else Z.type==="log"&&this.log[Z.logLevel]("".concat(Z.value))}}this.updateConfig(e),this.workletNode.port.postMessage({type:"enable"}),o.audioManager.addDenoiser(this.workletNode),o.sendAbilityStatus({ai_denoise:1})})}update(e){return DA(this,null,function*(){this.updateConfig(e)})}stop(){return DA(this,null,function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)})}updateConfig(e){if(!this.workletNode)return;let o=!1;Ee(e.mode)||(e.mode===0?this.config.enableFarFieldReduce=!1:e.mode===1&&(this.config.enableFarFieldReduce=!0),o=!0),Ee(e.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=e.farFieldReduceThreshold,o=!0),o&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};G(Jx,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),G(Jx,"stopValidateRule",{type:"object"}),G(Jx,"Name","AIDenoiser");var LeA=Jx,FeA=es(hg(),1),UeA=class extends FeA.EventEmitter{constructor(){super(),G(this,"observer"),G(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 DA(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!ra&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(A){Jo.uploadEvent({log:"stat-pressure-detector-start-failed",error:A})}})}onPressureChange(A){let e=this.stateNum,o=A[A.length-1];this.state=o.state,(this.stateNum>3||e>3)&&nA.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(e){Jo.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:e})}}},V4=new UeA,aK=0,sK=class n6{constructor(e){this.core=e,G(this,"log"),G(this,"_seiMessageList",[]),G(this,"_smallSeiMessageList",[]),G(this,"_subStreamSeiMessageList",[]),aK++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(aK)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(aK)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:o,mediaType:n}=e;try{return L4({frame:o,seiMessageList:n===8?this._smallSeiMessageList:n===2?this._subStreamSeiMessageList:this._seiMessageList})}catch(a){this.log.warn(a)}return o}decode(e){let{frame:o,track:n}=e;return F4({frame:o,onSEI:a=>{a.forEach(I=>{n!=null&&n.userId?this.core.trtc.emit(Xt.SEI_MESSAGE,{seiPayloadType:I.seiPayloadType,data:I.seiPayload.buffer,userId:n.userId,streamType:n.mediaType===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:I})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(e){switch(e){case"start":case"update":case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:JQ?this.encode:L4,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:JQ?this.decode:F4,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update(e){let{buffer:o,options:n}=e;var a;let I=[n.seiPayloadType,o],c=!!n.small;n.toSubStream?this._subStreamSeiMessageList.push(I):(this._seiMessageList.push(I),c&&this._smallSeiMessageList.push(I)),(a=this.core.room.scriptTransformWorker)==null||a.postMessage({type:"sei",data:I,isMain:!n.toSubStream,small:c})}getName(){return n6.Name}getAlias(){return"sei"}getGroup(){return"sei"}};G(sK,"autoStart",!0),G(sK,"Name","SEI");var Hx,OeA=sK,xeA=0,gK=class a6{constructor(e){this.core=e,G(this,"_core"),G(this,"log"),G(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++xeA)}),this.log.info("created")}getName(){return a6.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(e){switch(e){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return DA(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog())})}update(e){return DA(this,arguments,function(o){var n=this;let{visible:a}=o;return function*(){a?yield n.openDebugDiaLog():n.closeDebugDiaLog()}()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return DA(this,null,function*(){var e;if(!this.dialog)try{if(Hx)yield Hx;else{let o=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_DEBUG_DIALOG_PATH"))||"https://unpkg.com/".concat("trtc-sdk-v5","@").concat(ol,"/assets/debug-dialog.js");Hx=this._core.fileDownloader.loadScript(o),yield Hx}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)}};G(gK,"Name","Debug"),G(gK,"autoStart",!0);var YeA=gK,q4=A=>{switch(A){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},K4=class{constructor(A,e,o){G(this,"trackDoneOB"),G(this,"startOB"),G(this,"stopOB"),G(this,"inputFrameCount",0),G(this,"decodedFrameCount",0),G(this,"type","auto"),G(this,"config"),G(this,"decoder"),G(this,"_decodeSink");let{kvStatManager:n,trtc:a}=A;this.config=o.config,this.trackDoneOB=Ln(e,Uo.INIT),this.stopOB=wu(),this.startOB=wu(),o.type==="auto"?this.type="webCodecs":this.type=o.type;let I=wu();Jn(this.startOB,kq(0),yx(c=>{let u=this.pipe(e);return I.next("STARTING"),e.log.info("decoder type: ".concat(this.type)),Jn(u,Qc(this.stopOB),Ks(()=>{},d=>{e.log.error(d),n.addFailedEvent({key:q4(this.type),error:d}),c>4?this.startOB.error(d):this.startOB.next(c+1)})),Jn(u,OM(1),r4(Lq))}),Qc(this.stopOB),Ks(()=>{e.player.setOutput(),I.next("STARTED")},c=>{I.next("FAILED")},()=>{n.addSuccessEvent({key:q4(this.type)}),n.addSuccessEvent({key:504702})}))}mock(A){this._decodeSink?this._decodeSink.error(A):this.startOB.next(0)}close(A){this.stopOB.next(A)}pipe(A){return zT()(e=>DA(this,null,function*(){this._decodeSink=e,e.defer(()=>{var n;(n=this.decoder)==null||n.close()});let{type:o}=this;try{o==="webCodecs"&&(this.decoder=new AudioDecoder({error:n=>{A.log.error(n),e.error(4)},output:n=>{this.decodedFrameCount++,e.next(n),A.player.write(n)}})),this.decoder.configure(this.config)}catch(n){A.log.error(n),e.error(o==="webCodecs"?2:6)}}))}decodeFrame(A){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:A.data,timestamp:A.timestamp,type:"key"}))}},PeA={type:"object"},j4=class Nj{constructor(e){this.core=e,G(this,"log"),G(this,"contextMap",new Map),G(this,"decodeProcessorMap",new WeakMap),this.log=e.log.createChild({id:"".concat(this.getAlias())})}getAlias(){return Nj.Name}getGroup(e){return e.track.userId+e.track.streamType}getName(){return Nj.Name}getValidateRule(e){return PeA}start(e){let{track:o}=e;this.decodeProcessorMap.set(o,this.decode(e)),this.core.room.audioManager.addDecodeProcessor({processor:n=>{let{frame:a,track:I}=n;return this.decodeProcessorMap.has(I)?this.decodeProcessorMap.get(I)({frame:a,track:I}):a},type:3})}decode(e){return o=>{let{frame:n,track:a}=o;if(a!==e.track)return n;if(this.contextMap.has(a))return this.contextMap.get(a).decodeFrame(n);let I=new K4(this.core,a,e);return Jn(I.trackDoneOB,OM(1),Ks(()=>{this.core.clearStarted(this,this.getGroup(e)),this.stop({track:a})})),this.contextMap.set(a,I),I.decodeFrame(n)}}stop(e){let{track:o}=e,n=this.contextMap.get(o);n&&(n.close("stop"),this.contextMap.delete(o),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(e){let o=this.contextMap.get(e.track);if(o){if(e.type==="mock")return void o.mock(10);o.close("update"),this.contextMap.set(e.track,new K4(this.core,e.track,e))}}};G(j4,"Name","TRTCAudioDecoder");var W4=j4,JeA={rttPoorLimit:150,lossPoorLimit:20,rttGoodLimit:100,lossGoodLimit:10,fpsPoorLimit:5,cooldownTime:1e4,poorCount:3,goodCount:5,maxUpgradeFailCount:3},HeA=class{constructor(){G(this,"log"),G(this,"autoMode",{enabled:!1,instance:null,config:JeA,sortedStreamList:[],currentQualityIndex:0}),G(this,"switchControl",{isInternal:!1,isSwitching:!1,lastSwitchTime:0,boundOnStatistics:null}),G(this,"networkMetrics",{frameRate:0,rtt:0,loss:0}),G(this,"counters",{rttUnder:0,lossUnder:0,downgradeCondition:0,upgradeFail:0}),G(this,"onStatistics",A=>{var e,o;if(!this.autoMode.instance)return;let{config:n}=this.autoMode;if(this.networkMetrics.rtt=A.rtt,this.networkMetrics.loss=A.downLoss,this.counters.rttUnder=A.rttk.userId===I);if((o=u?.video)==null||!o.length)return;let d=c==="sub"?"sub":"big",R=u.video.find(k=>k.videoType===d);R?(this.networkMetrics.frameRate=R.frameRate||0,this.checkAndSwitchQuality()):this.log.warn("onStatistics: videoStat not found for userId=".concat(I,", streamType=").concat(c))}),this.log=nA.createLogger({id:"pqs"})}getCurrentPlayingStream(A){var e,o;let n=A,a=n._playbackQualityList;if(!a||a.length===0)return this.log.warn("getCurrentPlayingStream: streamList is empty"),null;for(let I of a){let c=A.room.remotePublishedUserMap.get(I.userId);if(!c)continue;let u=(e=I.streamType)!=null?e:"main";if((u==="sub"?c.remoteAuxiliaryTrack:c.remoteVideoTrack).isPlayCalled){let d=(o=n._remoteVideoConfigMap.get("".concat(I.userId,"_").concat(u)))==null?void 0:o.config;if(d)return{userId:I.userId,streamType:u,config:d}}}return null}switchPlaybackQuality(A){return DA(this,null,function*(){var e;let{trtcInstance:o,streamList:n,quality:a}=A;this.log.info("switchPlaybackQuality quality: ".concat(a,", streamList: ").concat(JSON.stringify(n)));let I=o;if(n&&n.length>0&&(I._playbackQualityList=n.map(cA=>{var TA;return fi(bt({},cA),{streamType:(TA=cA.streamType)!=null?TA:"main"})})),a==="auto")return void(yield this.startAutoMode(o));if(this.autoMode.enabled&&a&&!this.switchControl.isInternal&&this.stopAutoMode(),!a)return;if(!I._playbackQualityList||I._playbackQualityList.length<=0)return void this.log.warn("switchPlaybackQuality: streamList is empty, please call with streamList first");let c=I._playbackQualityList.find(cA=>cA.name===a);if(!c)return void this.log.warn('switchPlaybackQuality: quality "'.concat(a,'" not found in streamList'));let u=this.getCurrentPlayingStream(o);if(this.log.info("currentPlaying userId: ".concat(u?.userId,", streamType: ").concat(u?.streamType)),!u)return;let d=(e=c.streamType)!=null?e:"main";if(u.userId===c.userId&&u.streamType===d)return void this.log.info("switchPlaybackQuality: already playing target stream");let R=bt({},u.config);R.streamType==="main"&&d==="main"&&(yield o.muteRemoteAudio(R.userId,!0));let k,_=new Promise(cA=>{k=cA}),Z=cA=>{cA.userId===c.userId&&cA.streamType===d&&cA.state==="PLAYING"&&cA.reason==="playing"&&k("success")};o.on(Xt.VIDEO_PLAY_STATE_CHANGED,Z);let iA=new Promise(cA=>setTimeout(()=>cA("timeout"),1e4));try{if(yield o.startRemoteVideo(fi(bt({},u.config),{userId:c.userId,streamType:d,option:fi(bt({},u.config.option),{isLiveStream:!0})})),(yield Promise.race([_,iA]))==="timeout"){this.log.error("switchPlaybackQuality: VIDEO_PLAY_STATE_CHANGED timeout, rollback");try{yield o.stopRemoteVideo({userId:c.userId,streamType:d})}catch(TA){this.log.warn("switchPlaybackQuality: rollback stopRemoteVideo failed",TA)}throw R.streamType==="main"&&d==="main"&&(yield o.muteRemoteAudio(R.userId,!1).catch(TA=>{this.log.warn("switchPlaybackQuality: rollback muteRemoteAudio failed",TA)})),new Ct({code:Ge.SUBSCRIPTION_TIMEOUT,message:Wi({key:Mi.SWITCH_PLAYBACK_QUALITY_TIMEOUT,data:{userId:c.userId}})})}let cA=o.stopRemoteVideo(R);R.streamType==="main"&&d==="main"?yield Promise.all([o.muteRemoteAudio(c.userId,!1).catch(TA=>{this.log.warn("muteRemoteAudio(new, false) failed",TA)}),cA]):yield cA,I._currentLiveUserId=c.userId,I._currentLiveStreamType=d}finally{o.off(Xt.VIDEO_PLAY_STATE_CHANGED,Z)}})}startAutoMode(A){return DA(this,null,function*(){if(this.autoMode.enabled)return void this.log.info("auto mode already enabled");let e=A;if(!e._playbackQualityList||e._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=e._playbackQualityList||[];this.autoMode.sortedStreamList=[...o].sort((a,I)=>I.bitrate-a.bitrate),this.log.info("auto mode streams: ".concat(this.autoMode.sortedStreamList.map(a=>"".concat(a.name,"(").concat(a.bitrate,"kbps)")).join(" > ")));let n=this.getCurrentPlayingStream(A);if(n){let{userId:a,streamType:I}=n,c=this.autoMode.sortedStreamList.findIndex(u=>{var d;return u.userId===a&&((d=u.streamType)!=null?d:"main")===I});this.autoMode.currentQualityIndex=c>=0?c:0}else this.autoMode.currentQualityIndex=0;this.switchControl.boundOnStatistics=this.onStatistics,A.on(Xt.STATISTICS,this.switchControl.boundOnStatistics),this.log.info("auto mode started")})}stopAutoMode(){this.autoMode.enabled&&(this.autoMode.instance&&this.switchControl.boundOnStatistics&&this.autoMode.instance.off(Xt.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:e}=this.autoMode,o=Date.now()-this.switchControl.lastSwitchTime0,c=this.networkMetrics.frameRate<=e.fpsPoorLimit,u=this.networkMetrics.loss>=e.lossPoorLimit||this.networkMetrics.rtt>=e.rttPoorLimit,d=c&&u;this.counters.downgradeCondition=d?this.counters.downgradeCondition+1:0;let R=this.counters.rttUnder>=e.goodCount&&this.counters.lossUnder>=e.goodCount,k=this.counters.upgradeFail{if(k.remoteAudioTrack.isAvailable){if(d.get(k.userId))return;let _=u.getPCM(Z=>{e.emit(Xt.AUDIO_FRAME,Z)},k.userId);d.set(k.userId,_)}});else{if(d.get(n))return;let k=u.getPCM(_=>{e.emit(Xt.AUDIO_FRAME,_)},n);d.set(n,k)}else if(n==="*")e.room.remotePublishedUserMap.forEach(k=>{if(k.remoteAudioTrack.isSubscribed){let{userId:_}=k,Z=d.get(_);Z?.abort("disable"),d.delete(_)}});else{let k=d.get(n);k?.abort("disable"),d.delete(n)}})}resumeRemotePlayer(A){return DA(this,null,function*(){if(A.userId==="*"){let o=[];return A.trtcInstance.room.remotePublishedUserMap.forEach(n=>{let{remoteAudioTrack:a,remoteVideoTrack:I,remoteAuxiliaryTrack:c}=n;A.streamType?A.streamType==="main"?(a.isAvailable&&o.push(a.player.resume()),I.isAvailable&&o.push(I.player.resume())):c.isAvailable&&o.push(c.player.resume()):(a.isAvailable&&o.push(a.player.resume()),I.isAvailable&&o.push(I.player.resume()),c.isAvailable&&o.push(c.player.resume()))}),Promise.all(o)}let e=A.trtcInstance.room.remotePublishedUserMap.get(A.userId);if(e)return A.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(A){if(A.userId==="*")A.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:o,remoteVideoTrack:n,remoteAuxiliaryTrack:a}=e;A.streamType?A.streamType==="main"?(o.isAvailable&&o.player.pause(),n.isAvailable&&n.player.pause(!1)):a.isAvailable&&a.player.pause(!1):(o.isAvailable&&o.player.pause(),n.isAvailable&&n.player.pause(!1),a.isAvailable&&a.player.pause(!1))});else{let e=A.trtcInstance.room.remotePublishedUserMap.get(A.userId);e&&(A.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause(!1)):e.remoteAuxiliaryTrack.player.pause(!1))}}requestPictureInPicture(A){let e=[...A.trtcInstance.room.remotePublishedUserMap.values()].find(o=>o.remoteVideoTrack.isAvailable);return e?A.enable?e.remoteVideoTrack.player.enterPictureInPicture():e.remoteVideoTrack.player.exitPictureInPicture():Promise.reject(new Ct({code:Ge.INVALID_OPERATION,message:"no available remote video"}))}requestFullScreen(A){let e=[...A.trtcInstance.room.remotePublishedUserMap.values()].find(o=>o.remoteVideoTrack.isAvailable);return e?A.enable?e.remoteVideoTrack.player.enterFullscreen():e.remoteVideoTrack.player.exitFullscreen():Promise.reject(new Ct({code:Ge.INVALID_OPERATION,message:"no available remote video"}))}switchPlaybackQuality(A){return DA(this,null,function*(){let e=A.trtcInstance;return e._playbackQualitySwitcher||(e._playbackQualitySwitcher=new HeA),e._playbackQualitySwitcher.switchPlaybackQuality(A)})}prelink(A){return DA(this,null,function*(){let{trtcInstance:e}=A;return A.enable?e.room.prelink(A.sdkAppId,A.userId,A.userSig,EG.frameWorkType,A.roomId,A.strRoomId):e.room.closePrelink()})}};vt([C4({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"}}})],IK.prototype,"enableAudioFrameEvent"),vt([C4({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"}}})],IK.prototype,"prelink");var VeA=new IK,qeA=es(hg(),1),KeA=class extends qeA.EventEmitter{constructor(){super(),G(this,"states",{}),G(this,"permissionChangeHandler"),G(this,"log"),this.log=nA.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var A,e;this.emit("permission-state-change",{camera:(A=this.states.camera)==null?void 0:A.state,microphone:(e=this.states.microphone)==null?void 0:e.state})}}request(A){return DA(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(e=>e.stop())})}get(A){return DA(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(e){return this.log.error("get ".concat(A," permission failed, error: ").concat(e instanceof Error?e.message:e)),null}})}destroy(){Object.values(this.states).forEach(A=>{A?.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Vx=new KeA,z4=0,cG=new Set,Dg=null;iO(J4),yA.checkStorage();var Qo=class td extends XV.EventEmitter{constructor(e,o){super(),G(this,"_room"),G(this,"_eventListened",new Set),G(this,"_localVideoTrack",null),G(this,"_localAudioTrack",null),G(this,"_localScreenTrack",null),G(this,"_localScreenAudioTrack",null),G(this,"_localVideoConfig",null),G(this,"_localScreenConfig",null),G(this,"_localAudioConfig",null),G(this,"_remoteVideoConfigMap",new Map),G(this,"_remoteAudioConfigMap",new Map),G(this,"_remoteAudioVolumeMap",new Map),G(this,"_remoteAudioMuteMap",new Map),G(this,"_mediaTrackMap",new WeakMap),G(this,"_log",nA.createLogger({id:"t".concat(++z4)})),G(this,"_plugins",new Map),G(this,"_networkQuality",null),G(this,"_speakerId"),G(this,"enterRoomParams"),G(this,"_enableAutoSwitchWhenRecapturing",!0),G(this,"_autoSubscribeDataChannel",!1),G(this,"_playbackQualityList",[]),this._room=new e(bt({logger:this._log,frameWorkType:td.frameWorkType},o)),this._room.videoDecodeFallbackType=o.videoDecodeFallback,rn(o.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=o.enableAutoSwitchWhenRecapturing),this._log.info("create() ".concat(JSON.stringify(o,(n,a)=>n==="plugins"?a.map(I=>I.Name):a))),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(n){return this._room.audioManager.dump(n)}}}),o.plugins&&o.plugins.forEach(n=>{this._use(n,o.assetsPath)}),this._use(beA,o.assetsPath),this._use(keA,o.assetsPath),this._use(LeA,o.assetsPath),this._use(W4,o.assetsPath),this._use(YeA),o.enableSEI&&FT&&this._use(OeA),this._room.on("audio-volume",n=>{var a,I;!n.find(c=>c.userId==="")&&this._localAudioTrack&&n.push({userId:"",volume:Math.floor(100*((a=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?a:this._localAudioTrack.getAudioLevel())),floatVolume:(I=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?I:this._localAudioTrack.getInternalAudioLevel()}),o.volumeType===1&&n.forEach(c=>{var u;let d=c.userId===""?this._localAudioTrack:(u=this.room.remotePublishedUserMap.get(c.userId))==null?void 0:u.remoteAudioTrack;d&&(c.volume=d.dbVolume)}),o.enableDbVolume&&n.forEach(c=>{var u;let d=c.userId===""?this._localAudioTrack:(u=this.room.remotePublishedUserMap.get(c.userId))==null?void 0:u.remoteAudioTrack;d&&(c.volume=d.dbVolume)}),this.emit(Xt.AUDIO_VOLUME,{result:n.sort((c,u)=>u.volume-c.volume)})}),this._room.videoManager.on("error",n=>{this._log.error(new vi({code:Si.OPERATION_FAILED,extraCode:5504,message:n.message,originError:n}))}),this._listenEvents(),this._initActiveSpeaker(),((n,a)=>{let{emit:I}=n;n.emit=function(){for(var c=arguments.length,u=new Array(c),d=0;d{u&&nA.info(eC)})}})();let n=new $Q(e,o||{});return aG.add(n),n.__v_skip=!0,n}get room(){return this._room}_listenEvents(){nE(this,this._room).add("peer-join",e=>{let{userId:o}=e;this.emit(Xt.REMOTE_USER_ENTER,{userId:o})}).add("peer-leave",e=>{let{userId:o,reason:n}=e;this.emit(Xt.REMOTE_USER_EXIT,{userId:o,reason:n})}).add("banned",e=>{wu(!0),this._exitRoom().finally(()=>{this.emit(Xt.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(Xt.ERROR,vi.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(Xt.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let o=fi(bt({},e),{uplinkRTT:Math.min(e.uplinkRTT,OR),downlinkRTT:Math.min(e.downlinkRTT,OR)});this.emit(Xt.NETWORK_QUALITY,o)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{nE(o,o).add("player-state-changed",n=>{let a=fi(bt({},n),{userId:e.userId});o.kind===fA.VIDEO&&(a.streamType=cl(o.streamType)),this.emit(o.kind===fA.AUDIO?Xt.AUDIO_PLAY_STATE_CHANGED:Xt.VIDEO_PLAY_STATE_CHANGED,a)}).add("error",n=>{n.getCode()===Ge.PLAY_NOT_ALLOWED&&this.emit(Xt.AUTOPLAY_FAILED,{userId:o.userId,mediaType:o.strMediaType,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{pr(o)})}).add("remote-publish-state-changed",e=>{let{prevMuteState:o,muteState:n}=e,{userId:a}=n,I=o.audioAvailable,c=o.videoAvailable,{audioAvailable:u,videoAvailable:d}=n;u||this._remoteAudioConfigMap.delete(a),d||this._removeRemoteVideoConfig(a,"main"),n.hasAuxiliary||this._removeRemoteVideoConfig(a,"sub"),c!==d&&(d?this._onVideoAvailable({userId:a,streamType:"main"}):this._onVideoUnavailable({userId:a,streamType:"main"}),this.emit(d?Xt.REMOTE_VIDEO_AVAILABLE:Xt.REMOTE_VIDEO_UNAVAILABLE,{userId:a,streamType:"main"})),I!==u&&(u?this._onAudioAvailable({userId:a}):this._onAudioUnavailable({userId:a,muteState:n}),this.emit(u?Xt.REMOTE_AUDIO_AVAILABLE:Xt.REMOTE_AUDIO_UNAVAILABLE,{userId:a})),o.hasAuxiliary!==n.hasAuxiliary&&(n.hasAuxiliary?this._onVideoAvailable({userId:a,streamType:"sub"}):this._onVideoUnavailable({userId:a,streamType:"sub"}),this.emit(n.hasAuxiliary?Xt.REMOTE_VIDEO_AVAILABLE:Xt.REMOTE_VIDEO_UNAVAILABLE,{userId:a,streamType:"sub"})),o.hasDatachannel!==n.hasDatachannel&&n.hasDatachannel&&this._onDataChannelAvailable()}).add("sei-message",e=>{this.emit(Xt.SEI_MESSAGE,fi(bt({},e),{streamType:cl(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(Xt.ERROR,new vi({code:Si.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,I,c,u,d;let R={2:"big",3:"small",7:"sub"},k={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,OR),upLoss:((I=this._networkQuality)==null?void 0:I.uplinkLoss)||0,downLoss:((c=this._networkQuality)==null?void 0:c.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((d=e.msg_up_stream_info.msg_audio_status)==null?void 0:d.uint32_audio_level)||0)/iE},video:e.msg_up_stream_info.msg_video_status.filter(_=>R[_.uint32_video_stream_type]).map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_enc_fps,videoType:R[_.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(_=>({userId:_.msg_user_info.str_identifier,audio:{bitrate:(_.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(_.msg_audio_status.uint32_audio_level||0)/iE,point2pointDelay:(_.msg_audio_status.uint32_audio_p2p_delay||0)+(_.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:_.msg_audio_status.uint32_audio_cache_ms||0},video:_.msg_video_status.map(Z=>({bitrate:(Z.uint32_video_codec_bitrate||0)/1e3,width:Z.uint32_video_width,height:Z.uint32_video_height,frameRate:Z.uint32_video_dec_fps,videoType:R[Z.uint32_video_stream_type],point2pointDelay:(Z.uint32_video_p2p_delay||0)+(Z.uint32_video_cache_ms||0),jitterBufferDelay:Z.uint32_video_cache_ms||0,codec:Z.uint32_video_codec}))}))};this.emit(Xt.STATISTICS,k)}).add("custom-message",e=>{this.emit(Xt.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(Xt.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(Xt.FIRST_VIDEO_FRAME,fi(bt({},e),{streamType:cl(e.streamType)}))}).add("audio-frame",e=>{this.emit(Xt.AUDIO_FRAME,e)}).add("data-channel-message",e=>{var o,n,a,I,c;let{data:u}=e;if(u.sender==="")return;let d={segmentId:(o=u.payload)==null?void 0:o.roundid,speakerUserId:u.sender,sourceText:(n=u.payload)==null?void 0:n.text,translationTexts:(a=u.payload)==null?void 0:a.translate_msg,timestamp:(I=u.payload)==null?void 0:I.start_utc_ms,isCompleted:(c=u.payload)==null?void 0:c.end,robotId:u.robotid};d.sourceText!==""&&this.emit(Xt.REALTIME_TRANSCRIBER_MESSAGE,d)}).add("asr-robot-peer-join",e=>{this.emit(Xt.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"started",roomId:this.room.roomId,transcriberRobotId:e.userId})}).add("asr-robot-peer-leave",e=>{this.emit(Xt.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"stopped",roomId:this.room.roomId,transcriberRobotId:e.userId})}),nE(this,vs).add("audioInputAdded",e=>{this.emit(Xt.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(Xt.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(Xt.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(Xt.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>DA(this,null,function*(){if(this.emit(Xt.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Dg&&Dg.deviceId===UR){let o=(yield Mm()).find(n=>n.deviceId===UR);o&&Dg.groupId!==o.groupId&&(Dg=o,this.emit(Xt.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}))}})).add("audioOutputRemoved",e=>DA(this,null,function*(){this.emit(Xt.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let o=(yield Mm())[0];if(!o||!Dg||Dg.groupId===o.groupId)return;let n=Dg.deviceId===e.deviceId,a=Dg.deviceId===UR&&Dg.deviceId===o.deviceId;(n||a)&&(Dg=o,this.emit(Xt.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}))})),nE(this,Ux).add("permission-state-change",e=>{this.emit(Xt.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(Xt.SEI_MESSAGE,e=>{var o;let n=(o=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:o.remoteVideoTrack;n&&n.updateAlphaRenderInfo(e)})}getNetworkTime(){return gh()}use(e){let o,n;return"plugin"in e?(o=e.plugin,n=e.assetsPath):o=e,o.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(o,n)}_use(e,o){let n=this._plugins.get(e.Name);if(n)return this._log.warn("duplicate install plugin",e.Name),n;let a=new e(deA.call(this,{TRTC:$Q,room:this._room,assetsPath:o,errorModule:{RtcError:vi,ErrorCode:Si,CoreErrorCode:Ge,ErrorCodeDictionary:Rx}}));return this._plugins.set(e.Name,a),a.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),a}enterRoom(e){return DA(this,null,function*(){var o,n;this.enterRoomParams=e;let{scene:a="rtc",enableAutoPlayDialog:I=!0,autoReceiveAudio:c=!0,autoReceiveVideo:u=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Sr(e.proxy)&&e.proxy.turnServer&&((n=(o=this._room).setTurnServer)==null||n.call(o,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=I,this._room.autoReceiveAudio=c,this._room.autoReceiveVideo=u,rn(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let d={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,enableDataChannel:this._plugins.has("RealtimeTranscriber"),frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(d,a,$Q.frameWorkType),this._checkTrackToPublish(),U4.start()})}exitRoom(){return DA(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return DA(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(o){if(!(o instanceof VU)||o.code!==Ge.API_CALL_TIMEOUT&&o.code!==Ge.SWITCH_ROOM_FAILED)throw o;this._log.warn("switchRoom ".concat(o.code===Ge.API_CALL_TIMEOUT?"timeout":"failed",", fallback to exitRoom() and enterRoom()")),yield this._rejoinRoom(e)}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return DA(this,null,function*(){yield this.exitRoom();let o=bt(bt({},this.enterRoomParams),e);yield this.enterRoom(o)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let o=e.includes("main")?"main":"sub",n=e.split("_".concat(o))[0];n&&this._stopRemoteVideo({userId:n,streamType:o}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),function(e){let o=PM.get(e);o&&(o.forEach(n=>clearTimeout(n)),PM.delete(e))}(this),this._room.remotePublishedUserMap.forEach(e=>{pr(e.remoteAudioTrack),pr(e.remoteVideoTrack),pr(e.remoteAuxiliaryTrack)})}switchRole(e,o){return DA(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(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(e=>{var o;return(o=e.destroy)==null?void 0:o.call(e)}),this._plugins.clear(),pr(this),this.removeAllListeners(),this._room.destroy(),aG.delete(this),aG.size===0&&U4.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),S.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return DA(this,arguments,function(){var e=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn("local audio is already started");let{publish:n=!0,mute:a,muteKeepVolumeDetection:I,option:c}=o,u=new vm(e._room.audioManager),d={},R={muted:!0};c&&(Ee(c.microphoneId)?Ee(c.audioTrack)||(d.customSource=c.audioTrack):d.deviceId=c.microphoneId,c&&hr(c.captureVolume)&&u.setCaptureVolume(c.captureVolume),Ee(c.profile)||(Sr(c.profile)?dQ[c.profile]&&u.setProfile(dQ[c.profile]):u.setProfile(c.profile)),hr(c.earMonitorVolume)&&(R.muted=!(c.earMonitorVolume>0),R.volume=c.earMonitorVolume),Ee(c.echoCancellation)||(u.profile.echoCancellation=c.echoCancellation),Ee(c.noiseSuppression)||(u.profile.noiseSuppression=c.noiseSuppression),Ee(c.autoGainControl)||(u.profile.autoGainControl=c.autoGainControl),rn(e._enableAutoSwitchWhenRecapturing)&&(u.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),u.on("5",k=>{e.emit(Xt.ERROR,new vi({code:Si.DEVICE_ERROR,extraCode:5309,messageParams:{error:k}}))}),u.on("2",k=>{e.emit(Xt.DEVICE_CHANGED,{type:"microphone",action:"active",device:k})}),u.on("4",k=>{let _;k.error&&(_=vi.convertFrom(k.error)),e.emit(Xt.PUBLISH_STATE_CHANGED,fi(bt({},k),{error:_}))}),u.on("6",()=>{}),e._listenOutputTrackChanged(u),e._speakerId&&u.setAudioOutput(e._speakerId),yield u.capture(d),Ee(a)||u.setMute(a,I),nE(u,u).add("player-state-changed",k=>{e.emit(Xt.AUDIO_PLAY_STATE_CHANGED,fi(bt({},k),{userId:""}))}),n&&e._room.isJoined&&e._room.publish(u).catch(()=>{}),e._localAudioTrack=u,e._room.capturedLocalMainAudioTrack=u,e._localAudioConfig=fi(bt({},o),{publish:n}),yield e._updateAudioPlayOption({playOption:R,track:u}),S.emit("113",{userId:"",room:e.room})}()})}updateLocalAudio(e){return DA(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:o,mute:n,muteKeepVolumeDetection:a,option:I}=e,c={};I&&(I.microphoneId?yield this._localAudioTrack.switchDevice(I.microphoneId):Ee(I.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(I.audioTrack)),Ee(I.captureVolume)||this._localAudioTrack.setCaptureVolume(I.captureVolume),Ee(I.earMonitorVolume)||(c.muted=!(I.earMonitorVolume>0),c.volume=I.earMonitorVolume),yield this._localAudioTrack.update3A(I)),this._room.isJoined&&!Ee(o)&&(o&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!o&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),Ee(n)||this._localAudioTrack.setMute(n,a),yield this._updateAudioPlayOption({playOption:c,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),tB(this._localAudioConfig,e)})}stopLocalAudio(){return DA(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),S.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),pr(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,delete this._room.capturedLocalMainAudioTrack)})}startLocalVideo(){return DA(this,arguments,function(){var e=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0,view:null,capture:!0};return function*(){var n,a,I;if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:c,publish:u=!0,capture:d=!0,mute:R,option:k,forcePublish:_=!1}=o,Z=u||_,iA=d,cA=new Ru(e._room.videoManager),TA={},JA={};if(k&&(rn(k.avoidCropping)&&(cA.avoidCropping=k.avoidCropping),k.cameraId?TA.deviceId=k.cameraId:Ee(k.useFrontCamera)?Ee(k.videoTrack)||(TA.customSource=k.videoTrack):TA.facingMode=k.useFrontCamera?fA.FACING_MODE_USER:fA.FACING_MODE_ENVIRONMENT,Ee(k.retryWhenExactFailed)||(TA.retryWhenExactFailed=k.retryWhenExactFailed),k.qosPreference&&(TA.contentHint=Mx(k.qosPreference)),Ee(k.profile)||(Sr(k.profile)?$l[k.profile]&&cA.setProfile($l[k.profile]):cA.setProfile(k.profile)),Ee(k.fillMode)||(JA.objectFit=k.fillMode),Ee(k.mirror)||(JA.mirror=k.mirror),Ee(k.small)||(Ee(k.smallMode)||(e._room.smallMode=k.smallMode),rn(k.small)&&k.small===!1?cA.stopSmall():cA.updateSmallConfig(Sx(k.small,!0))),Ee(k.rotation)||cA.setRotation(k.rotation),rn(e._enableAutoSwitchWhenRecapturing)&&(cA.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),cA.once("first-video-frame",Ie=>{e.emit(Xt.FIRST_VIDEO_FRAME,fi(bt({},Ie),{streamType:cl(Ie.streamType)}))}),cA.on("5",Ie=>{e.emit(Xt.ERROR,new vi({code:Si.DEVICE_ERROR,extraCode:5308,messageParams:{error:Ie}}))}),cA.on("2",Ie=>{e.emit(Xt.DEVICE_CHANGED,{type:"camera",action:"active",device:Ie})}),cA.on("4",Ie=>{let XA;Ie.error&&(XA=vi.convertFrom(Ie.error)),e.emit(Xt.PUBLISH_STATE_CHANGED,fi(bt({},Ie),{error:XA}))}),cA.on("6",()=>{}),e._listenOutputTrackChanged(cA),TA.customSource&&DQ(TA.customSource)?(cA.setOutputMediaStreamTrack(TA.customSource),iA=!1):iA?yield cA.capture(TA):(n=cA.manager)==null||n.changeInput(cA),Ee(R)||(yield cA.setMute(R)),nE(cA,cA).add("player-state-changed",Ie=>{e.emit(Xt.VIDEO_PLAY_STATE_CHANGED,fi(bt({},Ie),{userId:"",streamType:"main"}))}).add("video-size-changed",Ie=>{e.emit(Xt.VIDEO_SIZE_CHANGED,fi(bt({},Ie),{streamType:cl(Ie.streamType)}))}),Z){let Ie=e._localScreenTrack&&((a=e._localScreenConfig)==null?void 0:a.publish)&&e._localScreenConfig.streamType==="main";e._room.isJoined?!Ie||_?(e._room.publish(cA).catch(()=>{}),((I=e._localScreenConfig)==null?void 0:I.streamType)==="main"&&e._localScreenConfig&&(e._localScreenConfig.publish=!1)):(Z=!1,e._log.warn("main stream is already published, local video track will not publish")):Ie&&(Z=!1)}e._localVideoTrack=cA,e._room.capturedLocalMainVideoTrack=cA,e._localVideoConfig=fi(bt({},o),{view:c,publish:Z,capture:iA}),yield e._updateVideoPlayOption({view:c,playOption:JA,track:cA})}()})}updateLocalVideo(e){return DA(this,null,function*(){var o,n,a,I,c,u,d;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:R,publish:k=!0,mute:_,capture:Z,option:iA,forcePublish:cA=!1}=e,TA=k||cA,JA=Z,Ie={};if(!this._localVideoConfig.capture&&DQ((o=this.localVideoTrack)==null?void 0:o.outMediaTrack)&&(iA!=null&&iA.cameraId||iA!=null&&iA.videoTrack)&&this._localVideoTrack.outMediaTrack!==iA?.videoTrack&&(JA=!0),this._localVideoConfig.capture)JA!==!1?iA!=null&&iA.cameraId?yield this._localVideoTrack.switchDevice(iA?.cameraId):Ee(iA?.useFrontCamera)?Ee(iA?.videoTrack)||(DQ(iA?.videoTrack)?iA?.videoTrack!==((n=this.localVideoTrack)==null?void 0:n.outMediaTrack)&&(yield this._localVideoTrack.setOutputMediaStreamTrack(iA?.videoTrack)):yield this._localVideoTrack.setInputMediaStreamTrack(iA?.videoTrack)):yield this._localVideoTrack.switchDevice(iA!=null&&iA.useFrontCamera?fA.FACING_MODE_USER:fA.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(JA){let XA={};XA.deviceId=iA?.cameraId||((a=this._localVideoConfig.option)==null?void 0:a.cameraId),XA.facingMode=iA!=null&&iA.useFrontCamera||(I=this._localVideoConfig.option)!=null&&I.useFrontCamera?fA.FACING_MODE_USER:fA.FACING_MODE_ENVIRONMENT,XA.customSource=iA!=null&&iA.videoTrack||!XA.deviceId?(c=this._localVideoConfig.option)==null?void 0:c.videoTrack:void 0,yield this._localVideoTrack.capture(XA)}iA&&(Ee(iA.profile)||(Sr(iA.profile)?$l[iA.profile]&&this._localVideoTrack.setProfile($l[iA.profile]):this._localVideoTrack.setProfile(iA.profile),(!iA.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(iA.cameraId||iA.useFrontCamera?fA.FACING_MODE_USER:fA.FACING_MODE_ENVIRONMENT))&&(yield this._localVideoTrack.applyProfile())),Ee(iA.fillMode)||(Ie.objectFit=iA.fillMode),Ee(iA.mirror)||(Ie.mirror=iA.mirror),Ee(iA.rotation)||this._localVideoTrack.setRotation(iA.rotation),iA.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(Mx(iA.qosPreference)),Ee(iA.small)||(rn(iA.small)&&!iA.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(Sx(iA.small,!0)))),this._room.isJoined&&Ee(TA)&&this._localVideoConfig.publish&&JA&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((TA??this._localVideoConfig.publish)||cA?this._localScreenTrack&&((u=this._localScreenConfig)!=null&&u.publish)&&this._localScreenConfig.streamType==="main"&&!cA?(TA=!1,this._log.warn("main stream is already published, local video track will not publish")):(this._room.publish(this._localVideoTrack).catch(()=>{}),((d=this._localScreenConfig)==null?void 0:d.streamType)==="main"&&this._localScreenConfig&&(this._localScreenConfig.publish=!1)):this._room.unpublish(this._localVideoTrack).catch(()=>{})),Ee(_)||(yield this._localVideoTrack.setMute(_)),yield this._updateVideoPlayOption({view:R,playOption:Ie,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),tB(this._localVideoConfig,fi(bt({},e),{publish:TA,capture:JA}))})}stopLocalVideo(){return DA(this,null,function*(){var e;this._localVideoTrack&&(this._room.isJoined&&(e=this._localVideoConfig)!=null&&e.publish&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),pr(this._localVideoTrack),this._localVideoTrack=null,delete this._room.capturedLocalMainVideoTrack,this._localVideoConfig=null)})}startScreenShare(){return DA(this,arguments,function(){var e=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0,view:null};return function*(){var n,a,I;if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:c=null,publish:u=!0,muteSystemAudio:d,option:R}=o,k=u,_=new Nm(e._room.videoManager);_.on("4",JA=>{let Ie;JA.error&&(Ie=vi.convertFrom(JA.error)),e.emit(Xt.PUBLISH_STATE_CHANGED,fi(bt({},JA),{error:Ie}))}),_.once("first-video-frame",JA=>{e.emit(Xt.FIRST_VIDEO_FRAME,fi(bt({},JA),{streamType:cl(JA.streamType)}))}),e._listenOutputTrackChanged(_),o.streamType==="main"&&(_.mediaType=4);let Z=null,iA={},cA={};R&&(Ee(R.profile)||(Sr(R.profile)?QN[R.profile]&&_.setProfile(QN[R.profile]):_.setProfile(R.profile)),R.systemAudio&&(iA.systemAudio=!0,iA.echoCancellation=R.echoCancellation,iA.noiseSuppression=R.noiseSuppression,iA.autoGainControl=R.autoGainControl),Ee(R.fillMode)||(cA.objectFit=R.fillMode),R.videoTrack&&(iA.videoTrack=R.videoTrack),R.audioTrack&&(iA.audioTrack=R.audioTrack),R.captureElement&&(iA.captureElement=R.captureElement),R.preferDisplaySurface&&(iA.preferDisplaySurface=R.preferDisplaySurface),R.qosPreference&&(iA.contentHint=Mx(R.qosPreference)));let TA=yield _.capture(iA);if(_.mediaTrack.addEventListener(fA.ENDED,()=>{e._stopScreenShare(),e.emit(Xt.SCREEN_SHARE_STOPPED)}),TA.getAudioTracks()[0]){Z=new xq(e._room.audioManager);let JA=TA.getAudioTracks()[0];(n=o.option)!=null&&n.systemAudio&&!((a=o.option)!=null&&a.audioTrack)&&(Z.sourceTrack=JA),yield Z.setInputMediaStreamTrack(JA),rn(d)&&Z.mediaTrack&&(Z.mediaTrack.enabled=!d),e._speakerId&&Z.setAudioOutput(e._speakerId)}if(nE(_,_).add("player-state-changed",JA=>{e.emit(Xt.VIDEO_PLAY_STATE_CHANGED,fi(bt({},JA),{userId:"",streamType:"sub"}))}),k){let JA=e._localVideoTrack&&((I=e._localVideoConfig)==null?void 0:I.publish),Ie=!(o.streamType==="main"&&JA);e._room.isJoined?(Ie?e._room.publish(_).catch(()=>{}):(k=!1,e._log.warn("main stream is already published, screen share main will not publish")),Z&&(e._checkScreenAudioEchoCancellation(_,Z),e._room.publish(Z).catch(()=>{}))):Ie||(k=!1)}e._localScreenTrack=_,e._room.capturedLocalAuxVideoTrack=_,e._localScreenAudioTrack=Z,e._localScreenConfig=fi(bt({},o),{view:c,publish:k}),yield e._updateVideoPlayOption({view:c,playOption:cA,track:_})}()})}updateScreenShare(e){return DA(this,null,function*(){var o,n;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:a,publish:I,muteSystemAudio:c,option:u}=e,d=I,R={};if(u){if(Ee(u.fillMode)||(R.objectFit=u.fillMode),u.qosPreference){let k=Mx(u.qosPreference);this._localScreenTrack.setContentHint(k)}u.videoTrack&&this._localScreenTrack.setInputMediaStreamTrack(u.videoTrack),u.audioTrack&&this._localScreenAudioTrack&&this._localScreenAudioTrack.setInputMediaStreamTrack(u.audioTrack)}if(this._room.isJoined&&!Ee(d)){if(d&&!this._localScreenConfig.publish){let k=this._localVideoTrack&&((o=this._localVideoConfig)==null?void 0:o.publish);this._localScreenConfig.streamType==="main"&&k?(d=!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&&!d){let k=[this._localScreenTrack];this._localScreenAudioTrack&&k.push(this._localScreenAudioTrack),k.forEach(_=>this._room.unpublish(_).catch(()=>{}))}}(n=this._localScreenAudioTrack)!=null&&n.mediaTrack&&rn(c)&&(this._localScreenAudioTrack.mediaTrack.enabled=!c),yield this._updateVideoPlayOption({view:a,playOption:R,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),tB(this._localScreenConfig,fi(bt({},e),{publish:d}))})}stopScreenShare(){return DA(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return DA(this,null,function*(){let{view:o,userId:n,streamType:a,option:I}=e,c="".concat(n,"_").concat(a);if(this._remoteVideoConfigMap.has(c))return void this._log.warn("remote video has already started. userId:".concat(n,", streamType:").concat(a));let u=this._room.remotePublishedUserMap.get(n);if(!u)return;let d={},R=a==="main"?u.remoteVideoTrack:u.remoteAuxiliaryTrack,k=this._bindRemoteVideoTrackEvents(R);this._listenOutputTrackChanged(R),I&&(Ee(I.fillMode)||(d.objectFit=I.fillMode),Ee(I.mirror)||(d.mirror=I.mirror),Ee(I.poster)||(d.poster=I.poster),d.canvasRender=I.canvasRender,a==="main"&&!Ee(I.small)&&(!u.remoteVideoTrack.isSubscribing&&!u.remoteVideoTrack.isSubscribed&&u.remoteVideoTrack.setMediaType(I.small?8:4),this._room.changeType(I.small,R.user)),Ee(I.draggable)||R.setDraggable(I.draggable)),d.isLiveStream=!!this._playbackQualityList.find(_=>_.userId===n&&_.streamType===a),yield this._room.subscribe(R),yield this._enableVideoDecodeFallback(R,a),yield this._updateVideoPlayOption({view:o,playOption:d,track:R}),this._emitTrackEvent(R),this._remoteVideoConfigMap.set(c,{config:e,handlers:k}),I&&!Ee(I.receiveWhenViewVisible)&&this._observeView({remoteTrack:R,view:o,receiveWhenViewVisible:I.receiveWhenViewVisible,viewRoot:I?.viewRoot})})}updateRemoteVideo(e){return DA(this,null,function*(){var o,n;let{view:a,userId:I,streamType:c,option:u,mute:d}=e,R="".concat(I,"_").concat(c),k=this._remoteVideoConfigMap.get(R);if(!k||!this._room.remotePublishedUserMap.has(I))return;let _={};u&&(Ee(u.fillMode)||(_.objectFit=u.fillMode),Ee(u.mirror)||(_.mirror=u.mirror));let Z=null,iA=this._room.remotePublishedUserMap.get(I);if(c==="main"&&iA!=null&&iA.muteState.hasVideo&&(Z=iA.remoteVideoTrack),c==="sub"&&iA!=null&&iA.muteState.hasAuxiliary&&(Z=iA.remoteAuxiliaryTrack),!Z)return;let{config:cA}=k;c==="main"&&u&&!Ee(u.small)&&this._room.changeType(u.small,Z.user),u&&!Ee(u.draggable)&&Z.setDraggable(u.draggable),u&&(rn(u.pictureInPicture)&&(u.pictureInPicture?yield Z.player.enterPictureInPicture():yield Z.player.exitPictureInPicture()),rn(u.fullScreen)&&(u.fullScreen?yield Z.player.enterFullscreen():yield Z.player.exitFullscreen())),rn(d)&&(Z.ignoreUpdatePlayingState=!0,d?(yield Z.player.pause(),yield this.room.unsubscribe(Z)):(yield this.room.subscribe(Z),yield Z.player.resume(!0))),yield this._updateVideoPlayOption({view:a,playOption:_,track:Z,prevConfig:cA}),tB(cA,e);let TA=Ee(u?.receiveWhenViewVisible)?(o=cA.option)==null?void 0:o.receiveWhenViewVisible:u.receiveWhenViewVisible,JA=Ee(a)?cA.view:a,Ie=Ee(u?.viewRoot)?(n=cA.option)==null?void 0:n.viewRoot:u.viewRoot;this._observeView({remoteTrack:Z,view:JA,receiveWhenViewVisible:TA,viewRoot:Ie})})}stopRemoteVideo(e){return DA(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return DA(this,null,function*(){let n=[],a=this._room.remotePublishedUserMap.get(e.userId);if(a){let{muteState:I,remoteVideoTrack:c,remoteAuxiliaryTrack:u}=a;e.streamType==="main"&&(c.stop(),I.hasVideo&&n.push(c)),e.streamType==="sub"&&(u.stop(),I.hasAuxiliary&&n.push(u))}for(let I of n)o&&(delete I.ignoreUpdatePlayingState,yield this._room.unsubscribe(I),this._mediaTrackMap.delete(I.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,o){let n="".concat(e,"_").concat(o),a=this._remoteVideoConfigMap.get(n);if(a&&(a.observer&&a.observer.disconnect(),a.handlers)){let I=this._room.remotePublishedUserMap.get(e);if(I){let c=o==="main"?I.remoteVideoTrack:I.remoteAuxiliaryTrack;this._unbindRemoteVideoTrackEvents(c,a.handlers)}}this._remoteVideoConfigMap.delete(n)}_bindRemoteVideoTrackEvents(e){let o={onEnterPIP:()=>DA(this,null,function*(){yield e.player.enterPIPPromise,this.emit(Xt.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:cl(e.streamType),userId:e.userId,isPictureInPicture:!0,pictureInPictureWindow:e.player.pipWindow})}),onLeavePIP:()=>{this.emit(Xt.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:cl(e.streamType),userId:e.userId,isPictureInPicture:!1})},onEnterFullScreen:()=>{this.emit(Xt.FULL_SCREEN_STATE_CHANGED,{streamType:cl(e.streamType),userId:e.userId,isFullScreen:!0})},onLeaveFullScreen:()=>{this.emit(Xt.FULL_SCREEN_STATE_CHANGED,{streamType:cl(e.streamType),userId:e.userId,isFullScreen:!1})},onDecodeFailed:()=>{this.emit(Xt.ERROR,new vi({code:Si.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))},onVideoSizeChanged:n=>{this.emit(Xt.VIDEO_SIZE_CHANGED,fi(bt({},n),{streamType:cl(n.streamType)}))}};return e.player.on(mi.ENTER_PICTURE_IN_PICTURE,o.onEnterPIP),e.player.on(mi.LEAVE_PICTURE_IN_PICTURE,o.onLeavePIP),e.player.on(mi.ENTER_FULL_SCREEN,o.onEnterFullScreen),e.player.on(mi.LEAVE_FULL_SCREEN,o.onLeaveFullScreen),e.on("decode-failed",o.onDecodeFailed),e.on("video-size-changed",o.onVideoSizeChanged),o}_unbindRemoteVideoTrackEvents(e,o){e.player.off(mi.ENTER_PICTURE_IN_PICTURE,o.onEnterPIP),e.player.off(mi.LEAVE_PICTURE_IN_PICTURE,o.onLeavePIP),e.player.off(mi.ENTER_FULL_SCREEN,o.onEnterFullScreen),e.player.off(mi.LEAVE_FULL_SCREEN,o.onLeaveFullScreen),e.off("decode-failed",o.onDecodeFailed),e.off("video-size-changed",o.onVideoSizeChanged)}muteRemoteAudio(e,o){return DA(this,null,function*(){this._remoteAudioMuteMap.set(e,o);try{if(e==="*")if(o)yield this._stopRemoteAudio({userId:e});else{let n=[...this._room.remotePublishedUserMap.values()];for(let a of n)a.muteState.hasAudio&&!this._remoteAudioConfigMap.has(a.userId)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:a.userId}))}else o?yield this._stopRemoteAudio({userId:e}):!this._remoteAudioConfigMap.has(e)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:e}))}catch(n){throw n.code!==Si.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),n}})}setRemoteAudioVolume(e,o){if(e==="*"){this._remoteAudioVolumeMap.set("*",o),this._remoteAudioVolumeMap.forEach((a,I)=>this._remoteAudioVolumeMap.set(I,o));let n=[...this._room.remotePublishedUserMap.values()];for(let a of n)this._remoteAudioVolumeMap.set(a.userId,o),a.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:o},track:a.remoteAudioTrack})}else if(e){let n=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,o),n&&n.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:o},track:n.remoteAudioTrack})}}startPlugin(e,o){return DA(this,null,function*(){return e.start(o)})}updatePlugin(e,o){return DA(this,null,function*(){return e.update(o)})}stopPlugin(e,o){return DA(this,null,function*(){return e.stop(o)})}enableAudioVolumeEvaluation(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3,o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this._room.enableAudioVolumeEvaluation(e,o)}on(e,o,n){if(this.listeners(e).includes(o))return this;if(this._log.debug("on",e),super.on(e,o,n),this._eventListened.add(e),this.listeners(Xt.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:a}=this.room.audioManager;a.get("")||a.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return e==="realtime-transcriber-message"&&this._room.subscribeDataChannel(),this}emit(e){for(var o=arguments.length,n=new Array(o>1?o-1:0),a=1;a{I?.abort("off")}),a.clear()}return this}getAudioTrack(){let e,o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userId:"",streamType:"main"},n=null,a="main",I=!1;if(Sr(o)?e=o:(e=o.userId,I=o.processed===!0,o.streamType&&(a=o.streamType)),e){let c=this._room.remotePublishedUserMap.get(e);c&&(n=c.remoteAudioTrack)}else n=a==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return n?I&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoTrack(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userId:"",streamType:"main"},{userId:o="",streamType:n="main",processed:a=!1}=e,I=null;if(o==="")n==="main"&&this._localVideoTrack&&(I=this._localVideoTrack),n==="sub"&&this._localScreenTrack&&(I=this._localScreenTrack);else{let c=this._room.remotePublishedUserMap.get(o);c&&(I=n==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack)}return I?a&&I.outMediaTrack&&I.outMediaTrack!==I.mediaTrack?I.outMediaTrack.clone():I.mediaTrack:null}getVideoSnapshot(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{userId:o,streamType:n="main"}=e;if(o){let a=this._room.remotePublishedUserMap.get(o);if(n==="main"&&a!=null&&a.muteState.hasVideo)return a.remoteVideoTrack.getVideoFrame();if(n==="sub"&&a!=null&&a.muteState.hasAuxiliary)return a.remoteAuxiliaryTrack.getVideoFrame()}else{if(n==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(n==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var o,n;this._speakerId=e,(o=this._localAudioTrack)==null||o.setAudioOutput(e),(n=this._localScreenAudioTrack)==null||n.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(a=>a.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return DA(this,null,function*(){(yield Mm()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(Xt.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),Dg=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($C,"/en/TRTC.html#.setCurrentSpeaker"))})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return DA(this,null,function*(){var o;let{userId:n}=e;if(this._remoteAudioConfigMap.has(n))return void this._log.warn("remote audio has already started. userId:".concat(n));let a=this._room.remotePublishedUserMap.get(n);if(!a)return;let I={},c=a.remoteAudioTrack;c.on("decode-failed",u=>{this.emit(Xt.ERROR,new vi({code:Si.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(c),this._speakerId&&c.setAudioOutput(this._speakerId);try{let u=(o=this._remoteAudioVolumeMap.get(n))!=null?o:this._remoteAudioVolumeMap.get("*"),d=hr(u)?u:100;I.volume=d,this._remoteAudioConfigMap.set(n,e),yield this._room.subscribe(c),Jn(Ln(c,"decode-failed"),Qc(Ln(c,Uo.INIT)),Ks(()=>{this.startPlugin(P4.Name,{track:c,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:I,track:c}),S.emit("115",{userId:n,room:this.room}),c.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:c.outMediaTrack,refId:"ra-".concat(n)})}catch(u){throw this._remoteAudioConfigMap.delete(n),u}this._emitTrackEvent(c)})}_stopRemoteAudio(e){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return DA(this,null,function*(){let n=this._room.remotePublishedUserMap.get(e.userId);n&&(n.remoteAudioTrack.stop(),n.muteState.hasAudio&&o&&(yield this._room.unsubscribe(n.remoteAudioTrack)),this._mediaTrackMap.delete(n.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId)),S.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:"ra-".concat(e.userId)})})}_enableVideoDecodeFallback(e,o){let n,a=this._room.videoDecodeFallbackType;a&&this._plugins.has("TRTCVideoDecoder")&&(e.log.debug("remote video will fall back when decode failed",e.id),Jn(Ln(e,"decode-failed"),Qc(Ln(e,Uo.INIT)),kq(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:a})}),hx(Ln(e,"decode-downgrade-state-changed")),Ks(I=>{n=I.state,this.emit(Xt.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,fi(bt({},I),{streamType:o,userId:e.userId}))},I=>{e.log.error("fallback",I)},()=>{n==="STARTED"&&e.log.info("fallback complete")})))}_updateVideoPlayOption(e){return DA(this,arguments,function(o){let{view:n,playOption:a,track:I,prevConfig:c}=o;return function*(){if(I.setMirror(a.mirror),Ee(n)&&c&&c.view&&!zR(a)){let u=Hf(c.view);u.length>0&&(yield I.play(u,a))}if(!Ee(n)){let u=Hf(n);u.length>0?yield I.play(u,a):I.stop()}}()})}_updateAudioPlayOption(e){return DA(this,arguments,function(o){var n=this;let{playOption:a={},track:I,prevConfig:c}=o;return function*(){if(!I.isPlayCalled)try{yield I.play(null,a)}catch{}if(Ee(a.muted)||I.setPlayerMute(a.muted),Ee(a.volume)||I.setAudioVolume(a.volume/100),I instanceof vm&&I.mediaTrack){let u=a.muted===!1&&!Ee(a.volume)&&a.volume>0?"add":"remove";n.room.audioManager.updateAudioReference({type:u,audioReference:I.mediaTrack,refId:"em"})}else if(I instanceof Dx){let u=a.muted?0:a.volume;if(Ee(u))return;n.room.audioManager.updateAudioReference({type:"updateVolume",refId:"ra-".concat(I.userId),volume:a.volume})}}()})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],n=e.isRemote?e.userId:"";e.outMediaTrack&&(o&&this._mediaTrackMap.get(e.outMediaTrack)===n||(this._mediaTrackMap.set(e.outMediaTrack,n),this.emit(Xt.TRACK,{userId:n,streamType:cl(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var e,o,n;let a=[];if((e=this._localAudioConfig)!=null&&e.publish&&this._localAudioTrack&&a.push(this._localAudioTrack),(o=this._localVideoConfig)!=null&&o.publish&&this._localVideoTrack&&a.push(this._localVideoTrack),(n=this._localScreenConfig)!=null&&n.publish&&(this._localScreenTrack&&a.push(this._localScreenTrack),this._localScreenAudioTrack&&a.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),a.length!==0)return Promise.all(a.map(I=>this._room.publish(I).catch(()=>{})))}_observeView(e){let{remoteTrack:o,view:n,receiveWhenViewVisible:a,viewRoot:I}=e;if(Ee(n)||Ee(a))return;let c=this._remoteVideoConfigMap.get("".concat(o.userId,"_").concat(cl(o.streamType)));if(!c)return;let u=c.observer||void 0;if(n===null||Aa(n)&&n.length===0||!a)return u?.disconnect(),void(o.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",o.userId,o.strMediaType),this._room.subscribe(o).catch(()=>{})));let d=c.visibleViewMap||new Map,R=-1;(!u||u.root!==I)&&(u?.disconnect(),d.clear(),u=new IntersectionObserver(_=>{_.forEach(Z=>{d.set(Z.target,Z.isIntersecting),o.log.info("view ".concat(Z.target.id," is").concat(Z.isIntersecting?"":" not"," visible"))}),clearTimeout(R),R=window.setTimeout(()=>{[...d.values()].find(Z=>Z)?o.isSubscribed||this._room.subscribe(o).catch(()=>{}):o.isSubscribed&&this._room.unsubscribe(o).catch(()=>{})},200)},{root:I}));let k=new Set(Hf(n));d.forEach((_,Z)=>{k.has(Z)||(u.unobserve(Z),d.delete(Z))}),k.forEach(_=>{d.set(_,!0),u.observe(_)}),u.takeRecords().forEach(_=>{d.set(_.target,_.isIntersecting)}),c.visibleViewMap=d,c.observer=u}_exitRoom(){return DA(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return DA(this,null,function*(){var e,o;if(this._localScreenTrack){if(this._room.isJoined){let n=[];(e=this._localScreenConfig)!=null&&e.publish&&n.push(this._localScreenTrack),this._localScreenAudioTrack&&n.push(this._localScreenAudioTrack),yield Promise.all(n.map(a=>this._room.unpublish(a).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),pr(this._localScreenTrack),this._localScreenTrack=null,delete this._room.capturedLocalAuxVideoTrack,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,o){return DA(this,null,function*(){var n,a;if(!e||!o)return;let I=(n=e.trackSettings)==null?void 0:n.displaySurface;if(((a=o.trackSettings)==null?void 0:a.echoCancellation)===!1&&(I==="monitor"||I==="browser"&&e.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(c){this._log.warn("start audioProcessor plugin failed: ",c)}}})}_onLocalTrackCaptured(e){let{track:o}=e;o.kind==="audio"&&(!Dg||HT(Dg))&&(this._initActiveSpeaker(),S.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return DA(this,null,function*(){if(Dg&&!HT(Dg))this.emit(Xt.DEVICE_CHANGED,{type:"speaker",action:"active",device:Dg});else{let e=yield Mm();e[0]&&!HT(e[0])?(Dg=e[0],this.emit(Xt.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):S.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable(e){let{userId:o}=e,n=this._remoteAudioMuteMap.has(o)?this._remoteAudioMuteMap.get(o):this._remoteAudioMuteMap.get("*");(n===!1||this._room.autoReceiveAudio&&!n)&&this._doStartRemoteAudio({userId:o}).catch(()=>{})}_onVideoAvailable(e){let{userId:o,streamType:n}=e;if(!this._room.autoReceiveVideo)return;let a=this._room.remotePublishedUserMap.get(o);if(a){let I=n==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack,c=[I];this._room.autoReceiveAudio&&a.remoteAudioTrack.isAvailable&&c.push(a.remoteAudioTrack),this._room.subscribe(...c).then(()=>{this._emitTrackEvent(I)}).catch(()=>{})}}_onAudioUnavailable(e){let{userId:o,muteState:n}=e;n.hasAudio&&n.audioMuted||this._stopRemoteAudio({userId:o},!1).catch(()=>{})}_onVideoUnavailable(e){let{userId:o,streamType:n}=e;this._stopRemoteVideo({userId:o,streamType:n},!1).catch(()=>{})}_onDataChannelAvailable(){if(this.listeners("realtime-transcriber-message").length>0)return this._room.subscribeDataChannel()}sendSEIMessage(e,o){var n;let a=this._plugins.get("SEI");a&&(a.update({buffer:e,options:fi(bt({seiPayloadType:243},o),{small:!((n=this._localVideoTrack)==null||!n.small)})}),ct.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var o,n;(n=(o=this._room).sendCustomMessage)==null||n.call(o,e),ct.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,o){return DA(this,null,function*(){return this._log.info("callExperimentalAPI(".concat(e,", ").concat(JSON.stringify(o),")")),GeA.call(e,bt({trtcInstance:this},o))})}static setLogLevel(e,o){nA.setLogLevel(e),Ee(o)||(o?nA.enableUploadLog():nA.disableUploadLog())}static isSupported(){return yT($Q.frameWorkType)}static getPermissions(e){return DA(this,arguments,function(o){let{request:n=!0,types:a=["camera","microphone"]}=o;return function*(){n&&(yield Ux.request(a).catch(u=>{var d;return nA.error("getPermissions request failed, error: ".concat((d=u?.message)!=null?d:u))}));let[I,c]=yield Promise.all([Ux.get("camera"),Ux.get("microphone")]);return{camera:I,microphone:c}}()})}static getCameraList(){return qQ(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getMicrophoneList(){return VQ(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getSpeakerList(){return Mm(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static setCurrentSpeaker(e){return DA(this,null,function*(){if(ra&&(e===iG.SPEAKER||e===iG.HEADSET)){let o=yield $Q.getMicrophoneList(),n="";return o.forEach(a=>{a.label===e&&(n=a.deviceId)}),n?void aG.forEach(a=>DA(null,null,function*(){a._localAudioTrack&&(yield a.updateLocalAudio({option:{microphoneId:n}}))})):void 0}(yield Mm()).forEach(o=>{o.deviceId===e&&(aG.forEach(n=>{n._setCurrentSpeaker(e),n.emit(Xt.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),Dg=o)})})}static _addKVStat(e){let{type:o,key:n,value:a,base:I,useUV:c,version:u,max:d}=e;switch(u&&(oB.version=u),o){case"count":oB.addCount({key:n,useUV:c});break;case"enum":oB.addEnum({key:n,value:a,useUV:c});break;case"number":oB.addNumber({key:n,value:a,split:I,max:d})}}get localVideoTrack(){return this._localVideoTrack}get localScreenTrack(){return this._localScreenTrack}get localScreenAudioTrack(){return this._localScreenAudioTrack}};G(Qo,"VERSION",L4),G(Qo,"_loggerManager",nA),G(Qo,"EVENT",Xt),G(Qo,"ERROR_CODE",Si),G(Qo,"TYPE",iG),G(Qo,"frameWorkType",30),vt([Hn({replaceArg:A=>({argIndex:0,value:{name:"plugin"in A?A.plugin.Name:A.Name,assetsPath:"assetsPath"in A?A?.assetsPath:"default"}})})],Qo.prototype,"use"),vt([vI(mg.TRTC.enterRoom),km("room",(A,e)=>{let[o]=A,[n]=e;return(o.roomId||o.strRoomId)===(n.roomId||n.strRoomId)&&o.userId===n.userId&&o.sdkAppId===n.sdkAppId}),Dn(A=>function(e){return this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),A.call(this,e)}),Hn()],Qo.prototype,"enterRoom"),vt([Hn()],Qo.prototype,"exitRoom"),vt([vI(mg.TRTC.switchRoom),Hn(),VT()],Qo.prototype,"switchRoom"),vt([vI(mg.TRTC.switchRole),YM("room",{merge:(A,e)=>e}),Hn()],Qo.prototype,"switchRole"),vt([Hn()],Qo.prototype,"destroy"),vt([vI(mg.TRTC.startLocalAudio),km("audio",(A,e)=>{let[o]=A,[n]=e;var a,I;return((a=o?.option)==null?void 0:a.microphoneId)===((I=n?.option)==null?void 0:I.microphoneId)}),Hn()],Qo.prototype,"startLocalAudio"),vt([vI(mg.TRTC.updateLocalAudio),YM("audio",{debounce:{delay:200,getKey:()=>"".concat(J4,"-localAudio"),isNeedToDebounce:A=>{var e;return!Ee((e=A.option)==null?void 0:e.captureVolume)}}}),Hn()],Qo.prototype,"updateLocalAudio"),vt([_m("audio"),Hn()],Qo.prototype,"stopLocalAudio"),vt([vI(mg.TRTC.startLocalVideo),km("video",(A,e)=>{let[o]=A,[n]=e;var a,I;return((a=o?.option)==null?void 0:a.cameraId)===((I=n?.option)==null?void 0:I.cameraId)}),Hn()],Qo.prototype,"startLocalVideo"),vt([vI(mg.TRTC.updateLocalVideo),YM("video"),Hn()],Qo.prototype,"updateLocalVideo"),vt([_m("video"),Hn()],Qo.prototype,"stopLocalVideo"),vt([vI(mg.TRTC.startScreenShare),km("screen",()=>!0),Hn()],Qo.prototype,"startScreenShare"),vt([vI(mg.TRTC.updateScreenShare),YM("screen"),Hn()],Qo.prototype,"updateScreenShare"),vt([Hn()],Qo.prototype,"stopScreenShare"),vt([vI(mg.TRTC.startRemoteVideo),km(A=>"v".concat(A.userId).concat(A.streamType),()=>!0),Hn({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],Qo.prototype,"startRemoteVideo"),vt([vI(mg.TRTC.updateRemoteVideo),YM(A=>"v".concat(A.userId).concat(A.streamType)),Hn({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],Qo.prototype,"updateRemoteVideo"),vt([vI(mg.TRTC.stopRemoteVideo),Dn(A=>function(e){return DA(this,null,function*(){if(e.userId==="*"){let o=[];return this._room.remotePublishedUserMap.forEach(n=>{this._remoteVideoConfigMap.has("".concat(n.userId,"_main"))&&o.push(this.stopRemoteVideo({streamType:"main",userId:n.userId}).catch(()=>{})),this._remoteVideoConfigMap.has("".concat(n.userId,"_sub"))&&o.push(this.stopRemoteVideo({streamType:"sub",userId:n.userId}).catch(()=>{}))}),Promise.all(o)}return A.call(this,e)})}),Hn({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],Qo.prototype,"stopRemoteVideo"),vt([_m(A=>"v".concat(A.userId).concat(A.streamType))],Qo.prototype,"_stopRemoteVideo"),vt([vI(...mg.TRTC.muteRemoteAudio),Hn({getRemoteId:A=>A})],Qo.prototype,"muteRemoteAudio"),vt([F4(...mg.TRTC.setRemoteAudioVolume),function(A,e){return Dn((o,n)=>function(){for(var a=arguments.length,I=new Array(a),c=0;c{var _;(_=PM.get(this))==null||_.delete(d)},A);u.set(d,k)}else{clearTimeout(R);let k=window.setTimeout(()=>{var _;o.apply(this,I),(_=PM.get(this))==null||_.delete(d)},A);u.set(d,k)}})}(200,A=>A),Hn({getRemoteId:A=>A})],Qo.prototype,"setRemoteAudioVolume"),vt([zq("start"),wm(A=>{var e;return(e=A.afterStart)==null?void 0:e.call(A)}),km((A,e)=>A.disableRandomCall?null:A.getAlias()+A.getGroup(e)),Hn({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>jO[A.getName()],ignoreLog:A=>A.getName()==="Debug",ignoreErrorLog:A=>A.getName()==="AudioProcessor"})],Qo.prototype,"startPlugin"),vt([zq("update"),YM((A,e)=>A.disableRandomCall?null:A.getAlias()+A.getGroup(e),{merge:(A,e)=>(tB(A[1],e[1]),A)}),Hn({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>xh[A.getName()]})],Qo.prototype,"updatePlugin"),vt([zq("stop"),_m((A,e)=>{if(A.disableRandomCall)return null;let o=A.getGroup(e),n=A.getAlias();return o==="*"?new RegExp("".concat(n,".*")):n+o}),Hn({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>DM[A.getName()]})],Qo.prototype,"stopPlugin"),vt([F4(...mg.TRTC.enableAudioVolumeEvaluation)],Qo.prototype,"enableAudioVolumeEvaluation"),vt([Hn()],Qo.prototype,"getVideoSnapshot"),vt([Hn()],Qo.prototype,"_setCurrentSpeaker"),vt([km(A=>"a".concat(A.userId),()=>!0)],Qo.prototype,"_startRemoteAudio"),vt([Dn(A=>function(e){return DA(this,null,function*(){return e.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(fi(bt({},e),{userId:o.userId})).catch(()=>{}))):A.call(this,e)})}),_m(A=>"a".concat(A.userId))],Qo.prototype,"_stopRemoteAudio"),vt([_m("room")],Qo.prototype,"_exitRoom"),vt([_m("screen")],Qo.prototype,"_stopScreenShare"),vt([vI(...mg.TRTC.sendSEIMessage),s4({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var A=arguments.length,e=new Array(A),o=0;oA.data.byteLength})],Qo.prototype,"sendCustomMessage"),vt([Hn()],Qo.prototype,"callExperimentalAPI"),vt([bm()],Qo,"create"),vt([vI(mg.TRTC.create)],Qo,"_create"),vt([bm()],Qo,"setLogLevel"),vt([bm()],Qo,"isSupported"),vt([bm(),Hn()],Qo,"getPermissions"),vt([bm()],Qo,"getCameraList"),vt([bm()],Qo,"getMicrophoneList"),vt([bm()],Qo,"getSpeakerList");var sG=Qo,beA=class{constructor(){G(this,"_set",new Set),S.on(K.LEAVE_SUCCESS,this.delete,this),S.on(K.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add(A){let{room:e,roomId:o}=A;if(e.scene==="rtc")return;let n=this.getKey(e.userId,o||e.roomId,e.sdkAppId,e.useStringRoomId);this._set.add(n)}delete(A){let{room:e,roomId:o}=A;if(e.scene==="rtc")return;let n=this.getKey(e.userId,e.roomId||o,e.sdkAppId,e.useStringRoomId);this._set.delete(n)}getKey(A,e,o,n){return"".concat(o,"_").concat(e,"_").concat(A,"_").concat(n)}isJoined(A){let{userId:e,roomId:o,sdkAppId:n,room:a}=A;return a.scene!=="rtc"&&this._set.has(this.getKey(e,o,n,a.useStringRoomId))}handleSwitchRoomSuccess(A){let{room:e,currentRoomId:o,targetRoomId:n}=A;e.scene!=="rtc"&&(this._set.delete(this.getKey(e.userId,o,e.sdkAppId,e.useStringRoomId)),this._set.add(this.getKey(e.userId,n,e.sdkAppId,e.useStringRoomId)))}};function LeA(){return DA(this,null,function*(){let A,e;try{let iA=yield VQ();A=iA&&iA.length}catch{}try{let iA=yield qQ();e=iA&&iA.length}catch{}let o={microphone:A,camera:e},{isH264EncodeSupported:n,isVp8EncodeSupported:a,isH264DecodeSupported:I,isVp8DecodeSupported:c,isH265EncodeSupported:u,isH265DecodeSupported:d}=this.checkSystemResult.detail,R=kA.basis(),k={webRTC:R.isWebRTCSupported,getUserMedia:R.isGetUserMediaSupported,webSocket:R.isWebSocketsSupported,screenShare:R.isScreenShareSupported,webAudio:R.isWebAudioSupported,h264Encode:n,h264Decode:I,vp8Encode:a,vp8Decode:c,h265Encode:u,h265Decode:d},_={browser:R.browser,os:R.os,trtc:k,devices:o},Z={isWebCodecSupported:R.isWebCodecSupported,isMediaSessionSupported:R.isMediaSessionSupported,isWebTransportSupported:R.isWebTransportSupported};Jo.uploadEvent({log:"trtcstats-".concat(JSON.stringify(_)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(_))),Jo.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(Z)),userId:this.userId}),hm()})}var FeA=es(hg()),H4="1",rK="2",gG="3",UeA="4",Ox="5",OeA="6",xx="7",V4="8",sB={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},xeA=[sB.UPDATE_REMOTE_MUTE_STAT,sB.UPLINK_NETWORK_STATS,sB.USER_LIST_RES,sB.MUTE_RESULT,sB.SERVER_FIRST_PACKAGE_RECEIVED,sB.RECEIVE_CUSTOM_MSG,sB.UPDATE_NETWORK_TIME_RESULT],io={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"},q4="publish_change",YeA="join",PeA="leave",JeA="quality_report",K4="mute_uplink",j4="publish",nK="publish_state_change",Yx="unpublish",W4="subscribe",aK="unsubscribe",sK="subscribe_change",HeA="start_publishing",VeA="stop_publishing",qeA="start_push_user_cdn",KeA="stop_push_user_cdn",jeA="start_mcu_mix",WeA="stop_mcu_mix",zeA="start_publish_cdn_stream",ZeA="update_publish_cdn_stream",XeA="stop_publish_cdn_stream",$eA="get_user_list",AtA="change_role",gK="update_constraint_config",etA="rebuild_pc",ttA="join/v2",z4="publish/v2",Z4="subscribe/v3",itA="ability_status_report",otA="reconnect",rtA="channel_msg",ntA="switch_room",atA="update_network_time",stA=new Set([j4,q4,nK,Yx,W4,sK,aK,z4,Z4]),Px=new Set,gtA=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],ItA=0,X4=class extends FeA.default{constructor(A){var e,o,n;super(),G(this,"room"),G(this,"sdkAppId"),G(this,"userId"),G(this,"userSig"),G(this,"url"),G(this,"backupUrl"),G(this,"destroyed",!1),G(this,"_socketInUse"),G(this,"_socket"),G(this,"_backupSocket"),G(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0}),G(this,"_currentState","DISCONNECTED"),G(this,"_isReconnecting",!1),G(this,"_seq",0),G(this,"_log"),G(this,"_lastMessageTime",-1),G(this,"_connectStartTime",-1),G(this,"_stopConnectRetry"),G(this,"_isFirstConnect",!0),G(this,"bytesSent",0),G(this,"bytesReceived",0),G(this,"keepAlive",!1),G(this,"signalDomainWhenUnifiedProxy"),G(this,"stopKeepAliveTimeout"),G(this,"stopPrelinkTimeout"),G(this,"rtt",0),G(this,"prelink",!1),G(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 a=((o=(e=this.room.scheduleResult)==null?void 0:e.config)==null?void 0:o.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!a&&(a=1),a-Px.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Px.add(this)),this.url=A.url,this.backupUrl=A.backupUrl,this._seq=0,this._log=nA.createLogger({parent:this.room.getLogger(),id:"ws".concat(++ItA),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 e=new URLSearchParams(location.search);return gtA.forEach(o=>{let n=e.get("trtc_".concat(o));n&&(A+="&".concat(o,"=").concat(encodeURIComponent(n)))}),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 DA(this,arguments,function(){var A=this;let e=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(e?" timeout: ".concat(e):""," keepAlive: ").concat(Number(A.keepAlive))),A.emitConnectionStateChanged("CONNECTING"),A._connectStartTime=ki();let o=[A.connectWS({url:A._urlWithParam,isMain:!0,timeout:e})];A.race&&A._backupUrlWithParam!==A._urlWithParam&&o.push(A.connectWS({url:A._backupUrlWithParam,isMain:!1,timeout:e})),A._socketInUse=yield Pf(o),A.unbindAndCloseSocket(A._socketInUse===A._socket?fA.BACKUP:fA.MAIN),A._isFirstConnect&&(ct.addSuccessEvent({key:521720}),A._isFirstConnect=!1),A.emitConnectionStateChanged("CONNECTED")}()})}connectWS(A){let{url:e,timeout:o,isMain:n}=A,a=new WebSocket(e);this.bindSocket(a),n?this._socket=a:this._backupSocket=a;let I=-1;return new Promise((c,u)=>{a.onclose=u,a.onerror=u,a.onopen=()=>c(a),o&&(I=setTimeout(()=>{this.unbindAndCloseSocket(n?fA.MAIN:fA.BACKUP),u(new Ct({code:Ge.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},o))}).finally(()=>{a.onclose=null,a.onerror=null,a.onopen=null,clearTimeout(I)})}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===fA.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(Ox,new Ct({code:Ge.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(fA.MAIN),this.unbindAndCloseSocket(fA.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(Ox,new Ct({code:Ge.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(A){if(!this.isConnected)return;let{isOnline:e}=this;this._lastMessageTime=Date.now(),e||this.emit(V4),this.bytesReceived+=XR(A.data);let o=JSON.parse(A.data),{cmd:n,data:a}=o,I=Object.values(sB),c=Object.keys(sB)[I.indexOf(n)],u=io[c]||n;switch(xeA.includes(n)||(this._log.debug("received ".concat(n," msg: ").concat(A.data)),u&&this._log.info("Received event: [ ".concat(u," ]"))),n){case sB.CHANNEL_SETUP_RESULT:if(o.code===0)this._signalInfo.clientIp=a.clientIp,this._signalInfo.signalIp=a.signalInnerIp,a.svrTime&&iu(a.svrTime-new Date().getTime()),this._log.info("ChannelSetup Success ".concat(ki()-this._connectStartTime)),ct.addSuccessEvent({key:521701,cost:ki()-this._connectStartTime}),this._connectStartTime=-1,this.room.firewallDetector.resetTimeoutCount(),this.emit(H4,{signalInfo:this._signalInfo});else{let d=new Ct({code:Ge.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:o.code,message:Wi({key:Mi.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:o.code,errorMsg:o.message}})});this._log.error("".concat(o.code,", ").concat(o.message)),this.close(),ct.addFailedEvent({key:521701,error:d}),this.emit(Ox,d)}break;case sB.JOIN_ROOM_RESULT:o.code===0&&(this._signalInfo.relayIp=a.relayOuterIp,this._signalInfo.relayInnerIp=a.relayInnerIp,this._signalInfo.bakRelayIps=a.bakRelayIps,this._signalInfo.relayPort=a.relayPort,this._signalInfo.tinyId=o.tinyId,this._signalInfo.endReportExtend=a.endReportExtend,this._signalInfo.reportToken=a.reportToken,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(u,{data:o});break;default:this.emit(String(u),{data:o})}}reGetSignalChannelUrl(){return DA(this,null,function*(){try{if(!this.room.joinParams)return;wu(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:A,backupUrl:e}=this.room.getSignalChannelUrl();this.url=A,this.backupUrl=e}catch{}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let A=this._socketInUse===this._socket;this.unbindAndCloseSocket(A?fA.MAIN:fA.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return DA(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:e}=this.room,{relayIp:o,relayInnerIp:n,relayPort:a}=this._signalInfo,{data:I}=yield this.sendWaitForResponse({command:otA,data:{roomId:A,useStringRoomId:e,relayInnerIp:n,relayOuterIp:o,relayPort:a},responseCommand:io.CHANNEL_RECONNECT_RESULT});I.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),ct.addSuccessEvent({key:521702,cost:ki()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(ct.addFailedEvent({key:521702,error:I.code}),this._log.warn("reconnect failed, ".concat(I.code," ").concat(I.message)),this.room.reJoin())}catch(A){this._log.error(A),this.room.reJoin()}}})}send(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let o={cmd:A,data:e,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},n=JSON.stringify(o);return this._socketInUse.send(n),stA.has(A)&&this._log.info("send",A,e),this.bytesSent+=XR(n),o.seq}}sendWaitForResponse(A){let{command:e,data:o,timeout:n=5e3,responseCommand:a,commandDesc:I,enableLog:c=!0,addReceiveTime:u=!1}=A;return new Promise((d,R)=>{let k=()=>{clearTimeout(_),R(new Ct({code:Ge.API_CALL_ABORTED,message:"".concat(e," aborted due to connection closed")}))};this.once(xx,k);let _=setTimeout(()=>{this.off(a,Z),this.off(xx,k);let cA=new Ct({code:Ge.API_CALL_TIMEOUT,message:Wi({key:Mi.API_CALL_TIMEOUT,data:{commandDesc:I,command:e}})});c&&this._log.warn(cA),R(cA)},n),Z=cA=>{cA.data.seq===iA&&(clearTimeout(_),this.off(a,Z),this.off(xx,k),u&&(cA.data.receiveTime=Date.now()),d(cA))};this.on(a,Z);let iA=this.send(e,o)})}sendWaitForResponseWithRetry(A){let{commandDesc:e,command:o,retries:n=0,retryTimeout:a=0}=A;return Kf({retryFunction:this.sendWaitForResponse,onError:I=>{let{retry:c,reject:u,error:d}=I;!this.room.isJoined||this.destroyed||d.code===Ge.API_CALL_ABORTED?u(d):this.isOnline?c():(this._log.warn("retry ".concat(o," when connected")),this.once(V4,c))},onRetrying:I=>{this._log.warn("".concat(e||o," timeout observed, retrying [").concat(I,"/").concat(n,"]"))},settings:{retries:n,timeout:a},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),Px.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(fA.MAIN),this.unbindAndCloseSocket(fA.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(xx)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var A;let e=(A=this._signalInfo.bakRelayIps)==null?void 0:A.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}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(io.JOIN_ROOM_RESULT,e)},1e3*A);let e=o=>{o.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(io.JOIN_ROOM_RESULT,e))};this.on(io.JOIN_ROOM_RESULT,e)}}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(io.JOIN_ROOM_RESULT,e)},1e3*A);let e=o=>{o.data.code===0&&(this._log.info("stopPrelink clear timeout"),clearTimeout(this.stopPrelinkTimeout),this.off(io.JOIN_ROOM_RESULT,e))};this.on(io.JOIN_ROOM_RESULT,e)}markPrelinkConnected(A){this._prelinkConfig=fi(bt({},A),{linkedTime:Date.now()})}isPrelinkValid(A,e,o){return!(!this.prelink||!this._prelinkConfig)&&(A!==this._prelinkConfig.sdkAppId||e!==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 e={prevState:this._currentState,state:A};A==="CONNECTING"&&(e.isReconnecting=this._isReconnecting),this.emit(rK,e),this._currentState=A,A==="CONNECTED"?this.emit(gG):A==="DISCONNECTED"&&this.emit(OeA)}};vt([nB({settings:{retries:1/0,timeout:2e3},onError(A,e){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(ct.addFailedEvent({key:521720,error:A}),this._isFirstConnect=!1),this.room.firewallDetector.increaseTimeoutCount(),e())},onRetrying(A,e){this._log.warn("retrying to connect ".concat(A)),A>=3&&A%3==0&&this.reGetSignalChannelUrl(),e&&(this._stopConnectRetry=e,(this.room.isDestroyed||this.destroyed)&&e())}})],X4.prototype,"connect");var ctA=es(hg()),$4=!1,WQ=class{constructor(A){G(this,"userId"),G(this,"tinyId"),G(this,"_sdpSemantics"),G(this,"_isUplink"),G(this,"_room"),G(this,"_log"),G(this,"_signalChannel"),G(this,"_isErrorObserved",!1),G(this,"_waitForPeerConnectionConnectedPromise"),G(this,"_waitForPeerConnectionConnectedPromiseReject",null),G(this,"_peerConnection",null),G(this,"_emitter",new ctA.default),G(this,"_currentState","DISCONNECTED"),G(this,"_isReconnecting",!1),G(this,"_reconnectionCount",0),G(this,"_reconnectionTimer",-1),G(this,"_isFirstConnection",!0),G(this,"_prevTime",-1),G(this,"_localAddress"),G(this,"_remoteAddress"),G(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=ki())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,ct.addSuccessEvent({key:521705,cost:Math.min(ki()-this._prevTime,3e4)})):this._isReconnecting&&ct.addSuccessEvent({key:521706,cost:ki()-this._prevTime}),this._prevTime=-1}catch(A){throw this._isFirstConnection?(this._isFirstConnection=!1,ct.addFailedEvent({key:521705,error:A})):this._isReconnecting&&this._reconnectionCount>=3&&ct.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 Ct({code:Ge.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return AB;let A=null;if(this._isUplink){if(!AI()||this._peerConnection.getSenders().length===0)return AB;A=this._peerConnection.getSenders()[0].transport}else{if(!Ph()||this._peerConnection.getReceivers().length===0)return AB;A=this._peerConnection.getReceivers()[0].transport}return A?A.state:AB}onConnectionStateChange(A){let e=this._peerConnection.iceConnectionState,o=this.getDTLSTransportState();if(this._log.info("connectionState: ".concat(A.target.connectionState,", ICE: ").concat(e,", DTLS: ").concat(o)),A.target.connectionState===hi.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),A.target.connectionState===hi.FAILED||A.target.connectionState===hi.CLOSED){let n="connection ".concat(A.target.connectionState,". ICE Transport state: ").concat(e,", DTLS Transport state: ").concat(o),a=new Ct({message:n,code:Ge.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",a)}(A.target.connectionState===hi.CONNECTED||A.target.connectionState===hi.COMPLETED)&&(this.logSelectedCandidate(),Jo.logSuccessEvent({userId:this._room.userId,eventType:oa.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(A){return A!==this._currentState&&(A==="CONNECTED"&&(this._room.firewallDetector.resetTimeoutCount(),$4=!0),S.emit(K.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 DA(this,null,function*(){if(!this._peerConnection)return;let A=yield this._peerConnection.getStats();for(let[,e]of A)if(Cm(e)){let o=A.get(e.localCandidateId),n=A.get(e.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)),n&&(this._log.info("remote candidate: ".concat(n.candidateType," ").concat(n.protocol,":").concat(n.ip||n.address,":").concat(n.port)),this._remoteAddress="".concat(n.protocol,":").concat(n.ip||n.address));break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise((A,e)=>{if(this._currentState==="CONNECTED")return A();this._waitForPeerConnectionConnectedPromiseReject=e;let o=c=>{c.state==="CONNECTED"&&(clearTimeout(I),a(),A())},n=c=>{let{room:u}=c;u===this._room&&(clearTimeout(I),a(),e(new Ct({code:Ge.API_CALL_ABORTED,message:Wi({key:Mi.CONNECTION_ABORTED,data:"leave room"})})))},a=()=>{S.off(K.LEAVE_SUCCESS,n,this),this._emitter.off("connection-state-changed",o,this)},I=setTimeout(()=>{a();let c=new Ct({code:Ge.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),e(c)},yN);S.on(K.LEAVE_SUCCESS,n,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(gG,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Ch()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let A=new Ct({code:this._isUplink?Ge.UPLINK_RECONNECTION_FAILED:Ge.DOWNLINK_RECONNECTION_FAILED,message:Wi({key:this._isUplink?Mi.UPLINK_RECONNECTION_FAILED:Mi.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(gG,this.reconnect,this),-1)}on(A,e,o){this._emitter.on(A,e,o)}off(A,e,o){this._emitter.off(A,e,o)}getIsReconnecting(){return this._isReconnecting}get isH264(){var A,e;return!((e=(A=this._peerConnection)==null?void 0:A.remoteDescription)==null||!e.sdp.includes("H264"))}setOffer(A){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(A)}setAnswer(A){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(A)}};vt([jh(521712,!1)],WQ.prototype,"setOffer"),vt([jh(521713,!1)],WQ.prototype,"setAnswer");var Az=es(cN()),rs=function(A){return Az.default.parse(A)},$h=function(A){return Az.default.write(A)};function IK(A){return Object.keys(A).filter(e=>A[e])}var Jx=class A6 extends WQ{constructor(e){super(fi(bt({},e),{isUplink:!1})),G(this,"_flag",0),G(this,"isRobot",!1),G(this,"role","anchor"),G(this,"remoteAudioTrack"),G(this,"remoteVideoTrack"),G(this,"remoteAuxiliaryTrack"),G(this,"avPlayerStateSyncManager"),G(this,"ssrc",{audio:0,video:0,auxiliary:0}),G(this,"_isSDPExchanging",!1),G(this,"_videoCodec"),G(this,"fromType"),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Dx(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new tG(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new n4(this._room,this),this.avPlayerStateSyncManager=new Kq({log:this._log,audioPlayer:this.remoteAudioTrack.player,videoPlayer:this.remoteVideoTrack.player})}get videoCodec(){var e,o;let n=(o=(e=this._peerConnection)==null?void 0:e.remoteDescription)==null?void 0:o.sdp;return n?n.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return mQ(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var o,n,a;e!==this._flag&&(this._flag=e,(o=this.remoteAudioTrack)==null||o.onFlagChanged(),(n=this.remoteVideoTrack)==null||n.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(e){return e===fA.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.avPlayerStateSyncManager.destroy(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let a=this._currentState,I=super.emitConnectionStateChangedEvent(e);return I&&a!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:a,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:a,state:e})),I}onTrack(e){let o=e.streams[0],{track:n}=e,a=o.id===RI?fA.MAIN:fA.AUXILIARY;this._log.debug("ontrack ".concat(a," ").concat(n.kind));let I=fA.AUDIO;n.kind===fA.VIDEO&&(I=a===fA.MAIN?fA.VIDEO:fA.AUXILIARY);let c=this.remoteAudioTrack;I===fA.VIDEO?c=this.remoteVideoTrack:I===fA.AUXILIARY&&(c=this.remoteAuxiliaryTrack),c.setInputMediaStreamTrack(n)}addRRTRLine(e){let o=e.split(`\r +`).concat(R.stack)),!1}}})(this,"trtc")}static create(e){}static _create(e,o){(function(){var a;if(u4){u4=!1,nA.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat($C,"/en/index.html")),console.info("* Changelog: ".concat($C,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),nA.info("TRTC Web SDK Version:",ol),bQ||nA.debug("Build Time:","2026-02-28 12:18:13");let I="UA: ".concat(navigator.userAgent,` +CPU core: `).concat(navigator.hardwareConcurrency,", GPU: ").concat(LQ());if(Ea&&window.screen&&(window.screen.width||window.screen.height)){let u="".concat(window.screen.width,"x").concat(window.screen.height,"@").concat(window.devicePixelRatio);I+=", screen: ".concat(u)}let c=navigator.deviceMemory;c&&(I+=", minRAM: ".concat(c,"GB")),nA.info(I),nA.info("URL: ".concat(location.href).concat(((a=self.frameElement)==null?void 0:a.tagName)==="IFRAME"?" in iframe":"")),Im().then(u=>{u&&nA.info(eC)})}})();let n=new td(e,o||{});return cG.add(n),n.__v_skip=!0,n}get room(){return this._room}_listenEvents(){nE(this,this._room).add("peer-join",e=>{let{userId:o}=e;this.emit(Xt.REMOTE_USER_ENTER,{userId:o})}).add("peer-leave",e=>{let{userId:o,reason:n}=e;this.emit(Xt.REMOTE_USER_EXIT,{userId:o,reason:n})}).add("banned",e=>{Nu(!0),this._exitRoom().finally(()=>{this.emit(Xt.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(Xt.ERROR,vi.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(Xt.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let o=fi(bt({},e),{uplinkRTT:Math.min(e.uplinkRTT,PR),downlinkRTT:Math.min(e.downlinkRTT,PR)});this.emit(Xt.NETWORK_QUALITY,o)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{nE(o,o).add("player-state-changed",n=>{let a=fi(bt({},n),{userId:e.userId});o.kind===fA.VIDEO&&(a.streamType=El(o.streamType)),this.emit(o.kind===fA.AUDIO?Xt.AUDIO_PLAY_STATE_CHANGED:Xt.VIDEO_PLAY_STATE_CHANGED,a)}).add("error",n=>{n.getCode()===Ge.PLAY_NOT_ALLOWED&&this.emit(Xt.AUTOPLAY_FAILED,{userId:o.userId,mediaType:o.strMediaType,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{pr(o)})}).add("remote-publish-state-changed",e=>{let{prevMuteState:o,muteState:n}=e,{userId:a}=n,I=o.audioAvailable,c=o.videoAvailable,{audioAvailable:u,videoAvailable:d}=n;u||this._remoteAudioConfigMap.delete(a),d||this._removeRemoteVideoConfig(a,"main"),n.hasAuxiliary||this._removeRemoteVideoConfig(a,"sub"),c!==d&&(d?this._onVideoAvailable({userId:a,streamType:"main"}):this._onVideoUnavailable({userId:a,streamType:"main"}),this.emit(d?Xt.REMOTE_VIDEO_AVAILABLE:Xt.REMOTE_VIDEO_UNAVAILABLE,{userId:a,streamType:"main"})),I!==u&&(u?this._onAudioAvailable({userId:a}):this._onAudioUnavailable({userId:a,muteState:n}),this.emit(u?Xt.REMOTE_AUDIO_AVAILABLE:Xt.REMOTE_AUDIO_UNAVAILABLE,{userId:a})),o.hasAuxiliary!==n.hasAuxiliary&&(n.hasAuxiliary?this._onVideoAvailable({userId:a,streamType:"sub"}):this._onVideoUnavailable({userId:a,streamType:"sub"}),this.emit(n.hasAuxiliary?Xt.REMOTE_VIDEO_AVAILABLE:Xt.REMOTE_VIDEO_UNAVAILABLE,{userId:a,streamType:"sub"})),o.hasDatachannel!==n.hasDatachannel&&n.hasDatachannel&&this._onDataChannelAvailable()}).add("sei-message",e=>{this.emit(Xt.SEI_MESSAGE,fi(bt({},e),{streamType:El(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(Xt.ERROR,new vi({code:Si.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,n,a,I,c,u,d;let R={2:"big",3:"small",7:"sub"},k={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((n=this._networkQuality)==null?void 0:n.uplinkRTT)||((a=this._networkQuality)==null?void 0:a.downlinkRTT)||0,PR),upLoss:((I=this._networkQuality)==null?void 0:I.uplinkLoss)||0,downLoss:((c=this._networkQuality)==null?void 0:c.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((u=e.msg_up_stream_info.msg_audio_status)==null?void 0:u.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((d=e.msg_up_stream_info.msg_audio_status)==null?void 0:d.uint32_audio_level)||0)/iE},video:e.msg_up_stream_info.msg_video_status.filter(_=>R[_.uint32_video_stream_type]).map(_=>({bitrate:(_.uint32_video_codec_bitrate||0)/1e3,width:_.uint32_video_width,height:_.uint32_video_height,frameRate:_.uint32_video_enc_fps,videoType:R[_.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(_=>({userId:_.msg_user_info.str_identifier,audio:{bitrate:(_.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(_.msg_audio_status.uint32_audio_level||0)/iE,point2pointDelay:(_.msg_audio_status.uint32_audio_p2p_delay||0)+(_.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:_.msg_audio_status.uint32_audio_cache_ms||0},video:_.msg_video_status.map(Z=>({bitrate:(Z.uint32_video_codec_bitrate||0)/1e3,width:Z.uint32_video_width,height:Z.uint32_video_height,frameRate:Z.uint32_video_dec_fps,videoType:R[Z.uint32_video_stream_type],point2pointDelay:(Z.uint32_video_p2p_delay||0)+(Z.uint32_video_cache_ms||0),jitterBufferDelay:Z.uint32_video_cache_ms||0,codec:Z.uint32_video_codec}))}))};this.emit(Xt.STATISTICS,k)}).add("custom-message",e=>{this.emit(Xt.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(Xt.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(Xt.FIRST_VIDEO_FRAME,fi(bt({},e),{streamType:El(e.streamType)}))}).add("audio-frame",e=>{this.emit(Xt.AUDIO_FRAME,e)}).add("data-channel-message",e=>{var o,n,a,I,c;let{data:u}=e;if(u.sender==="")return;let d={segmentId:(o=u.payload)==null?void 0:o.roundid,speakerUserId:u.sender,sourceText:(n=u.payload)==null?void 0:n.text,translationTexts:(a=u.payload)==null?void 0:a.translate_msg,timestamp:(I=u.payload)==null?void 0:I.start_utc_ms,isCompleted:(c=u.payload)==null?void 0:c.end,robotId:u.robotid};d.sourceText!==""&&this.emit(Xt.REALTIME_TRANSCRIBER_MESSAGE,d)}).add("asr-robot-peer-join",e=>{this.emit(Xt.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"started",roomId:this.room.roomId,transcriberRobotId:e.userId})}).add("asr-robot-peer-leave",e=>{this.emit(Xt.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"stopped",roomId:this.room.roomId,transcriberRobotId:e.userId})}),nE(this,vs).add("audioInputAdded",e=>{this.emit(Xt.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(Xt.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(Xt.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(Xt.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>DA(this,null,function*(){if(this.emit(Xt.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Dg&&Dg.deviceId===YR){let o=(yield Nm()).find(n=>n.deviceId===YR);o&&Dg.groupId!==o.groupId&&(Dg=o,this.emit(Xt.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}))}})).add("audioOutputRemoved",e=>DA(this,null,function*(){this.emit(Xt.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let o=(yield Nm())[0];if(!o||!Dg||Dg.groupId===o.groupId)return;let n=Dg.deviceId===e.deviceId,a=Dg.deviceId===YR&&Dg.deviceId===o.deviceId;(n||a)&&(Dg=o,this.emit(Xt.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}))})),nE(this,Vx).add("permission-state-change",e=>{this.emit(Xt.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(Xt.SEI_MESSAGE,e=>{var o;let n=(o=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:o.remoteVideoTrack;n&&n.updateAlphaRenderInfo(e)})}getNetworkTime(){return Eh()}use(e){let o,n;return"plugin"in e?(o=e.plugin,n=e.assetsPath):o=e,o.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(o,n)}_use(e,o){let n=this._plugins.get(e.Name);if(n)return this._log.warn("duplicate install plugin",e.Name),n;let a=new e(TeA.call(this,{TRTC:td,room:this._room,assetsPath:o,errorModule:{RtcError:vi,ErrorCode:Si,CoreErrorCode:Ge,ErrorCodeDictionary:kx}}));return this._plugins.set(e.Name,a),a.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),a}enterRoom(e){return DA(this,null,function*(){var o,n;this.enterRoomParams=e;let{scene:a="rtc",enableAutoPlayDialog:I=!0,autoReceiveAudio:c=!0,autoReceiveVideo:u=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Sr(e.proxy)&&e.proxy.turnServer&&((n=(o=this._room).setTurnServer)==null||n.call(o,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=I,this._room.autoReceiveAudio=c,this._room.autoReceiveVideo=u,rn(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let d={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,enableDataChannel:this._plugins.has("RealtimeTranscriber"),frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(d,a,td.frameWorkType),this._checkTrackToPublish(),V4.start()})}exitRoom(){return DA(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return DA(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(o){if(!(o instanceof XU)||o.code!==Ge.API_CALL_TIMEOUT&&o.code!==Ge.SWITCH_ROOM_FAILED)throw o;this._log.warn("switchRoom ".concat(o.code===Ge.API_CALL_TIMEOUT?"timeout":"failed",", fallback to exitRoom() and enterRoom()")),yield this._rejoinRoom(e)}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return DA(this,null,function*(){yield this.exitRoom();let o=bt(bt({},this.enterRoomParams),e);yield this.enterRoom(o)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let o=e.includes("main")?"main":"sub",n=e.split("_".concat(o))[0];n&&this._stopRemoteVideo({userId:n,streamType:o}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),function(e){let o=VM.get(e);o&&(o.forEach(n=>clearTimeout(n)),VM.delete(e))}(this),this._room.remotePublishedUserMap.forEach(e=>{pr(e.remoteAudioTrack),pr(e.remoteVideoTrack),pr(e.remoteAuxiliaryTrack)})}switchRole(e,o){return DA(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(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(e=>{var o;return(o=e.destroy)==null?void 0:o.call(e)}),this._plugins.clear(),pr(this),this.removeAllListeners(),this._room.destroy(),cG.delete(this),cG.size===0&&V4.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),S.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return DA(this,arguments,function(){var e=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn("local audio is already started");let{publish:n=!0,mute:a,muteKeepVolumeDetection:I,option:c}=o,u=new km(e._room.audioManager),d={},R={muted:!0};c&&(Ee(c.microphoneId)?Ee(c.audioTrack)||(d.customSource=c.audioTrack):d.deviceId=c.microphoneId,c&&hr(c.captureVolume)&&u.setCaptureVolume(c.captureVolume),Ee(c.profile)||(Sr(c.profile)?fQ[c.profile]&&u.setProfile(fQ[c.profile]):u.setProfile(c.profile)),hr(c.earMonitorVolume)&&(R.muted=!(c.earMonitorVolume>0),R.volume=c.earMonitorVolume),Ee(c.echoCancellation)||(u.profile.echoCancellation=c.echoCancellation),Ee(c.noiseSuppression)||(u.profile.noiseSuppression=c.noiseSuppression),Ee(c.autoGainControl)||(u.profile.autoGainControl=c.autoGainControl),rn(e._enableAutoSwitchWhenRecapturing)&&(u.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),u.on("5",k=>{e.emit(Xt.ERROR,new vi({code:Si.DEVICE_ERROR,extraCode:5309,messageParams:{error:k}}))}),u.on("2",k=>{e.emit(Xt.DEVICE_CHANGED,{type:"microphone",action:"active",device:k})}),u.on("4",k=>{let _;k.error&&(_=vi.convertFrom(k.error)),e.emit(Xt.PUBLISH_STATE_CHANGED,fi(bt({},k),{error:_}))}),u.on("6",()=>{}),e._listenOutputTrackChanged(u),e._speakerId&&u.setAudioOutput(e._speakerId),yield u.capture(d),Ee(a)||u.setMute(a,I),nE(u,u).add("player-state-changed",k=>{e.emit(Xt.AUDIO_PLAY_STATE_CHANGED,fi(bt({},k),{userId:""}))}),n&&e._room.isJoined&&e._room.publish(u).catch(()=>{}),e._localAudioTrack=u,e._room.capturedLocalMainAudioTrack=u,e._localAudioConfig=fi(bt({},o),{publish:n}),yield e._updateAudioPlayOption({playOption:R,track:u}),S.emit("113",{userId:"",room:e.room})}()})}updateLocalAudio(e){return DA(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:o,mute:n,muteKeepVolumeDetection:a,option:I}=e,c={};I&&(I.microphoneId?yield this._localAudioTrack.switchDevice(I.microphoneId):Ee(I.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(I.audioTrack)),Ee(I.captureVolume)||this._localAudioTrack.setCaptureVolume(I.captureVolume),Ee(I.earMonitorVolume)||(c.muted=!(I.earMonitorVolume>0),c.volume=I.earMonitorVolume),yield this._localAudioTrack.update3A(I)),this._room.isJoined&&!Ee(o)&&(o&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!o&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),Ee(n)||this._localAudioTrack.setMute(n,a),yield this._updateAudioPlayOption({playOption:c,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),tB(this._localAudioConfig,e)})}stopLocalAudio(){return DA(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),S.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),pr(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,delete this._room.capturedLocalMainAudioTrack)})}startLocalVideo(){return DA(this,arguments,function(){var e=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0,view:null,capture:!0};return function*(){var n,a,I;if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:c,publish:u=!0,capture:d=!0,mute:R,option:k,forcePublish:_=!1}=o,Z=u||_,iA=d,cA=new Su(e._room.videoManager),TA={},JA={};if(k&&(rn(k.avoidCropping)&&(cA.avoidCropping=k.avoidCropping),k.cameraId?TA.deviceId=k.cameraId:Ee(k.useFrontCamera)?Ee(k.videoTrack)||(TA.customSource=k.videoTrack):TA.facingMode=k.useFrontCamera?fA.FACING_MODE_USER:fA.FACING_MODE_ENVIRONMENT,Ee(k.retryWhenExactFailed)||(TA.retryWhenExactFailed=k.retryWhenExactFailed),k.qosPreference&&(TA.contentHint=_x(k.qosPreference)),Ee(k.profile)||(Sr(k.profile)?$l[k.profile]&&cA.setProfile($l[k.profile]):cA.setProfile(k.profile)),Ee(k.fillMode)||(JA.objectFit=k.fillMode),Ee(k.mirror)||(JA.mirror=k.mirror),Ee(k.small)||(Ee(k.smallMode)||(e._room.smallMode=k.smallMode),rn(k.small)&&k.small===!1?cA.stopSmall():cA.updateSmallConfig(bx(k.small,!0))),Ee(k.rotation)||cA.setRotation(k.rotation),rn(e._enableAutoSwitchWhenRecapturing)&&(cA.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),cA.once("first-video-frame",Ie=>{e.emit(Xt.FIRST_VIDEO_FRAME,fi(bt({},Ie),{streamType:El(Ie.streamType)}))}),cA.on("5",Ie=>{e.emit(Xt.ERROR,new vi({code:Si.DEVICE_ERROR,extraCode:5308,messageParams:{error:Ie}}))}),cA.on("2",Ie=>{e.emit(Xt.DEVICE_CHANGED,{type:"camera",action:"active",device:Ie})}),cA.on("4",Ie=>{let XA;Ie.error&&(XA=vi.convertFrom(Ie.error)),e.emit(Xt.PUBLISH_STATE_CHANGED,fi(bt({},Ie),{error:XA}))}),cA.on("6",()=>{}),e._listenOutputTrackChanged(cA),TA.customSource&&MQ(TA.customSource)?(cA.setOutputMediaStreamTrack(TA.customSource),iA=!1):iA?yield cA.capture(TA):(n=cA.manager)==null||n.changeInput(cA),Ee(R)||(yield cA.setMute(R)),nE(cA,cA).add("player-state-changed",Ie=>{e.emit(Xt.VIDEO_PLAY_STATE_CHANGED,fi(bt({},Ie),{userId:"",streamType:"main"}))}).add("video-size-changed",Ie=>{e.emit(Xt.VIDEO_SIZE_CHANGED,fi(bt({},Ie),{streamType:El(Ie.streamType)}))}),Z){let Ie=e._localScreenTrack&&((a=e._localScreenConfig)==null?void 0:a.publish)&&e._localScreenConfig.streamType==="main";e._room.isJoined?!Ie||_?(e._room.publish(cA).catch(()=>{}),((I=e._localScreenConfig)==null?void 0:I.streamType)==="main"&&e._localScreenConfig&&(e._localScreenConfig.publish=!1)):(Z=!1,e._log.warn("main stream is already published, local video track will not publish")):Ie&&(Z=!1)}e._localVideoTrack=cA,e._room.capturedLocalMainVideoTrack=cA,e._localVideoConfig=fi(bt({},o),{view:c,publish:Z,capture:iA}),yield e._updateVideoPlayOption({view:c,playOption:JA,track:cA})}()})}updateLocalVideo(e){return DA(this,null,function*(){var o,n,a,I,c,u,d;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:R,publish:k=!0,mute:_,capture:Z,option:iA,forcePublish:cA=!1}=e,TA=k||cA,JA=Z,Ie={};if(!this._localVideoConfig.capture&&MQ((o=this.localVideoTrack)==null?void 0:o.outMediaTrack)&&(iA!=null&&iA.cameraId||iA!=null&&iA.videoTrack)&&this._localVideoTrack.outMediaTrack!==iA?.videoTrack&&(JA=!0),this._localVideoConfig.capture)JA!==!1?iA!=null&&iA.cameraId?yield this._localVideoTrack.switchDevice(iA?.cameraId):Ee(iA?.useFrontCamera)?Ee(iA?.videoTrack)||(MQ(iA?.videoTrack)?iA?.videoTrack!==((n=this.localVideoTrack)==null?void 0:n.outMediaTrack)&&(yield this._localVideoTrack.setOutputMediaStreamTrack(iA?.videoTrack)):yield this._localVideoTrack.setInputMediaStreamTrack(iA?.videoTrack)):yield this._localVideoTrack.switchDevice(iA!=null&&iA.useFrontCamera?fA.FACING_MODE_USER:fA.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(JA){let XA={};XA.deviceId=iA?.cameraId||((a=this._localVideoConfig.option)==null?void 0:a.cameraId),XA.facingMode=iA!=null&&iA.useFrontCamera||(I=this._localVideoConfig.option)!=null&&I.useFrontCamera?fA.FACING_MODE_USER:fA.FACING_MODE_ENVIRONMENT,XA.customSource=iA!=null&&iA.videoTrack||!XA.deviceId?(c=this._localVideoConfig.option)==null?void 0:c.videoTrack:void 0,yield this._localVideoTrack.capture(XA)}iA&&(Ee(iA.profile)||(Sr(iA.profile)?$l[iA.profile]&&this._localVideoTrack.setProfile($l[iA.profile]):this._localVideoTrack.setProfile(iA.profile),(!iA.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(iA.cameraId||iA.useFrontCamera?fA.FACING_MODE_USER:fA.FACING_MODE_ENVIRONMENT))&&(yield this._localVideoTrack.applyProfile())),Ee(iA.fillMode)||(Ie.objectFit=iA.fillMode),Ee(iA.mirror)||(Ie.mirror=iA.mirror),Ee(iA.rotation)||this._localVideoTrack.setRotation(iA.rotation),iA.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(_x(iA.qosPreference)),Ee(iA.small)||(rn(iA.small)&&!iA.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(bx(iA.small,!0)))),this._room.isJoined&&Ee(TA)&&this._localVideoConfig.publish&&JA&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((TA??this._localVideoConfig.publish)||cA?this._localScreenTrack&&((u=this._localScreenConfig)!=null&&u.publish)&&this._localScreenConfig.streamType==="main"&&!cA?(TA=!1,this._log.warn("main stream is already published, local video track will not publish")):(this._room.publish(this._localVideoTrack).catch(()=>{}),((d=this._localScreenConfig)==null?void 0:d.streamType)==="main"&&this._localScreenConfig&&(this._localScreenConfig.publish=!1)):this._room.unpublish(this._localVideoTrack).catch(()=>{})),Ee(_)||(yield this._localVideoTrack.setMute(_)),yield this._updateVideoPlayOption({view:R,playOption:Ie,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),tB(this._localVideoConfig,fi(bt({},e),{publish:TA,capture:JA}))})}stopLocalVideo(){return DA(this,null,function*(){var e;this._localVideoTrack&&(this._room.isJoined&&(e=this._localVideoConfig)!=null&&e.publish&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),pr(this._localVideoTrack),this._localVideoTrack=null,delete this._room.capturedLocalMainVideoTrack,this._localVideoConfig=null)})}startScreenShare(){return DA(this,arguments,function(){var e=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0,view:null};return function*(){var n,a,I;if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:c=null,publish:u=!0,muteSystemAudio:d,option:R}=o,k=u,_=new _m(e._room.videoManager);_.on("4",JA=>{let Ie;JA.error&&(Ie=vi.convertFrom(JA.error)),e.emit(Xt.PUBLISH_STATE_CHANGED,fi(bt({},JA),{error:Ie}))}),_.once("first-video-frame",JA=>{e.emit(Xt.FIRST_VIDEO_FRAME,fi(bt({},JA),{streamType:El(JA.streamType)}))}),e._listenOutputTrackChanged(_),o.streamType==="main"&&(_.mediaType=4);let Z=null,iA={},cA={};R&&(Ee(R.profile)||(Sr(R.profile)?fN[R.profile]&&_.setProfile(fN[R.profile]):_.setProfile(R.profile)),R.systemAudio&&(iA.systemAudio=!0,iA.echoCancellation=R.echoCancellation,iA.noiseSuppression=R.noiseSuppression,iA.autoGainControl=R.autoGainControl),Ee(R.fillMode)||(cA.objectFit=R.fillMode),R.videoTrack&&(iA.videoTrack=R.videoTrack),R.audioTrack&&(iA.audioTrack=R.audioTrack),R.captureElement&&(iA.captureElement=R.captureElement),R.preferDisplaySurface&&(iA.preferDisplaySurface=R.preferDisplaySurface),R.qosPreference&&(iA.contentHint=_x(R.qosPreference)));let TA=yield _.capture(iA);if(_.mediaTrack.addEventListener(fA.ENDED,()=>{e._stopScreenShare(),e.emit(Xt.SCREEN_SHARE_STOPPED)}),TA.getAudioTracks()[0]){Z=new Kq(e._room.audioManager);let JA=TA.getAudioTracks()[0];(n=o.option)!=null&&n.systemAudio&&!((a=o.option)!=null&&a.audioTrack)&&(Z.sourceTrack=JA),yield Z.setInputMediaStreamTrack(JA),rn(d)&&Z.mediaTrack&&(Z.mediaTrack.enabled=!d),e._speakerId&&Z.setAudioOutput(e._speakerId)}if(nE(_,_).add("player-state-changed",JA=>{e.emit(Xt.VIDEO_PLAY_STATE_CHANGED,fi(bt({},JA),{userId:"",streamType:"sub"}))}),k){let JA=e._localVideoTrack&&((I=e._localVideoConfig)==null?void 0:I.publish),Ie=!(o.streamType==="main"&&JA);e._room.isJoined?(Ie?e._room.publish(_).catch(()=>{}):(k=!1,e._log.warn("main stream is already published, screen share main will not publish")),Z&&(e._checkScreenAudioEchoCancellation(_,Z),e._room.publish(Z).catch(()=>{}))):Ie||(k=!1)}e._localScreenTrack=_,e._room.capturedLocalAuxVideoTrack=_,e._localScreenAudioTrack=Z,e._localScreenConfig=fi(bt({},o),{view:c,publish:k}),yield e._updateVideoPlayOption({view:c,playOption:cA,track:_})}()})}updateScreenShare(e){return DA(this,null,function*(){var o,n;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:a,publish:I,muteSystemAudio:c,option:u}=e,d=I,R={};if(u){if(Ee(u.fillMode)||(R.objectFit=u.fillMode),u.qosPreference){let k=_x(u.qosPreference);this._localScreenTrack.setContentHint(k)}u.videoTrack&&this._localScreenTrack.setInputMediaStreamTrack(u.videoTrack),u.audioTrack&&this._localScreenAudioTrack&&this._localScreenAudioTrack.setInputMediaStreamTrack(u.audioTrack)}if(this._room.isJoined&&!Ee(d)){if(d&&!this._localScreenConfig.publish){let k=this._localVideoTrack&&((o=this._localVideoConfig)==null?void 0:o.publish);this._localScreenConfig.streamType==="main"&&k?(d=!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&&!d){let k=[this._localScreenTrack];this._localScreenAudioTrack&&k.push(this._localScreenAudioTrack),k.forEach(_=>this._room.unpublish(_).catch(()=>{}))}}(n=this._localScreenAudioTrack)!=null&&n.mediaTrack&&rn(c)&&(this._localScreenAudioTrack.mediaTrack.enabled=!c),yield this._updateVideoPlayOption({view:a,playOption:R,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),tB(this._localScreenConfig,fi(bt({},e),{publish:d}))})}stopScreenShare(){return DA(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return DA(this,null,function*(){let{view:o,userId:n,streamType:a,option:I}=e,c="".concat(n,"_").concat(a);if(this._remoteVideoConfigMap.has(c))return void this._log.warn("remote video has already started. userId:".concat(n,", streamType:").concat(a));let u=this._room.remotePublishedUserMap.get(n);if(!u)return;let d={},R=a==="main"?u.remoteVideoTrack:u.remoteAuxiliaryTrack,k=this._bindRemoteVideoTrackEvents(R);this._listenOutputTrackChanged(R),I&&(Ee(I.fillMode)||(d.objectFit=I.fillMode),Ee(I.mirror)||(d.mirror=I.mirror),Ee(I.poster)||(d.poster=I.poster),d.canvasRender=I.canvasRender,a==="main"&&!Ee(I.small)&&(!u.remoteVideoTrack.isSubscribing&&!u.remoteVideoTrack.isSubscribed&&u.remoteVideoTrack.setMediaType(I.small?8:4),this._room.changeType(I.small,R.user)),Ee(I.draggable)||R.setDraggable(I.draggable)),d.isLiveStream=!!this._playbackQualityList.find(_=>_.userId===n&&_.streamType===a),yield this._room.subscribe(R),yield this._enableVideoDecodeFallback(R,a),yield this._updateVideoPlayOption({view:o,playOption:d,track:R}),this._emitTrackEvent(R),this._remoteVideoConfigMap.set(c,{config:e,handlers:k}),I&&!Ee(I.receiveWhenViewVisible)&&this._observeView({remoteTrack:R,view:o,receiveWhenViewVisible:I.receiveWhenViewVisible,viewRoot:I?.viewRoot})})}updateRemoteVideo(e){return DA(this,null,function*(){var o,n;let{view:a,userId:I,streamType:c,option:u,mute:d}=e,R="".concat(I,"_").concat(c),k=this._remoteVideoConfigMap.get(R);if(!k||!this._room.remotePublishedUserMap.has(I))return;let _={};u&&(Ee(u.fillMode)||(_.objectFit=u.fillMode),Ee(u.mirror)||(_.mirror=u.mirror));let Z=null,iA=this._room.remotePublishedUserMap.get(I);if(c==="main"&&iA!=null&&iA.muteState.hasVideo&&(Z=iA.remoteVideoTrack),c==="sub"&&iA!=null&&iA.muteState.hasAuxiliary&&(Z=iA.remoteAuxiliaryTrack),!Z)return;let{config:cA}=k;c==="main"&&u&&!Ee(u.small)&&this._room.changeType(u.small,Z.user),u&&!Ee(u.draggable)&&Z.setDraggable(u.draggable),u&&(rn(u.pictureInPicture)&&(u.pictureInPicture?yield Z.player.enterPictureInPicture():yield Z.player.exitPictureInPicture()),rn(u.fullScreen)&&(u.fullScreen?yield Z.player.enterFullscreen():yield Z.player.exitFullscreen())),rn(d)&&(Z.ignoreUpdatePlayingState=!0,d?(yield Z.player.pause(),yield this.room.unsubscribe(Z)):(yield this.room.subscribe(Z),yield Z.player.resume(!0))),yield this._updateVideoPlayOption({view:a,playOption:_,track:Z,prevConfig:cA}),tB(cA,e);let TA=Ee(u?.receiveWhenViewVisible)?(o=cA.option)==null?void 0:o.receiveWhenViewVisible:u.receiveWhenViewVisible,JA=Ee(a)?cA.view:a,Ie=Ee(u?.viewRoot)?(n=cA.option)==null?void 0:n.viewRoot:u.viewRoot;this._observeView({remoteTrack:Z,view:JA,receiveWhenViewVisible:TA,viewRoot:Ie})})}stopRemoteVideo(e){return DA(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return DA(this,null,function*(){let n=[],a=this._room.remotePublishedUserMap.get(e.userId);if(a){let{muteState:I,remoteVideoTrack:c,remoteAuxiliaryTrack:u}=a;e.streamType==="main"&&(c.stop(),I.hasVideo&&n.push(c)),e.streamType==="sub"&&(u.stop(),I.hasAuxiliary&&n.push(u))}for(let I of n)o&&(delete I.ignoreUpdatePlayingState,yield this._room.unsubscribe(I),this._mediaTrackMap.delete(I.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,o){let n="".concat(e,"_").concat(o),a=this._remoteVideoConfigMap.get(n);if(a&&(a.observer&&a.observer.disconnect(),a.handlers)){let I=this._room.remotePublishedUserMap.get(e);if(I){let c=o==="main"?I.remoteVideoTrack:I.remoteAuxiliaryTrack;this._unbindRemoteVideoTrackEvents(c,a.handlers)}}this._remoteVideoConfigMap.delete(n)}_bindRemoteVideoTrackEvents(e){let o={onEnterPIP:()=>DA(this,null,function*(){yield e.player.enterPIPPromise,this.emit(Xt.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:El(e.streamType),userId:e.userId,isPictureInPicture:!0,pictureInPictureWindow:e.player.pipWindow})}),onLeavePIP:()=>{this.emit(Xt.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:El(e.streamType),userId:e.userId,isPictureInPicture:!1})},onEnterFullScreen:()=>{this.emit(Xt.FULL_SCREEN_STATE_CHANGED,{streamType:El(e.streamType),userId:e.userId,isFullScreen:!0})},onLeaveFullScreen:()=>{this.emit(Xt.FULL_SCREEN_STATE_CHANGED,{streamType:El(e.streamType),userId:e.userId,isFullScreen:!1})},onDecodeFailed:()=>{this.emit(Xt.ERROR,new vi({code:Si.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))},onVideoSizeChanged:n=>{this.emit(Xt.VIDEO_SIZE_CHANGED,fi(bt({},n),{streamType:El(n.streamType)}))}};return e.player.on(mi.ENTER_PICTURE_IN_PICTURE,o.onEnterPIP),e.player.on(mi.LEAVE_PICTURE_IN_PICTURE,o.onLeavePIP),e.player.on(mi.ENTER_FULL_SCREEN,o.onEnterFullScreen),e.player.on(mi.LEAVE_FULL_SCREEN,o.onLeaveFullScreen),e.on("decode-failed",o.onDecodeFailed),e.on("video-size-changed",o.onVideoSizeChanged),o}_unbindRemoteVideoTrackEvents(e,o){e.player.off(mi.ENTER_PICTURE_IN_PICTURE,o.onEnterPIP),e.player.off(mi.LEAVE_PICTURE_IN_PICTURE,o.onLeavePIP),e.player.off(mi.ENTER_FULL_SCREEN,o.onEnterFullScreen),e.player.off(mi.LEAVE_FULL_SCREEN,o.onLeaveFullScreen),e.off("decode-failed",o.onDecodeFailed),e.off("video-size-changed",o.onVideoSizeChanged)}muteRemoteAudio(e,o){return DA(this,null,function*(){this._remoteAudioMuteMap.set(e,o);try{if(e==="*")if(o)yield this._stopRemoteAudio({userId:e});else{let n=[...this._room.remotePublishedUserMap.values()];for(let a of n)a.muteState.hasAudio&&!this._remoteAudioConfigMap.has(a.userId)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:a.userId}))}else o?yield this._stopRemoteAudio({userId:e}):!this._remoteAudioConfigMap.has(e)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:e}))}catch(n){throw n.code!==Si.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),n}})}setRemoteAudioVolume(e,o){if(e==="*"){this._remoteAudioVolumeMap.set("*",o),this._remoteAudioVolumeMap.forEach((a,I)=>this._remoteAudioVolumeMap.set(I,o));let n=[...this._room.remotePublishedUserMap.values()];for(let a of n)this._remoteAudioVolumeMap.set(a.userId,o),a.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:o},track:a.remoteAudioTrack})}else if(e){let n=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,o),n&&n.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:o},track:n.remoteAudioTrack})}}startPlugin(e,o){return DA(this,null,function*(){return e.start(o)})}updatePlugin(e,o){return DA(this,null,function*(){return e.update(o)})}stopPlugin(e,o){return DA(this,null,function*(){return e.stop(o)})}enableAudioVolumeEvaluation(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3,o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this._room.enableAudioVolumeEvaluation(e,o)}on(e,o,n){if(this.listeners(e).includes(o))return this;if(this._log.debug("on",e),super.on(e,o,n),this._eventListened.add(e),this.listeners(Xt.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:a}=this.room.audioManager;a.get("")||a.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return e==="realtime-transcriber-message"&&this._room.subscribeDataChannel(),this}emit(e){for(var o=arguments.length,n=new Array(o>1?o-1:0),a=1;a{I?.abort("off")}),a.clear()}return this}getAudioTrack(){let e,o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userId:"",streamType:"main"},n=null,a="main",I=!1;if(Sr(o)?e=o:(e=o.userId,I=o.processed===!0,o.streamType&&(a=o.streamType)),e){let c=this._room.remotePublishedUserMap.get(e);c&&(n=c.remoteAudioTrack)}else n=a==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return n?I&&n.outMediaTrack&&n.outMediaTrack!==n.mediaTrack?n.outMediaTrack.clone():n.mediaTrack:null}getVideoTrack(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userId:"",streamType:"main"},{userId:o="",streamType:n="main",processed:a=!1}=e,I=null;if(o==="")n==="main"&&this._localVideoTrack&&(I=this._localVideoTrack),n==="sub"&&this._localScreenTrack&&(I=this._localScreenTrack);else{let c=this._room.remotePublishedUserMap.get(o);c&&(I=n==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack)}return I?a&&I.outMediaTrack&&I.outMediaTrack!==I.mediaTrack?I.outMediaTrack.clone():I.mediaTrack:null}getVideoSnapshot(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{userId:o,streamType:n="main"}=e;if(o){let a=this._room.remotePublishedUserMap.get(o);if(n==="main"&&a!=null&&a.muteState.hasVideo)return a.remoteVideoTrack.getVideoFrame();if(n==="sub"&&a!=null&&a.muteState.hasAuxiliary)return a.remoteAuxiliaryTrack.getVideoFrame()}else{if(n==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(n==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var o,n;this._speakerId=e,(o=this._localAudioTrack)==null||o.setAudioOutput(e),(n=this._localScreenAudioTrack)==null||n.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(a=>a.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return DA(this,null,function*(){(yield Nm()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(Xt.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),Dg=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($C,"/en/TRTC.html#.setCurrentSpeaker"))})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return DA(this,null,function*(){var o;let{userId:n}=e;if(this._remoteAudioConfigMap.has(n))return void this._log.warn("remote audio has already started. userId:".concat(n));let a=this._room.remotePublishedUserMap.get(n);if(!a)return;let I={},c=a.remoteAudioTrack;c.on("decode-failed",u=>{this.emit(Xt.ERROR,new vi({code:Si.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(c),this._speakerId&&c.setAudioOutput(this._speakerId);try{let u=(o=this._remoteAudioVolumeMap.get(n))!=null?o:this._remoteAudioVolumeMap.get("*"),d=hr(u)?u:100;I.volume=d,this._remoteAudioConfigMap.set(n,e),yield this._room.subscribe(c),Jn(Ln(c,"decode-failed"),Qc(Ln(c,Uo.INIT)),Ks(()=>{this.startPlugin(W4.Name,{track:c,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:I,track:c}),S.emit("115",{userId:n,room:this.room}),c.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:c.outMediaTrack,refId:"ra-".concat(n)})}catch(u){throw this._remoteAudioConfigMap.delete(n),u}this._emitTrackEvent(c)})}_stopRemoteAudio(e){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return DA(this,null,function*(){let n=this._room.remotePublishedUserMap.get(e.userId);n&&(n.remoteAudioTrack.stop(),n.muteState.hasAudio&&o&&(yield this._room.unsubscribe(n.remoteAudioTrack)),this._mediaTrackMap.delete(n.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId)),S.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:"ra-".concat(e.userId)})})}_enableVideoDecodeFallback(e,o){let n,a=this._room.videoDecodeFallbackType;a&&this._plugins.has("TRTCVideoDecoder")&&(e.log.debug("remote video will fall back when decode failed",e.id),Jn(Ln(e,"decode-failed"),Qc(Ln(e,Uo.INIT)),Oq(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:a})}),Mx(Ln(e,"decode-downgrade-state-changed")),Ks(I=>{n=I.state,this.emit(Xt.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,fi(bt({},I),{streamType:o,userId:e.userId}))},I=>{e.log.error("fallback",I)},()=>{n==="STARTED"&&e.log.info("fallback complete")})))}_updateVideoPlayOption(e){return DA(this,arguments,function(o){let{view:n,playOption:a,track:I,prevConfig:c}=o;return function*(){if(I.setMirror(a.mirror),Ee(n)&&c&&c.view&&!$R(a)){let u=jf(c.view);u.length>0&&(yield I.play(u,a))}if(!Ee(n)){let u=jf(n);u.length>0?yield I.play(u,a):I.stop()}}()})}_updateAudioPlayOption(e){return DA(this,arguments,function(o){var n=this;let{playOption:a={},track:I,prevConfig:c}=o;return function*(){if(!I.isPlayCalled)try{yield I.play(null,a)}catch{}if(Ee(a.muted)||I.setPlayerMute(a.muted),Ee(a.volume)||I.setAudioVolume(a.volume/100),I instanceof km&&I.mediaTrack){let u=a.muted===!1&&!Ee(a.volume)&&a.volume>0?"add":"remove";n.room.audioManager.updateAudioReference({type:u,audioReference:I.mediaTrack,refId:"em"})}else if(I instanceof Tx){let u=a.muted?0:a.volume;if(Ee(u))return;n.room.audioManager.updateAudioReference({type:"updateVolume",refId:"ra-".concat(I.userId),volume:a.volume})}}()})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],n=e.isRemote?e.userId:"";e.outMediaTrack&&(o&&this._mediaTrackMap.get(e.outMediaTrack)===n||(this._mediaTrackMap.set(e.outMediaTrack,n),this.emit(Xt.TRACK,{userId:n,streamType:El(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var e,o,n;let a=[];if((e=this._localAudioConfig)!=null&&e.publish&&this._localAudioTrack&&a.push(this._localAudioTrack),(o=this._localVideoConfig)!=null&&o.publish&&this._localVideoTrack&&a.push(this._localVideoTrack),(n=this._localScreenConfig)!=null&&n.publish&&(this._localScreenTrack&&a.push(this._localScreenTrack),this._localScreenAudioTrack&&a.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),a.length!==0)return Promise.all(a.map(I=>this._room.publish(I).catch(()=>{})))}_observeView(e){let{remoteTrack:o,view:n,receiveWhenViewVisible:a,viewRoot:I}=e;if(Ee(n)||Ee(a))return;let c=this._remoteVideoConfigMap.get("".concat(o.userId,"_").concat(El(o.streamType)));if(!c)return;let u=c.observer||void 0;if(n===null||Aa(n)&&n.length===0||!a)return u?.disconnect(),void(o.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",o.userId,o.strMediaType),this._room.subscribe(o).catch(()=>{})));let d=c.visibleViewMap||new Map,R=-1;(!u||u.root!==I)&&(u?.disconnect(),d.clear(),u=new IntersectionObserver(_=>{_.forEach(Z=>{d.set(Z.target,Z.isIntersecting),o.log.info("view ".concat(Z.target.id," is").concat(Z.isIntersecting?"":" not"," visible"))}),clearTimeout(R),R=window.setTimeout(()=>{[...d.values()].find(Z=>Z)?o.isSubscribed||this._room.subscribe(o).catch(()=>{}):o.isSubscribed&&this._room.unsubscribe(o).catch(()=>{})},200)},{root:I}));let k=new Set(jf(n));d.forEach((_,Z)=>{k.has(Z)||(u.unobserve(Z),d.delete(Z))}),k.forEach(_=>{d.set(_,!0),u.observe(_)}),u.takeRecords().forEach(_=>{d.set(_.target,_.isIntersecting)}),c.visibleViewMap=d,c.observer=u}_exitRoom(){return DA(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return DA(this,null,function*(){var e,o;if(this._localScreenTrack){if(this._room.isJoined){let n=[];(e=this._localScreenConfig)!=null&&e.publish&&n.push(this._localScreenTrack),this._localScreenAudioTrack&&n.push(this._localScreenAudioTrack),yield Promise.all(n.map(a=>this._room.unpublish(a).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),pr(this._localScreenTrack),this._localScreenTrack=null,delete this._room.capturedLocalAuxVideoTrack,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,o){return DA(this,null,function*(){var n,a;if(!e||!o)return;let I=(n=e.trackSettings)==null?void 0:n.displaySurface;if(((a=o.trackSettings)==null?void 0:a.echoCancellation)===!1&&(I==="monitor"||I==="browser"&&e.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(c){this._log.warn("start audioProcessor plugin failed: ",c)}}})}_onLocalTrackCaptured(e){let{track:o}=e;o.kind==="audio"&&(!Dg||jT(Dg))&&(this._initActiveSpeaker(),S.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return DA(this,null,function*(){if(Dg&&!jT(Dg))this.emit(Xt.DEVICE_CHANGED,{type:"speaker",action:"active",device:Dg});else{let e=yield Nm();e[0]&&!jT(e[0])?(Dg=e[0],this.emit(Xt.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):S.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable(e){let{userId:o}=e,n=this._remoteAudioMuteMap.has(o)?this._remoteAudioMuteMap.get(o):this._remoteAudioMuteMap.get("*");(n===!1||this._room.autoReceiveAudio&&!n)&&this._doStartRemoteAudio({userId:o}).catch(()=>{})}_onVideoAvailable(e){let{userId:o,streamType:n}=e;if(!this._room.autoReceiveVideo)return;let a=this._room.remotePublishedUserMap.get(o);if(a){let I=n==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack,c=[I];this._room.autoReceiveAudio&&a.remoteAudioTrack.isAvailable&&c.push(a.remoteAudioTrack),this._room.subscribe(...c).then(()=>{this._emitTrackEvent(I)}).catch(()=>{})}}_onAudioUnavailable(e){let{userId:o,muteState:n}=e;n.hasAudio&&n.audioMuted||this._stopRemoteAudio({userId:o},!1).catch(()=>{})}_onVideoUnavailable(e){let{userId:o,streamType:n}=e;this._stopRemoteVideo({userId:o,streamType:n},!1).catch(()=>{})}_onDataChannelAvailable(){if(this.listeners("realtime-transcriber-message").length>0)return this._room.subscribeDataChannel()}sendSEIMessage(e,o){var n;let a=this._plugins.get("SEI");a&&(a.update({buffer:e,options:fi(bt({seiPayloadType:243},o),{small:!((n=this._localVideoTrack)==null||!n.small)})}),ct.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var o,n;(n=(o=this._room).sendCustomMessage)==null||n.call(o,e),ct.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,o){return DA(this,null,function*(){return this._log.info("callExperimentalAPI(".concat(e,", ").concat(JSON.stringify(o),")")),VeA.call(e,bt({trtcInstance:this},o))})}static setLogLevel(e,o){nA.setLogLevel(e),Ee(o)||(o?nA.enableUploadLog():nA.disableUploadLog())}static isSupported(){return ST(td.frameWorkType)}static getPermissions(e){return DA(this,arguments,function(o){let{request:n=!0,types:a=["camera","microphone"]}=o;return function*(){n&&(yield Vx.request(a).catch(u=>{var d;return nA.error("getPermissions request failed, error: ".concat((d=u?.message)!=null?d:u))}));let[I,c]=yield Promise.all([Vx.get("camera"),Vx.get("microphone")]);return{camera:I,microphone:c}}()})}static getCameraList(){return WQ(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getMicrophoneList(){return jQ(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getSpeakerList(){return Nm(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static setCurrentSpeaker(e){return DA(this,null,function*(){if(ra&&(e===aG.SPEAKER||e===aG.HEADSET)){let o=yield td.getMicrophoneList(),n="";return o.forEach(a=>{a.label===e&&(n=a.deviceId)}),n?void cG.forEach(a=>DA(null,null,function*(){a._localAudioTrack&&(yield a.updateLocalAudio({option:{microphoneId:n}}))})):void 0}(yield Nm()).forEach(o=>{o.deviceId===e&&(cG.forEach(n=>{n._setCurrentSpeaker(e),n.emit(Xt.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),Dg=o)})})}static _addKVStat(e){let{type:o,key:n,value:a,base:I,useUV:c,version:u,max:d}=e;switch(u&&(oB.version=u),o){case"count":oB.addCount({key:n,useUV:c});break;case"enum":oB.addEnum({key:n,value:a,useUV:c});break;case"number":oB.addNumber({key:n,value:a,split:I,max:d})}}get localVideoTrack(){return this._localVideoTrack}get localScreenTrack(){return this._localScreenTrack}get localScreenAudioTrack(){return this._localScreenAudioTrack}};G(Qo,"VERSION",J4),G(Qo,"_loggerManager",nA),G(Qo,"EVENT",Xt),G(Qo,"ERROR_CODE",Si),G(Qo,"TYPE",aG),G(Qo,"frameWorkType",30),vt([Hn({replaceArg:A=>({argIndex:0,value:{name:"plugin"in A?A.plugin.Name:A.Name,assetsPath:"assetsPath"in A?A?.assetsPath:"default"}})})],Qo.prototype,"use"),vt([vI(mg.TRTC.enterRoom),Fm("room",(A,e)=>{let[o]=A,[n]=e;return(o.roomId||o.strRoomId)===(n.roomId||n.strRoomId)&&o.userId===n.userId&&o.sdkAppId===n.sdkAppId}),Dn(A=>function(e){return this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),A.call(this,e)}),Hn()],Qo.prototype,"enterRoom"),vt([Hn()],Qo.prototype,"exitRoom"),vt([vI(mg.TRTC.switchRoom),Hn(),WT()],Qo.prototype,"switchRoom"),vt([vI(mg.TRTC.switchRole),HM("room",{merge:(A,e)=>e}),Hn()],Qo.prototype,"switchRole"),vt([Hn()],Qo.prototype,"destroy"),vt([vI(mg.TRTC.startLocalAudio),Fm("audio",(A,e)=>{let[o]=A,[n]=e;var a,I;return((a=o?.option)==null?void 0:a.microphoneId)===((I=n?.option)==null?void 0:I.microphoneId)}),Hn()],Qo.prototype,"startLocalAudio"),vt([vI(mg.TRTC.updateLocalAudio),HM("audio",{debounce:{delay:200,getKey:()=>"".concat(z4,"-localAudio"),isNeedToDebounce:A=>{var e;return!Ee((e=A.option)==null?void 0:e.captureVolume)}}}),Hn()],Qo.prototype,"updateLocalAudio"),vt([Um("audio"),Hn()],Qo.prototype,"stopLocalAudio"),vt([vI(mg.TRTC.startLocalVideo),Fm("video",(A,e)=>{let[o]=A,[n]=e;var a,I;return((a=o?.option)==null?void 0:a.cameraId)===((I=n?.option)==null?void 0:I.cameraId)}),Hn()],Qo.prototype,"startLocalVideo"),vt([vI(mg.TRTC.updateLocalVideo),HM("video"),Hn()],Qo.prototype,"updateLocalVideo"),vt([Um("video"),Hn()],Qo.prototype,"stopLocalVideo"),vt([vI(mg.TRTC.startScreenShare),Fm("screen",()=>!0),Hn()],Qo.prototype,"startScreenShare"),vt([vI(mg.TRTC.updateScreenShare),HM("screen"),Hn()],Qo.prototype,"updateScreenShare"),vt([Hn()],Qo.prototype,"stopScreenShare"),vt([vI(mg.TRTC.startRemoteVideo),Fm(A=>"v".concat(A.userId).concat(A.streamType),()=>!0),Hn({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],Qo.prototype,"startRemoteVideo"),vt([vI(mg.TRTC.updateRemoteVideo),HM(A=>"v".concat(A.userId).concat(A.streamType)),Hn({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],Qo.prototype,"updateRemoteVideo"),vt([vI(mg.TRTC.stopRemoteVideo),Dn(A=>function(e){return DA(this,null,function*(){if(e.userId==="*"){let o=[];return this._room.remotePublishedUserMap.forEach(n=>{this._remoteVideoConfigMap.has("".concat(n.userId,"_main"))&&o.push(this.stopRemoteVideo({streamType:"main",userId:n.userId}).catch(()=>{})),this._remoteVideoConfigMap.has("".concat(n.userId,"_sub"))&&o.push(this.stopRemoteVideo({streamType:"sub",userId:n.userId}).catch(()=>{}))}),Promise.all(o)}return A.call(this,e)})}),Hn({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],Qo.prototype,"stopRemoteVideo"),vt([Um(A=>"v".concat(A.userId).concat(A.streamType))],Qo.prototype,"_stopRemoteVideo"),vt([vI(...mg.TRTC.muteRemoteAudio),Hn({getRemoteId:A=>A})],Qo.prototype,"muteRemoteAudio"),vt([H4(...mg.TRTC.setRemoteAudioVolume),function(A,e){return Dn((o,n)=>function(){for(var a=arguments.length,I=new Array(a),c=0;c{var _;(_=VM.get(this))==null||_.delete(d)},A);u.set(d,k)}else{clearTimeout(R);let k=window.setTimeout(()=>{var _;o.apply(this,I),(_=VM.get(this))==null||_.delete(d)},A);u.set(d,k)}})}(200,A=>A),Hn({getRemoteId:A=>A})],Qo.prototype,"setRemoteAudioVolume"),vt([tK("start"),Tm(A=>{var e;return(e=A.afterStart)==null?void 0:e.call(A)}),Fm((A,e)=>A.disableRandomCall?null:A.getAlias()+A.getGroup(e)),Hn({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>ex[A.getName()],ignoreLog:A=>A.getName()==="Debug",ignoreErrorLog:A=>A.getName()==="AudioProcessor"})],Qo.prototype,"startPlugin"),vt([tK("update"),HM((A,e)=>A.disableRandomCall?null:A.getAlias()+A.getGroup(e),{merge:(A,e)=>(tB(A[1],e[1]),A)}),Hn({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>Jh[A.getName()]})],Qo.prototype,"updatePlugin"),vt([tK("stop"),Um((A,e)=>{if(A.disableRandomCall)return null;let o=A.getGroup(e),n=A.getAlias();return o==="*"?new RegExp("".concat(n,".*")):n+o}),Hn({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>MM[A.getName()]})],Qo.prototype,"stopPlugin"),vt([H4(...mg.TRTC.enableAudioVolumeEvaluation)],Qo.prototype,"enableAudioVolumeEvaluation"),vt([Hn()],Qo.prototype,"getVideoSnapshot"),vt([Hn()],Qo.prototype,"_setCurrentSpeaker"),vt([Fm(A=>"a".concat(A.userId),()=>!0)],Qo.prototype,"_startRemoteAudio"),vt([Dn(A=>function(e){return DA(this,null,function*(){return e.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(fi(bt({},e),{userId:o.userId})).catch(()=>{}))):A.call(this,e)})}),Um(A=>"a".concat(A.userId))],Qo.prototype,"_stopRemoteAudio"),vt([Um("room")],Qo.prototype,"_exitRoom"),vt([Um("screen")],Qo.prototype,"_stopScreenShare"),vt([vI(...mg.TRTC.sendSEIMessage),B4({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var A=arguments.length,e=new Array(A),o=0;oA.data.byteLength})],Qo.prototype,"sendCustomMessage"),vt([Hn()],Qo.prototype,"callExperimentalAPI"),vt([Om()],Qo,"create"),vt([vI(mg.TRTC.create)],Qo,"_create"),vt([Om()],Qo,"setLogLevel"),vt([Om()],Qo,"isSupported"),vt([Om(),Hn()],Qo,"getPermissions"),vt([Om()],Qo,"getCameraList"),vt([Om()],Qo,"getMicrophoneList"),vt([Om()],Qo,"getSpeakerList");var EG=Qo,jeA=class{constructor(){G(this,"_set",new Set),S.on(K.LEAVE_SUCCESS,this.delete,this),S.on(K.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add(A){let{room:e,roomId:o}=A;if(e.scene==="rtc")return;let n=this.getKey(e.userId,o||e.roomId,e.sdkAppId,e.useStringRoomId);this._set.add(n)}delete(A){let{room:e,roomId:o}=A;if(e.scene==="rtc")return;let n=this.getKey(e.userId,e.roomId||o,e.sdkAppId,e.useStringRoomId);this._set.delete(n)}getKey(A,e,o,n){return"".concat(o,"_").concat(e,"_").concat(A,"_").concat(n)}isJoined(A){let{userId:e,roomId:o,sdkAppId:n,room:a}=A;return a.scene!=="rtc"&&this._set.has(this.getKey(e,o,n,a.useStringRoomId))}handleSwitchRoomSuccess(A){let{room:e,currentRoomId:o,targetRoomId:n}=A;e.scene!=="rtc"&&(this._set.delete(this.getKey(e.userId,o,e.sdkAppId,e.useStringRoomId)),this._set.add(this.getKey(e.userId,n,e.sdkAppId,e.useStringRoomId)))}};function WeA(){return DA(this,null,function*(){let A,e;try{let iA=yield jQ();A=iA&&iA.length}catch{}try{let iA=yield WQ();e=iA&&iA.length}catch{}let o={microphone:A,camera:e},{isH264EncodeSupported:n,isVp8EncodeSupported:a,isH264DecodeSupported:I,isVp8DecodeSupported:c,isH265EncodeSupported:u,isH265DecodeSupported:d}=this.checkSystemResult.detail,R=kA.basis(),k={webRTC:R.isWebRTCSupported,getUserMedia:R.isGetUserMediaSupported,webSocket:R.isWebSocketsSupported,screenShare:R.isScreenShareSupported,webAudio:R.isWebAudioSupported,h264Encode:n,h264Decode:I,vp8Encode:a,vp8Decode:c,h265Encode:u,h265Decode:d},_={browser:R.browser,os:R.os,trtc:k,devices:o},Z={isWebCodecSupported:R.isWebCodecSupported,isMediaSessionSupported:R.isMediaSessionSupported,isWebTransportSupported:R.isWebTransportSupported};Jo.uploadEvent({log:"trtcstats-".concat(JSON.stringify(_)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(_))),Jo.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(Z)),userId:this.userId}),Dm()})}var zeA=es(hg()),Z4="1",cK="2",lG="3",ZeA="4",qx="5",XeA="6",Kx="7",X4="8",sB={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},$eA=[sB.UPDATE_REMOTE_MUTE_STAT,sB.UPLINK_NETWORK_STATS,sB.USER_LIST_RES,sB.MUTE_RESULT,sB.SERVER_FIRST_PACKAGE_RECEIVED,sB.RECEIVE_CUSTOM_MSG,sB.UPDATE_NETWORK_TIME_RESULT],io={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"},$4="publish_change",AtA="join",etA="leave",ttA="quality_report",Az="mute_uplink",ez="publish",EK="publish_state_change",jx="unpublish",tz="subscribe",lK="unsubscribe",CK="subscribe_change",itA="start_publishing",otA="stop_publishing",rtA="start_push_user_cdn",ntA="stop_push_user_cdn",atA="start_mcu_mix",stA="stop_mcu_mix",gtA="start_publish_cdn_stream",ItA="update_publish_cdn_stream",ctA="stop_publish_cdn_stream",EtA="get_user_list",ltA="change_role",BK="update_constraint_config",CtA="rebuild_pc",BtA="join/v2",iz="publish/v2",oz="subscribe/v3",utA="ability_status_report",QtA="reconnect",dtA="channel_msg",htA="switch_room",ptA="update_network_time",ftA=new Set([ez,$4,EK,jx,tz,CK,lK,iz,oz]),Wx=new Set,mtA=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],DtA=0,rz=class extends zeA.default{constructor(A){var e,o,n;super(),G(this,"room"),G(this,"sdkAppId"),G(this,"userId"),G(this,"userSig"),G(this,"url"),G(this,"backupUrl"),G(this,"destroyed",!1),G(this,"_socketInUse"),G(this,"_socket"),G(this,"_backupSocket"),G(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0}),G(this,"_currentState","DISCONNECTED"),G(this,"_isReconnecting",!1),G(this,"_seq",0),G(this,"_log"),G(this,"_lastMessageTime",-1),G(this,"_connectStartTime",-1),G(this,"_stopConnectRetry"),G(this,"_isFirstConnect",!0),G(this,"bytesSent",0),G(this,"bytesReceived",0),G(this,"keepAlive",!1),G(this,"signalDomainWhenUnifiedProxy"),G(this,"stopKeepAliveTimeout"),G(this,"stopPrelinkTimeout"),G(this,"rtt",0),G(this,"prelink",!1),G(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 a=((o=(e=this.room.scheduleResult)==null?void 0:e.config)==null?void 0:o.keepAliveClient)||0;(n=this.room.joinParams)!=null&&n.keepAlive&&!a&&(a=1),a-Wx.size>0&&this.room.enableSPC&&(this.keepAlive=!0,Wx.add(this)),this.url=A.url,this.backupUrl=A.backupUrl,this._seq=0,this._log=nA.createLogger({parent:this.room.getLogger(),id:"ws".concat(++DtA),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 e=new URLSearchParams(location.search);return mtA.forEach(o=>{let n=e.get("trtc_".concat(o));n&&(A+="&".concat(o,"=").concat(encodeURIComponent(n)))}),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 DA(this,arguments,function(){var A=this;let e=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(e?" timeout: ".concat(e):""," keepAlive: ").concat(Number(A.keepAlive))),A.emitConnectionStateChanged("CONNECTING"),A._connectStartTime=ki();let o=[A.connectWS({url:A._urlWithParam,isMain:!0,timeout:e})];A.race&&A._backupUrlWithParam!==A._urlWithParam&&o.push(A.connectWS({url:A._backupUrlWithParam,isMain:!1,timeout:e})),A._socketInUse=yield qf(o),A.unbindAndCloseSocket(A._socketInUse===A._socket?fA.BACKUP:fA.MAIN),A._isFirstConnect&&(ct.addSuccessEvent({key:521720}),A._isFirstConnect=!1),A.emitConnectionStateChanged("CONNECTED")}()})}connectWS(A){let{url:e,timeout:o,isMain:n}=A,a=new WebSocket(e);this.bindSocket(a),n?this._socket=a:this._backupSocket=a;let I=-1;return new Promise((c,u)=>{a.onclose=u,a.onerror=u,a.onopen=()=>c(a),o&&(I=setTimeout(()=>{this.unbindAndCloseSocket(n?fA.MAIN:fA.BACKUP),u(new Ct({code:Ge.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},o))}).finally(()=>{a.onclose=null,a.onerror=null,a.onopen=null,clearTimeout(I)})}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===fA.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(qx,new Ct({code:Ge.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(fA.MAIN),this.unbindAndCloseSocket(fA.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(qx,new Ct({code:Ge.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(A){if(!this.isConnected)return;let{isOnline:e}=this;this._lastMessageTime=Date.now(),e||this.emit(X4),this.bytesReceived+=eM(A.data);let o=JSON.parse(A.data),{cmd:n,data:a}=o,I=Object.values(sB),c=Object.keys(sB)[I.indexOf(n)],u=io[c]||n;switch($eA.includes(n)||(this._log.debug("received ".concat(n," msg: ").concat(A.data)),u&&this._log.info("Received event: [ ".concat(u," ]"))),n){case sB.CHANNEL_SETUP_RESULT:if(o.code===0)this._signalInfo.clientIp=a.clientIp,this._signalInfo.signalIp=a.signalInnerIp,a.svrTime&&nu(a.svrTime-new Date().getTime()),this._log.info("ChannelSetup Success ".concat(ki()-this._connectStartTime)),ct.addSuccessEvent({key:521701,cost:ki()-this._connectStartTime}),this._connectStartTime=-1,this.room.firewallDetector.resetTimeoutCount(),this.emit(Z4,{signalInfo:this._signalInfo});else{let d=new Ct({code:Ge.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:o.code,message:Wi({key:Mi.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:o.code,errorMsg:o.message}})});this._log.error("".concat(o.code,", ").concat(o.message)),this.close(),ct.addFailedEvent({key:521701,error:d}),this.emit(qx,d)}break;case sB.JOIN_ROOM_RESULT:o.code===0&&(this._signalInfo.relayIp=a.relayOuterIp,this._signalInfo.relayInnerIp=a.relayInnerIp,this._signalInfo.bakRelayIps=a.bakRelayIps,this._signalInfo.relayPort=a.relayPort,this._signalInfo.tinyId=o.tinyId,this._signalInfo.endReportExtend=a.endReportExtend,this._signalInfo.reportToken=a.reportToken,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(u,{data:o});break;default:this.emit(String(u),{data:o})}}reGetSignalChannelUrl(){return DA(this,null,function*(){try{if(!this.room.joinParams)return;Nu(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:A,backupUrl:e}=this.room.getSignalChannelUrl();this.url=A,this.backupUrl=e}catch{}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let A=this._socketInUse===this._socket;this.unbindAndCloseSocket(A?fA.MAIN:fA.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return DA(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:e}=this.room,{relayIp:o,relayInnerIp:n,relayPort:a}=this._signalInfo,{data:I}=yield this.sendWaitForResponse({command:QtA,data:{roomId:A,useStringRoomId:e,relayInnerIp:n,relayOuterIp:o,relayPort:a},responseCommand:io.CHANNEL_RECONNECT_RESULT});I.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),ct.addSuccessEvent({key:521702,cost:ki()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(ct.addFailedEvent({key:521702,error:I.code}),this._log.warn("reconnect failed, ".concat(I.code," ").concat(I.message)),this.room.reJoin())}catch(A){this._log.error(A),this.room.reJoin()}}})}send(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let o={cmd:A,data:e,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},n=JSON.stringify(o);return this._socketInUse.send(n),ftA.has(A)&&this._log.info("send",A,e),this.bytesSent+=eM(n),o.seq}}sendWaitForResponse(A){let{command:e,data:o,timeout:n=5e3,responseCommand:a,commandDesc:I,enableLog:c=!0,addReceiveTime:u=!1}=A;return new Promise((d,R)=>{let k=()=>{clearTimeout(_),R(new Ct({code:Ge.API_CALL_ABORTED,message:"".concat(e," aborted due to connection closed")}))};this.once(Kx,k);let _=setTimeout(()=>{this.off(a,Z),this.off(Kx,k);let cA=new Ct({code:Ge.API_CALL_TIMEOUT,message:Wi({key:Mi.API_CALL_TIMEOUT,data:{commandDesc:I,command:e}})});c&&this._log.warn(cA),R(cA)},n),Z=cA=>{cA.data.seq===iA&&(clearTimeout(_),this.off(a,Z),this.off(Kx,k),u&&(cA.data.receiveTime=Date.now()),d(cA))};this.on(a,Z);let iA=this.send(e,o)})}sendWaitForResponseWithRetry(A){let{commandDesc:e,command:o,retries:n=0,retryTimeout:a=0}=A;return Zf({retryFunction:this.sendWaitForResponse,onError:I=>{let{retry:c,reject:u,error:d}=I;!this.room.isJoined||this.destroyed||d.code===Ge.API_CALL_ABORTED?u(d):this.isOnline?c():(this._log.warn("retry ".concat(o," when connected")),this.once(X4,c))},onRetrying:I=>{this._log.warn("".concat(e||o," timeout observed, retrying [").concat(I,"/").concat(n,"]"))},settings:{retries:n,timeout:a},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),Wx.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(fA.MAIN),this.unbindAndCloseSocket(fA.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(Kx)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var A;let e=(A=this._signalInfo.bakRelayIps)==null?void 0:A.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}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(io.JOIN_ROOM_RESULT,e)},1e3*A);let e=o=>{o.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(io.JOIN_ROOM_RESULT,e))};this.on(io.JOIN_ROOM_RESULT,e)}}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(io.JOIN_ROOM_RESULT,e)},1e3*A);let e=o=>{o.data.code===0&&(this._log.info("stopPrelink clear timeout"),clearTimeout(this.stopPrelinkTimeout),this.off(io.JOIN_ROOM_RESULT,e))};this.on(io.JOIN_ROOM_RESULT,e)}markPrelinkConnected(A){this._prelinkConfig=fi(bt({},A),{linkedTime:Date.now()})}isPrelinkValid(A,e,o){return!(!this.prelink||!this._prelinkConfig)&&(A!==this._prelinkConfig.sdkAppId||e!==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 e={prevState:this._currentState,state:A};A==="CONNECTING"&&(e.isReconnecting=this._isReconnecting),this.emit(cK,e),this._currentState=A,A==="CONNECTED"?this.emit(lG):A==="DISCONNECTED"&&this.emit(XeA)}};vt([nB({settings:{retries:1/0,timeout:2e3},onError(A,e){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(ct.addFailedEvent({key:521720,error:A}),this._isFirstConnect=!1),this.room.firewallDetector.increaseTimeoutCount(),e())},onRetrying(A,e){this._log.warn("retrying to connect ".concat(A)),A>=3&&A%3==0&&this.reGetSignalChannelUrl(),e&&(this._stopConnectRetry=e,(this.room.isDestroyed||this.destroyed)&&e())}})],rz.prototype,"connect");var ytA=es(hg()),nz=!1,XQ=class{constructor(A){G(this,"userId"),G(this,"tinyId"),G(this,"_sdpSemantics"),G(this,"_isUplink"),G(this,"_room"),G(this,"_log"),G(this,"_signalChannel"),G(this,"_isErrorObserved",!1),G(this,"_waitForPeerConnectionConnectedPromise"),G(this,"_waitForPeerConnectionConnectedPromiseReject",null),G(this,"_peerConnection",null),G(this,"_emitter",new ytA.default),G(this,"_currentState","DISCONNECTED"),G(this,"_isReconnecting",!1),G(this,"_reconnectionCount",0),G(this,"_reconnectionTimer",-1),G(this,"_isFirstConnection",!0),G(this,"_prevTime",-1),G(this,"_localAddress"),G(this,"_remoteAddress"),G(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=ki())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,ct.addSuccessEvent({key:521705,cost:Math.min(ki()-this._prevTime,3e4)})):this._isReconnecting&&ct.addSuccessEvent({key:521706,cost:ki()-this._prevTime}),this._prevTime=-1}catch(A){throw this._isFirstConnection?(this._isFirstConnection=!1,ct.addFailedEvent({key:521705,error:A})):this._isReconnecting&&this._reconnectionCount>=3&&ct.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 Ct({code:Ge.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return AB;let A=null;if(this._isUplink){if(!AI()||this._peerConnection.getSenders().length===0)return AB;A=this._peerConnection.getSenders()[0].transport}else{if(!Vh()||this._peerConnection.getReceivers().length===0)return AB;A=this._peerConnection.getReceivers()[0].transport}return A?A.state:AB}onConnectionStateChange(A){let e=this._peerConnection.iceConnectionState,o=this.getDTLSTransportState();if(this._log.info("connectionState: ".concat(A.target.connectionState,", ICE: ").concat(e,", DTLS: ").concat(o)),A.target.connectionState===hi.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),A.target.connectionState===hi.FAILED||A.target.connectionState===hi.CLOSED){let n="connection ".concat(A.target.connectionState,". ICE Transport state: ").concat(e,", DTLS Transport state: ").concat(o),a=new Ct({message:n,code:Ge.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",a)}(A.target.connectionState===hi.CONNECTED||A.target.connectionState===hi.COMPLETED)&&(this.logSelectedCandidate(),Jo.logSuccessEvent({userId:this._room.userId,eventType:oa.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(A){return A!==this._currentState&&(A==="CONNECTED"&&(this._room.firewallDetector.resetTimeoutCount(),nz=!0),S.emit(K.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 DA(this,null,function*(){if(!this._peerConnection)return;let A=yield this._peerConnection.getStats();for(let[,e]of A)if(dm(e)){let o=A.get(e.localCandidateId),n=A.get(e.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)),n&&(this._log.info("remote candidate: ".concat(n.candidateType," ").concat(n.protocol,":").concat(n.ip||n.address,":").concat(n.port)),this._remoteAddress="".concat(n.protocol,":").concat(n.ip||n.address));break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise((A,e)=>{if(this._currentState==="CONNECTED")return A();this._waitForPeerConnectionConnectedPromiseReject=e;let o=c=>{c.state==="CONNECTED"&&(clearTimeout(I),a(),A())},n=c=>{let{room:u}=c;u===this._room&&(clearTimeout(I),a(),e(new Ct({code:Ge.API_CALL_ABORTED,message:Wi({key:Mi.CONNECTION_ABORTED,data:"leave room"})})))},a=()=>{S.off(K.LEAVE_SUCCESS,n,this),this._emitter.off("connection-state-changed",o,this)},I=setTimeout(()=>{a();let c=new Ct({code:Ge.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),e(c)},SN);S.on(K.LEAVE_SUCCESS,n,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(lG,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Qh()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let A=new Ct({code:this._isUplink?Ge.UPLINK_RECONNECTION_FAILED:Ge.DOWNLINK_RECONNECTION_FAILED,message:Wi({key:this._isUplink?Mi.UPLINK_RECONNECTION_FAILED:Mi.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(lG,this.reconnect,this),-1)}on(A,e,o){this._emitter.on(A,e,o)}off(A,e,o){this._emitter.off(A,e,o)}getIsReconnecting(){return this._isReconnecting}get isH264(){var A,e;return!((e=(A=this._peerConnection)==null?void 0:A.remoteDescription)==null||!e.sdp.includes("H264"))}setOffer(A){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(A)}setAnswer(A){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(A)}};vt([Zh(521712,!1)],XQ.prototype,"setOffer"),vt([Zh(521713,!1)],XQ.prototype,"setAnswer");var az=es(BN()),rs=function(A){return az.default.parse(A)},tp=function(A){return az.default.write(A)};function uK(A){return Object.keys(A).filter(e=>A[e])}var zx=class s6 extends XQ{constructor(e){super(fi(bt({},e),{isUplink:!1})),G(this,"_flag",0),G(this,"isRobot",!1),G(this,"role","anchor"),G(this,"remoteAudioTrack"),G(this,"remoteVideoTrack"),G(this,"remoteAuxiliaryTrack"),G(this,"avPlayerStateSyncManager"),G(this,"ssrc",{audio:0,video:0,auxiliary:0}),G(this,"_isSDPExchanging",!1),G(this,"_videoCodec"),G(this,"fromType"),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new Tx(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new nG(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new l4(this._room,this),this.avPlayerStateSyncManager=new $q({log:this._log,audioPlayer:this.remoteAudioTrack.player,videoPlayer:this.remoteVideoTrack.player})}get videoCodec(){var e,o;let n=(o=(e=this._peerConnection)==null?void 0:e.remoteDescription)==null?void 0:o.sdp;return n?n.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return RQ(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var o,n,a;e!==this._flag&&(this._flag=e,(o=this.remoteAudioTrack)==null||o.onFlagChanged(),(n=this.remoteVideoTrack)==null||n.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(e){return e===fA.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.avPlayerStateSyncManager.destroy(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,n;let a=this._currentState,I=super.emitConnectionStateChangedEvent(e);return I&&a!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:a,state:e}),(n=this.remoteAuxiliaryTrack)==null||n.emit("connection-state-changed",{prevState:a,state:e})),I}onTrack(e){let o=e.streams[0],{track:n}=e,a=o.id===RI?fA.MAIN:fA.AUXILIARY;this._log.debug("ontrack ".concat(a," ").concat(n.kind));let I=fA.AUDIO;n.kind===fA.VIDEO&&(I=a===fA.MAIN?fA.VIDEO:fA.AUXILIARY);let c=this.remoteAudioTrack;I===fA.VIDEO?c=this.remoteVideoTrack:I===fA.AUXILIARY&&(c=this.remoteAuxiliaryTrack),c.setInputMediaStreamTrack(n)}addRRTRLine(e){let o=e.split(`\r `),n=new Map;o.forEach((I,c)=>{/^a=rtcp-fb:/.test(I)&&o[c+1]&&!/^a=rtcp-fb:/.test(o[c+1])&&n.set(c+1,"".concat(I.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))});let a=[...n];for(let I=0;I{n.type===fA.VIDEO&&n.fmtp.forEach(a=>{a.config+=";sps-pps-idr-in-keyframe=1"})}),$h(o)}removeSDESDescription(e){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"],n=rs(e);return n.media.forEach(a=>{a.ext&&(a.ext=a.ext.filter(I=>!o.includes(I.uri)))}),$h(n)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,o){return DA(this,null,function*(){var n,a;try{if((((n=this._peerConnection)==null?void 0:n.connectionState)===hi.NEW||((a=this._peerConnection)==null?void 0:a.connectionState)===hi.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info("subscribe ".concat(o," ").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let I="subscribe_change";Object.values(e).find(c=>c===!0)||(I="unsubscribe"),yield this.sendSubscription(I,e)}else this.initialize(),yield this.connect(e)}catch(I){throw this._room.isJoined&&this.isStreamUnpublished(o)?(this._log.warn("".concat(I.message," ").concat(JSON.stringify(this.muteState))),new Ct({code:Ge.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):I}})}unsubscribe(e){return DA(this,arguments,function(o){var n=this;let{remoteTracks:a,streamType:I}=o;return function*(){if(n._currentState==="CONNECTED"&&(I==="main"&&!n.isMainStreamSubscribed||I==="auxiliary"&&!n.isAuxStreamSubscribed))return void n._log.info("".concat(I," stream already unsubscribed"));let c=bt({},n.subscribeState);a.forEach(d=>{switch(d.mediaType){case 1:c.audio=!1;break;case 4:c.video=!1;break;case 8:c.smallVideo=!1;break;case 2:c.auxiliary=!1}});let u="subscribe_change";Object.values(c).find(d=>d===!0)||(u="unsubscribe"),n._log.info("".concat(u==="unsubscribe"?u:"subscribe"," ").concat(I," [").concat(IK(c),"]")),yield n.sendSubscription(u,c),u==="unsubscribe"&&(n.closePeerConnection(),n.emitConnectionStateChangedEvent("DISCONNECTED"))}()})}unsubscribeDataChannel(){return DA(this,null,function*(){})}sendSubscription(e){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscribeState,n={srcTinyId:this.tinyId,srcUserId:this.userId},a=aK,I=io.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(n={audio:o.audio,bigVideo:o.video,auxVideo:o.auxiliary,smallVideo:o.smallVideo,srcTinyId:this.tinyId},a=sK,I=io.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:a,data:n,responseCommand:I,timeout:1e4}).then(c=>{let{data:u}=c;if(u.code!==0){let d=new Ct({code:u.code,message:Wi({key:Mi.ERROR_MESSAGE,data:{type:e,message:u.message}})});throw this._log.error(d),d}})}connect(){return DA(this,arguments,function(){var e=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(o),yield e.waitForPeerConnectionConnected()}catch(n){throw e.closePeerConnection(!0),n}}()})}exchangeSDP(e){return DA(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:o,sdp:n}=this._peerConnection.localDescription,a={type:o,sdp:n,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},I=yield this._signalChannel.sendWaitForResponse({command:W4,commandDesc:"exchange sdp",data:a,responseCommand:io.SUBSCRIBE_RESULT,timeout:aO});if(!this._peerConnection){let c=new Ct({code:Ge.INVALID_OPERATION,message:Wi({key:Mi.CONNECTION_CLOSED})});throw this._log.warn(c),c}yield this.onSubscribeResult(I),this._isSDPExchanging=!1}catch(o){throw this._isSDPExchanging=!1,o}})}createOffer(){return DA(this,null,function*(){let e={voiceActivityDetection:!1};sl()&&this._sdpSemantics===_f?(this._peerConnection.addTransceiver(fA.AUDIO,{direction:_r.RECVONLY}),this._peerConnection.addTransceiver(fA.VIDEO,{direction:_r.RECVONLY}),this._peerConnection.addTransceiver(fA.VIDEO,{direction:_r.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let o=yield this._peerConnection.createOffer(e);if(o.sdp){let{isH264DecodeSupported:n}=yield DT();n||(this._log.warn("remove h264 desc from sdp"),o.sdp=function(a){let I=rs(a);return I.media.forEach(c=>{var u,d;if(c.type===fA.VIDEO){let R=new Set;c.rtp.forEach(_=>{let{payload:Z,codec:iA}=_;return iA==="H264"&&R.add(Z)}),c.fmtp.forEach(_=>{let{payload:Z,config:iA}=_,cA=iA.match(/apt=(\d+)/);cA&&cA[1]&&R.has(Number(cA[1]))&&R.add(Z)});let k=_=>{let{payload:Z}=_;return!R.has(Z)};c.rtp=c.rtp.filter(k),c.rtcpFb=(u=c.rtcpFb)==null?void 0:u.filter(k),c.fmtp=c.fmtp.filter(k),c.payloads=(d=c.payloads)==null?void 0:d.split(" ").filter(_=>!R.has(Number(_))).join(" ")}}),$h(I)}(o.sdp)),o.sdp=this.addRRTRLine(o.sdp),o.sdp=this.addSPSDescription(o.sdp),o.sdp=function(a){let I=rs(a);return I.media.forEach(c=>{c.type===fA.AUDIO&&c.fmtp.forEach(u=>{u.config+=";sprop-stereo=1;stereo=1"})}),$h(I)}(o.sdp),this._sdpSemantics===_f&&(o.sdp=this.removeSDESDescription(o.sdp))}yield this.setOffer(o)})}onSubscribeResult(e){return DA(this,null,function*(){let{code:o,message:n=""}=e&&e.data||{},{type:a,sdp:I}=e&&e.data&&e.data.data||{};if(o===FR)throw new Ct({code:Ge.NOT_SUPPORTED_H264,message:Wi({key:Mi.NOT_SUPPORTED_H264DECODE})});try{if(o!==0)throw new Ct({code:o,message:Wi({key:Mi.EXCHANGE_SDP_FAILED,data:{errMsg:n}})});this._log.debug("accept remote answer: ".concat(I)),yield this.setAnswer({type:a,sdp:I}),this.updateSSRC(I)}catch(c){throw this._log.error(c),c}})}updateSSRC(e){try{rs(e).media.forEach(o=>{if(o.ssrcs)if(o.type===fA.AUDIO){let n=o.ssrcs.find(a=>{var I;return(I=a.value)==null?void 0:I.includes(RI)});n&&(this.ssrc.audio=Number(n.id))}else{let n=o.ssrcs.find(I=>{var c;return(c=I.value)==null?void 0:c.includes(RI)}),a=o.ssrcs.find(I=>{var c;return(c=I.value)==null?void 0:c.includes(tO)});n&&(this.ssrc.video=Number(n.id)),a&&(this.ssrc.auxiliary=Number(a.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 DA(this,null,function*(){if(!(zg(A6.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch{let o=fQ(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(e){let{audioDelay:o,videoDelay:n}=e;this.remoteAudioTrack.stat.end2EndDelay=o,this.remoteVideoTrack.stat.end2EndDelay=n}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}};vt([Dn(A=>function(){for(var e=arguments.length,o=new Array(e),n=0;n{let c=u=>{this._emitter.off("closed",c),I(new Ct({code:Ge.API_CALL_ABORTED,message:Wi({key:Mi.CONNECTION_ABORTED,data:u})}))};this._emitter.on("closed",c),A.apply(this,o).then(a,I).finally(()=>{this._emitter.off("closed",c)})})})],Jx.prototype,"subscribe"),vt([jh(521717,!1)],Jx.prototype,"unsubscribe"),vt([wm(WQ.prototype.afterConnect),MW(WQ.prototype.beforeConnect)],Jx.prototype,"connect");var ez=Jx,tz={voiceActivityDetection:!1},Hx=class e6 extends WQ{constructor(e){super(fi(bt({},e),{isUplink:!0})),G(this,"localMainAudioTrack",null),G(this,"localMainVideoTrack",null),G(this,"localAuxAudioTrack",null),G(this,"localAuxVideoTrack",null),G(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),G(this,"_isPublishingAux",!1),G(this,"_publishingLocalAudioTrack"),G(this,"_publishingLocalVideoTrack"),G(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}),G(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(e){super.close(e),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(e,o){var n,a,I;let c=this._currentState,u=super.emitConnectionStateChangedEvent(e);return u&&c!==e&&(o?o.emit("connection-state-changed",{prevState:c,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:c,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:c,state:e}),(I=this._publishingLocalVideoTrack)==null||I.emit("connection-state-changed",{prevState:c,state:e}))),u}publish(e){return DA(this,arguments,function(o){var n=this;let{localAudioTrack:a,localVideoTrack:I,isAuxiliary:c}=o;return function*(){let u;n._peerConnection||n.initialize(),a&&(n._publishingLocalAudioTrack=a),I&&(n._publishingLocalVideoTrack=I),n._isPublishingAux=c,I&&!c&&I.small&&(u=n._room.videoManager.smallTrack),n.sendMediaSettings(),sl()?yield n.publishByTransceiver({localAudioTrack:a,localVideoTrack:I,smallTrack:u,isAuxiliary:c}):yield n.publishByAddTrack({localAudioTrack:a,localVideoTrack:I,smallTrack:u}),n._publishingLocalAudioTrack=null,n._publishingLocalVideoTrack=null,n._isPublishingAux=!1,c?(I&&(n.localAuxVideoTrack=I),a&&(n.localAuxAudioTrack=a)):(I&&(n.localMainVideoTrack=I),a&&(n.localMainAudioTrack=a)),n.installTrackMuteEvents(a,I),n.sendMutedFlag()}()})}publishByTransceiver(e){return DA(this,arguments,function(o){var n=this;let{localAudioTrack:a,localVideoTrack:I,smallTrack:c,isAuxiliary:u}=o;return function*(){n._log.info("publish by transceiver");let d=new MediaStream,R=I?.outMediaTrack,k=a?.outMediaTrack;k&&d.addTrack(k),R&&d.addTrack(R);let _=n._peerConnection.getTransceivers();if(_.length===0)n._peerConnection.addTransceiver(k||fA.AUDIO,{direction:_r.SENDONLY,streams:[d]}),n._peerConnection.addTransceiver(u?fA.VIDEO:R||fA.VIDEO,{direction:_r.SENDONLY,streams:[d]}),n._peerConnection.addTransceiver(c||fA.VIDEO,{direction:_r.SENDONLY,streams:[d]}),n._peerConnection.addTransceiver(u&&R||fA.VIDEO,{direction:_r.SENDONLY,streams:[d]}),yield n.connect();else{let Z=[];if(k&&(_[0].sender.track||Z.push(0),yield _[0].sender.replaceTrack(k),yield n.setBandwidth({bandwidth:a?.profile.bitrate||40,type:fA.AUDIO})),R){let iA=u?3:1;yield _[iA].sender.replaceTrack(R),yield n.setBandwidth({bandwidth:I.profile.bitrate,type:fA.VIDEO,videoType:u?fA.AUXILIARY:fA.BIG}),Z.push(iA),c&&(yield _[2].sender.replaceTrack(c),yield n.setBandwidth({bandwidth:I.small.bitrate,type:fA.VIDEO,videoType:fA.SMALL}),Z.push(2))}yield n.setTransceiverDirection(_r.SENDONLY,Z),yield n.doPublishChange(),I?.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),I?.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()})}publishByAddTrack(e){return DA(this,arguments,function(o){var n=this;let{localAudioTrack:a,localVideoTrack:I,smallTrack:c}=o;return function*(){n._log.info("publish by addtrack");let u=I?.outMediaTrack,d=a?.outMediaTrack;if(n._peerConnection&&n._peerConnection.connectionState!=="new")return a&&d&&(yield n.addTrack(a)),void(u&&(yield n.addTrack(I)));let R=new MediaStream;if(d&&R.addTrack(d),u&&R.addTrack(u),d&&n._peerConnection.addTrack(d,R),u&&(n._peerConnection.addTrack(u,R),c)){let k=new MediaStream;k.addTrack(c),n._peerConnection.addTrack(c,k)}yield n.connect()}()})}enableSmall(e){return DA(this,null,function*(){let o=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield o[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(_r.SENDONLY,[2])):(yield o[2].sender.replaceTrack(null),yield this.setTransceiverDirection(_r.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(){for(var e=arguments.length,o=new Array(e),n=0;n{a&&(a?.on("mute",this.sendMutedFlag,this),a?.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(){for(var e=arguments.length,o=new Array(e),n=0;n{a&&(a?.off("mute",this.sendMutedFlag,this),a?.off("unmute",this.sendMutedFlag,this))})}unpublish(e){return DA(this,arguments,function(o){var n=this;let{localAudioTrack:a,localVideoTrack:I}=o;return function*(){if(!mu())return a&&a.outMediaTrack&&!I&&n.localMainVideoTrack?(yield n.removeTrack(a),void(n.localMainAudioTrack=null)):I&&I.outMediaTrack&&!a&&n.localMainAudioTrack?(yield n.removeTrack(I),void(n.localMainVideoTrack=null)):(yield n.doUnpublish(),n.uninstallTrackMuteEvents(a,I),void n.emitConnectionStateChangedEvent("DISCONNECTED",I));let c=I&&I===n.localAuxVideoTrack,u=I?.outMediaTrack,d=n._peerConnection.getSenders(),R=[];a&&(c?n.localAuxAudioTrack=null:n.localMainAudioTrack=null,!n.localAuxAudioTrack&&!n.localMainAudioTrack&&(yield d[0].replaceTrack(null),R.push(0))),u&&(c?(yield d[3].replaceTrack(null),n.localAuxVideoTrack=null,n._mediaSettings=fi(bt({},n._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),R.push(3)):(yield d[1].replaceTrack(null),yield d[2].replaceTrack(null),n.localMainVideoTrack=null,n._mediaSettings=fi(bt({},n._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),R.push(1,2))),n.isMainStreamPublished||n.isAuxStreamPublished?(yield n.setTransceiverDirection(_r.INACTIVE,R),yield n.doPublishChange(!1)):yield n.doUnpublish(),n.uninstallTrackMuteEvents(a,I),I?.emit("connection-state-changed",{prevState:n._currentState,state:"DISCONNECTED"})}()})}doPublishChange(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return DA(this,null,function*(){let o={state:this._room.publishState,constraintConfig:this._mediaSettings},n=yield this._signalChannel.sendWaitForResponse({command:nK,data:o,responseCommand:io.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(n.data.code,n.data.message)})}doUnpublish(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this._signalChannel.sendWaitForResponse({command:Yx,commandDesc:"unpublish",responseCommand:io.UNPUBLISH_RESULT,enableLog:e}).catch(o=>{if(o.getCode()===Ge.API_CALL_TIMEOUT)return Promise.resolve();throw o})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:o}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":o&&(this._mediaSettings.videoCodec="VP8");let n=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:a,localAuxVideoTrack:I}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?I=this._publishingLocalVideoTrack:a=this._publishingLocalVideoTrack),Jh){if(n&&n.outMediaTrack){let c=n.outMediaTrack.getSettings();this._mediaSettings.audioChannel=c.channelCount||1,this._mediaSettings.audioBps=1e3*n.profile.bitrate,this._mediaSettings.audioFs=c.sampleRate||0}if(a&&a.outMediaTrack){let c=a.outMediaTrack.getSettings();this._mediaSettings.videoWidth=c.width||0,this._mediaSettings.videoHeight=c.height||0,this._mediaSettings.videoFps=c.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(I&&I.outMediaTrack){let c=I.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=c.width||0,this._mediaSettings.auxVideoHeight=c.height||0,this._mediaSettings.auxVideoFps=c.frameRate||0,this._mediaSettings.auxVideoBps=1e3*I.profile.bitrate}}else n&&n.outMediaTrack&&(this._mediaSettings.audioChannel=n.profile.channelCount,this._mediaSettings.audioBps=1e3*n.profile.bitrate,this._mediaSettings.audioFs=n.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:gK,data:this._mediaSettings,responseCommand:io.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return DA(this,null,function*(){if(!this._peerConnection)return;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(o?fA.AUXILIARY:fA.MAIN," stream")),sl()?yield this.addTrackByTransceiver(e,o):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,o){return DA(this,null,function*(){var n;if(!e.mediaTrack)return;let a=this._peerConnection.getTransceivers();if(e.kind===fA.AUDIO)yield a[0].sender.replaceTrack(e.outMediaTrack);else{let I=o?3:1;yield a[I].sender.replaceTrack(e.outMediaTrack),I===1&&(n=this.localMainVideoTrack)!=null&&n.small&&(yield a[2].sender.replaceTrack(this._room.videoManager.smallTrack)),a[I].direction===_r.INACTIVE&&(yield this.setTransceiverDirection(_r.SENDONLY,[I]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return DA(this,null,function*(){if(!e.outMediaTrack)return;let o=e.outMediaTrack;mu()&&this._peerConnection.getTransceivers().findIndex(a=>a.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",o));let n=this._peerConnection.getSenders().find(a=>a.track&&a.track.kind===o.kind);if(n&&n.track){this._log.warn("sender already exists, remove sender first");let a=n.track;this.removeSender(n),yield this.updateOffer("remove",a)}if(o&&this._peerConnection.addTrack(o,new MediaStream([o])),o.kind===fA.VIDEO&&e instanceof Ru&&e.small){let a=new MediaStream,{smallTrack:I}=this._room.videoManager;a.addTrack(I),this._peerConnection.addTrack(I,a)}yield this.updateOffer("add",o)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===LR||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,o=rs(e);for(let n=0;nn.sender&&n.sender.track===e.track)),this._peerConnection.removeTrack(e),o&&$n(o.stop)&&(this._log.info("stop transceiver"),o.stop())}removeTrack(e){return DA(this,null,function*(){if(!this._peerConnection)return;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(o?fA.AUXILIARY:fA.MAIN," stream")),sl()?yield this.removeTrackByTransceiver(e,o):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,o){return DA(this,null,function*(){if(!e.outMediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===fA.AUDIO)yield n[0].sender.replaceTrack(null);else{let a=o?3:1;yield n[a].sender.replaceTrack(null),a===1&&e.small&&(yield n[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(_r.INACTIVE,[a])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,o){return DA(this,null,function*(){if(!Yr)return;let n=!1,a=!1;this._log.info("setting transceiver ".concat(o.join(",")," direction to ").concat(e));let I=this._peerConnection.getTransceivers();if(o.forEach(d=>{I[d].direction!==e&&(I[d].direction=e,n=!0)}),n){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this.setOffer(d)}let c=-1,u=this._peerConnection.remoteDescription.sdp.split(`\r +`)}addSPSDescription(e){let o=rs(e);return o.media.forEach(n=>{n.type===fA.VIDEO&&n.fmtp.forEach(a=>{a.config+=";sps-pps-idr-in-keyframe=1"})}),tp(o)}removeSDESDescription(e){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"],n=rs(e);return n.media.forEach(a=>{a.ext&&(a.ext=a.ext.filter(I=>!o.includes(I.uri)))}),tp(n)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,o){return DA(this,null,function*(){var n,a;try{if((((n=this._peerConnection)==null?void 0:n.connectionState)===hi.NEW||((a=this._peerConnection)==null?void 0:a.connectionState)===hi.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info("subscribe ".concat(o," ").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let I="subscribe_change";Object.values(e).find(c=>c===!0)||(I="unsubscribe"),yield this.sendSubscription(I,e)}else this.initialize(),yield this.connect(e)}catch(I){throw this._room.isJoined&&this.isStreamUnpublished(o)?(this._log.warn("".concat(I.message," ").concat(JSON.stringify(this.muteState))),new Ct({code:Ge.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):I}})}unsubscribe(e){return DA(this,arguments,function(o){var n=this;let{remoteTracks:a,streamType:I}=o;return function*(){if(n._currentState==="CONNECTED"&&(I==="main"&&!n.isMainStreamSubscribed||I==="auxiliary"&&!n.isAuxStreamSubscribed))return void n._log.info("".concat(I," stream already unsubscribed"));let c=bt({},n.subscribeState);a.forEach(d=>{switch(d.mediaType){case 1:c.audio=!1;break;case 4:c.video=!1;break;case 8:c.smallVideo=!1;break;case 2:c.auxiliary=!1}});let u="subscribe_change";Object.values(c).find(d=>d===!0)||(u="unsubscribe"),n._log.info("".concat(u==="unsubscribe"?u:"subscribe"," ").concat(I," [").concat(uK(c),"]")),yield n.sendSubscription(u,c),u==="unsubscribe"&&(n.closePeerConnection(),n.emitConnectionStateChangedEvent("DISCONNECTED"))}()})}unsubscribeDataChannel(){return DA(this,null,function*(){})}sendSubscription(e){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscribeState,n={srcTinyId:this.tinyId,srcUserId:this.userId},a=lK,I=io.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(n={audio:o.audio,bigVideo:o.video,auxVideo:o.auxiliary,smallVideo:o.smallVideo,srcTinyId:this.tinyId},a=CK,I=io.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:a,data:n,responseCommand:I,timeout:1e4}).then(c=>{let{data:u}=c;if(u.code!==0){let d=new Ct({code:u.code,message:Wi({key:Mi.ERROR_MESSAGE,data:{type:e,message:u.message}})});throw this._log.error(d),d}})}connect(){return DA(this,arguments,function(){var e=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(o),yield e.waitForPeerConnectionConnected()}catch(n){throw e.closePeerConnection(!0),n}}()})}exchangeSDP(e){return DA(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:o,sdp:n}=this._peerConnection.localDescription,a={type:o,sdp:n,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},I=yield this._signalChannel.sendWaitForResponse({command:tz,commandDesc:"exchange sdp",data:a,responseCommand:io.SUBSCRIBE_RESULT,timeout:CO});if(!this._peerConnection){let c=new Ct({code:Ge.INVALID_OPERATION,message:Wi({key:Mi.CONNECTION_CLOSED})});throw this._log.warn(c),c}yield this.onSubscribeResult(I),this._isSDPExchanging=!1}catch(o){throw this._isSDPExchanging=!1,o}})}createOffer(){return DA(this,null,function*(){let e={voiceActivityDetection:!1};gl()&&this._sdpSemantics===Uf?(this._peerConnection.addTransceiver(fA.AUDIO,{direction:_r.RECVONLY}),this._peerConnection.addTransceiver(fA.VIDEO,{direction:_r.RECVONLY}),this._peerConnection.addTransceiver(fA.VIDEO,{direction:_r.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let o=yield this._peerConnection.createOffer(e);if(o.sdp){let{isH264DecodeSupported:n}=yield wT();n||(this._log.warn("remove h264 desc from sdp"),o.sdp=function(a){let I=rs(a);return I.media.forEach(c=>{var u,d;if(c.type===fA.VIDEO){let R=new Set;c.rtp.forEach(_=>{let{payload:Z,codec:iA}=_;return iA==="H264"&&R.add(Z)}),c.fmtp.forEach(_=>{let{payload:Z,config:iA}=_,cA=iA.match(/apt=(\d+)/);cA&&cA[1]&&R.has(Number(cA[1]))&&R.add(Z)});let k=_=>{let{payload:Z}=_;return!R.has(Z)};c.rtp=c.rtp.filter(k),c.rtcpFb=(u=c.rtcpFb)==null?void 0:u.filter(k),c.fmtp=c.fmtp.filter(k),c.payloads=(d=c.payloads)==null?void 0:d.split(" ").filter(_=>!R.has(Number(_))).join(" ")}}),tp(I)}(o.sdp)),o.sdp=this.addRRTRLine(o.sdp),o.sdp=this.addSPSDescription(o.sdp),o.sdp=function(a){let I=rs(a);return I.media.forEach(c=>{c.type===fA.AUDIO&&c.fmtp.forEach(u=>{u.config+=";sprop-stereo=1;stereo=1"})}),tp(I)}(o.sdp),this._sdpSemantics===Uf&&(o.sdp=this.removeSDESDescription(o.sdp))}yield this.setOffer(o)})}onSubscribeResult(e){return DA(this,null,function*(){let{code:o,message:n=""}=e&&e.data||{},{type:a,sdp:I}=e&&e.data&&e.data.data||{};if(o===xR)throw new Ct({code:Ge.NOT_SUPPORTED_H264,message:Wi({key:Mi.NOT_SUPPORTED_H264DECODE})});try{if(o!==0)throw new Ct({code:o,message:Wi({key:Mi.EXCHANGE_SDP_FAILED,data:{errMsg:n}})});this._log.debug("accept remote answer: ".concat(I)),yield this.setAnswer({type:a,sdp:I}),this.updateSSRC(I)}catch(c){throw this._log.error(c),c}})}updateSSRC(e){try{rs(e).media.forEach(o=>{if(o.ssrcs)if(o.type===fA.AUDIO){let n=o.ssrcs.find(a=>{var I;return(I=a.value)==null?void 0:I.includes(RI)});n&&(this.ssrc.audio=Number(n.id))}else{let n=o.ssrcs.find(I=>{var c;return(c=I.value)==null?void 0:c.includes(RI)}),a=o.ssrcs.find(I=>{var c;return(c=I.value)==null?void 0:c.includes(gO)});n&&(this.ssrc.video=Number(n.id)),a&&(this.ssrc.auxiliary=Number(a.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 DA(this,null,function*(){if(!(zg(s6.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch{let o=yQ(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(e){let{audioDelay:o,videoDelay:n}=e;this.remoteAudioTrack.stat.end2EndDelay=o,this.remoteVideoTrack.stat.end2EndDelay=n}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}};vt([Dn(A=>function(){for(var e=arguments.length,o=new Array(e),n=0;n{let c=u=>{this._emitter.off("closed",c),I(new Ct({code:Ge.API_CALL_ABORTED,message:Wi({key:Mi.CONNECTION_ABORTED,data:u})}))};this._emitter.on("closed",c),A.apply(this,o).then(a,I).finally(()=>{this._emitter.off("closed",c)})})})],zx.prototype,"subscribe"),vt([Zh(521717,!1)],zx.prototype,"unsubscribe"),vt([Tm(XQ.prototype.afterConnect),kW(XQ.prototype.beforeConnect)],zx.prototype,"connect");var sz=zx,gz={voiceActivityDetection:!1},Zx=class g6 extends XQ{constructor(e){super(fi(bt({},e),{isUplink:!0})),G(this,"localMainAudioTrack",null),G(this,"localMainVideoTrack",null),G(this,"localAuxAudioTrack",null),G(this,"localAuxVideoTrack",null),G(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),G(this,"_isPublishingAux",!1),G(this,"_publishingLocalAudioTrack"),G(this,"_publishingLocalVideoTrack"),G(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}),G(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(e){super.close(e),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(e,o){var n,a,I;let c=this._currentState,u=super.emitConnectionStateChangedEvent(e);return u&&c!==e&&(o?o.emit("connection-state-changed",{prevState:c,state:e}):((n=this.localMainVideoTrack)==null||n.emit("connection-state-changed",{prevState:c,state:e}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:c,state:e}),(I=this._publishingLocalVideoTrack)==null||I.emit("connection-state-changed",{prevState:c,state:e}))),u}publish(e){return DA(this,arguments,function(o){var n=this;let{localAudioTrack:a,localVideoTrack:I,isAuxiliary:c}=o;return function*(){let u;n._peerConnection||n.initialize(),a&&(n._publishingLocalAudioTrack=a),I&&(n._publishingLocalVideoTrack=I),n._isPublishingAux=c,I&&!c&&I.small&&(u=n._room.videoManager.smallTrack),n.sendMediaSettings(),gl()?yield n.publishByTransceiver({localAudioTrack:a,localVideoTrack:I,smallTrack:u,isAuxiliary:c}):yield n.publishByAddTrack({localAudioTrack:a,localVideoTrack:I,smallTrack:u}),n._publishingLocalAudioTrack=null,n._publishingLocalVideoTrack=null,n._isPublishingAux=!1,c?(I&&(n.localAuxVideoTrack=I),a&&(n.localAuxAudioTrack=a)):(I&&(n.localMainVideoTrack=I),a&&(n.localMainAudioTrack=a)),n.installTrackMuteEvents(a,I),n.sendMutedFlag()}()})}publishByTransceiver(e){return DA(this,arguments,function(o){var n=this;let{localAudioTrack:a,localVideoTrack:I,smallTrack:c,isAuxiliary:u}=o;return function*(){n._log.info("publish by transceiver");let d=new MediaStream,R=I?.outMediaTrack,k=a?.outMediaTrack;k&&d.addTrack(k),R&&d.addTrack(R);let _=n._peerConnection.getTransceivers();if(_.length===0)n._peerConnection.addTransceiver(k||fA.AUDIO,{direction:_r.SENDONLY,streams:[d]}),n._peerConnection.addTransceiver(u?fA.VIDEO:R||fA.VIDEO,{direction:_r.SENDONLY,streams:[d]}),n._peerConnection.addTransceiver(c||fA.VIDEO,{direction:_r.SENDONLY,streams:[d]}),n._peerConnection.addTransceiver(u&&R||fA.VIDEO,{direction:_r.SENDONLY,streams:[d]}),yield n.connect();else{let Z=[];if(k&&(_[0].sender.track||Z.push(0),yield _[0].sender.replaceTrack(k),yield n.setBandwidth({bandwidth:a?.profile.bitrate||40,type:fA.AUDIO})),R){let iA=u?3:1;yield _[iA].sender.replaceTrack(R),yield n.setBandwidth({bandwidth:I.profile.bitrate,type:fA.VIDEO,videoType:u?fA.AUXILIARY:fA.BIG}),Z.push(iA),c&&(yield _[2].sender.replaceTrack(c),yield n.setBandwidth({bandwidth:I.small.bitrate,type:fA.VIDEO,videoType:fA.SMALL}),Z.push(2))}yield n.setTransceiverDirection(_r.SENDONLY,Z),yield n.doPublishChange(),I?.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),I?.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()})}publishByAddTrack(e){return DA(this,arguments,function(o){var n=this;let{localAudioTrack:a,localVideoTrack:I,smallTrack:c}=o;return function*(){n._log.info("publish by addtrack");let u=I?.outMediaTrack,d=a?.outMediaTrack;if(n._peerConnection&&n._peerConnection.connectionState!=="new")return a&&d&&(yield n.addTrack(a)),void(u&&(yield n.addTrack(I)));let R=new MediaStream;if(d&&R.addTrack(d),u&&R.addTrack(u),d&&n._peerConnection.addTrack(d,R),u&&(n._peerConnection.addTrack(u,R),c)){let k=new MediaStream;k.addTrack(c),n._peerConnection.addTrack(c,k)}yield n.connect()}()})}enableSmall(e){return DA(this,null,function*(){let o=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield o[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(_r.SENDONLY,[2])):(yield o[2].sender.replaceTrack(null),yield this.setTransceiverDirection(_r.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(){for(var e=arguments.length,o=new Array(e),n=0;n{a&&(a?.on("mute",this.sendMutedFlag,this),a?.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(){for(var e=arguments.length,o=new Array(e),n=0;n{a&&(a?.off("mute",this.sendMutedFlag,this),a?.off("unmute",this.sendMutedFlag,this))})}unpublish(e){return DA(this,arguments,function(o){var n=this;let{localAudioTrack:a,localVideoTrack:I}=o;return function*(){if(!Ru())return a&&a.outMediaTrack&&!I&&n.localMainVideoTrack?(yield n.removeTrack(a),void(n.localMainAudioTrack=null)):I&&I.outMediaTrack&&!a&&n.localMainAudioTrack?(yield n.removeTrack(I),void(n.localMainVideoTrack=null)):(yield n.doUnpublish(),n.uninstallTrackMuteEvents(a,I),void n.emitConnectionStateChangedEvent("DISCONNECTED",I));let c=I&&I===n.localAuxVideoTrack,u=I?.outMediaTrack,d=n._peerConnection.getSenders(),R=[];a&&(c?n.localAuxAudioTrack=null:n.localMainAudioTrack=null,!n.localAuxAudioTrack&&!n.localMainAudioTrack&&(yield d[0].replaceTrack(null),R.push(0))),u&&(c?(yield d[3].replaceTrack(null),n.localAuxVideoTrack=null,n._mediaSettings=fi(bt({},n._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),R.push(3)):(yield d[1].replaceTrack(null),yield d[2].replaceTrack(null),n.localMainVideoTrack=null,n._mediaSettings=fi(bt({},n._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),R.push(1,2))),n.isMainStreamPublished||n.isAuxStreamPublished?(yield n.setTransceiverDirection(_r.INACTIVE,R),yield n.doPublishChange(!1)):yield n.doUnpublish(),n.uninstallTrackMuteEvents(a,I),I?.emit("connection-state-changed",{prevState:n._currentState,state:"DISCONNECTED"})}()})}doPublishChange(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return DA(this,null,function*(){let o={state:this._room.publishState,constraintConfig:this._mediaSettings},n=yield this._signalChannel.sendWaitForResponse({command:EK,data:o,responseCommand:io.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(n.data.code,n.data.message)})}doUnpublish(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this._signalChannel.sendWaitForResponse({command:jx,commandDesc:"unpublish",responseCommand:io.UNPUBLISH_RESULT,enableLog:e}).catch(o=>{if(o.getCode()===Ge.API_CALL_TIMEOUT)return Promise.resolve();throw o})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:o}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":o&&(this._mediaSettings.videoCodec="VP8");let n=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:a,localAuxVideoTrack:I}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?I=this._publishingLocalVideoTrack:a=this._publishingLocalVideoTrack),qh){if(n&&n.outMediaTrack){let c=n.outMediaTrack.getSettings();this._mediaSettings.audioChannel=c.channelCount||1,this._mediaSettings.audioBps=1e3*n.profile.bitrate,this._mediaSettings.audioFs=c.sampleRate||0}if(a&&a.outMediaTrack){let c=a.outMediaTrack.getSettings();this._mediaSettings.videoWidth=c.width||0,this._mediaSettings.videoHeight=c.height||0,this._mediaSettings.videoFps=c.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(I&&I.outMediaTrack){let c=I.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=c.width||0,this._mediaSettings.auxVideoHeight=c.height||0,this._mediaSettings.auxVideoFps=c.frameRate||0,this._mediaSettings.auxVideoBps=1e3*I.profile.bitrate}}else n&&n.outMediaTrack&&(this._mediaSettings.audioChannel=n.profile.channelCount,this._mediaSettings.audioBps=1e3*n.profile.bitrate,this._mediaSettings.audioFs=n.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:BK,data:this._mediaSettings,responseCommand:io.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return DA(this,null,function*(){if(!this._peerConnection)return;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(o?fA.AUXILIARY:fA.MAIN," stream")),gl()?yield this.addTrackByTransceiver(e,o):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,o){return DA(this,null,function*(){var n;if(!e.mediaTrack)return;let a=this._peerConnection.getTransceivers();if(e.kind===fA.AUDIO)yield a[0].sender.replaceTrack(e.outMediaTrack);else{let I=o?3:1;yield a[I].sender.replaceTrack(e.outMediaTrack),I===1&&(n=this.localMainVideoTrack)!=null&&n.small&&(yield a[2].sender.replaceTrack(this._room.videoManager.smallTrack)),a[I].direction===_r.INACTIVE&&(yield this.setTransceiverDirection(_r.SENDONLY,[I]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return DA(this,null,function*(){if(!e.outMediaTrack)return;let o=e.outMediaTrack;Ru()&&this._peerConnection.getTransceivers().findIndex(a=>a.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",o));let n=this._peerConnection.getSenders().find(a=>a.track&&a.track.kind===o.kind);if(n&&n.track){this._log.warn("sender already exists, remove sender first");let a=n.track;this.removeSender(n),yield this.updateOffer("remove",a)}if(o&&this._peerConnection.addTrack(o,new MediaStream([o])),o.kind===fA.VIDEO&&e instanceof Su&&e.small){let a=new MediaStream,{smallTrack:I}=this._room.videoManager;a.addTrack(I),this._peerConnection.addTrack(I,a)}yield this.updateOffer("add",o)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===OR||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,o=rs(e);for(let n=0;nn.sender&&n.sender.track===e.track)),this._peerConnection.removeTrack(e),o&&$n(o.stop)&&(this._log.info("stop transceiver"),o.stop())}removeTrack(e){return DA(this,null,function*(){if(!this._peerConnection)return;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(o?fA.AUXILIARY:fA.MAIN," stream")),gl()?yield this.removeTrackByTransceiver(e,o):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,o){return DA(this,null,function*(){if(!e.outMediaTrack)return;let n=this._peerConnection.getTransceivers();if(e.kind===fA.AUDIO)yield n[0].sender.replaceTrack(null);else{let a=o?3:1;yield n[a].sender.replaceTrack(null),a===1&&e.small&&(yield n[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(_r.INACTIVE,[a])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,o){return DA(this,null,function*(){if(!Yr)return;let n=!1,a=!1;this._log.info("setting transceiver ".concat(o.join(",")," direction to ").concat(e));let I=this._peerConnection.getTransceivers();if(o.forEach(d=>{I[d].direction!==e&&(I[d].direction=e,n=!0)}),n){this._log.info("updating offer");let d=yield this._peerConnection.createOffer();yield this.setOffer(d)}let c=-1,u=this._peerConnection.remoteDescription.sdp.split(`\r `).map(d=>{if(d.match(new RegExp("a=(".concat(_r.INACTIVE,"|").concat(_r.RECVONLY,"|").concat(_r.SENDONLY,")")))&&c++,o.includes(c)){if(e===_r.INACTIVE&&d.includes("a=".concat(_r.RECVONLY)))return a=!0,"a=".concat(e);if(e===_r.SENDONLY&&d.includes("a=".concat(_r.INACTIVE)))return a=!0,"a=".concat(_r.RECVONLY)}return d}).join(`\r -`);a&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:u}))})}removeTrackBySender(e){return DA(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===fA.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let o=this._peerConnection.getSenders().find(n=>n.track===e.outMediaTrack);o&&(this.removeSender(o),e.kind===fA.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(n=>{n.track&&n.track.kind===fA.VIDEO&&this.removeSender(n)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return DA(this,null,function*(){var o;let n,a=(o=this._peerConnection)==null?void 0:o.getSenders();if(!a||a.length===0||!e.mediaTrack||(n=sl()?e.kind===fA.AUDIO?a[0]:a[1]:a.find(c=>c.track&&c.track.kind===e.kind),!n))return!1;let I=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(e.kind," track on ").concat(I?fA.AUXILIARY:fA.MAIN," stream")),e.kind===fA.AUDIO?yield n.replaceTrack(e.outMediaTrack):e.kind===fA.VIDEO&&(I?a[3]&&(yield a[3].replaceTrack(e.outMediaTrack)):yield n.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,o){return DA(this,null,function*(){try{let n=yield this._peerConnection.createOffer(tz);Yr&&n.sdp&&(n.sdp=this.setSDPDirection(n.sdp,"sendrecv")),yield this.setOffer(n);let a=this.updateMediaSettings(),I={action:e,trackId:o.id,kind:o.kind===fA.VIDEO?"bigVideo":o.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:a,state:this._room.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(I.sdp));let c=yield this._signalChannel.sendWaitForResponse({command:q4,data:I,responseCommand:io.UPDATE_OFFER_RESULT,timeout:nO,commandDesc:"update offer"}),{code:u,message:d}=c.data;u!==0&&this.checkPublishResultCode(u,d),yield this.acceptAnswer(c.data.data),n.sdp&&this.updateSSRC(n.sdp)}catch(n){throw this._log.error(n),n}})}setBandwidth(e){return DA(this,arguments,function(o){var n=this;let{bandwidth:a,type:I,videoType:c,sdp:u}=o;return function*(){if(!TT())return u?I===fA.VIDEO?n.updateVideoBandwidthRestriction(u,a,c):n.updateAudioBandwidthRestriction(u,a):void 0;let d,R=n._peerConnection.getSenders();if(sl()){let k=0;I===fA.VIDEO&&(k=c===fA.SMALL?2:c===fA.AUXILIARY?3:1),d=R[k]}else d=R.find(k=>k.track&&k.track.kind===I);if(d){let k=d.getParameters();(!k.encodings||k.encodings.length===0)&&(k.encodings=[{}]),k.encodings[0].maxBitrate=1e3*a;try{return yield d.setParameters(k),n._log.info("".concat(c||"").concat(I," bandwidth ").concat(a," kbps")),u}catch(_){if(n._log.info("failed to set bandwidth by setting maxBitrate: ".concat(_)),u)return I===fA.VIDEO?n.updateVideoBandwidthRestriction(u,a,c):n.updateAudioBandwidthRestriction(u,a)}}return u}()})}updateVideoBandwidthRestriction(e,o,n){let a="AS";Yr&&(a="TIAS",o*=1e3);let I=0,c=-1;return n===fA.SMALL?I=1:n===fA.AUXILIARY&&(I=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,u=>(c+=1,c===I?"".concat(u,"b=").concat(a,":").concat(o,`\r +`);a&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:u}))})}removeTrackBySender(e){return DA(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===fA.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let o=this._peerConnection.getSenders().find(n=>n.track===e.outMediaTrack);o&&(this.removeSender(o),e.kind===fA.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(n=>{n.track&&n.track.kind===fA.VIDEO&&this.removeSender(n)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return DA(this,null,function*(){var o;let n,a=(o=this._peerConnection)==null?void 0:o.getSenders();if(!a||a.length===0||!e.mediaTrack||(n=gl()?e.kind===fA.AUDIO?a[0]:a[1]:a.find(c=>c.track&&c.track.kind===e.kind),!n))return!1;let I=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(e.kind," track on ").concat(I?fA.AUXILIARY:fA.MAIN," stream")),e.kind===fA.AUDIO?yield n.replaceTrack(e.outMediaTrack):e.kind===fA.VIDEO&&(I?a[3]&&(yield a[3].replaceTrack(e.outMediaTrack)):yield n.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,o){return DA(this,null,function*(){try{let n=yield this._peerConnection.createOffer(gz);Yr&&n.sdp&&(n.sdp=this.setSDPDirection(n.sdp,"sendrecv")),yield this.setOffer(n);let a=this.updateMediaSettings(),I={action:e,trackId:o.id,kind:o.kind===fA.VIDEO?"bigVideo":o.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:a,state:this._room.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(I.sdp));let c=yield this._signalChannel.sendWaitForResponse({command:$4,data:I,responseCommand:io.UPDATE_OFFER_RESULT,timeout:lO,commandDesc:"update offer"}),{code:u,message:d}=c.data;u!==0&&this.checkPublishResultCode(u,d),yield this.acceptAnswer(c.data.data),n.sdp&&this.updateSSRC(n.sdp)}catch(n){throw this._log.error(n),n}})}setBandwidth(e){return DA(this,arguments,function(o){var n=this;let{bandwidth:a,type:I,videoType:c,sdp:u}=o;return function*(){if(!bT())return u?I===fA.VIDEO?n.updateVideoBandwidthRestriction(u,a,c):n.updateAudioBandwidthRestriction(u,a):void 0;let d,R=n._peerConnection.getSenders();if(gl()){let k=0;I===fA.VIDEO&&(k=c===fA.SMALL?2:c===fA.AUXILIARY?3:1),d=R[k]}else d=R.find(k=>k.track&&k.track.kind===I);if(d){let k=d.getParameters();(!k.encodings||k.encodings.length===0)&&(k.encodings=[{}]),k.encodings[0].maxBitrate=1e3*a;try{return yield d.setParameters(k),n._log.info("".concat(c||"").concat(I," bandwidth ").concat(a," kbps")),u}catch(_){if(n._log.info("failed to set bandwidth by setting maxBitrate: ".concat(_)),u)return I===fA.VIDEO?n.updateVideoBandwidthRestriction(u,a,c):n.updateAudioBandwidthRestriction(u,a)}}return u}()})}updateVideoBandwidthRestriction(e,o,n){let a="AS";Yr&&(a="TIAS",o*=1e3);let I=0,c=-1;return n===fA.SMALL?I=1:n===fA.AUXILIARY&&(I=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,u=>(c+=1,c===I?"".concat(u,"b=").concat(a,":").concat(o,`\r `):u)),e}updateAudioBandwidthRestriction(e,o){let n="AS";return Yr&&(n="TIAS",o*=1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r c=IN $2\r b=`.concat(n,":").concat(o,`\r -`))}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return DA(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return DA(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return DA(this,null,function*(){try{let e=yield this._peerConnection.createOffer(tz);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:j4,responseCommand:io.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof Nm||this.localAuxVideoTrack instanceof Nm,state:this._room.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(e.data.sdp)),this._signalChannel.sendWaitForResponse(e).then(o=>{let{code:n,message:a,data:I}=o.data;return n===0?this.acceptAnswer(I):this.checkPublishResultCode(n,a)})}setSDPDirection(e,o){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"all",a=rs(e);return a.media.forEach(I=>{(n==="all"||I.type===n)&&(I.direction=o)}),$h(a)}acceptAnswer(e){return DA(this,null,function*(){var o,n,a,I,c;try{let u;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let R=((o=this._publishingLocalVideoTrack)==null?void 0:o.profile.bitrate)||((n=this.localMainVideoTrack)==null?void 0:n.profile.bitrate),k=((a=this._publishingLocalAudioTrack)==null?void 0:a.profile.bitrate)||((I=this.localMainAudioTrack)==null?void 0:I.profile.bitrate);if(R){let _=this._isPublishingAux?fA.AUXILIARY:fA.BIG;u=yield this.setBandwidth({bandwidth:R,type:fA.VIDEO,sdp:u,videoType:_})}k&&(u=yield this.setBandwidth({bandwidth:k,type:fA.AUDIO,sdp:u}))}if(u=this.removeVideoOrientation(e.sdp),(c=this._publishingLocalVideoTrack)!=null&&c.small){let{smallStreamConfig:R}=this._room;u=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||R.bitrate,type:fA.VIDEO,videoType:fA.SMALL,sdp:u})}let d={type:e.type,sdp:u};yield this.setAnswer(d),this._log.debug("accepted answer: ".concat(u))}catch(u){throw this._log.error("failed to accept remote answer ".concat(u)),u}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.send(K4,this._room.muteState))}getIsReconnecting(){return this._isReconnecting}reconnect(){return DA(this,null,function*(){if(!(zg(e6.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:Yx,responseCommand:io.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=fQ(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(o/1e3,"s")),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},o)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(K.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{rs(e).media.forEach((o,n)=>{if(o.type===fA.AUDIO){let a=o.ssrcs&&o.ssrcs[0];a&&(this.ssrc.audio=Number(a.id))}else{if(this._sdpSemantics===LR&&o.ssrcGroups)return void o.ssrcGroups.forEach((I,c)=>{let u=Number(I.ssrcs.split(" ")[0]);c===0?this.ssrc.video=u:c===1&&(this.ssrc.small=u)});let a=o.ssrcs&&o.ssrcs[0];if(!a)return;switch(n){case 1:this.ssrc.video=Number(a.id);break;case 2:this.ssrc.small=Number(a.id);break;case 3:this.ssrc.auxiliary=Number(a.id)}}})}catch{}}getVideoTrackId(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:fA.VIDEO;if(this._peerConnection){let o=this._peerConnection.getSenders();if(e===fA.AUXILIARY&&o[3]&&o[3].track)return o[3].track.id;if(e===fA.VIDEO&&o[1]&&o[1].track)return o[1].track.id}if(this.localMainVideoTrack&&e===fA.VIDEO){let o=this.localMainVideoTrack.mediaTrack;if(o)return o.id}if(this.localAuxVideoTrack&&e===fA.AUXILIARY){let o=this.localAuxVideoTrack.mediaTrack;if(o)return o.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,o){if(e!==0)throw e===FR?(this._log.error(ts.NOT_SUPPORTED_H264ENCODE),new Ct({code:Ge.NOT_SUPPORTED_H264,message:Wi({key:Mi.NOT_SUPPORTED_H264ENCODE})})):new Ct({code:Ge.UNKNOWN,message:Wi({key:Mi.SIGNAL_RESPONSE_FAILED,data:{signalResponse:io.PUBLISH_RESULT,code:e,message:o}})})}};vt([Dn(A=>function(){for(var e=arguments.length,o=new Array(e),n=0;n{let c=u=>{this._emitter.off("closed",c),I(new Ct({code:Ge.API_CALL_ABORTED,message:Wi({key:Mi.CONNECTION_ABORTED,data:u})}))};this._emitter.on("closed",c),A.apply(this,o).then(a,I).finally(()=>{this._emitter.off("closed",c)})})})],Hx.prototype,"publish"),vt([jh(521715,!1)],Hx.prototype,"unpublish"),vt([wm(WQ.prototype.afterConnect),MW(WQ.prototype.beforeConnect)],Hx.prototype,"connect");var Vx=Hx,EtA=class{constructor(A,e){this.room=A,G(this,"_log"),G(this,"_prevReportTime",0),G(this,"_prevReport",{}),G(this,"_prevStats",null),G(this,"_prevEncoderImplementation",""),G(this,"_prevAuxEncoderImpl",""),G(this,"_prevQualityLimitationReason",""),G(this,"_prevAuxQualityLimitationReason",""),G(this,"_prevDecoderImplementationMap",new Map),G(this,"_decodeMap",new Map),G(this,"_prevQpSum",0),G(this,"_prevAuxQpSum",0),G(this,"totalBytesSent",0),G(this,"totalBytesReceived",0),G(this,"_spcStats",null),this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(A){return DA(this,null,function*(){var e,o,n,a,I,c,u;let d={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},R=A.getPeerConnection(),k=A.getSSRC();if(R)try{if((this._spcStats||(yield R.getStats())).forEach(_=>{var Z,iA,cA,TA,JA,Ie,XA,Ft,ie,ke,Nt,Ut,Ui;let Oi,or;if(_.type==="outbound-rtp")if((_.mediaType||_.kind)===fA.VIDEO){if(_.ssrc===k.video?(Oi=fA.VIDEO,or=A.localMainVideoTrack):_.ssrc===k.small?Oi=fA.SMALL:_.ssrc===k.auxiliary&&(or=A.localAuxVideoTrack,Oi=fA.AUXILIARY),!Oi)return;d[Oi].bytesSent=_.bytesSent,d[Oi].packetsSent=_.packetsSent,d[Oi].framesEncoded=_.framesEncoded,Ee(_.keyFramesEncoded)||(d[Oi].keyFramesEncoded=_.keyFramesEncoded),Ee(_.nackCount)||(d[Oi].nackCount=_.nackCount),Ee(_.pliCount)||(d[Oi].pliCount=_.pliCount),Ee(_.retransmittedPacketsSent)||(d[Oi].retransmittedPacketsSent=_.retransmittedPacketsSent),Ee(_.totalEncodeTime)||(d[Oi].totalEncodeTime=_.totalEncodeTime),Ee(_.totalPacketSendDelay)||(d[Oi].totalPacketSendDelay=_.totalPacketSendDelay);let xi=0;if(!Ee(_.qpSum)&&!Ee(_.framesEncoded)&&_.framesEncoded>0){let yo=_.qpSum,Sa=_.framesEncoded,Vn=Oi===fA.VIDEO?this._prevQpSum:this._prevAuxQpSum,NI=Oi===fA.VIDEO?((iA=(Z=A.localMainVideoTrack)==null?void 0:Z.stat)==null?void 0:iA.framesEncoded)||0:((TA=(cA=A.localAuxVideoTrack)==null?void 0:cA.stat)==null?void 0:TA.framesEncoded)||0;if(Sa>NI&&yo>Vn){let IG=yo-Vn,qM=Sa-NI;xi=Math.round(IG/qM),xi>35&&A.videoCodec==="h264"&&this._log.warn("".concat(Oi===fA.AUXILIARY?"aux ":"","video encoder QP is high: ").concat(xi,", resolution: ").concat(_.frameWidth,"x").concat(_.frameHeight,", codec: ").concat(A.videoCodec,", "))}Oi===fA.VIDEO?this._prevQpSum=yo:Oi===fA.AUXILIARY&&(this._prevAuxQpSum=yo)}if(!Ee(_.encoderImplementation)&&(Oi===fA.VIDEO&&this._prevEncoderImplementation!==_.encoderImplementation||Oi===fA.AUXILIARY&&this._prevAuxEncoderImpl!==_.encoderImplementation)){let yo=2,Sa=this._prevEncoderImplementation;Oi===fA.AUXILIARY&&(yo=7,Sa=this._prevAuxEncoderImpl),S.emit("262",{userId:A.userId,streamType:yo,prevImplementation:Sa,implementation:_.encoderImplementation,codec:A.videoCodec,isHWCodec:_.powerEfficientEncoder}),this[Oi===fA.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=_.encoderImplementation,or?.log.info("encoderImplementation change to ".concat(_.encoderImplementation,"(").concat(A.videoCodec,") HWEncoder: ").concat(_.powerEfficientEncoder))}_.ssrc===k.video?!Ee(_.qualityLimitationReason)&&_.bytesSent!==0&&this._prevQualityLimitationReason!==_.qualityLimitationReason&&(or?.log.info("qualityLimitationReason change to ".concat(_.qualityLimitationReason)),S.emit("263",{userId:A.userId,reason:_.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(JA=A.localMainVideoTrack)==null?void 0:JA.isQosClearFirst}),this._prevQualityLimitationReason=_.qualityLimitationReason):_.ssrc===k.auxiliary&&!Ee(_.qualityLimitationReason)&&_.bytesSent!==0&&this._prevAuxQualityLimitationReason!==_.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(_.qualityLimitationReason)),S.emit("263",{userId:A.userId,reason:_.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(Ie=A.localAuxVideoTrack)==null?void 0:Ie.isQosClearFirst}),this._prevAuxQualityLimitationReason=_.qualityLimitationReason)}else d.audio.bytesSent=_.bytesSent,d.audio.packetsSent=_.packetsSent;else if(_.type==="candidate-pair")Cm(_)&&(this.totalBytesSent=_.bytesSent,hr(_.currentRoundTripTime)&&(d.rtt=Math.floor(1e3*_.currentRoundTripTime)));else if(_.type==="media-source"){if(_.kind===fA.AUDIO)d.audio.audioLevel=_.audioLevel||0,d.audio.totalAudioEnergy=_.totalAudioEnergy||0,_.echoReturnLoss,Ee((ie=(Ft=(XA=A.localMainAudioTrack)==null?void 0:XA.sourceTrack)==null?void 0:Ft.stats)==null?void 0:ie.deliveredFramesDuration)?_.totalSamplesDuration&&(d.audio.totalSamplesDuration=_.totalSamplesDuration):d.audio.totalSamplesDuration=A.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(_.kind===fA.VIDEO)if(_.trackIdentifier===A.getVideoTrackId(fA.VIDEO))if((Ut=(Nt=(ke=A.localMainVideoTrack)==null?void 0:ke.sourceTrack)==null?void 0:Nt.stats)!=null&&Ut.deliveredFrames){let{deliveredFrames:xi}=A.localMainVideoTrack.sourceTrack.stats;d.video.framesCaptured=xi,A.localMainVideoTrack.stat.framesCaptured&&A.localMainVideoTrack.stat.framesCaptured>0&&xi>=A.localMainVideoTrack.stat.framesCaptured?d.video.fpsCapture=Math.floor((xi-A.localMainVideoTrack.stat.framesCaptured)/this.statInterval):d.video.fpsCapture=_.framesPerSecond}else d.video.fpsCapture=_.framesPerSecond;else _.trackIdentifier===A.getVideoTrackId(fA.AUXILIARY)?d.auxiliary.fpsCapture=_.framesPerSecond:d.small.fpsCapture=_.framesPerSecond}if(!Ee(_.audioLevel)&&(Ui=A.localMainAudioTrack)!=null&&Ui.mediaTrack&&_.trackIdentifier===A.localMainAudioTrack.mediaTrack.id&&(d.audio.audioLevel=_.audioLevel||0),!Ee(_.frameWidth)){let xi=fA.SMALL;_.trackIdentifier===A.getVideoTrackId(fA.VIDEO)||_.ssrc===k.video?xi=fA.VIDEO:(_.trackIdentifier===A.getVideoTrackId(fA.AUXILIARY)||_.ssrc===k.auxiliary)&&(xi=fA.AUXILIARY),d[xi].frameWidth=_.frameWidth,d[xi].frameHeight=_.frameHeight,d[xi].framesSent=_.framesSent}}),A.localMainAudioTrack||A.getRoom().capturedLocalMainAudioTrack){let _=A.localMainAudioTrack||A.getRoom().capturedLocalMainAudioTrack;if(_){let Z=_.getInternalAudioLevel(),iA=_.getInternalAudioLevelAfter3A();d.audio.audioCaptureEnergyAfter3a=iA,d.audio.micAudioLevel=Z,d.audio.audioLevel===0&&A.localMainAudioTrack&&(d.audio.audioLevel=iA??Z),!A.localMainAudioTrack&&!Ee((o=(e=_.sourceTrack)==null?void 0:e.stats)==null?void 0:o.deliveredFramesDuration)&&(d.audio.totalSamplesDuration=_.sourceTrack.stats.deliveredFramesDuration/1e3)}}if(!A.localMainVideoTrack&&A.getRoom().capturedLocalMainVideoTrack){let _=A.getRoom().capturedLocalMainVideoTrack;if((a=(n=_?.sourceTrack)==null?void 0:n.stats)!=null&&a.deliveredFrames){let{deliveredFrames:Z}=_.sourceTrack.stats;d.video.framesCaptured=Z,_.stat.framesCaptured&&_.stat.framesCaptured>0&&Z>=_.stat.framesCaptured&&(d.video.fpsCapture=Math.floor((Z-_.stat.framesCaptured)/this.statInterval)),_.stat.framesCaptured=Z}}if(!A.localAuxVideoTrack&&A.getRoom().capturedLocalAuxVideoTrack){let _=A.getRoom().capturedLocalAuxVideoTrack;if((c=(I=_?.sourceTrack)==null?void 0:I.stats)!=null&&c.deliveredFrames){let{deliveredFrames:Z}=_.sourceTrack.stats;d.auxiliary.framesCaptured=Z,_.stat.framesCaptured&&_.stat.framesCaptured>0&&Z>=_.stat.framesCaptured&&(d.auxiliary.fpsCapture=Math.floor((Z-_.stat.framesCaptured)/this.statInterval)),_.stat.framesCaptured=Z}}this.totalBytesSent||(this.totalBytesSent+=d.audio.bytesSent+d.video.bytesSent+d.auxiliary.bytesSent),Object.keys(d).forEach(_=>{_===fA.AUDIO?(A.localMainAudioTrack&&(A.localMainAudioTrack.stat=d[_]),A.localAuxAudioTrack&&(A.localAuxAudioTrack.stat=d[_])):_===fA.VIDEO?A.localMainVideoTrack&&(A.localMainVideoTrack.stat=d[_]):_===fA.AUXILIARY&&A.localAuxVideoTrack&&(A.localAuxVideoTrack.stat=d[_])})}catch(_){this._log.warn("failed to getStats on sender connection ".concat(_))}return d.rtt===0&&(d.rtt=((u=this.room.networkQuality)==null?void 0:u.uplinkRTT)||0),d})}getReceiverStats(A){return DA(this,null,function*(){var e,o,n;let a={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:""}},I=A.getPeerConnection();if(I)try{let{ssrc:c}=A,{muteState:u,subscribeState:d}=A;(this._spcStats||(yield I.getStats())).forEach(_=>{var Z,iA;if(_.type==="codec"&&this._decodeMap.set(_.id,_),_.type==="inbound-rtp"){let cA=(_.mediaType||_.kind)===fA.AUDIO;if(cA){if(_.ssrc!==c.audio||!u.hasAudio)return;a.audio.packetsReceived=_.packetsReceived,a.audio.bytesReceived=_.bytesReceived,a.audio.packetsLost=_.packetsLost,_.insertedSamplesForDeceleration&&(a.audio.insertedSamplesForDeceleration=_.insertedSamplesForDeceleration),_.removedSamplesForAcceleration&&(a.audio.removedSamplesForAcceleration=_.removedSamplesForAcceleration),_.totalSamplesDuration&&(a.audio.totalSamplesDuration=_.totalSamplesDuration),_.totalSamplesReceived&&(a.audio.totalSamplesReceived=_.totalSamplesReceived),_.concealedSamples&&(a.audio.concealedSamples=_.concealedSamples),_.silentConcealedSamples&&(a.audio.silentConcealedSamples=_.silentConcealedSamples);let{remoteAudioTrack:TA}=A;TA.stat.packetsReceived=_.packetsReceived,TA.stat.bytesReceived=_.bytesReceived,TA.stat.packetsLost=_.packetsLost,a.audio.p2pDelay=TA.stat.end2EndDelay,a.hasAudio=!0}else{if(Yr&&_.bytesReceived===0)return;let TA;_.ssrc===c.video&&u.hasVideo&&(a.video.packetsReceived=_.packetsReceived,a.video.bytesReceived=_.bytesReceived,a.video.packetsLost=_.packetsLost,a.video.framesReceived=_.framesReceived,a.video.framesDecoded=_.framesDecoded,a.video.fpsDecoded=_.framesPerSecond,a.hasVideo=!0,A.videoCodec=Vs[(Z=this._decodeMap.get(_.codecId))==null?void 0:Z.mimeType.split("/")[1]]||"h264",a.video.codec=A.videoCodec,TA=A.remoteVideoTrack,u.hasSmall&&d.smallVideo&&(a.isSmallSubscribed=!0),_.decoderImplementation&&(!this._prevDecoderImplementationMap.has(a.userId)||this._prevDecoderImplementationMap.get(a.userId)!==_.decoderImplementation)&&(TA.log.info("decoderImplementation change to ".concat(_.decoderImplementation,"(").concat(A.videoCodec,") HWDecoder: ").concat(_.powerEfficientDecoder)),S.emit("262",{userId:this.room.userId,remoteUserId:a.userId,prevImplementation:this._prevDecoderImplementationMap.get(a.userId),implementation:_.decoderImplementation,codec:A.videoCodec,isHWCodec:_.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(a.userId,_.decoderImplementation)),Ee(_.keyFramesDecoded)||TA.updateKeyFramesDecoded(_.keyFramesDecoded)),_.ssrc===c.auxiliary&&u.hasAuxiliary&&(a.auxiliary.packetsReceived=_.packetsReceived,a.auxiliary.bytesReceived=_.bytesReceived,a.auxiliary.packetsLost=_.packetsLost,a.auxiliary.framesReceived=_.framesReceived,a.auxiliary.framesDecoded=_.framesDecoded,a.auxiliary.fpsDecoded=_.framesPerSecond,TA=A.remoteAuxiliaryTrack,a.auxiliary.p2pDelay=TA.stat.end2EndDelay,a.hasAuxiliary=!0,a.video.codec=((iA=this._decodeMap.get(_.codecId))==null?void 0:iA.mimeType.split("/")[1].toLowerCase())||"h264",Ee(_.keyFramesDecoded)||TA.updateKeyFramesDecoded(_.keyFramesDecoded)),TA&&(TA.stat.packetsReceived=_.packetsReceived,TA.stat.bytesReceived=_.bytesReceived,TA.stat.packetsLost=_.packetsLost,TA.stat.framesReceived=_.framesReceived,TA.stat.framesDecoded=_.framesDecoded,_.jitterBufferDelay&&(TA.stat.jitterBufferDelay=Math.floor(_.jitterBufferDelay/_.jitterBufferEmittedCount*1e3)),a.video.p2pDelay=TA.stat.end2EndDelay)}_.jitterBufferDelay&&(cA?(a.audio.totalJitter=_.jitterBufferDelay,a.audio.totalJitterCount=_.jitterBufferEmittedCount,a.audio.estimatedPlayoutTimestamp=_.estimatedPlayoutTimestamp):_.ssrc===c.video&&u.hasVideo?(a.video.totalJitter=_.jitterBufferDelay,a.video.totalJitterCount=_.jitterBufferEmittedCount,a.video.estimatedPlayoutTimestamp=_.estimatedPlayoutTimestamp):_.ssrc===c.auxiliary&&u.hasAuxiliary&&(a.auxiliary.totalJitter=_.jitterBufferDelay,a.auxiliary.totalJitterCount=_.jitterBufferEmittedCount))}else _.type==="candidate-pair"&&Cm(_)&&(this.totalBytesReceived=_.bytesReceived,hr(_.currentRoundTripTime)&&(a.rtt=Math.floor(1e3*_.currentRoundTripTime)));Ee(_.frameWidth)||((_.trackIdentifier===A.getMainStreamVideoTrackId()||_.ssrc===c.video)&&(a.video.frameWidth=_.frameWidth,a.video.frameHeight=_.frameHeight,A.remoteVideoTrack.stat.frameWidth=_.frameWidth,A.remoteVideoTrack.stat.frameHeight=_.frameHeight),(_.trackIdentifier===A.getAuxStreamVideoTrackId()||_.ssrc===c.auxiliary)&&(a.auxiliary.frameWidth=_.frameWidth,a.auxiliary.frameHeight=_.frameHeight,A.remoteAuxiliaryTrack.stat.frameWidth=_.frameWidth,A.remoteAuxiliaryTrack.stat.frameHeight=_.frameHeight)),!Ee(_.audioLevel)&&A.muteState.audioAvailable&&A.remoteAudioTrack.mediaTrack&&_.trackIdentifier===A.remoteAudioTrack.mediaTrack.id&&(a.audio.audioLevel=_.audioLevel||0,a.audio.totalAudioEnergy=_.totalAudioEnergy||0)}),a.audio.audioLevel===0&&A.muteState.audioAvailable&&(a.audio.audioLevel=A.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=a.audio.bytesReceived+a.video.bytesReceived+a.auxiliary.bytesReceived),Ee((e=A.remoteVideoTrack.player.stat)==null?void 0:e.fps)||(a.video.fpsRender=A.remoteVideoTrack.player.stat.fps),Ee((o=A.remoteAuxiliaryTrack.player.stat)==null?void 0:o.fps)||(a.auxiliary.fpsRender=A.remoteAuxiliaryTrack.player.stat.fps);let R=a.audio.estimatedPlayoutTimestamp,k=a.video.estimatedPlayoutTimestamp;if(R&&k&&A.remoteAudioTrack.isAvailable&&A.remoteVideoTrack.isAvailable){let _=k-R;Math.abs(_)<=1e4&&(a.avSyncDelay=_,Math.abs(_)>150&&this._log.warn("av sync delay",_))}}catch(c){this._log.warn("failed to getStats on receiver connection ".concat(c))}return a.rtt===0&&(a.rtt=((n=this.room.networkQuality)==null?void 0:n.uplinkRTT)||0),a})}getStats(A,e){return DA(this,null,function*(){let o,n={},a=[];if(this.room.singlePC){let I=this.room.singlePC.getPeerConnection();if(!I)return{senderStats:n,receiverStats:a};let c=ki(),u=yield I.getStats(),d=ki();d-c>2e3&&this._log.warn("getStats cost ".concat(d-c,"ms"));let R=[],k=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec","media-playout"]);u.forEach(_=>k.has(_.type)&&R.push(_)),this._spcStats=R}A&&(n=yield this.getSenderStats(A));for(let[I,c]of e){let u=yield this.getReceiverStats(c);u&&a.push(u)}return e.size&&(o=this.getMediaPlayoutStats(this._spcStats)),{senderStats:n,receiverStats:a,mediaPlayoutStats:o}})}getDifferenceValue(A,e){if(KQ(A))return e;let o=e-A;return o<0?0:o}prepareReport(A){let{stats:e,report:o,freezeMap:n,uplinkConnection:a}=A;var I,c,u,d,R,k,_,Z,iA;if(!KQ(e.senderStats)){let ie={uint32_audio_level:e.senderStats.audio.audioLevel*iE,uint32_audio_energy:1e6*(e.senderStats.audio.totalAudioEnergy||0),uint32_audio_codec_bitrate:e.senderStats.audio.bytesSent};e.senderStats.audio.micAudioLevel&&(ie.uint32_mic_audio_level=e.senderStats.audio.micAudioLevel*iE),Ee(e.senderStats.audio.audioCaptureEnergyAfter3a)||(ie.uint32_audio_capture_energy_after3a=e.senderStats.audio.audioCaptureEnergyAfter3a*iE),e.senderStats.audio.totalSamplesDuration&&(o.msg_device_info.uint32_audio_capture_cost=e.senderStats.audio.totalSamplesDuration);let ke=[];if(e.senderStats.video.bytesSent){let Ut={uint32_video_stream_type:2,uint32_video_codec_fps:e.senderStats.video.framesSent,uint32_video_capture_fps:e.senderStats.video.fpsCapture,uint32_video_width:e.senderStats.video.frameWidth,uint32_video_height:e.senderStats.video.frameHeight,uint32_video_codec_bitrate:e.senderStats.video.bytesSent,uint32_video_enc_fps:e.senderStats.video.framesEncoded,uint32_key_frame_count:e.senderStats.video.keyFramesEncoded,uint32_nack_count:e.senderStats.video.nackCount,uint32_pli_count:e.senderStats.video.pliCount,uint32_encode_cost:1e3*(e.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(e.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:e.senderStats.video.retransmittedPacketsSent};ke.push(Ut)}if(e.senderStats.small.bytesSent){let Ut={uint32_video_stream_type:3,uint32_video_codec_fps:e.senderStats.small.framesSent||0,uint32_video_capture_fps:e.senderStats.small.fpsCapture||0,uint32_video_width:e.senderStats.small.frameWidth||0,uint32_video_height:e.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:e.senderStats.small.bytesSent,uint32_video_enc_fps:e.senderStats.small.framesEncoded||0,uint32_key_frame_count:e.senderStats.small.keyFramesEncoded,uint32_nack_count:e.senderStats.small.nackCount,uint32_pli_count:e.senderStats.small.pliCount,uint32_encode_cost:1e3*(e.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(e.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:e.senderStats.small.retransmittedPacketsSent};ke.push(Ut)}if(e.senderStats.auxiliary.bytesSent){let Ut={uint32_video_stream_type:7,uint32_video_codec_fps:e.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:e.senderStats.auxiliary.fpsCapture||0,uint32_video_width:e.senderStats.auxiliary.frameWidth||0,uint32_video_height:e.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:e.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:e.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:e.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:e.senderStats.auxiliary.nackCount,uint32_pli_count:e.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(e.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(e.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:e.senderStats.auxiliary.retransmittedPacketsSent};ke.push(Ut)}let Nt={uint32_bitrate:0,uint32_lost:0,uint32_rtt:e.senderStats.rtt};o.msg_up_stream_info={msg_audio_status:ie,msg_video_status:ke,msg_network_status:Nt}}let{statInterval:cA}=this;o.msg_down_stream_info=[],e.receiverStats.forEach(ie=>{let ke={msg_user_info:{str_identifier:ie.userId,uint64_tinyid:ie.tinyId},msg_network_status:{uint32_rtt:ie.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(ie.hasAudio){let Nt={uint32_audio_p2p_delay:ie.audio.p2pDelay,uint32_audio_cache_ms:ie.audio.totalJitter,uint32_audio_cache_ms_count:ie.audio.totalJitterCount,uint32_audio_codec_bitrate:ie.audio.bytesReceived,uint32_audio_total_bitrate:ie.audio.bytesReceived,uint32_audio_level:1e8*ie.audio.audioLevel,uint32_audio_energy:1e6*ie.audio.totalAudioEnergy,uint32_audio_receive:ie.audio.packetsReceived,uint32_audio_origin_lost:ie.audio.packetsLost};ke.msg_audio_status=Nt}if(ie.hasVideo){let Nt=n.get("".concat(ie.userId,"_").concat(kR)),Ut=Nt?Nt.duration:0,Ui={uint32_video_stream_type:ie.isSmallSubscribed?3:2,uint32_video_receive_fps:ie.video.framesReceived,uint32_video_width:ie.video.frameWidth,uint32_video_height:ie.video.frameHeight,uint32_video_codec_bitrate:ie.video.bytesReceived,uint32_video_receive:ie.video.packetsReceived,uint32_video_origin_lost:ie.video.packetsLost,uint32_video_block_time:Ut,uint32_video_dec_fps:ie.video.framesDecoded,uint32_video_codec_fps:ie.video.fpsRender,uint32_video_cache_ms:ie.video.totalJitter,uint32_video_cache_ms_count:ie.video.totalJitterCount,uint32_video_p2p_delay:ie.video.p2pDelay,uint32_video_codec:ie.video.codec,int32_video_audio_relative_delay:ie.avSyncDelay+5e3};ke.msg_video_status.push(Ui)}if(ie.hasAuxiliary){let Nt=n.get("".concat(ie.userId,"_").concat(pN)),Ut=Nt?Nt.duration:0,Ui={uint32_video_stream_type:7,uint32_video_receive_fps:ie.auxiliary.framesReceived,uint32_video_width:ie.auxiliary.frameWidth,uint32_video_height:ie.auxiliary.frameHeight,uint32_video_codec_bitrate:ie.auxiliary.bytesReceived,uint32_video_receive:ie.auxiliary.packetsReceived+ie.auxiliary.packetsLost,uint32_video_origin_lost:ie.auxiliary.packetsLost,uint32_video_block_time:Ut,uint32_video_dec_fps:ie.auxiliary.framesDecoded,uint32_video_codec_fps:ie.video.fpsRender,uint32_video_cache_ms:ie.auxiliary.totalJitter,uint32_video_cache_ms_count:ie.auxiliary.totalJitterCount,uint32_video_p2p_delay:ie.auxiliary.p2pDelay,uint32_video_codec:ie.video.codec};ke.msg_video_status.push(Ui)}o.msg_down_stream_info.push(ke)}),e.mediaPlayoutStats&&!KQ(e.mediaPlayoutStats)&&(e.mediaPlayoutStats.synthesizedSamplesDuration*=1e3,e.mediaPlayoutStats.totalSamplesDuration*=1e3);let TA=this._prevReport,JA=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(o)),this._prevStats=JSON.parse(JSON.stringify(e)),o.msg_up_stream_info.msg_audio_status&&TA.msg_up_stream_info.msg_audio_status){let ie=TA.msg_up_stream_info.msg_audio_status,ke=o.msg_up_stream_info.msg_audio_status;if(ie.uint32_audio_codec_bitrate===0)ke.uint32_audio_codec_bitrate=0;else{let Nt=this.getDifferenceValue(ie.uint32_audio_codec_bitrate,ke.uint32_audio_codec_bitrate);ke.uint32_audio_codec_bitrate=Math.round(8*Nt/cA),o.msg_up_stream_info.msg_network_status.uint32_bitrate+=ke.uint32_audio_codec_bitrate}(I=TA.msg_device_info)!=null&&I.uint32_audio_capture_cost?(o.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(TA.msg_device_info.uint32_audio_capture_cost,o.msg_device_info.uint32_audio_capture_cost)/cA),o.msg_device_info.uint32_audio_capture_cost>0&&((u=a?.localMainAudioTrack)==null||u.updateAfter3aSilenceStartTime((c=e.senderStats.audio.audioCaptureEnergyAfter3a)!=null?c:e.senderStats.audio.micAudioLevel))):delete o.msg_device_info.uint32_audio_capture_cost}let Ie=TA.msg_up_stream_info.msg_video_status;o.msg_up_stream_info.msg_video_status.forEach(ie=>{let ke=Ie.find(or=>or.uint32_video_stream_type===ie.uint32_video_stream_type);if(!ke||ke.uint32_video_codec_bitrate===0)return ie.uint32_video_codec_bitrate=0,ie.uint32_video_enc_fps=0,void(ie.uint32_video_codec_fps=0);let Nt=0,Ut=0,Ui=0;ke&&ie.uint32_video_codec_bitrate>=ke.uint32_video_codec_bitrate&&(Nt=ke.uint32_video_codec_bitrate,Ut=ke.uint32_video_enc_fps,Ui=ke.uint32_video_codec_fps);let Oi=this.getDifferenceValue(Nt,ie.uint32_video_codec_bitrate);ie.uint32_video_codec_bitrate=Math.round(8*Oi/cA),o.msg_up_stream_info.msg_network_status.uint32_bitrate+=ie.uint32_video_codec_bitrate,ie.uint32_video_enc_fps=Math.round(this.getDifferenceValue(Ut,ie.uint32_video_enc_fps)/cA),ie.uint32_video_codec_fps=Math.round(this.getDifferenceValue(Ui,ie.uint32_video_codec_fps)/cA),ke.uint32_video_width===0&&ke.uint32_video_height===0&&ke.uint32_video_codec_fps===0&&(ie.uint32_video_codec_fps=ie.uint32_video_enc_fps),Ee(ke.uint32_key_frame_count)||(ie.uint32_key_frame_count=Math.round(this.getDifferenceValue(ke.uint32_key_frame_count,ie.uint32_key_frame_count))),Ee(ke.uint32_nack_count)||(ie.uint32_nack_count=Math.round(this.getDifferenceValue(ke.uint32_nack_count,ie.uint32_nack_count))),Ee(ke.uint32_pli_count)||(ie.uint32_pli_count=Math.round(this.getDifferenceValue(ke.uint32_pli_count,ie.uint32_pli_count))),Ee(ke.uint32_video_arq_packets)||(ie.uint32_video_arq_packets=Math.round(this.getDifferenceValue(ke.uint32_video_arq_packets,ie.uint32_video_arq_packets))),Ee(ke.uint32_encode_cost)||(ie.uint32_encode_cost=Math.round(this.getDifferenceValue(ke.uint32_encode_cost,ie.uint32_encode_cost)/cA)),Ee(ke.uint32_send_packet_cost)||(ie.uint32_send_packet_cost=Math.round(this.getDifferenceValue(ke.uint32_send_packet_cost,ie.uint32_send_packet_cost)/cA))});let XA=TA.msg_down_stream_info;o.msg_down_stream_info=o.msg_down_stream_info.filter(ie=>XA.find(ke=>ke.msg_user_info.uint64_tinyid===ie.msg_user_info.uint64_tinyid));let Ft=o.msg_down_stream_info;if(Ft.forEach(ie=>{let ke=XA.find(Nt=>Nt.msg_user_info.uint64_tinyid===ie.msg_user_info.uint64_tinyid);if(KQ(ie.msg_audio_status)||KQ(ke.msg_audio_status))ie.msg_audio_status={};else{let Nt=ie.msg_audio_status,Ut=ke.msg_audio_status,Ui=this.getDifferenceValue(Ut.uint32_audio_cache_ms_count,Nt.uint32_audio_cache_ms_count);delete Nt.uint32_audio_cache_ms_count,Nt.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(Ut.uint32_audio_cache_ms,Nt.uint32_audio_cache_ms)/Ui)||0;let Oi=this.room.remotePublishedUserMap.get(ie.msg_user_info.str_identifier);Oi&&(Oi.remoteAudioTrack.stat.jitterBufferDelay=Nt.uint32_audio_cache_ms),Nt.uint32_audio_origin_lost=this.getDifferenceValue(Ut.uint32_audio_origin_lost,Nt.uint32_audio_origin_lost),Nt.uint32_audio_receive=this.getDifferenceValue(Ut.uint32_audio_receive,Nt.uint32_audio_receive),Nt.uint32_audio_receive+=Nt.uint32_audio_origin_lost;let or=this.getDifferenceValue(Ut.uint32_audio_codec_bitrate,Nt.uint32_audio_codec_bitrate);Nt.uint32_audio_codec_bitrate=Math.round(8*or/cA),Nt.uint32_audio_total_bitrate=Math.round(8*or/cA)}if(ie.msg_video_status&&ke.msg_video_status){let Nt=ke.msg_video_status;ie.msg_video_status=ie.msg_video_status.filter(Ut=>Nt.find(Ui=>Ui.uint32_video_stream_type===Ut.uint32_video_stream_type)),ie.msg_video_status.forEach(Ut=>{let Ui=Nt.find(qM=>qM.uint32_video_stream_type===Ut.uint32_video_stream_type),Oi=Ui.uint32_video_receive,or=Ui.uint32_video_origin_lost,xi=Ui.uint32_video_codec_bitrate,yo=Ui.uint32_video_receive_fps,Sa=Ui.uint32_video_dec_fps;Ut.uint32_video_origin_lost=this.getDifferenceValue(or,Ut.uint32_video_origin_lost),Ut.uint32_video_receive=this.getDifferenceValue(Oi,Ut.uint32_video_receive)+Ut.uint32_video_origin_lost;let Vn=this.getDifferenceValue(xi,Ut.uint32_video_codec_bitrate);Ut.uint32_video_codec_bitrate=Math.round(8*Vn/cA);let NI=this.getDifferenceValue(yo,Ut.uint32_video_receive_fps);Ut.uint32_video_receive_fps=Math.round(NI/cA),Ut.uint32_video_dec_fps=Math.round(this.getDifferenceValue(Sa,Ut.uint32_video_dec_fps)/cA);let IG=this.getDifferenceValue(Ui.uint32_video_cache_ms_count,Ut.uint32_video_cache_ms_count);delete Ut.uint32_video_cache_ms_count,Ut.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Ui.uint32_video_cache_ms,Ut.uint32_video_cache_ms)/IG)||0})}}),!Ee((d=JA?.mediaPlayoutStats)==null?void 0:d.totalSamplesDuration)&&!Ee((R=e.mediaPlayoutStats)==null?void 0:R.totalSamplesDuration)){let ie=2*Math.floor(this.getDifferenceValue((k=JA?.mediaPlayoutStats)==null?void 0:k.synthesizedSamplesDuration,(_=e.mediaPlayoutStats)==null?void 0:_.synthesizedSamplesDuration)/cA),ke=2*Math.floor(this.getDifferenceValue((Z=JA?.mediaPlayoutStats)==null?void 0:Z.totalSamplesDuration,(iA=e.mediaPlayoutStats)==null?void 0:iA.totalSamplesDuration)/cA);o.msg_device_info.uint32_audio_play_cost=ke-ie}return JA&&e.receiverStats.forEach(ie=>{if(ie.audio.concealedSamples&&ie.audio.totalSamplesReceived){let ke=JA.receiverStats.find(Nt=>Nt.userId===ie.userId);if(ke&&ke.audio.concealedSamples&&ke.audio.totalSamplesReceived){let Nt=(ie.audio.silentConcealedSamples||0)-(ke.audio.silentConcealedSamples||0),Ut=ie.audio.concealedSamples-ke.audio.concealedSamples,Ui=ie.audio.totalSamplesReceived-ke.audio.totalSamplesReceived,Oi=Math.floor((Ut-Nt)/Ui*1e3*cA);if(Oi>1e3*cA/5){let or=Ft.find(xi=>xi.msg_user_info.str_identifier===ie.userId);or&&(or.msg_audio_status.uint32_audio_block_time=Oi)}}}}),o.msg_down_stream_info.forEach(ie=>{ie.msg_video_status.forEach(ke=>{ke.uint32_video_codec_bitrate===0&&ke.uint32_video_receive_fps===0&&(ke.uint32_video_width=0,ke.uint32_video_height=0)})}),o}getStatsReport(A){return DA(this,arguments,function(e){var o=this;let{uplinkConnection:n,downlinkConnections:a,freezeMap:I}=e;return function*(){let c={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}}]},u=yield o.getStats(n,a);return JSON.stringify(o._prevReport)==="{}"&&(o._prevReport=JSON.parse(JSON.stringify(c))),o.prepareReport({stats:u,report:c,freezeMap:I,uplinkConnection:n}),o._prevReportTime=Date.now(),c}()})}getMediaPlayoutStats(A){let e;if(Aa(A)){for(let o of A)if(o.type==="media-playout"){let{synthesizedSamplesDuration:n,totalSamplesDuration:a}=o;e={synthesizedSamplesDuration:n,totalSamplesDuration:a};break}return e}}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)})}},ltA=es(hg());function CtA(A){return new Promise(e=>DA(null,null,function*(){let o=setTimeout(()=>{e({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),n=Date.now(),a="https://".concat(A,"/?t=").concat(n);try{yield fetch(a)}catch{}clearTimeout(o);let I=function(c){let u={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let d=performance.getEntriesByType("resource").reverse();for(let R of d)if(R.name===c){let k=Math.round(R.duration),_=Math.max(Math.round(R.domainLookupStart-R.startTime),0),Z=R.redirectStart>0?Math.max(Math.round(R.redirectEnd-R.redirectStart),0):0,iA=R.fetchStart>0?Math.max(Math.round(R.domainLookupStart-R.fetchStart),0):0,cA=Math.round(R.domainLookupEnd-R.domainLookupStart),TA=Math.round(R.requestStart-R.secureConnectionStart),JA=Math.round(R.secureConnectionStart-R.connectStart),Ie=Math.round(R.responseStart-R.requestStart),XA=Math.round(R.responseEnd-(R.responseStart||R.startTime));u=fi(bt({},u),{totalCost:k,local:_,redirect:Z,httpCache:iA,dns:cA,tcp:JA,tls:TA,request:Ie,response:XA});break}}catch{}return u}(a);I.totalCost===0&&(I.totalCost=Date.now()-n),e(I)}))}var qx=class ew extends ltA.default{constructor(e){let{signalChannel:o,room:n}=e;super(),G(this,"_room"),G(this,"_signalChannel"),G(this,"_log"),G(this,"uplinkRTT",0),G(this,"uplinkLoss",0),G(this,"downlinkRTT",0),G(this,"downlinkLoss",0),G(this,"pingResults",{}),G(this,"_downlinkPrevStatMap",new Map),G(this,"_downlinkLossAndRTTMap",new Map),G(this,"_interval",-1),G(this,"_uplinkNetworkQuality",0),G(this,"_downlinkNetworkQuality",0),G(this,"_uplinkQualityHistory",[]),G(this,"_downlinkQualityHistory",[]),this._room=n,this._signalChannel=o,this._log=nA.createLogger({parent:n.getLogger(),id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this.uplinkRTT,", loss: ").concat(this.uplinkLoss," ws-rtt: ").concat(this._signalChannel.rtt)),this._uplinkNetworkQuality=e,this._uplinkQualityHistory.push(e),this._uplinkQualityHistory.length>ew.HISTORY_SIZE&&this._uplinkQualityHistory.shift()}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:o,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(o,", loss: ").concat(n," ws-rtt: ").concat(this._signalChannel.rtt))}this._downlinkNetworkQuality=e,this._downlinkQualityHistory.push(e),this._downlinkQualityHistory.length>ew.HISTORY_SIZE&&this._downlinkQualityHistory.shift()}initialize(){this._signalChannel.on(io.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(rK,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var o,n;if(e.data.code!==0)return;let a=e.data.data;if(a.delay&&this.updateDelay(a.delay),this._room.signalChannel&&a.wsRtt&&(this._room.signalChannel.rtt=a.wsRtt),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this.uplinkLoss=0,void(this.uplinkRTT=0);let I=(n=(o=this._room)==null?void 0:o.uplinkConnection)==null?void 0:n.getPeerConnection();if(I&&this.isPeerConnectionDisconnected(I))return this.uplinkNetworkQuality=6,this.uplinkLoss=0,void(this.uplinkRTT=0);let c=a.expectAudPkg+a.expectVidPkg,u=a.recvAudPkg+a.recvVidPkg,d=c-u;c===0&&u===0||(this.uplinkLoss=d<=0?0:Math.round(d/c*100),this.uplinkRTT=a.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return DA(this,null,function*(){if(this._room.remotePublishedUserMap.size===0)return void(this.downlinkNetworkQuality=0);let e=[...this._room.remotePublishedUserMap.values()],o=new Set,n=e.filter(u=>{let d=u.getPeerConnection();return!(!d||o.has(d))&&(o.add(d),!0)}),a=n.filter(u=>{var d;return((d=u.getPeerConnection())==null?void 0:d.connectionState)===hi.CONNECTED});if(n.filter(u=>this.isPeerConnectionDisconnected(u.getPeerConnection())).length===e.length)return void(this.downlinkNetworkQuality=6);for(let u=0;u{this.isPeerConnectionDisconnected(u)&&(this._downlinkPrevStatMap.delete(u),this._downlinkLossAndRTTMap.delete(u))}),this._downlinkLossAndRTTMap.size===0)return this.downlinkRTT=0,this.downlinkLoss=0,void(this.downlinkNetworkQuality=0);let{rtt:I,loss:c}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=I,this.downlinkLoss=c,this.downlinkNetworkQuality=this.getNetworkQuality(c,I)})}getStat(e){return DA(this,null,function*(){let o={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Ph())return o;let n=e.getReceivers();try{for(let a=0;a{I.type==="candidate-pair"&&hr(I.currentRoundTripTime)&&(o.rtt=Math.round(1e3*I.currentRoundTripTime)),I.type==="inbound-rtp"&&(I.mediaType===fA.AUDIO||I.mediaType===fA.VIDEO)&&(o.totalPacketsLost+=I.packetsLost,o.totalPacketsReceived+=I.packetsReceived)});return o.rtt===0&&(o.rtt=this.uplinkRTT),o}catch{return o}})}getAverageLossAndRTT(e){let o={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(n=>{o.rtt+=n.rtt,o.loss+=n.loss}),Object.keys(o).forEach(n=>{o[n]=Math.round(o[n]/e.length)})),o}getNetworkQuality(e,o){return e>50||o>500?5:e>30||o>350?4:e>20||o>200?3:e>10||o>100?2:e>=0||o>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=1)}handleUplinkConnectionStateChange(e){let{state:o}=e;o==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):o==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==hi.DISCONNECTED&&e.connectionState!==hi.FAILED&&e.connectionState!==hi.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,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=nn.run("ric",()=>{var e;this.handleDownlinkNetworkQuality();let o=[...this._downlinkLossAndRTTMap.values()];S.emit(K.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:o});let n=(e=this._room.scheduleResult.config)==null?void 0:e.pingDomainInfo,a={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};n&&(a=fi(bt({},a),{pingResults:this.uplinkRTT>n.rttThreshold||this.downlinkRTT>n.rttThreshold?this.pingResults:{}})),this.emit(ew.EVENT_NETWORK_QUALITY,a);let I=Date.now();if(n&&(this.uplinkRTT>n.rttThreshold||this.downlinkRTT>n.rttThreshold)&&I-ew.lastPingTime>1e3*n.interval){ew.lastPingTime=Date.now();let c=n.domain.map(u=>CtA(u).then(d=>({domain:u,cost:d.totalCost})));Promise.all(c).then(u=>{this.pingResults.isPoorNetwork=u.some(d=>d.cost>700),this.pingResults.timestamp=I,this.pingResults.data=u,u.forEach(d=>{ct.addSuccessEvent({key:521718,cost:d.cost})}),this._log.warn("All ping results: ".concat(JSON.stringify(u)))}).catch(u=>{this._log.warn("Error during pinging domains: ".concat(u))})}},{delay:2e3})):this._log.info("network quality calculating is already started")}hadRecentBadUplink(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2;return this._uplinkQualityHistory.some(o=>o>e)}hadRecentBadDownlink(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2;return this._downlinkQualityHistory.some(o=>o>e)}stop(){this._log.debug("stopped"),this._interval!==-1&&(nn.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:o}=this._room;e.forEach(n=>{let{srcTinyId:a,videoDelay:I,audioDelay:c}=n,u=o.get(a);if(u){let d=this._room.remotePublishedUserMap.get(u);d?.setDelay({videoDelay:I,audioDelay:c})}})}};G(qx,"HISTORY_SIZE",10),G(qx,"EVENT_NETWORK_QUALITY","0"),G(qx,"lastPingTime",0);var iz=qx,oz=class{constructor(A){G(this,"_frameWorkType"),G(this,"_component"),G(this,"_language"),G(this,"connectionType"),G(this,"_room"),G(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0}),G(this,"_keyPrefix"),G(this,"_log"),G(this,"_intervalId"),G(this,"_firstPublishedUserList"),G(this,"_networkQuality"),G(this,"_basicInfo"),G(this,"_pathJoinRoom"),G(this,"_pathLeaveRoom"),G(this,"_pathMainVideoMap"),G(this,"_pathMainAudioMap"),G(this,"_pathAuxiliaryMap"),G(this,"_remoteStreamStatMap"),G(this,"_localStreamStat"),G(this,"_eventMap",new Map),G(this,"_captureCostSum",0),G(this,"_captureCostCount",0),G(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=nA.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&$n(this[e])&&(this[e]=function(o){let{fn:n,context:a}=o;return function(){try{for(var I=arguments.length,c=new Array(I),u=0;unA.error("".concat(n.name,"() error observed ").concat(R))):d}catch(d){nA.error("".concat(n.name,"() error observed ").concat(d))}}}({fn:this[e],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:il,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,nm().then(()=>{this._basicInfo.string_os_version=bQ(),this._basicInfo.string_device_name=Qu()||this._basicInfo.string_os_version})}addEvent(A,e){return this._eventMap.set(A,e),S.on(A,e),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(K.JOIN_START,this.handleJoinStart).addEvent(K.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(K.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(K.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(K.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(K.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(K.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(K.JOIN_FAILED,this.handleJoinFailed).addEvent(K.LEAVE_START,this.handleLeaveStart).addEvent(K.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(K.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(K.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(K.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(K.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(K.PUBLISH_START,this.handlePublishStart).addEvent(K.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(K.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(K.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(K.PLAY_TRACK_START,this.handlePlayStart).addEvent(K.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(K.PLAYER_STATE_CHANGED,A=>{let{track:e,state:o,type:n}=A;!e.isRemote||!this.hitTest(e.room)||o==="PLAYING"&&(n===fA.AUDIO?this.handleAudioPlaying(e):this.handleVideoPlaying(e))}).addEvent(K.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(K.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(K.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(K.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(K.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(K.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(K.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:e,prevMuteState:o,muteState:n}=A;if(!this.hitTest(e))return;let a=o.hasAudio||o.hasVideo||o.hasSmall,I=o.hasAuxiliary,c=n.hasAudio||n.hasVideo||n.hasSmall,u=n.hasAuxiliary;!a&&c&&this.handleRemoteStreamAdded(n.userId,"main"),!I&&u&&this.handleRemoteStreamAdded(n.userId,"auxiliary")}).addEvent(K.SINGLE_CONNECTION_STAT,A=>{let{room:e,stat:o}=A;this.hitTest(e)&&(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,e)=>S.off(e,A)),this._eventMap.clear()}destroy(){this.uninstallEvents(),nn.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&&(Ee(A.params.frameWorkType)||(this._frameWorkType=A.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),Ee(A.params.component)||(this._component=A.params.component,this._basicInfo.uint32_component=this._component),Ee(A.params.language)||(this._language=A.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(A){let{room:e,detailCost:o}=A;if(this.hitTest(e)&&o){let{totalCost:n,local:a,dns:I,tcp:c,tls:u,request:d,response:R}=o;this._pathJoinRoom.int32_schedule_cost=n,this._pathJoinRoom.int32_schedule_local=a,this._pathJoinRoom.int32_schedule_dns=I,this._pathJoinRoom.int32_schedule_tcp=c,this._pathJoinRoom.int32_schedule_tls=u,this._pathJoinRoom.int32_schedule_request=d,this._pathJoinRoom.int32_schedule_response=R}}handleSignalConnectionStart(A){let{room:e}=A;this.hitTest(e)&&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:e,error:o}=A;this.hitTest(e)&&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 Ct?Number(o.getExtraCode()||o.getCode()):Ge.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:e,error:o}=A;this.hitTest(e)&&(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:e}=A;this.hitTest(e)&&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 e;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=(e=this._room.audioManager.localAudioTrack)==null?void 0:e.after3aSilenceStartTime;o&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=ki()-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 e=Date.now();this.report().then(()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e})}}handleSwitchRoomSuccess(A){let{room:e}=A;if(this.hitTest(e)&&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:e,error:o}=A;if(this.hitTest(e)){let n=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=n,this._pathJoinRoom.uint64_end_time=n,o&&(this._pathJoinRoom.int32_end_ret=o instanceof Ct?Number(o.getExtraCode()||o.getCode()):Ge.UNKNOWN)}}handleRemoteStreamAdded(A,e){var o;let n="".concat(A,"_").concat(e);if(!this._remoteStreamStatMap.has(n)){let a={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:fi(bt({},BtA),{msg_user_info:new cK({userId:A,tinyId:(o=this._room.remotePublishedUserMap.get(A))==null?void 0:o.tinyId,role:20})})};a.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(n,a)}}handleSubscribeStart(A){let{room:e,remotePublishedUser:o,streamType:n,subscribeState:a}=A;if(!this.hitTest(e))return;let{userId:I,tinyId:c,role:u}=o,d=new cK({userId:I,tinyId:c,role:u==="anchor"?20:21}),R=Date.now(),k="".concat(I,"_").concat(n),_=this._remoteStreamStatMap.get(k);_&&_.subscribeStartTime===0&&(_.subscribeStartTime=R),n==="main"?(o.muteState.hasVideo&&(a.video||a.smallVideo)&&!this._pathMainVideoMap.has(k)&&this._pathMainVideoMap.set(k,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:I,sendSubscribeCMDTime:R}),o.muteState.hasAudio&&a.audio&&!this._pathMainAudioMap.has(k)&&this._pathMainAudioMap.set(k,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:I,sendSubscribeCMDTime:R})):o.muteState.hasAuxiliary&&a.auxiliary&&!this._pathAuxiliaryMap.has(k)&&this._pathAuxiliaryMap.set(k,{sendSubscribeCMDTime:R})}handleSubscribed(A){let{room:e,remotePublishedUser:o,streamType:n}=A;if(this.hitTest(e)){let a="".concat(o.userId,"_").concat(n),I=this._remoteStreamStatMap.get(a);I&&I.subscribedTime===0&&(I.subscribedTime=Date.now())}}handlePlayStart(A){let{track:e}=A;if(!e.isRemote||!this.hitTest(e.room))return;let o="".concat(e.userId,"_").concat(e.streamType),n=this._remoteStreamStatMap.get(o);n?.playStreamTime===0&&(n.playStreamTime=Date.now())}handleVideoLoadedData(A){let{track:e}=A;if(!e.isRemote||!this.hitTest(e.room))return;let o="".concat(e.userId,"_").concat(e.streamType),n=this._pathMainVideoMap.get(o);n&&n.statsToReport.uint64_combine_first_frame_time===0&&(n.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(A){let e="".concat(A.userId,"_").concat(A.streamType),o=Date.now(),n=this._pathMainVideoMap.get(e),a=this._remoteStreamStatMap.get(e);if(a){let{statsToReport:I}=a;if(I.uint32_video_render_first||A.streamType!=="main"?this.hasAuxFlag(A.userId):this.hasVideoFlag(A.userId)){let c=o-this._pathJoinRoom.uint64_start_time;I.uint32_video_render_first=c,ct.addNumber({key:516820,value:c})}}n?.statsToReport.uint64_render_first_frame_time===0&&(n.statsToReport.uint64_render_first_frame_time=o)}handleAudioPlaying(A){let e="".concat(A.userId,"_").concat(A.streamType),o=this._pathMainAudioMap.get(e);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(e=>{let{rtt:o,loss:n,userId:a,videoDelay:I,audioDelay:c}=e,u=this._networkQuality.totalDownlinkRTTAndLossMap.get(a);if(u)u.totalRTT+=o,u.totalLoss+=n,I&&(u.totalVideoDelay=(u.totalVideoDelay||0)+I,u.videoDelayCount=(u.videoDelayCount||0)+1),c&&(u.totalAudioDelay=(u.totalAudioDelay||0)+c,u.audioDelayCount=(u.audioDelayCount||0)+1),u.count++;else{let d,R,k,_;I&&(R=I,k=1),c&&(d=c,_=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(a,{totalRTT:o,totalLoss:n,count:1,totalAudioDelay:d,totalVideoDelay:R,audioDelayCount:_,videoDelayCount:k})}}))}handleHeartbeatStats(A){var e;if(this.hitTest(A.room)){let{msg_device_info:o,msg_up_stream_info:n,msg_down_stream_info:a}=A.report;if(n.msg_video_status[0]){let{uint32_video_codec_bitrate:I,uint32_video_enc_fps:c,uint32_video_width:u,uint32_video_height:d}=n.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=I,this._localStreamStat.totalVideoFPS+=c,this._localStreamStat.totalVideoWidth+=u,this._localStreamStat.totalVideoHeight+=d,this._localStreamStat.videoCount++}if(n.msg_audio_status){let{uint32_audio_level:I}=n.msg_audio_status;Math.floor(I/iE*100)>0&&(this._localStreamStat.totalAudioLevel+=I/iE,this._localStreamStat.audioLevelCount++)}a.forEach(I=>{let{msg_user_info:c,msg_audio_status:u,msg_video_status:d}=I,R=c.str_identifier,k=this._room.remotePublishedUserMap.get(R);if(d.forEach(_=>{let Z=_.uint32_video_stream_type===2,iA=_.uint32_video_stream_type===7,cA="".concat(R,"_").concat(Z?"main":"auxiliary"),TA=this._remoteStreamStatMap.get(cA);if(TA&&(Z&&k!=null&&k.remoteVideoTrack.isSubscribed||iA&&k!=null&&k.remoteAuxiliaryTrack)){TA.totalVideoFPS+=_.uint32_video_receive_fps,TA.totalVideoBitrate+=_.uint32_video_codec_bitrate,TA.videoCount++,TA.statsToReport.uint32_video_width===0&&(TA.statsToReport.uint32_video_width=_.uint32_video_width),TA.statsToReport.uint32_video_height===0&&(TA.statsToReport.uint32_video_height=_.uint32_video_height);let JA=Z?k.remoteVideoTrack:k.remoteAuxiliaryTrack;JA.stat.jitterBufferDelay&&(TA.videoJitterBufferDelay=JA.stat.jitterBufferDelay),JA.stat.framesReceived&&(TA.statsToReport.uint32_video_consume_render_rate=Math.floor(JA.stat.framesDecoded/JA.stat.framesReceived*Rf(10,6)))}}),!zR(u)){let _="".concat(R,"_main"),Z=this._remoteStreamStatMap.get(_);this._remoteStreamStatMap.has(_)&&Z&&k!=null&&k.remoteAudioTrack.isSubscribed&&(Z.totalAudioBitrate+=u.uint32_audio_codec_bitrate,Z.audioCount++,k.remoteAudioTrack.stat.jitterBufferDelay&&(Z.audioJitterBufferDelay=k.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(u.uint32_audio_level/iE*100)>0&&(Z.totalAudioLevel+=u.uint32_audio_level/iE,Z.audioLevelCount++),u.uint32_audio_block_time&&(Z.statsToReport.uint32_audio_block_time+=u.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&&((e=this._room.audioManager.localAudioTrack)==null?void 0:e.muted)===!1&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}handlePublishStart(A){let{room:e}=A;this.hitTest(e)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(A){let{track:e}=A;e.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),e.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(A){let{track:e}=A;e.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()),e.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:e,error:o}=A,n={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[o.name]||(o instanceof Ct?o.getExtraCode()||o.getCode():Ge.UNKNOWN);e.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=n,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),e.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=n,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(A){return this._firstPublishedUserList.findIndex(e=>e.userId===A&&e.flag&Nf)>=0}hasAudioFlag(A){return this._firstPublishedUserList.findIndex(e=>e.userId===A&&e.flag&Gf)>=0}hasAuxFlag(A){return this._firstPublishedUserList.findIndex(e=>e.userId===A&&e.flag&Tf)>=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),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=A<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((A,e)=>{let{userId:o}=A,n=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(n){let{totalLoss:R,count:k,audioDelayCount:_,videoDelayCount:Z,totalAudioDelay:iA,totalVideoDelay:cA}=n;A.statsToReport.uint32_avg_down_loss=Math.floor(R/k),_&&iA&&(A.statsToReport.uint32_audio_network_p2p_delay=Math.floor(iA/_),A.audioJitterBufferDelay&&(A.statsToReport.uint32_p2p_delay=Math.floor(A.statsToReport.uint32_audio_network_p2p_delay+A.audioJitterBufferDelay))),Z&&cA&&(A.statsToReport.uint32_video_network_p2p_delay=Math.floor(cA/Z))}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:a}=this._room;a&&(A.statsToReport.uint32_audio_play_time=a.getDuration(e,fA.AUDIO),A.statsToReport.uint32_video_play_time=a.getDuration(e,fA.VIDEO)),A.statsToReport.uint32_video_render_first&&(A.statsToReport.uint32_video_render_first=Math.min(A.statsToReport.uint32_video_render_first,Lm));let{badCaseDetector:I}=this._room,{dataFreeze:c,count:u}=I.getDataFreezeDuration(e),{renderFreeze:d}=I.getRenderFreezeDuration(e);A.statsToReport.uint32_video_block_count=u,A.statsToReport.uint32_video_block_time=Math.min(c,A.statsToReport.uint32_video_play_time),A.statsToReport.uint32_video_external_block_time=Math.min(d,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),I.isBlackStream(e)&&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,e)=>{this.hasAudioFlag(A.userId)?A.statsToReport.uint64_play_first_frame_time-A.statsToReport.uint64_start_enter_time>Lm&&(A.statsToReport.uint64_play_first_frame_time=A.statsToReport.uint64_start_enter_time+Lm):this._pathMainAudioMap.delete(e)}),this._pathMainVideoMap.forEach((A,e)=>{this.hasVideoFlag(A.userId)?A.statsToReport.uint64_render_first_frame_time-A.statsToReport.uint64_start_enter_time>Lm&&(A.statsToReport.uint64_render_first_frame_time=A.statsToReport.uint64_start_enter_time+Lm):this._pathMainVideoMap.delete(e)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>Lm&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+Lm)}getReportData(){this._basicInfo.uint32_networkType=hh();let A={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new cK({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Jf(this._signalInfo.relayIp),uint32_client_ip:Jf(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*Rf(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:Jf(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 $R(A),A}report(){return DA(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 DA(this,null,function*(){if(A.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),o=lA.enable?Iu(A,2001,e):yield PN(A),n=o instanceof ArrayBuffer,a="".concat(dh(e,Xg.KEY_POINT),"&gzip=").concat(+n),I=!1;navigator.sendBeacon&&(I=navigator.sendBeacon(a,o));let c=[this.uploadKVStat(ct),this.uploadKVStat(oB)];I||c.push(cu({url:a,body:o,priority:"low"})),yield Promise.all(c)})}setConnectionType(A){this.connectionType=A,this._basicInfo.uint32_connection_type=A}uploadKVStat(A){return DA(this,arguments,function(e){var o=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._room.sdkAppId;return function*(){var a,I;let c=e.getReportData((a=o._room)==null?void 0:a.userSig,(I=o._signalInfo)==null?void 0:I.reportToken);if(c.stats_count.length===0&&c.stats_distribution.length===0)return;c.msg_sdk_basic_info=fi(bt({},c.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(c);let u=lA.enable?Iu(c,2003,n):yield PN(c),d=u instanceof ArrayBuffer,R="".concat(dh(+n,Xg.KV_STAT),"&gzip=").concat(+d),k=!1;navigator.sendBeacon&&(k=navigator.sendBeacon(R,u)),k||cu({url:R,body:u})}()})}};vt([nB({settings:{timeout:500,retries:3}})],oz.prototype,"upload");var Lm=5e3,BtA={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},cK=class{constructor(A){G(this,"str_identifier"),G(this,"str_tinyid"),G(this,"uint32_role"),this.str_identifier=String(A.userId),this.str_tinyid=String(A.tinyId||0),this.uint32_role=A.role}},utA=oz,rz=class{constructor(){G(this,"_startTime"),G(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=ki())}stop(){this._endTime===0&&(this._endTime=ki())}getDuration(){return this._endTime===0?ki()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},QtA=class{constructor(A){G(this,"_room",null),G(this,"_durationMap"),G(this,"_eventMap",new Map),this._room=A.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(K.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(K.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(K.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:e,prevMuteState:o,muteState:n}=A;var a;let{userId:I}=n;if(!this.hitTest(e))return;o.hasAudio&&!n.hasAudio&&this.stopDurationItem("".concat(I,"_main"),fA.AUDIO),o.hasVideo&&!n.hasVideo&&this.stopDurationItem("".concat(I,"_main"),fA.VIDEO),o.hasAuxiliary&&!n.hasAuxiliary&&this.stopDurationItem("".concat(I,"_auxiliary"),fA.VIDEO);let c=(a=this._room)==null?void 0:a.remotePublishedUserMap.get(I);c&&(!o.hasAudio&&n.hasAudio&&c.remoteAudioTrack.isSubscribed&&this.addDuractionItem(I,fA.AUDIO,"main"),!o.hasVideo&&n.hasVideo&&c.remoteVideoTrack.isSubscribed&&this.addDuractionItem(I,fA.VIDEO,"main"),!o.hasAuxiliary&&n.hasAuxiliary&&c.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(I,fA.VIDEO,"auxiliary"))}),this._eventMap.forEach((A,e)=>S.on(e,A,this))}uninstallEvents(){this._eventMap.forEach((A,e)=>S.off(e,A,this)),this._eventMap.clear()}handleSubscribed(A){let{track:e}=A;if(!this.hitTest(e.room))return;let{userId:o,streamType:n,kind:a}=e;e.isSubscribed?this.addDuractionItem(o,a,n):this.stopDurationItem("".concat(o,"_").concat(n),a)}handleUnsubscribed(A){let{track:e}=A;this.hitTest(e.room)&&this.stopDurationItem("".concat(e.userId,"_").concat(e.streamType),e.kind)}isRecording(A){return A.findIndex(e=>e.endTime===0)>=0}addDuractionItem(A,e,o){let n="".concat(A,"_").concat(o),a=new rz,I=this._durationMap.get(n);I?this.isRecording(I[e])||I[e].push(a):this._durationMap.set(n,{userId:A,type:o,audio:e===fA.AUDIO?[a]:[],video:e===fA.AUDIO?[]:[a]})}stopDurationItem(A,e){if(this._durationMap.has(A)){let o=this._durationMap.get(A)[e].find(n=>n.endTime===0);o&&o.stop()}}hitTest(A){return this._room===A}getDuration(A,e){return this._durationMap.has(A)?this._durationMap.get(A)[e].reduce((o,n)=>o+n.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},dtA=class{constructor(){G(this,"renderFreezeMap",new Map),G(this,"dataFreezeMap",new Map)}get(A,e){let o=this.renderFreezeMap.get(A),n=this.dataFreezeMap.get(A);return e?e==="data"?n:o:(Ma||Yr)&&o&&n&&o.duration>n.duration?o:n}set(A,e,o){o==="data"?this.dataFreezeMap.set(A,e):this.renderFreezeMap.set(A,e)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},htA=class{constructor(A){G(this,"_room"),G(this,"_renderFreezeMap",new Map),G(this,"_isVideoPlayingEventFiredMap",new Map),G(this,"_dataFreezeMap",new Map),G(this,"_monitorFreezeData",new dtA),G(this,"_eventMap",new Map),G(this,"_videoEncodeFailedCount",0),G(this,"_audioEncodeFailedCount",0),G(this,"_encodeFailedThreshold",3),G(this,"ABNORMAL_TIME_LOWER_LIMIT",3e3),G(this,"ABNORMAL_TIME_UPPER_LIMIT",5e3),G(this,"_videoAbnormalTimestampMap",new Map),G(this,"_remoteVideoAbnormalTimestampMap",new Map),G(this,"_audioAbnormalTimestampMap",new Map),G(this,"eventListenerMap",new Map),this._room=A.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(K.LEAVE_SUCCESS,A=>{let{room:e}=A;this.hitTest(e)&&this.stop()}).set(K.PLAY_TRACK_START,this.onPlayTrackStart).set(K.UNSUBSCRIBE_SUCCESS,A=>{let{room:e,streamType:o,remotePublishedUser:n}=A;if(!this.hitTest(e))return;let{userId:a}=n,I="".concat(a,"_").concat(o);this.stopDataFreeze({key:I,userId:a,type:o})}).set(K.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:e,prevMuteState:o,muteState:n}=A;if(!this.hitTest(e))return;let{userId:a}=n;if(o.hasVideo&&!n.hasVideo){let I="main",c="".concat(n.userId,"_").concat(I);this.stopDataFreeze({key:c,userId:a,type:I})}if(o.hasAuxiliary&&!n.hasAuxiliary){let I="auxiliary",c="".concat(n.userId,"_").concat(I);this.stopDataFreeze({key:c,userId:a,type:I})}}).set(K.PLAYER_STATE_CHANGED,A=>{let{track:e,state:o,reason:n,type:a}=A;if(e.isRemote&&e.room&&this.hitTest(e.room)&&a===fA.VIDEO){if(o==="PLAYING"){let I="".concat(e.userId,"_").concat(e.streamType);this._isVideoPlayingEventFiredMap.set(I,!0)}n===fA.MUTE?this.onVideoTrackMuted(e):n===fA.UNMUTE&&this.onVideoTrackUnmuted(e)}}).set(K.HEARTBEAT_REPORT,this.onHearBeatReport).set(K.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(K.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((A,e)=>S.on(e,A,this))}uninstallEvents(){this._eventMap.forEach((A,e)=>S.off(e,A,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(A){if(!A.isSubscribed)return;let{userId:e,streamType:o}=A,n="".concat(e,"_").concat(o),a=this._dataFreezeMap.get(n),I=new rz;a?a.durationItemList.push(I):this._dataFreezeMap.set(n,{userId:e,type:o,durationItemList:[I],isFreezing(){let c=this.durationItemList[this.durationItemList.length-1];return c&&c.endTime===0}})}onVideoTrackUnmuted(A){if(!A.isSubscribed)return;let{userId:e,streamType:o}=A,n="".concat(e,"_").concat(o);this.stopDataFreeze({key:n,userId:e,type:o})}onHearBeatReport(A){let{room:e,report:o}=A;this.hitTest(e)&&(this.localMediaTrackDetector(o),this.remoteMediaTrackDetector(o))}remoteMediaTrackDetector(A){A.msg_down_stream_info.length>0&&A.msg_down_stream_info.forEach(e=>{var o;if(e.msg_video_status.length===0)return;let n=e.msg_user_info.str_identifier,a=(o=this._room.remotePublishedUserMap.get(n))==null?void 0:o.remoteVideoTrack;e.msg_video_status.forEach(I=>{let c=ki();if(I.uint32_video_codec_bitrate!==void 0&&I.uint32_video_codec_bitrate>0&&I.uint32_video_receive_fps===0&&a!=null&&a.muted)if(this._remoteVideoAbnormalTimestampMap.has("".concat(n,"-decode"))){let u=this._remoteVideoAbnormalTimestampMap.get("".concat(n,"-decode"));u&&c-u>this.ABNORMAL_TIME_LOWER_LIMIT&&c-u=this.ABNORMAL_TIME_UPPER_LIMIT&&(Jo.uploadEvent({userId:this._room.userId,log:"stat-".concat(oa.VIDEO_DECODE_RESUME_DURING_CALL)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(n,"-decode")))}if(I.uint32_video_codec_bitrate!==void 0&&I.uint32_video_codec_bitrate>5e5&&I.uint32_video_dec_fps!==void 0&&I.uint32_video_dec_fps<=5)if(this._remoteVideoAbnormalTimestampMap.has("".concat(n,"-hardware"))){let u=this._remoteVideoAbnormalTimestampMap.get("".concat(n,"-hardware"));if(u&&c-u>this.ABNORMAL_TIME_LOWER_LIMIT/2&&c-u<2*this.ABNORMAL_TIME_UPPER_LIMIT){Jo.uploadEvent({userId:this._room.userId,log:"stat-".concat(oa.VIDEO_HARDWARE_DECODE_FAILED)});let d=this._room.remotePublishedUserMap.get(n);if(d){let R=I.uint32_video_stream_type===2?d.remoteVideoTrack:d.remoteAuxiliaryTrack;R&&(R.log.warn("decode failed during call"),R.emit("decode-failed-during-call"))}}}else this._remoteVideoAbnormalTimestampMap.set("".concat(n,"-hardware"),c);else{let u=this._remoteVideoAbnormalTimestampMap.get("".concat(n,"-hardware"));u&&c-u>=2*this.ABNORMAL_TIME_UPPER_LIMIT&&(Jo.uploadEvent({userId:this._room.userId,log:"stat-".concat(oa.VIDEO_HARDWARE_DECODE_RESUME)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(n,"-hardware")))}})})}localMediaTrackDetector(A){if(A.msg_up_stream_info.msg_video_status){let e=A.msg_up_stream_info.msg_video_status,o=Array.from(this._room.localTracks).find(a=>a.kind==="video"&&!a.isScreen),n=o?.stat.bytesSent||0;if(o?.isMediaTrackActive===!1||n<=0||o!=null&&o.isUseCustomSource)return;e.forEach(a=>{let I=ki();if(a.uint32_video_stream_type===2)if(a.uint32_video_capture_fps!==0&&a.uint32_video_codec_bitrate===0&&a.uint32_video_enc_fps===0&&o!=null&&o.isPublished)if(this._videoAbnormalTimestampMap.has("local-encode")){let c=this._videoAbnormalTimestampMap.get("local-encode");c&&I-c>this.ABNORMAL_TIME_LOWER_LIMIT&&I-c=this.ABNORMAL_TIME_UPPER_LIMIT&&Jo.uploadEvent({userId:this._room.userId,log:"stat-".concat(oa.VIDEO_ENCODE_RESUME_DURING_CALL)}),this._videoAbnormalTimestampMap.delete("local-encode")}})}if(A.msg_up_stream_info.msg_audio_status){let e=A.msg_up_stream_info.msg_audio_status,o=Array.from(this._room.localTracks).find(I=>I.kind==="audio"),n=o?.stat.bytesSent||0;if(o?.isMediaTrackActive===!1||n<=0||o!=null&&o.isUseCustomSource)return;let a=ki();if(e.uint32_audio_codec_bitrate===0&&o!=null&&o.isPublished)if(this._audioAbnormalTimestampMap.has("local-encode")){let I=this._audioAbnormalTimestampMap.get("local-encode");I&&a-I>this.ABNORMAL_TIME_LOWER_LIMIT&&a-I=this.ABNORMAL_TIME_UPPER_LIMIT&&Jo.uploadEvent({userId:this._room.userId,log:"stat-".concat(oa.AUDIO_ENCODE_RESUME_DURING_CALL)}),this._audioAbnormalTimestampMap.delete("local-encode")}}}stopDataFreeze(A){let{key:e,userId:o,type:n}=A,a=this._dataFreezeMap.get(e);if(!a||!a.isFreezing())return;let I=a.durationItemList[a.durationItemList.length-1];I.stop();let c=I.getDuration();if(c>DN){let u=this._monitorFreezeData.get(e,"data");this._monitorFreezeData.set(e,{userId:o,type:n,duration:u?u.duration+c:c},"data")}else a.durationItemList.pop()}getTotalDuration(A){return A.reduce((e,o)=>{let n=o.getDuration();return e+Math.min(n,5e3)},0)}onPlayTrackStart(A){let{track:e}=A;if(!e.isRemote||!this.hitTest(e.room)||e.kind!==fA.VIDEO||!e.isRemotePublished)return;let o="".concat(e.userId,"_").concat(e.streamType);this._isVideoPlayingEventFiredMap.has(o)||this._isVideoPlayingEventFiredMap.set(o,!1)}getDataFreezeDuration(A){let e={dataFreeze:0,count:0},o=this._dataFreezeMap.get(A);if(o){if(o.isFreezing()){let n=o.durationItemList[o.durationItemList.length-1];n.stop(),n.getDuration(){document.hidden||(a=0)};document.addEventListener("visibilitychange",I);let c=(u,d)=>{var R;if(a){let k=e.decodeFPS,_=k>0&&k<=5?600+1e3/k:600,Z=d.presentationTime-a;if(Z>_){Z=Math.min(Z,5e3);let iA="".concat(e.userId,"_").concat(e.streamType),cA=this._monitorFreezeData.get(iA,"render");cA?cA.duration+=Z:this._monitorFreezeData.set(iA,{userId:e.userId,type:e.streamType,duration:Z},"render");let TA=this._renderFreezeMap.get(iA);TA?(TA.totalDuration+=Z,TA.count+=1):this._renderFreezeMap.set(iA,{userId:e.userId,type:e.streamType,totalDuration:Z,count:1})}}a=d.presentationTime,(R=o.element)==null||R.requestVideoFrameCallback(c)};(n=o.element)==null||n.requestVideoFrameCallback(c),this.eventListenerMap.set("".concat(e.userId,"_").concat(e.streamType),{onVisibilityChange:I})}onRemoteVideoPlayEnd(A){let{track:e,player:o}=A,n="".concat(e.userId,"_").concat(e.streamType),a=this.eventListenerMap.get(n);a&&document.removeEventListener("visibilitychange",a.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(A){return A===this._room}destroy(){this.uninstallEvents()}},ptA=es(hg(),1),ftA=class{constructor(A,e,o,n,a){let I=arguments.length>5&&arguments[5]!==void 0?arguments[5]:1.3333333333333333;this.vbMode=A,this.faceDetectorHash=o,this.visionTaskRegistry=n,this.logger=a,G(this,"animationState"),G(this,"originalAspect"),G(this,"totalOffsetX",0),G(this,"totalOffsetY",0),G(this,"defaultScaleRatio",.1),G(this,"isRecovering",!1),G(this,"boundaryY",280),G(this,"lastActionTime",0),G(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=I||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,e)}addEvent(A,e,o){let n=[{key:570704,error:o??(e?void 0:11)},{key:570705,error:o??(e?void 0:22)}][A-1];n&&(e?ct.addSuccessEvent({key:n.key}):ct.addFailedEvent({key:n.key,error:n.error}))}actionCentering(A){let e=Date.now();if(this.animation(),!this.faceDetectorHash||e-this.lastActionTimee/2?(a=e-o-n,I=o-a):(a=o,I=0),{min:a,offset:I}}calculateTargetPosition(A,e,o,n,a,I){let c,u,d=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.4,R=A+o/2,k=e+n/2,{min:_,offset:Z}=this.calculateBoundary(R,a,A,o),{min:iA,offset:cA}=this.calculateBoundary(k,I,e,n);return c=2*_+o,u=2*iA+n,c/u>this.originalAspect?(c=u*this.originalAspect,Z=R-c/2):(u=c/this.originalAspect,cA=k-u/2),o/a>d&&(Z=0,cA=0,c=a,u=I),Z=Math.max(0,Math.min(Z,a-c)),cA=Math.max(0,Math.min(cA,I-u)),{sx:Z,sy:cA,cropWidth:c,cropHeight:u,timestamp:Date.now()}}processFacePositionCrop(A,e,o){if(!this.animationState.current||!this.animationState.target){let c={sx:0,sy:0,cropWidth:e,cropHeight:o,timestamp:Date.now()};return this.animationState.current=c,void(this.animationState.target=c)}let n=this.positionDistance(this.animationState.target,A),a=this.positionDistance(this.animationState.current,A),I=this.animationState.current.cropWidth/e;n>this.animationState.debounceThreshold*I&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&a>this.animationState.movementThreshold*I&&(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=bt({},A),void(this.animationState.target=bt({},A));let e=this.positionDistance(this.animationState.current,A),o=this.positionDistance(this.animationState.target,A);e>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,e=Math.min(A/this.animationState.duration,1),o=n=>n<.5?2*n*n:(4-2*n)*n-1;if(this.animationState.current&&this.animationState.target){let n=(this.animationState.target.sx-this.animationState.current.sx)*o(e);this.animationState.current.sx+=n,this.totalOffsetX+=n;let a=(this.animationState.target.sy-this.animationState.current.sy)*o(e);if(this.animationState.current.sy+=a,this.totalOffsetY+=a,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*o(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*o(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*o(e)),hr(this.animationState.current.scaleOffsetX)&&hr(this.animationState.target.scaleOffsetX)&&hr(this.animationState.current.scaleOffsetY)&&hr(this.animationState.target.scaleOffsetY)){let I=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*o(e);this.animationState.current.scaleOffsetX+=I;let c=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*o(e);this.animationState.current.scaleOffsetY+=c}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(A,e){return Math.sqrt(Rf(A.sx-e.sx,2)+Rf(A.sy-e.sy,2))}recoverOriginal(A,e){this.animationState.target={sx:0,sy:0,cropWidth:A,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(A,e,o,n,a,I){let c=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.3;if(this.isRecovering)return;let u=this.calculateTargetPosition(o,n,a,I,A,e);this.processFacePositionCrop(u,A,e),a*I/u.cropWidth/u.cropHeight>c&&this.recoverOriginal(A,e)}movingPortrait(A,e,o,n,a,I){var c,u,d,R,k,_,Z,iA,cA,TA,JA,Ie;let XA={sx:o+a/2+this.totalOffsetX,sy:n+I/2+this.totalOffsetY,cropWidth:A,cropHeight:e,scaleRatio:(u=(c=this.animationState.current)==null?void 0:c.scaleRatio)!=null?u:1,scaleOffsetX:(R=(d=this.animationState.current)==null?void 0:d.scaleOffsetX)!=null?R:0,scaleOffsetY:(_=(k=this.animationState.current)==null?void 0:k.scaleOffsetY)!=null?_:0,timestamp:Date.now()};this.animationState.target={sx:A/2,sy:n+I/2,cropWidth:A,cropHeight:e,scaleRatio:(iA=(Z=this.animationState.target)==null?void 0:Z.scaleRatio)!=null?iA:1,scaleOffsetX:(TA=(cA=this.animationState.target)==null?void 0:cA.scaleOffsetX)!=null?TA:0,scaleOffsetY:(Ie=(JA=this.animationState.target)==null?void 0:JA.scaleOffsetY)!=null?Ie:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(a*I/A/e/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 Ct({code:Ge.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(o.message||o)})),this.resolvePreditReady()})}init(A){return DA(this,null,function*(){var e,o,n;this.predictReady=new Promise(u=>{this.resolvePreditReady=u});let a=A.Wasm,I=this.context.ctx;if(A.color&&(this._color=A.color),A.mat4&&(this._mat4=A.mat4),A.postProcessing&&(this._postProcessing=A.postProcessing),this._enableFaceCentering=(e=A.enableFaceCentering)!=null&&e,this._enableEffectOptimization=(o=A.enableEffectOptimization)!=null&&o,this.wasm=new a.AllIn1(I),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:u,y:d,width:R,height:k}=A.waterMark;this.wasm.setWaterMark(u,d,R,k)}if(A.beautyParams){let{beauty:u,brightness:d,ruddy:R}=A.beautyParams;this.wasm.setBeauty(u,d,R,A?.width,A?.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),I.uniform1i(I.getUniformLocation(this.program,"mask"),1),A.bg instanceof HTMLImageElement&&(I.uniform1i(I.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(A.bg)),A.waterMark&&(I.uniform1i(I.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(A.waterMark.image));let c=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=I.getUniformLocation(this.program,"u_textureMatrix"),I.uniformMatrix4fv(this._textureMatrixLocation,!1,c),this._offsetMatrixLocation=I.getUniformLocation(this.program,"u_offsetMatrix"),I.uniformMatrix4fv(this._offsetMatrixLocation,!1,c),this._colorLocation=I.getUniformLocation(this.program,"u_color"),I.uniform1i(I.getUniformLocation(this.program,"lastMask"),4),this._weixin){let u=this.context.createShader(I.FRAGMENT_SHADER,`#version 300 es +`))}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return DA(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return DA(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return DA(this,null,function*(){try{let e=yield this._peerConnection.createOffer(gz);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:ez,responseCommand:io.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof _m||this.localAuxVideoTrack instanceof _m,state:this._room.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(e.data.sdp)),this._signalChannel.sendWaitForResponse(e).then(o=>{let{code:n,message:a,data:I}=o.data;return n===0?this.acceptAnswer(I):this.checkPublishResultCode(n,a)})}setSDPDirection(e,o){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"all",a=rs(e);return a.media.forEach(I=>{(n==="all"||I.type===n)&&(I.direction=o)}),tp(a)}acceptAnswer(e){return DA(this,null,function*(){var o,n,a,I,c;try{let u;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let R=((o=this._publishingLocalVideoTrack)==null?void 0:o.profile.bitrate)||((n=this.localMainVideoTrack)==null?void 0:n.profile.bitrate),k=((a=this._publishingLocalAudioTrack)==null?void 0:a.profile.bitrate)||((I=this.localMainAudioTrack)==null?void 0:I.profile.bitrate);if(R){let _=this._isPublishingAux?fA.AUXILIARY:fA.BIG;u=yield this.setBandwidth({bandwidth:R,type:fA.VIDEO,sdp:u,videoType:_})}k&&(u=yield this.setBandwidth({bandwidth:k,type:fA.AUDIO,sdp:u}))}if(u=this.removeVideoOrientation(e.sdp),(c=this._publishingLocalVideoTrack)!=null&&c.small){let{smallStreamConfig:R}=this._room;u=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||R.bitrate,type:fA.VIDEO,videoType:fA.SMALL,sdp:u})}let d={type:e.type,sdp:u};yield this.setAnswer(d),this._log.debug("accepted answer: ".concat(u))}catch(u){throw this._log.error("failed to accept remote answer ".concat(u)),u}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.send(Az,this._room.muteState))}getIsReconnecting(){return this._isReconnecting}reconnect(){return DA(this,null,function*(){if(!(zg(g6.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:jx,responseCommand:io.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=yQ(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(o/1e3,"s")),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},o)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(K.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{rs(e).media.forEach((o,n)=>{if(o.type===fA.AUDIO){let a=o.ssrcs&&o.ssrcs[0];a&&(this.ssrc.audio=Number(a.id))}else{if(this._sdpSemantics===OR&&o.ssrcGroups)return void o.ssrcGroups.forEach((I,c)=>{let u=Number(I.ssrcs.split(" ")[0]);c===0?this.ssrc.video=u:c===1&&(this.ssrc.small=u)});let a=o.ssrcs&&o.ssrcs[0];if(!a)return;switch(n){case 1:this.ssrc.video=Number(a.id);break;case 2:this.ssrc.small=Number(a.id);break;case 3:this.ssrc.auxiliary=Number(a.id)}}})}catch{}}getVideoTrackId(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:fA.VIDEO;if(this._peerConnection){let o=this._peerConnection.getSenders();if(e===fA.AUXILIARY&&o[3]&&o[3].track)return o[3].track.id;if(e===fA.VIDEO&&o[1]&&o[1].track)return o[1].track.id}if(this.localMainVideoTrack&&e===fA.VIDEO){let o=this.localMainVideoTrack.mediaTrack;if(o)return o.id}if(this.localAuxVideoTrack&&e===fA.AUXILIARY){let o=this.localAuxVideoTrack.mediaTrack;if(o)return o.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,o){if(e!==0)throw e===xR?(this._log.error(ts.NOT_SUPPORTED_H264ENCODE),new Ct({code:Ge.NOT_SUPPORTED_H264,message:Wi({key:Mi.NOT_SUPPORTED_H264ENCODE})})):new Ct({code:Ge.UNKNOWN,message:Wi({key:Mi.SIGNAL_RESPONSE_FAILED,data:{signalResponse:io.PUBLISH_RESULT,code:e,message:o}})})}};vt([Dn(A=>function(){for(var e=arguments.length,o=new Array(e),n=0;n{let c=u=>{this._emitter.off("closed",c),I(new Ct({code:Ge.API_CALL_ABORTED,message:Wi({key:Mi.CONNECTION_ABORTED,data:u})}))};this._emitter.on("closed",c),A.apply(this,o).then(a,I).finally(()=>{this._emitter.off("closed",c)})})})],Zx.prototype,"publish"),vt([Zh(521715,!1)],Zx.prototype,"unpublish"),vt([Tm(XQ.prototype.afterConnect),kW(XQ.prototype.beforeConnect)],Zx.prototype,"connect");var Xx=Zx,RtA=class{constructor(A,e){this.room=A,G(this,"_log"),G(this,"_prevReportTime",0),G(this,"_prevReport",{}),G(this,"_prevStats",null),G(this,"_prevEncoderImplementation",""),G(this,"_prevAuxEncoderImpl",""),G(this,"_prevQualityLimitationReason",""),G(this,"_prevAuxQualityLimitationReason",""),G(this,"_prevDecoderImplementationMap",new Map),G(this,"_decodeMap",new Map),G(this,"_prevQpSum",0),G(this,"_prevAuxQpSum",0),G(this,"totalBytesSent",0),G(this,"totalBytesReceived",0),G(this,"_spcStats",null),this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(A){return DA(this,null,function*(){var e,o,n,a,I,c,u;let d={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},R=A.getPeerConnection(),k=A.getSSRC();if(R)try{if((this._spcStats||(yield R.getStats())).forEach(_=>{var Z,iA,cA,TA,JA,Ie,XA,Ft,ie,ke,Nt,Ut,Ui;let Oi,or;if(_.type==="outbound-rtp")if((_.mediaType||_.kind)===fA.VIDEO){if(_.ssrc===k.video?(Oi=fA.VIDEO,or=A.localMainVideoTrack):_.ssrc===k.small?Oi=fA.SMALL:_.ssrc===k.auxiliary&&(or=A.localAuxVideoTrack,Oi=fA.AUXILIARY),!Oi)return;d[Oi].bytesSent=_.bytesSent,d[Oi].packetsSent=_.packetsSent,d[Oi].framesEncoded=_.framesEncoded,Ee(_.keyFramesEncoded)||(d[Oi].keyFramesEncoded=_.keyFramesEncoded),Ee(_.nackCount)||(d[Oi].nackCount=_.nackCount),Ee(_.pliCount)||(d[Oi].pliCount=_.pliCount),Ee(_.retransmittedPacketsSent)||(d[Oi].retransmittedPacketsSent=_.retransmittedPacketsSent),Ee(_.totalEncodeTime)||(d[Oi].totalEncodeTime=_.totalEncodeTime),Ee(_.totalPacketSendDelay)||(d[Oi].totalPacketSendDelay=_.totalPacketSendDelay);let xi=0;if(!Ee(_.qpSum)&&!Ee(_.framesEncoded)&&_.framesEncoded>0){let yo=_.qpSum,Sa=_.framesEncoded,Vn=Oi===fA.VIDEO?this._prevQpSum:this._prevAuxQpSum,NI=Oi===fA.VIDEO?((iA=(Z=A.localMainVideoTrack)==null?void 0:Z.stat)==null?void 0:iA.framesEncoded)||0:((TA=(cA=A.localAuxVideoTrack)==null?void 0:cA.stat)==null?void 0:TA.framesEncoded)||0;if(Sa>NI&&yo>Vn){let CG=yo-Vn,WM=Sa-NI;xi=Math.round(CG/WM),xi>35&&A.videoCodec==="h264"&&this._log.warn("".concat(Oi===fA.AUXILIARY?"aux ":"","video encoder QP is high: ").concat(xi,", resolution: ").concat(_.frameWidth,"x").concat(_.frameHeight,", codec: ").concat(A.videoCodec,", "))}Oi===fA.VIDEO?this._prevQpSum=yo:Oi===fA.AUXILIARY&&(this._prevAuxQpSum=yo)}if(!Ee(_.encoderImplementation)&&(Oi===fA.VIDEO&&this._prevEncoderImplementation!==_.encoderImplementation||Oi===fA.AUXILIARY&&this._prevAuxEncoderImpl!==_.encoderImplementation)){let yo=2,Sa=this._prevEncoderImplementation;Oi===fA.AUXILIARY&&(yo=7,Sa=this._prevAuxEncoderImpl),S.emit("262",{userId:A.userId,streamType:yo,prevImplementation:Sa,implementation:_.encoderImplementation,codec:A.videoCodec,isHWCodec:_.powerEfficientEncoder}),this[Oi===fA.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=_.encoderImplementation,or?.log.info("encoderImplementation change to ".concat(_.encoderImplementation,"(").concat(A.videoCodec,") HWEncoder: ").concat(_.powerEfficientEncoder))}_.ssrc===k.video?!Ee(_.qualityLimitationReason)&&_.bytesSent!==0&&this._prevQualityLimitationReason!==_.qualityLimitationReason&&(or?.log.info("qualityLimitationReason change to ".concat(_.qualityLimitationReason)),S.emit("263",{userId:A.userId,reason:_.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(JA=A.localMainVideoTrack)==null?void 0:JA.isQosClearFirst}),this._prevQualityLimitationReason=_.qualityLimitationReason):_.ssrc===k.auxiliary&&!Ee(_.qualityLimitationReason)&&_.bytesSent!==0&&this._prevAuxQualityLimitationReason!==_.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(_.qualityLimitationReason)),S.emit("263",{userId:A.userId,reason:_.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(Ie=A.localAuxVideoTrack)==null?void 0:Ie.isQosClearFirst}),this._prevAuxQualityLimitationReason=_.qualityLimitationReason)}else d.audio.bytesSent=_.bytesSent,d.audio.packetsSent=_.packetsSent;else if(_.type==="candidate-pair")dm(_)&&(this.totalBytesSent=_.bytesSent,hr(_.currentRoundTripTime)&&(d.rtt=Math.floor(1e3*_.currentRoundTripTime)));else if(_.type==="media-source"){if(_.kind===fA.AUDIO)d.audio.audioLevel=_.audioLevel||0,d.audio.totalAudioEnergy=_.totalAudioEnergy||0,_.echoReturnLoss,Ee((ie=(Ft=(XA=A.localMainAudioTrack)==null?void 0:XA.sourceTrack)==null?void 0:Ft.stats)==null?void 0:ie.deliveredFramesDuration)?_.totalSamplesDuration&&(d.audio.totalSamplesDuration=_.totalSamplesDuration):d.audio.totalSamplesDuration=A.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(_.kind===fA.VIDEO)if(_.trackIdentifier===A.getVideoTrackId(fA.VIDEO))if((Ut=(Nt=(ke=A.localMainVideoTrack)==null?void 0:ke.sourceTrack)==null?void 0:Nt.stats)!=null&&Ut.deliveredFrames){let{deliveredFrames:xi}=A.localMainVideoTrack.sourceTrack.stats;d.video.framesCaptured=xi,A.localMainVideoTrack.stat.framesCaptured&&A.localMainVideoTrack.stat.framesCaptured>0&&xi>=A.localMainVideoTrack.stat.framesCaptured?d.video.fpsCapture=Math.floor((xi-A.localMainVideoTrack.stat.framesCaptured)/this.statInterval):d.video.fpsCapture=_.framesPerSecond}else d.video.fpsCapture=_.framesPerSecond;else _.trackIdentifier===A.getVideoTrackId(fA.AUXILIARY)?d.auxiliary.fpsCapture=_.framesPerSecond:d.small.fpsCapture=_.framesPerSecond}if(!Ee(_.audioLevel)&&(Ui=A.localMainAudioTrack)!=null&&Ui.mediaTrack&&_.trackIdentifier===A.localMainAudioTrack.mediaTrack.id&&(d.audio.audioLevel=_.audioLevel||0),!Ee(_.frameWidth)){let xi=fA.SMALL;_.trackIdentifier===A.getVideoTrackId(fA.VIDEO)||_.ssrc===k.video?xi=fA.VIDEO:(_.trackIdentifier===A.getVideoTrackId(fA.AUXILIARY)||_.ssrc===k.auxiliary)&&(xi=fA.AUXILIARY),d[xi].frameWidth=_.frameWidth,d[xi].frameHeight=_.frameHeight,d[xi].framesSent=_.framesSent}}),A.localMainAudioTrack||A.getRoom().capturedLocalMainAudioTrack){let _=A.localMainAudioTrack||A.getRoom().capturedLocalMainAudioTrack;if(_){let Z=_.getInternalAudioLevel(),iA=_.getInternalAudioLevelAfter3A();d.audio.audioCaptureEnergyAfter3a=iA,d.audio.micAudioLevel=Z,d.audio.audioLevel===0&&A.localMainAudioTrack&&(d.audio.audioLevel=iA??Z),!A.localMainAudioTrack&&!Ee((o=(e=_.sourceTrack)==null?void 0:e.stats)==null?void 0:o.deliveredFramesDuration)&&(d.audio.totalSamplesDuration=_.sourceTrack.stats.deliveredFramesDuration/1e3)}}if(!A.localMainVideoTrack&&A.getRoom().capturedLocalMainVideoTrack){let _=A.getRoom().capturedLocalMainVideoTrack;if((a=(n=_?.sourceTrack)==null?void 0:n.stats)!=null&&a.deliveredFrames){let{deliveredFrames:Z}=_.sourceTrack.stats;d.video.framesCaptured=Z,_.stat.framesCaptured&&_.stat.framesCaptured>0&&Z>=_.stat.framesCaptured&&(d.video.fpsCapture=Math.floor((Z-_.stat.framesCaptured)/this.statInterval)),_.stat.framesCaptured=Z}}if(!A.localAuxVideoTrack&&A.getRoom().capturedLocalAuxVideoTrack){let _=A.getRoom().capturedLocalAuxVideoTrack;if((c=(I=_?.sourceTrack)==null?void 0:I.stats)!=null&&c.deliveredFrames){let{deliveredFrames:Z}=_.sourceTrack.stats;d.auxiliary.framesCaptured=Z,_.stat.framesCaptured&&_.stat.framesCaptured>0&&Z>=_.stat.framesCaptured&&(d.auxiliary.fpsCapture=Math.floor((Z-_.stat.framesCaptured)/this.statInterval)),_.stat.framesCaptured=Z}}this.totalBytesSent||(this.totalBytesSent+=d.audio.bytesSent+d.video.bytesSent+d.auxiliary.bytesSent),Object.keys(d).forEach(_=>{_===fA.AUDIO?(A.localMainAudioTrack&&(A.localMainAudioTrack.stat=d[_]),A.localAuxAudioTrack&&(A.localAuxAudioTrack.stat=d[_])):_===fA.VIDEO?A.localMainVideoTrack&&(A.localMainVideoTrack.stat=d[_]):_===fA.AUXILIARY&&A.localAuxVideoTrack&&(A.localAuxVideoTrack.stat=d[_])})}catch(_){this._log.warn("failed to getStats on sender connection ".concat(_))}return d.rtt===0&&(d.rtt=((u=this.room.networkQuality)==null?void 0:u.uplinkRTT)||0),d})}getReceiverStats(A){return DA(this,null,function*(){var e,o,n;let a={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:""}},I=A.getPeerConnection();if(I)try{let{ssrc:c}=A,{muteState:u,subscribeState:d}=A;(this._spcStats||(yield I.getStats())).forEach(_=>{var Z,iA;if(_.type==="codec"&&this._decodeMap.set(_.id,_),_.type==="inbound-rtp"){let cA=(_.mediaType||_.kind)===fA.AUDIO;if(cA){if(_.ssrc!==c.audio||!u.hasAudio)return;a.audio.packetsReceived=_.packetsReceived,a.audio.bytesReceived=_.bytesReceived,a.audio.packetsLost=_.packetsLost,_.insertedSamplesForDeceleration&&(a.audio.insertedSamplesForDeceleration=_.insertedSamplesForDeceleration),_.removedSamplesForAcceleration&&(a.audio.removedSamplesForAcceleration=_.removedSamplesForAcceleration),_.totalSamplesDuration&&(a.audio.totalSamplesDuration=_.totalSamplesDuration),_.totalSamplesReceived&&(a.audio.totalSamplesReceived=_.totalSamplesReceived),_.concealedSamples&&(a.audio.concealedSamples=_.concealedSamples),_.silentConcealedSamples&&(a.audio.silentConcealedSamples=_.silentConcealedSamples);let{remoteAudioTrack:TA}=A;TA.stat.packetsReceived=_.packetsReceived,TA.stat.bytesReceived=_.bytesReceived,TA.stat.packetsLost=_.packetsLost,a.audio.p2pDelay=TA.stat.end2EndDelay,a.hasAudio=!0}else{if(Yr&&_.bytesReceived===0)return;let TA;_.ssrc===c.video&&u.hasVideo&&(a.video.packetsReceived=_.packetsReceived,a.video.bytesReceived=_.bytesReceived,a.video.packetsLost=_.packetsLost,a.video.framesReceived=_.framesReceived,a.video.framesDecoded=_.framesDecoded,a.video.fpsDecoded=_.framesPerSecond,a.hasVideo=!0,A.videoCodec=Vs[(Z=this._decodeMap.get(_.codecId))==null?void 0:Z.mimeType.split("/")[1]]||"h264",a.video.codec=A.videoCodec,TA=A.remoteVideoTrack,u.hasSmall&&d.smallVideo&&(a.isSmallSubscribed=!0),_.decoderImplementation&&(!this._prevDecoderImplementationMap.has(a.userId)||this._prevDecoderImplementationMap.get(a.userId)!==_.decoderImplementation)&&(TA.log.info("decoderImplementation change to ".concat(_.decoderImplementation,"(").concat(A.videoCodec,") HWDecoder: ").concat(_.powerEfficientDecoder)),S.emit("262",{userId:this.room.userId,remoteUserId:a.userId,prevImplementation:this._prevDecoderImplementationMap.get(a.userId),implementation:_.decoderImplementation,codec:A.videoCodec,isHWCodec:_.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(a.userId,_.decoderImplementation)),Ee(_.keyFramesDecoded)||TA.updateKeyFramesDecoded(_.keyFramesDecoded)),_.ssrc===c.auxiliary&&u.hasAuxiliary&&(a.auxiliary.packetsReceived=_.packetsReceived,a.auxiliary.bytesReceived=_.bytesReceived,a.auxiliary.packetsLost=_.packetsLost,a.auxiliary.framesReceived=_.framesReceived,a.auxiliary.framesDecoded=_.framesDecoded,a.auxiliary.fpsDecoded=_.framesPerSecond,TA=A.remoteAuxiliaryTrack,a.auxiliary.p2pDelay=TA.stat.end2EndDelay,a.hasAuxiliary=!0,a.video.codec=((iA=this._decodeMap.get(_.codecId))==null?void 0:iA.mimeType.split("/")[1].toLowerCase())||"h264",Ee(_.keyFramesDecoded)||TA.updateKeyFramesDecoded(_.keyFramesDecoded)),TA&&(TA.stat.packetsReceived=_.packetsReceived,TA.stat.bytesReceived=_.bytesReceived,TA.stat.packetsLost=_.packetsLost,TA.stat.framesReceived=_.framesReceived,TA.stat.framesDecoded=_.framesDecoded,_.jitterBufferDelay&&(TA.stat.jitterBufferDelay=Math.floor(_.jitterBufferDelay/_.jitterBufferEmittedCount*1e3)),a.video.p2pDelay=TA.stat.end2EndDelay)}_.jitterBufferDelay&&(cA?(a.audio.totalJitter=_.jitterBufferDelay,a.audio.totalJitterCount=_.jitterBufferEmittedCount,a.audio.estimatedPlayoutTimestamp=_.estimatedPlayoutTimestamp):_.ssrc===c.video&&u.hasVideo?(a.video.totalJitter=_.jitterBufferDelay,a.video.totalJitterCount=_.jitterBufferEmittedCount,a.video.estimatedPlayoutTimestamp=_.estimatedPlayoutTimestamp):_.ssrc===c.auxiliary&&u.hasAuxiliary&&(a.auxiliary.totalJitter=_.jitterBufferDelay,a.auxiliary.totalJitterCount=_.jitterBufferEmittedCount))}else _.type==="candidate-pair"&&dm(_)&&(this.totalBytesReceived=_.bytesReceived,hr(_.currentRoundTripTime)&&(a.rtt=Math.floor(1e3*_.currentRoundTripTime)));Ee(_.frameWidth)||((_.trackIdentifier===A.getMainStreamVideoTrackId()||_.ssrc===c.video)&&(a.video.frameWidth=_.frameWidth,a.video.frameHeight=_.frameHeight,A.remoteVideoTrack.stat.frameWidth=_.frameWidth,A.remoteVideoTrack.stat.frameHeight=_.frameHeight),(_.trackIdentifier===A.getAuxStreamVideoTrackId()||_.ssrc===c.auxiliary)&&(a.auxiliary.frameWidth=_.frameWidth,a.auxiliary.frameHeight=_.frameHeight,A.remoteAuxiliaryTrack.stat.frameWidth=_.frameWidth,A.remoteAuxiliaryTrack.stat.frameHeight=_.frameHeight)),!Ee(_.audioLevel)&&A.muteState.audioAvailable&&A.remoteAudioTrack.mediaTrack&&_.trackIdentifier===A.remoteAudioTrack.mediaTrack.id&&(a.audio.audioLevel=_.audioLevel||0,a.audio.totalAudioEnergy=_.totalAudioEnergy||0)}),a.audio.audioLevel===0&&A.muteState.audioAvailable&&(a.audio.audioLevel=A.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=a.audio.bytesReceived+a.video.bytesReceived+a.auxiliary.bytesReceived),Ee((e=A.remoteVideoTrack.player.stat)==null?void 0:e.fps)||(a.video.fpsRender=A.remoteVideoTrack.player.stat.fps),Ee((o=A.remoteAuxiliaryTrack.player.stat)==null?void 0:o.fps)||(a.auxiliary.fpsRender=A.remoteAuxiliaryTrack.player.stat.fps);let R=a.audio.estimatedPlayoutTimestamp,k=a.video.estimatedPlayoutTimestamp;if(R&&k&&A.remoteAudioTrack.isAvailable&&A.remoteVideoTrack.isAvailable){let _=k-R;Math.abs(_)<=1e4&&(a.avSyncDelay=_,Math.abs(_)>150&&this._log.warn("av sync delay",_))}}catch(c){this._log.warn("failed to getStats on receiver connection ".concat(c))}return a.rtt===0&&(a.rtt=((n=this.room.networkQuality)==null?void 0:n.uplinkRTT)||0),a})}getStats(A,e){return DA(this,null,function*(){let o,n={},a=[];if(this.room.singlePC){let I=this.room.singlePC.getPeerConnection();if(!I)return{senderStats:n,receiverStats:a};let c=ki(),u=yield I.getStats(),d=ki();d-c>2e3&&this._log.warn("getStats cost ".concat(d-c,"ms"));let R=[],k=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec","media-playout"]);u.forEach(_=>k.has(_.type)&&R.push(_)),this._spcStats=R}A&&(n=yield this.getSenderStats(A));for(let[I,c]of e){let u=yield this.getReceiverStats(c);u&&a.push(u)}return e.size&&(o=this.getMediaPlayoutStats(this._spcStats)),{senderStats:n,receiverStats:a,mediaPlayoutStats:o}})}getDifferenceValue(A,e){if(zQ(A))return e;let o=e-A;return o<0?0:o}prepareReport(A){let{stats:e,report:o,freezeMap:n,uplinkConnection:a}=A;var I,c,u,d,R,k,_,Z,iA;if(!zQ(e.senderStats)){let ie={uint32_audio_level:e.senderStats.audio.audioLevel*iE,uint32_audio_energy:1e6*(e.senderStats.audio.totalAudioEnergy||0),uint32_audio_codec_bitrate:e.senderStats.audio.bytesSent};e.senderStats.audio.micAudioLevel&&(ie.uint32_mic_audio_level=e.senderStats.audio.micAudioLevel*iE),Ee(e.senderStats.audio.audioCaptureEnergyAfter3a)||(ie.uint32_audio_capture_energy_after3a=e.senderStats.audio.audioCaptureEnergyAfter3a*iE),e.senderStats.audio.totalSamplesDuration&&(o.msg_device_info.uint32_audio_capture_cost=e.senderStats.audio.totalSamplesDuration);let ke=[];if(e.senderStats.video.bytesSent){let Ut={uint32_video_stream_type:2,uint32_video_codec_fps:e.senderStats.video.framesSent,uint32_video_capture_fps:e.senderStats.video.fpsCapture,uint32_video_width:e.senderStats.video.frameWidth,uint32_video_height:e.senderStats.video.frameHeight,uint32_video_codec_bitrate:e.senderStats.video.bytesSent,uint32_video_enc_fps:e.senderStats.video.framesEncoded,uint32_key_frame_count:e.senderStats.video.keyFramesEncoded,uint32_nack_count:e.senderStats.video.nackCount,uint32_pli_count:e.senderStats.video.pliCount,uint32_encode_cost:1e3*(e.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(e.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:e.senderStats.video.retransmittedPacketsSent};ke.push(Ut)}if(e.senderStats.small.bytesSent){let Ut={uint32_video_stream_type:3,uint32_video_codec_fps:e.senderStats.small.framesSent||0,uint32_video_capture_fps:e.senderStats.small.fpsCapture||0,uint32_video_width:e.senderStats.small.frameWidth||0,uint32_video_height:e.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:e.senderStats.small.bytesSent,uint32_video_enc_fps:e.senderStats.small.framesEncoded||0,uint32_key_frame_count:e.senderStats.small.keyFramesEncoded,uint32_nack_count:e.senderStats.small.nackCount,uint32_pli_count:e.senderStats.small.pliCount,uint32_encode_cost:1e3*(e.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(e.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:e.senderStats.small.retransmittedPacketsSent};ke.push(Ut)}if(e.senderStats.auxiliary.bytesSent){let Ut={uint32_video_stream_type:7,uint32_video_codec_fps:e.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:e.senderStats.auxiliary.fpsCapture||0,uint32_video_width:e.senderStats.auxiliary.frameWidth||0,uint32_video_height:e.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:e.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:e.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:e.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:e.senderStats.auxiliary.nackCount,uint32_pli_count:e.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(e.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(e.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:e.senderStats.auxiliary.retransmittedPacketsSent};ke.push(Ut)}let Nt={uint32_bitrate:0,uint32_lost:0,uint32_rtt:e.senderStats.rtt};o.msg_up_stream_info={msg_audio_status:ie,msg_video_status:ke,msg_network_status:Nt}}let{statInterval:cA}=this;o.msg_down_stream_info=[],e.receiverStats.forEach(ie=>{let ke={msg_user_info:{str_identifier:ie.userId,uint64_tinyid:ie.tinyId},msg_network_status:{uint32_rtt:ie.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(ie.hasAudio){let Nt={uint32_audio_p2p_delay:ie.audio.p2pDelay,uint32_audio_cache_ms:ie.audio.totalJitter,uint32_audio_cache_ms_count:ie.audio.totalJitterCount,uint32_audio_codec_bitrate:ie.audio.bytesReceived,uint32_audio_total_bitrate:ie.audio.bytesReceived,uint32_audio_level:1e8*ie.audio.audioLevel,uint32_audio_energy:1e6*ie.audio.totalAudioEnergy,uint32_audio_receive:ie.audio.packetsReceived,uint32_audio_origin_lost:ie.audio.packetsLost};ke.msg_audio_status=Nt}if(ie.hasVideo){let Nt=n.get("".concat(ie.userId,"_").concat(LR)),Ut=Nt?Nt.duration:0,Ui={uint32_video_stream_type:ie.isSmallSubscribed?3:2,uint32_video_receive_fps:ie.video.framesReceived,uint32_video_width:ie.video.frameWidth,uint32_video_height:ie.video.frameHeight,uint32_video_codec_bitrate:ie.video.bytesReceived,uint32_video_receive:ie.video.packetsReceived,uint32_video_origin_lost:ie.video.packetsLost,uint32_video_block_time:Ut,uint32_video_dec_fps:ie.video.framesDecoded,uint32_video_codec_fps:ie.video.fpsRender,uint32_video_cache_ms:ie.video.totalJitter,uint32_video_cache_ms_count:ie.video.totalJitterCount,uint32_video_p2p_delay:ie.video.p2pDelay,uint32_video_codec:ie.video.codec,int32_video_audio_relative_delay:ie.avSyncDelay+5e3};ke.msg_video_status.push(Ui)}if(ie.hasAuxiliary){let Nt=n.get("".concat(ie.userId,"_").concat(yN)),Ut=Nt?Nt.duration:0,Ui={uint32_video_stream_type:7,uint32_video_receive_fps:ie.auxiliary.framesReceived,uint32_video_width:ie.auxiliary.frameWidth,uint32_video_height:ie.auxiliary.frameHeight,uint32_video_codec_bitrate:ie.auxiliary.bytesReceived,uint32_video_receive:ie.auxiliary.packetsReceived+ie.auxiliary.packetsLost,uint32_video_origin_lost:ie.auxiliary.packetsLost,uint32_video_block_time:Ut,uint32_video_dec_fps:ie.auxiliary.framesDecoded,uint32_video_codec_fps:ie.video.fpsRender,uint32_video_cache_ms:ie.auxiliary.totalJitter,uint32_video_cache_ms_count:ie.auxiliary.totalJitterCount,uint32_video_p2p_delay:ie.auxiliary.p2pDelay,uint32_video_codec:ie.video.codec};ke.msg_video_status.push(Ui)}o.msg_down_stream_info.push(ke)}),e.mediaPlayoutStats&&!zQ(e.mediaPlayoutStats)&&(e.mediaPlayoutStats.synthesizedSamplesDuration*=1e3,e.mediaPlayoutStats.totalSamplesDuration*=1e3);let TA=this._prevReport,JA=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(o)),this._prevStats=JSON.parse(JSON.stringify(e)),o.msg_up_stream_info.msg_audio_status&&TA.msg_up_stream_info.msg_audio_status){let ie=TA.msg_up_stream_info.msg_audio_status,ke=o.msg_up_stream_info.msg_audio_status;if(ie.uint32_audio_codec_bitrate===0)ke.uint32_audio_codec_bitrate=0;else{let Nt=this.getDifferenceValue(ie.uint32_audio_codec_bitrate,ke.uint32_audio_codec_bitrate);ke.uint32_audio_codec_bitrate=Math.round(8*Nt/cA),o.msg_up_stream_info.msg_network_status.uint32_bitrate+=ke.uint32_audio_codec_bitrate}(I=TA.msg_device_info)!=null&&I.uint32_audio_capture_cost?(o.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(TA.msg_device_info.uint32_audio_capture_cost,o.msg_device_info.uint32_audio_capture_cost)/cA),o.msg_device_info.uint32_audio_capture_cost>0&&((u=a?.localMainAudioTrack)==null||u.updateAfter3aSilenceStartTime((c=e.senderStats.audio.audioCaptureEnergyAfter3a)!=null?c:e.senderStats.audio.micAudioLevel))):delete o.msg_device_info.uint32_audio_capture_cost}let Ie=TA.msg_up_stream_info.msg_video_status;o.msg_up_stream_info.msg_video_status.forEach(ie=>{let ke=Ie.find(or=>or.uint32_video_stream_type===ie.uint32_video_stream_type);if(!ke||ke.uint32_video_codec_bitrate===0)return ie.uint32_video_codec_bitrate=0,ie.uint32_video_enc_fps=0,void(ie.uint32_video_codec_fps=0);let Nt=0,Ut=0,Ui=0;ke&&ie.uint32_video_codec_bitrate>=ke.uint32_video_codec_bitrate&&(Nt=ke.uint32_video_codec_bitrate,Ut=ke.uint32_video_enc_fps,Ui=ke.uint32_video_codec_fps);let Oi=this.getDifferenceValue(Nt,ie.uint32_video_codec_bitrate);ie.uint32_video_codec_bitrate=Math.round(8*Oi/cA),o.msg_up_stream_info.msg_network_status.uint32_bitrate+=ie.uint32_video_codec_bitrate,ie.uint32_video_enc_fps=Math.round(this.getDifferenceValue(Ut,ie.uint32_video_enc_fps)/cA),ie.uint32_video_codec_fps=Math.round(this.getDifferenceValue(Ui,ie.uint32_video_codec_fps)/cA),ke.uint32_video_width===0&&ke.uint32_video_height===0&&ke.uint32_video_codec_fps===0&&(ie.uint32_video_codec_fps=ie.uint32_video_enc_fps),Ee(ke.uint32_key_frame_count)||(ie.uint32_key_frame_count=Math.round(this.getDifferenceValue(ke.uint32_key_frame_count,ie.uint32_key_frame_count))),Ee(ke.uint32_nack_count)||(ie.uint32_nack_count=Math.round(this.getDifferenceValue(ke.uint32_nack_count,ie.uint32_nack_count))),Ee(ke.uint32_pli_count)||(ie.uint32_pli_count=Math.round(this.getDifferenceValue(ke.uint32_pli_count,ie.uint32_pli_count))),Ee(ke.uint32_video_arq_packets)||(ie.uint32_video_arq_packets=Math.round(this.getDifferenceValue(ke.uint32_video_arq_packets,ie.uint32_video_arq_packets))),Ee(ke.uint32_encode_cost)||(ie.uint32_encode_cost=Math.round(this.getDifferenceValue(ke.uint32_encode_cost,ie.uint32_encode_cost)/cA)),Ee(ke.uint32_send_packet_cost)||(ie.uint32_send_packet_cost=Math.round(this.getDifferenceValue(ke.uint32_send_packet_cost,ie.uint32_send_packet_cost)/cA))});let XA=TA.msg_down_stream_info;o.msg_down_stream_info=o.msg_down_stream_info.filter(ie=>XA.find(ke=>ke.msg_user_info.uint64_tinyid===ie.msg_user_info.uint64_tinyid));let Ft=o.msg_down_stream_info;if(Ft.forEach(ie=>{let ke=XA.find(Nt=>Nt.msg_user_info.uint64_tinyid===ie.msg_user_info.uint64_tinyid);if(zQ(ie.msg_audio_status)||zQ(ke.msg_audio_status))ie.msg_audio_status={};else{let Nt=ie.msg_audio_status,Ut=ke.msg_audio_status,Ui=this.getDifferenceValue(Ut.uint32_audio_cache_ms_count,Nt.uint32_audio_cache_ms_count);delete Nt.uint32_audio_cache_ms_count,Nt.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(Ut.uint32_audio_cache_ms,Nt.uint32_audio_cache_ms)/Ui)||0;let Oi=this.room.remotePublishedUserMap.get(ie.msg_user_info.str_identifier);Oi&&(Oi.remoteAudioTrack.stat.jitterBufferDelay=Nt.uint32_audio_cache_ms),Nt.uint32_audio_origin_lost=this.getDifferenceValue(Ut.uint32_audio_origin_lost,Nt.uint32_audio_origin_lost),Nt.uint32_audio_receive=this.getDifferenceValue(Ut.uint32_audio_receive,Nt.uint32_audio_receive),Nt.uint32_audio_receive+=Nt.uint32_audio_origin_lost;let or=this.getDifferenceValue(Ut.uint32_audio_codec_bitrate,Nt.uint32_audio_codec_bitrate);Nt.uint32_audio_codec_bitrate=Math.round(8*or/cA),Nt.uint32_audio_total_bitrate=Math.round(8*or/cA)}if(ie.msg_video_status&&ke.msg_video_status){let Nt=ke.msg_video_status;ie.msg_video_status=ie.msg_video_status.filter(Ut=>Nt.find(Ui=>Ui.uint32_video_stream_type===Ut.uint32_video_stream_type)),ie.msg_video_status.forEach(Ut=>{let Ui=Nt.find(WM=>WM.uint32_video_stream_type===Ut.uint32_video_stream_type),Oi=Ui.uint32_video_receive,or=Ui.uint32_video_origin_lost,xi=Ui.uint32_video_codec_bitrate,yo=Ui.uint32_video_receive_fps,Sa=Ui.uint32_video_dec_fps;Ut.uint32_video_origin_lost=this.getDifferenceValue(or,Ut.uint32_video_origin_lost),Ut.uint32_video_receive=this.getDifferenceValue(Oi,Ut.uint32_video_receive)+Ut.uint32_video_origin_lost;let Vn=this.getDifferenceValue(xi,Ut.uint32_video_codec_bitrate);Ut.uint32_video_codec_bitrate=Math.round(8*Vn/cA);let NI=this.getDifferenceValue(yo,Ut.uint32_video_receive_fps);Ut.uint32_video_receive_fps=Math.round(NI/cA),Ut.uint32_video_dec_fps=Math.round(this.getDifferenceValue(Sa,Ut.uint32_video_dec_fps)/cA);let CG=this.getDifferenceValue(Ui.uint32_video_cache_ms_count,Ut.uint32_video_cache_ms_count);delete Ut.uint32_video_cache_ms_count,Ut.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Ui.uint32_video_cache_ms,Ut.uint32_video_cache_ms)/CG)||0})}}),!Ee((d=JA?.mediaPlayoutStats)==null?void 0:d.totalSamplesDuration)&&!Ee((R=e.mediaPlayoutStats)==null?void 0:R.totalSamplesDuration)){let ie=2*Math.floor(this.getDifferenceValue((k=JA?.mediaPlayoutStats)==null?void 0:k.synthesizedSamplesDuration,(_=e.mediaPlayoutStats)==null?void 0:_.synthesizedSamplesDuration)/cA),ke=2*Math.floor(this.getDifferenceValue((Z=JA?.mediaPlayoutStats)==null?void 0:Z.totalSamplesDuration,(iA=e.mediaPlayoutStats)==null?void 0:iA.totalSamplesDuration)/cA);o.msg_device_info.uint32_audio_play_cost=ke-ie}return JA&&e.receiverStats.forEach(ie=>{if(ie.audio.concealedSamples&&ie.audio.totalSamplesReceived){let ke=JA.receiverStats.find(Nt=>Nt.userId===ie.userId);if(ke&&ke.audio.concealedSamples&&ke.audio.totalSamplesReceived){let Nt=(ie.audio.silentConcealedSamples||0)-(ke.audio.silentConcealedSamples||0),Ut=ie.audio.concealedSamples-ke.audio.concealedSamples,Ui=ie.audio.totalSamplesReceived-ke.audio.totalSamplesReceived,Oi=Math.floor((Ut-Nt)/Ui*1e3*cA);if(Oi>1e3*cA/5){let or=Ft.find(xi=>xi.msg_user_info.str_identifier===ie.userId);or&&(or.msg_audio_status.uint32_audio_block_time=Oi)}}}}),o.msg_down_stream_info.forEach(ie=>{ie.msg_video_status.forEach(ke=>{ke.uint32_video_codec_bitrate===0&&ke.uint32_video_receive_fps===0&&(ke.uint32_video_width=0,ke.uint32_video_height=0)})}),o}getStatsReport(A){return DA(this,arguments,function(e){var o=this;let{uplinkConnection:n,downlinkConnections:a,freezeMap:I}=e;return function*(){let c={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}}]},u=yield o.getStats(n,a);return JSON.stringify(o._prevReport)==="{}"&&(o._prevReport=JSON.parse(JSON.stringify(c))),o.prepareReport({stats:u,report:c,freezeMap:I,uplinkConnection:n}),o._prevReportTime=Date.now(),c}()})}getMediaPlayoutStats(A){let e;if(Aa(A)){for(let o of A)if(o.type==="media-playout"){let{synthesizedSamplesDuration:n,totalSamplesDuration:a}=o;e={synthesizedSamplesDuration:n,totalSamplesDuration:a};break}return e}}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)})}},MtA=es(hg());function wtA(A){return new Promise(e=>DA(null,null,function*(){let o=setTimeout(()=>{e({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),n=Date.now(),a="https://".concat(A,"/?t=").concat(n);try{yield fetch(a)}catch{}clearTimeout(o);let I=function(c){let u={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let d=performance.getEntriesByType("resource").reverse();for(let R of d)if(R.name===c){let k=Math.round(R.duration),_=Math.max(Math.round(R.domainLookupStart-R.startTime),0),Z=R.redirectStart>0?Math.max(Math.round(R.redirectEnd-R.redirectStart),0):0,iA=R.fetchStart>0?Math.max(Math.round(R.domainLookupStart-R.fetchStart),0):0,cA=Math.round(R.domainLookupEnd-R.domainLookupStart),TA=Math.round(R.requestStart-R.secureConnectionStart),JA=Math.round(R.secureConnectionStart-R.connectStart),Ie=Math.round(R.responseStart-R.requestStart),XA=Math.round(R.responseEnd-(R.responseStart||R.startTime));u=fi(bt({},u),{totalCost:k,local:_,redirect:Z,httpCache:iA,dns:cA,tcp:JA,tls:TA,request:Ie,response:XA});break}}catch{}return u}(a);I.totalCost===0&&(I.totalCost=Date.now()-n),e(I)}))}var $x=class ow extends MtA.default{constructor(e){let{signalChannel:o,room:n}=e;super(),G(this,"_room"),G(this,"_signalChannel"),G(this,"_log"),G(this,"uplinkRTT",0),G(this,"uplinkLoss",0),G(this,"downlinkRTT",0),G(this,"downlinkLoss",0),G(this,"pingResults",{}),G(this,"_downlinkPrevStatMap",new Map),G(this,"_downlinkLossAndRTTMap",new Map),G(this,"_interval",-1),G(this,"_uplinkNetworkQuality",0),G(this,"_downlinkNetworkQuality",0),G(this,"_uplinkQualityHistory",[]),G(this,"_downlinkQualityHistory",[]),this._room=n,this._signalChannel=o,this._log=nA.createLogger({parent:n.getLogger(),id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this.uplinkRTT,", loss: ").concat(this.uplinkLoss," ws-rtt: ").concat(this._signalChannel.rtt)),this._uplinkNetworkQuality=e,this._uplinkQualityHistory.push(e),this._uplinkQualityHistory.length>ow.HISTORY_SIZE&&this._uplinkQualityHistory.shift()}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:o,loss:n}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(o,", loss: ").concat(n," ws-rtt: ").concat(this._signalChannel.rtt))}this._downlinkNetworkQuality=e,this._downlinkQualityHistory.push(e),this._downlinkQualityHistory.length>ow.HISTORY_SIZE&&this._downlinkQualityHistory.shift()}initialize(){this._signalChannel.on(io.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(cK,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var o,n;if(e.data.code!==0)return;let a=e.data.data;if(a.delay&&this.updateDelay(a.delay),this._room.signalChannel&&a.wsRtt&&(this._room.signalChannel.rtt=a.wsRtt),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this.uplinkLoss=0,void(this.uplinkRTT=0);let I=(n=(o=this._room)==null?void 0:o.uplinkConnection)==null?void 0:n.getPeerConnection();if(I&&this.isPeerConnectionDisconnected(I))return this.uplinkNetworkQuality=6,this.uplinkLoss=0,void(this.uplinkRTT=0);let c=a.expectAudPkg+a.expectVidPkg,u=a.recvAudPkg+a.recvVidPkg,d=c-u;c===0&&u===0||(this.uplinkLoss=d<=0?0:Math.round(d/c*100),this.uplinkRTT=a.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return DA(this,null,function*(){if(this._room.remotePublishedUserMap.size===0)return void(this.downlinkNetworkQuality=0);let e=[...this._room.remotePublishedUserMap.values()],o=new Set,n=e.filter(u=>{let d=u.getPeerConnection();return!(!d||o.has(d))&&(o.add(d),!0)}),a=n.filter(u=>{var d;return((d=u.getPeerConnection())==null?void 0:d.connectionState)===hi.CONNECTED});if(n.filter(u=>this.isPeerConnectionDisconnected(u.getPeerConnection())).length===e.length)return void(this.downlinkNetworkQuality=6);for(let u=0;u{this.isPeerConnectionDisconnected(u)&&(this._downlinkPrevStatMap.delete(u),this._downlinkLossAndRTTMap.delete(u))}),this._downlinkLossAndRTTMap.size===0)return this.downlinkRTT=0,this.downlinkLoss=0,void(this.downlinkNetworkQuality=0);let{rtt:I,loss:c}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=I,this.downlinkLoss=c,this.downlinkNetworkQuality=this.getNetworkQuality(c,I)})}getStat(e){return DA(this,null,function*(){let o={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!Vh())return o;let n=e.getReceivers();try{for(let a=0;a{I.type==="candidate-pair"&&hr(I.currentRoundTripTime)&&(o.rtt=Math.round(1e3*I.currentRoundTripTime)),I.type==="inbound-rtp"&&(I.mediaType===fA.AUDIO||I.mediaType===fA.VIDEO)&&(o.totalPacketsLost+=I.packetsLost,o.totalPacketsReceived+=I.packetsReceived)});return o.rtt===0&&(o.rtt=this.uplinkRTT),o}catch{return o}})}getAverageLossAndRTT(e){let o={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(n=>{o.rtt+=n.rtt,o.loss+=n.loss}),Object.keys(o).forEach(n=>{o[n]=Math.round(o[n]/e.length)})),o}getNetworkQuality(e,o){return e>50||o>500?5:e>30||o>350?4:e>20||o>200?3:e>10||o>100?2:e>=0||o>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=1)}handleUplinkConnectionStateChange(e){let{state:o}=e;o==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):o==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==hi.DISCONNECTED&&e.connectionState!==hi.FAILED&&e.connectionState!==hi.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,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=nn.run("ric",()=>{var e;this.handleDownlinkNetworkQuality();let o=[...this._downlinkLossAndRTTMap.values()];S.emit(K.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:o});let n=(e=this._room.scheduleResult.config)==null?void 0:e.pingDomainInfo,a={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};n&&(a=fi(bt({},a),{pingResults:this.uplinkRTT>n.rttThreshold||this.downlinkRTT>n.rttThreshold?this.pingResults:{}})),this.emit(ow.EVENT_NETWORK_QUALITY,a);let I=Date.now();if(n&&(this.uplinkRTT>n.rttThreshold||this.downlinkRTT>n.rttThreshold)&&I-ow.lastPingTime>1e3*n.interval){ow.lastPingTime=Date.now();let c=n.domain.map(u=>wtA(u).then(d=>({domain:u,cost:d.totalCost})));Promise.all(c).then(u=>{this.pingResults.isPoorNetwork=u.some(d=>d.cost>700),this.pingResults.timestamp=I,this.pingResults.data=u,u.forEach(d=>{ct.addSuccessEvent({key:521718,cost:d.cost})}),this._log.warn("All ping results: ".concat(JSON.stringify(u)))}).catch(u=>{this._log.warn("Error during pinging domains: ".concat(u))})}},{delay:2e3})):this._log.info("network quality calculating is already started")}hadRecentBadUplink(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2;return this._uplinkQualityHistory.some(o=>o>e)}hadRecentBadDownlink(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2;return this._downlinkQualityHistory.some(o=>o>e)}stop(){this._log.debug("stopped"),this._interval!==-1&&(nn.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:o}=this._room;e.forEach(n=>{let{srcTinyId:a,videoDelay:I,audioDelay:c}=n,u=o.get(a);if(u){let d=this._room.remotePublishedUserMap.get(u);d?.setDelay({videoDelay:I,audioDelay:c})}})}};G($x,"HISTORY_SIZE",10),G($x,"EVENT_NETWORK_QUALITY","0"),G($x,"lastPingTime",0);var Iz=$x,cz=class{constructor(A){G(this,"_frameWorkType"),G(this,"_component"),G(this,"_language"),G(this,"connectionType"),G(this,"_room"),G(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0}),G(this,"_keyPrefix"),G(this,"_log"),G(this,"_intervalId"),G(this,"_firstPublishedUserList"),G(this,"_networkQuality"),G(this,"_basicInfo"),G(this,"_pathJoinRoom"),G(this,"_pathLeaveRoom"),G(this,"_pathMainVideoMap"),G(this,"_pathMainAudioMap"),G(this,"_pathAuxiliaryMap"),G(this,"_remoteStreamStatMap"),G(this,"_localStreamStat"),G(this,"_eventMap",new Map),G(this,"_captureCostSum",0),G(this,"_captureCostCount",0),G(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=nA.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&$n(this[e])&&(this[e]=function(o){let{fn:n,context:a}=o;return function(){try{for(var I=arguments.length,c=new Array(I),u=0;unA.error("".concat(n.name,"() error observed ").concat(R))):d}catch(d){nA.error("".concat(n.name,"() error observed ").concat(d))}}}({fn:this[e],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:ol,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,Im().then(()=>{this._basicInfo.string_os_version=UQ(),this._basicInfo.string_device_name=pu()||this._basicInfo.string_os_version})}addEvent(A,e){return this._eventMap.set(A,e),S.on(A,e),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(K.JOIN_START,this.handleJoinStart).addEvent(K.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(K.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(K.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(K.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(K.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(K.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(K.JOIN_FAILED,this.handleJoinFailed).addEvent(K.LEAVE_START,this.handleLeaveStart).addEvent(K.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(K.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(K.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(K.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(K.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(K.PUBLISH_START,this.handlePublishStart).addEvent(K.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(K.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(K.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(K.PLAY_TRACK_START,this.handlePlayStart).addEvent(K.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(K.PLAYER_STATE_CHANGED,A=>{let{track:e,state:o,type:n}=A;!e.isRemote||!this.hitTest(e.room)||o==="PLAYING"&&(n===fA.AUDIO?this.handleAudioPlaying(e):this.handleVideoPlaying(e))}).addEvent(K.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(K.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(K.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(K.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(K.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(K.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(K.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:e,prevMuteState:o,muteState:n}=A;if(!this.hitTest(e))return;let a=o.hasAudio||o.hasVideo||o.hasSmall,I=o.hasAuxiliary,c=n.hasAudio||n.hasVideo||n.hasSmall,u=n.hasAuxiliary;!a&&c&&this.handleRemoteStreamAdded(n.userId,"main"),!I&&u&&this.handleRemoteStreamAdded(n.userId,"auxiliary")}).addEvent(K.SINGLE_CONNECTION_STAT,A=>{let{room:e,stat:o}=A;this.hitTest(e)&&(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,e)=>S.off(e,A)),this._eventMap.clear()}destroy(){this.uninstallEvents(),nn.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&&(Ee(A.params.frameWorkType)||(this._frameWorkType=A.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),Ee(A.params.component)||(this._component=A.params.component,this._basicInfo.uint32_component=this._component),Ee(A.params.language)||(this._language=A.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(A){let{room:e,detailCost:o}=A;if(this.hitTest(e)&&o){let{totalCost:n,local:a,dns:I,tcp:c,tls:u,request:d,response:R}=o;this._pathJoinRoom.int32_schedule_cost=n,this._pathJoinRoom.int32_schedule_local=a,this._pathJoinRoom.int32_schedule_dns=I,this._pathJoinRoom.int32_schedule_tcp=c,this._pathJoinRoom.int32_schedule_tls=u,this._pathJoinRoom.int32_schedule_request=d,this._pathJoinRoom.int32_schedule_response=R}}handleSignalConnectionStart(A){let{room:e}=A;this.hitTest(e)&&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:e,error:o}=A;this.hitTest(e)&&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 Ct?Number(o.getExtraCode()||o.getCode()):Ge.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:e,error:o}=A;this.hitTest(e)&&(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:e}=A;this.hitTest(e)&&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 e;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=(e=this._room.audioManager.localAudioTrack)==null?void 0:e.after3aSilenceStartTime;o&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=ki()-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 e=Date.now();this.report().then(()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e})}}handleSwitchRoomSuccess(A){let{room:e}=A;if(this.hitTest(e)&&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:e,error:o}=A;if(this.hitTest(e)){let n=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=n,this._pathJoinRoom.uint64_end_time=n,o&&(this._pathJoinRoom.int32_end_ret=o instanceof Ct?Number(o.getExtraCode()||o.getCode()):Ge.UNKNOWN)}}handleRemoteStreamAdded(A,e){var o;let n="".concat(A,"_").concat(e);if(!this._remoteStreamStatMap.has(n)){let a={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:fi(bt({},StA),{msg_user_info:new QK({userId:A,tinyId:(o=this._room.remotePublishedUserMap.get(A))==null?void 0:o.tinyId,role:20})})};a.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(n,a)}}handleSubscribeStart(A){let{room:e,remotePublishedUser:o,streamType:n,subscribeState:a}=A;if(!this.hitTest(e))return;let{userId:I,tinyId:c,role:u}=o,d=new QK({userId:I,tinyId:c,role:u==="anchor"?20:21}),R=Date.now(),k="".concat(I,"_").concat(n),_=this._remoteStreamStatMap.get(k);_&&_.subscribeStartTime===0&&(_.subscribeStartTime=R),n==="main"?(o.muteState.hasVideo&&(a.video||a.smallVideo)&&!this._pathMainVideoMap.has(k)&&this._pathMainVideoMap.set(k,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:I,sendSubscribeCMDTime:R}),o.muteState.hasAudio&&a.audio&&!this._pathMainAudioMap.has(k)&&this._pathMainAudioMap.set(k,{statsToReport:{msg_user_info:d,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:I,sendSubscribeCMDTime:R})):o.muteState.hasAuxiliary&&a.auxiliary&&!this._pathAuxiliaryMap.has(k)&&this._pathAuxiliaryMap.set(k,{sendSubscribeCMDTime:R})}handleSubscribed(A){let{room:e,remotePublishedUser:o,streamType:n}=A;if(this.hitTest(e)){let a="".concat(o.userId,"_").concat(n),I=this._remoteStreamStatMap.get(a);I&&I.subscribedTime===0&&(I.subscribedTime=Date.now())}}handlePlayStart(A){let{track:e}=A;if(!e.isRemote||!this.hitTest(e.room))return;let o="".concat(e.userId,"_").concat(e.streamType),n=this._remoteStreamStatMap.get(o);n?.playStreamTime===0&&(n.playStreamTime=Date.now())}handleVideoLoadedData(A){let{track:e}=A;if(!e.isRemote||!this.hitTest(e.room))return;let o="".concat(e.userId,"_").concat(e.streamType),n=this._pathMainVideoMap.get(o);n&&n.statsToReport.uint64_combine_first_frame_time===0&&(n.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(A){let e="".concat(A.userId,"_").concat(A.streamType),o=Date.now(),n=this._pathMainVideoMap.get(e),a=this._remoteStreamStatMap.get(e);if(a){let{statsToReport:I}=a;if(I.uint32_video_render_first||A.streamType!=="main"?this.hasAuxFlag(A.userId):this.hasVideoFlag(A.userId)){let c=o-this._pathJoinRoom.uint64_start_time;I.uint32_video_render_first=c,ct.addNumber({key:516820,value:c})}}n?.statsToReport.uint64_render_first_frame_time===0&&(n.statsToReport.uint64_render_first_frame_time=o)}handleAudioPlaying(A){let e="".concat(A.userId,"_").concat(A.streamType),o=this._pathMainAudioMap.get(e);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(e=>{let{rtt:o,loss:n,userId:a,videoDelay:I,audioDelay:c}=e,u=this._networkQuality.totalDownlinkRTTAndLossMap.get(a);if(u)u.totalRTT+=o,u.totalLoss+=n,I&&(u.totalVideoDelay=(u.totalVideoDelay||0)+I,u.videoDelayCount=(u.videoDelayCount||0)+1),c&&(u.totalAudioDelay=(u.totalAudioDelay||0)+c,u.audioDelayCount=(u.audioDelayCount||0)+1),u.count++;else{let d,R,k,_;I&&(R=I,k=1),c&&(d=c,_=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(a,{totalRTT:o,totalLoss:n,count:1,totalAudioDelay:d,totalVideoDelay:R,audioDelayCount:_,videoDelayCount:k})}}))}handleHeartbeatStats(A){var e;if(this.hitTest(A.room)){let{msg_device_info:o,msg_up_stream_info:n,msg_down_stream_info:a}=A.report;if(n.msg_video_status[0]){let{uint32_video_codec_bitrate:I,uint32_video_enc_fps:c,uint32_video_width:u,uint32_video_height:d}=n.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=I,this._localStreamStat.totalVideoFPS+=c,this._localStreamStat.totalVideoWidth+=u,this._localStreamStat.totalVideoHeight+=d,this._localStreamStat.videoCount++}if(n.msg_audio_status){let{uint32_audio_level:I}=n.msg_audio_status;Math.floor(I/iE*100)>0&&(this._localStreamStat.totalAudioLevel+=I/iE,this._localStreamStat.audioLevelCount++)}a.forEach(I=>{let{msg_user_info:c,msg_audio_status:u,msg_video_status:d}=I,R=c.str_identifier,k=this._room.remotePublishedUserMap.get(R);if(d.forEach(_=>{let Z=_.uint32_video_stream_type===2,iA=_.uint32_video_stream_type===7,cA="".concat(R,"_").concat(Z?"main":"auxiliary"),TA=this._remoteStreamStatMap.get(cA);if(TA&&(Z&&k!=null&&k.remoteVideoTrack.isSubscribed||iA&&k!=null&&k.remoteAuxiliaryTrack)){TA.totalVideoFPS+=_.uint32_video_receive_fps,TA.totalVideoBitrate+=_.uint32_video_codec_bitrate,TA.videoCount++,TA.statsToReport.uint32_video_width===0&&(TA.statsToReport.uint32_video_width=_.uint32_video_width),TA.statsToReport.uint32_video_height===0&&(TA.statsToReport.uint32_video_height=_.uint32_video_height);let JA=Z?k.remoteVideoTrack:k.remoteAuxiliaryTrack;JA.stat.jitterBufferDelay&&(TA.videoJitterBufferDelay=JA.stat.jitterBufferDelay),JA.stat.framesReceived&&(TA.statsToReport.uint32_video_consume_render_rate=Math.floor(JA.stat.framesDecoded/JA.stat.framesReceived*vf(10,6)))}}),!$R(u)){let _="".concat(R,"_main"),Z=this._remoteStreamStatMap.get(_);this._remoteStreamStatMap.has(_)&&Z&&k!=null&&k.remoteAudioTrack.isSubscribed&&(Z.totalAudioBitrate+=u.uint32_audio_codec_bitrate,Z.audioCount++,k.remoteAudioTrack.stat.jitterBufferDelay&&(Z.audioJitterBufferDelay=k.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(u.uint32_audio_level/iE*100)>0&&(Z.totalAudioLevel+=u.uint32_audio_level/iE,Z.audioLevelCount++),u.uint32_audio_block_time&&(Z.statsToReport.uint32_audio_block_time+=u.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&&((e=this._room.audioManager.localAudioTrack)==null?void 0:e.muted)===!1&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}handlePublishStart(A){let{room:e}=A;this.hitTest(e)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(A){let{track:e}=A;e.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),e.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(A){let{track:e}=A;e.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()),e.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:e,error:o}=A,n={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[o.name]||(o instanceof Ct?o.getExtraCode()||o.getCode():Ge.UNKNOWN);e.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=n,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),e.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=n,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(A){return this._firstPublishedUserList.findIndex(e=>e.userId===A&&e.flag&_f)>=0}hasAudioFlag(A){return this._firstPublishedUserList.findIndex(e=>e.userId===A&&e.flag&Lf)>=0}hasAuxFlag(A){return this._firstPublishedUserList.findIndex(e=>e.userId===A&&e.flag&bf)>=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),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=A<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((A,e)=>{let{userId:o}=A,n=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(n){let{totalLoss:R,count:k,audioDelayCount:_,videoDelayCount:Z,totalAudioDelay:iA,totalVideoDelay:cA}=n;A.statsToReport.uint32_avg_down_loss=Math.floor(R/k),_&&iA&&(A.statsToReport.uint32_audio_network_p2p_delay=Math.floor(iA/_),A.audioJitterBufferDelay&&(A.statsToReport.uint32_p2p_delay=Math.floor(A.statsToReport.uint32_audio_network_p2p_delay+A.audioJitterBufferDelay))),Z&&cA&&(A.statsToReport.uint32_video_network_p2p_delay=Math.floor(cA/Z))}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:a}=this._room;a&&(A.statsToReport.uint32_audio_play_time=a.getDuration(e,fA.AUDIO),A.statsToReport.uint32_video_play_time=a.getDuration(e,fA.VIDEO)),A.statsToReport.uint32_video_render_first&&(A.statsToReport.uint32_video_render_first=Math.min(A.statsToReport.uint32_video_render_first,xm));let{badCaseDetector:I}=this._room,{dataFreeze:c,count:u}=I.getDataFreezeDuration(e),{renderFreeze:d}=I.getRenderFreezeDuration(e);A.statsToReport.uint32_video_block_count=u,A.statsToReport.uint32_video_block_time=Math.min(c,A.statsToReport.uint32_video_play_time),A.statsToReport.uint32_video_external_block_time=Math.min(d,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),I.isBlackStream(e)&&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,e)=>{this.hasAudioFlag(A.userId)?A.statsToReport.uint64_play_first_frame_time-A.statsToReport.uint64_start_enter_time>xm&&(A.statsToReport.uint64_play_first_frame_time=A.statsToReport.uint64_start_enter_time+xm):this._pathMainAudioMap.delete(e)}),this._pathMainVideoMap.forEach((A,e)=>{this.hasVideoFlag(A.userId)?A.statsToReport.uint64_render_first_frame_time-A.statsToReport.uint64_start_enter_time>xm&&(A.statsToReport.uint64_render_first_frame_time=A.statsToReport.uint64_start_enter_time+xm):this._pathMainVideoMap.delete(e)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>xm&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+xm)}getReportData(){this._basicInfo.uint32_networkType=mh();let A={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new QK({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:Kf(this._signalInfo.relayIp),uint32_client_ip:Kf(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*vf(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:Kf(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 tM(A),A}report(){return DA(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 DA(this,null,function*(){if(A.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),o=lA.enable?lu(A,2001,e):yield qN(A),n=o instanceof ArrayBuffer,a="".concat(fh(e,Xg.KEY_POINT),"&gzip=").concat(+n),I=!1;navigator.sendBeacon&&(I=navigator.sendBeacon(a,o));let c=[this.uploadKVStat(ct),this.uploadKVStat(oB)];I||c.push(Cu({url:a,body:o,priority:"low"})),yield Promise.all(c)})}setConnectionType(A){this.connectionType=A,this._basicInfo.uint32_connection_type=A}uploadKVStat(A){return DA(this,arguments,function(e){var o=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._room.sdkAppId;return function*(){var a,I;let c=e.getReportData((a=o._room)==null?void 0:a.userSig,(I=o._signalInfo)==null?void 0:I.reportToken);if(c.stats_count.length===0&&c.stats_distribution.length===0)return;c.msg_sdk_basic_info=fi(bt({},c.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(c);let u=lA.enable?lu(c,2003,n):yield qN(c),d=u instanceof ArrayBuffer,R="".concat(fh(+n,Xg.KV_STAT),"&gzip=").concat(+d),k=!1;navigator.sendBeacon&&(k=navigator.sendBeacon(R,u)),k||Cu({url:R,body:u})}()})}};vt([nB({settings:{timeout:500,retries:3}})],cz.prototype,"upload");var xm=5e3,StA={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},QK=class{constructor(A){G(this,"str_identifier"),G(this,"str_tinyid"),G(this,"uint32_role"),this.str_identifier=String(A.userId),this.str_tinyid=String(A.tinyId||0),this.uint32_role=A.role}},vtA=cz,Ez=class{constructor(){G(this,"_startTime"),G(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=ki())}stop(){this._endTime===0&&(this._endTime=ki())}getDuration(){return this._endTime===0?ki()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},NtA=class{constructor(A){G(this,"_room",null),G(this,"_durationMap"),G(this,"_eventMap",new Map),this._room=A.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(K.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(K.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(K.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:e,prevMuteState:o,muteState:n}=A;var a;let{userId:I}=n;if(!this.hitTest(e))return;o.hasAudio&&!n.hasAudio&&this.stopDurationItem("".concat(I,"_main"),fA.AUDIO),o.hasVideo&&!n.hasVideo&&this.stopDurationItem("".concat(I,"_main"),fA.VIDEO),o.hasAuxiliary&&!n.hasAuxiliary&&this.stopDurationItem("".concat(I,"_auxiliary"),fA.VIDEO);let c=(a=this._room)==null?void 0:a.remotePublishedUserMap.get(I);c&&(!o.hasAudio&&n.hasAudio&&c.remoteAudioTrack.isSubscribed&&this.addDuractionItem(I,fA.AUDIO,"main"),!o.hasVideo&&n.hasVideo&&c.remoteVideoTrack.isSubscribed&&this.addDuractionItem(I,fA.VIDEO,"main"),!o.hasAuxiliary&&n.hasAuxiliary&&c.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(I,fA.VIDEO,"auxiliary"))}),this._eventMap.forEach((A,e)=>S.on(e,A,this))}uninstallEvents(){this._eventMap.forEach((A,e)=>S.off(e,A,this)),this._eventMap.clear()}handleSubscribed(A){let{track:e}=A;if(!this.hitTest(e.room))return;let{userId:o,streamType:n,kind:a}=e;e.isSubscribed?this.addDuractionItem(o,a,n):this.stopDurationItem("".concat(o,"_").concat(n),a)}handleUnsubscribed(A){let{track:e}=A;this.hitTest(e.room)&&this.stopDurationItem("".concat(e.userId,"_").concat(e.streamType),e.kind)}isRecording(A){return A.findIndex(e=>e.endTime===0)>=0}addDuractionItem(A,e,o){let n="".concat(A,"_").concat(o),a=new Ez,I=this._durationMap.get(n);I?this.isRecording(I[e])||I[e].push(a):this._durationMap.set(n,{userId:A,type:o,audio:e===fA.AUDIO?[a]:[],video:e===fA.AUDIO?[]:[a]})}stopDurationItem(A,e){if(this._durationMap.has(A)){let o=this._durationMap.get(A)[e].find(n=>n.endTime===0);o&&o.stop()}}hitTest(A){return this._room===A}getDuration(A,e){return this._durationMap.has(A)?this._durationMap.get(A)[e].reduce((o,n)=>o+n.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},TtA=class{constructor(){G(this,"renderFreezeMap",new Map),G(this,"dataFreezeMap",new Map)}get(A,e){let o=this.renderFreezeMap.get(A),n=this.dataFreezeMap.get(A);return e?e==="data"?n:o:(Ma||Yr)&&o&&n&&o.duration>n.duration?o:n}set(A,e,o){o==="data"?this.dataFreezeMap.set(A,e):this.renderFreezeMap.set(A,e)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},GtA=class{constructor(A){G(this,"_room"),G(this,"_renderFreezeMap",new Map),G(this,"_isVideoPlayingEventFiredMap",new Map),G(this,"_dataFreezeMap",new Map),G(this,"_monitorFreezeData",new TtA),G(this,"_eventMap",new Map),G(this,"_videoEncodeFailedCount",0),G(this,"_audioEncodeFailedCount",0),G(this,"_encodeFailedThreshold",3),G(this,"ABNORMAL_TIME_LOWER_LIMIT",3e3),G(this,"ABNORMAL_TIME_UPPER_LIMIT",5e3),G(this,"_videoAbnormalTimestampMap",new Map),G(this,"_remoteVideoAbnormalTimestampMap",new Map),G(this,"_audioAbnormalTimestampMap",new Map),G(this,"eventListenerMap",new Map),this._room=A.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(K.LEAVE_SUCCESS,A=>{let{room:e}=A;this.hitTest(e)&&this.stop()}).set(K.PLAY_TRACK_START,this.onPlayTrackStart).set(K.UNSUBSCRIBE_SUCCESS,A=>{let{room:e,streamType:o,remotePublishedUser:n}=A;if(!this.hitTest(e))return;let{userId:a}=n,I="".concat(a,"_").concat(o);this.stopDataFreeze({key:I,userId:a,type:o})}).set(K.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:e,prevMuteState:o,muteState:n}=A;if(!this.hitTest(e))return;let{userId:a}=n;if(o.hasVideo&&!n.hasVideo){let I="main",c="".concat(n.userId,"_").concat(I);this.stopDataFreeze({key:c,userId:a,type:I})}if(o.hasAuxiliary&&!n.hasAuxiliary){let I="auxiliary",c="".concat(n.userId,"_").concat(I);this.stopDataFreeze({key:c,userId:a,type:I})}}).set(K.PLAYER_STATE_CHANGED,A=>{let{track:e,state:o,reason:n,type:a}=A;if(e.isRemote&&e.room&&this.hitTest(e.room)&&a===fA.VIDEO){if(o==="PLAYING"){let I="".concat(e.userId,"_").concat(e.streamType);this._isVideoPlayingEventFiredMap.set(I,!0)}n===fA.MUTE?this.onVideoTrackMuted(e):n===fA.UNMUTE&&this.onVideoTrackUnmuted(e)}}).set(K.HEARTBEAT_REPORT,this.onHearBeatReport).set(K.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(K.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((A,e)=>S.on(e,A,this))}uninstallEvents(){this._eventMap.forEach((A,e)=>S.off(e,A,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(A){if(!A.isSubscribed)return;let{userId:e,streamType:o}=A,n="".concat(e,"_").concat(o),a=this._dataFreezeMap.get(n),I=new Ez;a?a.durationItemList.push(I):this._dataFreezeMap.set(n,{userId:e,type:o,durationItemList:[I],isFreezing(){let c=this.durationItemList[this.durationItemList.length-1];return c&&c.endTime===0}})}onVideoTrackUnmuted(A){if(!A.isSubscribed)return;let{userId:e,streamType:o}=A,n="".concat(e,"_").concat(o);this.stopDataFreeze({key:n,userId:e,type:o})}onHearBeatReport(A){let{room:e,report:o}=A;this.hitTest(e)&&(this.localMediaTrackDetector(o),this.remoteMediaTrackDetector(o))}remoteMediaTrackDetector(A){A.msg_down_stream_info.length>0&&A.msg_down_stream_info.forEach(e=>{var o;if(e.msg_video_status.length===0)return;let n=e.msg_user_info.str_identifier,a=(o=this._room.remotePublishedUserMap.get(n))==null?void 0:o.remoteVideoTrack;e.msg_video_status.forEach(I=>{let c=ki();if(I.uint32_video_codec_bitrate!==void 0&&I.uint32_video_codec_bitrate>0&&I.uint32_video_receive_fps===0&&a!=null&&a.muted)if(this._remoteVideoAbnormalTimestampMap.has("".concat(n,"-decode"))){let u=this._remoteVideoAbnormalTimestampMap.get("".concat(n,"-decode"));u&&c-u>this.ABNORMAL_TIME_LOWER_LIMIT&&c-u=this.ABNORMAL_TIME_UPPER_LIMIT&&(Jo.uploadEvent({userId:this._room.userId,log:"stat-".concat(oa.VIDEO_DECODE_RESUME_DURING_CALL)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(n,"-decode")))}if(I.uint32_video_codec_bitrate!==void 0&&I.uint32_video_codec_bitrate>5e5&&I.uint32_video_dec_fps!==void 0&&I.uint32_video_dec_fps<=5)if(this._remoteVideoAbnormalTimestampMap.has("".concat(n,"-hardware"))){let u=this._remoteVideoAbnormalTimestampMap.get("".concat(n,"-hardware"));if(u&&c-u>this.ABNORMAL_TIME_LOWER_LIMIT/2&&c-u<2*this.ABNORMAL_TIME_UPPER_LIMIT){Jo.uploadEvent({userId:this._room.userId,log:"stat-".concat(oa.VIDEO_HARDWARE_DECODE_FAILED)});let d=this._room.remotePublishedUserMap.get(n);if(d){let R=I.uint32_video_stream_type===2?d.remoteVideoTrack:d.remoteAuxiliaryTrack;R&&(R.log.warn("decode failed during call"),R.emit("decode-failed-during-call"))}}}else this._remoteVideoAbnormalTimestampMap.set("".concat(n,"-hardware"),c);else{let u=this._remoteVideoAbnormalTimestampMap.get("".concat(n,"-hardware"));u&&c-u>=2*this.ABNORMAL_TIME_UPPER_LIMIT&&(Jo.uploadEvent({userId:this._room.userId,log:"stat-".concat(oa.VIDEO_HARDWARE_DECODE_RESUME)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(n,"-hardware")))}})})}localMediaTrackDetector(A){if(A.msg_up_stream_info.msg_video_status){let e=A.msg_up_stream_info.msg_video_status,o=Array.from(this._room.localTracks).find(a=>a.kind==="video"&&!a.isScreen),n=o?.stat.bytesSent||0;if(o?.isMediaTrackActive===!1||n<=0||o!=null&&o.isUseCustomSource)return;e.forEach(a=>{let I=ki();if(a.uint32_video_stream_type===2)if(a.uint32_video_capture_fps!==0&&a.uint32_video_codec_bitrate===0&&a.uint32_video_enc_fps===0&&o!=null&&o.isPublished)if(this._videoAbnormalTimestampMap.has("local-encode")){let c=this._videoAbnormalTimestampMap.get("local-encode");c&&I-c>this.ABNORMAL_TIME_LOWER_LIMIT&&I-c=this.ABNORMAL_TIME_UPPER_LIMIT&&Jo.uploadEvent({userId:this._room.userId,log:"stat-".concat(oa.VIDEO_ENCODE_RESUME_DURING_CALL)}),this._videoAbnormalTimestampMap.delete("local-encode")}})}if(A.msg_up_stream_info.msg_audio_status){let e=A.msg_up_stream_info.msg_audio_status,o=Array.from(this._room.localTracks).find(I=>I.kind==="audio"),n=o?.stat.bytesSent||0;if(o?.isMediaTrackActive===!1||n<=0||o!=null&&o.isUseCustomSource)return;let a=ki();if(e.uint32_audio_codec_bitrate===0&&o!=null&&o.isPublished)if(this._audioAbnormalTimestampMap.has("local-encode")){let I=this._audioAbnormalTimestampMap.get("local-encode");I&&a-I>this.ABNORMAL_TIME_LOWER_LIMIT&&a-I=this.ABNORMAL_TIME_UPPER_LIMIT&&Jo.uploadEvent({userId:this._room.userId,log:"stat-".concat(oa.AUDIO_ENCODE_RESUME_DURING_CALL)}),this._audioAbnormalTimestampMap.delete("local-encode")}}}stopDataFreeze(A){let{key:e,userId:o,type:n}=A,a=this._dataFreezeMap.get(e);if(!a||!a.isFreezing())return;let I=a.durationItemList[a.durationItemList.length-1];I.stop();let c=I.getDuration();if(c>wN){let u=this._monitorFreezeData.get(e,"data");this._monitorFreezeData.set(e,{userId:o,type:n,duration:u?u.duration+c:c},"data")}else a.durationItemList.pop()}getTotalDuration(A){return A.reduce((e,o)=>{let n=o.getDuration();return e+Math.min(n,5e3)},0)}onPlayTrackStart(A){let{track:e}=A;if(!e.isRemote||!this.hitTest(e.room)||e.kind!==fA.VIDEO||!e.isRemotePublished)return;let o="".concat(e.userId,"_").concat(e.streamType);this._isVideoPlayingEventFiredMap.has(o)||this._isVideoPlayingEventFiredMap.set(o,!1)}getDataFreezeDuration(A){let e={dataFreeze:0,count:0},o=this._dataFreezeMap.get(A);if(o){if(o.isFreezing()){let n=o.durationItemList[o.durationItemList.length-1];n.stop(),n.getDuration(){document.hidden||(a=0)};document.addEventListener("visibilitychange",I);let c=(u,d)=>{var R;if(a){let k=e.decodeFPS,_=k>0&&k<=5?600+1e3/k:600,Z=d.presentationTime-a;if(Z>_){Z=Math.min(Z,5e3);let iA="".concat(e.userId,"_").concat(e.streamType),cA=this._monitorFreezeData.get(iA,"render");cA?cA.duration+=Z:this._monitorFreezeData.set(iA,{userId:e.userId,type:e.streamType,duration:Z},"render");let TA=this._renderFreezeMap.get(iA);TA?(TA.totalDuration+=Z,TA.count+=1):this._renderFreezeMap.set(iA,{userId:e.userId,type:e.streamType,totalDuration:Z,count:1})}}a=d.presentationTime,(R=o.element)==null||R.requestVideoFrameCallback(c)};(n=o.element)==null||n.requestVideoFrameCallback(c),this.eventListenerMap.set("".concat(e.userId,"_").concat(e.streamType),{onVisibilityChange:I})}onRemoteVideoPlayEnd(A){let{track:e,player:o}=A,n="".concat(e.userId,"_").concat(e.streamType),a=this.eventListenerMap.get(n);a&&document.removeEventListener("visibilitychange",a.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(A){return A===this._room}destroy(){this.uninstallEvents()}},ktA=es(hg(),1),_tA=class{constructor(A,e,o,n,a){let I=arguments.length>5&&arguments[5]!==void 0?arguments[5]:1.3333333333333333;this.vbMode=A,this.faceDetectorHash=o,this.visionTaskRegistry=n,this.logger=a,G(this,"animationState"),G(this,"originalAspect"),G(this,"totalOffsetX",0),G(this,"totalOffsetY",0),G(this,"defaultScaleRatio",.1),G(this,"isRecovering",!1),G(this,"boundaryY",280),G(this,"lastActionTime",0),G(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=I||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,e)}addEvent(A,e,o){let n=[{key:570704,error:o??(e?void 0:11)},{key:570705,error:o??(e?void 0:22)}][A-1];n&&(e?ct.addSuccessEvent({key:n.key}):ct.addFailedEvent({key:n.key,error:n.error}))}actionCentering(A){let e=Date.now();if(this.animation(),!this.faceDetectorHash||e-this.lastActionTimee/2?(a=e-o-n,I=o-a):(a=o,I=0),{min:a,offset:I}}calculateTargetPosition(A,e,o,n,a,I){let c,u,d=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.4,R=A+o/2,k=e+n/2,{min:_,offset:Z}=this.calculateBoundary(R,a,A,o),{min:iA,offset:cA}=this.calculateBoundary(k,I,e,n);return c=2*_+o,u=2*iA+n,c/u>this.originalAspect?(c=u*this.originalAspect,Z=R-c/2):(u=c/this.originalAspect,cA=k-u/2),o/a>d&&(Z=0,cA=0,c=a,u=I),Z=Math.max(0,Math.min(Z,a-c)),cA=Math.max(0,Math.min(cA,I-u)),{sx:Z,sy:cA,cropWidth:c,cropHeight:u,timestamp:Date.now()}}processFacePositionCrop(A,e,o){if(!this.animationState.current||!this.animationState.target){let c={sx:0,sy:0,cropWidth:e,cropHeight:o,timestamp:Date.now()};return this.animationState.current=c,void(this.animationState.target=c)}let n=this.positionDistance(this.animationState.target,A),a=this.positionDistance(this.animationState.current,A),I=this.animationState.current.cropWidth/e;n>this.animationState.debounceThreshold*I&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&a>this.animationState.movementThreshold*I&&(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=bt({},A),void(this.animationState.target=bt({},A));let e=this.positionDistance(this.animationState.current,A),o=this.positionDistance(this.animationState.target,A);e>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,e=Math.min(A/this.animationState.duration,1),o=n=>n<.5?2*n*n:(4-2*n)*n-1;if(this.animationState.current&&this.animationState.target){let n=(this.animationState.target.sx-this.animationState.current.sx)*o(e);this.animationState.current.sx+=n,this.totalOffsetX+=n;let a=(this.animationState.target.sy-this.animationState.current.sy)*o(e);if(this.animationState.current.sy+=a,this.totalOffsetY+=a,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*o(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*o(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*o(e)),hr(this.animationState.current.scaleOffsetX)&&hr(this.animationState.target.scaleOffsetX)&&hr(this.animationState.current.scaleOffsetY)&&hr(this.animationState.target.scaleOffsetY)){let I=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*o(e);this.animationState.current.scaleOffsetX+=I;let c=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*o(e);this.animationState.current.scaleOffsetY+=c}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(A,e){return Math.sqrt(vf(A.sx-e.sx,2)+vf(A.sy-e.sy,2))}recoverOriginal(A,e){this.animationState.target={sx:0,sy:0,cropWidth:A,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(A,e,o,n,a,I){let c=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.3;if(this.isRecovering)return;let u=this.calculateTargetPosition(o,n,a,I,A,e);this.processFacePositionCrop(u,A,e),a*I/u.cropWidth/u.cropHeight>c&&this.recoverOriginal(A,e)}movingPortrait(A,e,o,n,a,I){var c,u,d,R,k,_,Z,iA,cA,TA,JA,Ie;let XA={sx:o+a/2+this.totalOffsetX,sy:n+I/2+this.totalOffsetY,cropWidth:A,cropHeight:e,scaleRatio:(u=(c=this.animationState.current)==null?void 0:c.scaleRatio)!=null?u:1,scaleOffsetX:(R=(d=this.animationState.current)==null?void 0:d.scaleOffsetX)!=null?R:0,scaleOffsetY:(_=(k=this.animationState.current)==null?void 0:k.scaleOffsetY)!=null?_:0,timestamp:Date.now()};this.animationState.target={sx:A/2,sy:n+I/2,cropWidth:A,cropHeight:e,scaleRatio:(iA=(Z=this.animationState.target)==null?void 0:Z.scaleRatio)!=null?iA:1,scaleOffsetX:(TA=(cA=this.animationState.target)==null?void 0:cA.scaleOffsetX)!=null?TA:0,scaleOffsetY:(Ie=(JA=this.animationState.target)==null?void 0:JA.scaleOffsetY)!=null?Ie:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(a*I/A/e/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 Ct({code:Ge.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(o.message||o)})),this.resolvePreditReady()})}init(A){return DA(this,null,function*(){var e,o,n;this.predictReady=new Promise(u=>{this.resolvePreditReady=u});let a=A.Wasm,I=this.context.ctx;if(A.color&&(this._color=A.color),A.mat4&&(this._mat4=A.mat4),A.postProcessing&&(this._postProcessing=A.postProcessing),this._enableFaceCentering=(e=A.enableFaceCentering)!=null&&e,this._enableEffectOptimization=(o=A.enableEffectOptimization)!=null&&o,this.wasm=new a.AllIn1(I),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:u,y:d,width:R,height:k}=A.waterMark;this.wasm.setWaterMark(u,d,R,k)}if(A.beautyParams){let{beauty:u,brightness:d,ruddy:R}=A.beautyParams;this.wasm.setBeauty(u,d,R,A?.width,A?.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),I.uniform1i(I.getUniformLocation(this.program,"mask"),1),A.bg instanceof HTMLImageElement&&(I.uniform1i(I.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(A.bg)),A.waterMark&&(I.uniform1i(I.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(A.waterMark.image));let c=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=I.getUniformLocation(this.program,"u_textureMatrix"),I.uniformMatrix4fv(this._textureMatrixLocation,!1,c),this._offsetMatrixLocation=I.getUniformLocation(this.program,"u_offsetMatrix"),I.uniformMatrix4fv(this._offsetMatrixLocation,!1,c),this._colorLocation=I.getUniformLocation(this.program,"u_color"),I.uniform1i(I.getUniformLocation(this.program,"lastMask"),4),this._weixin){let u=this.context.createShader(I.FRAGMENT_SHADER,`#version 300 es precision highp float; uniform sampler2D u_texture; uniform sampler2D mask; @@ -236,7 +236,7 @@ out vec2 v_texCoord; void main() { gl_Position = vec4(a_position.x, a_position.y, 0, 1); v_texCoord = a_texCoord; -}`);this._prePrograme=this.context.createProgram(d,u),I.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),I.uniform1i(I.getUniformLocation(this._prePrograme,"mask"),1)}!this._enableEffectOptimization||this.wasm.vbMode!==2&&this.wasm.vbMode!==3?this._postProcessing=void 0:QM()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):(n=this._postProcessing)==null||n.init(I,this.positionBuffer,this.texCoordBuffer,4/3),yield this.initVisionTasks(A)})}initVisionTasks(A){return DA(this,null,function*(){if(A.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._visionTaskRegistry.setVideo(this._selfieSegmentationHash,this.image),this._enableFaceCentering)try{this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let e=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!e)return;this._centerFace=new ftA(this.wasm.vbMode,this.image,e,this._visionTaskRegistry,this.context.log)}catch{this.log.error("Face detector model not found. Please redeploy the assets of the npm package.")}}})}onPredict(A){let e=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture)));let o=this.getMaskTexture(A);if(!o)return;let n=o;this._postProcessing&&(this._postProcessing.ratio=this.image.videoWidth/this.image.videoHeight,n=this._postProcessing.postProcessing(o)),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,n||null),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,this._bgTexture||null),e.activeTexture(e.TEXTURE3),e.bindTexture(e.TEXTURE_2D,this._waterMarkTexture||null),this.wasm.vbMode===3&&e.uniform3fv(this._colorLocation,this._color),this.useBufferFrame(),this._segmentationMask=A,this.totalFrames++,this.centerFace(),gu(this.wasm.rotation)&&this.resize(this.image.height,this.image.width),e.viewport(0,0,e.canvas.width,e.canvas.height),e.drawArrays(e.TRIANGLE_STRIP,0,4),A.close()}getMaskTexture(A){return A.confidenceMasks?A.confidenceMasks[0].getAsWebGLTexture():void 0}onFirstFrame(){this.waitingFirstFrame=!1;let A=this.context.ctx;this.useTexture(),A.texImage2D(A.TEXTURE_2D,0,A.RGBA,A.RGBA,A.UNSIGNED_BYTE,this.image)}render(A){let e=this.context.ctx,{image:o}=this;this.tryVideoFrameCallback();let{videoWidth:n,videoHeight:a}=o;if(gu(this.wasm.rotation)&&!this._visionTaskRegistry&&([n,a]=[a,n]),n===0||a===0||!this.available)return!1;o.width=n,o.height=a;let I=!1;if(this.totalFrames)this.useTexture(),I=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),I=this._textureValid,this._textureValid=!0}if(this.width===n&&this.height===a&&I?e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,o):(this.resize(n,a),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,o)),this._weixin){if(e.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask){let c=this.getMaskTexture(this._segmentationMask);e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,c||null),e.bindFramebuffer(e.FRAMEBUFFER,this._lastMaskFbo||null)}e.drawArrays(e.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,n,a):e.copyTexImage2D(e.TEXTURE_2D,0,e.RGBA,0,0,n,a,0)}try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let c=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);this.totalFrames===1&&this.context._canvas&&this.resolvePreditReady(),this.onPredict(c)}}catch(c){this._onAbort&&this._onAbort(c)}return this.totalFrames||(e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,this._bgTexture||null),e.activeTexture(e.TEXTURE3),e.bindTexture(e.TEXTURE_2D,this._waterMarkTexture||null),e.drawArrays(e.TRIANGLE_STRIP,0,4)),this._visionTaskRegistry&&this._visionTaskRegistry.resetHashResults(),!1}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let A=this.context.ctx;this._centerFace.aspectRatio=A.canvas.width/A.canvas.height,this._centerFace.actionCentering(this.image);let{current:e,offset:o}=this._centerFace;if(e&&(this.wasm.vbMode===1&&this.drawImage(e.sx,e.sy,e.cropWidth,e.cropHeight),o&&this.wasm.vbMode===2)){if(!this._mat4)return;let n=this._mat4.create(),{scaleRatio:a=1,scaleOffsetX:I=0,scaleOffsetY:c=0}=e;this._mat4.fromTranslation(n,[-o.offsetX/A.canvas.width+I,c,0]),this._mat4.scale(n,n,[a,a,1]),A.uniformMatrix4fv(this._offsetMatrixLocation,!1,n)}}drawImage(A,e,o,n){let a=this.context.ctx;if(!this._mat4)return;let{width:I,height:c}=a.canvas,u=this._mat4.create();this._mat4.fromTranslation(u,[A/I,1-(e+n)/c,0]),this._mat4.scale(u,u,[o/I,n/c,1]),a.uniformMatrix4fv(this._textureMatrixLocation,!1,u)}close(){var A;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),this._postProcessing&&this._postProcessing.close(),(A=this.wasm)==null||A.close()}},DtA=class extends Il{constructor(A){super(A,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:A.log,fragmentShaderSource:` +}`);this._prePrograme=this.context.createProgram(d,u),I.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),I.uniform1i(I.getUniformLocation(this._prePrograme,"mask"),1)}!this._enableEffectOptimization||this.wasm.vbMode!==2&&this.wasm.vbMode!==3?this._postProcessing=void 0:pM()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):(n=this._postProcessing)==null||n.init(I,this.positionBuffer,this.texCoordBuffer,4/3),yield this.initVisionTasks(A)})}initVisionTasks(A){return DA(this,null,function*(){if(A.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._visionTaskRegistry.setVideo(this._selfieSegmentationHash,this.image),this._enableFaceCentering)try{this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let e=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!e)return;this._centerFace=new _tA(this.wasm.vbMode,this.image,e,this._visionTaskRegistry,this.context.log)}catch{this.log.error("Face detector model not found. Please redeploy the assets of the npm package.")}}})}onPredict(A){let e=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture)));let o=this.getMaskTexture(A);if(!o)return;let n=o;this._postProcessing&&(this._postProcessing.ratio=this.image.videoWidth/this.image.videoHeight,n=this._postProcessing.postProcessing(o)),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,n||null),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,this._bgTexture||null),e.activeTexture(e.TEXTURE3),e.bindTexture(e.TEXTURE_2D,this._waterMarkTexture||null),this.wasm.vbMode===3&&e.uniform3fv(this._colorLocation,this._color),this.useBufferFrame(),this._segmentationMask=A,this.totalFrames++,this.centerFace(),Eu(this.wasm.rotation)&&this.resize(this.image.height,this.image.width),e.viewport(0,0,e.canvas.width,e.canvas.height),e.drawArrays(e.TRIANGLE_STRIP,0,4),A.close()}getMaskTexture(A){return A.confidenceMasks?A.confidenceMasks[0].getAsWebGLTexture():void 0}onFirstFrame(){this.waitingFirstFrame=!1;let A=this.context.ctx;this.useTexture(),A.texImage2D(A.TEXTURE_2D,0,A.RGBA,A.RGBA,A.UNSIGNED_BYTE,this.image)}render(A){let e=this.context.ctx,{image:o}=this;this.tryVideoFrameCallback();let{videoWidth:n,videoHeight:a}=o;if(Eu(this.wasm.rotation)&&!this._visionTaskRegistry&&([n,a]=[a,n]),n===0||a===0||!this.available)return!1;o.width=n,o.height=a;let I=!1;if(this.totalFrames)this.useTexture(),I=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),I=this._textureValid,this._textureValid=!0}if(this.width===n&&this.height===a&&I?e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,o):(this.resize(n,a),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,o)),this._weixin){if(e.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask){let c=this.getMaskTexture(this._segmentationMask);e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,c||null),e.bindFramebuffer(e.FRAMEBUFFER,this._lastMaskFbo||null)}e.drawArrays(e.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,n,a):e.copyTexImage2D(e.TEXTURE_2D,0,e.RGBA,0,0,n,a,0)}try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let c=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);this.totalFrames===1&&this.context._canvas&&this.resolvePreditReady(),this.onPredict(c)}}catch(c){this._onAbort&&this._onAbort(c)}return this.totalFrames||(e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,this._bgTexture||null),e.activeTexture(e.TEXTURE3),e.bindTexture(e.TEXTURE_2D,this._waterMarkTexture||null),e.drawArrays(e.TRIANGLE_STRIP,0,4)),this._visionTaskRegistry&&this._visionTaskRegistry.resetHashResults(),!1}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let A=this.context.ctx;this._centerFace.aspectRatio=A.canvas.width/A.canvas.height,this._centerFace.actionCentering(this.image);let{current:e,offset:o}=this._centerFace;if(e&&(this.wasm.vbMode===1&&this.drawImage(e.sx,e.sy,e.cropWidth,e.cropHeight),o&&this.wasm.vbMode===2)){if(!this._mat4)return;let n=this._mat4.create(),{scaleRatio:a=1,scaleOffsetX:I=0,scaleOffsetY:c=0}=e;this._mat4.fromTranslation(n,[-o.offsetX/A.canvas.width+I,c,0]),this._mat4.scale(n,n,[a,a,1]),A.uniformMatrix4fv(this._offsetMatrixLocation,!1,n)}}drawImage(A,e,o,n){let a=this.context.ctx;if(!this._mat4)return;let{width:I,height:c}=a.canvas,u=this._mat4.create();this._mat4.fromTranslation(u,[A/I,1-(e+n)/c,0]),this._mat4.scale(u,u,[o/I,n/c,1]),a.uniformMatrix4fv(this._textureMatrixLocation,!1,u)}close(){var A;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),this._postProcessing&&this._postProcessing.close(),(A=this.wasm)==null||A.close()}},LtA=class extends cl{constructor(A){super(A,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:A.log,fragmentShaderSource:` precision highp float; uniform sampler2D ySampler; uniform sampler2D uSampler; @@ -261,29 +261,29 @@ void main() { void main() { gl_Position = vertexPos; textureCoord = texturePos; - }`}),G(this,"yTextureRef"),G(this,"uTextureRef"),G(this,"vTextureRef"),G(this,"Y"),G(this,"U"),G(this,"V"),this.useProgram();let e=this.context.ctx;e.pixelStorei(e.PACK_ALIGNMENT,1),e.pixelStorei(e.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,e){let o=this.context.ctx,n=o.createTexture();return o.bindTexture(o.TEXTURE_2D,n),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),e),n}render(A){let e=this.context.ctx,o=this.width,n=this.height;return this.useProgram(),e.viewport(0,0,o,n),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.yTextureRef),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o,n,e.LUMINANCE,e.UNSIGNED_BYTE,this.Y),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,this.uTextureRef),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o/2,n/2,e.LUMINANCE,e.UNSIGNED_BYTE,this.U),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,this.vTextureRef),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o/2,n/2,e.LUMINANCE,e.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(A,e){super.resize(A,e);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,e,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,e/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,e/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null)}},nz=(A,e)=>{switch(A){case"webCodecs":return e==="videoFrame"?514705:514706;case"wasm":return e==="webgl"?514707:e==="videoFrame"?514708:514709}throw new Error("decoder type not supported")},ytA=0,RtA=class{constructor(A){G(this,"id",ytA++),G(this,"trackDoneOB"),G(this,"startOB"),G(this,"stopOB"),G(this,"decoder"),G(this,"videoContext"),G(this,"gop",0),G(this,"gop_helper",0),G(this,"waitFirstKeyFrame",!0),G(this,"startTimestamp",0),G(this,"startTime",0),G(this,"startPerformanceTime",0),G(this,"inputFrameCount",0),G(this,"decodedFrameCount",0),G(this,"decodeFrameCount",0),G(this,"downgradeLevel",0),G(this,"lastDowngradeTime",0),G(this,"lastFrameDiff",0),G(this,"lastDecodeFrameTimestamp",0),G(this,"config"),G(this,"gop_before_configure",[]),G(this,"videoElement"),G(this,"type","wasm"),G(this,"goodType"),G(this,"renderer","2d"),G(this,"wasmOption"),G(this,"createDecoder"),G(this,"_decodeSink"),G(this,"isReported",!1),G(this,"track"),G(this,"stateChangeOB"),G(this,"failedReason");let{track:e,createDecoder:o}=A;if(this.stateChangeOB=yu(),this.track=e,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=Ln(e.availableState,Uo.OFF),this.stopOB=yu(),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),Jn(this.stateChangeOB,VW((n,a)=>(n!==a&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:n,state:a}),a),"INITIALIZED"),Qc(this.stopOB),Ks()),this.start()}start(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=Jn(this.pipe(this.track),Qc(this.stopOB),qT());Jn(e,Ks(()=>{this.track.stat.framesDecoded++},o=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(o," retryCount: ").concat(A)),ct.addFailedEvent({key:nz(this.type,this.renderer),error:o}),A>4)this.failedReason=o,this.stateChangeOB.next("FAILED"),ct.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")),ct.addSuccessEvent({key:nz(this.type,this.renderer)}),ct.addSuccessEvent({key:514704})})),Jn(e,LM(1),Ks(()=>{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"&&!Em()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var o,n;if(this.failedReason)return;this.inputFrameCount++;let a=new Uint8Array(A.data);if((I=a)[0]!==0||I[1]!==0||I[2]!==0||I[3]!==1||a.length<5)return this.stateChangeOB.next("FAILED"),this.close("not h26x frame ".concat(a.subarray(0,5))),A;var I;let c=!1;switch(31&a[4]){case 5:case 7:c=!0}if(((o=this.decoder)==null?void 0:o.state)!=="configured")return this.track.log.debug("not configured ".concat(this.inputFrameCount)),c&&(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&&!e&&(this.gop_before_configure.forEach(d=>this.decode(d,!0)),this.gop_before_configure=[]);let{timestamp:u}=A;if(c?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!c)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount," ").concat(a.subarray(0,5).join(" ")));this.waitFirstKeyFrame=!1,this.startTimestamp=u,this.startTime=Date.now(),this.startPerformanceTime=ki()}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(u," ").concat((n=A.getMetadata)==null?void 0:n.call(A).rtpTimestamp)),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=u,void this.decoder.decode({data:A.data,type:A.type,timestamp:this.lastDecodeFrameTimestamp})}return A}checkDowngradeByFrameDiff(){let A=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=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(e,", lastFrameDiff: ").concat(this.lastFrameDiff)),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(A){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-A>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug("downgrade level ".concat(e," to ").concat(this.downgradeLevel))}pipe(A){return e=>DA(this,null,function*(){this._decodeSink=e;let o,n=A.mediaTrack;e.defer(()=>{var c;n&&(A.player.setCanvas(),A.setInputMediaStreamTrack(n)),o?.close(),(c=this.videoContext)==null||c.destroy(),delete this._decodeSink});let{renderer:a,type:I}=this;A.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(I){case"wasm":o=this.createDecoder(I,this.wasmOption);break;case"webCodecs":o=this.createDecoder(I);break;default:throw new Error("not supported yet")}let c=0;if(o.on("videoFrame",u=>{this.decodedFrameCount++,c++,(c<=10||c%500==0)&&A.log.debug("frame ".concat(c," ").concat(this.decodedFrameCount,"/").concat(this.decodeFrameCount," decoded ").concat(u.timestamp)),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(u.timestamp)),e.next(u)}),o.on("error",u=>{A.log.error(u),e.error(I==="webCodecs"?4:8)}),yield o.initialize(this.videoElement),!this._decodeSink)return;if(o.configure(this.config),I==="wasm"&&a==="webgl"){this.videoContext=new aC({frameRate:15,logger:A.log,name:A.userId}),this.videoContext.create(),this.videoContext.on(aC.UNAVAILABLE,d=>{A.log.error(d),e.error(7)});let u=new DtA(this.videoContext);o.on("videoCodecInfo",d=>u.resize(d.width,d.height)),o.on("videoFrame",d=>{({y:u.Y,u:u.U,v:u.V}=d),this.downgradeLevel===1?this.decodedFrameCount%2==0&&u.render(this.decodedFrameCount):u.render(this.decodedFrameCount)}),A.source=u,A.player.setCanvas(this.videoContext._canvas,2)}else if(a==="videoFrame"){A.player.setCanvas();let u=new MediaStreamTrackGenerator({kind:"video"}),d=u.writable.getWriter();A.setInputMediaStreamTrack(u),o.on("videoFrame",R=>d.write(R))}else{this.videoContext=new Mu({frameRate:15,logger:A.log,name:A.userId}),this.videoContext.create({alpha:!1});let u=this.videoContext.createVideoImageSource();o.on("videoFrame",R=>{try{u.image=R,u.update()}catch(k){delete this.goodType,A.log.error(k),e.error(11)}});let d=new bq(this.videoContext,{name:"remotePlayer",logger:A.log});u.connect(d),A.source=u,A.player.setCanvas(this.videoContext._canvas,2)}this.decoder=o}catch(c){A.log.error(c),e.error(I==="webCodecs"?2:6)}})}},az=Promise.resolve(),sz=class extends ptA.EventEmitter{constructor(A){super(),this.room=A,G(this,"videoContext"),G(this,"_glVideoContext"),G(this,"_2dVideoContext"),G(this,"destination"),G(this,"smallVideoContext"),G(this,"smallDestination"),G(this,"smallTrackSource"),G(this,"smallImageSource"),G(this,"_isMirror",!1),G(this,"_rotation",0),G(this,"cameraTrack"),G(this,"cameraNode"),G(this,"transformNode"),G(this,"mixNode"),G(this,"screenTrack"),G(this,"screenNode"),G(this,"selfModel",!1),G(this,"blurRadius",3),G(this,"arTrack"),G(this,"_enableFaceCentering",!1),G(this,"_enableEffectOptimization",!1),G(this,"onAbort"),G(this,"_color"),G(this,"Wasm"),G(this,"waterMarkNode"),G(this,"_waterMarkOption"),G(this,"watermarkImageList",[]),G(this,"_beautyParams"),G(this,"isUsingArTrack",!1),G(this,"mixTrack"),G(this,"_isMixScreen",!1),G(this,"_virtualBackground"),G(this,"_virtualBackgroundAbortCallback"),G(this,"virtualBackgroundInstance"),G(this,"_bgAssetPath"),G(this,"log"),G(this,"_mat4"),G(this,"_postProcessing"),G(this,"_checkId",0),G(this,"_use2d",!1),G(this,"_autoSwitchRenderMode",!0),G(this,"encodePipeline",[]),G(this,"decodePipeline",[]),G(this,"updated",az),G(this,"_updateFlag",!1),this.log=nA.createLogger({parent:A?.getLogger(),id:"vm",userId:A?.userId,sdkAppId:A?.sdkAppId}),this.smallVideoContext=new Mu({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 e=A==="2d";this._use2d!==e&&(this._use2d=e,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get cameraResolution(){var A;let{width:e,height:o}=((A=this.cameraTrack)==null?void 0:A.settings)||{};return gu(this._rotation)?{width:o,height:e}:{width:e,height:o}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new Mu({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 aC({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(OO<=22),this._glVideoContext.on(aC.UNAVAILABLE,A=>{var e;this.emit("error",A),this.log.warn("video context unavailable",A),(e=this._virtualBackgroundAbortCallback)==null||e.call(this,A),this.update().catch(o=>{this.log.error(o)})})}catch(A){this.emit("error",A)}}initVirtualBackground(A,e,o){this.onAbort=A,this._mat4=e,this._postProcessing=o}enablePrintDetail(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;this._checkId=nn.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:A})}destroy(){var A,e;(A=this._2dVideoContext)==null||A.destroy(),(e=this._glVideoContext)==null||e.destroy(),this.smallVideoContext.destroy(),nn.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(TQ||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(){let A=arguments.length>1?arguments[1]:void 0,e=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"videoCtxGl")==="videoCtxGl"?512700:512701;A?ct.addFailedEvent({key:e,error:A}):ct.addSuccessEvent({key:e})}checkOrCreateVideoContext(){let A=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let e=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&A===this._hasVirtualBg)this.clear();else{if(!e||!this._use2d)return!0;this.clear()}}else{if(this._glVideoContext=new aC({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,e){if(this.smallMode!=="api")if(A){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new ZAA(this.smallVideoContext,A,this.log),this.smallVideoContext.on(aC.UNAVAILABLE,o=>{this.log.warn("small video context lost",o)})}if(this.smallVideoContext.frameRate=A.frameRate,this.smallDestination.resolution=A,e)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.resize(e.width,e.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:n}=this.cameraTrack.settings;this.smallTrackSource.resize(o,n),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(A){var e,o;try{let n=this.cameraTrack,{small:a,player:I}=n;TQ&&I.setCanvas(A);let c=A&&((e=this.destination)==null?void 0:e.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),c=this.arTrack),this.log.info("set main output ".concat(c?c.label:"no output track")),this.setSmallVideo(a,A),S.emit(K.LOCAL_VIDEO_TRACK_PREPROCESSED,{mediaTrack:c,profile:(o=this.cameraTrack)==null?void 0:o.profile,room:this.room}),n.setOutputMediaStreamTrack(c)}catch(n){this.log.error("set main output failed",n)}}update(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return DA(this,null,function*(){var e;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:o,profile:n}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(Il.RENDER,a=>{var I;(I=this.cameraTrack)==null||I.emit("render",a)})),al===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof FM?(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 FM?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 zAA(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(Il.RENDER,u=>{var d;(d=this.cameraTrack)==null||d.emit("render",u)}));let{width:a,height:I}=this.cameraResolution,c=yield this.getWatermarkImage(a,I);this._waterMarkOption={x:0,y:0,width:c.width,height:c.height,image:c},this.cameraNode=new mtA(this.videoContext,{input:this.initialTrack,width:a,height:I,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=n.frameRate,this._use2d){let a=this.cameraNode;if(a.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new Zh(this.videoContext,this.log,this._isMirror,this._rotation),a=a.connect(this.transformNode),a.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 o4(this.videoContext,this.log),a.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:I,height:c}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(I,c),I&&c&&this.waterMarkNode.resize(I,c)}(e=this.waterMarkNode)==null||e.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})),a=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))}a.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 e,o,n,a,I;if(A instanceof Nm)return this.log.info("change screen input",(e=A.mediaTrack)==null?void 0:e.label),this.setScreenTrack(A);if(A instanceof Ru)return this.log.info("change video input",(o=A.mediaTrack)==null?void 0:o.label),this.setCameraTrack(A);if(A instanceof tG){this.log.info("change remote input",(n=A.mediaTrack)==null?void 0:n.label);let c=A.mediaTrack;return A.setOutputMediaStreamTrack(c)}if(A instanceof Fq)return this.log.info("change mix input",(a=A.outMediaTrack)==null?void 0:a.label),this.setMixTrack(A);this.log.warn("change unknown input",(I=A.mediaTrack)==null?void 0:I.label)}removeInput(A){var e;A instanceof Nm?((e=this.screenNode)==null||e.close(),delete this.screenNode,delete this.screenTrack,this.update()):A instanceof Ru?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 tG?A.source&&A.source.context.destroy():A instanceof Fq&&(delete this.mixTrack,this.update())}setMixTrack(A){this.mixTrack=A}setCameraTrack(A){return this.cameraTrack=A,this.update(!0)}setScreenTrack(A){return DA(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,e){return DA(this,null,function*(){let o=document.createElement("canvas");e&&A&&(o.height=e,o.width=A);let n=o.getContext("2d");if(!n)throw new Ct({code:Ge.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((a,I)=>a.zIndex-I.zIndex),this.watermarkImageList.forEach(a=>{let{image:I,x:c,y:u,width:d,height:R,fillVideo:k}=a,_=k&&A||d,Z=k&&e||R,iA=k?0:c,cA=k?0:u;n.drawImage(I,iA,cA,_,Z)}),Vf(o.toDataURL())})}pushWaterMarkImageList(A){let{type:e}=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)||((e==="mute"||e==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(o=>o.type!==e)),this.watermarkImageList.push(A))}setBeautyParams(A){return DA(this,null,function*(){this._beautyParams=A,this.update()})}stopBeauty(){return DA(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(A){return DA(this,null,function*(){let e;try{e=yield Vf(A?.imageElement||A.imageUrl)}catch{throw new Ct({code:Ge.INVALID_PARAMETER,message:"load image failed, url: ".concat(A.imageUrl)})}let{x:o=0,y:n=0,width:a=e.width,height:I=e.height,type:c="watermark",zIndex:u=2,fillVideo:d=!1}=A;this.watermarkImageList.some(R=>R.type===c)?(this.watermarkImageList=this.watermarkImageList.filter(R=>R.type!==c),this.pushWaterMarkImageList({x:o,y:n,width:a,height:I,image:e,zIndex:u,type:c,imageUrl:A.imageUrl,fillVideo:d}),e=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(e.width,e.height),this.waterMarkNode.image=e):this.update()):(this.pushWaterMarkImageList({x:o,y:n,width:a,height:I,image:e,zIndex:u,type:c,imageUrl:A.imageUrl,fillVideo:d}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(R,k)=>R==="imageUrl"?void 0:k))})}deleteWatermark(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"watermark";return DA(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(e=>e.type!==A),this.log.info("delete watermark",A,JSON.stringify(this.watermarkImageList,(e,o)=>e==="imageUrl"?void 0:o)),yield this.freshWatermark()})}freshWatermark(){return DA(this,null,function*(){var A;(A=this.waterMarkNode)==null||A.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:e,height:o}=this.cameraResolution,n=yield this.getWatermarkImage(e,o);this._waterMarkOption={x:0,y:0,width:n.width,height:n.height,image:n},this.update()})}setVirtualBackground(A){return DA(this,null,function*(){var e,o,n;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 Vf(A.imageUrl):(this.blurRadius=A.blurLevel||this.blurRadius||3,this._virtualBackground=A.type),this._enableFaceCentering=(e=A.enableFaceCentering)!=null?e:this._enableFaceCentering,this._enableEffectOptimization=(o=A.enableEffectOptimization)!=null?o:this._enableEffectOptimization,this._color=(n=A.color)!=null?n:[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 Ct({code:Ge.INVALID_OPERATION,message:"webgl context create failed, ".concat(this._glVideoContext.error)})})}get mixScreen(){return this._isMixScreen}set mixScreen(A){var e;this._isMixScreen=A,this._isMixScreen||((e=this.screenNode)==null||e.close(),delete this.screenNode),this.update()}set mirror(A){var e;this._isMirror!==A&&(this._isMirror=A,this._isTransform||((e=this.transformNode)==null||e.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(A){var e;this._rotation!==A&&(this._rotation=A,this._isTransform||((e=this.transformNode)==null||e.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(A){this.arTrack=A,this.isUsingArTrack=!0,this.update()}updateAr(){return DA(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 RtA(A)}clear(){var A,e;(A=this.videoContext)==null||A.disconnect(),(e=this.destination)==null||e.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor(A){let{processor:e,type:o}=A;var n;this.encodePipeline.includes(e)||(this.encodePipeline[o]=e,(n=this.room)==null||n.enableInsertableStreams())}addDecodeProcessor(A){let{processor:e,type:o}=A;var n;this.decodePipeline.includes(e)||(this.decodePipeline[o]=e,(n=this.room)==null||n.enableInsertableStreams())}removeEncodeProcessor(A){let{type:e}=A;this.encodePipeline[e]=void 0}removeDecodeProcessor(A){let{type:e}=A;this.decodePipeline[e]=void 0}};vt([wW(function(A){this.log.error("update failed",A)}),Dn(A=>function(){for(var e=arguments.length,o=new Array(e),n=0;n{A.apply(this,o).then(a,I),setTimeout(I,5e3,new Ct({code:Ge.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],sz.prototype,"update");var MtA=0,wtA=class extends Uo{constructor(A){super("room"),G(this,"seq",++MtA),G(this,"sdkAppId"),G(this,"userId"),G(this,"userSig"),G(this,"privateMapKey"),G(this,"latencyLevel"),G(this,"tinyId"),G(this,"scene"),G(this,"roomId"),G(this,"useStringRoomId"),G(this,"role","anchor"),G(this,"joinParams",null),G(this,"localPublishFlag",0),G(this,"localTracks",new Set),G(this,"enableAutoPlayDialog",!0),G(this,"autoReceiveAudio",!0),G(this,"autoReceiveVideo",!0),G(this,"proxy_ws"),G(this,"proxy_wt"),G(this,"proxy_unified"),G(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}}),G(this,"keyPointManager"),G(this,"audioManager"),G(this,"videoManager"),G(this,"callDurationCalculator"),G(this,"badCaseDetector"),G(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),G(this,"videoDecodeFallbackType"),G(this,"smallMode","canvas"),G(this,"prelinkPromise",null),G(this,"enableChorus",!1),G(this,"_isUsingCachedSchedule",!1),G(this,"_log"),G(this,"_joinedTimestamp",0),G(this,"_sdkType"),G(this,"heartbeatReport"),G(this,"heartbeatCount",0),G(this,"quality"),G(this,"enableSEI"),G(this,"isDestroyed",!1),this._log=nA.createLogger({parent:A.logger,id:"r".concat(this.seq)}),this.useStringRoomId=!!A.useStringRoomId,rn(A.autoReceiveAudio)&&(this.autoReceiveAudio=A.autoReceiveAudio),rn(A.autoReceiveVideo)&&(this.autoReceiveVideo=A.autoReceiveVideo),rn(A.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=A.enableAutoPlayDialog),this._sdkType=A.sdkType,this.keyPointManager=new utA({room:this,frameWorkType:A.frameWorkType,component:A.component,language:A.language}),this.callDurationCalculator=new QtA({room:this}),this.badCaseDetector=new htA({room:this}),this.audioManager=new ieA(this),this.videoManager=new sz(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(e=>{if(e.isPublished||e.isPublishing)switch(e.mediaType){case 1:A.audio=!0;break;case 4:A.bigVideo=!0,A.smallVideo=e.hasSmall;break;case 2:A.auxVideo=!0}}),A}get muteState(){var A,e,o;return{audio:!((A=this.localMainAudioTrack)==null||!A.muted),bigVideo:!((e=this.localMainVideoTrack)==null||!e.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 DA(this,null,function*(){return this.publish(A)})}removeTrack(A){return DA(this,null,function*(){return this.unpublish(A)})}replaceTrack(A){return DA(this,null,function*(){})}setEncodedDataProcessingListener(A){throw new Error("Method not implemented.")}enableAIVoice(A){throw new Error("Method not implemented.")}setProxyServer(A){if(Sr(A))/^wss?:\/\//i.test(A)?this.proxy_ws=A:/^https?:\/\//i.test(A)&&(this.proxy_wt=A);else if(Cc(A)){let{websocketProxy:e,webtransportProxy:o,loggerProxy:n,scheduleProxy:a,unifiedProxy:I}=A;this.proxy_ws=e,this.proxy_wt=o,this.proxy_unified=I,I?(Pq([I,I]),wf("https://".concat(I))):(n&&wf(n),a&&Pq(a))}S.once(K.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:jQ.main,sched_back_domain:jQ.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return DA(this,null,function*(){let A={};return this.remotePublishedUserMap.forEach(e=>{A[e.userId]=e.remoteAudioTrack.stat}),A})}getTransportStats(){return DA(this,null,function*(){var A;let e={rtt:((A=this.quality)==null?void 0:A.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let o of this.quality.downlinkInfo)e.downlinksRTT[o.userId]=o.rtt;return e})}getRemoteVideoStats(){return DA(this,arguments,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"main";return function*(){let o={};return A.remotePublishedUserMap.forEach(n=>{let a=e==="auxiliary"?n.remoteAuxiliaryTrack:n.remoteVideoTrack;o[n.userId]=a.stat}),o}()})}checkDestroy(){if(this.isDestroyed)throw new Ct({code:Ge.INVALID_OPERATION,message:Wi({key:Mi.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(ts.INVALID_DESTROY),new Ct({code:Ge.INVALID_OPERATION,message:Wi({key:Mi.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,S.emit(K.ROOM_DESTROY,{room:this})}schedule(A,e){return DA(this,null,function*(){var o,n,a,I;let c=ki();try{let{isCached:u,result:d,detailCost:R}=yield m4({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?A.strRoomId:A.roomId,useStringRoomId:this.useStringRoomId,version:il,userSig:this.userSig,role:this.scene==="live"?A.role:void 0,frameWorkType:e,latencyLevel:A.latencyLevel});this._isUsingCachedSchedule=u,this._log.info("schedule cache:".concat(+u," ").concat(nl(d,{keysToExclude:["username","credential"]}))),u&&S.once(K.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=bt(bt({},this.scheduleResult),d),hr((o=d.config)==null?void 0:o.retryCount)&&bR(d.config.retryCount),Sr((n=d.config)==null?void 0:n.loggerDomain)&&wf(d.config.loggerDomain),this.videoDecodeFallbackType=((a=d.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((I=d.config)==null?void 0:I.smallMode)||this.smallMode,S.emit(K.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:R}),ct.addSuccessEvent({key:521700,cost:ki()-c})}catch(u){throw ct.addFailedEvent({key:521700,error:u}),u}})}sendAbilityStatus(A){}enableInsertableStreams(){return Promise.resolve()}switchRoom(A){return Promise.reject()}isSwitchRoomSupported(){return!1}prelink(A,e,o,n,a,I){return DA(this,null,function*(){return Promise.resolve()})}closePrelink(){return DA(this,null,function*(){return Promise.resolve()})}},StA=es(hg()),gz=es(cN());function Iz(A){var e;let o=[];for(let n=0;nI.payload===A.rtp[n].payload)[0];o.push({payload:A.rtp[n].payload,codec:A.rtp[n].codec,fmtp:a?a.config:"",rate:A.rtp[n].rate,rtx:((e=A.rtp[n+1])==null?void 0:e.codec)==="rtx"?A.rtp[n+1].payload:0,rtcpfb:(A?.rtcpFb||[]).filter(I=>I.payload===A.rtp[n].payload).map(I=>{let{type:c,subtype:u}=I;return{id:c,params:u?[u]:[]}})})}return o}var vtA=(A,e,o)=>DA(null,null,function*(){var n;let a=rs(A),I={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:o};I.ice.ufrag=String(a.media[0].iceUfrag),I.ice.password=a.media[0].icePwd||"",a.fingerprint&&(I.dtls.hash=a.fingerprint.type,I.dtls.fingerprint=a.fingerprint.hash,I.dtls.setup=a.setup||""),a.media[0].fingerprint&&(I.dtls.hash=a.media[0].fingerprint.type,I.dtls.fingerprint=a.media[0].fingerprint.hash),I.dtls.setup=a.media[0].setup||"";let c=a.media[0],u=a.media[1];c.ext&&(I.audio.extensions=c.ext.map(R=>({id:R.value,uri:R.uri}))),u.ext&&(I.video.extensions=u.ext.map(R=>({id:R.value,uri:R.uri})));for(let R of c.rtp){if(R.codec!=="opus")continue;let k=c.fmtp.find(Z=>Z.payload===R.payload);if(!k)continue;let _={codec:R.codec,fmtp:k.config,payload:k.payload,rate:R.rate,channels:R.encoding,rtcpfb:[],rtx:0};(n=c.rtcpFb)==null||n.forEach(Z=>{let{payload:iA,type:cA,subtype:TA}=Z;if(iA===_.payload){let JA={id:cA,params:[]};TA&&JA.params.push(TA),_.rtcpfb.push(JA)}}),I.audio.codecs.push(_);break}let d=["h264","vp8","h265"];return e&&d.shift(),I.video.codecs=[...Iz(u)].filter(R=>d.includes(R.codec.toLocaleLowerCase())),I.video.decoders=(yield function(){return DA(this,null,function*(){let R=new RTCPeerConnection;R.addTransceiver(fA.VIDEO,{direction:fA.TRANSCEIVER_DIRECTION_RECVONLY});let k=yield R.createOffer();if(!k.sdp)return[];let _=Iz(rs(k.sdp).media[0]);return R.close(),_})}()).filter(R=>["h264","vp8","h265"].includes(R.codec.toLocaleLowerCase())),I}),cz=(A,e)=>{let o=(A||"").trim(),n=(e||"").trim(),a="profile-level-id",I="".concat(a,"=[0-9a-fA-F]{6}");if(new RegExp(I).test(o)){let u=new RegExp(I,"g");return o.replace(u,"".concat(a,"=").concat(n))}if(!o)return"".concat(a,"=").concat(n);let c=o.endsWith(";")?"":";";return"".concat(o).concat(c).concat(a,"=").concat(n)},NtA=A=>{let{serverAbility:e,clientAbility:o,offerSDP:n,enableCustomMessage:a,profileLevelIdConfig:I}=A,c=rs(n),u={extmapAllowMixed:"extmap-allow-mixed",groups:c.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},d={candidates:e.candidates.map(k=>({component:1,foundation:"1",generation:0,ip:k.ip,port:k.port,priority:k.priority,transport:k.foundation,type:k.type})),connection:{version:4,ip:"0.0.0.0"},direction:fA.TRANSCEIVER_DIRECTION_RECVONLY,ext:e.audio.extensions.map(k=>({value:k.id,uri:k.uri})),fingerprint:{type:e.dtls.hash,hash:e.dtls.fingerprint},fmtp:[{payload:e.audio.codecs[0].payload,config:e.audio.codecs[0].fmtp}],icePwd:e.ice.password,iceUfrag:e.ice.ufrag,mid:"0",payloads:String(e.audio.codecs[0].payload),port:c.media[0].port,protocol:c.media[0].protocol,type:fA.AUDIO,setup:e.dtls.setup,rtcpFb:e.audio.codecs[0].rtcpfb.map(k=>({payload:e.audio.codecs[0].payload,type:k.id,subtype:k.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:e.audio.codecs[0].payload,codec:e.audio.codecs[0].codec,rate:e.audio.codecs[0].rate,encoding:e.audio.codecs[0].channels}]};u.media.push(d);let R=[I?.big,I?.small,I?.aux];return[1,2,3].forEach((k,_)=>{u.media.push(Ez({mid:k,serverAbility:e,clientAbility:o,parsedOffer:c,profileLevelId:R[_]}))}),a&&u.media.push(c.media.find(k=>k.mid==="dc")),$h(u)},Ez=A=>{let{mid:e,serverAbility:o,clientAbility:n,parsedOffer:a,isDownlink:I=!1,profileLevelId:c}=A,u={candidates:o.candidates.map(d=>({component:1,foundation:"1",generation:0,ip:d.ip,port:d.port,priority:d.priority,transport:d.foundation,type:d.type})),connection:{version:4,ip:"0.0.0.0"},direction:fA.TRANSCEIVER_DIRECTION_RECVONLY,ext:o.video.extensions.map(d=>({value:d.id,uri:d.uri})),fingerprint:{type:o.dtls.hash,hash:o.dtls.fingerprint},fmtp:[],icePwd:o.ice.password,iceUfrag:o.ice.ufrag,mid:String(e),payloads:"",port:a.media[0].port,protocol:a.media[0].protocol,type:fA.VIDEO,setup:o.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(I){let d=o.video.decoders;(!d||d.length===0)&&(d=o.video.codecs),(!d||d.length===0)&&(d=n.video.decoders),d.forEach(R=>{HM(u,R)})}else{let d;d=o.useH265?o.video.codecs.findIndex(k=>k.codec.toLowerCase()==="h265"):o.video.codecs.findIndex(k=>k.codec.toLowerCase()===(o.useVp8?"vp8":"h264"));let R=o.video.codecs[d]||n.video.codecs[0];HM(u,R)}if(!I&&c){let d=u.fmtp,R=u.rtp.find(k=>{var _;return((_=k.codec)==null?void 0:_.toLowerCase())==="h264"});if(R){let k=d.find(_=>String(_.payload)===String(R.payload));k&&(k.config=cz(k.config,c))}}return u},HM=(A,e)=>{A.payloads="".concat(A.payloads," ").concat(e.payload).trim(),A.fmtp.push({payload:e.payload,config:e.fmtp}),A.rtcpFb=[...A.rtcpFb||[],...e.rtcpfb.map(o=>({payload:e.payload,type:o.id,subtype:o.params[0]}))],A.rtp.push({payload:e.payload,codec:e.codec.toUpperCase(),rate:e.rate}),e.rtx&&(A.payloads="".concat(A.payloads," ").concat(e.rtx),A.fmtp.push({payload:e.rtx,config:"apt=".concat(e.payload)}),A.rtp.push({payload:e.rtx,codec:"rtx",rate:e.rate}))},TtA=(A,e,o)=>{let n=gz.default.parse(A);return n.media.forEach((a,I)=>{var c;if((a.type===fA.AUDIO||a.type===fA.VIDEO)&&(function(u){if(!u.rtcpFb)return;let d=[];u.rtcpFb.forEach((R,k)=>{var _;d.push(R),u.rtcpFb&&((_=u.rtcpFb[k+1])==null?void 0:_.payload)!==R.payload&&R.type!=="rrtr"&&d.push({payload:R.payload,type:"rrtr"})}),u.rtcpFb=d}(a),function(u){u.type===fA.VIDEO&&u.fmtp&&u.fmtp.forEach(d=>{d.config.includes("apt")||(d.config+=";sps-pps-idr-in-keyframe=1")})}(a),function(u){u.type===fA.AUDIO&&u.fmtp&&u.fmtp.forEach(d=>{d.config+=";sprop-stereo=1;stereo=1"})}(a),function(u){let d=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"]);u.ext&&(u.ext=u.ext.filter(R=>!d.has(R.uri)))}(a),a.type===fA.VIDEO)){if(I<4)a.payloads="",a.fmtp=[],a.rtp=[],a.rtcpFb=[],e.video.codecs.forEach(u=>HM(a,u));else if(o){a.payloads="",a.fmtp=[],a.rtp=[],a.rtcpFb=[];let u=o.video.decoders;(!u||u.length===0)&&(u=o.video.codecs),(!u||u.length===0)&&(u=e.video.decoders),u.forEach(d=>HM(a,d))}}(c=a.payloads)!=null&&c.includes("datachannel")&&n.groups&&a.mid&&(n.groups[0].mids=n.groups[0].mids.replace(a.mid,"dc"),a.mid="dc")}),gz.default.write(n)};function EK(A){var e,o;let n=/profile-level-id=([0-9a-fA-F]{6})/.exec(A);return(o=(e=n?.[1])==null?void 0:e.toLowerCase())!=null?o:null}function lK(A){let e=A.toLowerCase();if(!/^[0-9a-f]{6}$/.test(e))return"unknown";let o=parseInt(e.slice(0,2),16);return o===66?"baseline":o===77?"main":o===100?"high":"unknown"}function lz(A,e){if(!e)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 n of e.video.codecs){let a=EK(n.fmtp);if(a&&lK(a)===o)return a}return""}var GtA=es(hg()),Cz=class extends GtA.EventEmitter{constructor(A){super(),this.room=A,G(this,"mainFpsHealth",1),G(this,"mainBitrateHealth",1),G(this,"badMainBitrateHealthCount",0),G(this,"lastEmitBadHealthTime",0),G(this,"log"),!ra&&Bc&&S.on("262",this.onVideoCodecChanged,this),this.log=A.getLogger().createChild({id:"h-d"})}onVideoCodecChanged(A){let{remoteUserId:e,streamType:o,isHWCodec:n,codec:a}=A;if(!e&&o!==7&&a==="h264"){if(!n)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(e=>{if(e.uint32_video_enc_fps&&e.uint32_video_capture_fps){let o=e.uint32_video_enc_fps/e.uint32_video_capture_fps;e.uint32_video_stream_type===2&&(this.mainFpsHealth=o)}if(e.uint32_video_codec_bitrate&&e.uint32_video_stream_type===2){let{localMainVideoTrack:o}=this.room;o&&(this.mainBitrateHealth=e.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(){S.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};G(Cz,"EVENT_BAD_HEALTH","bad_health");var ktA=Cz,VM=(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))(VM||{}),_tA=1,Ap=class extends StA.default{constructor(A){let{signalChannel:e,room:o,enableDataChannel:n}=A;super(),G(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),G(this,"isDestroyed",!1),G(this,"currentState","DISCONNECTED"),G(this,"_room"),G(this,"_signalChannel"),G(this,"_peerConnection",null),G(this,"_datachannel",null),G(this,"_enableDataChannel"),G(this,"_log"),G(this,"_downlinkMIDMap",new Map),G(this,"_downlinkMIDUserIDMap",new Map),G(this,"_reconnectionTimer",-1),G(this,"reconnectionCount",0),G(this,"clientAbility"),G(this,"_serverAbility",null),G(this,"addDownlinkQueue",new Set),G(this,"removeDownlinkQueue",new Set),G(this,"_parsedAnswer",null),G(this,"_updateSDPPromise",null),G(this,"_waitForPCConnectedPromise"),G(this,"clearWaitForConnectedPromise"),G(this,"clearConnectTimeout"),G(this,"_isSDPLogged",!1),G(this,"enableInsertableStreams",!1),G(this,"insertableStreamsAbortMap",new Map),G(this,"receiverRemoteTrackMap",new WeakMap),G(this,"scriptTransformWorker"),G(this,"_isRelayTried",!1),G(this,"_rttOverCount",0),G(this,"originOffer",null),G(this,"autoSubscribedSsrcGroups",new Map),G(this,"autoSubscribedUserMap",new Map),G(this,"_h265DecodeFailed",!1),this._room=o,this._enableDataChannel=n,this._signalChannel=e,this._log=nA.createLogger({parent:this._room.getLogger(),id:"spc".concat(_tA++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(xQ?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(e=>e.codec.toLowerCase()==="h264")),A}addAbortController(A,e){var o;(o=this.insertableStreamsAbortMap.get(A))==null||o.abort("destroy"),this.insertableStreamsAbortMap.set(A,e)}get isVP8EncodeSupported(){let A=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(A=A&&this._serverAbility.video.codecs.find(e=>e.codec.toLowerCase()==="vp8")),A}get isH265EncodeSupported(){let A=this._room.checkSystemResult.detail.isH265EncodeSupported;return this._serverAbility&&(A=A&&!!this._serverAbility.video.codecs.find(e=>e.codec.toLowerCase()==="h265")),A}get videoCodec(){var A,e,o;let n=(A=this._parsedAnswer)==null?void 0:A.media[1].rtp.find(a=>["h264","vp8","h265"].includes(a.codec.toLowerCase()));return n?n.codec.toLowerCase():(e=this._serverAbility)!=null&&e.useH265?"h265":(o=this._serverAbility)!=null&&o.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var A,e,o;return(A=this._serverAbility)!=null&&A.useH265&&(e=this._serverAbility)!=null&&e.video.decoders.find(n=>n.codec.toLowerCase()==="h265")&&!this._h265DecodeFailed?"h265":(o=this._serverAbility)!=null&&o.video.decoders.find(n=>n.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(e=>e.fmtp.includes(A))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(A=>{let e=rs(A),o={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return e.media.forEach((n,a)=>{var I;if(n.ssrcs&&!Ee(n.ssrcs[0].id)){let c=Number(n.ssrcs[0].id),u=Number((I=n.ssrcs.filter(d=>d.attribute==="cname")[1])==null?void 0:I.id);switch(a){case 0:o.audioSsrc=c;break;case 1:o.bigVideoSsrc=c,o.bigVideoRtxSsrc=u;break;case 2:o.smallVideoSsrc=c,o.smallVideoRtxSsrc=u;break;case 3:o.auxVideoSsrc=c,o.auxVideoRtxSsrc=u}}}),o})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(A){}initScriptTransformWorker(){MM&&(this.scriptTransformWorker=k4({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 e;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"},n=(e=this._peerConnection)==null?void 0:e.getConfiguration().encodedInsertableStreams;return NO(n)&&(o.encodedInsertableStreams=n),this._log.debug("getPeerConnectionConfig",JSON.stringify(o)),o}initialize(A){return DA(this,null,function*(){var e;let o;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(A)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let n=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(n)),n==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():n==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),ct.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):n==="failed"&&ct.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var n;let a=((n=this._peerConnection)==null?void 0:n.signalingState)||"";this._log[a==="closed"?"debug":"info"]("signaling state: ".concat(a))},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=n=>this.emit("track",n),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=n=>{let a=new LtA(n.data);this.emit("data_channel_msg",{data:a})},this._datachannel.onerror=n=>{this._log.warn("datachannel error",n)}),this._peerConnection.addTransceiver(fA.AUDIO,{direction:fA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(fA.VIDEO,{direction:fA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(fA.VIDEO,{direction:fA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(fA.VIDEO,{direction:fA.TRANSCEIVER_DIRECTION_SENDONLY}),o=yield this._peerConnection.createOffer(),this.clientAbility=yield vtA(o.sdp,((e=this._room.scheduleResult.config)==null?void 0:e.remove264FromSDP)||!1,this._enableDataChannel),this.originOffer=o,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:n}=this;n&&(this._log.debug("dtls state: ".concat(n.state)),n.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():n.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),ct.addSuccessEvent({key:521707}),this.clientAbility}catch(n){throw ct.addFailedEvent({key:521707,error:n}),this._log.error("initialize failed ".concat(n,` -offer: `).concat(o?.sdp)),n}})}setIceServers(A){return DA(this,null,function*(){var e;if(this._peerConnection&&A.length!==0)try{if(this._log.info("setIceServers",JSON.stringify(A,(o,n)=>o==="username"||o==="credential"?"hided":n)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(A)),(e=this._peerConnection)!=null&&e.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(e=>{let o=e.getParameters();o.encodings[0]&&(o.encodings[0].priority=A,o.encodings[0].networkPriority=A,e.setParameters(o).catch(n=>{this._log.warn("setPriority error ",n)}))})}catch(e){this._log.warn("setPriority error ",e)}}connect(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return DA(this,null,function*(){var o,n,a;try{if(this.currentState==="CONNECTED")return;((o=this._peerConnection)==null||!o.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let I=ki(),c=this.getProfileLevelIdConfig(),u={type:"answer",sdp:NtA({serverAbility:A,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableDataChannel,profileLevelIdConfig:c})};this._serverAbility=A,yield this.setAnswer(u),yield this.waitForPeerConnectionConnected(),this._room.firewallDetector.resetTimeoutCount();let d=((n=this._room.scheduleResult.config)==null?void 0:n.priority)||((a=this._room.joinParams)==null?void 0:a.priority)||new URLSearchParams(location.search).get("priority");d&&this.setPriority(d),e||ct.addSuccessEvent({key:521703,cost:ki()-I})}catch(I){let c=I instanceof Ct&&I.code===Ge.API_CALL_ABORTED;throw c||this._log.error("connect failed: ".concat(I),A),this.reset(),!c&&!this.isReconnecting&&!this.isDestroyed&&(ct.addFailedEvent({key:521703,error:I}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),I}})}reconnect(){return DA(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(gG,this.reconnect,this);try{this.reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this.reconnectionCount,"]")),this.reset();let A=this._signalChannel.getBackupRelayIpPair(),e=yield this.initialize(this._room.getIceServers(A!=null&&A.iceServer?[A.iceServer]:[])),o=bt({ability:e},A),n=yield this._signalChannel.sendWaitForResponse({command:etA,responseCommand:io.REBUILD_PEER_CONNECTION_RES,data:o,enableLog:!1});if(n.data.code!==0)throw new Ct({code:n.data.code,message:n.data.message});yield this.connect(n.data.data.ability,!0),ct.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),S.emit(K.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 e=fQ(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield AC(e,o=>{this._reconnectionTimer=o}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(A?.code," ").concat(A)),ct.addFailedEvent({key:521704,error:A}),this.reconnectionCount>=Ch()&&this._log.warn("SDK has tried reconnect for ".concat(Ch()," 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 DA(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(gG,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var A;!this.isReconnecting&&((A=this._peerConnection)==null?void 0:A.connectionState)===hi.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(A){var e;let o=((e=this._peerConnection)==null?void 0:e.iceConnectionState)||"closed",n=this.getDTLSTransportState();this._log.info("connectionState: ".concat(A.target.connectionState," ICE: ").concat(o," DTLS: ").concat(n)),A.target.connectionState===hi.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(A.target.connectionState===hi.FAILED||A.target.connectionState===hi.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(A.target.connectionState===hi.CONNECTED||A.target.connectionState===hi.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),S.emit(K.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 AB;let A=null;return AI()&&this._peerConnection.getSenders().length!==0?(A=this._peerConnection.getSenders()[0].transport,Ph()&&this._peerConnection.getReceivers().length!==0&&A?A.state:AB):AB}emitConnectionStateChangedEvent(A){A!==this.currentState&&(this.currentState==="RECONNECTING"&&A==="CONNECTING"||(this.emit(VM.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:A}),this.currentState=A))}logSelectedCandidate(){return DA(this,null,function*(){if(!this._peerConnection)return;let A=yield this._peerConnection.getStats();for(let[e,o]of A)if(Cm(o)){let n=A.get(o.localCandidateId),a=A.get(o.remoteCandidateId);n&&(this._log.info("local candidate: ".concat(n.candidateType," ").concat(n.protocol,":").concat(n.ip||n.address,":").concat(n.port," ").concat(n.networkType||""," ").concat(n.relayProtocol?"relayProtocol:".concat(n.relayProtocol," url: ").concat(n.url):"")),n.networkType&&KR(n.networkType)),a&&this._log.info("remote candidate: ".concat(a.candidateType," ").concat(a.protocol,":").concat(a.ip||a.address,":").concat(a.port));break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise((A,e)=>{if(this.currentState==="CONNECTED")return A();let o=c=>{c.state==="CONNECTED"&&(clearTimeout(I),a(),A())},n=c=>{let{room:u}=c;u===this._room&&(clearTimeout(I),a(),e(new Ct({code:Ge.API_CALL_ABORTED,message:Wi({key:Mi.CONNECTION_ABORTED,data:"leave room"})})))},a=()=>{S.off(K.LEAVE_SUCCESS,n,this),this.off(VM.CONNECTION_STATE_CHANGED,o,this)},I=setTimeout(()=>{a();let c=new Ct({code:Ge.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),e(c)},yN);this.clearConnectTimeout=()=>{a(),clearTimeout(I),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,e(new Ct({code:Ge.API_CALL_TIMEOUT,message:"connection timeout"}))},S.on(K.LEAVE_SUCCESS,n,this),this.on(VM.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,e)=>{this.once("spc-reconnected",A),this.once("error",e)}):Promise.resolve()}addDownlink(A){return DA(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(e){this._log.error("addDownlink(".concat(A.userId,") failed ").concat(e)),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig(A){let{ssrc:e,userId:o,tinyId:n,prevMids:a}=A;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(o," ").concat(JSON.stringify(e))),this._parsedAnswer||(this._parsedAnswer=rs(this._peerConnection.remoteDescription.sdp));let I,c,u,d=this._parsedAnswer.media.filter(_=>{var Z;return(Z=_.ssrcs)==null?void 0:Z.find(iA=>{var cA;return(cA=iA.value)==null?void 0:cA.includes(n)})});if(d.length===3)I=d[0],c=d[1],u=d[2];else{let _,Z=this._peerConnection.getTransceivers().slice(4);if(a?.length===3&&a.every(cA=>{var TA;return((TA=Z.find(JA=>Number(JA.mid)===cA))==null?void 0:TA.direction)==="inactive"})?(_=a,this._log.info("reusing previous mids for ".concat(o,": ").concat(_.join(","))),Z.forEach(cA=>{_.includes(Number(cA.mid))&&(cA.direction=fA.TRANSCEIVER_DIRECTION_RECVONLY)})):_=Z.filter(cA=>cA.direction==="inactive").slice(0,3).map(cA=>(cA.direction=fA.TRANSCEIVER_DIRECTION_RECVONLY,Number(cA.mid))),_.length===3)I=this._parsedAnswer.media.find(cA=>Number(cA.mid)===Number(_[0])),c=this._parsedAnswer.media.find(cA=>Number(cA.mid)===Number(_[1])),u=this._parsedAnswer.media.find(cA=>Number(cA.mid)===Number(_[2]));else if(_.length===0){this._peerConnection.addTransceiver(fA.AUDIO,{direction:fA.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(fA.VIDEO,{direction:fA.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(fA.VIDEO,{direction:fA.TRANSCEIVER_DIRECTION_RECVONLY}),I=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let cA=Ez({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:rs(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(cA)),u=JSON.parse(JSON.stringify(cA)),I.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(I),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c),u.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(u)}}I.direction=fA.TRANSCEIVER_DIRECTION_SENDONLY;let R="".concat(n,"-").concat(e.audio);I.ssrcs=[{id:e.audio,attribute:"cname",value:"".concat(R)},{id:e.audio,attribute:"msid",value:"".concat(R,"-").concat(fA.MAIN," ").concat(R,"-audio")}],c.direction=fA.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:"".concat(R)},{id:e.video,attribute:"msid",value:"".concat(R,"-").concat(fA.MAIN," ").concat(R,"-bigvideo")},{id:e.videoRtx,attribute:"cname",value:"".concat(R)},{id:e.videoRtx,attribute:"msid",value:"".concat(R,"-").concat(fA.MAIN," ").concat(R,"-bigvideo")}],c.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(e.video," ").concat(e.videoRtx)}],u.direction=fA.TRANSCEIVER_DIRECTION_SENDONLY;let k="".concat(R,"-aux");u.ssrcs=[{id:e.auxiliary,attribute:"cname",value:k},{id:e.auxiliary,attribute:"msid",value:"".concat(k," ").concat(R,"-aux").concat(fA.VIDEO)},{id:e.auxiliaryRtx,attribute:"cname",value:"".concat(k," ").concat(R,"-aux").concat(fA.VIDEO)},{id:e.auxiliaryRtx,attribute:"msid",value:"".concat(k," ").concat(R,"-aux").concat(fA.VIDEO)}],u.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(e.auxiliary," ").concat(e.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(_=>_.mid).join(" ")),this._downlinkMIDMap.set(o,[I.mid,c.mid,u.mid]),this._downlinkMIDUserIDMap.set(I.mid,o),this._downlinkMIDUserIDMap.set(c.mid,o),this._downlinkMIDUserIDMap.set(u.mid,o)}removeDownlink(A){return DA(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 e=this._downlinkMIDMap.get(A),o=!1;return this._peerConnection.getTransceivers().forEach(n=>{e!=null&&e.includes(Number(n.mid))&&(o=!0,n.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=rs(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(n=>{e!=null&&e.includes(Number(n.mid))&&(o=!0,n.direction="inactive",n.ssrcs=[],n.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&o&&(yield this.updateSDP()),this._downlinkMIDMap.delete(A),e?.forEach(n=>this._downlinkMIDUserIDMap.delete(n)),this._log.info("removeDownlink(".concat(A,") done")),e})}setBandwidth(A){return DA(this,null,function*(){if(!this._peerConnection)return;let{audio:e,bigVideo:o,smallVideo:n,auxVideo:a}=A;try{if(TT()){let I=this._peerConnection.getSenders().slice(0,4);for(let u=0;u5e3?5e3:e),!0)}setSenderMaxBitrate(A,e){let o=A.getParameters();if((!o.encodings||o.encodings.length===0)&&(o.encodings=[{}]),e==="unlimited")delete o.encodings[0].maxBitrate;else{if(o.encodings[0].maxBitrate===1e3*e)return;o.encodings[0].maxBitrate=1e3*e}return A.setParameters(o)}setBandwidthBySDP(A){let{audio:e,bigVideo:o,smallVideo:n,auxVideo:a}=A;if(!this._peerConnection||!this._peerConnection.localDescription)return;let I=rs(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=rs(this._peerConnection.remoteDescription.sdp));let c=Yr?"TIAS":"AS";e&&(I.media[0].bandwidth=[{type:c,limit:Yr?1e3*e:e}],this._parsedAnswer.media[0].bandwidth=[{type:c,limit:Yr?1e3*e:e}]),o&&(I.media[1].bandwidth=[{type:c,limit:Yr?1e3*o:o}],this._parsedAnswer.media[1].bandwidth=[{type:c,limit:Yr?1e3*o:o}]),n&&(I.media[2].bandwidth=[{type:c,limit:Yr?1e3*n:n}],this._parsedAnswer.media[2].bandwidth=[{type:c,limit:Yr?1e3*n:n}]),a&&(I.media[3].bandwidth=[{type:c,limit:Yr?1e3*a:a}],this._parsedAnswer.media[3].bandwidth=[{type:c,limit:Yr?1e3*a:a}]);let u={type:"offer",sdp:$h(I)};return this.updateSDP({localDescription:u})}setScaleResolutionDownBy(A,e,o){let n=A.getParameters();(!n.encodings||n.encodings.length===0)&&(n.encodings=[{}]);let a=n.encodings[0].scaleResolutionDownBy;if(Ee(a)?e===1:e===a)return;let I="setScaleResolutionDownBy ".concat(o," ").concat(e);return a&&(I+=" prevScale: ".concat(a)),this._log.warn(I),n.encodings[0].scaleResolutionDownBy=e,A.setParameters(n)}setDegradationPreference(A,e,o){if(Bc&&tE<83||Ea&&gT($g,"12.1")||Yr&&aM<138)return;let n=A.getParameters(),a="balanced";if(e==="motion"?a="maintain-framerate":e==="detail"&&(a="maintain-resolution"),n.degradationPreference===a)return;let I="setDegradationPreference ".concat(o," ").concat(a);return this._log.info(I),n.degradationPreference=a,A.setParameters(n).catch(c=>this._log.warn("".concat(I," failed: ").concat(c)))}updateSDP(){let{localDescription:A}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let e=$h(this._parsedAnswer);return this._updateSDPPromise=new Promise((o,n)=>DA(this,null,function*(){var a,I;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:e}),this._updateSDPPromise=null,o()}catch(c){this._log.error(c),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection((a=this._peerConnection.localDescription)==null?void 0:a.sdp),` + }`}),G(this,"yTextureRef"),G(this,"uTextureRef"),G(this,"vTextureRef"),G(this,"Y"),G(this,"U"),G(this,"V"),this.useProgram();let e=this.context.ctx;e.pixelStorei(e.PACK_ALIGNMENT,1),e.pixelStorei(e.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,e){let o=this.context.ctx,n=o.createTexture();return o.bindTexture(o.TEXTURE_2D,n),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),e),n}render(A){let e=this.context.ctx,o=this.width,n=this.height;return this.useProgram(),e.viewport(0,0,o,n),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.yTextureRef),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o,n,e.LUMINANCE,e.UNSIGNED_BYTE,this.Y),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,this.uTextureRef),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o/2,n/2,e.LUMINANCE,e.UNSIGNED_BYTE,this.U),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,this.vTextureRef),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o/2,n/2,e.LUMINANCE,e.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(A,e){super.resize(A,e);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,e,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,e/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,e/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null)}},lz=(A,e)=>{switch(A){case"webCodecs":return e==="videoFrame"?514705:514706;case"wasm":return e==="webgl"?514707:e==="videoFrame"?514708:514709}throw new Error("decoder type not supported")},FtA=0,UtA=class{constructor(A){G(this,"id",FtA++),G(this,"trackDoneOB"),G(this,"startOB"),G(this,"stopOB"),G(this,"decoder"),G(this,"videoContext"),G(this,"gop",0),G(this,"gop_helper",0),G(this,"waitFirstKeyFrame",!0),G(this,"startTimestamp",0),G(this,"startTime",0),G(this,"startPerformanceTime",0),G(this,"inputFrameCount",0),G(this,"decodedFrameCount",0),G(this,"decodeFrameCount",0),G(this,"downgradeLevel",0),G(this,"lastDowngradeTime",0),G(this,"lastFrameDiff",0),G(this,"lastDecodeFrameTimestamp",0),G(this,"config"),G(this,"gop_before_configure",[]),G(this,"videoElement"),G(this,"type","wasm"),G(this,"goodType"),G(this,"renderer","2d"),G(this,"wasmOption"),G(this,"createDecoder"),G(this,"_decodeSink"),G(this,"isReported",!1),G(this,"track"),G(this,"stateChangeOB"),G(this,"failedReason");let{track:e,createDecoder:o}=A;if(this.stateChangeOB=wu(),this.track=e,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=Ln(e.availableState,Uo.OFF),this.stopOB=wu(),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),Jn(this.stateChangeOB,XW((n,a)=>(n!==a&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:n,state:a}),a),"INITIALIZED"),Qc(this.stopOB),Ks()),this.start()}start(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=Jn(this.pipe(this.track),Qc(this.stopOB),zT());Jn(e,Ks(()=>{this.track.stat.framesDecoded++},o=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(o," retryCount: ").concat(A)),ct.addFailedEvent({key:lz(this.type,this.renderer),error:o}),A>4)this.failedReason=o,this.stateChangeOB.next("FAILED"),ct.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")),ct.addSuccessEvent({key:lz(this.type,this.renderer)}),ct.addSuccessEvent({key:514704})})),Jn(e,OM(1),Ks(()=>{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"&&!um()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var o,n;if(this.failedReason)return;this.inputFrameCount++;let a=new Uint8Array(A.data);if((I=a)[0]!==0||I[1]!==0||I[2]!==0||I[3]!==1||a.length<5)return this.stateChangeOB.next("FAILED"),this.close("not h26x frame ".concat(a.subarray(0,5))),A;var I;let c=!1;switch(31&a[4]){case 5:case 7:c=!0}if(((o=this.decoder)==null?void 0:o.state)!=="configured")return this.track.log.debug("not configured ".concat(this.inputFrameCount)),c&&(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&&!e&&(this.gop_before_configure.forEach(d=>this.decode(d,!0)),this.gop_before_configure=[]);let{timestamp:u}=A;if(c?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!c)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount," ").concat(a.subarray(0,5).join(" ")));this.waitFirstKeyFrame=!1,this.startTimestamp=u,this.startTime=Date.now(),this.startPerformanceTime=ki()}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(u," ").concat((n=A.getMetadata)==null?void 0:n.call(A).rtpTimestamp)),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=u,void this.decoder.decode({data:A.data,type:A.type,timestamp:this.lastDecodeFrameTimestamp})}return A}checkDowngradeByFrameDiff(){let A=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=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(e,", lastFrameDiff: ").concat(this.lastFrameDiff)),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(A){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-A>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug("downgrade level ".concat(e," to ").concat(this.downgradeLevel))}pipe(A){return e=>DA(this,null,function*(){this._decodeSink=e;let o,n=A.mediaTrack;e.defer(()=>{var c;n&&(A.player.setCanvas(),A.setInputMediaStreamTrack(n)),o?.close(),(c=this.videoContext)==null||c.destroy(),delete this._decodeSink});let{renderer:a,type:I}=this;A.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(I){case"wasm":o=this.createDecoder(I,this.wasmOption);break;case"webCodecs":o=this.createDecoder(I);break;default:throw new Error("not supported yet")}let c=0;if(o.on("videoFrame",u=>{this.decodedFrameCount++,c++,(c<=10||c%500==0)&&A.log.debug("frame ".concat(c," ").concat(this.decodedFrameCount,"/").concat(this.decodeFrameCount," decoded ").concat(u.timestamp)),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(u.timestamp)),e.next(u)}),o.on("error",u=>{A.log.error(u),e.error(I==="webCodecs"?4:8)}),yield o.initialize(this.videoElement),!this._decodeSink)return;if(o.configure(this.config),I==="wasm"&&a==="webgl"){this.videoContext=new aC({frameRate:15,logger:A.log,name:A.userId}),this.videoContext.create(),this.videoContext.on(aC.UNAVAILABLE,d=>{A.log.error(d),e.error(7)});let u=new LtA(this.videoContext);o.on("videoCodecInfo",d=>u.resize(d.width,d.height)),o.on("videoFrame",d=>{({y:u.Y,u:u.U,v:u.V}=d),this.downgradeLevel===1?this.decodedFrameCount%2==0&&u.render(this.decodedFrameCount):u.render(this.decodedFrameCount)}),A.source=u,A.player.setCanvas(this.videoContext._canvas,2)}else if(a==="videoFrame"){A.player.setCanvas();let u=new MediaStreamTrackGenerator({kind:"video"}),d=u.writable.getWriter();A.setInputMediaStreamTrack(u),o.on("videoFrame",R=>d.write(R))}else{this.videoContext=new vu({frameRate:15,logger:A.log,name:A.userId}),this.videoContext.create({alpha:!1});let u=this.videoContext.createVideoImageSource();o.on("videoFrame",R=>{try{u.image=R,u.update()}catch(k){delete this.goodType,A.log.error(k),e.error(11)}});let d=new Yq(this.videoContext,{name:"remotePlayer",logger:A.log});u.connect(d),A.source=u,A.player.setCanvas(this.videoContext._canvas,2)}this.decoder=o}catch(c){A.log.error(c),e.error(I==="webCodecs"?2:6)}})}},Cz=Promise.resolve(),Bz=class extends ktA.EventEmitter{constructor(A){super(),this.room=A,G(this,"videoContext"),G(this,"_glVideoContext"),G(this,"_2dVideoContext"),G(this,"destination"),G(this,"smallVideoContext"),G(this,"smallDestination"),G(this,"smallTrackSource"),G(this,"smallImageSource"),G(this,"_isMirror",!1),G(this,"_rotation",0),G(this,"cameraTrack"),G(this,"cameraNode"),G(this,"transformNode"),G(this,"mixNode"),G(this,"screenTrack"),G(this,"screenNode"),G(this,"selfModel",!1),G(this,"blurRadius",3),G(this,"arTrack"),G(this,"_enableFaceCentering",!1),G(this,"_enableEffectOptimization",!1),G(this,"onAbort"),G(this,"_color"),G(this,"Wasm"),G(this,"waterMarkNode"),G(this,"_waterMarkOption"),G(this,"watermarkImageList",[]),G(this,"_beautyParams"),G(this,"isUsingArTrack",!1),G(this,"mixTrack"),G(this,"_isMixScreen",!1),G(this,"_virtualBackground"),G(this,"_virtualBackgroundAbortCallback"),G(this,"virtualBackgroundInstance"),G(this,"_bgAssetPath"),G(this,"log"),G(this,"_mat4"),G(this,"_postProcessing"),G(this,"_checkId",0),G(this,"_use2d",!1),G(this,"_autoSwitchRenderMode",!0),G(this,"encodePipeline",[]),G(this,"decodePipeline",[]),G(this,"updated",Cz),G(this,"_updateFlag",!1),this.log=nA.createLogger({parent:A?.getLogger(),id:"vm",userId:A?.userId,sdkAppId:A?.sdkAppId}),this.smallVideoContext=new vu({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 e=A==="2d";this._use2d!==e&&(this._use2d=e,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get cameraResolution(){var A;let{width:e,height:o}=((A=this.cameraTrack)==null?void 0:A.settings)||{};return Eu(this._rotation)?{width:o,height:e}:{width:e,height:o}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new vu({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 aC({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(qO<=22),this._glVideoContext.on(aC.UNAVAILABLE,A=>{var e;this.emit("error",A),this.log.warn("video context unavailable",A),(e=this._virtualBackgroundAbortCallback)==null||e.call(this,A),this.update().catch(o=>{this.log.error(o)})})}catch(A){this.emit("error",A)}}initVirtualBackground(A,e,o){this.onAbort=A,this._mat4=e,this._postProcessing=o}enablePrintDetail(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;this._checkId=nn.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:A})}destroy(){var A,e;(A=this._2dVideoContext)==null||A.destroy(),(e=this._glVideoContext)==null||e.destroy(),this.smallVideoContext.destroy(),nn.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(_Q||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(){let A=arguments.length>1?arguments[1]:void 0,e=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"videoCtxGl")==="videoCtxGl"?512700:512701;A?ct.addFailedEvent({key:e,error:A}):ct.addSuccessEvent({key:e})}checkOrCreateVideoContext(){let A=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let e=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&A===this._hasVirtualBg)this.clear();else{if(!e||!this._use2d)return!0;this.clear()}}else{if(this._glVideoContext=new aC({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,e){if(this.smallMode!=="api")if(A){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new IeA(this.smallVideoContext,A,this.log),this.smallVideoContext.on(aC.UNAVAILABLE,o=>{this.log.warn("small video context lost",o)})}if(this.smallVideoContext.frameRate=A.frameRate,this.smallDestination.resolution=A,e)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.resize(e.width,e.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:n}=this.cameraTrack.settings;this.smallTrackSource.resize(o,n),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(A){var e,o;try{let n=this.cameraTrack,{small:a,player:I}=n;_Q&&I.setCanvas(A);let c=A&&((e=this.destination)==null?void 0:e.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),c=this.arTrack),this.log.info("set main output ".concat(c?c.label:"no output track")),this.setSmallVideo(a,A),S.emit(K.LOCAL_VIDEO_TRACK_PREPROCESSED,{mediaTrack:c,profile:(o=this.cameraTrack)==null?void 0:o.profile,room:this.room}),n.setOutputMediaStreamTrack(c)}catch(n){this.log.error("set main output failed",n)}}update(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return DA(this,null,function*(){var e;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:o,profile:n}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(cl.RENDER,a=>{var I;(I=this.cameraTrack)==null||I.emit("render",a)})),sl===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof xM?(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 xM?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 geA(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(cl.RENDER,u=>{var d;(d=this.cameraTrack)==null||d.emit("render",u)}));let{width:a,height:I}=this.cameraResolution,c=yield this.getWatermarkImage(a,I);this._waterMarkOption={x:0,y:0,width:c.width,height:c.height,image:c},this.cameraNode=new btA(this.videoContext,{input:this.initialTrack,width:a,height:I,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=n.frameRate,this._use2d){let a=this.cameraNode;if(a.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new Ap(this.videoContext,this.log,this._isMirror,this._rotation),a=a.connect(this.transformNode),a.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 c4(this.videoContext,this.log),a.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:I,height:c}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(I,c),I&&c&&this.waterMarkNode.resize(I,c)}(e=this.waterMarkNode)==null||e.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})),a=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))}a.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 e,o,n,a,I;if(A instanceof _m)return this.log.info("change screen input",(e=A.mediaTrack)==null?void 0:e.label),this.setScreenTrack(A);if(A instanceof Su)return this.log.info("change video input",(o=A.mediaTrack)==null?void 0:o.label),this.setCameraTrack(A);if(A instanceof nG){this.log.info("change remote input",(n=A.mediaTrack)==null?void 0:n.label);let c=A.mediaTrack;return A.setOutputMediaStreamTrack(c)}if(A instanceof Jq)return this.log.info("change mix input",(a=A.outMediaTrack)==null?void 0:a.label),this.setMixTrack(A);this.log.warn("change unknown input",(I=A.mediaTrack)==null?void 0:I.label)}removeInput(A){var e;A instanceof _m?((e=this.screenNode)==null||e.close(),delete this.screenNode,delete this.screenTrack,this.update()):A instanceof Su?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 nG?A.source&&A.source.context.destroy():A instanceof Jq&&(delete this.mixTrack,this.update())}setMixTrack(A){this.mixTrack=A}setCameraTrack(A){return this.cameraTrack=A,this.update(!0)}setScreenTrack(A){return DA(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,e){return DA(this,null,function*(){let o=document.createElement("canvas");e&&A&&(o.height=e,o.width=A);let n=o.getContext("2d");if(!n)throw new Ct({code:Ge.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((a,I)=>a.zIndex-I.zIndex),this.watermarkImageList.forEach(a=>{let{image:I,x:c,y:u,width:d,height:R,fillVideo:k}=a,_=k&&A||d,Z=k&&e||R,iA=k?0:c,cA=k?0:u;n.drawImage(I,iA,cA,_,Z)}),Wf(o.toDataURL())})}pushWaterMarkImageList(A){let{type:e}=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)||((e==="mute"||e==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(o=>o.type!==e)),this.watermarkImageList.push(A))}setBeautyParams(A){return DA(this,null,function*(){this._beautyParams=A,this.update()})}stopBeauty(){return DA(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(A){return DA(this,null,function*(){let e;try{e=yield Wf(A?.imageElement||A.imageUrl)}catch{throw new Ct({code:Ge.INVALID_PARAMETER,message:"load image failed, url: ".concat(A.imageUrl)})}let{x:o=0,y:n=0,width:a=e.width,height:I=e.height,type:c="watermark",zIndex:u=2,fillVideo:d=!1}=A;this.watermarkImageList.some(R=>R.type===c)?(this.watermarkImageList=this.watermarkImageList.filter(R=>R.type!==c),this.pushWaterMarkImageList({x:o,y:n,width:a,height:I,image:e,zIndex:u,type:c,imageUrl:A.imageUrl,fillVideo:d}),e=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(e.width,e.height),this.waterMarkNode.image=e):this.update()):(this.pushWaterMarkImageList({x:o,y:n,width:a,height:I,image:e,zIndex:u,type:c,imageUrl:A.imageUrl,fillVideo:d}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(R,k)=>R==="imageUrl"?void 0:k))})}deleteWatermark(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"watermark";return DA(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(e=>e.type!==A),this.log.info("delete watermark",A,JSON.stringify(this.watermarkImageList,(e,o)=>e==="imageUrl"?void 0:o)),yield this.freshWatermark()})}freshWatermark(){return DA(this,null,function*(){var A;(A=this.waterMarkNode)==null||A.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:e,height:o}=this.cameraResolution,n=yield this.getWatermarkImage(e,o);this._waterMarkOption={x:0,y:0,width:n.width,height:n.height,image:n},this.update()})}setVirtualBackground(A){return DA(this,null,function*(){var e,o,n;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 Wf(A.imageUrl):(this.blurRadius=A.blurLevel||this.blurRadius||3,this._virtualBackground=A.type),this._enableFaceCentering=(e=A.enableFaceCentering)!=null?e:this._enableFaceCentering,this._enableEffectOptimization=(o=A.enableEffectOptimization)!=null?o:this._enableEffectOptimization,this._color=(n=A.color)!=null?n:[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 Ct({code:Ge.INVALID_OPERATION,message:"webgl context create failed, ".concat(this._glVideoContext.error)})})}get mixScreen(){return this._isMixScreen}set mixScreen(A){var e;this._isMixScreen=A,this._isMixScreen||((e=this.screenNode)==null||e.close(),delete this.screenNode),this.update()}set mirror(A){var e;this._isMirror!==A&&(this._isMirror=A,this._isTransform||((e=this.transformNode)==null||e.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(A){var e;this._rotation!==A&&(this._rotation=A,this._isTransform||((e=this.transformNode)==null||e.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(A){this.arTrack=A,this.isUsingArTrack=!0,this.update()}updateAr(){return DA(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 UtA(A)}clear(){var A,e;(A=this.videoContext)==null||A.disconnect(),(e=this.destination)==null||e.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor(A){let{processor:e,type:o}=A;var n;this.encodePipeline.includes(e)||(this.encodePipeline[o]=e,(n=this.room)==null||n.enableInsertableStreams())}addDecodeProcessor(A){let{processor:e,type:o}=A;var n;this.decodePipeline.includes(e)||(this.decodePipeline[o]=e,(n=this.room)==null||n.enableInsertableStreams())}removeEncodeProcessor(A){let{type:e}=A;this.encodePipeline[e]=void 0}removeDecodeProcessor(A){let{type:e}=A;this.decodePipeline[e]=void 0}};vt([_W(function(A){this.log.error("update failed",A)}),Dn(A=>function(){for(var e=arguments.length,o=new Array(e),n=0;n{A.apply(this,o).then(a,I),setTimeout(I,5e3,new Ct({code:Ge.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],Bz.prototype,"update");var OtA=0,xtA=class extends Uo{constructor(A){super("room"),G(this,"seq",++OtA),G(this,"sdkAppId"),G(this,"userId"),G(this,"userSig"),G(this,"privateMapKey"),G(this,"latencyLevel"),G(this,"tinyId"),G(this,"scene"),G(this,"roomId"),G(this,"useStringRoomId"),G(this,"role","anchor"),G(this,"joinParams",null),G(this,"localPublishFlag",0),G(this,"localTracks",new Set),G(this,"enableAutoPlayDialog",!0),G(this,"autoReceiveAudio",!0),G(this,"autoReceiveVideo",!0),G(this,"proxy_ws"),G(this,"proxy_wt"),G(this,"proxy_unified"),G(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}}),G(this,"keyPointManager"),G(this,"audioManager"),G(this,"videoManager"),G(this,"callDurationCalculator"),G(this,"badCaseDetector"),G(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),G(this,"videoDecodeFallbackType"),G(this,"smallMode","canvas"),G(this,"prelinkPromise",null),G(this,"enableChorus",!1),G(this,"_isUsingCachedSchedule",!1),G(this,"_log"),G(this,"_joinedTimestamp",0),G(this,"_sdkType"),G(this,"heartbeatReport"),G(this,"heartbeatCount",0),G(this,"quality"),G(this,"enableSEI"),G(this,"isDestroyed",!1),this._log=nA.createLogger({parent:A.logger,id:"r".concat(this.seq)}),this.useStringRoomId=!!A.useStringRoomId,rn(A.autoReceiveAudio)&&(this.autoReceiveAudio=A.autoReceiveAudio),rn(A.autoReceiveVideo)&&(this.autoReceiveVideo=A.autoReceiveVideo),rn(A.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=A.enableAutoPlayDialog),this._sdkType=A.sdkType,this.keyPointManager=new vtA({room:this,frameWorkType:A.frameWorkType,component:A.component,language:A.language}),this.callDurationCalculator=new NtA({room:this}),this.badCaseDetector=new GtA({room:this}),this.audioManager=new ueA(this),this.videoManager=new Bz(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(e=>{if(e.isPublished||e.isPublishing)switch(e.mediaType){case 1:A.audio=!0;break;case 4:A.bigVideo=!0,A.smallVideo=e.hasSmall;break;case 2:A.auxVideo=!0}}),A}get muteState(){var A,e,o;return{audio:!((A=this.localMainAudioTrack)==null||!A.muted),bigVideo:!((e=this.localMainVideoTrack)==null||!e.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 DA(this,null,function*(){return this.publish(A)})}removeTrack(A){return DA(this,null,function*(){return this.unpublish(A)})}replaceTrack(A){return DA(this,null,function*(){})}setEncodedDataProcessingListener(A){throw new Error("Method not implemented.")}enableAIVoice(A){throw new Error("Method not implemented.")}setProxyServer(A){if(Sr(A))/^wss?:\/\//i.test(A)?this.proxy_ws=A:/^https?:\/\//i.test(A)&&(this.proxy_wt=A);else if(Cc(A)){let{websocketProxy:e,webtransportProxy:o,loggerProxy:n,scheduleProxy:a,unifiedProxy:I}=A;this.proxy_ws=e,this.proxy_wt=o,this.proxy_unified=I,I?(Wq([I,I]),Tf("https://".concat(I))):(n&&Tf(n),a&&Wq(a))}S.once(K.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:ZQ.main,sched_back_domain:ZQ.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return DA(this,null,function*(){let A={};return this.remotePublishedUserMap.forEach(e=>{A[e.userId]=e.remoteAudioTrack.stat}),A})}getTransportStats(){return DA(this,null,function*(){var A;let e={rtt:((A=this.quality)==null?void 0:A.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let o of this.quality.downlinkInfo)e.downlinksRTT[o.userId]=o.rtt;return e})}getRemoteVideoStats(){return DA(this,arguments,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"main";return function*(){let o={};return A.remotePublishedUserMap.forEach(n=>{let a=e==="auxiliary"?n.remoteAuxiliaryTrack:n.remoteVideoTrack;o[n.userId]=a.stat}),o}()})}checkDestroy(){if(this.isDestroyed)throw new Ct({code:Ge.INVALID_OPERATION,message:Wi({key:Mi.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(ts.INVALID_DESTROY),new Ct({code:Ge.INVALID_OPERATION,message:Wi({key:Mi.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,S.emit(K.ROOM_DESTROY,{room:this})}schedule(A,e){return DA(this,null,function*(){var o,n,a,I;let c=ki();try{let{isCached:u,result:d,detailCost:R}=yield v4({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?A.strRoomId:A.roomId,useStringRoomId:this.useStringRoomId,version:ol,userSig:this.userSig,role:this.scene==="live"?A.role:void 0,frameWorkType:e,latencyLevel:A.latencyLevel});this._isUsingCachedSchedule=u,this._log.info("schedule cache:".concat(+u," ").concat(al(d,{keysToExclude:["username","credential"]}))),u&&S.once(K.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=bt(bt({},this.scheduleResult),d),hr((o=d.config)==null?void 0:o.retryCount)&&UR(d.config.retryCount),Sr((n=d.config)==null?void 0:n.loggerDomain)&&Tf(d.config.loggerDomain),this.videoDecodeFallbackType=((a=d.config)==null?void 0:a.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((I=d.config)==null?void 0:I.smallMode)||this.smallMode,S.emit(K.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:R}),ct.addSuccessEvent({key:521700,cost:ki()-c})}catch(u){throw ct.addFailedEvent({key:521700,error:u}),u}})}sendAbilityStatus(A){}enableInsertableStreams(){return Promise.resolve()}switchRoom(A){return Promise.reject()}isSwitchRoomSupported(){return!1}prelink(A,e,o,n,a,I){return DA(this,null,function*(){return Promise.resolve()})}closePrelink(){return DA(this,null,function*(){return Promise.resolve()})}},YtA=es(hg()),uz=es(BN());function Qz(A){var e;let o=[];for(let n=0;nI.payload===A.rtp[n].payload)[0];o.push({payload:A.rtp[n].payload,codec:A.rtp[n].codec,fmtp:a?a.config:"",rate:A.rtp[n].rate,rtx:((e=A.rtp[n+1])==null?void 0:e.codec)==="rtx"?A.rtp[n+1].payload:0,rtcpfb:(A?.rtcpFb||[]).filter(I=>I.payload===A.rtp[n].payload).map(I=>{let{type:c,subtype:u}=I;return{id:c,params:u?[u]:[]}})})}return o}var PtA=(A,e,o)=>DA(null,null,function*(){var n;let a=rs(A),I={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:o};I.ice.ufrag=String(a.media[0].iceUfrag),I.ice.password=a.media[0].icePwd||"",a.fingerprint&&(I.dtls.hash=a.fingerprint.type,I.dtls.fingerprint=a.fingerprint.hash,I.dtls.setup=a.setup||""),a.media[0].fingerprint&&(I.dtls.hash=a.media[0].fingerprint.type,I.dtls.fingerprint=a.media[0].fingerprint.hash),I.dtls.setup=a.media[0].setup||"";let c=a.media[0],u=a.media[1];c.ext&&(I.audio.extensions=c.ext.map(R=>({id:R.value,uri:R.uri}))),u.ext&&(I.video.extensions=u.ext.map(R=>({id:R.value,uri:R.uri})));for(let R of c.rtp){if(R.codec!=="opus")continue;let k=c.fmtp.find(Z=>Z.payload===R.payload);if(!k)continue;let _={codec:R.codec,fmtp:k.config,payload:k.payload,rate:R.rate,channels:R.encoding,rtcpfb:[],rtx:0};(n=c.rtcpFb)==null||n.forEach(Z=>{let{payload:iA,type:cA,subtype:TA}=Z;if(iA===_.payload){let JA={id:cA,params:[]};TA&&JA.params.push(TA),_.rtcpfb.push(JA)}}),I.audio.codecs.push(_);break}let d=["h264","vp8","h265"];return e&&d.shift(),I.video.codecs=[...Qz(u)].filter(R=>d.includes(R.codec.toLocaleLowerCase())),I.video.decoders=(yield function(){return DA(this,null,function*(){let R=new RTCPeerConnection;R.addTransceiver(fA.VIDEO,{direction:fA.TRANSCEIVER_DIRECTION_RECVONLY});let k=yield R.createOffer();if(!k.sdp)return[];let _=Qz(rs(k.sdp).media[0]);return R.close(),_})}()).filter(R=>["h264","vp8","h265"].includes(R.codec.toLocaleLowerCase())),I}),dz=(A,e)=>{let o=(A||"").trim(),n=(e||"").trim(),a="profile-level-id",I="".concat(a,"=[0-9a-fA-F]{6}");if(new RegExp(I).test(o)){let u=new RegExp(I,"g");return o.replace(u,"".concat(a,"=").concat(n))}if(!o)return"".concat(a,"=").concat(n);let c=o.endsWith(";")?"":";";return"".concat(o).concat(c).concat(a,"=").concat(n)},JtA=A=>{let{serverAbility:e,clientAbility:o,offerSDP:n,enableCustomMessage:a,profileLevelIdConfig:I}=A,c=rs(n),u={extmapAllowMixed:"extmap-allow-mixed",groups:c.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},d={candidates:e.candidates.map(k=>({component:1,foundation:"1",generation:0,ip:k.ip,port:k.port,priority:k.priority,transport:k.foundation,type:k.type})),connection:{version:4,ip:"0.0.0.0"},direction:fA.TRANSCEIVER_DIRECTION_RECVONLY,ext:e.audio.extensions.map(k=>({value:k.id,uri:k.uri})),fingerprint:{type:e.dtls.hash,hash:e.dtls.fingerprint},fmtp:[{payload:e.audio.codecs[0].payload,config:e.audio.codecs[0].fmtp}],icePwd:e.ice.password,iceUfrag:e.ice.ufrag,mid:"0",payloads:String(e.audio.codecs[0].payload),port:c.media[0].port,protocol:c.media[0].protocol,type:fA.AUDIO,setup:e.dtls.setup,rtcpFb:e.audio.codecs[0].rtcpfb.map(k=>({payload:e.audio.codecs[0].payload,type:k.id,subtype:k.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:e.audio.codecs[0].payload,codec:e.audio.codecs[0].codec,rate:e.audio.codecs[0].rate,encoding:e.audio.codecs[0].channels}]};u.media.push(d);let R=[I?.big,I?.small,I?.aux];return[1,2,3].forEach((k,_)=>{u.media.push(hz({mid:k,serverAbility:e,clientAbility:o,parsedOffer:c,profileLevelId:R[_]}))}),a&&u.media.push(c.media.find(k=>k.mid==="dc")),tp(u)},hz=A=>{let{mid:e,serverAbility:o,clientAbility:n,parsedOffer:a,isDownlink:I=!1,profileLevelId:c}=A,u={candidates:o.candidates.map(d=>({component:1,foundation:"1",generation:0,ip:d.ip,port:d.port,priority:d.priority,transport:d.foundation,type:d.type})),connection:{version:4,ip:"0.0.0.0"},direction:fA.TRANSCEIVER_DIRECTION_RECVONLY,ext:o.video.extensions.map(d=>({value:d.id,uri:d.uri})),fingerprint:{type:o.dtls.hash,hash:o.dtls.fingerprint},fmtp:[],icePwd:o.ice.password,iceUfrag:o.ice.ufrag,mid:String(e),payloads:"",port:a.media[0].port,protocol:a.media[0].protocol,type:fA.VIDEO,setup:o.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(I){let d=o.video.decoders;(!d||d.length===0)&&(d=o.video.codecs),(!d||d.length===0)&&(d=n.video.decoders),d.forEach(R=>{KM(u,R)})}else{let d;d=o.useH265?o.video.codecs.findIndex(k=>k.codec.toLowerCase()==="h265"):o.video.codecs.findIndex(k=>k.codec.toLowerCase()===(o.useVp8?"vp8":"h264"));let R=o.video.codecs[d]||n.video.codecs[0];KM(u,R)}if(!I&&c){let d=u.fmtp,R=u.rtp.find(k=>{var _;return((_=k.codec)==null?void 0:_.toLowerCase())==="h264"});if(R){let k=d.find(_=>String(_.payload)===String(R.payload));k&&(k.config=dz(k.config,c))}}return u},KM=(A,e)=>{A.payloads="".concat(A.payloads," ").concat(e.payload).trim(),A.fmtp.push({payload:e.payload,config:e.fmtp}),A.rtcpFb=[...A.rtcpFb||[],...e.rtcpfb.map(o=>({payload:e.payload,type:o.id,subtype:o.params[0]}))],A.rtp.push({payload:e.payload,codec:e.codec.toUpperCase(),rate:e.rate}),e.rtx&&(A.payloads="".concat(A.payloads," ").concat(e.rtx),A.fmtp.push({payload:e.rtx,config:"apt=".concat(e.payload)}),A.rtp.push({payload:e.rtx,codec:"rtx",rate:e.rate}))},HtA=(A,e,o)=>{let n=uz.default.parse(A);return n.media.forEach((a,I)=>{var c;if((a.type===fA.AUDIO||a.type===fA.VIDEO)&&(function(u){if(!u.rtcpFb)return;let d=[];u.rtcpFb.forEach((R,k)=>{var _;d.push(R),u.rtcpFb&&((_=u.rtcpFb[k+1])==null?void 0:_.payload)!==R.payload&&R.type!=="rrtr"&&d.push({payload:R.payload,type:"rrtr"})}),u.rtcpFb=d}(a),function(u){u.type===fA.VIDEO&&u.fmtp&&u.fmtp.forEach(d=>{d.config.includes("apt")||(d.config+=";sps-pps-idr-in-keyframe=1")})}(a),function(u){u.type===fA.AUDIO&&u.fmtp&&u.fmtp.forEach(d=>{d.config+=";sprop-stereo=1;stereo=1"})}(a),function(u){let d=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"]);u.ext&&(u.ext=u.ext.filter(R=>!d.has(R.uri)))}(a),a.type===fA.VIDEO)){if(I<4)a.payloads="",a.fmtp=[],a.rtp=[],a.rtcpFb=[],e.video.codecs.forEach(u=>KM(a,u));else if(o){a.payloads="",a.fmtp=[],a.rtp=[],a.rtcpFb=[];let u=o.video.decoders;(!u||u.length===0)&&(u=o.video.codecs),(!u||u.length===0)&&(u=e.video.decoders),u.forEach(d=>KM(a,d))}}(c=a.payloads)!=null&&c.includes("datachannel")&&n.groups&&a.mid&&(n.groups[0].mids=n.groups[0].mids.replace(a.mid,"dc"),a.mid="dc")}),uz.default.write(n)};function dK(A){var e,o;let n=/profile-level-id=([0-9a-fA-F]{6})/.exec(A);return(o=(e=n?.[1])==null?void 0:e.toLowerCase())!=null?o:null}function hK(A){let e=A.toLowerCase();if(!/^[0-9a-f]{6}$/.test(e))return"unknown";let o=parseInt(e.slice(0,2),16);return o===66?"baseline":o===77?"main":o===100?"high":"unknown"}function pz(A,e){if(!e)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 n of e.video.codecs){let a=dK(n.fmtp);if(a&&hK(a)===o)return a}return""}var VtA=es(hg()),fz=class extends VtA.EventEmitter{constructor(A){super(),this.room=A,G(this,"mainFpsHealth",1),G(this,"mainBitrateHealth",1),G(this,"badMainBitrateHealthCount",0),G(this,"lastEmitBadHealthTime",0),G(this,"log"),!ra&&Bc&&S.on("262",this.onVideoCodecChanged,this),this.log=A.getLogger().createChild({id:"h-d"})}onVideoCodecChanged(A){let{remoteUserId:e,streamType:o,isHWCodec:n,codec:a}=A;if(!e&&o!==7&&a==="h264"){if(!n)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(e=>{if(e.uint32_video_enc_fps&&e.uint32_video_capture_fps){let o=e.uint32_video_enc_fps/e.uint32_video_capture_fps;e.uint32_video_stream_type===2&&(this.mainFpsHealth=o)}if(e.uint32_video_codec_bitrate&&e.uint32_video_stream_type===2){let{localMainVideoTrack:o}=this.room;o&&(this.mainBitrateHealth=e.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(){S.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};G(fz,"EVENT_BAD_HEALTH","bad_health");var qtA=fz,jM=(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))(jM||{}),KtA=1,ip=class extends YtA.default{constructor(A){let{signalChannel:e,room:o,enableDataChannel:n}=A;super(),G(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),G(this,"isDestroyed",!1),G(this,"currentState","DISCONNECTED"),G(this,"_room"),G(this,"_signalChannel"),G(this,"_peerConnection",null),G(this,"_datachannel",null),G(this,"_enableDataChannel"),G(this,"_log"),G(this,"_downlinkMIDMap",new Map),G(this,"_downlinkMIDUserIDMap",new Map),G(this,"_reconnectionTimer",-1),G(this,"reconnectionCount",0),G(this,"clientAbility"),G(this,"_serverAbility",null),G(this,"addDownlinkQueue",new Set),G(this,"removeDownlinkQueue",new Set),G(this,"_parsedAnswer",null),G(this,"_updateSDPPromise",null),G(this,"_waitForPCConnectedPromise"),G(this,"clearWaitForConnectedPromise"),G(this,"clearConnectTimeout"),G(this,"_isSDPLogged",!1),G(this,"enableInsertableStreams",!1),G(this,"insertableStreamsAbortMap",new Map),G(this,"receiverRemoteTrackMap",new WeakMap),G(this,"scriptTransformWorker"),G(this,"_isRelayTried",!1),G(this,"_rttOverCount",0),G(this,"originOffer",null),G(this,"autoSubscribedSsrcGroups",new Map),G(this,"autoSubscribedUserMap",new Map),G(this,"_h265DecodeFailed",!1),this._room=o,this._enableDataChannel=n,this._signalChannel=e,this._log=nA.createLogger({parent:this._room.getLogger(),id:"spc".concat(KtA++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(JQ?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(e=>e.codec.toLowerCase()==="h264")),A}addAbortController(A,e){var o;(o=this.insertableStreamsAbortMap.get(A))==null||o.abort("destroy"),this.insertableStreamsAbortMap.set(A,e)}get isVP8EncodeSupported(){let A=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(A=A&&this._serverAbility.video.codecs.find(e=>e.codec.toLowerCase()==="vp8")),A}get isH265EncodeSupported(){let A=this._room.checkSystemResult.detail.isH265EncodeSupported;return this._serverAbility&&(A=A&&!!this._serverAbility.video.codecs.find(e=>e.codec.toLowerCase()==="h265")),A}get videoCodec(){var A,e,o;let n=(A=this._parsedAnswer)==null?void 0:A.media[1].rtp.find(a=>["h264","vp8","h265"].includes(a.codec.toLowerCase()));return n?n.codec.toLowerCase():(e=this._serverAbility)!=null&&e.useH265?"h265":(o=this._serverAbility)!=null&&o.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var A,e,o;return(A=this._serverAbility)!=null&&A.useH265&&(e=this._serverAbility)!=null&&e.video.decoders.find(n=>n.codec.toLowerCase()==="h265")&&!this._h265DecodeFailed?"h265":(o=this._serverAbility)!=null&&o.video.decoders.find(n=>n.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(e=>e.fmtp.includes(A))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(A=>{let e=rs(A),o={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return e.media.forEach((n,a)=>{var I;if(n.ssrcs&&!Ee(n.ssrcs[0].id)){let c=Number(n.ssrcs[0].id),u=Number((I=n.ssrcs.filter(d=>d.attribute==="cname")[1])==null?void 0:I.id);switch(a){case 0:o.audioSsrc=c;break;case 1:o.bigVideoSsrc=c,o.bigVideoRtxSsrc=u;break;case 2:o.smallVideoSsrc=c,o.smallVideoRtxSsrc=u;break;case 3:o.auxVideoSsrc=c,o.auxVideoRtxSsrc=u}}}),o})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(A){}initScriptTransformWorker(){vM&&(this.scriptTransformWorker=x4({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 e;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"},n=(e=this._peerConnection)==null?void 0:e.getConfiguration().encodedInsertableStreams;return FO(n)&&(o.encodedInsertableStreams=n),this._log.debug("getPeerConnectionConfig",JSON.stringify(o)),o}initialize(A){return DA(this,null,function*(){var e;let o;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(A)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let n=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(n)),n==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():n==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),ct.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):n==="failed"&&ct.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var n;let a=((n=this._peerConnection)==null?void 0:n.signalingState)||"";this._log[a==="closed"?"debug":"info"]("signaling state: ".concat(a))},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=n=>this.emit("track",n),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=n=>{let a=new WtA(n.data);this.emit("data_channel_msg",{data:a})},this._datachannel.onerror=n=>{this._log.warn("datachannel error",n)}),this._peerConnection.addTransceiver(fA.AUDIO,{direction:fA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(fA.VIDEO,{direction:fA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(fA.VIDEO,{direction:fA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(fA.VIDEO,{direction:fA.TRANSCEIVER_DIRECTION_SENDONLY}),o=yield this._peerConnection.createOffer(),this.clientAbility=yield PtA(o.sdp,((e=this._room.scheduleResult.config)==null?void 0:e.remove264FromSDP)||!1,this._enableDataChannel),this.originOffer=o,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:n}=this;n&&(this._log.debug("dtls state: ".concat(n.state)),n.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():n.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),ct.addSuccessEvent({key:521707}),this.clientAbility}catch(n){throw ct.addFailedEvent({key:521707,error:n}),this._log.error("initialize failed ".concat(n,` +offer: `).concat(o?.sdp)),n}})}setIceServers(A){return DA(this,null,function*(){var e;if(this._peerConnection&&A.length!==0)try{if(this._log.info("setIceServers",JSON.stringify(A,(o,n)=>o==="username"||o==="credential"?"hided":n)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(A)),(e=this._peerConnection)!=null&&e.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(e=>{let o=e.getParameters();o.encodings[0]&&(o.encodings[0].priority=A,o.encodings[0].networkPriority=A,e.setParameters(o).catch(n=>{this._log.warn("setPriority error ",n)}))})}catch(e){this._log.warn("setPriority error ",e)}}connect(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return DA(this,null,function*(){var o,n,a;try{if(this.currentState==="CONNECTED")return;((o=this._peerConnection)==null||!o.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let I=ki(),c=this.getProfileLevelIdConfig(),u={type:"answer",sdp:JtA({serverAbility:A,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableDataChannel,profileLevelIdConfig:c})};this._serverAbility=A,yield this.setAnswer(u),yield this.waitForPeerConnectionConnected(),this._room.firewallDetector.resetTimeoutCount();let d=((n=this._room.scheduleResult.config)==null?void 0:n.priority)||((a=this._room.joinParams)==null?void 0:a.priority)||new URLSearchParams(location.search).get("priority");d&&this.setPriority(d),e||ct.addSuccessEvent({key:521703,cost:ki()-I})}catch(I){let c=I instanceof Ct&&I.code===Ge.API_CALL_ABORTED;throw c||this._log.error("connect failed: ".concat(I),A),this.reset(),!c&&!this.isReconnecting&&!this.isDestroyed&&(ct.addFailedEvent({key:521703,error:I}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),I}})}reconnect(){return DA(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(lG,this.reconnect,this);try{this.reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this.reconnectionCount,"]")),this.reset();let A=this._signalChannel.getBackupRelayIpPair(),e=yield this.initialize(this._room.getIceServers(A!=null&&A.iceServer?[A.iceServer]:[])),o=bt({ability:e},A),n=yield this._signalChannel.sendWaitForResponse({command:CtA,responseCommand:io.REBUILD_PEER_CONNECTION_RES,data:o,enableLog:!1});if(n.data.code!==0)throw new Ct({code:n.data.code,message:n.data.message});yield this.connect(n.data.data.ability,!0),ct.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),S.emit(K.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 e=yQ(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield AC(e,o=>{this._reconnectionTimer=o}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(A?.code," ").concat(A)),ct.addFailedEvent({key:521704,error:A}),this.reconnectionCount>=Qh()&&this._log.warn("SDK has tried reconnect for ".concat(Qh()," 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 DA(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(lG,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var A;!this.isReconnecting&&((A=this._peerConnection)==null?void 0:A.connectionState)===hi.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(A){var e;let o=((e=this._peerConnection)==null?void 0:e.iceConnectionState)||"closed",n=this.getDTLSTransportState();this._log.info("connectionState: ".concat(A.target.connectionState," ICE: ").concat(o," DTLS: ").concat(n)),A.target.connectionState===hi.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(A.target.connectionState===hi.FAILED||A.target.connectionState===hi.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(A.target.connectionState===hi.CONNECTED||A.target.connectionState===hi.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),S.emit(K.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 AB;let A=null;return AI()&&this._peerConnection.getSenders().length!==0?(A=this._peerConnection.getSenders()[0].transport,Vh()&&this._peerConnection.getReceivers().length!==0&&A?A.state:AB):AB}emitConnectionStateChangedEvent(A){A!==this.currentState&&(this.currentState==="RECONNECTING"&&A==="CONNECTING"||(this.emit(jM.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:A}),this.currentState=A))}logSelectedCandidate(){return DA(this,null,function*(){if(!this._peerConnection)return;let A=yield this._peerConnection.getStats();for(let[e,o]of A)if(dm(o)){let n=A.get(o.localCandidateId),a=A.get(o.remoteCandidateId);n&&(this._log.info("local candidate: ".concat(n.candidateType," ").concat(n.protocol,":").concat(n.ip||n.address,":").concat(n.port," ").concat(n.networkType||""," ").concat(n.relayProtocol?"relayProtocol:".concat(n.relayProtocol," url: ").concat(n.url):"")),n.networkType&&zR(n.networkType)),a&&this._log.info("remote candidate: ".concat(a.candidateType," ").concat(a.protocol,":").concat(a.ip||a.address,":").concat(a.port));break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise((A,e)=>{if(this.currentState==="CONNECTED")return A();let o=c=>{c.state==="CONNECTED"&&(clearTimeout(I),a(),A())},n=c=>{let{room:u}=c;u===this._room&&(clearTimeout(I),a(),e(new Ct({code:Ge.API_CALL_ABORTED,message:Wi({key:Mi.CONNECTION_ABORTED,data:"leave room"})})))},a=()=>{S.off(K.LEAVE_SUCCESS,n,this),this.off(jM.CONNECTION_STATE_CHANGED,o,this)},I=setTimeout(()=>{a();let c=new Ct({code:Ge.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),e(c)},SN);this.clearConnectTimeout=()=>{a(),clearTimeout(I),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,e(new Ct({code:Ge.API_CALL_TIMEOUT,message:"connection timeout"}))},S.on(K.LEAVE_SUCCESS,n,this),this.on(jM.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,e)=>{this.once("spc-reconnected",A),this.once("error",e)}):Promise.resolve()}addDownlink(A){return DA(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(e){this._log.error("addDownlink(".concat(A.userId,") failed ").concat(e)),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig(A){let{ssrc:e,userId:o,tinyId:n,prevMids:a}=A;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(o," ").concat(JSON.stringify(e))),this._parsedAnswer||(this._parsedAnswer=rs(this._peerConnection.remoteDescription.sdp));let I,c,u,d=this._parsedAnswer.media.filter(_=>{var Z;return(Z=_.ssrcs)==null?void 0:Z.find(iA=>{var cA;return(cA=iA.value)==null?void 0:cA.includes(n)})});if(d.length===3)I=d[0],c=d[1],u=d[2];else{let _,Z=this._peerConnection.getTransceivers().slice(4);if(a?.length===3&&a.every(cA=>{var TA;return((TA=Z.find(JA=>Number(JA.mid)===cA))==null?void 0:TA.direction)==="inactive"})?(_=a,this._log.info("reusing previous mids for ".concat(o,": ").concat(_.join(","))),Z.forEach(cA=>{_.includes(Number(cA.mid))&&(cA.direction=fA.TRANSCEIVER_DIRECTION_RECVONLY)})):_=Z.filter(cA=>cA.direction==="inactive").slice(0,3).map(cA=>(cA.direction=fA.TRANSCEIVER_DIRECTION_RECVONLY,Number(cA.mid))),_.length===3)I=this._parsedAnswer.media.find(cA=>Number(cA.mid)===Number(_[0])),c=this._parsedAnswer.media.find(cA=>Number(cA.mid)===Number(_[1])),u=this._parsedAnswer.media.find(cA=>Number(cA.mid)===Number(_[2]));else if(_.length===0){this._peerConnection.addTransceiver(fA.AUDIO,{direction:fA.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(fA.VIDEO,{direction:fA.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(fA.VIDEO,{direction:fA.TRANSCEIVER_DIRECTION_RECVONLY}),I=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let cA=hz({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:rs(this._peerConnection.localDescription.sdp),isDownlink:!0});c=JSON.parse(JSON.stringify(cA)),u=JSON.parse(JSON.stringify(cA)),I.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(I),c.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(c),u.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(u)}}I.direction=fA.TRANSCEIVER_DIRECTION_SENDONLY;let R="".concat(n,"-").concat(e.audio);I.ssrcs=[{id:e.audio,attribute:"cname",value:"".concat(R)},{id:e.audio,attribute:"msid",value:"".concat(R,"-").concat(fA.MAIN," ").concat(R,"-audio")}],c.direction=fA.TRANSCEIVER_DIRECTION_SENDONLY,c.ssrcs=[{id:e.video,attribute:"cname",value:"".concat(R)},{id:e.video,attribute:"msid",value:"".concat(R,"-").concat(fA.MAIN," ").concat(R,"-bigvideo")},{id:e.videoRtx,attribute:"cname",value:"".concat(R)},{id:e.videoRtx,attribute:"msid",value:"".concat(R,"-").concat(fA.MAIN," ").concat(R,"-bigvideo")}],c.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(e.video," ").concat(e.videoRtx)}],u.direction=fA.TRANSCEIVER_DIRECTION_SENDONLY;let k="".concat(R,"-aux");u.ssrcs=[{id:e.auxiliary,attribute:"cname",value:k},{id:e.auxiliary,attribute:"msid",value:"".concat(k," ").concat(R,"-aux").concat(fA.VIDEO)},{id:e.auxiliaryRtx,attribute:"cname",value:"".concat(k," ").concat(R,"-aux").concat(fA.VIDEO)},{id:e.auxiliaryRtx,attribute:"msid",value:"".concat(k," ").concat(R,"-aux").concat(fA.VIDEO)}],u.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(e.auxiliary," ").concat(e.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(_=>_.mid).join(" ")),this._downlinkMIDMap.set(o,[I.mid,c.mid,u.mid]),this._downlinkMIDUserIDMap.set(I.mid,o),this._downlinkMIDUserIDMap.set(c.mid,o),this._downlinkMIDUserIDMap.set(u.mid,o)}removeDownlink(A){return DA(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 e=this._downlinkMIDMap.get(A),o=!1;return this._peerConnection.getTransceivers().forEach(n=>{e!=null&&e.includes(Number(n.mid))&&(o=!0,n.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=rs(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(n=>{e!=null&&e.includes(Number(n.mid))&&(o=!0,n.direction="inactive",n.ssrcs=[],n.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&o&&(yield this.updateSDP()),this._downlinkMIDMap.delete(A),e?.forEach(n=>this._downlinkMIDUserIDMap.delete(n)),this._log.info("removeDownlink(".concat(A,") done")),e})}setBandwidth(A){return DA(this,null,function*(){if(!this._peerConnection)return;let{audio:e,bigVideo:o,smallVideo:n,auxVideo:a}=A;try{if(bT()){let I=this._peerConnection.getSenders().slice(0,4);for(let u=0;u5e3?5e3:e),!0)}setSenderMaxBitrate(A,e){let o=A.getParameters();if((!o.encodings||o.encodings.length===0)&&(o.encodings=[{}]),e==="unlimited")delete o.encodings[0].maxBitrate;else{if(o.encodings[0].maxBitrate===1e3*e)return;o.encodings[0].maxBitrate=1e3*e}return A.setParameters(o)}setBandwidthBySDP(A){let{audio:e,bigVideo:o,smallVideo:n,auxVideo:a}=A;if(!this._peerConnection||!this._peerConnection.localDescription)return;let I=rs(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=rs(this._peerConnection.remoteDescription.sdp));let c=Yr?"TIAS":"AS";e&&(I.media[0].bandwidth=[{type:c,limit:Yr?1e3*e:e}],this._parsedAnswer.media[0].bandwidth=[{type:c,limit:Yr?1e3*e:e}]),o&&(I.media[1].bandwidth=[{type:c,limit:Yr?1e3*o:o}],this._parsedAnswer.media[1].bandwidth=[{type:c,limit:Yr?1e3*o:o}]),n&&(I.media[2].bandwidth=[{type:c,limit:Yr?1e3*n:n}],this._parsedAnswer.media[2].bandwidth=[{type:c,limit:Yr?1e3*n:n}]),a&&(I.media[3].bandwidth=[{type:c,limit:Yr?1e3*a:a}],this._parsedAnswer.media[3].bandwidth=[{type:c,limit:Yr?1e3*a:a}]);let u={type:"offer",sdp:tp(I)};return this.updateSDP({localDescription:u})}setScaleResolutionDownBy(A,e,o){let n=A.getParameters();(!n.encodings||n.encodings.length===0)&&(n.encodings=[{}]);let a=n.encodings[0].scaleResolutionDownBy;if(Ee(a)?e===1:e===a)return;let I="setScaleResolutionDownBy ".concat(o," ").concat(e);return a&&(I+=" prevScale: ".concat(a)),this._log.warn(I),n.encodings[0].scaleResolutionDownBy=e,A.setParameters(n)}setDegradationPreference(A,e,o){if(Bc&&tE<83||Ea&&lT($g,"12.1")||Yr&&IM<138)return;let n=A.getParameters(),a="balanced";if(e==="motion"?a="maintain-framerate":e==="detail"&&(a="maintain-resolution"),n.degradationPreference===a)return;let I="setDegradationPreference ".concat(o," ").concat(a);return this._log.info(I),n.degradationPreference=a,A.setParameters(n).catch(c=>this._log.warn("".concat(I," failed: ").concat(c)))}updateSDP(){let{localDescription:A}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let e=tp(this._parsedAnswer);return this._updateSDPPromise=new Promise((o,n)=>DA(this,null,function*(){var a,I;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:e}),this._updateSDPPromise=null,o()}catch(c){this._log.error(c),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection((a=this._peerConnection.localDescription)==null?void 0:a.sdp),` next offer: `).concat(this.filterSDPDirection(A?.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection((I=this._peerConnection.remoteDescription)==null?void 0:I.sdp),` -next answer: `).concat(this.filterSDPDirection(e))),this._log.warn("offer: ".concat(A?.sdp)),this._log.warn("answer: ".concat(e)),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map(u=>{let{mid:d,currentDirection:R,direction:k,stopped:_}=u;return{mid:d,currentDirection:R,direction:k,stopped:_}})))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,n(c)}})),this._updateSDPPromise}setTransceiverDirection(A,e){return DA(this,null,function*(){if(!Yr||!this._peerConnection||!this._parsedAnswer)return;this._log.info("setting transceiver ".concat(e.join(",")," direction to ").concat(A));let o=this._peerConnection.getTransceivers();e.forEach(n=>{o[n].direction!==A&&(o[n].direction=A)});for(let n of e){let a=this._parsedAnswer.media[n].direction;A===_r.INACTIVE&&a===_r.RECVONLY&&(this._parsedAnswer.media[n].direction=A),A===_r.SENDONLY&&a===_r.INACTIVE&&(this._parsedAnswer.media[n].direction=_r.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(){return rs(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"").media.map(A=>A.direction)}setOffer(A){this._log.info("setting offer");let e=TtA(A.sdp,this.clientAbility,this._serverAbility);return this._log.debug(e),this._peerConnection.setLocalDescription({type:"offer",sdp:e})}setAnswer(A){return this._log.info("setting answer"),this._log.debug(A.sdp),this._peerConnection.setRemoteDescription(A)}switchVideoEncoder(A){return DA(this,null,function*(){if(this._parsedAnswer||(this._parsedAnswer=rs(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let e=!1;this._parsedAnswer.media.forEach(o=>{var n;if(o.type===fA.VIDEO){let a=this._serverAbility.video.codecs.find(I=>I.codec.toLowerCase()===A);a&&((n=o.payloads)==null||!n.includes(String(a.payload)))&&(o.fmtp=[],o.payloads="",o.rtp=[],o.rtcpFb=[],HM(o,a),e=!0)}}),e&&(this._log.warn("switch video encoder to ".concat(A)),yield this.updateSDP())})}getScheduleProfileLevelId(A){var e;try{let o=(e=this._room.scheduleResult.config)==null?void 0:e.profileLevelId,n="";if(A===2?n=JN(o?.big)?o.big:"":A===3?n=JN(o?.small)?o.small:"":A===7&&(n=JN(o?.aux)?o.aux:""),!n)return"";let a=lz(n,this.clientAbility);return a?this._log.info("use schedule profile level id: streamType=".concat(A,", raw=").concat(n,", resolved=").concat(a)):this._log.warn("schedule profile level id not resolved: streamType=".concat(A,", raw=").concat(n)),a}catch(o){return this._log.warn("getScheduleProfileLevelId error: ".concat(o)),""}}getProfileLevelIdConfig(){try{let A=new URLSearchParams(location.search).get("profileLevelId")||"",e=lz(A,this.clientAbility);if(e)return this._log.info("use url profile level id: raw=".concat(A,", resolved=").concat(e)),{big:e,small:e,aux:e};let o=this.getScheduleProfileLevelId(2),n=this.getScheduleProfileLevelId(3),a=this.getScheduleProfileLevelId(7);if(!o&&!n&&!a)return;let I={};return o&&(I.big=o),n&&(I.small=n),a&&(I.aux=a),I}catch(A){return void this._log.warn("getProfileLevelIdConfig error: ".concat(A))}}setH264ProfileLevelId(A,e){return DA(this,null,function*(){if(!this._peerConnection||!this._serverAbility)return;this._updateSDPPromise&&(yield this._updateSDPPromise),this._log.info("set H264 profile-level-id to ".concat(e?"high":"default"," for ").concat(A)),this._parsedAnswer||(this._parsedAnswer=rs(this._peerConnection.remoteDescription.sdp));let o=A==="main"?1:3,n=this._parsedAnswer.media[o];if(!n||n.type!==fA.VIDEO)return;let a=n.rtp||[],I=n.fmtp||[],c=a.find(Z=>{var iA;return((iA=Z.codec)==null?void 0:iA.toLowerCase())==="h264"});if(!c)return;let u=I.find(Z=>String(Z.payload)===String(c.payload));if(!u)return;let d=EK(u.config);if(!d)return;let R=lK(d)==="high";if(e&&R||!e&&!R)return;let k=this._serverAbility.video.codecs.map(Z=>EK(Z.fmtp)).filter(Boolean).find(Z=>{let iA=lK(Z);return e?iA==="high":iA!=="high"});if(!k)return;let _=u.config;u.config=cz(u.config,k),u.config!==_&&(yield this.updateSDP(),this._log.info("set H264 profile-level-id to ".concat(e?"high":"default"," success")))})}useHWEncoder(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0],e=arguments.length>1?arguments[1]:void 0;return DA(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let o=!1,n=[];Ee(e)?n=this._parsedAnswer.media.slice(1,4):e===2?n.push(this._parsedAnswer.media[1]):e===3?n.push(this._parsedAnswer.media[2]):e===7&&n.push(this._parsedAnswer.media[3]),n.forEach(a=>{var I;if(a.type===fA.VIDEO){let c;A&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(u=>u.fmtp.includes("42001f")):A||(c=this._serverAbility.video.codecs.find(u=>u.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),c&&((I=a.payloads)==null||!I.includes(String(c.payload)))&&(a.fmtp=[],a.payloads="",a.rtp=[],a.rtcpFb=[],HM(a,c),o=!0)}}),o&&(this._log.warn("use ".concat(A?"hw":"sw"," encoder")),yield this.updateSDP())})}sendDataChannelMessage(A){var e;(e=this._datachannel)==null||e.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=>RQ(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 e=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(A)||[]).map(o=>e[o])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP(A){let{uplinkRTT:e,downlinkRTT:o}=A;var n;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let a=this._signalChannel.rtt,I=Math.max(e,o),{rttRatioThreshold:c,rttThreshold:u}=((n=this._room.scheduleResult.config)==null?void 0:n.useTurnTcpInfo)||{};if(!(c&&u&&a&&I))return;let d=Math.floor(I/a),R=(this._isRelayTried||d>c)&&I>u;R?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(a," upRTT: ").concat(e," downRTT: ").concat(o," ratio: ").concat(d," over-count: ").concat(this._rttOverCount," isOver: ").concat(R," 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 e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return DA(this,null,function*(){if(this.isUsingRelay===A)return;let o=A?"relay":"udp",n=A?521709:521710;try{this._room.forceRelay=A,this._log.warn("switchRelay ".concat(o));let a=Date.now();yield this.doSwitchRelay(o),this._log.warn("switchRelay ".concat(o," success")),ct.addSuccessEvent({key:n,cost:Date.now()-a})}catch(a){this._log.warn("switchRelay ".concat(o," failed"),a),ct.addFailedEvent({key:n,error:a}),e?this._room.reJoin():yield this.switchRelay(!A,!0)}})}doSwitchRelay(A){return new Promise((e,o)=>{let n=setTimeout(()=>{this.stopReconnection(),o(new Error("switch ".concat(A," timeout")))},1e4);this.startReconnection().then(e,o).finally(()=>clearTimeout(n))})}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:gK,data:{videoDecCodec:"h264"},responseCommand:io.UPDATE_CONSTRAINT_CONFIG_RES}).then(A=>{A.data.code!==0&&this._log.warn(A.data.message)})}};vt([vW("reconnect")],Ap.prototype,"startReconnection"),vt([Kh(A=>A.userId)],Ap.prototype,"addDownlink"),vt([Kh(A=>A)],Ap.prototype,"removeDownlink"),vt([VT(!0)],Ap.prototype,"updateSDP"),vt([jh(521712,!1),mx(10,0)],Ap.prototype,"setOffer"),vt([jh(521713,!1),mx(10,0)],Ap.prototype,"setAnswer"),vt([Dn((A,e)=>function(){for(var o=arguments.length,n=new Array(o),a=0;aclearTimeout(I)),this._checkPendingPromiseSet.clear()),A.apply(this,n)})],Ap.prototype,"close");var btA=class{constructor(A){G(this,"tag"),G(this,"len"),G(this,"data");let e=new DataView(A);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(A).slice(4,4+this.len).buffer}},LtA=class{constructor(A){G(this,"tinyId"),G(this,"data");let e=new DataView(A),o=0,n=[];for(;o{d.tag===1?this.tinyId=new TextDecoder().decode(d.data):d.tag===2&&a.push(d.data)});let I=a.reduce((d,R)=>d+R.byteLength,0),c=new Uint8Array(I),u=0;a.forEach(d=>{c.set(new Uint8Array(d),u),u+=d.byteLength}),this.data=c.buffer}},Bz=new Set;function gB(){let A=Math.floor(4294967296*Math.random());return Bz.has(A)?gB():(Bz.add(A),A)}var FtA=es(hg()),uz=class extends FtA.default{constructor(A){super(),G(this,"userId"),G(this,"tinyId"),G(this,"_sdpSemantics"),G(this,"_isUplink"),G(this,"_room"),G(this,"_log"),G(this,"_currentState","DISCONNECTED"),G(this,"_prevTime",-1),G(this,"_blackSmallVideoDetectionId"),G(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=nA.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&&(S.emit(K.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,e;return!((e=(A=this._peerConnection)==null?void 0:A.remoteDescription)==null||!e.sdp.includes("H264"))}};function Qz(A){let{when:e,onSkip:o}=A;return Dn((n,a)=>function(){for(var I=arguments.length,c=new Array(I),u=0;u{let{mid:d,currentDirection:R,direction:k,stopped:_}=u;return{mid:d,currentDirection:R,direction:k,stopped:_}})))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,n(c)}})),this._updateSDPPromise}setTransceiverDirection(A,e){return DA(this,null,function*(){if(!Yr||!this._peerConnection||!this._parsedAnswer)return;this._log.info("setting transceiver ".concat(e.join(",")," direction to ").concat(A));let o=this._peerConnection.getTransceivers();e.forEach(n=>{o[n].direction!==A&&(o[n].direction=A)});for(let n of e){let a=this._parsedAnswer.media[n].direction;A===_r.INACTIVE&&a===_r.RECVONLY&&(this._parsedAnswer.media[n].direction=A),A===_r.SENDONLY&&a===_r.INACTIVE&&(this._parsedAnswer.media[n].direction=_r.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(){return rs(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"").media.map(A=>A.direction)}setOffer(A){this._log.info("setting offer");let e=HtA(A.sdp,this.clientAbility,this._serverAbility);return this._log.debug(e),this._peerConnection.setLocalDescription({type:"offer",sdp:e})}setAnswer(A){return this._log.info("setting answer"),this._log.debug(A.sdp),this._peerConnection.setRemoteDescription(A)}switchVideoEncoder(A){return DA(this,null,function*(){if(this._parsedAnswer||(this._parsedAnswer=rs(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let e=!1;this._parsedAnswer.media.forEach(o=>{var n;if(o.type===fA.VIDEO){let a=this._serverAbility.video.codecs.find(I=>I.codec.toLowerCase()===A);a&&((n=o.payloads)==null||!n.includes(String(a.payload)))&&(o.fmtp=[],o.payloads="",o.rtp=[],o.rtcpFb=[],KM(o,a),e=!0)}}),e&&(this._log.warn("switch video encoder to ".concat(A)),yield this.updateSDP())})}getScheduleProfileLevelId(A){var e;try{let o=(e=this._room.scheduleResult.config)==null?void 0:e.profileLevelId,n="";if(A===2?n=KN(o?.big)?o.big:"":A===3?n=KN(o?.small)?o.small:"":A===7&&(n=KN(o?.aux)?o.aux:""),!n)return"";let a=pz(n,this.clientAbility);return a?this._log.info("use schedule profile level id: streamType=".concat(A,", raw=").concat(n,", resolved=").concat(a)):this._log.warn("schedule profile level id not resolved: streamType=".concat(A,", raw=").concat(n)),a}catch(o){return this._log.warn("getScheduleProfileLevelId error: ".concat(o)),""}}getProfileLevelIdConfig(){try{let A=new URLSearchParams(location.search).get("profileLevelId")||"",e=pz(A,this.clientAbility);if(e)return this._log.info("use url profile level id: raw=".concat(A,", resolved=").concat(e)),{big:e,small:e,aux:e};let o=this.getScheduleProfileLevelId(2),n=this.getScheduleProfileLevelId(3),a=this.getScheduleProfileLevelId(7);if(!o&&!n&&!a)return;let I={};return o&&(I.big=o),n&&(I.small=n),a&&(I.aux=a),I}catch(A){return void this._log.warn("getProfileLevelIdConfig error: ".concat(A))}}setH264ProfileLevelId(A,e){return DA(this,null,function*(){if(!this._peerConnection||!this._serverAbility)return;this._updateSDPPromise&&(yield this._updateSDPPromise),this._log.info("set H264 profile-level-id to ".concat(e?"high":"default"," for ").concat(A)),this._parsedAnswer||(this._parsedAnswer=rs(this._peerConnection.remoteDescription.sdp));let o=A==="main"?1:3,n=this._parsedAnswer.media[o];if(!n||n.type!==fA.VIDEO)return;let a=n.rtp||[],I=n.fmtp||[],c=a.find(Z=>{var iA;return((iA=Z.codec)==null?void 0:iA.toLowerCase())==="h264"});if(!c)return;let u=I.find(Z=>String(Z.payload)===String(c.payload));if(!u)return;let d=dK(u.config);if(!d)return;let R=hK(d)==="high";if(e&&R||!e&&!R)return;let k=this._serverAbility.video.codecs.map(Z=>dK(Z.fmtp)).filter(Boolean).find(Z=>{let iA=hK(Z);return e?iA==="high":iA!=="high"});if(!k)return;let _=u.config;u.config=dz(u.config,k),u.config!==_&&(yield this.updateSDP(),this._log.info("set H264 profile-level-id to ".concat(e?"high":"default"," success")))})}useHWEncoder(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0],e=arguments.length>1?arguments[1]:void 0;return DA(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let o=!1,n=[];Ee(e)?n=this._parsedAnswer.media.slice(1,4):e===2?n.push(this._parsedAnswer.media[1]):e===3?n.push(this._parsedAnswer.media[2]):e===7&&n.push(this._parsedAnswer.media[3]),n.forEach(a=>{var I;if(a.type===fA.VIDEO){let c;A&&this.is42001fSupported?c=this.clientAbility.video.codecs.find(u=>u.fmtp.includes("42001f")):A||(c=this._serverAbility.video.codecs.find(u=>u.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),c&&((I=a.payloads)==null||!I.includes(String(c.payload)))&&(a.fmtp=[],a.payloads="",a.rtp=[],a.rtcpFb=[],KM(a,c),o=!0)}}),o&&(this._log.warn("use ".concat(A?"hw":"sw"," encoder")),yield this.updateSDP())})}sendDataChannelMessage(A){var e;(e=this._datachannel)==null||e.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=>SQ(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 e=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(A)||[]).map(o=>e[o])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP(A){let{uplinkRTT:e,downlinkRTT:o}=A;var n;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let a=this._signalChannel.rtt,I=Math.max(e,o),{rttRatioThreshold:c,rttThreshold:u}=((n=this._room.scheduleResult.config)==null?void 0:n.useTurnTcpInfo)||{};if(!(c&&u&&a&&I))return;let d=Math.floor(I/a),R=(this._isRelayTried||d>c)&&I>u;R?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(a," upRTT: ").concat(e," downRTT: ").concat(o," ratio: ").concat(d," over-count: ").concat(this._rttOverCount," isOver: ").concat(R," 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 e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return DA(this,null,function*(){if(this.isUsingRelay===A)return;let o=A?"relay":"udp",n=A?521709:521710;try{this._room.forceRelay=A,this._log.warn("switchRelay ".concat(o));let a=Date.now();yield this.doSwitchRelay(o),this._log.warn("switchRelay ".concat(o," success")),ct.addSuccessEvent({key:n,cost:Date.now()-a})}catch(a){this._log.warn("switchRelay ".concat(o," failed"),a),ct.addFailedEvent({key:n,error:a}),e?this._room.reJoin():yield this.switchRelay(!A,!0)}})}doSwitchRelay(A){return new Promise((e,o)=>{let n=setTimeout(()=>{this.stopReconnection(),o(new Error("switch ".concat(A," timeout")))},1e4);this.startReconnection().then(e,o).finally(()=>clearTimeout(n))})}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:BK,data:{videoDecCodec:"h264"},responseCommand:io.UPDATE_CONSTRAINT_CONFIG_RES}).then(A=>{A.data.code!==0&&this._log.warn(A.data.message)})}};vt([LW("reconnect")],ip.prototype,"startReconnection"),vt([zh(A=>A.userId)],ip.prototype,"addDownlink"),vt([zh(A=>A)],ip.prototype,"removeDownlink"),vt([WT(!0)],ip.prototype,"updateSDP"),vt([Zh(521712,!1),Nx(10,0)],ip.prototype,"setOffer"),vt([Zh(521713,!1),Nx(10,0)],ip.prototype,"setAnswer"),vt([Dn((A,e)=>function(){for(var o=arguments.length,n=new Array(o),a=0;aclearTimeout(I)),this._checkPendingPromiseSet.clear()),A.apply(this,n)})],ip.prototype,"close");var jtA=class{constructor(A){G(this,"tag"),G(this,"len"),G(this,"data");let e=new DataView(A);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(A).slice(4,4+this.len).buffer}},WtA=class{constructor(A){G(this,"tinyId"),G(this,"data");let e=new DataView(A),o=0,n=[];for(;o{d.tag===1?this.tinyId=new TextDecoder().decode(d.data):d.tag===2&&a.push(d.data)});let I=a.reduce((d,R)=>d+R.byteLength,0),c=new Uint8Array(I),u=0;a.forEach(d=>{c.set(new Uint8Array(d),u),u+=d.byteLength}),this.data=c.buffer}},mz=new Set;function gB(){let A=Math.floor(4294967296*Math.random());return mz.has(A)?gB():(mz.add(A),A)}var ztA=es(hg()),Dz=class extends ztA.default{constructor(A){super(),G(this,"userId"),G(this,"tinyId"),G(this,"_sdpSemantics"),G(this,"_isUplink"),G(this,"_room"),G(this,"_log"),G(this,"_currentState","DISCONNECTED"),G(this,"_prevTime",-1),G(this,"_blackSmallVideoDetectionId"),G(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=nA.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&&(S.emit(K.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,e;return!((e=(A=this._peerConnection)==null?void 0:A.remoteDescription)==null||!e.sdp.includes("H264"))}};function yz(A){let{when:e,onSkip:o}=A;return Dn((n,a)=>function(){for(var I=arguments.length,c=new Array(I),u=0;upostMessage({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"}),e=URL.createObjectURL(A);this.worker=new Worker(e),URL.revokeObjectURL(e),this.worker.onerror=o=>this._log.warn("worker error:",o.message,o.filename||"unknown",o.lineno||"unknown"),this.worker.onmessage=o=>{var n;let{type:a,trackId:I,message:c,count:u}=o.data;if(a==="black")(n=this.callbacks.get(I))==null||n();else if(a==="log")this._log.warn(c);else if(a==="blackCount"){let d=this.userIdMap.get(I);this._log.warn("".concat(d||I," black count: ").concat(u))}}}return this.worker}start(A){let{track:e,isUplink:o,room:n,userId:a,onBlack:I}=A;if(this._log.debug("start detect black video",e.id),!Em()||!I||!e||typeof Worker>"u")return void this._log.warn("black video detector not supported");let c=u=>{var d,R,k,_;let Z;if(o)Z=(R=(d=u.msg_up_stream_info)==null?void 0:d.msg_video_status)==null?void 0:R.filter(iA=>iA.uint32_video_stream_type===3)[0];else{let iA=(k=u.msg_down_stream_info)==null?void 0:k.filter(cA=>{var TA;return((TA=cA.msg_user_info)==null?void 0:TA.str_identifier)===a})[0];Z=(_=iA?.msg_video_status)==null?void 0:_.filter(cA=>cA.uint32_video_stream_type===3)[0]}if(Z){let iA=(Z.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[e.id]&&this.sleep[e.id]>0)return void(this.sleep[e.id]-=1);iA>0&&iA<10&&(this.sleep[e.id]=30,this._log.info("track bitrate",iA,"start check"),this.checkOnce(e,3e4))}};return n.on("heartbeat-report",c),this.heartbeatListenerCleaner.set(e.id,()=>n.off("heartbeat-report",c)),this.callbacks.set(e.id,I),this.userIdMap.set(e.id,a),e.id}checkOnce(A,e){try{let o=this.getWorker();if(!o)throw new Error("Worker not available");let n=new MediaStreamTrackProcessor({track:A});o.postMessage({type:"addTrack",trackId:A.id,timeout:e,readable:n.readable},[n.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 e=this.heartbeatListenerCleaner.get(A);e&&e(),this.heartbeatListenerCleaner.delete(A),this.userIdMap.delete(A)}}destroy(){this.callbacks.forEach((A,e)=>this.stop(e)),this.worker&&(this.worker.terminate(),this.worker=null)}},Kx=class extends uz{constructor(A){super(fi(bt({},A),{isUplink:!0})),G(this,"localMainAudioTrack",null),G(this,"localMainVideoTrack",null),G(this,"localAuxAudioTrack",null),G(this,"localAuxVideoTrack",null),G(this,"_isPublishingAux",!1),G(this,"_publishingLocalAudioTrack"),G(this,"_publishingLocalVideoTrack"),G(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}),G(this,"_flag",0),G(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:e,bigVideoRtxSsrc:o,smallVideoSsrc:n,smallVideoRtxSsrc:a,auxVideoSsrc:I,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:A||0,video:e||0,videoRtx:o||0,small:n||0,smallRtx:a||0,auxiliary:I||0,auxiliaryRtx:c||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:e}=this,{publishState:o}=this._room,n=Object.keys(o).filter(a=>{if(o[a]!==e[a]&&o[a])switch(a){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(n.length>0){if(!A)return void(this._checkPublishStateTimeoutId=nn.run("timeout",()=>this.checkPublishState(!0),{delay:1e4,count:1}));ct.addCount({key:521e3}),n.forEach(a=>{this._log.warn("".concat(a," publish failed during call ").concat(bQ()," ").concat(Qu())),ct.addEnum({key:521719,value:dz[a]})}),nn.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(e){this._log.warn("checkPublishState failed",e)}}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get serverPublishState(){return{audio:!!(this.flag&Gf),bigVideo:!!(this.flag&Nf),smallVideo:!!(this.flag&dN),auxVideo:!!(this.flag&Tf)}}initialize(){this.installEvents()}close(A){var e;let o=((e=this._peerConnection)==null?void 0:e.getSenders())||[];for(let n of o)n.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,e;(A=this.singlePC)!=null&&A.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(e=this.singlePC)==null||e.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,e){var o,n,a;let I=this._currentState,c=super.emitConnectionStateChangedEvent(A);return c&&I!==A&&(e?e.emit("connection-state-changed",{prevState:I,state:A}):((o=this.localMainVideoTrack)==null||o.emit("connection-state-changed",{prevState:I,state:A}),(n=this.localAuxVideoTrack)==null||n.emit("connection-state-changed",{prevState:I,state:A}),(a=this._publishingLocalVideoTrack)==null||a.emit("connection-state-changed",{prevState:I,state:A}))),c}onVideoEncodeFailed(A){return DA(this,null,function*(){if(!A||!A.isMediaTrackActive)return;let{videoCodec:e,singlePC:o}=this;if(!o)return;let n={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(e==="vp9"||e==="av1")return;let a=n[e];this._log.warn(a.log),a!=null&&a.supported&&(yield o.switchVideoEncoder(a.target))})}publish(A){return DA(this,arguments,function(e){var o=this;let{localAudioTrack:n,localVideoTrack:a,isAuxiliary:I}=e;return function*(){var c,u,d,R,k,_,Z;if(!o.singlePC)return;if(o.installEvents(),o.installTrackMuteEvents(n,a),a&&(a.retryEncodeFailed=o.onVideoEncodeFailed.bind(o),Ea&&(kh($g,"26.2",!0)||kh(Cu,"26.2",!0)||Eu&&kh($g,"18.7",!0)))){o._log.warn("detectH264Supported for fallback 26.2 video encode issue");try{yield kA.detectH264SupportedByFakeStreaming(500)}catch{}}if(yield o.singlePC.waitForPeerConnectionConnected(),n&&(o._publishingLocalAudioTrack=n),a){if(!o.singlePC.isH264EncodeSupported&&!o.singlePC.isVP8EncodeSupported)throw new Ct({code:Ge.NOT_SUPPORTED_H264,message:Wi({key:Mi.NOT_SUPPORTED_H264ENCODE})});o.singlePC.isUsingH264&&!o.singlePC.isH264EncodeSupported&&o.singlePC.isVP8EncodeSupported&&(o._log.warn("h264 encoder not supported"),yield o.singlePC.switchVideoEncoder("vp8")),ra&&om()===115&&a.profile.width*a.profile.height<=230400&&(o._log.warn("fallback video to defaultBigVideoProfile: ".concat(JSON.stringify(vf))),a.setProfile(vf),yield a.applyProfile()),o._publishingLocalVideoTrack=a}let iA;if(o._isPublishingAux=I,a&&!I&&a.small&&(iA=o._room.videoManager.smallTrack),yield o._signalChannel.sendWaitForResponseWithRetry({command:z4,responseCommand:io.SPC_PUBLISH_RESULT,data:fi(bt({},o.singlePC.uplinkSSRC),{state:o._room.publishState,muteState:o._room.muteState}),retries:3}),a&&(yield o.checkHighProfile({streamType:a.streamType,newWidth:a.settings.width,newHeight:a.settings.height})),yield o.publishByTransceiver({localAudioTrack:n,localVideoTrack:a,smallTrack:iA,isAuxiliary:I}),o._publishingLocalAudioTrack=null,o._publishingLocalVideoTrack=null,o._isPublishingAux=!1,a){o[I?"localAuxVideoTrack":"localMainVideoTrack"]=a,yield o.singlePC.setDegradationPreference(o._peerConnection.getSenders()[I?3:1],a.contentHint,a.streamType);let{scaleResolutionDownBy:TA}=a;yield o.singlePC.setScaleResolutionDownBy(o._peerConnection.getSenders()[I?3:1],TA,a.streamType)}n&&(o[I?"localAuxAudioTrack":"localMainAudioTrack"]=n),yield o.singlePC.setBandwidth({audio:((c=o.localMainAudioTrack)==null?void 0:c.profile.bitrate)||((u=o.localAuxAudioTrack)==null?void 0:u.profile.bitrate),bigVideo:(d=o.localMainVideoTrack)==null?void 0:d.profile.bitrate,smallVideo:(k=(R=o.localMainVideoTrack)==null?void 0:R.small)==null?void 0:k.bitrate,auxVideo:(_=o.localAuxVideoTrack)==null?void 0:_.profile.bitrate}),o.sendMediaSettings();let cA=I?7:2;(o._room.preferHW||(Z=o._room.scheduleResult.config)!=null&&Z.preferHW)&&a&&a.profile.width*a.profile.height>=921600&&o.singlePC.useHWEncoder(!0,cA)}()})}publishByTransceiver(A){let{localAudioTrack:e,localVideoTrack:o,smallTrack:n,isAuxiliary:a}=A;if(!sl())return;this._log.info("publish by transceiver");let I=o?.outMediaTrack,c=e?.outMediaTrack,u=this._peerConnection.getTransceivers(),d=[],R=[],k=(Z,iA,cA)=>{var TA;let JA=u[iA].sender.replaceTrack(cA);R.push(iA),(TA=this.singlePC)!=null&&TA.enableInsertableStreams&&JA.then(()=>this.createEncodedStreams(u[iA].sender,Z)),this.initSenderTransform(u[iA].sender,Z),d.push(JA)};c&&k(e.mediaType,0,c),I&&k(o.mediaType,a?3:1,I),o!=null&&o.small&&d.push(this.publishSmall(this._room.videoManager.smallMode,o));let _=this.singlePC.setTransceiverDirection(_r.SENDONLY,R);return d.push(_),Promise.all(d)}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,e){var o,n;if(this.singlePC.insertableStreamsAbortMap.has(A))return;let a=A.createEncodedStreams(),I=new AbortController;(o=this.singlePC)==null||o.addAbortController(A,I),((n=this.getTrackByMediaType(e))!=null&&n.enableEncodeFrame?a.readable.pipeThrough(new TransformStream({transform:(c,u)=>{var d,R;let k=this.getTrackByMediaType(e);if(!k||!k.encodeFrame)return u.enqueue(c);k.isAudio?u.enqueue(k.enableEncodeFrame?k.encodeFrame(c):c):u.enqueue((d=this.singlePC)!=null&&d.isUsingH264||(R=this.singlePC)!=null&&R.isUsingH265?k.encodeFrame(c,e===8):c)}}),I):a.readable).pipeTo(a.writable,I).catch(c=>{this._log.debug("encoded stream error",c),c!=="destroy"&&this._log.warn(c)})}initSenderTransform(A,e){if(!(this._peerConnection&&this.singlePC&&this.singlePC.scriptTransformWorker&&MM))return;let o=e!==2,n=e===8;A.transform||(A.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:e===1,isMain:o,isSmall:n}))}enableSmall(A){return DA(this,null,function*(){A?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(A){return DA(this,arguments,function(e){var o=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.localMainVideoTrack;return function*(){var a;if(!o.singlePC)return;if(e==="canvas"&&!RM())return void o._log.warn("canvas mode small stream is not supported");let I=o._peerConnection.getTransceivers(),{sender:c}=I[2],u=yield o.doPublishSmall(e,n),d=e==="canvas"?524700:524701;ct.addSuccessEvent({key:d}),u?((a=o.singlePC)!=null&&a.enableInsertableStreams&&o.createEncodedStreams(c,8),o.initSenderTransform(c,8),yield o.singlePC.setTransceiverDirection(_r.SENDONLY,[2]),o.updateMediaSettings(),yield o.doPublishChange(),c.track&&(o._blackSmallVideoDetectionId=Fm.start({track:c.track,room:o._room,isUplink:!0,userId:o.userId,onBlack:()=>{o._log.warn("small video is black");let R=e==="canvas"?524700:524701;ct.addFailedEvent({key:R,error:10002}),Fm.stop(o._blackSmallVideoDetectionId),o._blackSmallVideoDetectionId=void 0}}))):ct.addFailedEvent({key:d,error:10001})}()})}doPublishSmall(A){return DA(this,arguments,function(e){var o=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.localMainVideoTrack;return function*(){if(!o.singlePC)return null;o._log.info("publish small",e);let a=o._peerConnection.getTransceivers(),{sender:I}=a[2];if(e==="canvas"&&o._room.videoManager.smallTrack)return yield I.replaceTrack(o._room.videoManager.smallTrack),"canvas";if(e==="api"&&n!=null&&n.outMediaTrack&&n!=null&&n.small){yield I.replaceTrack(n?.outMediaTrack);let c=I.getParameters(),u=AM(n?.profile,n?.small);return o._log.info("small scaleResolutionDownBy",u),c.encodings[0].scaleResolutionDownBy=u,I.setParameters(c),"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(!(n==null||!n.outMediaTrack))),null}()})}unpublishSmall(){return DA(this,null,function*(){this.singlePC&&(this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(_r.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),Fm.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)})}checkHighProfile(A){return DA(this,null,function*(){var e,o;if((((e=this._room.scheduleResult.config)==null?void 0:e.profileLevelId)||{})[A.streamType==="main"?"big":"aux"]!=="high")return;let n=A.newWidth*A.newHeight>=921600&&!_h();try{yield(o=this.singlePC)==null?void 0:o.setH264ProfileLevelId(A.streamType,n)}catch(a){this._log.warn("setH264ProfileLevelId failed, ignore",a)}})}installTrackMuteEvents(){for(var A=arguments.length,e=new Array(A),o=0;o{n&&(n?.on("mute",this.sendMutedFlag,this),n?.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(){for(var A=arguments.length,e=new Array(A),o=0;o{n&&(n?.off("mute",this.sendMutedFlag,this),n?.off("unmute",this.sendMutedFlag,this))})}unpublish(A){return DA(this,arguments,function(e){var o=this;let{localAudioTrack:n,localVideoTrack:a}=e;return function*(){var I;yield(I=o.singlePC)==null?void 0:I.waitForPeerConnectionConnected();let c=a&&a===o.localAuxVideoTrack||n&&n===o.localAuxAudioTrack,u=a?.outMediaTrack,d=o._peerConnection.getSenders(),R=[];n&&(c?o.localAuxAudioTrack=null:o.localMainAudioTrack=null,!o.localMainAudioTrack&&!o.localAuxAudioTrack&&(yield d[0].replaceTrack(null),R.push(0))),u&&(c?(yield d[3].replaceTrack(null),o.localAuxVideoTrack=null,o._mediaSettings=fi(bt({},o._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),R.push(3)):(yield d[1].replaceTrack(null),yield d[2].replaceTrack(null),o.localMainVideoTrack=null,o._mediaSettings=fi(bt({},o._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),R.push(1,2))),o.isMainStreamPublished||o.isAuxStreamPublished?(yield o.singlePC.setTransceiverDirection(_r.INACTIVE,R),yield o.doPublishChange(!1)):yield o.doUnpublish(),o.uninstallTrackMuteEvents(n,a),a?.emit("connection-state-changed",{prevState:o._currentState,state:"DISCONNECTED"})}()})}doPublishChange(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return DA(this,null,function*(){let e={state:this._room.publishState,constraintConfig:this._mediaSettings},o=yield this._signalChannel.sendWaitForResponseWithRetry({command:nK,data:e,responseCommand:io.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:Yx,commandDesc:"unpublish",responseCommand:io.UNPUBLISH_RESULT,enableLog:A}).catch(e=>{if(e.getCode()===Ge.API_CALL_TIMEOUT||e.getCode()===Ge.API_CALL_ABORTED)return Promise.resolve();throw e})}updateMediaSettings(){var A,e;this._mediaSettings.videoCodec=((A=this.singlePC)==null?void 0:A.videoCodec)||"h264",this._mediaSettings.videoDecCodec=((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264";let o=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:n,localAuxVideoTrack:a}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?a=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),Jh){if(o&&o.outMediaTrack){let I=o.outMediaTrack.getSettings();this._mediaSettings.audioChannel=I.channelCount||1,this._mediaSettings.audioBps=1e3*o.profile.bitrate,this._mediaSettings.audioFs=I.sampleRate||0}if(n&&n.outMediaTrack){let I=n.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=n;this._mediaSettings.videoWidth=(I.width||0)/c||0,this._mediaSettings.videoHeight=(I.height||0)/c||0,this._mediaSettings.videoFps=I.frameRate||0,this._mediaSettings.videoBps=1e3*n.profile.bitrate,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=1e3*n.small.bitrate)}if(a&&a.outMediaTrack){let I=a.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=a;this._mediaSettings.auxVideoWidth=(I.width||0)/c||0,this._mediaSettings.auxVideoHeight=(I.height||0)/c||0,this._mediaSettings.auxVideoFps=I.frameRate||0,this._mediaSettings.auxVideoBps=1e3*a.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),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=1e3*n.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:gK,data:this._mediaSettings,responseCommand:io.UPDATE_CONSTRAINT_CONFIG_RES}).then(A=>{A.data.code!==0&&this._log.warn(A.data.message)}).catch(()=>{})}addTrack(A){return DA(this,null,function*(){if(!this._peerConnection)return;let e=A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;this._log.info("is adding ".concat(A.kind," track to current published local ").concat(e?fA.AUXILIARY:fA.MAIN," stream")),mu()&&(yield this.addTrackByTransceiver(A,e))})}addTrackByTransceiver(A,e){return DA(this,null,function*(){var o;if(!A.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(A.kind===fA.AUDIO)yield n[0].sender.replaceTrack(A.outMediaTrack);else{let a=e?3:1;yield n[a].sender.replaceTrack(A.outMediaTrack),a===1&&(o=this.localMainVideoTrack)!=null&&o.small&&this._room.videoManager.smallTrack&&(yield n[2].sender.replaceTrack(this._room.videoManager.smallTrack)),n[a].direction===_r.INACTIVE&&(yield this.singlePC.setTransceiverDirection(_r.SENDONLY,[a]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(A){return DA(this,null,function*(){if(!this._peerConnection)return;let e=A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;this._log.info("is removing ".concat(A.kind," track from current published local ").concat(e?fA.AUXILIARY:fA.MAIN," stream")),mu()&&(yield this.removeTrackByTransceiver(A,e))})}removeTrackByTransceiver(A,e){return DA(this,null,function*(){if(!A.mediaTrack)return;let o=this._peerConnection.getTransceivers();if(A.kind===fA.AUDIO)yield o[0].sender.replaceTrack(null);else{let n=e?3:1;yield o[n].sender.replaceTrack(null),n===1&&this._room.videoManager.hasSmall&&(yield o[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(_r.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(A){return DA(this,null,function*(){var e;let o=(e=this._peerConnection)==null?void 0:e.getSenders(),n=A.outMediaTrack||A.mediaTrack;if(!o||o.length===0||!n||o.find(I=>I.track===n))return!1;let a=A.mediaType===2||A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(n.kind," track ").concat(n.id," ").concat(n.label," on ").concat(a?fA.AUXILIARY:fA.MAIN," stream")),n.kind===fA.AUDIO&&o[0]&&(yield o[0].replaceTrack(n)),n.kind===fA.VIDEO&&(!a&&o[1]&&(yield o[1].replaceTrack(n)),a&&o[3]&&(yield o[3].replaceTrack(n))),!0})}setBandwidth(A){return DA(this,arguments,function(e){var o=this;let{bandwidth:n,type:a,videoType:I}=e;return function*(){if(o.singlePC){let c={};a===fA.AUDIO?c.audio=n:I==="big"?c.bigVideo=n:I==="small"?c.smallVideo=n:c.auxVideo=n,yield o.singlePC.setBandwidth(c)}}()})}sendMutedFlag(A){A===this.localAuxAudioTrack||A===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:K4,responseCommand:io.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(A){A.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(K.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:fA.VIDEO;if(this._peerConnection){let e=this._peerConnection.getSenders();if(A===fA.AUXILIARY&&e[3]&&e[3].track)return e[3].track.id;if(A===fA.VIDEO&&e[1]&&e[1].track)return e[1].track.id}if(this.localMainVideoTrack&&A===fA.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&A===fA.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(A,e){if(A!==0)throw A===FR?(this._log.error(ts.NOT_SUPPORTED_H264ENCODE),new Ct({code:Ge.NOT_SUPPORTED_H264,message:Wi({key:Mi.NOT_SUPPORTED_H264ENCODE})})):new Ct({code:Ge.UNKNOWN,message:Wi({key:Mi.SIGNAL_RESPONSE_FAILED,data:{signalResponse:io.PUBLISH_RESULT,code:A,message:e}})})}onSinglePCReconnected(){return DA(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}))})}};vt([wm(A=>{let{localVideoTrack:e}=A;e==null||delete e.retryEncodeFailed})],Kx.prototype,"unpublish"),vt([Qz({when(){return this.isDestroyed}})],Kx.prototype,"doPublishChange"),vt([Qz({when(){return this.isDestroyed}})],Kx.prototype,"doUnpublish");var dz=(A=>(A[A.audio=1]="audio",A[A.bigVideo=2]="bigVideo",A[A.smallVideo=3]="smallVideo",A[A.auxVideo=4]="auxVideo",A))(dz||{}),hz=Kx;function pz(A){return Object.keys(A).filter(e=>A[e])}var jx=class extends uz{constructor(A){super(fi(bt({},A),{isUplink:!1})),G(this,"_flag",0),G(this,"isRobot",!1),G(this,"role","anchor"),G(this,"fromType"),G(this,"remoteAudioTrack"),G(this,"remoteVideoTrack"),G(this,"remoteAuxiliaryTrack"),G(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),G(this,"_prevMids"),G(this,"jitterBufferTimeoutId",-1),G(this,"_jitterBufferResolve"),G(this,"_videoCodec"),G(this,"avPlayerStateSyncManager"),G(this,"isDataChannelSubscribed",!1),this.flag=A.flag,this.isRobot=A.isRobot||!1,this.fromType=A.fromType,this.remoteAudioTrack=new Dx(this._room,this),this.remoteVideoTrack=new tG(this._room,this),this.remoteAuxiliaryTrack=new n4(this._room,this),this.avPlayerStateSyncManager=new Kq({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 mQ(this.flag,this.userId)}get flag(){return this._flag}set flag(A){var e,o,n;A!==this._flag&&(this._flag=A,(e=this.remoteAudioTrack)==null||e.onFlagChanged(),(o=this.remoteVideoTrack)==null||o.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||n.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===fA.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 e,o;let n=this._currentState,a=super.emitConnectionStateChangedEvent(A);return a&&n!==A&&((e=this.remoteVideoTrack)==null||e.emit("connection-state-changed",{prevState:n,state:A}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:n,state:A})),a}onTrack(A){var e,o;let n=A.streams[0],{track:a,receiver:I}=A;if(!n.id.includes(this.tinyId))return;let c=n.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(c," ").concat(a.kind));let u=fA.AUDIO;a.kind===fA.VIDEO&&(u=c===fA.MAIN?fA.VIDEO:fA.AUXILIARY);let d=this.remoteAudioTrack;u===fA.VIDEO?d=this.remoteVideoTrack:u===fA.AUXILIARY&&(d=this.remoteAuxiliaryTrack),(e=this.singlePC)==null||e.receiverRemoteTrackMap.set(I,d),(o=this.singlePC)!=null&&o.scriptTransformWorker&&this.initReceiverTransform(I,c,a.kind===fA.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(I),d.setInputMediaStreamTrack(a)}createEncodedStreams(A){if(!this.singlePC.insertableStreamsAbortMap.has(A)){let e=A.createEncodedStreams(),o=new AbortController,n={abortController:o,enqueue:a=>{var I,c,u;let d=(I=this.singlePC)==null?void 0:I.receiverRemoteTrackMap.get(A);return d&&(d.kind!=="video"||(c=this.singlePC)!=null&&c.isUsingH264||(u=this.singlePC)!=null&&u.isUsingH265)?d.decodeFrame(a):a}};e.readable.pipeThrough(new TransformStream({transform:(a,I)=>{let c=n.enqueue(a);c&&I.enqueue(c)}})).pipeTo(e.writable,o).catch(a=>{a!=="destroy"&&this._log.warn(a)}),this.singlePC.addAbortController(A,o)}}initReceiverTransform(A,e,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:e}))}subscribe(A,e){return DA(this,null,function*(){var o,n;try{let a=!0;if(this._log.info("subscribe ".concat(e," ").concat(pz(A))),this.hasSSRC){let u="subscribe_change";Object.values(A).find(d=>d===!0)||(u="unsubscribe"),yield this.sendSubscription(u,A)}else{if(yield this._room.switchRoomSubedReq,(o=this.singlePC)!=null&&o.autoSubscribedUserMap.size){let u=this.singlePC.autoSubscribedUserMap.get(this.userId);if(u){this.singlePC.autoSubscribedUserMap.delete(this.userId);let d=(n=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:n[u.groupIndex];d&&(this.ssrc={audio:d.audioSsrc,video:d.bigVideoSsrc,videoRtx:d.bigVideoRtxSsrc,auxiliary:d.auxVideoSsrc,auxiliaryRtx:d.auxVideoRtxSsrc},a=!1)}}yield this.doSubscribe(A,a),this.checkTrackEnded(A)}let{user:I,mediaTrack:c}=this.remoteVideoTrack;A.smallVideo&&c?(ct.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=Fm.start({track:c,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,I),ct.addFailedEvent({key:524702}),Fm.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(Fm.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}catch(a){throw this._room.isJoined&&this.isStreamUnpublished(e)?(this._log.warn("".concat(a.message," ").concat(JSON.stringify(this.muteState))),new Ct({code:Ge.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):a}})}checkTrackEnded(A){var e,o,n;if((A.audio&&((e=this.remoteAudioTrack.mediaTrack)==null?void 0:e.readyState)==="ended"||A.video&&((o=this.remoteVideoTrack.mediaTrack)==null?void 0:o.readyState)==="ended"||A.auxiliary&&((n=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:n.readyState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Bc&&tE<92)return;this.singlePC.startReconnection()}}unsubscribe(A){return DA(this,arguments,function(e){var o=this;let{remoteTracks:n,streamType:a}=e;return function*(){var I;if(a==="main"&&!o.isMainStreamSubscribed||a==="auxiliary"&&!o.isAuxStreamSubscribed)return void o._log.info("".concat(a," stream already unsubscribed"));let c=bt({},o.subscribeState);n.forEach(d=>{switch(d.mediaType){case 1:c.audio=!1;break;case 4:c.video=!1;break;case 8:c.smallVideo=!1;break;case 2:c.auxiliary=!1}});let u="subscribe_change";Object.values(c).find(d=>d===!0)||(u="unsubscribe"),o._log.info("".concat(u==="unsubscribe"?u:"subscribe"," ").concat(a," [").concat(pz(c),"]")),u==="unsubscribe"&&((I=o.singlePC)==null||I.removeDownlinkQueue.add(o.tinyId)),yield o.sendSubscription(u,c),a==="main"&&(Fm.stop(o._blackSmallVideoDetectionId),o._blackSmallVideoDetectionId=void 0),u==="unsubscribe"&&(yield o.removeDownlink())}()})}subscribeDataChannel(){return DA(this,null,function*(){if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let A=fi(bt({},this.subscribeState),{datachannel:!0});yield this.doSubscribe(A)})}unsubscribeDataChannel(){return DA(this,null,function*(){let A=fi(bt({},this.subscribeState),{datachannel:!1});yield this.sendSubscription("unsubscribe",A),yield this.removeDownlink()})}sendSubscription(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscribeState,o={srcTinyId:this.tinyId,srcUserId:this.userId},n=aK,a=io.UNSUBSCRIBE_RESULT;return A==="subscribe_change"&&(o={audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:e.datachannel,srcTinyId:this.tinyId},n=sK,a=io.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:n,data:o,responseCommand:a,timeout:1e4,retries:3}).then(I=>{let{data:c}=I;if(c.code!==0){let u=new Ct({code:c.code,message:Wi({key:Mi.ERROR_MESSAGE,data:{type:A,message:c.message}})});throw this._log.error(u),u}})}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:e,videoDelay:o}=A;this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=o}onSinglePCReconnected(){return DA(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 DA(this,arguments,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.subscribeState,o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return function*(){var n,a;if(A.singlePC){A.singlePC.addDownlinkQueue.add(A.tinyId),yield A.singlePC.waitForPeerConnectionConnected();try{if(o||!A.hasSSRC){let I={audioSsrc:gB(),bigVideoSsrc:gB(),bigVideoRtxSsrc:gB(),auxVideoSsrc:gB(),auxVideoRtxSsrc:gB()},{audioSsrc:c,bigVideoSsrc:u,bigVideoRtxSsrc:d,auxVideoSsrc:R,auxVideoRtxSsrc:k}=I;A.ssrc={audio:c,video:u,videoRtx:d,auxiliary:R,auxiliaryRtx:k},A.singlePC.addDownlinkQueue.delete(A.tinyId),yield A.singlePC.addDownlink({userId:A.userId,tinyId:A.tinyId,ssrc:A.ssrc,prevMids:A._prevMids});try{let _=yield A._signalChannel.sendWaitForResponseWithRetry({command:Z4,responseCommand:io.SPC_SUBSCRIBE_RESULT,data:{srcUserId:A.userId,srcTinyId:A.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:(n=e.datachannel)!=null&&n,ssrc:I},retries:3,retryTimeout:0});if(_.data.code!==0&&_.data.code!==-10036)throw new Ct({code:_.data.code,message:_.data.message});A.isDataChannelSubscribed=(a=e.datachannel)!=null&&a}catch(_){throw yield A.removeDownlink(),_}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((e.audio||e.video||e.smallVideo||e.auxiliary||!e.datachannel)&&Du){let{main:I,aux:c}=A._room.jitterBufferDelay||{},{jitterDelay:u=I,jitterDelayAux:d=c}=A._room.scheduleResult.config||{};(hr(u)||hr(d))&&A.setJitterBufferDelay({mainDelay:u,auxDelay:d})}}}}()})}removeDownlink(){return DA(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:e,auxDelay:o}=A;if(!Du||!this.singlePC||!this._peerConnection||$c(e)&&$c(o))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(e," aux: ").concat(o));let n=this.singlePC.getReceiversByUserId(this.userId);return hr(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),hr(o)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=o,$c(e)&&(this.remoteAudioTrack.jitterBufferDelay=o)),new Promise(a=>{this._jitterBufferResolve=a,this.doSetJitterBufferDelay({mainDelay:e,auxDelay:o,receivers:n,resolve:a})})}doSetJitterBufferDelay(A){let{mainDelay:e,auxDelay:o,receivers:n,resolve:a}=A;try{if(e===0&&o===0)return n.forEach(I=>I.jitterBufferTarget=0),this._jitterBufferResolve=void 0,a();if(n.forEach(I=>{var c;let u=I.track===this.remoteAuxiliaryTrack.outMediaTrack||$c(e)&&I.track===this.remoteAudioTrack.outMediaTrack;if(u&&$c(o)||!u&&$c(e))return;let d=u?o||0:e,R=(I.jitterBufferTarget||0)+100;R>d||(I.jitterBufferTarget=R,this._log.debug("set ".concat(u?"aux ":"").concat((c=I?.track)==null?void 0:c.kind," jitterBuffer delay ").concat(R," -> ").concat(d)))}),!n.find(I=>{let c=I.track===this.remoteAuxiliaryTrack.outMediaTrack?o||0:e;return I.jitterBufferTarget{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:o,receivers:n,resolve:a})},1e3)}catch(I){this._log.warn("set jitterBuffer delay error: ".concat(I)),clearTimeout(this.jitterBufferTimeoutId),this._jitterBufferResolve=void 0,a()}}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()}};vt([VT(),Dn(A=>function(){for(var e=arguments.length,o=new Array(e),n=0;n{let c=u=>{this.off("closed",c),I(new Ct({code:Ge.API_CALL_ABORTED,message:Wi({key:Mi.CONNECTION_ABORTED,data:u})}))};this.on("closed",c),A.apply(this,o).then(a,I).finally(()=>{this.off("closed",c)})})})],jx.prototype,"subscribe"),vt([VT()],jx.prototype,"unsubscribe"),vt([Kh(()=>"jitter")],jx.prototype,"setJitterBufferDelay");var UtA=jx,OtA=es(hg()),fz=class t6 extends OtA.EventEmitter{constructor(e,o){super(),this.room=e,this.signalChannel=o,G(this,"log"),G(this,"cmdIdSeqMap",new Map),G(this,"messageMap",new Map),this.log=nA.createLogger({parent:e.getLogger(),id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),o.on(io.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",n=>{let{userId:a}=n;[...this.messageMap.keys()].forEach(I=>{I.split("_").slice(0,-1).join("_")===a&&this.messageMap.delete(I)})})}send(e){let{cmdId:o,data:n}=e,a=this.cmdIdSeqMap.get(o)||Math.floor(16383*Math.random()),I={cmdId:o,msg:btoa(String.fromCharCode(...new Uint8Array(n))),ordered:!0,reliable:!0,streamSeq:a};this.cmdIdSeqMap.set(o,a+1),this.signalChannel.send(rtA,I),this.log.debug("send custom msg: ".concat(JSON.stringify(I)))}onReceiveMsg(e){let{data:o}=e.data,n=this.room.tinyIdToUserIdMap.get(o.srcTinyId);if(n){let a={userId:n,cmdId:o.cmdId,seq:o.streamSeq,data:Uint8Array.from(atob(o.msg),I=>I.charCodeAt(0)).buffer};if(o.ordered){let I="".concat(n,"_").concat(a.cmdId),c=this.messageMap.get(I);if(c&&c.lastSeq!==0)if(Math.abs(c.lastSeq-a.seq)>t6.SEQ_INTERVAL)this.messageMap.set(I,{lastSeq:a.seq,cachedMessageMap:new Map}),this.emitMessage(a);else if(a.seq>c.lastSeq){if(a.seq===c.lastSeq+1)this.emitMessage(a);else if(!c.cachedMessageMap.has(a.seq)){let u=setTimeout(()=>this.emitMessage(a,!0),5e3);c.cachedMessageMap.set(a.seq,{message:a,timeoutId:u})}}else this.log.debug("drop message ".concat(a.userId,"-").concat(a.cmdId,"-").concat(a.seq));else c||(c={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(I,c),setTimeout(()=>this.emitMessage(a,!0),100)),c.cachedMessageMap.set(a.seq,{message:a})}else this.emit("message",a)}else{this.log.warn("receive msg from unknown user, wait peer-join tinyId: ".concat(o.srcTinyId));let a=I=>{I.tinyId===o.srcTinyId&&(this.room.off("peer-join",a),this.onReceiveMsg(e))};this.room.on("peer-join",a),AC(2e3).then(()=>this.room.off("peer-join",a))}}emitMessage(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var n;let a=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),I=e;if(a){if(o){let u=[...a.cachedMessageMap.values()].sort((d,R)=>d.message.seq-R.message.seq);u[0]&&(I=u[0].message)}a.lastSeq!==0&&I.seq-a.lastSeq>1&&this.log.debug("msg lost userId: ".concat(I.userId," seq: ").concat(a.lastSeq," -> ").concat(I.seq)),a.lastSeq=I.seq,clearTimeout((n=a.cachedMessageMap.get(I.seq))==null?void 0:n.timeoutId),a.cachedMessageMap.delete(I.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(I))),this.emit("message",I);let c=a?.cachedMessageMap.get(I.seq+1);c&&this.emitMessage(c.message)}};G(fz,"SEQ_INTERVAL",300);var xtA=fz,{isString:mz,isUndefined:Um,getNetworkType:YtA,isEmpty:PtA}=tl,ep=class extends wtA{constructor(A){super(A),G(this,"_businessInfo"),G(this,"userManager"),G(this,"_version"),G(this,"_heartbeat",-1),G(this,"_lastHeartBeatTime",-1),G(this,"_stats"),G(this,"_joinTimeout",-1),G(this,"_firstPublishedList",null),G(this,"_joinReject",null),G(this,"_isRelayChanged",!1),G(this,"sdpSemantics"),G(this,"signalChannel",null),G(this,"uplinkConnection",null),G(this,"singlePC",null),G(this,"enableSPC",Qm),G(this,"_changeBigSmallRecords",new Map),G(this,"networkQuality"),G(this,"_iceTransportPolicy"),G(this,"forceRelay",!1),G(this,"_turnServers",[]),G(this,"_iceServersFromJoin"),G(this,"_syncUserListInterval",-1),G(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),G(this,"enableSEI",!1),G(this,"_enableAudioVolumeEvaluation",!1),G(this,"_audioVolumeIntervalId",0),G(this,"_enableMultiAuxStream",!1),G(this,"_pureAudioPushMode",!1),G(this,"_customMessageManager"),G(this,"_enableDataChannel",!1),G(this,"preferHW",!1),G(this,"healthDetector"),G(this,"playoutDelay"),G(this,"jitterBufferDelay"),G(this,"_updateAudioLevelTaskId",-1),G(this,"switchRoomSubedReq"),G(this,"resolveSwitchRoomSubedReq"),G(this,"enableVolumeControlInIOS"),G(this,"capturedLocalMainAudioTrack"),G(this,"capturedLocalMainVideoTrack"),G(this,"capturedLocalAuxVideoTrack"),G(this,"PRELINK_EXPIRED_TIME",3e5),G(this,"PRELINK_TIMEOUT",1e4),G(this,"prelinkTimeoutId",null),G(this,"firewallDetector"),this.firewallDetector=new geA,this.firewallDetector.on("firewall-restriction",()=>{this._log.warn("firewall restriction"),this.emit("firewall-restriction")}),this._stats=new EtA(this,this._log),this.userManager=new aeA(this.userId,this._log),this._version=il,this.sdpSemantics=LR,Um(A.sdpSemantics)?kA.isUnifiedPlanDefault()&&(this.sdpSemantics=_f):this.sdpSemantics=A.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(YtA())),A.iceTransportPolicy&&(this._iceTransportPolicy=A.iceTransportPolicy),this._enableMultiAuxStream=!Um(A.enableMultiAuxStream)&&A.enableMultiAuxStream,this.enableSEI=A.enableSEI&&Qm,!Um(A.enableSPC)&&Qm&&(this.enableSPC=A.enableSPC),this.preferHW=!!A.preferHW,this.enableVolumeControlInIOS=A.enableVolumeControlInIOS,this._initBusinessInfo(A),this.healthDetector=new ktA(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,e,o){return DA(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",n=>{this.emit("peer-join",n)}),this.userManager.on("8",n=>{this.emit("asr-robot-peer-join",n)}),this.userManager.on("9",n=>{this.emit("asr-robot-peer-leave",n)}),this.userManager.on("2",n=>{let{userId:a,reason:I}=n;this.closeDownLinkConnection(a,"remote user exitRoom"),this.emit("peer-leave",{userId:a,reason:I})}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var a=PU(n,[]);S.emit(K.REMOTE_PUBLISH_STATE_CHANGED,bt({room:this},a)),this.emit("remote-publish-state-changed",bt({},a))}),this.joinParams=A,rn(A.enableDataChannel)&&(this._enableDataChannel=A.enableDataChannel),new Promise((n,a)=>DA(this,null,function*(){var I,c;this._joinReject=a;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(d){if(!(d instanceof Ct&&d.code===Ge.SPC_INITIALIZED_FAILED))return a(d);(I=this.signalChannel)==null||I.destroy(),yield this.initialize()}let u=ki();yield this.doJoin(A,(c=this.singlePC)==null?void 0:c.clientAbility),ct.addSuccessEvent({key:521708,cost:ki()-u}),n(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(u){ct.addFailedEvent({key:521708,error:u}),a(u)}this._joinReject=null}))})}initSinglePC(){return DA(this,null,function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new Ap({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 e=new TextDecoder().decode(A.data.data||A.data);try{this.emit("data-channel-message",{data:JSON.parse(e)})}catch{}});try{return yield this.singlePC.initialize()}catch(A){throw this.fallbackToMPC(),new Ct({code:Ge.SPC_INITIALIZED_FAILED,message:A?.message})}}})}doJoin(A,e){return new Promise((o,n)=>DA(this,null,function*(){var a,I,c,u,d,R,k,_;A.privateMapKey&&(this.privateMapKey=A.privateMapKey),A.latencyLevel&&(this.latencyLevel=A.latencyLevel),this.signalChannel.once(Ox,cA=>{this.clearJoinTimeout(),S.emit(K.JOIN_SIGNAL_CONNECTION_END,{room:this,error:cA}),n(cA)}),rn((I=(a=this.scheduleResult)==null?void 0:a.config)==null?void 0:I.singlePC)&&Qm&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),(!((u=(c=this.scheduleResult)==null?void 0:c.config)!=null&&u.jitterDelay)&&!((R=(d=this.scheduleResult)==null?void 0:d.config)!=null&&R.jitterDelayAux)||!Du)&&e&&this.playoutDelay&&(this._log.info("set playoutDelay",JSON.stringify(this.playoutDelay)),e.playoutDelay=this.playoutDelay);let Z={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:er(),netType:hh(),bussinessInfo:this._businessInfo,ability:e,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&yM(),transcription:this._enableDataChannel,downUseVp8:((k=this.scheduleResult.config)==null?void 0:k.downUseVp8)||!1};this._log.debug("join room signal data: ".concat(JSON.stringify(Z)));let iA=5e3;(_=this.scheduleResult.config)!=null&&_.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(iA=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout(()=>{n(new Ct({code:Ge.JOIN_ROOM_FAILED,message:Wi({key:Mi.JOIN_ROOM_TIMEOUT})}))},iA),S.emit(K.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?ttA:YeA,Z),this.signalChannel.once(io.JOIN_ROOM_RESULT,cA=>DA(this,null,function*(){this.clearJoinTimeout();let{code:TA,message:JA,data:Ie,tinyId:XA}=cA.data;S.emit(K.JOIN_RECEIVED_CMD_RES,{room:this,code:TA}),TA===0?(this._log.info("Join room success, start heartbeat"),XA&&(this.tinyId=XA),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=Ie.publishers,this._iceServersFromJoin=Ie.iceServer?[Ie.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var Ft;(Ft=this.singlePC)==null||Ft.connect(fi(bt({},Ie.ability),{useVp8:Ie.ability.useVp8||!!A.useVp8,useH265:Ie.ability.useH265&&!!A.useH265})).catch(()=>{})}),o()):(this._log.error("Join room failed result: ".concat(TA," error: ").concat(JA)),n(new Ct({code:Ge.JOIN_ROOM_FAILED,extraCode:TA,message:Wi({key:Mi.JOIN_ROOM_FAILED,data:{error:JA,code:TA}})})))}))}))}reJoin(){return DA(this,null,function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this.joinParams.roomId));let A,e=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,e.push(this.initSinglePC().then(o=>(A=o,o)))),this.signalChannel&&(this.signalChannel.close(),e.push(this.signalChannel.connect())),yield Promise.all(e),yield this.doJoin(fi(bt({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),A),this._log.warn("reJoin success"),Jo.logSuccessEvent({userId:this.userId,eventType:oa.REJOIN}),this.singlePC){let o=n=>{var a;n.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(VM.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof hz&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(I=>{I.installEvents(),I.onSinglePCReconnected()}))};this.singlePC.on(VM.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Vx&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(A){this._log.warn("reJoin fail ".concat(A)),this.reset(),Jo.logFailedEvent({userId:this.userId,eventType:oa.REJOIN,error:A}),this.emit("error",new Ct({code:Ge.JOIN_ROOM_FAILED,message:Wi({key:Mi.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")})}initialize(A){return DA(this,null,function*(){var e,o;if(!(A!=null&&A.isPrelink)&&this.prelinkPromise&&(yield this.prelinkPromise),(e=this.signalChannel)!=null&&e.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 n,{mainUrl:a,backupUrl:I}=this.getSignalChannelUrl(),c=this.signalChannel||function(d){return[...Px.values()].find(k=>k.room.userId===d&&!k.room.isJoined)||null}(this.userId),u=!!(c&&c.isConnected&&c.keepAlive&&c.userId===this.userId);return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info("".concat(u?"reuse":"setup"," signal channel")),u?(c.url=a,c.backupUrl=I,c.room.setSignalChannel(null),c.room=this,this.signalChannel=c):(c&&c.close(),this.signalChannel=new X4({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:a,backupUrl:I,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0,prelink:A?.isPrelink}),this._customMessageManager=new xtA(this,this.signalChannel),this._customMessageManager.on("message",d=>{this.emit("custom-message",d)})),this.networkQuality||(this.networkQuality=new iz({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(iz.EVENT_NETWORK_QUALITY,d=>{var R;this.emit("network-quality",d),(R=this.singlePC)==null||R.detectTCPAndUDP(d)})),nE(this,this.signalChannel).add(rK,d=>{S.emit(K.SIGNAL_CONNECTION_STATE_CHANGED,bt({room:this},d)),this.emit("signal-connection-state-changed",d)}).add(UeA,d=>{this.reset(),this.emit("error",d)}).add(io.PEER_JOIN,d=>{let{srcTinyId:R,userId:k,role:_,fromType:Z}=d.data.data;this.userManager.addUser({userId:k,tinyId:R,role:_,fromType:Z})}).add(io.PEER_LEAVE,d=>{let{userId:R,reason:k=0}=d.data.data;this.userManager.deleteUser(R,k)}).add(io.UPDATE_REMOTE_MUTE_STAT,d=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(d.data)}).add(io.CLIENT_BANNED,d=>{let R=d.data.data,{reason:k}=R;if(Jo.uploadEvent({log:"stat-banned:".concat(k),userId:this.userId}),k==="user_time_out")return this._log.warn("".concat(k," last heart beat time: ").concat(this._lastHeartBeatTime," interval: ").concat(Date.now()-this._lastHeartBeatTime,", visibility: ").concat(document.visibilityState)),void this.reJoin();this._log[k==="kick"?"error":"info"]("user was banned because of [".concat(k,"]")),this.reset(),this.emit("banned",{reason:k})}).add(io.SEND_SWITCH_ROOM_SUBED_REQ,d=>{if(!this.singlePC)return;let{subList:R}=d.data.data;this._log.info("auto subscribe ".concat(nl(R,{keysToInclude:["userId"]}))),R.forEach(k=>{this.singlePC.autoSubscribedUserMap.set(k.userId,k)}),this.resolveSwitchRoomSubedReq()}).add(io.FALLBACK_CODEC,d=>DA(this,null,function*(){var R,k,_,Z,iA;let cA=d.data.data;((R=cA.videoControlInfo)==null?void 0:R.enableH265Enc)===0&&((k=this.singlePC)==null?void 0:k.videoCodec)==="h265"&&(this._log.warn("fallback codec enableH265Enc: ".concat((_=cA.videoControlInfo)==null?void 0:_.enableH265Enc)),ct.addCount({key:513e3}),yield(Z=this.singlePC)==null?void 0:Z.switchVideoEncoder("h264"),yield(iA=this.uplinkConnection)==null?void 0:iA.sendMediaSettings())})),this.signalChannel.once(H4,d=>{this.tinyId=d.signalInfo.tinyId,S.emit(K.JOIN_SIGNAL_CONNECTION_END,{room:this})}),S.emit(K.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),u&&S.emit(K.JOIN_SIGNAL_CONNECTION_END,{room:this}),u})}setSignalChannel(A){this.signalChannel=A,A||pr(this)}leave(){return DA(this,null,function*(){var A;try{yield this.doHeartbeat()}catch{}this._log.info("leave() => leaving room"),S.emit(K.LEAVE_SEND_CMD,{room:this}),(A=this.signalChannel)==null||A.send(PeA),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=nn.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),nn.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return DA(this,null,function*(){var A;let e=this.badCaseDetector.getMonitorFreeze(),o=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let n=(A=this.signalChannel)!=null&&A.isConnected?function(I){if(UM.has(I)){let c=UM.get(I).map(u=>({uint32_event_id:u.eventId,uint64_date:u.timestamp,str_userid:u.remoteUserId,uint32_param1:u.param1,uint32_param2:u.param2,uint32_video_stream_type:u.streamType}));return UM.delete(I),c}return[]}(this.userId):[],a=fi(bt({str_sdk_version:wR,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:n,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},o),{msg_device_info:bt({uint32_terminal_type:15,str_device_name:Qu(),str_os_version:"",uint32_net_type:hh()},o.msg_device_info)});if(this.heartbeatReport=a,this.heartbeatCount++,S.emit(K.HEARTBEAT_REPORT,{room:this,report:a}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(JeA,a);let I=Date.now();this._lastHeartBeatTime>0&&I-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(I-this._lastHeartBeatTime)),this._lastHeartBeatTime=I,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",fi(bt({},a),{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 e=!1,o=A.data.userList||[],n=A.data.mixRobotList||[],a=[];for(let c of o){if(c.flag===hN)continue;let{userId:u,srcTinyId:d,flag:R,fromType:k}=c;u===this.userId&&(e=!0,this.uplinkConnection&&(this.uplinkConnection.flag=R),this.localPublishFlag!==R&&(this.localPublishFlag=R,this.emit("local-publish-flag-changed",R))),a.push({userId:u,tinyId:d,flag:R,fromType:k})}let I=[...n.map(c=>{let{userId:u,srcTinyId:d,flag:R,mixUserList:k,fromType:_}=c;return{userId:u,tinyId:d,flag:R,isRobot:!0,mixUserList:k,fromType:_}}),...a];I.forEach(c=>{let{userId:u}=c,d=this.remotePublishedUserMap.get(u);d&&this.checkSubscribeBigSmallVideo(d)}),A.data.fakeMixUser&&(A.data.fakeMixUser.tinyId=A.data.fakeMixUser.srcTinyId,I.push(A.data.fakeMixUser)),S.emit(K.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:I}),e||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),this.userManager.setRemotePublishedUserList(I)}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 Vx&&(this.uplinkConnection=null)),this.localTracks.forEach(e=>e.unpublish()),this.localTracks.clear()}createDownlinkConnection(A){let{userId:e,tinyId:o,flag:n,isRobot:a,fromType:I}=A,c=new(this.singlePC?UtA:ez)({userId:e,tinyId:o,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:n,isRobot:a,fromType:I});this.userManager.addRemotePublishedUser(c),this.installDownlinkEvents(c,e),this.emit("remote-published",c)}closeDownLinkConnection(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"remote user unpublished",o=this.remotePublishedUserMap.get(A);o&&(o.close(e),this.emit("remote-unpublished",o))}installDownlinkEvents(A,e){A.on("error",o=>{let n=o.getCode();n!==Ge.ICE_TRANSPORT_ERROR&&(n===Ge.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(e),this.emit("error",o))}),A.on("connection-state-changed",o=>{this.emit("media-connection-state-changed",fi(bt({},o),{userId:A.userId}))})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=nn.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){nn.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:$eA,responseCommand:io.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(e=>{let{data:o}=e,{code:n,message:a}=o;if(n===0)return(o.data&&o.data.userList||[]).map(I=>{let{userId:c,srcTinyId:u,role:d,fromType:R}=I;return{userId:c,tinyId:u,role:d,fromType:R}});throw Wi({key:Mi.SIGNAL_RESPONSE_FAILED,data:{signalResponse:io.USER_LIST_RES,code:n,message:a}})}):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||!$4)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let A=this.getAllConnections();if(A.length===0)return!1;for(let e=0;e{if(e instanceof WQ&&!e.getIsReconnecting()){let o=e.getPeerConnection();o&&o.connectionState===hi.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}})}fallbackToMPC(){return DA(this,null,function*(){var A;if(this._log.warn("fallback to multi pc"),Jo.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 e=this.uplinkConnection;this.uplinkConnection=new Vx({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),e.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localMainAudioTrack,localVideoTrack:e.localMainVideoTrack,isAuxiliary:!1})),e.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localAuxAudioTrack,localVideoTrack:e.localAuxVideoTrack,isAuxiliary:!0})),e.close()}for(let e of[...this.remotePublishedUserMap.values()]){let o=new ez({userId:e.userId,tinyId:e.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:e.flag,remoteAudioTrack:e.remoteAudioTrack,remoteVideoTrack:e.remoteVideoTrack,remoteAuxiliaryTrack:e.remoteAuxiliaryTrack});this.installDownlinkEvents(o,e.userId),this.remotePublishedUserMap.set(e.userId,o),e.isMainStreamSubscribed&&(yield o.subscribe(e.subscribeState,"main")),e.isAuxStreamSubscribed&&(yield o.subscribe(e.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 Ct({code:Ge.INVALID_OPERATION,message:Wi({key:Mi.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.firewallDetector.destroy(),this.removeAllListeners(),this.healthDetector.destroy(),nn.clearTask(this._audioVolumeIntervalId))}switchRole(A){return DA(this,null,function*(){this.role!==A&&(A==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(A))})}doSwitchRole(A){let e={command:AtA,data:{role:A==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:io.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(e.data))),this.signalChannel.sendWaitForResponseWithRetry(e).then(o=>{let{code:n,message:a}=o.data;if(n!==0)throw new Ct({code:Ge.SWITCH_ROLE_FAILED,message:Wi({key:Mi.SWITCH_ROLE_FAILED,data:{message:a,code:n}})});this.role=A}).catch(o=>{throw o instanceof Ct&&o.getCode()===Ge.API_CALL_TIMEOUT&&(o=new Ct({code:Ge.SWITCH_ROLE_FAILED,message:Wi({key:Mi.SWITCH_ROLE_TIMEOUT})})),this._log.error(o),o})}subscribeDataChannel(){return DA(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let A=[...this.remotePublishedUserMap.values()].filter(e=>e.fromType===xR);this._log.info("subscribeDataChannel",A.map(e=>e.userId)),yield Promise.all(A.map(e=>DA(this,null,function*(){try{yield e.subscribe(fi(bt({},e.subscribeState),{datachannel:!0}),"main")}catch(o){this._log.error("subscribeDataChannel failed:",e.userId,o)}})))})}unsubscribeDataChannel(){return DA(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let A=[...this.remotePublishedUserMap.values()].filter(e=>e.fromType===xR);this._log.info("unsubscribeDataChannel",A.map(e=>e.userId)),yield Promise.all(A.map(e=>e.unsubscribeDataChannel()))})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new hz({userId:this.userId,tinyId:this.tinyId,room:this}):new Vx({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",fi(bt({},A),{userId:this.userId}))}),this.uplinkConnection.on("error",A=>{let e=A.getCode();e!==Ge.ICE_TRANSPORT_ERROR&&(e===Ge.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",A))})}publish(A){return DA(this,null,function*(){var e;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(e=this.singlePC)==null?void 0:e.waitForPeerConnectionConnected(),yield this.uplinkConnection.publish({localAudioTrack:A instanceof vm?A:null,localVideoTrack:A instanceof Ru?A:null,isAuxiliary:A.streamType==="auxiliary"})})}unpublish(A){return DA(this,null,function*(){if((this.scene!=="live"||this.role==="anchor")&&(this.isMainStreamPublished||this.isAuxStreamPublished)&&this.uplinkConnection){try{let e="".concat(A.streamType," ").concat(A.isAudio&&A.isScreen?"screen":"").concat(A.kind);this._log.info("unpublish() => ".concat(e)),yield this.uplinkConnection.unpublish({localAudioTrack:A instanceof vm?A:null,localVideoTrack:A instanceof Ru?A:null})}catch{}this.localTracks.size===0&&this.closeUplink("you unpublished")}})}addTrack(A){if(!this.uplinkConnection||!A.mediaTrack)return Promise.resolve();let e=this.uplinkConnection.addTrack(A);return A.publish(this,e),e}removeTrack(A){return this.uplinkConnection&&A.mediaTrack?(A.unpublish(),this.uplinkConnection.removeTrack(A)):Promise.resolve()}replaceTrack(A){return this.uplinkConnection&&A.mediaTrack&&XO()?this.uplinkConnection.replaceTrack(A).then(e=>{e&&S.emit(K.LOCAL_TRACK_REPLACED,{track:A})}):Promise.resolve()}setBandWidth(A){return DA(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(A),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(A){return DA(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();A&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:fA.VIDEO,videoType:fA.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(A)})}subscribe(){for(var A=arguments.length,e=new Array(A),o=0;o!c.isSubscribed),e.length===0)return;let{userId:n}=e[0],a=this.remotePublishedUserMap.get(n);if(!a)return;let I=e.find(c=>c.mediaType===2)?"auxiliary":"main";try{let c=bt({},a.subscribeState);e.forEach(d=>{switch(d.mediaType){case 1:c.audio=!0;break;case 4:c.video=!0;break;case 8:c.smallVideo=!0;break;case 2:c.auxiliary=!0}});let u=this._changeBigSmallRecords.get(n);u&&u.options.smallVideo&&a.muteState.hasSmall&&c.video&&(c.video=!1,c.smallVideo=!0),S.emit(K.SUBSCRIBE_START,{room:this,streamType:I,remotePublishedUser:a,subscribeState:c}),this._log.info("subscribe() => ".concat(n," ").concat(I," ").concat(e.map(d=>d.strMediaType).join(",")," [").concat(IK(c),"] prev: [").concat(IK(a.subscribeState),"]")),yield a.subscribe(c,I),this._log.info("subscribe ".concat(n," ").concat(I," done"));for(let d of e)d.mediaTrack||(yield d.waitHasMediaTrack());S.emit(K.SUBSCRIBE_SUCCESS,{room:this,streamType:I,remotePublishedUser:a})}catch(c){let u=c instanceof Ct?c.getCode():Ge.UNKNOWN,d=c;throw c instanceof Ct?u===Ge.REMOTE_STREAM_NOT_EXIST&&(d=new Ct({code:Ge.API_CALL_ABORTED,message:Wi({key:Mi.API_CALL_ABORTED,data:{message:c.message,userId:n,streamType:I}})}),this._log.warn(d)):(d=new Ct({code:u,message:Wi({key:Mi.SUBSCRIBE_FAILED,data:{message:c.message,userId:n,streamType:I}})}),this._log.error(d)),d}})}unsubscribe(){for(var A=arguments.length,e=new Array(A),o=0;oc.mediaType===2)?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(n," ").concat(I," ").concat(e.map(c=>c.strMediaType).join(",")));try{yield a.unsubscribe({remoteTracks:e,streamType:I})}catch(c){this._log.warn("unsubscribe() => failed ".concat(c))}e.forEach(c=>{c.unsubscribe(),c.mediaType===8&&c.setMediaType(4)}),S.emit(K.UNSUBSCRIBE_SUCCESS,{room:this,streamType:I,remotePublishedUser:a})})}setEncodedDataProcessingListener(A){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3,e=arguments.length>1?arguments[1]:void 0;if(A<=0)return this._enableAudioVolumeEvaluation=!1,void nn.clearTask(this._audioVolumeIntervalId);A=Math.floor(Math.max(A,100)),S.emit(K.AUDIO_LEVEL_INTERVAL,{interval:A}),this._audioVolumeIntervalId&&nn.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=nn.run("intervalInWorker",()=>{var o;gx.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(A,e);let n=[];(o=this.remotePublishedUserMap)==null||o.forEach(a=>{if(a.muteState.hasAudio){!gx.isRunning&&a.muteState.audioAvailable&&a.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(a):a.remoteAudioTrack.volume=0;let I=Math.floor(100*a.remoteAudioTrack.getAudioLevel());n.push({userId:a.userId,volume:I,floatVolume:a.remoteAudioTrack.getInternalAudioLevel()})}}),this.emit("audio-volume",n)},{delay:A,backgroundTask:e})}updateAudioLevelFromSenderStat(A,e){return DA(this,null,function*(){var o;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let n=(o=this.uplinkConnection.getPeerConnection())==null?void 0:o.getSenders()[0];if(!n)return;let a=Math.max(A,500);this._log.warn("updateAudioLevelFromSenderStat ".concat(a)),this._updateAudioLevelTaskId=nn.run("intervalInWorker",()=>DA(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack)return void this.stopUpdateAudioLevelFromSenderStat();let I=yield n.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:c}=this.uplinkConnection;I.forEach(u=>{u.type==="media-source"&&u.audioLevel&&(c.volume=u.audioLevel)})}),{delay:a,backgroundTask:e})})}stopUpdateAudioLevelFromSenderStat(){var A;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),nn.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(A=this.uplinkConnection)!=null&&A.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(A){var e;let{audioReceiver:o}=A;if(!GT||!o)return;let n=(e=o.getSynchronizationSources()[0])==null?void 0:e.audioLevel;hr(n)?A.remoteAudioTrack.volume=Math.min(2*n,1):o.getStats().then(a=>{a.forEach(I=>{I.type==="inbound-rtp"&&hr(I.audioLevel)&&(A.remoteAudioTrack.volume=I.audioLevel)})})}getLocalAudioStats(){return DA(this,null,function*(){var A;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(A=this.uplinkConnection)!=null&&A.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return DA(this,null,function*(){var A,e;let o={};return o[this.userId]=((e=(A=this.uplinkConnection)==null?void 0:A.localMainVideoTrack)==null?void 0:e.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},o})}getTransportStats(){return DA(this,null,function*(){let A={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let e=yield this._stats.getSenderStats(this.uplinkConnection);A.rtt=e.rtt}for(let[,e]of this.remotePublishedUserMap){let o=yield this._stats.getReceiverStats(e);A.downlinksRTT[o.userId]=o.rtt}return A})}getRemoteVideoStats(A){return DA(this,null,function*(){let e={};for(let[o,n]of this.remotePublishedUserMap)A==="main"&&n.muteState.hasVideo&&(e[o]=n.remoteVideoTrack.stat),A==="auxiliary"&&n.muteState.hasAuxiliary&&(e[o]=n.remoteAuxiliaryTrack.stat);return e})}getRemoteAudioStats(){return DA(this,null,function*(){let A={};for(let[e,o]of this.remotePublishedUserMap)o.muteState.hasAudio&&(A[e]=o.remoteAudioTrack.stat);return A})}setTurnServer(A,e){this._log.info("set turn server: ".concat(JSON.stringify(A)," ").concat(e||""));let o=[];Array.isArray(A)?A.forEach(n=>o.push(tl.getTurnServer(n))):tl.isPlainObject(A)&&o.push(tl.getTurnServer(A)),this._turnServers=o,e&&(this._iceTransportPolicy=e)}sendStartMixTranscode(A){return this.signalChannel.sendWaitForResponse({command:jeA,data:A,timeout:5e3,responseCommand:io.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(e=>{if(e.code!==Ge.API_CALL_ABORTED)throw e})}sendStopMixTranscode(A){return this.signalChannel.sendWaitForResponse({command:WeA,data:A,timeout:5e3,responseCommand:io.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(e=>{if(e.code!==Ge.API_CALL_ABORTED)throw e})}sendStartPublishCDN(A){let e=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:e?HeA:qeA,data:A,timeout:5e3,responseCommand:e?io.START_PUBLISH_TENCENT_CDN_RES:io.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(o=>{if(o.code!==Ge.API_CALL_ABORTED)throw o})}sendStopPublishCDN(A){let e=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:e?VeA:KeA,data:A,timeout:5e3,responseCommand:e?io.STOP_PUBLISH_TENCENT_CDN_RES:io.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(o=>{if(o.code!==Ge.API_CALL_ABORTED)throw o})}sendStartPushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:zeA,data:A,timeout:5e3,responseCommand:io.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(e=>{if(e.code!==Ge.API_CALL_ABORTED)throw e})}sendUpdatePushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:ZeA,data:A,timeout:5e3,responseCommand:io.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(e=>{if(e.code!==Ge.API_CALL_ABORTED)throw e})}sendStopPushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:XeA,data:A,timeout:5e3,responseCommand:io.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(e=>{if(e.code!==Ge.API_CALL_ABORTED)throw e})}sendAbilityStatus(A){var e;(e=this.signalChannel)==null||e.sendWaitForResponse({command:itA,data:A,timeout:5e3,responseCommand:io.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(o=>{})}getIceServers(A){var e,o;return this._turnServers.length>0?this._turnServers:(e=this.scheduleResult.iceServers)!=null&&e.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:""},e=tl.getEnv();return e?(A.mainUrl="wss://".concat(tl.getTestSignalDomain(e)),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,e,o,n,a,I){return DA(this,null,function*(){var c;if(this.isJoined)throw new Ct({code:Ge.INVALID_OPERATION,message:"already joined room"});if(!a&&!I)throw new Ct({code:Ge.INVALID_OPERATION,message:"roomId or strRoomId is required"});if((c=this.signalChannel)!=null&&c.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=e,this.sdkAppId=A,this.userSig=o,this.roomId=String(a||I),this.useStringRoomId=!(!I||a),this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.prelinkPromise=Promise.race([this.doPrelink(A,e,o,n,a,I),new Promise((u,d)=>{this.prelinkTimeoutId=setTimeout(()=>{d(new Ct({code:Ge.INVALID_OPERATION,message:"prelink timeout after ".concat(this.PRELINK_TIMEOUT,"ms")}))},this.PRELINK_TIMEOUT)})]).then(()=>{this.clearPrelinkTimeout()}).catch(u=>{throw this.clearPrelinkTimeout(),this.closePrelink().catch(()=>{}),u}),this.prelinkPromise})}doPrelink(A,e,o,n,a,I){return DA(this,null,function*(){var c,u,d;try{if(!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!tl.getEnv()&&(yield this.schedule({sdkAppId:A,userId:e,userSig:o,roomId:a,strRoomId:I,role:20,privateMapKey:null,businessInfo:null,streamId:null,userDefineRecordId:null},n)),(c=this.scheduleResult.config)==null||!c.prelink)throw new Ct({code:Ge.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}),(u=this.signalChannel)==null||u.markPrelinkConnected({sdkAppId:A,userId:e,userSig:o}),(d=this.signalChannel)==null||d.stopPrelinkIn(this.PRELINK_EXPIRED_TIME/1e3),this._log.info("prelink success")}catch(R){throw this._log.error("prelink failed",R),R}})}clearPrelinkTimeout(){this.prelinkTimeoutId&&(clearTimeout(this.prelinkTimeoutId),this.prelinkTimeoutId=null)}closePrelink(){return DA(this,null,function*(){var A;if(this.isJoined)throw new Ct({code:Ge.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 DA(this,null,function*(){let{subscribeState:e,userId:o,muteState:{hasSmall:n,hasVideo:a}}=A;if(!n&&!a||!e.video&&!e.smallVideo)return;let I=this._changeBigSmallRecords.get(o);if(!I||I.isSubscribing||I.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:u}=I;if(c.video&&e.video||c.smallVideo&&e.smallVideo&&n)return;let d={audio:A.remoteAudioTrack.isSubscribed||A.remoteAudioTrack.isSubscribing,auxiliary:A.remoteAuxiliaryTrack.isSubscribed||A.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo,datachannel:A.subscribeState.datachannel};try{if(!n&&d.smallVideo&&(d.video=!0,d.smallVideo=!1),d.smallVideo===e.smallVideo&&d.video===e.video)return;I.isSubscribing=!0,I.reSubscribeCount=u-1,yield A.subscribe(d,"main"),A.remoteVideoTrack.setMediaType(d.smallVideo?8:4),this._log.info("change [".concat(o,"] to ").concat(d.smallVideo?"small":"big"," video successfully. count ").concat(Lf-I.reSubscribeCount,".")),I.isSubscribing=!1,I.reSubscribeCount=Lf}catch(R){this._log.info("change [".concat(o,"] to ").concat(d.smallVideo?"small":"big"," video failed. count ").concat(Lf-I.reSubscribeCount,". reason: ").concat(R)),I.isSubscribing=!1,I.reSubscribeCount===0&&this._changeBigSmallRecords.delete(o)}})}changeType(A,e){let o={options:{video:!A,smallVideo:A},isSubscribing:!1,reSubscribeCount:Lf};this._changeBigSmallRecords.set(e.userId,o),this._log.info("set [".concat(e.userId,"] video prefer type: ").concat(A?"small":"big")),this.emit("subscribe-small-video-changed",{userId:e.userId,isSmall:A});let n=this.remotePublishedUserMap.get(e.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(A){this._businessInfo=A.businessInfo;let e={};if(mz(A.businessInfo)&&(e=JSON.parse(A.businessInfo)),!Um(A.pureAudioPushMode)){if(!Number.isInteger(Number(A.pureAudioPushMode)))throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_PURE_AUDIO})});this._pureAudioPushMode=A.pureAudioPushMode,e.Str_uc_params||(e.Str_uc_params={}),e.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!Um(A.userDefineRecordId)){let o=/^[A-Za-z0-9_-]{1,64}$/gi;if(A.userDefineRecordId.match(o)===null)throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_USER_DEFINE_RECORDID})});e.Str_uc_params||(e.Str_uc_params={}),e.Str_uc_params.userdefine_record_id=A.userDefineRecordId}if(!Um(A.userDefinePushArgs)){if(!(mz(A.userDefinePushArgs)&&String(A.userDefinePushArgs)&&String(A.userDefinePushArgs).length<=256))throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_USER_DEFINE_PUSH_ARGS})});e.Str_uc_params||(e.Str_uc_params={}),e.Str_uc_params.userdefine_push_args=A.userDefinePushArgs}PtA(e)||(this._businessInfo=JSON.stringify(e))}sendCustomMessage(A){var e;(e=this._customMessageManager)==null||e.send(A)}enableInsertableStreams(){return DA(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&xQ)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(A){var e;return this.signalChannel?(e=this.signalChannel)==null?void 0:e.sendWaitForResponseWithRetry(A):Promise.reject(new Ct({code:Ge.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 DA(this,null,function*(){var e;if(!this.signalChannel||!this.singlePC)return;let{roomId:o,strRoomId:n,userSig:a,privateMapKey:I}=A,c=((e=this.scheduleResult.config)==null?void 0:e.autoSubscribeCount)||A?.autoSubscribeCount||1,u=String(this.useStringRoomId?n:o),d=[];for(let Z=0;Z{this.resolveSwitchRoomSubedReq=Z,AC(5e3).then(Z)}),S.emit(K.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();try{this.userManager.clear(),k=yield this.signalChannel.sendWaitForResponse({command:ntA,responseCommand:io.SEND_SWITCH_ROOM_RES,data:R});let{code:Z,message:iA}=k.data;if(Z!==0){this._log.error("switch room failed. result: ".concat(Z," error: ").concat(iA));let cA=new Ct({code:Ge.SWITCH_ROOM_FAILED,extraCode:Z,message:iA});throw S.emit(K.SWITCH_ROOM_FAILED,{room:this,error:cA}),cA}this.userSig=a,Um(I)||(this.privateMapKey=I),S.emit(K.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:_,targetRoomId:u})}catch(Z){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=_,this.resolveSwitchRoomSubedReq(),Z}})}isSwitchRoomSupported(){var A;let e="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(e," Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.")),!1):this.scene!=="live"?(this._log.warn("".concat(e," Reason: the scene is not 'live'.")),!1):this.role!=="audience"?(this._log.warn("".concat(e," Reason: the role is not 'audience'.")),!1):!!this.singlePC||(this._log.warn("".concat(e," 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 e=0;e<5;e++)A.push(this.updateNTPTime());return Promise.all(A).then(e=>{var o;let n=e[0].offset,a=e[0].offset;e.forEach(u=>{n=Math.min(u.offset,n),a=Math.max(u.offset,a)});let I=Math.floor(e.reduce((u,d)=>u+d.rtt,0)/e.length),c=Math.floor(e.reduce((u,d)=>u+d.offset,0)/e.length);(a-n>30||I>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),iu(c),(o=this.scriptTransformWorker)==null||o.postMessage({type:"ntp-offset",data:c}),this._log.debug("ntp updated offset: ".concat(c)),this.emit("ntp-time-updated")}).catch(e=>{this._log.warn("ntp updated failed: ".concat(e))})}updateNTPTime(){let A=Date.now();return this.signalChannel.sendWaitForResponse({command:atA,responseCommand:io.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(A)},enableLog:!1}).then(e=>{let o=Number(e.data.data.serverSendTime),n=Number(e.data.data.serverRecvTime),a=e.data.receiveTime||Date.now();return{rtt:a-A-(n-o),offset:(n-A+(o-a))/2}})}};return vt([is(["left",Uo.INIT],"joined"),nB({settings:{retries:1,timeout:0},onRetrying(A){this._log.warn("join retry ".concat(A))},onRetryFailed(A){this._log.error("join failed",A)},onError(A,e){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),wu(!0),this.reset(),e()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),e()):(this.reset(),e())}}),Dn(A=>{let e=new beA;return function(o,n,a){return DA(this,null,function*(){let I=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=n,o.privateMapKey=o.privateMapKey||"",this.isJoined)throw new Ct({code:Ge.INVALID_OPERATION,message:Wi({key:Mi.INVALID_JOIN})});if(this.checkDestroy(),e.isJoined({userId:this.userId,roomId:I,sdkAppId:this.sdkAppId,room:this}))throw new Ct({code:Ge.INVALID_OPERATION,message:Wi({key:Mi.REPEAT_JOIN,data:this.userId})});e.add({room:this,roomId:I}),this.role=o.role===21?"audience":"anchor",this._log.info("Join() => joining room: ".concat(I," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),S.emit(K.JOIN_START,{room:this,roomId:I,params:o});let c=tl.getEnv();c||(c=ou.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Ih.OLD_CLOUD_LADDER)?c=ou.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Ih.WEBRTC)&&(c=ou.WEBRTC))),Jo.setConfig({env:c,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:I}),kA.checkSystemRequirementsInternal(a).then(u=>{this.checkSystemResult=u,LeA.call(this)});try{!this.prelinkPromise&&!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!tl.getEnv()&&(yield this.schedule(o,a));let u=yield A.call(this,o,n,a);return this.roomId=I,this._joinedTimestamp=tl.performanceNow(),S.emit(K.JOIN_SUCCESS,{room:this}),a===30&&!o.component&&Jo.uploadEvent({log:"stat-conv-".concat(Number(GQ),"-").concat(location.hostname),userId:this.userId}),u}catch(u){throw e.delete({room:this,roomId:I}),S.emit(K.JOIN_FAILED,{room:this,error:u}),u}})}})],ep.prototype,"join"),vt([is("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Dn(A=>function(){for(var e=arguments.length,o=new Array(e),n=0;nA.mediaType),Dn(A=>function(){for(var e=arguments.length,o=new Array(e),n=0;nI.outMediaTrack&&I.state==="ready"),!o.length))return;S.emit("61",{room:this});let a=A.apply(this,o);return Promise.all(o.map(I=>I.publish(this,a)))})}),nB({settings:{retries:Ch,timeout:A=>fQ(A)},onError(A,e,o,n){let[a]=n;var I;(I=A.message)!=null&&I.includes("timeout")?(this._log.warn("publish ".concat(a.strMediaType," timeout"),A),e()):(this._log.error("publish ".concat(a.strMediaType," failed: ").concat(A)),o(A),S.emit(K.PUBLISH_FAILED,{room:this}))}})],ep.prototype,"publish"),vt([TM({fnName:"publish"}),Kh(A=>A.mediaType),Dn(A=>function(){for(var e=arguments.length,o=new Array(e),n=0;nI.unpublish()),a}),wm(function(){var A,e;this.localTracks.size===0&&AI()&&((e=(A=this.singlePC)==null?void 0:A.getPeerConnection())==null||e.getSenders().forEach(o=>o.track&&o.replaceTrack(null)))})],ep.prototype,"unpublish"),vt([wW(A=>{if(A.code!==Ge.API_CALL_ABORTED)throw A}),Kh(A=>A.userId)],ep.prototype,"replaceTrack"),vt([Kh(function(){for(var A=arguments.length,e=new Array(A),o=0;ofunction(){for(var e=arguments.length,o=new Array(e),n=0;n!I.isSubscribed&&I.subscribe(a)),a}),nB({settings:{retries:Ch,timeout:A=>fQ(A)},onError(A,e,o,n){if(A.message.includes("timeout"))this._log.warn("subscribe timeout"),e();else{let a=A?.code===Ge.API_CALL_ABORTED;this._log[a?"warn":"error"]("subscribe failed ".concat(n.map(I=>I.strMediaType).join(","),": ").concat(A)),o(A),S.emit(K.SUBSCRIBE_FAILED,{room:this,remoteTracks:n})}}})],ep.prototype,"subscribe"),vt([TM({fnName:"subscribe",callback(){for(var A=arguments.length,e=new Array(A),o=0;o{let a=this.remotePublishedUserMap.get(n.userId);a&&!a.isMainStreamSubscribed&&!a.isAuxStreamSubscribed&&a.close("you unsubscribed")})}}),Kh(function(){for(var A=arguments.length,e=new Array(A),o=0;oi in t?pY(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,krA=(t,i)=>{for(var r in i||(i={}))r6.call(i,r)&&Rj(t,r,i[r]);if(E5)for(var r of E5(i))GrA.call(i,r)&&Rj(t,r,i[r]);return t},_rA=(t,i)=>function(){return i||(0,t[o6(t)[0]])((i={exports:{}}).exports,i),i.exports},brA=(t,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let g of o6(i))r6.call(t,g)||g===r||pY(t,g,{get:()=>i[g],enumerable:!(s=i6(i,g))||s.enumerable});return t},LrA=(t,i,r)=>(r=t!=null?NrA(TrA(t)):{},brA(pY(r,"default",{value:t,enumerable:!0}),t)),gw=(t,i,r,s)=>{for(var g,B=i6(i,r),Q=t.length-1;Q>=0;Q--)(g=t[Q])&&(B=g(i,r,B)||B);return B&&pY(i,r,B),B},rr=(t,i,r)=>Rj(t,typeof i!="symbol"?i+"":i,r),FrA=_rA({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(t,i){var r=Object.prototype.hasOwnProperty,s="~";function g(){}function B(M,v,U){this.fn=M,this.context=v,this.once=U||!1}function Q(M,v,U,AA,z){if(typeof U!="function")throw new TypeError("The listener must be a function");var sA=new B(U,AA||M,z),eA=s?s+v:v;return M._events[eA]?M._events[eA].fn?M._events[eA]=[M._events[eA],sA]:M._events[eA].push(sA):(M._events[eA]=sA,M._eventsCount++),M}function f(M,v){--M._eventsCount===0?M._events=new g:delete M._events[v]}function m(){this._events=new g,this._eventsCount=0}Object.create&&(g.prototype=Object.create(null),new g().__proto__||(s=!1)),m.prototype.eventNames=function(){var M,v,U=[];if(this._eventsCount===0)return U;for(v in M=this._events)r.call(M,v)&&U.push(s?v.slice(1):v);return Object.getOwnPropertySymbols?U.concat(Object.getOwnPropertySymbols(M)):U},m.prototype.listeners=function(M){var v=s?s+M:M,U=this._events[v];if(!U)return[];if(U.fn)return[U.fn];for(var AA=0,z=U.length,sA=new Array(z);AA{if(!navigator.userAgent.includes("Firefox"))return t;const i=t.split(`\r + `],{type:"application/javascript"}),e=URL.createObjectURL(A);this.worker=new Worker(e),URL.revokeObjectURL(e),this.worker.onerror=o=>this._log.warn("worker error:",o.message,o.filename||"unknown",o.lineno||"unknown"),this.worker.onmessage=o=>{var n;let{type:a,trackId:I,message:c,count:u}=o.data;if(a==="black")(n=this.callbacks.get(I))==null||n();else if(a==="log")this._log.warn(c);else if(a==="blackCount"){let d=this.userIdMap.get(I);this._log.warn("".concat(d||I," black count: ").concat(u))}}}return this.worker}start(A){let{track:e,isUplink:o,room:n,userId:a,onBlack:I}=A;if(this._log.debug("start detect black video",e.id),!um()||!I||!e||typeof Worker>"u")return void this._log.warn("black video detector not supported");let c=u=>{var d,R,k,_;let Z;if(o)Z=(R=(d=u.msg_up_stream_info)==null?void 0:d.msg_video_status)==null?void 0:R.filter(iA=>iA.uint32_video_stream_type===3)[0];else{let iA=(k=u.msg_down_stream_info)==null?void 0:k.filter(cA=>{var TA;return((TA=cA.msg_user_info)==null?void 0:TA.str_identifier)===a})[0];Z=(_=iA?.msg_video_status)==null?void 0:_.filter(cA=>cA.uint32_video_stream_type===3)[0]}if(Z){let iA=(Z.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[e.id]&&this.sleep[e.id]>0)return void(this.sleep[e.id]-=1);iA>0&&iA<10&&(this.sleep[e.id]=30,this._log.info("track bitrate",iA,"start check"),this.checkOnce(e,3e4))}};return n.on("heartbeat-report",c),this.heartbeatListenerCleaner.set(e.id,()=>n.off("heartbeat-report",c)),this.callbacks.set(e.id,I),this.userIdMap.set(e.id,a),e.id}checkOnce(A,e){try{let o=this.getWorker();if(!o)throw new Error("Worker not available");let n=new MediaStreamTrackProcessor({track:A});o.postMessage({type:"addTrack",trackId:A.id,timeout:e,readable:n.readable},[n.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 e=this.heartbeatListenerCleaner.get(A);e&&e(),this.heartbeatListenerCleaner.delete(A),this.userIdMap.delete(A)}}destroy(){this.callbacks.forEach((A,e)=>this.stop(e)),this.worker&&(this.worker.terminate(),this.worker=null)}},A2=class extends Dz{constructor(A){super(fi(bt({},A),{isUplink:!0})),G(this,"localMainAudioTrack",null),G(this,"localMainVideoTrack",null),G(this,"localAuxAudioTrack",null),G(this,"localAuxVideoTrack",null),G(this,"_isPublishingAux",!1),G(this,"_publishingLocalAudioTrack"),G(this,"_publishingLocalVideoTrack"),G(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}),G(this,"_flag",0),G(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:e,bigVideoRtxSsrc:o,smallVideoSsrc:n,smallVideoRtxSsrc:a,auxVideoSsrc:I,auxVideoRtxSsrc:c}=this.singlePC.uplinkSSRC;return{audio:A||0,video:e||0,videoRtx:o||0,small:n||0,smallRtx:a||0,auxiliary:I||0,auxiliaryRtx:c||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:e}=this,{publishState:o}=this._room,n=Object.keys(o).filter(a=>{if(o[a]!==e[a]&&o[a])switch(a){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(n.length>0){if(!A)return void(this._checkPublishStateTimeoutId=nn.run("timeout",()=>this.checkPublishState(!0),{delay:1e4,count:1}));ct.addCount({key:521e3}),n.forEach(a=>{this._log.warn("".concat(a," publish failed during call ").concat(UQ()," ").concat(pu())),ct.addEnum({key:521719,value:Rz[a]})}),nn.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(e){this._log.warn("checkPublishState failed",e)}}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get serverPublishState(){return{audio:!!(this.flag&Lf),bigVideo:!!(this.flag&_f),smallVideo:!!(this.flag&mN),auxVideo:!!(this.flag&bf)}}initialize(){this.installEvents()}close(A){var e;let o=((e=this._peerConnection)==null?void 0:e.getSenders())||[];for(let n of o)n.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,e;(A=this.singlePC)!=null&&A.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(e=this.singlePC)==null||e.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,e){var o,n,a;let I=this._currentState,c=super.emitConnectionStateChangedEvent(A);return c&&I!==A&&(e?e.emit("connection-state-changed",{prevState:I,state:A}):((o=this.localMainVideoTrack)==null||o.emit("connection-state-changed",{prevState:I,state:A}),(n=this.localAuxVideoTrack)==null||n.emit("connection-state-changed",{prevState:I,state:A}),(a=this._publishingLocalVideoTrack)==null||a.emit("connection-state-changed",{prevState:I,state:A}))),c}onVideoEncodeFailed(A){return DA(this,null,function*(){if(!A||!A.isMediaTrackActive)return;let{videoCodec:e,singlePC:o}=this;if(!o)return;let n={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(e==="vp9"||e==="av1")return;let a=n[e];this._log.warn(a.log),a!=null&&a.supported&&(yield o.switchVideoEncoder(a.target))})}publish(A){return DA(this,arguments,function(e){var o=this;let{localAudioTrack:n,localVideoTrack:a,isAuxiliary:I}=e;return function*(){var c,u,d,R,k,_,Z;if(!o.singlePC)return;if(o.installEvents(),o.installTrackMuteEvents(n,a),a&&(a.retryEncodeFailed=o.onVideoEncodeFailed.bind(o),Ea&&(Lh($g,"26.2",!0)||Lh(Qu,"26.2",!0)||Bu&&Lh($g,"18.7",!0)))){o._log.warn("detectH264Supported for fallback 26.2 video encode issue");try{yield kA.detectH264SupportedByFakeStreaming(500)}catch{}}if(yield o.singlePC.waitForPeerConnectionConnected(),n&&(o._publishingLocalAudioTrack=n),a){if(!o.singlePC.isH264EncodeSupported&&!o.singlePC.isVP8EncodeSupported)throw new Ct({code:Ge.NOT_SUPPORTED_H264,message:Wi({key:Mi.NOT_SUPPORTED_H264ENCODE})});o.singlePC.isUsingH264&&!o.singlePC.isH264EncodeSupported&&o.singlePC.isVP8EncodeSupported&&(o._log.warn("h264 encoder not supported"),yield o.singlePC.switchVideoEncoder("vp8")),ra&&sm()===115&&a.profile.width*a.profile.height<=230400&&(o._log.warn("fallback video to defaultBigVideoProfile: ".concat(JSON.stringify(kf))),a.setProfile(kf),yield a.applyProfile()),o._publishingLocalVideoTrack=a}let iA;if(o._isPublishingAux=I,a&&!I&&a.small&&(iA=o._room.videoManager.smallTrack),yield o._signalChannel.sendWaitForResponseWithRetry({command:iz,responseCommand:io.SPC_PUBLISH_RESULT,data:fi(bt({},o.singlePC.uplinkSSRC),{state:o._room.publishState,muteState:o._room.muteState}),retries:3}),a&&(yield o.checkHighProfile({streamType:a.streamType,newWidth:a.settings.width,newHeight:a.settings.height})),yield o.publishByTransceiver({localAudioTrack:n,localVideoTrack:a,smallTrack:iA,isAuxiliary:I}),o._publishingLocalAudioTrack=null,o._publishingLocalVideoTrack=null,o._isPublishingAux=!1,a){o[I?"localAuxVideoTrack":"localMainVideoTrack"]=a,yield o.singlePC.setDegradationPreference(o._peerConnection.getSenders()[I?3:1],a.contentHint,a.streamType);let{scaleResolutionDownBy:TA}=a;yield o.singlePC.setScaleResolutionDownBy(o._peerConnection.getSenders()[I?3:1],TA,a.streamType)}n&&(o[I?"localAuxAudioTrack":"localMainAudioTrack"]=n),yield o.singlePC.setBandwidth({audio:((c=o.localMainAudioTrack)==null?void 0:c.profile.bitrate)||((u=o.localAuxAudioTrack)==null?void 0:u.profile.bitrate),bigVideo:(d=o.localMainVideoTrack)==null?void 0:d.profile.bitrate,smallVideo:(k=(R=o.localMainVideoTrack)==null?void 0:R.small)==null?void 0:k.bitrate,auxVideo:(_=o.localAuxVideoTrack)==null?void 0:_.profile.bitrate}),o.sendMediaSettings();let cA=I?7:2;(o._room.preferHW||(Z=o._room.scheduleResult.config)!=null&&Z.preferHW)&&a&&a.profile.width*a.profile.height>=921600&&o.singlePC.useHWEncoder(!0,cA)}()})}publishByTransceiver(A){let{localAudioTrack:e,localVideoTrack:o,smallTrack:n,isAuxiliary:a}=A;if(!gl())return;this._log.info("publish by transceiver");let I=o?.outMediaTrack,c=e?.outMediaTrack,u=this._peerConnection.getTransceivers(),d=[],R=[],k=(Z,iA,cA)=>{var TA;let JA=u[iA].sender.replaceTrack(cA);R.push(iA),(TA=this.singlePC)!=null&&TA.enableInsertableStreams&&JA.then(()=>this.createEncodedStreams(u[iA].sender,Z)),this.initSenderTransform(u[iA].sender,Z),d.push(JA)};c&&k(e.mediaType,0,c),I&&k(o.mediaType,a?3:1,I),o!=null&&o.small&&d.push(this.publishSmall(this._room.videoManager.smallMode,o));let _=this.singlePC.setTransceiverDirection(_r.SENDONLY,R);return d.push(_),Promise.all(d)}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,e){var o,n;if(this.singlePC.insertableStreamsAbortMap.has(A))return;let a=A.createEncodedStreams(),I=new AbortController;(o=this.singlePC)==null||o.addAbortController(A,I),((n=this.getTrackByMediaType(e))!=null&&n.enableEncodeFrame?a.readable.pipeThrough(new TransformStream({transform:(c,u)=>{var d,R;let k=this.getTrackByMediaType(e);if(!k||!k.encodeFrame)return u.enqueue(c);k.isAudio?u.enqueue(k.enableEncodeFrame?k.encodeFrame(c):c):u.enqueue((d=this.singlePC)!=null&&d.isUsingH264||(R=this.singlePC)!=null&&R.isUsingH265?k.encodeFrame(c,e===8):c)}}),I):a.readable).pipeTo(a.writable,I).catch(c=>{this._log.debug("encoded stream error",c),c!=="destroy"&&this._log.warn(c)})}initSenderTransform(A,e){if(!(this._peerConnection&&this.singlePC&&this.singlePC.scriptTransformWorker&&vM))return;let o=e!==2,n=e===8;A.transform||(A.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:e===1,isMain:o,isSmall:n}))}enableSmall(A){return DA(this,null,function*(){A?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(A){return DA(this,arguments,function(e){var o=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.localMainVideoTrack;return function*(){var a;if(!o.singlePC)return;if(e==="canvas"&&!SM())return void o._log.warn("canvas mode small stream is not supported");let I=o._peerConnection.getTransceivers(),{sender:c}=I[2],u=yield o.doPublishSmall(e,n),d=e==="canvas"?524700:524701;ct.addSuccessEvent({key:d}),u?((a=o.singlePC)!=null&&a.enableInsertableStreams&&o.createEncodedStreams(c,8),o.initSenderTransform(c,8),yield o.singlePC.setTransceiverDirection(_r.SENDONLY,[2]),o.updateMediaSettings(),yield o.doPublishChange(),c.track&&(o._blackSmallVideoDetectionId=Ym.start({track:c.track,room:o._room,isUplink:!0,userId:o.userId,onBlack:()=>{o._log.warn("small video is black");let R=e==="canvas"?524700:524701;ct.addFailedEvent({key:R,error:10002}),Ym.stop(o._blackSmallVideoDetectionId),o._blackSmallVideoDetectionId=void 0}}))):ct.addFailedEvent({key:d,error:10001})}()})}doPublishSmall(A){return DA(this,arguments,function(e){var o=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.localMainVideoTrack;return function*(){if(!o.singlePC)return null;o._log.info("publish small",e);let a=o._peerConnection.getTransceivers(),{sender:I}=a[2];if(e==="canvas"&&o._room.videoManager.smallTrack)return yield I.replaceTrack(o._room.videoManager.smallTrack),"canvas";if(e==="api"&&n!=null&&n.outMediaTrack&&n!=null&&n.small){yield I.replaceTrack(n?.outMediaTrack);let c=I.getParameters(),u=iM(n?.profile,n?.small);return o._log.info("small scaleResolutionDownBy",u),c.encodings[0].scaleResolutionDownBy=u,I.setParameters(c),"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(!(n==null||!n.outMediaTrack))),null}()})}unpublishSmall(){return DA(this,null,function*(){this.singlePC&&(this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(_r.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),Ym.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)})}checkHighProfile(A){return DA(this,null,function*(){var e,o;if((((e=this._room.scheduleResult.config)==null?void 0:e.profileLevelId)||{})[A.streamType==="main"?"big":"aux"]!=="high")return;let n=A.newWidth*A.newHeight>=921600&&!Fh();try{yield(o=this.singlePC)==null?void 0:o.setH264ProfileLevelId(A.streamType,n)}catch(a){this._log.warn("setH264ProfileLevelId failed, ignore",a)}})}installTrackMuteEvents(){for(var A=arguments.length,e=new Array(A),o=0;o{n&&(n?.on("mute",this.sendMutedFlag,this),n?.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(){for(var A=arguments.length,e=new Array(A),o=0;o{n&&(n?.off("mute",this.sendMutedFlag,this),n?.off("unmute",this.sendMutedFlag,this))})}unpublish(A){return DA(this,arguments,function(e){var o=this;let{localAudioTrack:n,localVideoTrack:a}=e;return function*(){var I;yield(I=o.singlePC)==null?void 0:I.waitForPeerConnectionConnected();let c=a&&a===o.localAuxVideoTrack||n&&n===o.localAuxAudioTrack,u=a?.outMediaTrack,d=o._peerConnection.getSenders(),R=[];n&&(c?o.localAuxAudioTrack=null:o.localMainAudioTrack=null,!o.localMainAudioTrack&&!o.localAuxAudioTrack&&(yield d[0].replaceTrack(null),R.push(0))),u&&(c?(yield d[3].replaceTrack(null),o.localAuxVideoTrack=null,o._mediaSettings=fi(bt({},o._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),R.push(3)):(yield d[1].replaceTrack(null),yield d[2].replaceTrack(null),o.localMainVideoTrack=null,o._mediaSettings=fi(bt({},o._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),R.push(1,2))),o.isMainStreamPublished||o.isAuxStreamPublished?(yield o.singlePC.setTransceiverDirection(_r.INACTIVE,R),yield o.doPublishChange(!1)):yield o.doUnpublish(),o.uninstallTrackMuteEvents(n,a),a?.emit("connection-state-changed",{prevState:o._currentState,state:"DISCONNECTED"})}()})}doPublishChange(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return DA(this,null,function*(){let e={state:this._room.publishState,constraintConfig:this._mediaSettings},o=yield this._signalChannel.sendWaitForResponseWithRetry({command:EK,data:e,responseCommand:io.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:jx,commandDesc:"unpublish",responseCommand:io.UNPUBLISH_RESULT,enableLog:A}).catch(e=>{if(e.getCode()===Ge.API_CALL_TIMEOUT||e.getCode()===Ge.API_CALL_ABORTED)return Promise.resolve();throw e})}updateMediaSettings(){var A,e;this._mediaSettings.videoCodec=((A=this.singlePC)==null?void 0:A.videoCodec)||"h264",this._mediaSettings.videoDecCodec=((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264";let o=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:n,localAuxVideoTrack:a}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?a=this._publishingLocalVideoTrack:n=this._publishingLocalVideoTrack),qh){if(o&&o.outMediaTrack){let I=o.outMediaTrack.getSettings();this._mediaSettings.audioChannel=I.channelCount||1,this._mediaSettings.audioBps=1e3*o.profile.bitrate,this._mediaSettings.audioFs=I.sampleRate||0}if(n&&n.outMediaTrack){let I=n.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=n;this._mediaSettings.videoWidth=(I.width||0)/c||0,this._mediaSettings.videoHeight=(I.height||0)/c||0,this._mediaSettings.videoFps=I.frameRate||0,this._mediaSettings.videoBps=1e3*n.profile.bitrate,n.small&&(this._mediaSettings.smallVideoWidth=n.small.width,this._mediaSettings.smallVideoHeight=n.small.height,this._mediaSettings.smallVideoFps=n.small.frameRate,this._mediaSettings.smallVideoBps=1e3*n.small.bitrate)}if(a&&a.outMediaTrack){let I=a.outMediaTrack.getSettings(),{scaleResolutionDownBy:c}=a;this._mediaSettings.auxVideoWidth=(I.width||0)/c||0,this._mediaSettings.auxVideoHeight=(I.height||0)/c||0,this._mediaSettings.auxVideoFps=I.frameRate||0,this._mediaSettings.auxVideoBps=1e3*a.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),n&&n.outMediaTrack&&(this._mediaSettings.videoWidth=n.profile.width,this._mediaSettings.videoHeight=n.profile.height,this._mediaSettings.videoFps=n.profile.frameRate,this._mediaSettings.videoBps=1e3*n.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:BK,data:this._mediaSettings,responseCommand:io.UPDATE_CONSTRAINT_CONFIG_RES}).then(A=>{A.data.code!==0&&this._log.warn(A.data.message)}).catch(()=>{})}addTrack(A){return DA(this,null,function*(){if(!this._peerConnection)return;let e=A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;this._log.info("is adding ".concat(A.kind," track to current published local ").concat(e?fA.AUXILIARY:fA.MAIN," stream")),Ru()&&(yield this.addTrackByTransceiver(A,e))})}addTrackByTransceiver(A,e){return DA(this,null,function*(){var o;if(!A.mediaTrack)return;let n=this._peerConnection.getTransceivers();if(A.kind===fA.AUDIO)yield n[0].sender.replaceTrack(A.outMediaTrack);else{let a=e?3:1;yield n[a].sender.replaceTrack(A.outMediaTrack),a===1&&(o=this.localMainVideoTrack)!=null&&o.small&&this._room.videoManager.smallTrack&&(yield n[2].sender.replaceTrack(this._room.videoManager.smallTrack)),n[a].direction===_r.INACTIVE&&(yield this.singlePC.setTransceiverDirection(_r.SENDONLY,[a]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(A){return DA(this,null,function*(){if(!this._peerConnection)return;let e=A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;this._log.info("is removing ".concat(A.kind," track from current published local ").concat(e?fA.AUXILIARY:fA.MAIN," stream")),Ru()&&(yield this.removeTrackByTransceiver(A,e))})}removeTrackByTransceiver(A,e){return DA(this,null,function*(){if(!A.mediaTrack)return;let o=this._peerConnection.getTransceivers();if(A.kind===fA.AUDIO)yield o[0].sender.replaceTrack(null);else{let n=e?3:1;yield o[n].sender.replaceTrack(null),n===1&&this._room.videoManager.hasSmall&&(yield o[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(_r.INACTIVE,[n])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(A){return DA(this,null,function*(){var e;let o=(e=this._peerConnection)==null?void 0:e.getSenders(),n=A.outMediaTrack||A.mediaTrack;if(!o||o.length===0||!n||o.find(I=>I.track===n))return!1;let a=A.mediaType===2||A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(n.kind," track ").concat(n.id," ").concat(n.label," on ").concat(a?fA.AUXILIARY:fA.MAIN," stream")),n.kind===fA.AUDIO&&o[0]&&(yield o[0].replaceTrack(n)),n.kind===fA.VIDEO&&(!a&&o[1]&&(yield o[1].replaceTrack(n)),a&&o[3]&&(yield o[3].replaceTrack(n))),!0})}setBandwidth(A){return DA(this,arguments,function(e){var o=this;let{bandwidth:n,type:a,videoType:I}=e;return function*(){if(o.singlePC){let c={};a===fA.AUDIO?c.audio=n:I==="big"?c.bigVideo=n:I==="small"?c.smallVideo=n:c.auxVideo=n,yield o.singlePC.setBandwidth(c)}}()})}sendMutedFlag(A){A===this.localAuxAudioTrack||A===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:Az,responseCommand:io.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(A){A.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&S.emit(K.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:fA.VIDEO;if(this._peerConnection){let e=this._peerConnection.getSenders();if(A===fA.AUXILIARY&&e[3]&&e[3].track)return e[3].track.id;if(A===fA.VIDEO&&e[1]&&e[1].track)return e[1].track.id}if(this.localMainVideoTrack&&A===fA.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&A===fA.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(A,e){if(A!==0)throw A===xR?(this._log.error(ts.NOT_SUPPORTED_H264ENCODE),new Ct({code:Ge.NOT_SUPPORTED_H264,message:Wi({key:Mi.NOT_SUPPORTED_H264ENCODE})})):new Ct({code:Ge.UNKNOWN,message:Wi({key:Mi.SIGNAL_RESPONSE_FAILED,data:{signalResponse:io.PUBLISH_RESULT,code:A,message:e}})})}onSinglePCReconnected(){return DA(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}))})}};vt([Tm(A=>{let{localVideoTrack:e}=A;e==null||delete e.retryEncodeFailed})],A2.prototype,"unpublish"),vt([yz({when(){return this.isDestroyed}})],A2.prototype,"doPublishChange"),vt([yz({when(){return this.isDestroyed}})],A2.prototype,"doUnpublish");var Rz=(A=>(A[A.audio=1]="audio",A[A.bigVideo=2]="bigVideo",A[A.smallVideo=3]="smallVideo",A[A.auxVideo=4]="auxVideo",A))(Rz||{}),Mz=A2;function wz(A){return Object.keys(A).filter(e=>A[e])}var e2=class extends Dz{constructor(A){super(fi(bt({},A),{isUplink:!1})),G(this,"_flag",0),G(this,"isRobot",!1),G(this,"role","anchor"),G(this,"fromType"),G(this,"remoteAudioTrack"),G(this,"remoteVideoTrack"),G(this,"remoteAuxiliaryTrack"),G(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),G(this,"_prevMids"),G(this,"jitterBufferTimeoutId",-1),G(this,"_jitterBufferResolve"),G(this,"_videoCodec"),G(this,"avPlayerStateSyncManager"),G(this,"isDataChannelSubscribed",!1),this.flag=A.flag,this.isRobot=A.isRobot||!1,this.fromType=A.fromType,this.remoteAudioTrack=new Tx(this._room,this),this.remoteVideoTrack=new nG(this._room,this),this.remoteAuxiliaryTrack=new l4(this._room,this),this.avPlayerStateSyncManager=new $q({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 RQ(this.flag,this.userId)}get flag(){return this._flag}set flag(A){var e,o,n;A!==this._flag&&(this._flag=A,(e=this.remoteAudioTrack)==null||e.onFlagChanged(),(o=this.remoteVideoTrack)==null||o.onFlagChanged(),(n=this.remoteAuxiliaryTrack)==null||n.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===fA.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 e,o;let n=this._currentState,a=super.emitConnectionStateChangedEvent(A);return a&&n!==A&&((e=this.remoteVideoTrack)==null||e.emit("connection-state-changed",{prevState:n,state:A}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:n,state:A})),a}onTrack(A){var e,o;let n=A.streams[0],{track:a,receiver:I}=A;if(!n.id.includes(this.tinyId))return;let c=n.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(c," ").concat(a.kind));let u=fA.AUDIO;a.kind===fA.VIDEO&&(u=c===fA.MAIN?fA.VIDEO:fA.AUXILIARY);let d=this.remoteAudioTrack;u===fA.VIDEO?d=this.remoteVideoTrack:u===fA.AUXILIARY&&(d=this.remoteAuxiliaryTrack),(e=this.singlePC)==null||e.receiverRemoteTrackMap.set(I,d),(o=this.singlePC)!=null&&o.scriptTransformWorker&&this.initReceiverTransform(I,c,a.kind===fA.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(I),d.setInputMediaStreamTrack(a)}createEncodedStreams(A){if(!this.singlePC.insertableStreamsAbortMap.has(A)){let e=A.createEncodedStreams(),o=new AbortController,n={abortController:o,enqueue:a=>{var I,c,u;let d=(I=this.singlePC)==null?void 0:I.receiverRemoteTrackMap.get(A);return d&&(d.kind!=="video"||(c=this.singlePC)!=null&&c.isUsingH264||(u=this.singlePC)!=null&&u.isUsingH265)?d.decodeFrame(a):a}};e.readable.pipeThrough(new TransformStream({transform:(a,I)=>{let c=n.enqueue(a);c&&I.enqueue(c)}})).pipeTo(e.writable,o).catch(a=>{a!=="destroy"&&this._log.warn(a)}),this.singlePC.addAbortController(A,o)}}initReceiverTransform(A,e,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:e}))}subscribe(A,e){return DA(this,null,function*(){var o,n;try{let a=!0;if(this._log.info("subscribe ".concat(e," ").concat(wz(A))),this.hasSSRC){let u="subscribe_change";Object.values(A).find(d=>d===!0)||(u="unsubscribe"),yield this.sendSubscription(u,A)}else{if(yield this._room.switchRoomSubedReq,(o=this.singlePC)!=null&&o.autoSubscribedUserMap.size){let u=this.singlePC.autoSubscribedUserMap.get(this.userId);if(u){this.singlePC.autoSubscribedUserMap.delete(this.userId);let d=(n=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:n[u.groupIndex];d&&(this.ssrc={audio:d.audioSsrc,video:d.bigVideoSsrc,videoRtx:d.bigVideoRtxSsrc,auxiliary:d.auxVideoSsrc,auxiliaryRtx:d.auxVideoRtxSsrc},a=!1)}}yield this.doSubscribe(A,a),this.checkTrackEnded(A)}let{user:I,mediaTrack:c}=this.remoteVideoTrack;A.smallVideo&&c?(ct.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=Ym.start({track:c,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,I),ct.addFailedEvent({key:524702}),Ym.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(Ym.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}catch(a){throw this._room.isJoined&&this.isStreamUnpublished(e)?(this._log.warn("".concat(a.message," ").concat(JSON.stringify(this.muteState))),new Ct({code:Ge.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):a}})}checkTrackEnded(A){var e,o,n;if((A.audio&&((e=this.remoteAudioTrack.mediaTrack)==null?void 0:e.readyState)==="ended"||A.video&&((o=this.remoteVideoTrack.mediaTrack)==null?void 0:o.readyState)==="ended"||A.auxiliary&&((n=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:n.readyState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),Bc&&tE<92)return;this.singlePC.startReconnection()}}unsubscribe(A){return DA(this,arguments,function(e){var o=this;let{remoteTracks:n,streamType:a}=e;return function*(){var I;if(a==="main"&&!o.isMainStreamSubscribed||a==="auxiliary"&&!o.isAuxStreamSubscribed)return void o._log.info("".concat(a," stream already unsubscribed"));let c=bt({},o.subscribeState);n.forEach(d=>{switch(d.mediaType){case 1:c.audio=!1;break;case 4:c.video=!1;break;case 8:c.smallVideo=!1;break;case 2:c.auxiliary=!1}});let u="subscribe_change";Object.values(c).find(d=>d===!0)||(u="unsubscribe"),o._log.info("".concat(u==="unsubscribe"?u:"subscribe"," ").concat(a," [").concat(wz(c),"]")),u==="unsubscribe"&&((I=o.singlePC)==null||I.removeDownlinkQueue.add(o.tinyId)),yield o.sendSubscription(u,c),a==="main"&&(Ym.stop(o._blackSmallVideoDetectionId),o._blackSmallVideoDetectionId=void 0),u==="unsubscribe"&&(yield o.removeDownlink())}()})}subscribeDataChannel(){return DA(this,null,function*(){if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let A=fi(bt({},this.subscribeState),{datachannel:!0});yield this.doSubscribe(A)})}unsubscribeDataChannel(){return DA(this,null,function*(){let A=fi(bt({},this.subscribeState),{datachannel:!1});yield this.sendSubscription("unsubscribe",A),yield this.removeDownlink()})}sendSubscription(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscribeState,o={srcTinyId:this.tinyId,srcUserId:this.userId},n=lK,a=io.UNSUBSCRIBE_RESULT;return A==="subscribe_change"&&(o={audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:e.datachannel,srcTinyId:this.tinyId},n=CK,a=io.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:n,data:o,responseCommand:a,timeout:1e4,retries:3}).then(I=>{let{data:c}=I;if(c.code!==0){let u=new Ct({code:c.code,message:Wi({key:Mi.ERROR_MESSAGE,data:{type:A,message:c.message}})});throw this._log.error(u),u}})}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:e,videoDelay:o}=A;this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=o}onSinglePCReconnected(){return DA(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 DA(this,arguments,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.subscribeState,o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return function*(){var n,a;if(A.singlePC){A.singlePC.addDownlinkQueue.add(A.tinyId),yield A.singlePC.waitForPeerConnectionConnected();try{if(o||!A.hasSSRC){let I={audioSsrc:gB(),bigVideoSsrc:gB(),bigVideoRtxSsrc:gB(),auxVideoSsrc:gB(),auxVideoRtxSsrc:gB()},{audioSsrc:c,bigVideoSsrc:u,bigVideoRtxSsrc:d,auxVideoSsrc:R,auxVideoRtxSsrc:k}=I;A.ssrc={audio:c,video:u,videoRtx:d,auxiliary:R,auxiliaryRtx:k},A.singlePC.addDownlinkQueue.delete(A.tinyId),yield A.singlePC.addDownlink({userId:A.userId,tinyId:A.tinyId,ssrc:A.ssrc,prevMids:A._prevMids});try{let _=yield A._signalChannel.sendWaitForResponseWithRetry({command:oz,responseCommand:io.SPC_SUBSCRIBE_RESULT,data:{srcUserId:A.userId,srcTinyId:A.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:(n=e.datachannel)!=null&&n,ssrc:I},retries:3,retryTimeout:0});if(_.data.code!==0&&_.data.code!==-10036)throw new Ct({code:_.data.code,message:_.data.message});A.isDataChannelSubscribed=(a=e.datachannel)!=null&&a}catch(_){throw yield A.removeDownlink(),_}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((e.audio||e.video||e.smallVideo||e.auxiliary||!e.datachannel)&&Mu){let{main:I,aux:c}=A._room.jitterBufferDelay||{},{jitterDelay:u=I,jitterDelayAux:d=c}=A._room.scheduleResult.config||{};(hr(u)||hr(d))&&A.setJitterBufferDelay({mainDelay:u,auxDelay:d})}}}}()})}removeDownlink(){return DA(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:e,auxDelay:o}=A;if(!Mu||!this.singlePC||!this._peerConnection||$c(e)&&$c(o))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(e," aux: ").concat(o));let n=this.singlePC.getReceiversByUserId(this.userId);return hr(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),hr(o)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=o,$c(e)&&(this.remoteAudioTrack.jitterBufferDelay=o)),new Promise(a=>{this._jitterBufferResolve=a,this.doSetJitterBufferDelay({mainDelay:e,auxDelay:o,receivers:n,resolve:a})})}doSetJitterBufferDelay(A){let{mainDelay:e,auxDelay:o,receivers:n,resolve:a}=A;try{if(e===0&&o===0)return n.forEach(I=>I.jitterBufferTarget=0),this._jitterBufferResolve=void 0,a();if(n.forEach(I=>{var c;let u=I.track===this.remoteAuxiliaryTrack.outMediaTrack||$c(e)&&I.track===this.remoteAudioTrack.outMediaTrack;if(u&&$c(o)||!u&&$c(e))return;let d=u?o||0:e,R=(I.jitterBufferTarget||0)+100;R>d||(I.jitterBufferTarget=R,this._log.debug("set ".concat(u?"aux ":"").concat((c=I?.track)==null?void 0:c.kind," jitterBuffer delay ").concat(R," -> ").concat(d)))}),!n.find(I=>{let c=I.track===this.remoteAuxiliaryTrack.outMediaTrack?o||0:e;return I.jitterBufferTarget{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:o,receivers:n,resolve:a})},1e3)}catch(I){this._log.warn("set jitterBuffer delay error: ".concat(I)),clearTimeout(this.jitterBufferTimeoutId),this._jitterBufferResolve=void 0,a()}}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()}};vt([WT(),Dn(A=>function(){for(var e=arguments.length,o=new Array(e),n=0;n{let c=u=>{this.off("closed",c),I(new Ct({code:Ge.API_CALL_ABORTED,message:Wi({key:Mi.CONNECTION_ABORTED,data:u})}))};this.on("closed",c),A.apply(this,o).then(a,I).finally(()=>{this.off("closed",c)})})})],e2.prototype,"subscribe"),vt([WT()],e2.prototype,"unsubscribe"),vt([zh(()=>"jitter")],e2.prototype,"setJitterBufferDelay");var ZtA=e2,XtA=es(hg()),Sz=class I6 extends XtA.EventEmitter{constructor(e,o){super(),this.room=e,this.signalChannel=o,G(this,"log"),G(this,"cmdIdSeqMap",new Map),G(this,"messageMap",new Map),this.log=nA.createLogger({parent:e.getLogger(),id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),o.on(io.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",n=>{let{userId:a}=n;[...this.messageMap.keys()].forEach(I=>{I.split("_").slice(0,-1).join("_")===a&&this.messageMap.delete(I)})})}send(e){let{cmdId:o,data:n}=e,a=this.cmdIdSeqMap.get(o)||Math.floor(16383*Math.random()),I={cmdId:o,msg:btoa(String.fromCharCode(...new Uint8Array(n))),ordered:!0,reliable:!0,streamSeq:a};this.cmdIdSeqMap.set(o,a+1),this.signalChannel.send(dtA,I),this.log.debug("send custom msg: ".concat(JSON.stringify(I)))}onReceiveMsg(e){let{data:o}=e.data,n=this.room.tinyIdToUserIdMap.get(o.srcTinyId);if(n){let a={userId:n,cmdId:o.cmdId,seq:o.streamSeq,data:Uint8Array.from(atob(o.msg),I=>I.charCodeAt(0)).buffer};if(o.ordered){let I="".concat(n,"_").concat(a.cmdId),c=this.messageMap.get(I);if(c&&c.lastSeq!==0)if(Math.abs(c.lastSeq-a.seq)>I6.SEQ_INTERVAL)this.messageMap.set(I,{lastSeq:a.seq,cachedMessageMap:new Map}),this.emitMessage(a);else if(a.seq>c.lastSeq){if(a.seq===c.lastSeq+1)this.emitMessage(a);else if(!c.cachedMessageMap.has(a.seq)){let u=setTimeout(()=>this.emitMessage(a,!0),5e3);c.cachedMessageMap.set(a.seq,{message:a,timeoutId:u})}}else this.log.debug("drop message ".concat(a.userId,"-").concat(a.cmdId,"-").concat(a.seq));else c||(c={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(I,c),setTimeout(()=>this.emitMessage(a,!0),100)),c.cachedMessageMap.set(a.seq,{message:a})}else this.emit("message",a)}else{this.log.warn("receive msg from unknown user, wait peer-join tinyId: ".concat(o.srcTinyId));let a=I=>{I.tinyId===o.srcTinyId&&(this.room.off("peer-join",a),this.onReceiveMsg(e))};this.room.on("peer-join",a),AC(2e3).then(()=>this.room.off("peer-join",a))}}emitMessage(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var n;let a=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),I=e;if(a){if(o){let u=[...a.cachedMessageMap.values()].sort((d,R)=>d.message.seq-R.message.seq);u[0]&&(I=u[0].message)}a.lastSeq!==0&&I.seq-a.lastSeq>1&&this.log.debug("msg lost userId: ".concat(I.userId," seq: ").concat(a.lastSeq," -> ").concat(I.seq)),a.lastSeq=I.seq,clearTimeout((n=a.cachedMessageMap.get(I.seq))==null?void 0:n.timeoutId),a.cachedMessageMap.delete(I.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(I))),this.emit("message",I);let c=a?.cachedMessageMap.get(I.seq+1);c&&this.emitMessage(c.message)}};G(Sz,"SEQ_INTERVAL",300);var $tA=Sz,{isString:vz,isUndefined:Pm,getNetworkType:AiA,isEmpty:eiA}=il,op=class extends xtA{constructor(A){super(A),G(this,"_businessInfo"),G(this,"userManager"),G(this,"_version"),G(this,"_heartbeat",-1),G(this,"_lastHeartBeatTime",-1),G(this,"_stats"),G(this,"_joinTimeout",-1),G(this,"_firstPublishedList",null),G(this,"_joinReject",null),G(this,"_isRelayChanged",!1),G(this,"sdpSemantics"),G(this,"signalChannel",null),G(this,"uplinkConnection",null),G(this,"singlePC",null),G(this,"enableSPC",fm),G(this,"_changeBigSmallRecords",new Map),G(this,"networkQuality"),G(this,"_iceTransportPolicy"),G(this,"forceRelay",!1),G(this,"_turnServers",[]),G(this,"_iceServersFromJoin"),G(this,"_syncUserListInterval",-1),G(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),G(this,"enableSEI",!1),G(this,"_enableAudioVolumeEvaluation",!1),G(this,"_audioVolumeIntervalId",0),G(this,"_enableMultiAuxStream",!1),G(this,"_pureAudioPushMode",!1),G(this,"_customMessageManager"),G(this,"_enableDataChannel",!1),G(this,"preferHW",!1),G(this,"healthDetector"),G(this,"playoutDelay"),G(this,"jitterBufferDelay"),G(this,"_updateAudioLevelTaskId",-1),G(this,"switchRoomSubedReq"),G(this,"resolveSwitchRoomSubedReq"),G(this,"enableVolumeControlInIOS"),G(this,"capturedLocalMainAudioTrack"),G(this,"capturedLocalMainVideoTrack"),G(this,"capturedLocalAuxVideoTrack"),G(this,"PRELINK_EXPIRED_TIME",3e5),G(this,"PRELINK_TIMEOUT",1e4),G(this,"prelinkTimeoutId",null),G(this,"firewallDetector"),this.firewallDetector=new meA,this.firewallDetector.on("firewall-restriction",()=>{this._log.warn("firewall restriction"),this.emit("firewall-restriction")}),this._stats=new RtA(this,this._log),this.userManager=new peA(this.userId,this._log),this._version=ol,this.sdpSemantics=OR,Pm(A.sdpSemantics)?kA.isUnifiedPlanDefault()&&(this.sdpSemantics=Uf):this.sdpSemantics=A.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(AiA())),A.iceTransportPolicy&&(this._iceTransportPolicy=A.iceTransportPolicy),this._enableMultiAuxStream=!Pm(A.enableMultiAuxStream)&&A.enableMultiAuxStream,this.enableSEI=A.enableSEI&&fm,!Pm(A.enableSPC)&&fm&&(this.enableSPC=A.enableSPC),this.preferHW=!!A.preferHW,this.enableVolumeControlInIOS=A.enableVolumeControlInIOS,this._initBusinessInfo(A),this.healthDetector=new qtA(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,e,o){return DA(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",n=>{this.emit("peer-join",n)}),this.userManager.on("8",n=>{this.emit("asr-robot-peer-join",n)}),this.userManager.on("9",n=>{this.emit("asr-robot-peer-leave",n)}),this.userManager.on("2",n=>{let{userId:a,reason:I}=n;this.closeDownLinkConnection(a,"remote user exitRoom"),this.emit("peer-leave",{userId:a,reason:I})}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",n=>{var a=WU(n,[]);S.emit(K.REMOTE_PUBLISH_STATE_CHANGED,bt({room:this},a)),this.emit("remote-publish-state-changed",bt({},a))}),this.joinParams=A,rn(A.enableDataChannel)&&(this._enableDataChannel=A.enableDataChannel),new Promise((n,a)=>DA(this,null,function*(){var I,c;this._joinReject=a;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(d){if(!(d instanceof Ct&&d.code===Ge.SPC_INITIALIZED_FAILED))return a(d);(I=this.signalChannel)==null||I.destroy(),yield this.initialize()}let u=ki();yield this.doJoin(A,(c=this.singlePC)==null?void 0:c.clientAbility),ct.addSuccessEvent({key:521708,cost:ki()-u}),n(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(u){ct.addFailedEvent({key:521708,error:u}),a(u)}this._joinReject=null}))})}initSinglePC(){return DA(this,null,function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new ip({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 e=new TextDecoder().decode(A.data.data||A.data);try{this.emit("data-channel-message",{data:JSON.parse(e)})}catch{}});try{return yield this.singlePC.initialize()}catch(A){throw this.fallbackToMPC(),new Ct({code:Ge.SPC_INITIALIZED_FAILED,message:A?.message})}}})}doJoin(A,e){return new Promise((o,n)=>DA(this,null,function*(){var a,I,c,u,d,R,k,_;A.privateMapKey&&(this.privateMapKey=A.privateMapKey),A.latencyLevel&&(this.latencyLevel=A.latencyLevel),this.signalChannel.once(qx,cA=>{this.clearJoinTimeout(),S.emit(K.JOIN_SIGNAL_CONNECTION_END,{room:this,error:cA}),n(cA)}),rn((I=(a=this.scheduleResult)==null?void 0:a.config)==null?void 0:I.singlePC)&&fm&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),(!((u=(c=this.scheduleResult)==null?void 0:c.config)!=null&&u.jitterDelay)&&!((R=(d=this.scheduleResult)==null?void 0:d.config)!=null&&R.jitterDelayAux)||!Mu)&&e&&this.playoutDelay&&(this._log.info("set playoutDelay",JSON.stringify(this.playoutDelay)),e.playoutDelay=this.playoutDelay);let Z={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:er(),netType:mh(),bussinessInfo:this._businessInfo,ability:e,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&wM(),transcription:this._enableDataChannel,downUseVp8:((k=this.scheduleResult.config)==null?void 0:k.downUseVp8)||!1};this._log.debug("join room signal data: ".concat(JSON.stringify(Z)));let iA=5e3;(_=this.scheduleResult.config)!=null&&_.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(iA=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout(()=>{n(new Ct({code:Ge.JOIN_ROOM_FAILED,message:Wi({key:Mi.JOIN_ROOM_TIMEOUT})}))},iA),S.emit(K.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?BtA:AtA,Z),this.signalChannel.once(io.JOIN_ROOM_RESULT,cA=>DA(this,null,function*(){this.clearJoinTimeout();let{code:TA,message:JA,data:Ie,tinyId:XA}=cA.data;S.emit(K.JOIN_RECEIVED_CMD_RES,{room:this,code:TA}),TA===0?(this._log.info("Join room success, start heartbeat"),XA&&(this.tinyId=XA),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=Ie.publishers,this._iceServersFromJoin=Ie.iceServer?[Ie.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var Ft;(Ft=this.singlePC)==null||Ft.connect(fi(bt({},Ie.ability),{useVp8:Ie.ability.useVp8||!!A.useVp8,useH265:Ie.ability.useH265&&!!A.useH265})).catch(()=>{})}),o()):(this._log.error("Join room failed result: ".concat(TA," error: ").concat(JA)),n(new Ct({code:Ge.JOIN_ROOM_FAILED,extraCode:TA,message:Wi({key:Mi.JOIN_ROOM_FAILED,data:{error:JA,code:TA}})})))}))}))}reJoin(){return DA(this,null,function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this.joinParams.roomId));let A,e=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,e.push(this.initSinglePC().then(o=>(A=o,o)))),this.signalChannel&&(this.signalChannel.close(),e.push(this.signalChannel.connect())),yield Promise.all(e),yield this.doJoin(fi(bt({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),A),this._log.warn("reJoin success"),Jo.logSuccessEvent({userId:this.userId,eventType:oa.REJOIN}),this.singlePC){let o=n=>{var a;n.state==="CONNECTED"&&((a=this.singlePC)==null||a.off(jM.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof Mz&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(I=>{I.installEvents(),I.onSinglePCReconnected()}))};this.singlePC.on(jM.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof Xx&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(A){this._log.warn("reJoin fail ".concat(A)),this.reset(),Jo.logFailedEvent({userId:this.userId,eventType:oa.REJOIN,error:A}),this.emit("error",new Ct({code:Ge.JOIN_ROOM_FAILED,message:Wi({key:Mi.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")})}initialize(A){return DA(this,null,function*(){var e,o;if(!(A!=null&&A.isPrelink)&&this.prelinkPromise&&(yield this.prelinkPromise),(e=this.signalChannel)!=null&&e.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 n,{mainUrl:a,backupUrl:I}=this.getSignalChannelUrl(),c=this.signalChannel||function(d){return[...Wx.values()].find(k=>k.room.userId===d&&!k.room.isJoined)||null}(this.userId),u=!!(c&&c.isConnected&&c.keepAlive&&c.userId===this.userId);return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(n=this.scheduleResult.domains[0]),this._log.info("".concat(u?"reuse":"setup"," signal channel")),u?(c.url=a,c.backupUrl=I,c.room.setSignalChannel(null),c.room=this,this.signalChannel=c):(c&&c.close(),this.signalChannel=new rz({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:a,backupUrl:I,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?n:void 0,prelink:A?.isPrelink}),this._customMessageManager=new $tA(this,this.signalChannel),this._customMessageManager.on("message",d=>{this.emit("custom-message",d)})),this.networkQuality||(this.networkQuality=new Iz({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Iz.EVENT_NETWORK_QUALITY,d=>{var R;this.emit("network-quality",d),(R=this.singlePC)==null||R.detectTCPAndUDP(d)})),nE(this,this.signalChannel).add(cK,d=>{S.emit(K.SIGNAL_CONNECTION_STATE_CHANGED,bt({room:this},d)),this.emit("signal-connection-state-changed",d)}).add(ZeA,d=>{this.reset(),this.emit("error",d)}).add(io.PEER_JOIN,d=>{let{srcTinyId:R,userId:k,role:_,fromType:Z}=d.data.data;this.userManager.addUser({userId:k,tinyId:R,role:_,fromType:Z})}).add(io.PEER_LEAVE,d=>{let{userId:R,reason:k=0}=d.data.data;this.userManager.deleteUser(R,k)}).add(io.UPDATE_REMOTE_MUTE_STAT,d=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(d.data)}).add(io.CLIENT_BANNED,d=>{let R=d.data.data,{reason:k}=R;if(Jo.uploadEvent({log:"stat-banned:".concat(k),userId:this.userId}),k==="user_time_out")return this._log.warn("".concat(k," last heart beat time: ").concat(this._lastHeartBeatTime," interval: ").concat(Date.now()-this._lastHeartBeatTime,", visibility: ").concat(document.visibilityState)),void this.reJoin();this._log[k==="kick"?"error":"info"]("user was banned because of [".concat(k,"]")),this.reset(),this.emit("banned",{reason:k})}).add(io.SEND_SWITCH_ROOM_SUBED_REQ,d=>{if(!this.singlePC)return;let{subList:R}=d.data.data;this._log.info("auto subscribe ".concat(al(R,{keysToInclude:["userId"]}))),R.forEach(k=>{this.singlePC.autoSubscribedUserMap.set(k.userId,k)}),this.resolveSwitchRoomSubedReq()}).add(io.FALLBACK_CODEC,d=>DA(this,null,function*(){var R,k,_,Z,iA;let cA=d.data.data;((R=cA.videoControlInfo)==null?void 0:R.enableH265Enc)===0&&((k=this.singlePC)==null?void 0:k.videoCodec)==="h265"&&(this._log.warn("fallback codec enableH265Enc: ".concat((_=cA.videoControlInfo)==null?void 0:_.enableH265Enc)),ct.addCount({key:513e3}),yield(Z=this.singlePC)==null?void 0:Z.switchVideoEncoder("h264"),yield(iA=this.uplinkConnection)==null?void 0:iA.sendMediaSettings())})),this.signalChannel.once(Z4,d=>{this.tinyId=d.signalInfo.tinyId,S.emit(K.JOIN_SIGNAL_CONNECTION_END,{room:this})}),S.emit(K.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),u&&S.emit(K.JOIN_SIGNAL_CONNECTION_END,{room:this}),u})}setSignalChannel(A){this.signalChannel=A,A||pr(this)}leave(){return DA(this,null,function*(){var A;try{yield this.doHeartbeat()}catch{}this._log.info("leave() => leaving room"),S.emit(K.LEAVE_SEND_CMD,{room:this}),(A=this.signalChannel)==null||A.send(etA),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=nn.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),nn.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return DA(this,null,function*(){var A;let e=this.badCaseDetector.getMonitorFreeze(),o=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let n=(A=this.signalChannel)!=null&&A.isConnected?function(I){if(YM.has(I)){let c=YM.get(I).map(u=>({uint32_event_id:u.eventId,uint64_date:u.timestamp,str_userid:u.remoteUserId,uint32_param1:u.param1,uint32_param2:u.param2,uint32_video_stream_type:u.streamType}));return YM.delete(I),c}return[]}(this.userId):[],a=fi(bt({str_sdk_version:NR,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:n,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},o),{msg_device_info:bt({uint32_terminal_type:15,str_device_name:pu(),str_os_version:"",uint32_net_type:mh()},o.msg_device_info)});if(this.heartbeatReport=a,this.heartbeatCount++,S.emit(K.HEARTBEAT_REPORT,{room:this,report:a}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(ttA,a);let I=Date.now();this._lastHeartBeatTime>0&&I-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(I-this._lastHeartBeatTime)),this._lastHeartBeatTime=I,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",fi(bt({},a),{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 e=!1,o=A.data.userList||[],n=A.data.mixRobotList||[],a=[];for(let c of o){if(c.flag===DN)continue;let{userId:u,srcTinyId:d,flag:R,fromType:k}=c;u===this.userId&&(e=!0,this.uplinkConnection&&(this.uplinkConnection.flag=R),this.localPublishFlag!==R&&(this.localPublishFlag=R,this.emit("local-publish-flag-changed",R))),a.push({userId:u,tinyId:d,flag:R,fromType:k})}let I=[...n.map(c=>{let{userId:u,srcTinyId:d,flag:R,mixUserList:k,fromType:_}=c;return{userId:u,tinyId:d,flag:R,isRobot:!0,mixUserList:k,fromType:_}}),...a];I.forEach(c=>{let{userId:u}=c,d=this.remotePublishedUserMap.get(u);d&&this.checkSubscribeBigSmallVideo(d)}),A.data.fakeMixUser&&(A.data.fakeMixUser.tinyId=A.data.fakeMixUser.srcTinyId,I.push(A.data.fakeMixUser)),S.emit(K.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:I}),e||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),this.userManager.setRemotePublishedUserList(I)}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 Xx&&(this.uplinkConnection=null)),this.localTracks.forEach(e=>e.unpublish()),this.localTracks.clear()}createDownlinkConnection(A){let{userId:e,tinyId:o,flag:n,isRobot:a,fromType:I}=A,c=new(this.singlePC?ZtA:sz)({userId:e,tinyId:o,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:n,isRobot:a,fromType:I});this.userManager.addRemotePublishedUser(c),this.installDownlinkEvents(c,e),this.emit("remote-published",c)}closeDownLinkConnection(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"remote user unpublished",o=this.remotePublishedUserMap.get(A);o&&(o.close(e),this.emit("remote-unpublished",o))}installDownlinkEvents(A,e){A.on("error",o=>{let n=o.getCode();n!==Ge.ICE_TRANSPORT_ERROR&&(n===Ge.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(e),this.emit("error",o))}),A.on("connection-state-changed",o=>{this.emit("media-connection-state-changed",fi(bt({},o),{userId:A.userId}))})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=nn.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){nn.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:EtA,responseCommand:io.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(e=>{let{data:o}=e,{code:n,message:a}=o;if(n===0)return(o.data&&o.data.userList||[]).map(I=>{let{userId:c,srcTinyId:u,role:d,fromType:R}=I;return{userId:c,tinyId:u,role:d,fromType:R}});throw Wi({key:Mi.SIGNAL_RESPONSE_FAILED,data:{signalResponse:io.USER_LIST_RES,code:n,message:a}})}):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||!nz)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let A=this.getAllConnections();if(A.length===0)return!1;for(let e=0;e{if(e instanceof XQ&&!e.getIsReconnecting()){let o=e.getPeerConnection();o&&o.connectionState===hi.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}})}fallbackToMPC(){return DA(this,null,function*(){var A;if(this._log.warn("fallback to multi pc"),Jo.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 e=this.uplinkConnection;this.uplinkConnection=new Xx({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),e.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localMainAudioTrack,localVideoTrack:e.localMainVideoTrack,isAuxiliary:!1})),e.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localAuxAudioTrack,localVideoTrack:e.localAuxVideoTrack,isAuxiliary:!0})),e.close()}for(let e of[...this.remotePublishedUserMap.values()]){let o=new sz({userId:e.userId,tinyId:e.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:e.flag,remoteAudioTrack:e.remoteAudioTrack,remoteVideoTrack:e.remoteVideoTrack,remoteAuxiliaryTrack:e.remoteAuxiliaryTrack});this.installDownlinkEvents(o,e.userId),this.remotePublishedUserMap.set(e.userId,o),e.isMainStreamSubscribed&&(yield o.subscribe(e.subscribeState,"main")),e.isAuxStreamSubscribed&&(yield o.subscribe(e.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 Ct({code:Ge.INVALID_OPERATION,message:Wi({key:Mi.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.firewallDetector.destroy(),this.removeAllListeners(),this.healthDetector.destroy(),nn.clearTask(this._audioVolumeIntervalId))}switchRole(A){return DA(this,null,function*(){this.role!==A&&(A==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(A))})}doSwitchRole(A){let e={command:ltA,data:{role:A==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:io.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(e.data))),this.signalChannel.sendWaitForResponseWithRetry(e).then(o=>{let{code:n,message:a}=o.data;if(n!==0)throw new Ct({code:Ge.SWITCH_ROLE_FAILED,message:Wi({key:Mi.SWITCH_ROLE_FAILED,data:{message:a,code:n}})});this.role=A}).catch(o=>{throw o instanceof Ct&&o.getCode()===Ge.API_CALL_TIMEOUT&&(o=new Ct({code:Ge.SWITCH_ROLE_FAILED,message:Wi({key:Mi.SWITCH_ROLE_TIMEOUT})})),this._log.error(o),o})}subscribeDataChannel(){return DA(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let A=[...this.remotePublishedUserMap.values()].filter(e=>e.fromType===JR);this._log.info("subscribeDataChannel",A.map(e=>e.userId)),yield Promise.all(A.map(e=>DA(this,null,function*(){try{yield e.subscribe(fi(bt({},e.subscribeState),{datachannel:!0}),"main")}catch(o){this._log.error("subscribeDataChannel failed:",e.userId,o)}})))})}unsubscribeDataChannel(){return DA(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let A=[...this.remotePublishedUserMap.values()].filter(e=>e.fromType===JR);this._log.info("unsubscribeDataChannel",A.map(e=>e.userId)),yield Promise.all(A.map(e=>e.unsubscribeDataChannel()))})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new Mz({userId:this.userId,tinyId:this.tinyId,room:this}):new Xx({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",fi(bt({},A),{userId:this.userId}))}),this.uplinkConnection.on("error",A=>{let e=A.getCode();e!==Ge.ICE_TRANSPORT_ERROR&&(e===Ge.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",A))})}publish(A){return DA(this,null,function*(){var e;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(e=this.singlePC)==null?void 0:e.waitForPeerConnectionConnected(),yield this.uplinkConnection.publish({localAudioTrack:A instanceof km?A:null,localVideoTrack:A instanceof Su?A:null,isAuxiliary:A.streamType==="auxiliary"})})}unpublish(A){return DA(this,null,function*(){if((this.scene!=="live"||this.role==="anchor")&&(this.isMainStreamPublished||this.isAuxStreamPublished)&&this.uplinkConnection){try{let e="".concat(A.streamType," ").concat(A.isAudio&&A.isScreen?"screen":"").concat(A.kind);this._log.info("unpublish() => ".concat(e)),yield this.uplinkConnection.unpublish({localAudioTrack:A instanceof km?A:null,localVideoTrack:A instanceof Su?A:null})}catch{}this.localTracks.size===0&&this.closeUplink("you unpublished")}})}addTrack(A){if(!this.uplinkConnection||!A.mediaTrack)return Promise.resolve();let e=this.uplinkConnection.addTrack(A);return A.publish(this,e),e}removeTrack(A){return this.uplinkConnection&&A.mediaTrack?(A.unpublish(),this.uplinkConnection.removeTrack(A)):Promise.resolve()}replaceTrack(A){return this.uplinkConnection&&A.mediaTrack&&rx()?this.uplinkConnection.replaceTrack(A).then(e=>{e&&S.emit(K.LOCAL_TRACK_REPLACED,{track:A})}):Promise.resolve()}setBandWidth(A){return DA(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(A),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(A){return DA(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();A&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:fA.VIDEO,videoType:fA.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(A)})}subscribe(){for(var A=arguments.length,e=new Array(A),o=0;o!c.isSubscribed),e.length===0)return;let{userId:n}=e[0],a=this.remotePublishedUserMap.get(n);if(!a)return;let I=e.find(c=>c.mediaType===2)?"auxiliary":"main";try{let c=bt({},a.subscribeState);e.forEach(d=>{switch(d.mediaType){case 1:c.audio=!0;break;case 4:c.video=!0;break;case 8:c.smallVideo=!0;break;case 2:c.auxiliary=!0}});let u=this._changeBigSmallRecords.get(n);u&&u.options.smallVideo&&a.muteState.hasSmall&&c.video&&(c.video=!1,c.smallVideo=!0),S.emit(K.SUBSCRIBE_START,{room:this,streamType:I,remotePublishedUser:a,subscribeState:c}),this._log.info("subscribe() => ".concat(n," ").concat(I," ").concat(e.map(d=>d.strMediaType).join(",")," [").concat(uK(c),"] prev: [").concat(uK(a.subscribeState),"]")),yield a.subscribe(c,I),this._log.info("subscribe ".concat(n," ").concat(I," done"));for(let d of e)d.mediaTrack||(yield d.waitHasMediaTrack());S.emit(K.SUBSCRIBE_SUCCESS,{room:this,streamType:I,remotePublishedUser:a})}catch(c){let u=c instanceof Ct?c.getCode():Ge.UNKNOWN,d=c;throw c instanceof Ct?u===Ge.REMOTE_STREAM_NOT_EXIST&&(d=new Ct({code:Ge.API_CALL_ABORTED,message:Wi({key:Mi.API_CALL_ABORTED,data:{message:c.message,userId:n,streamType:I}})}),this._log.warn(d)):(d=new Ct({code:u,message:Wi({key:Mi.SUBSCRIBE_FAILED,data:{message:c.message,userId:n,streamType:I}})}),this._log.error(d)),d}})}unsubscribe(){for(var A=arguments.length,e=new Array(A),o=0;oc.mediaType===2)?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(n," ").concat(I," ").concat(e.map(c=>c.strMediaType).join(",")));try{yield a.unsubscribe({remoteTracks:e,streamType:I})}catch(c){this._log.warn("unsubscribe() => failed ".concat(c))}e.forEach(c=>{c.unsubscribe(),c.mediaType===8&&c.setMediaType(4)}),S.emit(K.UNSUBSCRIBE_SUCCESS,{room:this,streamType:I,remotePublishedUser:a})})}setEncodedDataProcessingListener(A){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3,e=arguments.length>1?arguments[1]:void 0;if(A<=0)return this._enableAudioVolumeEvaluation=!1,void nn.clearTask(this._audioVolumeIntervalId);A=Math.floor(Math.max(A,100)),S.emit(K.AUDIO_LEVEL_INTERVAL,{interval:A}),this._audioVolumeIntervalId&&nn.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=nn.run("intervalInWorker",()=>{var o;ux.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(A,e);let n=[];(o=this.remotePublishedUserMap)==null||o.forEach(a=>{if(a.muteState.hasAudio){!ux.isRunning&&a.muteState.audioAvailable&&a.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(a):a.remoteAudioTrack.volume=0;let I=Math.floor(100*a.remoteAudioTrack.getAudioLevel());n.push({userId:a.userId,volume:I,floatVolume:a.remoteAudioTrack.getInternalAudioLevel()})}}),this.emit("audio-volume",n)},{delay:A,backgroundTask:e})}updateAudioLevelFromSenderStat(A,e){return DA(this,null,function*(){var o;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let n=(o=this.uplinkConnection.getPeerConnection())==null?void 0:o.getSenders()[0];if(!n)return;let a=Math.max(A,500);this._log.warn("updateAudioLevelFromSenderStat ".concat(a)),this._updateAudioLevelTaskId=nn.run("intervalInWorker",()=>DA(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack)return void this.stopUpdateAudioLevelFromSenderStat();let I=yield n.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:c}=this.uplinkConnection;I.forEach(u=>{u.type==="media-source"&&u.audioLevel&&(c.volume=u.audioLevel)})}),{delay:a,backgroundTask:e})})}stopUpdateAudioLevelFromSenderStat(){var A;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),nn.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(A=this.uplinkConnection)!=null&&A.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(A){var e;let{audioReceiver:o}=A;if(!LT||!o)return;let n=(e=o.getSynchronizationSources()[0])==null?void 0:e.audioLevel;hr(n)?A.remoteAudioTrack.volume=Math.min(2*n,1):o.getStats().then(a=>{a.forEach(I=>{I.type==="inbound-rtp"&&hr(I.audioLevel)&&(A.remoteAudioTrack.volume=I.audioLevel)})})}getLocalAudioStats(){return DA(this,null,function*(){var A;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(A=this.uplinkConnection)!=null&&A.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return DA(this,null,function*(){var A,e;let o={};return o[this.userId]=((e=(A=this.uplinkConnection)==null?void 0:A.localMainVideoTrack)==null?void 0:e.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},o})}getTransportStats(){return DA(this,null,function*(){let A={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let e=yield this._stats.getSenderStats(this.uplinkConnection);A.rtt=e.rtt}for(let[,e]of this.remotePublishedUserMap){let o=yield this._stats.getReceiverStats(e);A.downlinksRTT[o.userId]=o.rtt}return A})}getRemoteVideoStats(A){return DA(this,null,function*(){let e={};for(let[o,n]of this.remotePublishedUserMap)A==="main"&&n.muteState.hasVideo&&(e[o]=n.remoteVideoTrack.stat),A==="auxiliary"&&n.muteState.hasAuxiliary&&(e[o]=n.remoteAuxiliaryTrack.stat);return e})}getRemoteAudioStats(){return DA(this,null,function*(){let A={};for(let[e,o]of this.remotePublishedUserMap)o.muteState.hasAudio&&(A[e]=o.remoteAudioTrack.stat);return A})}setTurnServer(A,e){this._log.info("set turn server: ".concat(JSON.stringify(A)," ").concat(e||""));let o=[];Array.isArray(A)?A.forEach(n=>o.push(il.getTurnServer(n))):il.isPlainObject(A)&&o.push(il.getTurnServer(A)),this._turnServers=o,e&&(this._iceTransportPolicy=e)}sendStartMixTranscode(A){return this.signalChannel.sendWaitForResponse({command:atA,data:A,timeout:5e3,responseCommand:io.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(e=>{if(e.code!==Ge.API_CALL_ABORTED)throw e})}sendStopMixTranscode(A){return this.signalChannel.sendWaitForResponse({command:stA,data:A,timeout:5e3,responseCommand:io.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(e=>{if(e.code!==Ge.API_CALL_ABORTED)throw e})}sendStartPublishCDN(A){let e=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:e?itA:rtA,data:A,timeout:5e3,responseCommand:e?io.START_PUBLISH_TENCENT_CDN_RES:io.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(o=>{if(o.code!==Ge.API_CALL_ABORTED)throw o})}sendStopPublishCDN(A){let e=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:e?otA:ntA,data:A,timeout:5e3,responseCommand:e?io.STOP_PUBLISH_TENCENT_CDN_RES:io.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(o=>{if(o.code!==Ge.API_CALL_ABORTED)throw o})}sendStartPushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:gtA,data:A,timeout:5e3,responseCommand:io.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(e=>{if(e.code!==Ge.API_CALL_ABORTED)throw e})}sendUpdatePushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:ItA,data:A,timeout:5e3,responseCommand:io.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(e=>{if(e.code!==Ge.API_CALL_ABORTED)throw e})}sendStopPushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:ctA,data:A,timeout:5e3,responseCommand:io.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(e=>{if(e.code!==Ge.API_CALL_ABORTED)throw e})}sendAbilityStatus(A){var e;(e=this.signalChannel)==null||e.sendWaitForResponse({command:utA,data:A,timeout:5e3,responseCommand:io.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(o=>{})}getIceServers(A){var e,o;return this._turnServers.length>0?this._turnServers:(e=this.scheduleResult.iceServers)!=null&&e.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:""},e=il.getEnv();return e?(A.mainUrl="wss://".concat(il.getTestSignalDomain(e)),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,e,o,n,a,I){return DA(this,null,function*(){var c;if(this.isJoined)throw new Ct({code:Ge.INVALID_OPERATION,message:"already joined room"});if(!a&&!I)throw new Ct({code:Ge.INVALID_OPERATION,message:"roomId or strRoomId is required"});if((c=this.signalChannel)!=null&&c.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=e,this.sdkAppId=A,this.userSig=o,this.roomId=String(a||I),this.useStringRoomId=!(!I||a),this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.prelinkPromise=Promise.race([this.doPrelink(A,e,o,n,a,I),new Promise((u,d)=>{this.prelinkTimeoutId=setTimeout(()=>{d(new Ct({code:Ge.INVALID_OPERATION,message:"prelink timeout after ".concat(this.PRELINK_TIMEOUT,"ms")}))},this.PRELINK_TIMEOUT)})]).then(()=>{this.clearPrelinkTimeout()}).catch(u=>{throw this.clearPrelinkTimeout(),this.closePrelink().catch(()=>{}),u}),this.prelinkPromise})}doPrelink(A,e,o,n,a,I){return DA(this,null,function*(){var c,u,d;try{if(!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!il.getEnv()&&(yield this.schedule({sdkAppId:A,userId:e,userSig:o,roomId:a,strRoomId:I,role:20,privateMapKey:null,businessInfo:null,streamId:null,userDefineRecordId:null},n)),(c=this.scheduleResult.config)==null||!c.prelink)throw new Ct({code:Ge.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}),(u=this.signalChannel)==null||u.markPrelinkConnected({sdkAppId:A,userId:e,userSig:o}),(d=this.signalChannel)==null||d.stopPrelinkIn(this.PRELINK_EXPIRED_TIME/1e3),this._log.info("prelink success")}catch(R){throw this._log.error("prelink failed",R),R}})}clearPrelinkTimeout(){this.prelinkTimeoutId&&(clearTimeout(this.prelinkTimeoutId),this.prelinkTimeoutId=null)}closePrelink(){return DA(this,null,function*(){var A;if(this.isJoined)throw new Ct({code:Ge.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 DA(this,null,function*(){let{subscribeState:e,userId:o,muteState:{hasSmall:n,hasVideo:a}}=A;if(!n&&!a||!e.video&&!e.smallVideo)return;let I=this._changeBigSmallRecords.get(o);if(!I||I.isSubscribing||I.reSubscribeCount<=0)return;let{options:c,reSubscribeCount:u}=I;if(c.video&&e.video||c.smallVideo&&e.smallVideo&&n)return;let d={audio:A.remoteAudioTrack.isSubscribed||A.remoteAudioTrack.isSubscribing,auxiliary:A.remoteAuxiliaryTrack.isSubscribed||A.remoteAuxiliaryTrack.isSubscribing,video:c.video,smallVideo:c.smallVideo,datachannel:A.subscribeState.datachannel};try{if(!n&&d.smallVideo&&(d.video=!0,d.smallVideo=!1),d.smallVideo===e.smallVideo&&d.video===e.video)return;I.isSubscribing=!0,I.reSubscribeCount=u-1,yield A.subscribe(d,"main"),A.remoteVideoTrack.setMediaType(d.smallVideo?8:4),this._log.info("change [".concat(o,"] to ").concat(d.smallVideo?"small":"big"," video successfully. count ").concat(xf-I.reSubscribeCount,".")),I.isSubscribing=!1,I.reSubscribeCount=xf}catch(R){this._log.info("change [".concat(o,"] to ").concat(d.smallVideo?"small":"big"," video failed. count ").concat(xf-I.reSubscribeCount,". reason: ").concat(R)),I.isSubscribing=!1,I.reSubscribeCount===0&&this._changeBigSmallRecords.delete(o)}})}changeType(A,e){let o={options:{video:!A,smallVideo:A},isSubscribing:!1,reSubscribeCount:xf};this._changeBigSmallRecords.set(e.userId,o),this._log.info("set [".concat(e.userId,"] video prefer type: ").concat(A?"small":"big")),this.emit("subscribe-small-video-changed",{userId:e.userId,isSmall:A});let n=this.remotePublishedUserMap.get(e.userId);n&&this.checkSubscribeBigSmallVideo(n)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(A){this._businessInfo=A.businessInfo;let e={};if(vz(A.businessInfo)&&(e=JSON.parse(A.businessInfo)),!Pm(A.pureAudioPushMode)){if(!Number.isInteger(Number(A.pureAudioPushMode)))throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_PURE_AUDIO})});this._pureAudioPushMode=A.pureAudioPushMode,e.Str_uc_params||(e.Str_uc_params={}),e.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!Pm(A.userDefineRecordId)){let o=/^[A-Za-z0-9_-]{1,64}$/gi;if(A.userDefineRecordId.match(o)===null)throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_USER_DEFINE_RECORDID})});e.Str_uc_params||(e.Str_uc_params={}),e.Str_uc_params.userdefine_record_id=A.userDefineRecordId}if(!Pm(A.userDefinePushArgs)){if(!(vz(A.userDefinePushArgs)&&String(A.userDefinePushArgs)&&String(A.userDefinePushArgs).length<=256))throw new Ct({code:Ge.INVALID_PARAMETER,message:Wi({key:Mi.INVALID_USER_DEFINE_PUSH_ARGS})});e.Str_uc_params||(e.Str_uc_params={}),e.Str_uc_params.userdefine_push_args=A.userDefinePushArgs}eiA(e)||(this._businessInfo=JSON.stringify(e))}sendCustomMessage(A){var e;(e=this._customMessageManager)==null||e.send(A)}enableInsertableStreams(){return DA(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&JQ)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(A){var e;return this.signalChannel?(e=this.signalChannel)==null?void 0:e.sendWaitForResponseWithRetry(A):Promise.reject(new Ct({code:Ge.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 DA(this,null,function*(){var e;if(!this.signalChannel||!this.singlePC)return;let{roomId:o,strRoomId:n,userSig:a,privateMapKey:I}=A,c=((e=this.scheduleResult.config)==null?void 0:e.autoSubscribeCount)||A?.autoSubscribeCount||1,u=String(this.useStringRoomId?n:o),d=[];for(let Z=0;Z{this.resolveSwitchRoomSubedReq=Z,AC(5e3).then(Z)}),S.emit(K.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();try{this.userManager.clear(),k=yield this.signalChannel.sendWaitForResponse({command:htA,responseCommand:io.SEND_SWITCH_ROOM_RES,data:R});let{code:Z,message:iA}=k.data;if(Z!==0){this._log.error("switch room failed. result: ".concat(Z," error: ").concat(iA));let cA=new Ct({code:Ge.SWITCH_ROOM_FAILED,extraCode:Z,message:iA});throw S.emit(K.SWITCH_ROOM_FAILED,{room:this,error:cA}),cA}this.userSig=a,Pm(I)||(this.privateMapKey=I),S.emit(K.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:_,targetRoomId:u})}catch(Z){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=_,this.resolveSwitchRoomSubedReq(),Z}})}isSwitchRoomSupported(){var A;let e="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(e," Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.")),!1):this.scene!=="live"?(this._log.warn("".concat(e," Reason: the scene is not 'live'.")),!1):this.role!=="audience"?(this._log.warn("".concat(e," Reason: the role is not 'audience'.")),!1):!!this.singlePC||(this._log.warn("".concat(e," 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 e=0;e<5;e++)A.push(this.updateNTPTime());return Promise.all(A).then(e=>{var o;let n=e[0].offset,a=e[0].offset;e.forEach(u=>{n=Math.min(u.offset,n),a=Math.max(u.offset,a)});let I=Math.floor(e.reduce((u,d)=>u+d.rtt,0)/e.length),c=Math.floor(e.reduce((u,d)=>u+d.offset,0)/e.length);(a-n>30||I>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),nu(c),(o=this.scriptTransformWorker)==null||o.postMessage({type:"ntp-offset",data:c}),this._log.debug("ntp updated offset: ".concat(c)),this.emit("ntp-time-updated")}).catch(e=>{this._log.warn("ntp updated failed: ".concat(e))})}updateNTPTime(){let A=Date.now();return this.signalChannel.sendWaitForResponse({command:ptA,responseCommand:io.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(A)},enableLog:!1}).then(e=>{let o=Number(e.data.data.serverSendTime),n=Number(e.data.data.serverRecvTime),a=e.data.receiveTime||Date.now();return{rtt:a-A-(n-o),offset:(n-A+(o-a))/2}})}};return vt([is(["left",Uo.INIT],"joined"),nB({settings:{retries:1,timeout:0},onRetrying(A){this._log.warn("join retry ".concat(A))},onRetryFailed(A){this._log.error("join failed",A)},onError(A,e){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),Nu(!0),this.reset(),e()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),e()):(this.reset(),e())}}),Dn(A=>{let e=new jeA;return function(o,n,a){return DA(this,null,function*(){let I=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=n,o.privateMapKey=o.privateMapKey||"",this.isJoined)throw new Ct({code:Ge.INVALID_OPERATION,message:Wi({key:Mi.INVALID_JOIN})});if(this.checkDestroy(),e.isJoined({userId:this.userId,roomId:I,sdkAppId:this.sdkAppId,room:this}))throw new Ct({code:Ge.INVALID_OPERATION,message:Wi({key:Mi.REPEAT_JOIN,data:this.userId})});e.add({room:this,roomId:I}),this.role=o.role===21?"audience":"anchor",this._log.info("Join() => joining room: ".concat(I," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),S.emit(K.JOIN_START,{room:this,roomId:I,params:o});let c=il.getEnv();c||(c=au.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(lh.OLD_CLOUD_LADDER)?c=au.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(lh.WEBRTC)&&(c=au.WEBRTC))),Jo.setConfig({env:c,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:I}),kA.checkSystemRequirementsInternal(a).then(u=>{this.checkSystemResult=u,WeA.call(this)});try{!this.prelinkPromise&&!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!il.getEnv()&&(yield this.schedule(o,a));let u=yield A.call(this,o,n,a);return this.roomId=I,this._joinedTimestamp=il.performanceNow(),S.emit(K.JOIN_SUCCESS,{room:this}),a===30&&!o.component&&Jo.uploadEvent({log:"stat-conv-".concat(Number(bQ),"-").concat(location.hostname),userId:this.userId}),u}catch(u){throw e.delete({room:this,roomId:I}),S.emit(K.JOIN_FAILED,{room:this,error:u}),u}})}})],op.prototype,"join"),vt([is("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Dn(A=>function(){for(var e=arguments.length,o=new Array(e),n=0;nA.mediaType),Dn(A=>function(){for(var e=arguments.length,o=new Array(e),n=0;nI.outMediaTrack&&I.state==="ready"),!o.length))return;S.emit("61",{room:this});let a=A.apply(this,o);return Promise.all(o.map(I=>I.publish(this,a)))})}),nB({settings:{retries:Qh,timeout:A=>yQ(A)},onError(A,e,o,n){let[a]=n;var I;(I=A.message)!=null&&I.includes("timeout")?(this._log.warn("publish ".concat(a.strMediaType," timeout"),A),e()):(this._log.error("publish ".concat(a.strMediaType," failed: ").concat(A)),o(A),S.emit(K.PUBLISH_FAILED,{room:this}))}})],op.prototype,"publish"),vt([_M({fnName:"publish"}),zh(A=>A.mediaType),Dn(A=>function(){for(var e=arguments.length,o=new Array(e),n=0;nI.unpublish()),a}),Tm(function(){var A,e;this.localTracks.size===0&&AI()&&((e=(A=this.singlePC)==null?void 0:A.getPeerConnection())==null||e.getSenders().forEach(o=>o.track&&o.replaceTrack(null)))})],op.prototype,"unpublish"),vt([_W(A=>{if(A.code!==Ge.API_CALL_ABORTED)throw A}),zh(A=>A.userId)],op.prototype,"replaceTrack"),vt([zh(function(){for(var A=arguments.length,e=new Array(A),o=0;ofunction(){for(var e=arguments.length,o=new Array(e),n=0;n!I.isSubscribed&&I.subscribe(a)),a}),nB({settings:{retries:Qh,timeout:A=>yQ(A)},onError(A,e,o,n){if(A.message.includes("timeout"))this._log.warn("subscribe timeout"),e();else{let a=A?.code===Ge.API_CALL_ABORTED;this._log[a?"warn":"error"]("subscribe failed ".concat(n.map(I=>I.strMediaType).join(","),": ").concat(A)),o(A),S.emit(K.SUBSCRIBE_FAILED,{room:this,remoteTracks:n})}}})],op.prototype,"subscribe"),vt([_M({fnName:"subscribe",callback(){for(var A=arguments.length,e=new Array(A),o=0;o{let a=this.remotePublishedUserMap.get(n.userId);a&&!a.isMainStreamSubscribed&&!a.isAuxStreamSubscribed&&a.close("you unsubscribed")})}}),zh(function(){for(var A=arguments.length,e=new Array(A),o=0;oi in t?MY(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,HrA=(t,i)=>{for(var r in i||(i={}))C6.call(i,r)&&Tj(t,r,i[r]);if(h5)for(var r of h5(i))JrA.call(i,r)&&Tj(t,r,i[r]);return t},VrA=(t,i)=>function(){return i||(0,t[l6(t)[0]])((i={exports:{}}).exports,i),i.exports},qrA=(t,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let g of l6(i))C6.call(t,g)||g===r||MY(t,g,{get:()=>i[g],enumerable:!(s=E6(i,g))||s.enumerable});return t},KrA=(t,i,r)=>(r=t!=null?YrA(PrA(t)):{},qrA(MY(r,"default",{value:t,enumerable:!0}),t)),Ew=(t,i,r,s)=>{for(var g,B=E6(i,r),Q=t.length-1;Q>=0;Q--)(g=t[Q])&&(B=g(i,r,B)||B);return B&&MY(i,r,B),B},rr=(t,i,r)=>Tj(t,typeof i!="symbol"?i+"":i,r),jrA=VrA({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(t,i){var r=Object.prototype.hasOwnProperty,s="~";function g(){}function B(M,v,U){this.fn=M,this.context=v,this.once=U||!1}function Q(M,v,U,AA,z){if(typeof U!="function")throw new TypeError("The listener must be a function");var sA=new B(U,AA||M,z),eA=s?s+v:v;return M._events[eA]?M._events[eA].fn?M._events[eA]=[M._events[eA],sA]:M._events[eA].push(sA):(M._events[eA]=sA,M._eventsCount++),M}function f(M,v){--M._eventsCount===0?M._events=new g:delete M._events[v]}function m(){this._events=new g,this._eventsCount=0}Object.create&&(g.prototype=Object.create(null),new g().__proto__||(s=!1)),m.prototype.eventNames=function(){var M,v,U=[];if(this._eventsCount===0)return U;for(v in M=this._events)r.call(M,v)&&U.push(s?v.slice(1):v);return Object.getOwnPropertySymbols?U.concat(Object.getOwnPropertySymbols(M)):U},m.prototype.listeners=function(M){var v=s?s+M:M,U=this._events[v];if(!U)return[];if(U.fn)return[U.fn];for(var AA=0,z=U.length,sA=new Array(z);AA{if(!navigator.userAgent.includes("Firefox"))return t;const i=t.split(`\r `),r=[],s=[];i.forEach(Q=>{const f=Q.toLowerCase();f.includes("a=rtpmap")&&f.includes("h264")&&r.push(Q)}),r.length>1&&s.push(...r.slice(1));const g=s.map(Q=>{const f=/a=rtpmap:(\d+)\s/.exec(Q);return f&&f.length>1?f[1]:null}).filter(Q=>Q!==null),B=[];return i.forEach(Q=>{let f=Q;if(Q.includes("a=setup")&&(f="a=setup:passive"),(Q.includes("m=audio")||Q.includes("m=video"))&&(f=Q.split(" ").filter((m,M)=>M<3||!g.includes(m)).join(" ")),Q.includes("a=fmtp")||Q.includes("a=rtcp-fb")||Q.includes("a=rtpmap")){const m=/a=(?:fmtp|rtcp-fb|rtpmap):(\d+)\s/.exec(Q);if(m&&m.length>1&&g.includes(m[1]))return}B.push(f)}),B.join(`\r -`)},l5=t=>{const i=t.split(`\r +`)},p5=t=>{const i=t.split(`\r `),r=[];i.forEach(Q=>{const f=Q.toLowerCase();f.includes("a=rtpmap")&&f.includes("h264")&&r.push(Q)});const s=r.map(Q=>{const f=/a=rtpmap:(\d+)\s/.exec(Q);return f&&f.length>1?f[1]:null}).filter(Q=>Q!==null),g=[];i.forEach(Q=>{let f=Q;if(Q.includes("a=fmtp:111")&&(f=`${Q};stereo=1`),Q.includes("a=fmtp")){const m=/a=fmtp:(\d+)\s/.exec(Q);m&&m.length>1&&s.includes(m[1])&&(f=`${Q};sps-pps-idr-in-keyframe=1`)}g.push(f)});const B=g.join(`\r -`);return OrA(B)},xrA="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",SK=(t=21)=>{let i="",r=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)i+=xrA[63&r[t]];return i},tw=t=>typeof t=="function",YrA=0,PrA=1,C5=2;function JrA({retryFunction:t,settings:i,onError:r,onRetrying:s,onRetryFailed:g,onRetrySuccess:B,context:Q}){return function(...f){const{retries:m=5,timeout:M=1e3}=i;let v=0,U=-1,AA=YrA;const z=async(sA,eA)=>{const X=Q||this;try{const QA=await t.apply(X,f);v>0&&B&&B.call(this,v),v=0,sA(QA)}catch(QA){const wA=()=>{clearTimeout(U),v=0,AA=C5,eA(QA)},HA=()=>{AA!==C5&&v<(tw(m)?m():m)?(v++,AA=PrA,tw(s)&&s.call(this,v,wA),U=window.setTimeout(()=>{U=-1,z(sA,eA)},tw(M)?M(v):M)):(wA(),tw(g)&&g.call(this,QA))};tw(r)?r.call(this,{error:QA,retry:HA,reject:eA,retryFuncArgs:f,retriedCount:v}):HA()}};return new Promise(z)}}var HrA=JrA,Nu=new WeakMap;function VrA({settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:s}){return function(g,B,Q){const f=HrA({retryFunction:Q.value,settings:t,onError({error:m,retry:M,reject:v,retryFuncArgs:U}){var AA;i?i.call(this,m,()=>{var z;(z=Nu.get(g))!=null&&z.has(B)?M():v(m)},v,U):(AA=Nu.get(g))!=null&&AA.has(B)?M():v(m)},onRetrying(m,M){var v;tw(r)&&r.call(this,m,M),(v=Nu.get(g))!=null&&v.has(B)&&(Nu.get(g).get(B).stopRetry=M)},onRetryFailed:s});return Q.value=function(...m){const M=Nu.get(g);return M?M.set(B,{args:m}):Nu.set(g,new Map([[B,{args:m}]])),f.apply(this,m).finally(()=>{var v;return(v=Nu.get(g))==null?void 0:v.delete(B)})},Q}}function qrA({fnName:t,callback:i,validateArgs:r=!0}){return function(s,g,B){const Q=B.value;return B.value=function(...f){var m,M;if((m=Nu.get(s))!=null&&m.has(t)){const{stopRetry:v,args:U}=Nu.get(s).get(t);let AA=!0;if(r){for(const z of U)if(!f.find(sA=>sA===z)){AA=!1;break}}AA&&(i&&i.apply(this,f),v&&v(),(M=Nu.get(s))==null||M.delete(t))}return Q.apply(this,f)},B}}var KrA=class{constructor(t,i){this.core=i,rr(this,"peerConnection"),rr(this,"audioTransceiver",null),rr(this,"videoTransceiver",null),rr(this,"timerId",null),rr(this,"callback",null),rr(this,"previousRawStats",null),rr(this,"_prevReportTime",0),rr(this,"_prevDecoderImplementation",""),rr(this,"_decodeMap",new Map),this.peerConnection=t,this.findTransceivers()}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}findTransceivers(){const t=this.peerConnection.getTransceivers();for(const i of t)if(i.receiver&&i.receiver.track){const{track:r}=i.receiver;r.kind==="audio"?this.audioTransceiver=i:r.kind==="video"&&(this.videoTransceiver=i)}}start(t,i=2e3){this.stop(),this.callback=t,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 t=await this.peerConnection.getStats(),i=new Set(["inbound-rtp","track","candidate-pair","media-source","codec"]),r=[];t.forEach(f=>i.has(f.type)&&r.push(f));const s=Date.now(),g=this.parseAudioStats(r),B=this.parseVideoStats(r),Q=this.parseNetworkStats(r);this._prevReportTime=s,this.callback({audio:g,video:B,network:Q})}catch(t){this.core.log.error("Failed to collect WebRTC stats:",t)}}getDifferenceValue(t,i){if(this.core.utils.isUndefined(t))return i;const r=(i||0)-t;return r<0?0:r}parseAudioStats(t){var i,r,s,g;const B={bitrate:0,volume:0,packetLossRate:0,jitterBufferDelay:0,bytesReceived:0,packetsReceived:0,packetsLost:0};for(const Q of t){if(Q.type==="inbound-rtp"&&(Q.mediaType==="audio"||Q.kind==="audio")){if(B.bytesReceived=Q.bytesReceived||0,B.packetsReceived=Q.packetsReceived||0,B.packetsLost=Q.packetsLost||0,this.previousRawStats&&this.previousRawStats.audio){const M=this.getDifferenceValue(this.previousRawStats.audio.bytesReceived,B.bytesReceived);B.bitrate=Math.round(8*M/this.statInterval/1e3)}const f=this.getDifferenceValue((i=this.previousRawStats)==null?void 0:i.audio.packetsLost,B.packetsLost),m=this.getDifferenceValue((r=this.previousRawStats)==null?void 0:r.audio.packetsReceived,B.packetsReceived)+f;if(m>0&&(B.packetLossRate=Math.round(f/m*100)),this.core.utils.isUndefined(Q.audioLevel)||(B.volume=Q.audioLevel||0),Q.jitterBufferDelay&&Q.jitterBufferEmittedCount){let{jitterBufferEmittedCount:M}=Q,{jitterBufferDelay:v}=Q;(s=this.previousRawStats)!=null&&s.audio&&(M=this.getDifferenceValue(this.previousRawStats.audio.jitterBufferEmittedCount,Q.jitterBufferEmittedCount),v=this.getDifferenceValue(this.previousRawStats.audio.jitterBufferDelay,Q.jitterBufferDelay)),M>0&&(B.jitterBufferDelay=Math.floor(v/M*1e3)),this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.audio.jitterBufferDelay=Q.jitterBufferDelay,this.previousRawStats.audio.jitterBufferEmittedCount=Q.jitterBufferEmittedCount}this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.audio.bytesReceived=B.bytesReceived,this.previousRawStats.audio.packetsReceived=B.packetsReceived,this.previousRawStats.audio.packetsLost=B.packetsLost}!this.core.utils.isUndefined(Q.audioLevel)&&((g=this.audioTransceiver)!=null&&g.receiver.track)&&Q.trackIdentifier===this.audioTransceiver.receiver.track.id&&(B.volume=Q.audioLevel||0)}return B}parseVideoStats(t){var i,r,s,g,B;const Q={bitrate:0,frameRate:0,width:0,height:0,packetLossRate:0,jitterBufferDelay:0,bytesReceived:0,packetsReceived:0,packetsLost:0,framesDecoded:0};for(const f of t){if(f.type==="codec"&&this._decodeMap.set(f.id,f),f.type==="inbound-rtp"&&(f.mediaType==="video"||f.kind==="video")){if(Q.bytesReceived=f.bytesReceived||0,Q.packetsReceived=f.packetsReceived||0,Q.packetsLost=f.packetsLost||0,Q.framesDecoded=f.framesDecoded||0,this.core.utils.isUndefined(f.framesPerSecond)||(Q.frameRate=Math.round(f.framesPerSecond)),f.decoderImplementation&&this._prevDecoderImplementation!==f.decoderImplementation){const v=this._decodeMap.get(f.codecId),U=((i=v?.mimeType)==null?void 0:i.split("/")[1])||"unknown",AA=f.powerEfficientDecoder;this.core.log.info(`decoderImplementation change to ${f.decoderImplementation}(${U}) HWDecoder: ${AA}`),this._prevDecoderImplementation=f.decoderImplementation}if(this.previousRawStats&&this.previousRawStats.video){const v=this.getDifferenceValue(this.previousRawStats.video.bytesReceived,Q.bytesReceived);Q.bitrate=Math.round(8*v/this.statInterval/1e3)}const m=this.getDifferenceValue((r=this.previousRawStats)==null?void 0:r.video.packetsLost,Q.packetsLost),M=this.getDifferenceValue((s=this.previousRawStats)==null?void 0:s.video.packetsReceived,Q.packetsReceived)+m;if(M>0&&(Q.packetLossRate=Math.round(m/M*100)),f.jitterBufferDelay&&f.jitterBufferEmittedCount){let{jitterBufferEmittedCount:v}=f,{jitterBufferDelay:U}=f;(g=this.previousRawStats)!=null&&g.video&&(v=this.getDifferenceValue(this.previousRawStats.video.jitterBufferEmittedCount,f.jitterBufferEmittedCount),U=this.getDifferenceValue(this.previousRawStats.video.jitterBufferDelay,f.jitterBufferDelay)),v>0&&(Q.jitterBufferDelay=Math.floor(U/v*1e3)),this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.video.jitterBufferDelay=f.jitterBufferDelay,this.previousRawStats.video.jitterBufferEmittedCount=f.jitterBufferEmittedCount}this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.video.bytesReceived=Q.bytesReceived,this.previousRawStats.video.packetsReceived=Q.packetsReceived,this.previousRawStats.video.packetsLost=Q.packetsLost}!this.core.utils.isUndefined(f.frameWidth)&&((B=this.videoTransceiver)!=null&&B.receiver.track)&&f.trackIdentifier===this.videoTransceiver.receiver.track.id&&(Q.width=f.frameWidth,Q.height=f.frameHeight)}return Q}parseNetworkStats(t){const i={rtt:0};for(const r of t)if(r.type==="candidate-pair"&&(r.selected||r.state==="succeeded")&&this.core.utils.isNumber(r.currentRoundTripTime)){i.rtt=Math.floor(1e3*r.currentRoundTripTime);break}return i}initPreviousRawStats(){this.previousRawStats={timestamp:Date.now(),audio:{bytesReceived:0,packetsReceived:0,packetsLost:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0}}}},jrA=LrA(FrA()),B5=Symbol("instance"),A2=Symbol("cacheResult"),vK=class{constructor(i,r,s){this.oldState=i,this.newState=r,this.action=s,this.aborted=!1}abort(i){this.aborted=!0,HG.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},NK=class extends Error{constructor(i,r,s){super(r),this.state=i,this.message=r,this.cause=s}};function WrA(t){return typeof t=="object"&&t&&"then"in t}var JG=new Map;function e2(t,i,r={}){return(s,g,B)=>{const Q=r.action||g;if(!r.context){const m=JG.get(s)||[];JG.has(s)||JG.set(s,m),m.push({from:t,to:i,action:Q})}const f=B.value;B.value=function(...m){let M=this;if(r.context&&(M=uC.get(typeof r.context=="function"?r.context.call(this,...m):r.context)),M.state===i)return r.sync?M[A2]:Promise.resolve(M[A2]);M.state instanceof vK&&M.state.action==r.abortAction&&M.state.abort(M);let v=null;Array.isArray(t)?t.length==0?M.state instanceof vK&&M.state.abort(M):typeof M.state=="string"&&t.includes(M.state)||(v=new NK(M._state,`${M.name} ${Q} to ${i} failed: current state ${M._state} not from ${t.join("|")}`)):t!==M.state&&(v=new NK(M._state,`${M.name} ${Q} to ${i} failed: current state ${M._state} not from ${t}`));const U=X=>{if(r.fail&&r.fail.call(this,X),r.sync){if(r.ignoreError)return X;throw X}return r.ignoreError?Promise.resolve(X):Promise.reject(X)};if(v)return U(v);const AA=M.state,z=new vK(AA,i,Q);HG.call(M,z);const sA=X=>{var QA;return M[A2]=X,z.aborted||(HG.call(M,i),(QA=r.success)===null||QA===void 0||QA.call(this,M[A2])),X},eA=X=>(HG.call(M,AA,X),U(X));try{const X=f.apply(this,m);return WrA(X)?X.then(sA).catch(eA):r.sync?sA(X):Promise.resolve(sA(X))}catch(X){return eA(new NK(M._state,`${M.name} ${Q} from ${t} to ${i} failed: ${X}`,X instanceof Error?X:new Error(String(X))))}}}}var zrA=typeof window<"u"&&window.__AFSM__?(r,s)=>{window.dispatchEvent(new CustomEvent(r,{detail:s}))}:typeof importScripts<"u"?(r,s)=>{postMessage({type:r,payload:s})}:()=>{};function HG(t,i){const r=this._state;this._state=t;const s=t.toString();t&&this.emit(s,r),this.emit(uC.STATECHANGED,t,r,i),this.updateDevTools({value:t,old:r,err:i instanceof Error?i.message:String(i)})}var uC=class EC extends jrA.default{constructor(i,r,s){super(),this.name=i,this.groupName=r,this._state=EC.INIT,i||(i=Date.now().toString(36)),s?Object.setPrototypeOf(this,s):s=Object.getPrototypeOf(this),r||(this.groupName=this.constructor.name);const g=s[B5];g?this.name=g.name+"-"+g.count++:s[B5]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){const i=Object.getPrototypeOf(this),r=JG.get(i)||[];let s=new Set,g=[],B=[];const Q=new Set,f=Object.getPrototypeOf(i);JG.has(f)&&(f.stateDiagram.forEach(M=>s.add(M)),f.allStates.forEach(M=>Q.add(M))),r.forEach(({from:M,to:v,action:U})=>{typeof M=="string"?g.push({from:M,to:v,action:U}):M.length?M.forEach(AA=>{g.push({from:AA,to:v,action:U})}):B.push({to:v,action:U})}),g.forEach(({from:M,to:v,action:U})=>{Q.add(M),Q.add(v),Q.add(U+"ing"),s.add(`${M} --> ${U}ing : ${U}`),s.add(`${U}ing --> ${v} : ${U} 🟢`),s.add(`${U}ing --> ${M} : ${U} 🔴`)}),B.forEach(({to:M,action:v})=>{s.add(`${v}ing --> ${M} : ${v} 🟢`),Q.forEach(U=>{U!==M&&s.add(`${U} --> ${v}ing : ${v}`)})});const m=[...s];return Object.defineProperties(i,{stateDiagram:{value:m},allStates:{value:Q}}),m}static get(i){let r;return typeof i=="string"?(r=EC.instances.get(i),r||EC.instances.set(i,r=new EC(i,void 0,Object.create(EC.prototype)))):(r=EC.instances2.get(i),r||EC.instances2.set(i,r=new EC(i.constructor.name,void 0,Object.create(EC.prototype)))),r}static getState(i){var r;return(r=EC.get(i))===null||r===void 0?void 0:r.state}updateDevTools(i={}){zrA(EC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){HG.call(this,i)}};uC.STATECHANGED="stateChanged",uC.UPDATEAFSM="updateAFSM",uC.INIT="[*]",uC.ON="on",uC.OFF="off",uC.instances=new Map,uC.instances2=new WeakMap;var MG=class extends uC{constructor(i,r){super(),this.core=i,rr(this,"audioPlayer"),rr(this,"videoPlayer"),rr(this,"callback"),rr(this,"avPlayerStateSyncManager"),rr(this,"_log"),rr(this,"_videoPlayerLog"),rr(this,"_audioPlayerLog"),rr(this,"lastPausedReason"),rr(this,"muted",!1),this._log=r,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,s=>this.handleAutoPlayFailed(this.audioPlayer,s)),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,r;await this.videoPlayer.enterPIPPromise,(r=(i=this.callback)==null?void 0:i.onPictureInPictureStateChanged)==null||r.call(i,{isPictureInPicture:!0,pictureInPictureWindow:this.videoPlayer.pipWindow})}handleLeavePictureInPicture(){var i,r;(r=(i=this.callback)==null?void 0:i.onPictureInPictureStateChanged)==null||r.call(i,{isPictureInPicture:!1})}handleEnterFullScreen(){var i,r;(r=(i=this.callback)==null?void 0:i.onFullScreenStateChanged)==null||r.call(i,{isFullScreen:!0})}handleLeaveFullScreen(){var i,r;(r=(i=this.callback)==null?void 0:i.onFullScreenStateChanged)==null||r.call(i,{isFullScreen:!1})}onLoadStart(){}onPlaying(){}onPaused(i){this.lastPausedReason=i}onStopped(){}setVideoContainer(i){if(this.core.utils.isString(i)){const r=document.getElementById(i);r&&this.videoPlayer.setContainer(r)}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(s=>{this.handleAutoPlayFailed(this.videoPlayer,s,"video")}),r=this.audioPlayer.play().catch(s=>{this.handleAutoPlayFailed(this.audioPlayer,s)});await Promise.all([i,r])}handleAutoPlayFailed(i,r,s="audio"){var g,B;this._log.warn("handleAutoPlayFailed",r);const Q=()=>{this.audioPlayer.resume().then(()=>{document.removeEventListener("click",Q,!0)})};document.addEventListener("click",Q,!0),(B=(g=this.callback)==null?void 0:g.onAutoPlayFailed)==null||B.call(g,{type:s,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))}};gw([e2([uC.INIT,"PAUSED"],"LOADSTART",{ignoreError:!0,sync:!0,success(){var t,i;(i=(t=this.callback)==null?void 0:t.onLoadStart)==null||i.call(t)},fail(t){this._log.warn("onLoadStart",t)}})],MG.prototype,"onLoadStart"),gw([e2(["LOADSTART","PAUSED"],"PLAYING",{ignoreError:!0,sync:!0,success(){var t,i;(i=(t=this.callback)==null?void 0:t.onPlaying)==null||i.call(t)},fail(t){this._log.warn("onPlaying",t)}})],MG.prototype,"onPlaying"),gw([e2("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(){var t,i;(i=(t=this.callback)==null?void 0:t.onPaused)==null||i.call(t,{reason:this.lastPausedReason})},fail(t){this._log.warn("onPaused",t)}})],MG.prototype,"onPaused"),gw([e2([],uC.INIT,{ignoreError:!0,sync:!0,success(){var t,i;(i=(t=this.callback)==null?void 0:t.onStopped)==null||i.call(t)},fail(t){this._log.warn("onStopped",t)}})],MG.prototype,"onStopped");var u5=MG,ZrA=["overseas-webrtc.tlivewebrtc.com","oswebrtc-lint.tliveplay.com"],f2=class n6{constructor(i){this.core=i,rr(this,"_sdkAppId"),rr(this,"_userId"),rr(this,"connectedRoomIdSet",new Set),rr(this,"updateSeq",0),rr(this,"_log"),rr(this,"player"),rr(this,"peerConnection"),rr(this,"svrSig"),rr(this,"streamURL"),rr(this,"signalURL"),rr(this,"insertableStreamsAbortMap",new Map),rr(this,"scriptTransformWorker"),rr(this,"connectionState","disconnected"),rr(this,"isStarted",!1),rr(this,"isStopped",!0),rr(this,"isReconnecting",!1),rr(this,"callback"),rr(this,"isFireWallErrorEmitted",!1),rr(this,"stat"),rr(this,"isH264DecodeSupported"),rr(this,"connectionTimeoutId"),rr(this,"streamHealthCheckTimeoutId"),rr(this,"streamHealthCheckReject"),i.loggerManager.startUpload(),this._log=this.core.log.createChild({id:`${this.getAlias()}`}),this.player=new u5(i,this._log),i.innerEmitter.on(i.INNER_EVENT.SEI_MESSAGE,this.onSEIMessage,this)}getName(){return n6.Name}getAlias(){return"LEB"}getGroup(){return""}getValidateRule(i){switch(i){case"start":return UrA;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 r={},s=["onStats","onSEIMessage"];for(const g of Object.keys(i)){const B=i[g];typeof B=="function"&&(s.includes(g)?r[g]=B:r[g]=(...Q)=>(this._log.debug(`callback ${g} called`,Q.length>0?Q[0]:""),B(...Q)))}return r}async start(i){var r;this.isStopped=!1;const{view:s,url:g,volume:B,muted:Q,fillMode:f,loggerConfig:m,callback:M}=i;this.callback=this.wrapCallback(M),this.player.setCallback(this.callback);const{errorModule:{RtcError:v,ErrorCode:U,ErrorCodeDictionary:AA},loggerManager:z,rtcDectection:sA}=this.core;if(this._sdkAppId=m.sdkAppId,this._userId=m.userId,this._log.setSdkAppId(m.sdkAppId),this._log.setUserId(m.userId),this.player.updateLogConfig(m),z.addJoinedUser(m),!sA.isWebRTCSupported()||!sA.isAddTransceiverSupported())throw new v({code:U.ENV_NOT_SUPPORTED,extraCode:AA.NOT_SUPPORTED_WEBRTC,message:"webrtc not supported"});if(!(await sA.decodeSupportStatus()).isH264DecodeSupported||this.isH264DecodeSupported===!1)throw this.isH264DecodeSupported=!1,new v({code:U.ENV_NOT_SUPPORTED,extraCode:AA.NOT_SUPPORTED_H264_DECODE,message:"h264 not supported"});!sA.IS_SEI_SUPPORTED&&M?.onSEIMessage&&((r=M.onError)==null||r.call(M,new v({code:U.ENV_NOT_SUPPORTED,extraCode:AA.NOT_SUPPORTED_SEI,message:"sei not supported"}))),this.player.setVideoContainer(s),this.player.setMuted(Q),this.player.setFillMode(f);try{await this.connect(g),this.stat=new KrA(this.peerConnection,this.core),this.stat.start(QA=>{var wA,HA;return(HA=(wA=this.callback)==null?void 0:wA.onStats)==null?void 0:HA.call(wA,QA)});const eA=this.player.play();this.player.setVolume(B);const X=this.createStreamHealthCheckPromise();await Promise.race([eA,X]),this.clearStreamHealthCheck(),this.isStarted=!0}catch(eA){throw this.stop(),eA}}async update(i){const{view:r,url:s,volume:g,muted:B,fillMode:Q,action:f,fullScreen:m,pictureInPicture:M}=i;s&&s!==this.streamURL&&await this.switchStream(s),this.player.setMuted(B),this.player.setVolume(g),this.player.setFillMode(Q),r&&this.player.videoPlayer.setContainer(this.core.utils.isString(r)?document.getElementById(r):r),f==="pause"?this.player.pause():f==="resume"&&this.player.resume(),this.core.utils.isBoolean(m)&&(m?await this.player.enterFullscreen():await this.player.exitFullscreen()),this.core.utils.isBoolean(M)&&(M?await this.player.enterPictureInPicture():await this.player.exitPictureInPicture())}async switchStream(i){this._log.info("switchStream",i);const r=this.peerConnection,s=this.streamURL,g=this.signalURL,B=this.svrSig,Q=new Map(this.insertableStreamsAbortMap),f=this.player;delete this.peerConnection,delete this.streamURL,delete this.signalURL,delete this.svrSig,this.insertableStreamsAbortMap.clear();const m=new u5(this.core,this._log);m.setVideoContainer(f.videoPlayer.container),m.setFillMode(f.videoPlayer.objectFit),m.setMuted(f.muted),m.setCallback(this.callback);const M=v=>{const{track:U}=v;this.createEncodedStreams(v.receiver),this.initReceiverTransform(v.receiver,U.kind==="audio"),U.kind==="audio"?m.setAudioTrack(U):m.setVideoTrack(U)};try{await this.connectForSwitch(i,M),this._log.info("switchStream: new connection established"),await this.waitForNewPlayerFirstFrame(m),this._log.info("switchStream: new stream first frame received"),f.audioPlayer.setMuted(!0),f.stop(),this.player=m,r&&(clearTimeout(this.connectionTimeoutId),r.close(),r.getReceivers().forEach(v=>Q.delete(v)),s&&B&&g&&this.fetchStopStreamWithParams(s,g,B).catch(v=>{this._log.warn("switchStream: stop old stream failed",v)})),this._log.info("switchStream: switch completed successfully")}catch(v){this._log.error("switchStream failed",v),m.stop();const U=this.peerConnection;throw U&&(U.close(),U.getReceivers().forEach(AA=>this.insertableStreamsAbortMap.delete(AA))),this.peerConnection=r,this.streamURL=s,this.signalURL=g,this.svrSig=B,this.insertableStreamsAbortMap=Q,this.player=f,f.audioPlayer.setMuted(f.muted),v}}waitForNewPlayerFirstFrame(i){return new Promise((r,s)=>{let g=0,B=!1;const Q=i.videoPlayer.getElement();if(!Q)return void s(new Error("VideoPlayer has no video element"));const f=()=>{B=!0,clearInterval(v),Q.removeEventListener("loadeddata",m),Q.removeEventListener("playing",M)},m=()=>{B||(this._log.info("waitForNewPlayerFirstFrame: loadeddata event fired"),f(),r())},M=()=>{B||(this._log.info("waitForNewPlayerFirstFrame: playing event fired"),f(),r())};Q.addEventListener("loadeddata",m,{once:!0}),Q.addEventListener("playing",M,{once:!0}),i.play().catch(U=>{this._log.warn("waitForNewPlayerFirstFrame: play failed",U)});const v=setInterval(()=>{if(!B){if(g+=100,Q.videoWidth>0&&Q.videoHeight>0)return this._log.info(`waitForNewPlayerFirstFrame: video has valid dimensions ${Q.videoWidth}x${Q.videoHeight}`),f(),void r();g>=1e4&&(f(),s(new Error("waitForNewPlayerFirstFrame timeout")))}},100)})}connectForSwitch(i,r){return new Promise((s,g)=>{try{this.initScriptTransformWorker();const B={encodedInsertableStreams:this.enableSEI,iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},Q=new RTCPeerConnection(B);this.peerConnection=Q,Q.onconnectionstatechange=()=>{this.connectionState=Q.connectionState,this._log.info("connectForSwitch connectionState",Q.connectionState),Q.connectionState!=="failed"&&Q.connectionState!=="closed"||g(new Error(`connection is ${Q.connectionState}`)),Q.connectionState==="connected"&&(this.logSelectedCandidate(),s())},Q.ontrack=r,Q.addTransceiver("audio",{direction:"recvonly"}),Q.addTransceiver("video",{direction:"recvonly"}),this._log.info("connectForSwitch createOffer"),Q.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}).then(f=>(f.sdp=l5(f.sdp),this._log.info("connectForSwitch setOffer"),Q.setLocalDescription(f))).then(()=>{const f={sessionId:SK(),streamurl:i,clientinfo:this.core.environment.getOSString(),localsdp:Q.localDescription};return this.exchangeSDP(i,f)}).then(f=>(this._log.info("connectForSwitch setAnswer"),Q.setRemoteDescription(f))).catch(g)}catch(B){g(B)}this.connectionTimeoutId=setTimeout(()=>g(new Error("connection timeout")),1e4)})}async fetchStopStreamWithParams(i,r,s){try{const g=`${r}/webrtc/v1/stopstream`,B=await t2(g,{streamurl:i,svrsig:s},{timeout:3}),{errcode:Q,errmsg:f}=B;if(Q!==0)throw new Error(`errCode:${Q}, errmsg:${f}`);return B}catch(g){this._log.error("fetchStopStreamWithParams error",g)}}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,r)=>{this.streamHealthCheckReject=r,this.streamHealthCheckTimeoutId=window.setTimeout(()=>this.checkStreamHealth(r),5e3)})}clearStreamHealthCheck(){this.streamHealthCheckTimeoutId&&(clearTimeout(this.streamHealthCheckTimeoutId),delete this.streamHealthCheckTimeoutId),delete this.streamHealthCheckReject}async checkStreamHealth(i){if(!this.isStopped&&this.peerConnection)try{const r=this.peerConnection.getReceivers().find(U=>{var AA;return((AA=U.track)==null?void 0:AA.kind)==="video"});if(!r)return void this._log.warn("checkStreamHealth: no video receiver found");const s=await r.getStats();let g=0,B=0;s.forEach(U=>{U.type==="inbound-rtp"&&(U.mediaType==="video"||U.kind==="video")&&(g=U.bytesReceived||0,B=U.framesDecoded||0)});const{isPlaying:Q}=this.player,f=Q||B>0;this._log.info(`checkStreamHealth: bytesReceived=${g}, framesDecoded=${B}, isPlaying=${Q}`);const{RtcError:m,ErrorCode:M,ErrorCodeDictionary:v}=this.core.errorModule;g===0?(this._log.warn("checkStreamHealth: no stream data received after 5s"),i(new m({code:M.OPERATION_FAILED,message:"no stream data received"}))):f||(this._log.warn("checkStreamHealth: decode failed"),this.isH264DecodeSupported=!1,i(new m({code:M.ENV_NOT_SUPPORTED,extraCode:v.NOT_SUPPORTED_H264_DECODE,message:"h264 decode failed"})))}catch(r){this._log.warn("checkStreamHealth error",r)}}connect(i){return new Promise((r,s)=>{try{this.initScriptTransformWorker();const g={encodedInsertableStreams:this.enableSEI,iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},B=new RTCPeerConnection(g);this.peerConnection=B,B.onconnectionstatechange=()=>{this.connectionState=B.connectionState,this._log.info("connectionState",B.connectionState),B.connectionState!=="failed"&&B.connectionState!=="closed"||(this.isStarted?this.reconnect(i):s(new Error(`connection is ${B.connectionState}`))),B.connectionState==="connected"&&(this.logSelectedCandidate(),r())},B.ontrack=Q=>this.onTrack(Q),B.addTransceiver("audio",{direction:"recvonly"}),B.addTransceiver("video",{direction:"recvonly"}),this._log.info("createOffer"),B.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}).then(Q=>(Q.sdp=l5(Q.sdp),this._log.info("setOffer"),B.setLocalDescription(Q))).then(()=>{const Q={sessionId:SK(),streamurl:i,clientinfo:this.core.environment.getOSString(),localsdp:B.localDescription};return this.exchangeSDP(i,Q)}).then(Q=>(this._log.info("setAnswer"),B.setRemoteDescription(Q))).catch(s)}catch(g){s(g)}this.connectionTimeoutId=setTimeout(()=>s(new Error("connection timeout")),1e4)})}async exchangeSDP(i,r){let s,g,B;try{this._log.info("exchangeSDP");const Q=XrA(i);if(!Q)throw new Error("streamDomain is empty");const{signalDomain:f,cached:m}=await this.fetchSignalDomain(Q);if(!f)throw new Error("signalDomain is empty");{this._log.info("try exchangeSDP signalDomain:",f,m);const M=await this.doExchangeSDP(`https://${f}`,r,3);s=M.url,g=M.remoteSdp,B=M.svrSig}}catch(Q){this._log.warn("exchangeSDP failed, fallback",Q);try{const f=await this.core.utils.promiseAny(ZrA.map(m=>this.doExchangeSDP(`https://${m}`,r,3)));s=f.url,g=f.remoteSdp,B=f.svrSig}catch(f){throw this._log.error("exchangeSDP failed",f),f[0]||f}}return this.streamURL=i,this.signalURL=s,this.svrSig=B,g}async reconnect(i){var r,s;if(!this.isReconnecting){this.isReconnecting=!0;try{this._log.warn("start reconnect"),await this.connect(i),this._log.warn("reconnect success")}catch(g){this._log.error("reconnect error",g);const{RtcError:B,ErrorCode:Q}=this.core.errorModule;(s=(r=this.callback)==null?void 0:r.onError)==null||s.call(r,new B({code:Q.OPERATION_FAILED,message:"reconnect failed"}))}finally{this.isReconnecting=!1}}}async logSelectedCandidate(){if(!this.peerConnection)return;const i=await this.peerConnection.getStats();for(const[r,s]of i)if(this.core.rtcDectection.isSelectedCandidatePair(s)){const g=i.get(s.localCandidateId),B=i.get(s.remoteCandidateId);g&&this._log.info(`local candidate: ${g.candidateType} ${g.protocol}:${g.ip||g.address}:${g.port} ${g.networkType||""} ${g.relayProtocol?`relayProtocol:${g.relayProtocol} url: ${g.url}`:""}`),B&&this._log.info(`remote candidate: ${B.candidateType} ${B.protocol}:${B.ip||B.address}:${B.port}`);break}}async doExchangeSDP(i,r,s){const g=`${i}/webrtc/v1/pullstream`,B=await t2(g,r,{timeout:s}),{errcode:Q,errmsg:f,remotesdp:m,svrsig:M}=B;if(Q!==0){const v=new Error(`errCode:${Q}, errMsg:${f}`);throw v.name="RequestSignalError",v}return{url:i,remoteSdp:m,svrSig:M}}createEncodedStreams(i){var r;if(this.enableSEI&&this.core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED)try{if(this._log.warn("enableSEI",this.enableSEI),!this.insertableStreamsAbortMap.has(i)){const s=i.createEncodedStreams(),g=new AbortController,B={abortController:g,enqueue:Q=>i.track.kind==="audio"?Q:this.decodeVideoFrame(Q)};s.readable.pipeThrough(new TransformStream({transform:(Q,f)=>{const m=B.enqueue(Q);m&&f.enqueue(m)}})).pipeTo(s.writable,g).catch(Q=>{Q!=="destroy"&&this._log.warn(Q)}),(r=this.insertableStreamsAbortMap.get(i))==null||r.abort("destroy"),this.insertableStreamsAbortMap.set(i,g)}}catch(s){this._log.warn(`createEncodedStreams ${i.track.kind} failed`,s)}}initReceiverTransform(i,r){this.peerConnection&&this.enableSEI&&this.scriptTransformWorker&&!i.transform&&(i.transform=new RTCRtpScriptTransform(this.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:"",streamType:this.core.enums.RemoteStreamType.Main}))}initScriptTransformWorker(){const{room:i,rtcDectection:r,createScriptTransformWorker:s,trtc:g,TRTC:B}=this.core;!this.enableSEI||r.IS_INSERTABLE_STREAM_SUPPORTED||this.scriptTransformWorker||r.IS_SCRIPT_TRANSFORM_SUPPORTED&&(this._log.info("initScriptTransformWorker"),this.scriptTransformWorker=s({videoEncodePipeline:i.videoManager.encodePipeline,videoDecodePipeline:i.videoManager.decodePipeline,audioEncodePipeline:i.audioManager.encodePipeline,audioDecodePipeline:i.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=Q=>{var f,m;Q.data.type==="sei"&&((m=(f=this.callback)==null?void 0:f.onSEIMessage)==null||m.call(f,{data:Q.data.data,seiPayloadType:Q.data.seiPayloadType}))},this.scriptTransformWorker.onerror=Q=>{this._log.error("scriptTransformWorker error: ",Q.message)})}decodeVideoFrame(i){if(!this.core.room.videoManager)return i;for(const r of this.core.room.videoManager.decodePipeline)if(r&&!(i=r({frame:i})))return;return i}async fetchStopStream(){if(this.streamURL&&this.svrSig&&this.signalURL)try{const i=`${this.signalURL}/webrtc/v1/stopstream`,r=await t2(i,{streamurl:this.streamURL,svrsig:this.svrSig},{timeout:3}),{errcode:s,errmsg:g}=r;if(s!==0)throw new Error(`errCode:${s}, errmsg:${g}`);return r}catch(i){this._log.error("fetchStopStream error",i)}}onTrack(i){const{track:r}=i;this.createEncodedStreams(i.receiver),this.initReceiverTransform(i.receiver,r.kind==="audio"),r.kind==="audio"?this.player.setAudioTrack(r):this.player.setVideoTrack(r)}onSEIMessage({room:i,nalu:r}){var s,g;i===this.core.room&&((g=(s=this.callback)==null?void 0:s.onSEIMessage)==null||g.call(s,{data:r.seiPayload.buffer,seiPayloadType:r.seiPayloadType}))}async fetchSignalDomain(i,r=i2[0]){var s;const g=`https://${r}/signal_query`;try{const B=window.localStorage.getItem(TK);if(B){const v=JSON.parse(B);if(((s=v[i])==null?void 0:s.expire)-new Date().getTime()>0)return{signalDomain:v[i].signal,cached:!0}}const Q=await t2(g,{domain:i,requestid:SK(16),client_type:"Web",client_info:window.navigator.userAgent}),{errcode:f,errmsg:m,data:M}=Q;if(f===0){const{signal_domain:v,cache_time:U}=M;let AA={};const z=window.localStorage.getItem(TK);z&&(AA=JSON.parse(z)),AA[i]={signal:v,expire:new Date().getTime()+1e3*U};try{window.localStorage.setItem(TK,JSON.stringify(AA))}catch{}return{signalDomain:v,cached:!1}}throw new Error(`errCode:${f} errmsg:${m}`)}catch(B){return this._log.error("fetchSignalDomain error",B),i2[1]&&r!==i2[1]?this.fetchSignalDomain(i,i2[1]):{signalDomain:"",cached:!1}}}};rr(f2,"Name","LEBPlayer"),gw([qrA({fnName:"connect"})],f2.prototype,"stop"),gw([VrA({settings:{retries:1/0,timeout:2e3},onRetrying(t){var i;if(this._log.warn(`retry connect ${t}`),t>=3&&((i=this.callback)==null?void 0:i.onError)&&!this.isFireWallErrorEmitted){const{RtcError:r,ErrorCode:s,ErrorCodeDictionary:g}=this.core.errorModule;this.isFireWallErrorEmitted=!0,this.callback.onError(new r({code:s.OPERATION_FAILED,extraCode:g.FIREWALL_RESTRICTION,message:"firewall restriction"}))}},onError(t,i,r,s){var g;if(this._log.warn("connect failed",t),this.peerConnection&&(this.peerConnection.close(),delete this.peerConnection),!this.isStopped&&((g=t.message||t)==null?void 0:g.includes("connection")))i();else{const{RtcError:B,ErrorCode:Q}=this.core.errorModule;r(new B({code:Q.UNKNOWN_ERROR,message:t.message}))}}})],f2.prototype,"connect");var a6=f2,t2=async(t,i,r={})=>{const{timeout:s=10}=r;let g,B=0,Q={};window.AbortController&&(g=new window.AbortController,Q={signal:g.signal},B=window.setTimeout(()=>g.abort(),1e3*s));const f=await fetch(t,krA({body:JSON.stringify(i),cache:"no-cache",credentials:"same-origin",headers:{"content-type":"text/plain;charset=utf-8"},method:"POST",mode:"cors"},Q));if(B&&window.clearTimeout(B),f.status!==200)throw new Error(`Network Error, status code:${f.status}`);return f.json()},i2=["webrtc-signal-scheduler.tlivesource.com","bak-webrtc-signal-scheduler.tlivesource.com"],TK="LEB_PLAYER_STORAGE_KEY",XrA=t=>{const i=/^(?:webrtc:\/\/)([0-9.\-A-Za-z_]+)(?:\/)(?:[0-9.\-A-Za-z_=]+)(?:\/)(?:[^?#]*)(?:\?*)(?:[^?#]*)/.exec(t);return i?i[1]:""},$rA=a6;const AnA=Object.freeze(Object.defineProperty({__proto__:null,LEBPlayer:a6,default:$rA},Symbol.toStringTag,{value:"Module"})),enA=hk(AnA);var s6=Object.defineProperty,tnA=Object.defineProperties,inA=Object.getOwnPropertyDescriptors,Q5=Object.getOwnPropertySymbols,onA=Object.prototype.hasOwnProperty,rnA=Object.prototype.propertyIsEnumerable,Mj=(t,i,r)=>i in t?s6(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,nnA=(t,i)=>{for(var r in i||(i={}))onA.call(i,r)&&Mj(t,r,i[r]);if(Q5)for(var r of Q5(i))rnA.call(i,r)&&Mj(t,r,i[r]);return t},anA=(t,i)=>tnA(t,inA(i)),snA=(t,i)=>{for(var r in i)s6(t,r,{get:i[r],enumerable:!0})},Oa=(t,i,r)=>Mj(t,typeof i!="symbol"?i+"":i,r);async function gnA({sdkAppId:t,userId:i,userSig:r,core:s}){var g;const B=Math.round(new Date().getTime()/1e3);try{const Q=await s.schedule.getAbilityConfig(t,s.schedule.ScheduleRequestType.TRTC_AUTO_CONF,{sdkAppId:t,userId:i,userSig:r,timestamp:B});s.log.info(`virtual background ability response: ${JSON.stringify(Q)}`);const{data:f}=Q;return(g=f?.trtcAutoConf)!=null&&g.web_ar?{auth:!0,timestamp:B}:{auth:!1}}catch(Q){return s.log.error("virtual background fetch error",Q),{auth:!1}}}var InA={sdkAppId:{required:!0,type:"number"},userId:{required:!0,type:"string"},userSig:{required:!0,type:"string"}};function cnA(t){return{name:"VirtualBackgroundOptions",type:"object",required:!0,allowEmpty:!1,properties:anA(nnA({},InA),{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,r,s,g){var B;const{RtcError:Q,ErrorCode:f,ErrorCodeDictionary:m}=t.errorModule;if(!i)return;const{type:M,src:v,onAbort:U}=i;if(M==="image"&&!v)throw new Q({code:f.INVALID_PARAMETER,extraCode:m.INVALID_PARAMETER_REQUIRED,fnName:s,messageParams:{key:"src"}});if(U&&!t.utils.isFunction(U))throw new Q({code:f.INVALID_PARAMETER,extraCode:m.INVALID_PARAMETER_TYPE,fnName:s,messageParams:{key:"onAbort",value:typeof U,rule:{type:"Function"}}});if(!((B=t.room.videoManager.cameraTrack)!=null&&B.mediaTrack))throw new Q({code:f.INVALID_OPERATION,extraCode:m.INVALID_OPERATION_NEED_VIDEO,fnName:s})}}}function EnA(t){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,r,s,g){if(!i)return;const{RtcError:B,ErrorCode:Q,ErrorCodeDictionary:f}=t.errorModule,{type:m,src:M}=i;if(m==="image"&&!M)throw new B({code:Q.INVALID_PARAMETER,extraCode:f.INVALID_PARAMETER_REQUIRED,fnName:s,messageParams:{key:"src"}})}}}function lnA(t){return{name:"StopVirtualBackgroundOptions",required:!1}}var CnA=(()=>{var t=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(i={}){var r,s,g=i;g.ready=new Promise((P,F)=>{r=P,s=F});var B=Object.assign({},g),Q="";typeof document<"u"&&document.currentScript&&(Q=document.currentScript.src),t&&(Q=t),Q=Q.indexOf("blob:")!==0?Q.substr(0,Q.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var f,m,M=g.print||console.log.bind(console),v=g.printErr||console.error.bind(console);function U(P){if(bi(P))return function(F){for(var EA=atob(F),RA=new Uint8Array(EA.length),GA=0;GAP.startsWith(Zi);function qt(P){return Promise.resolve().then(()=>function(F){if(F==$e&&f)return new Uint8Array(f);var EA=U(F);if(EA)return EA;throw"both async and sync fetching of the wasm failed"}(P))}function ai(P,F,EA,RA){return function(GA,WA,Ce){return qt(GA).then(ge=>WebAssembly.instantiate(ge,WA)).then(ge=>ge).then(Ce,ge=>{v(`failed to asynchronously prepare wasm: ${ge}`),Je(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EfyACIANqIAMgBBBFIAEgAkEAIAMgBGogAUsbQQAgASADTxtqBSABCyACEEUgACACIARqIgEQMSAFQQA6AA8gASADaiAFLQAPOgAADAELIAAgAyACIARqIANrIARBACACIAEQRAsgBUEQaiQAIAAMAQsQJwALC/ICAgJ/AX4CQCACRQ0AIAAgAToAACAAIAJqIgNBAWsgAToAACACQQNJDQAgACABOgACIAAgAToAASADQQNrIAE6AAAgA0ECayABOgAAIAJBB0kNACAAIAE6AAMgA0EEayABOgAAIAJBCUkNACAAQQAgAGtBA3EiBGoiAyABQf8BcUGBgoQIbCIBNgIAIAMgAiAEa0F8cSIEaiICQQRrIAE2AgAgBEEJSQ0AIAMgATYCCCADIAE2AgQgAkEIayABNgIAIAJBDGsgATYCACAEQRlJDQAgAyABNgIYIAMgATYCFCADIAE2AhAgAyABNgIMIAJBEGsgATYCACACQRRrIAE2AgAgAkEYayABNgIAIAJBHGsgATYCACAEIANBBHFBGHIiBGsiAkEgSQ0AIAGtQoGAgIAQfiEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkEgayICQR9LDQALCyAACwUAEAwAC1IBAn9B2NQAKAIAIgEgAEEHakF4cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQEUUNAQtB2NQAIAA2AgAgAQ8LQejeAEEwNgIAQX8LgwECBX8BfgJAIABCgICAgBBUBEAgACEHDAELA0AgAUEBayIBIAAgAEIKgCIHQgp+fadBMHI6AAAgAEL/////nwFWIQUgByEAIAUNAAsLIAenIgIEQANAIAFBAWsiASACIAJBCm4iA0EKbGtBMHI6AAAgAkEJSyEGIAMhAiAGDQALCyABC3oBA38CQAJAIAAiAUEDcUUNACABLQAARQRAQQAPCwNAIAFBAWoiAUEDcUUNASABLQAADQALDAELA0AgASICQQRqIQEgAigCACIDQX9zIANBgYKECGtxQYCBgoR4cUUNAAsDQCACIgFBAWohAiABLQAADQALCyABIABrC78EAQl/AkACfyAALQALQQd2BEAgACgCBAwBCyAALQALQf8AcQsiAiABSQRAIwBBEGsiBiQAIAEgAmsiBQRAIAUgAC0AC0EHdgR/IAAoAghB/////wdxQQFrBUEKCyICAn8gAC0AC0EHdgRAIAAoAgQMAQsgAC0AC0H/AHELIgFrSwRAIwBBEGsiBCQAAkAgBSACayABaiIDQe////8HIAJrTQRAAn8gAC0AC0EHdgRAIAAoAgAMAQsgAAshByAEQQRqIgggACACQef///8DSQR/IAQgAkEBdDYCDCAEIAIgA2o2AgQjAEEQayIDJAAgCCgCACAEQQxqIgkoAgBJIQogA0EQaiQAIAkgCCAKGygCACIDQQtPBH8gA0EQakFwcSIDIANBAWsiAyADQQtGGwVBCgtBAWoFQe////8HCxAwIAQoAgQhAyAEKAIIGiABBEAgAyAHIAEQIwsgAkEKRwRAIAcQGQsgACADNgIAIAAgACgCCEGAgICAeHEgBCgCCEH/////B3FyNgIIIAAgACgCCEGAgICAeHI2AgggBEEQaiQADAELECcACyAAIAE2AgQLIAECfyAALQALQQd2BEAgACgCAAwBCyAACyICaiAFEEAgACABIAVqIgAQMSAGQQA6AA8gACACaiAGLQAPOgAACyAGQRBqJAAMAQsCfyAALQALQQd2BEAgACgCAAwBCyAACyEEIwBBEGsiAiQAIAAgARAxIAJBADoADyABIARqIAItAA86AAAgAkEQaiQACwsGACAAEBkL0igBDH8jAEEQayIKJAACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEHs3gAoAgAiBkEQIABBC2pBeHEgAEELSRsiBUEDdiIAdiIBQQNxBEACQCABQX9zQQFxIABqIgJBA3QiAUGU3wBqIgAgAUGc3wBqKAIAIgEoAggiA0YEQEHs3gAgBkF+IAJ3cTYCAAwBCyADIAA2AgwgACADNgIICyABQQhqIQAgASACQQN0IgJBA3I2AgQgASACaiIBIAEoAgRBAXI2AgQMCgsgBUH03gAoAgAiB00NASABBEACQEECIAB0IgJBACACa3IgASAAdHFoIgFBA3QiAEGU3wBqIgIgAEGc3wBqKAIAIgAoAggiA0Y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8LAkAgASADRgRAIAAoAhhBAkcNASAAIAI2AhgPCyAAQQE6ADYgAEECNgIYIAAgACgCJEEBajYCJAsLYwECfyMAQRBrIgIkACABIAAoAgQiA0EBdWohASAAKAIAIQAgAkEIaiABIANBAXEEfyABKAIAIABqKAIABSAACxEAACACKAIMIgAQAiACKAIMIgEEQCABEAMLIAJBEGokACAAC0MBAX8jAEEQayIBJAAgAEIANwIAIABBADYCCCABQRBqJAAgACAALQALQQd2BH8gACgCCEH/////B3FBAWsFQQoLECsLPQEBfyMAQRBrIgIkACACQQA6AA8DQCABBEAgACACLQAPOgAAIAFBAWshASAAQQFqIQAMAQsLIAJBEGokAAsaACAALQALQQd2BEAgACgCCBogACgCABAZCwvmAQEFfyMAQRBrIgUkACMAQSBrIgMkACMAQRBrIgQkACAEIAA2AgwgBCAAIAFqNgIIIAMgBCgCDDYCGCADIAQoAgg2AhwgBEEQaiQAIAMoAhghBCADKAIcIQYjAEEQayIBJAAgASAGNgIMIAIgBCAGIARrIgQQQyABIAIgBGo2AgggAyABKAIMNgIQIAMgASgCCDYCFCABQRBqJAAgAyAAIAMoAhAgAGtqNgIMIAMgAiADKAIUIAJrajYCCCAFIAMoAgw2AgggBSADKAIINgIMIANBIGokACAFKAIMIQcgBUEQaiQAIAcLDwAgAgRAIAAgASACEDILC/UCAQV/IwBBEGsiByQAIAIgAUF/c0Hv////B2pNBEACfyAALQALQQd2BEAgACgCAAwBCyAACyEIIAdBBGoiCSAAIAFB5////wNJBH8gByABQQF0NgIMIAcgASACajYCBCMAQRBrIgIkACAJKAIAIAdBDGoiCigCAEkhCyACQRBqJAAgCiAJIAsbKAIAIgJBC08EfyACQRBqQXBxIgIgAkEBayICIAJBC0YbBUEKC0EBagVB7////wcLEDAgBygCBCECIAcoAggaIAQEQCACIAggBBAjCyAFBEAgAiAEaiAGIAUQIwsgAyAEayEGIAMgBEcEQCACIARqIAVqIAQgCGogBhAjCyABQQpHBEAgCBAZCyAAIAI2AgAgACAAKAIIQYCA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7M0AECAiA0UNASADKAIIIAEoAghBf3NxDQFBASABKAIMIAMoAgxBABAeDQIaIAEtAAhBAXFFDQEgASgCDCIARQ0BIABB7M0AECAiAQRAIAMoAgwhAAwBCwsgAEHczgAQICIARQ0AIAAgAygCDBA8IQILIAILIQUMAgsgA0HczgAQICIBBEAgAC0ACEEBcUUNAiABIAYoAgwQPCEFDAILIANBjM0AECAiAUUNASAGKAIMIgBFDQEgAEGMzQAQICIARQ0BIARBDGpBAEE0ECYaIARBATYCOCAEQX82AhQgBCABNgIQIAQgADYCCCAAIARBCGogAigCAEEBIAAoAgAoAhwRBgACQCAEKAIgIgBBAUcNACACKAIARQ0AIAIgBCgCGDYCAAsgAEEBRiEFDAELQQAhBQsgBEFAayQAIAULMQAgACABKAIIQQAQHgRAIAEgAiADED0PCyAAKAIIIgAgASACIAMgACgCACgCHBEGAAsYACAAIAEoAghBABAeBEAgASACIAMQPQsLnQEBAn8jAEFAaiIDJAACf0EBIAAgAUEAEB4NABpBACABRQ0AGkEAIAFBjM0AECAiAUUNABogA0EMakEAQTQQJhogA0EBNgI4IANBfzYCFCADIAA2AhAgAyABNgIIIAEgA0EIaiACKAIAQQEgASgCACgCHBEGACADKAIgIgBBAUYEQCACIAMoAhg2AgALIABBAUYLIQQgA0FAayQAIAQLCgAgACABQQAQHgtOAgF/AXwjAEEQayICJAAgAkEANgIMIAEoAgRB1M8AIAJBDGoQCSEDIAIoAgwiAQRAIAEQAQsgACADRAAAAAAAAAAAYjoAOCACQRBqJAALNwEBfyMAQRBrIgIkACACIAEtADg2AgggAEHUzwAgAkEIahAHNgIEIABB1NUANgIAIAJBEGokAAuoAQEFfyAAKAJUIgMoAgAhBSADKAIEIgQgACgCFCAAKAIcIgdrIgYgBCAGSRsiBgRAIAUgByAGECIaIAMgAygCACAGaiIFNgIAIAMgAygCBCAGayIENgIECyAEIAIgAiAESxsiBARAIAUgASAEECIaIAMgAygCACAEaiIFNgIAIAMgAygCBCAEazYCBAsgBUEAOgAAIAAgACgCLCIBNgIcIAAgATYCFCACC5wBAQJ/IwBBEGsiAiQAQcgAEBwhASAAKAIEIgAQAiACIAA2AgggAUHMLSACQQhqEAc2AgQgAUHU1QA2AgAgAUEBNgIcIAFB1NUANgIYIAFBATYCFCABQdTVADYCECABQQE2AgwgAUHU1QA2AgggAUEAOgAgIAFBADYCRCABQoCAgIAwNwI8IAFBADsANyABQQA7ACsgAkEQaiQAIAELigUCBn4CfyABIAEoAgBBB2pBeHEiAUEQajYCACAAIQkgASkDACEDIAEpAwghBSMAQSBrIgAkAAJAIAVC////////////AIMiBEKAgICAgIDAgDx9IARCgICAgICAwP/DAH1UBEAgBUIEhiADQjyIhCEEIANC//////////8PgyIDQoGAgICAgICACFoEQCAEQoGAgICAgICAwAB8IQIMAgsgBEKAgICAgICAgEB9IQIgA0KAgICAgICAgAhSDQEgAiAEQgGDfCECDAELIANQIARCgICAgICAwP//AFQgBEKAgICAgIDA//8AURtFBEAgBUIEhiADQjyIhEL/////////A4NCgICAgICAgPz/AIQhAgwBC0KAgICAgICA+P8AIQIgBEL///////+//8MAVg0AQgAhAiAEQjCIpyIBQZH3AEkNACADIQIgBUL///////8/g0KAgICAgIDAAIQiBCEGAkAgAUGB9wBrIghBwABxBEAgAyAIQUBqrYYhBkIAIQIMAQsgCEUNACAGIAitIgeGIAJBwAAgCGutiIQhBiACIAeGIQILIAAgAjcDECAAIAY3AxgCQEGB+AAgAWsiAUHAAHEEQCAEIAFBQGqtiCEDQgAhBAwBCyABRQ0AIARBwAAgAWuthiADIAGtIgKIhCEDIAQgAoghBAsgACADNwMAIAAgBDcDCCAAKQMIQgSGIAApAwAiA0I8iIQhAiAAKQMQIAApAxiEQgBSrSADQv//////////D4OEIgNCgYCAgICAgIAIWgRAIAJCAXwhAgwBCyADQoCAgICAgICACFINACACQgGDIAJ8IQILIABBIGokACAJIAIgBUKAgICAgICAgIB/g4S/OQMAC0ABAn8jAEEQayICJAAgAiABNgIMIAJB1NUANgIIIAJBCGogABEBAC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MAAAAAAAAAA8KQAAMQAAADIAAAAzAAAAU3Q5ZXhjZXB0aW9uAAAAAIAoAAAsKQAAAAAAAGgpAAAYAAAANAAAADUAAABTdDExbG9naWNfZXJyb3IAqCgAAFgpAAA8KQAAAAAAAJwpAAAYAAAANgAAADUAAABTdDEybGVuZ3RoX2Vycm9yAAAAAKgoAACIKQAAaCkAAFN0OXR5cGVfaW5mbwAAAACAKAAAqCkAQcDTAAsJCxUAAAAAAAAFAEHU0wALARsAQezTAAsOHAAAAB0AAABoKwAAAAQAQYTUAAsBAQBBlNQACwX/////CgBB2NQACwNgMQE=")||(Dt=$e,$e=g.locateFile?g.locateFile(Dt,Q):Q+Dt);var Ki=P=>{for(;P.length>0;)P.shift()(g)};g.noExitRuntime;function Ur(P){this.excPtr=P,this.ptr=P-24,this.set_type=function(F){QA[this.ptr+4>>2]=F},this.get_type=function(){return QA[this.ptr+4>>2]},this.set_destructor=function(F){QA[this.ptr+8>>2]=F},this.get_destructor=function(){return QA[this.ptr+8>>2]},this.set_caught=function(F){F=F?1:0,AA[this.ptr+12|0]=F},this.get_caught=function(){return AA[this.ptr+12|0]!=0},this.set_rethrown=function(F){F=F?1:0,AA[this.ptr+13|0]=F},this.get_rethrown=function(){return AA[this.ptr+13|0]!=0},this.init=function(F,EA){this.set_adjusted_ptr(0),this.set_type(F),this.set_destructor(EA)},this.set_adjusted_ptr=function(F){QA[this.ptr+16>>2]=F},this.get_adjusted_ptr=function(){return QA[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Cs(this.get_type()))return QA[this.excPtr>>2];var F=this.get_adjusted_ptr();return F!==0?F:this.excPtr}}var Er,no,Kn,Xi=P=>{for(var F="",EA=P;z[EA];)F+=Er[z[EA++]];return F},yr={},lr={},Ni={},wt=P=>{throw new no(P)},Ji=P=>{throw new Kn(P)},Di=(P,F,EA)=>{function RA(ge){var we=EA(ge);we.length!==P.length&&Ji("Mismatched type converter count");for(var _e=0;_e{lr.hasOwnProperty(ge)?GA[we]=lr[ge]:(WA.push(ge),yr.hasOwnProperty(ge)||(yr[ge]=[]),yr[ge].push(()=>{GA[we]=lr[ge],++Ce===WA.length&&RA(GA)}))}),WA.length===0&&RA(GA)};function ar(P,F,EA={}){if(!("argPackAdvance"in F))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(RA,GA,WA={}){var Ce=GA.name;if(RA||wt(`type "${Ce}" must have a positive integer typeid pointer`),lr.hasOwnProperty(RA)){if(WA.ignoreDuplicateRegistrations)return;wt(`Cannot register type '${Ce}' twice`)}if(lr[RA]=GA,delete Ni[RA],yr.hasOwnProperty(RA)){var ge=yr[RA];delete yr[RA],ge.forEach(we=>we())}}(P,F,EA)}var MA,YA=P=>{wt(P.$$.ptrType.registeredClass.name+" instance already deleted")},pe=!1,st=P=>{},Te=P=>{P.count.value-=1,P.count.value===0&&(F=>{F.smartPtr?F.smartPtrType.rawDestructor(F.smartPtr):F.ptrType.registeredClass.rawDestructor(F.ptr)})(P)},be=(P,F,EA)=>{if(F===EA)return P;if(EA.baseClass===void 0)return null;var RA=be(P,F,EA.baseClass);return RA===null?null:EA.downcast(RA)},yt={},ht=()=>Object.keys(zt).length,ae=()=>{var P=[];for(var F in zt)zt.hasOwnProperty(F)&&P.push(zt[F]);return P},ye=[],Xe=()=>{for(;ye.length;){var P=ye.pop();P.$$.deleteScheduled=!1,P.delete()}},ot=P=>{MA=P,ye.length&&MA&&MA(Xe)},zt={},yi=(P,F)=>(F=((EA,RA)=>{for(RA===void 0&&wt("ptr should not be undefined");EA.baseClass;)RA=EA.upcast(RA),EA=EA.baseClass;return RA})(P,F),zt[F]),Hi=(P,F)=>(F.ptrType&&F.ptr||Ji("makeClassHandle requires ptr and ptrType"),!!F.smartPtrType!=!!F.smartPtr&&Ji("Both smartPtrType and smartPtr must be specified"),F.count={value:1},ji(Object.create(P,{$$:{value:F}})));function Ei(P){var F=this.getPointee(P);if(!F)return this.destructor(P),null;var EA=yi(this.registeredClass,F);if(EA!==void 0){if(EA.$$.count.value===0)return EA.$$.ptr=F,EA.$$.smartPtr=P,EA.clone();var RA=EA.clone();return this.destructor(P),RA}function GA(){return this.isSmartPointer?Hi(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:F,smartPtrType:this,smartPtr:P}):Hi(this.registeredClass.instancePrototype,{ptrType:this,ptr:P})}var WA,Ce=this.registeredClass.getActualType(F),ge=yt[Ce];if(!ge)return GA.call(this);WA=this.isConst?ge.constPointerType:ge.pointerType;var we=be(F,this.registeredClass,WA.registeredClass);return we===null?GA.call(this):this.isSmartPointer?Hi(WA.registeredClass.instancePrototype,{ptrType:WA,ptr:we,smartPtrType:this,smartPtr:P}):Hi(WA.registeredClass.instancePrototype,{ptrType:WA,ptr:we})}var ji=P=>typeof FinalizationRegistry>"u"?(ji=F=>F,P):(pe=new FinalizationRegistry(F=>{Te(F.$$)}),st=F=>pe.unregister(F),(ji=F=>{var EA=F.$$;if(EA.smartPtr){var RA={$$:EA};pe.register(F,RA,F)}return F})(P));function Xo(){}var sr=(P,F)=>Object.defineProperty(F,"name",{value:P}),Lo=(P,F,EA)=>{if(P[F].overloadTable===void 0){var RA=P[F];P[F]=function(){return P[F].overloadTable.hasOwnProperty(arguments.length)||wt(`Function '${EA}' called with an invalid number of arguments (${arguments.length}) - expects one of (${P[F].overloadTable})!`),P[F].overloadTable[arguments.length].apply(this,arguments)},P[F].overloadTable=[],P[F].overloadTable[RA.argCount]=RA}};function Nr(P,F,EA,RA,GA,WA,Ce,ge){this.name=P,this.constructor=F,this.instancePrototype=EA,this.rawDestructor=RA,this.baseClass=GA,this.getActualType=WA,this.upcast=Ce,this.downcast=ge,this.pureVirtualFunctions=[]}var Vo=(P,F,EA)=>{for(;F!==EA;)F.upcast||wt(`Expected null or instance of ${EA.name}, got an instance of ${F.name}`),P=F.upcast(P),F=F.baseClass;return P};function et(P,F){if(F===null)return this.isReference&&wt(`null is not a valid ${this.name}`),0;F.$$||wt(`Cannot pass "${ao(F)}" as a ${this.name}`),F.$$.ptr||wt(`Cannot pass deleted object as a pointer of type ${this.name}`);var EA=F.$$.ptrType.registeredClass;return Vo(F.$$.ptr,EA,this.registeredClass)}function Kr(P,F){var EA;if(F===null)return this.isReference&&wt(`null is not a valid ${this.name}`),this.isSmartPointer?(EA=this.rawConstructor(),P!==null&&P.push(this.rawDestructor,EA),EA):0;F.$$||wt(`Cannot pass "${ao(F)}" as a ${this.name}`),F.$$.ptr||wt(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&F.$$.ptrType.isConst&&wt(`Cannot convert argument of type ${F.$$.smartPtrType?F.$$.smartPtrType.name:F.$$.ptrType.name} to parameter type ${this.name}`);var RA=F.$$.ptrType.registeredClass;if(EA=Vo(F.$$.ptr,RA,this.registeredClass),this.isSmartPointer)switch(F.$$.smartPtr===void 0&&wt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:F.$$.smartPtrType===this?EA=F.$$.smartPtr:wt(`Cannot convert argument of type ${F.$$.smartPtrType?F.$$.smartPtrType.name:F.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:EA=F.$$.smartPtr;break;case 2:if(F.$$.smartPtrType===this)EA=F.$$.smartPtr;else{var GA=F.clone();EA=this.rawShare(EA,gr.toHandle(()=>GA.delete())),P!==null&&P.push(this.rawDestructor,EA)}break;default:wt("Unsupporting sharing policy")}return EA}function Qn(P,F){if(F===null)return this.isReference&&wt(`null is not a valid ${this.name}`),0;F.$$||wt(`Cannot pass "${ao(F)}" as a ${this.name}`),F.$$.ptr||wt(`Cannot pass deleted object as a pointer of type ${this.name}`),F.$$.ptrType.isConst&&wt(`Cannot convert argument of type ${F.$$.ptrType.name} to parameter type ${this.name}`);var EA=F.$$.ptrType.registeredClass;return Vo(F.$$.ptr,EA,this.registeredClass)}function ho(P){return this.fromWireType(QA[P>>2])}function jn(P,F,EA,RA,GA,WA,Ce,ge,we,_e,Ke){this.name=P,this.registeredClass=F,this.isReference=EA,this.isConst=RA,this.isSmartPointer=GA,this.pointeeType=WA,this.sharingPolicy=Ce,this.rawGetPointee=ge,this.rawConstructor=we,this.rawShare=_e,this.rawDestructor=Ke,GA||F.baseClass!==void 0?this.toWireType=Kr:RA?(this.toWireType=et,this.destructorFunction=null):(this.toWireType=Qn,this.destructorFunction=null)}var $t,$r,On=[],An=P=>{var F=On[P];return F||(P>=On.length&&(On.length=P+1),On[P]=F=$t.get(P)),F},Tr=(P,F,EA)=>P.includes("j")?((RA,GA,WA)=>{var Ce=g["dynCall_"+RA];return WA&&WA.length?Ce.apply(null,[GA].concat(WA)):Ce.call(null,GA)})(P,F,EA):An(F).apply(null,EA),ei=(P,F)=>{var EA,RA,GA,WA=(P=Xi(P)).includes("j")?(EA=P,RA=F,GA=[],function(){return GA.length=0,Object.assign(GA,arguments),Tr(EA,RA,GA)}):An(F);return typeof WA!="function"&&wt(`unknown function pointer with signature ${P}: ${F}`),WA},Es=P=>{var F=Ba(P),EA=Xi(F);return Mr(F),EA},jr=(P,F)=>{var EA=[],RA={};throw F.forEach(function GA(WA){RA[WA]||lr[WA]||(Ni[WA]?Ni[WA].forEach(GA):(EA.push(WA),RA[WA]=!0))}),new $r(`${P}: `+EA.map(Es).join([", "]))},Gr=(P,F)=>{for(var EA=[],RA=0;RA>2]);return EA},$o=P=>{for(;P.length;){var F=P.pop();P.pop()(F)}};function sn(P,F,EA,RA,GA,WA){var Ce=F.length;Ce<2&&wt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var ge=F[1]!==null&&EA!==null,we=!1,_e=1;_e(P instanceof Object||wt(`${EA} with invalid "this": ${P}`),P instanceof F.registeredClass.constructor||wt(`${EA} incompatible with "this" of type ${P.constructor.name}`),P.$$.ptr||wt(`cannot call emscripten binding method ${EA} on deleted object`),Vo(P.$$.ptr,P.$$.ptrType.registeredClass,F.registeredClass));function hn(){this.allocated=[void 0],this.freelist=[]}var Gi=new hn,pn=P=>{P>=Gi.reserved&&--Gi.get(P).refcount===0&&Gi.free(P)},nI=()=>{for(var P=0,F=Gi.reserved;F(P||wt("Cannot use deleted val. handle = "+P),Gi.get(P).value),toHandle:P=>{switch(P){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return Gi.allocate({refcount:1,value:P})}}};function gn(P){return this.fromWireType(X[P>>2])}var Yo,Tg,So,ao=P=>{if(P===null)return"null";var F=typeof P;return F==="object"||F==="array"||F==="function"?P.toString():""+P},EE=(P,F)=>{switch(F){case 4:return function(EA){return this.fromWireType(wA[EA>>2])};case 8:return function(EA){return this.fromWireType(HA[EA>>3])};default:throw new TypeError(`invalid float width (${F}): ${P}`)}},Ta=(P,F,EA)=>{switch(F){case 1:return EA?RA=>AA[RA|0]:RA=>z[RA|0];case 2:return EA?RA=>sA[RA>>1]:RA=>eA[RA>>1];case 4:return EA?RA=>X[RA>>2]:RA=>QA[RA>>2];default:throw new TypeError(`invalid integer width (${F}): ${P}`)}},po=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ja=(P,F,EA)=>{for(var RA=F+EA,GA=F;P[GA]&&!(GA>=RA);)++GA;if(GA-F>16&&P.buffer&&po)return po.decode(P.subarray(F,GA));for(var WA="";F>10,56320|1023&_e)}}else WA+=String.fromCharCode((31&Ce)<<6|ge)}else WA+=String.fromCharCode(Ce)}return WA},Mc=(P,F)=>P?Ja(z,P,F):"",Qr=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Fo=(P,F)=>{for(var EA=P,RA=EA>>1,GA=RA+F/2;!(RA>=GA)&&eA[RA];)++RA;if((EA=RA<<1)-P>32&&Qr)return Qr.decode(z.subarray(P,EA));for(var WA="",Ce=0;!(Ce>=F/2);++Ce){var ge=sA[P+2*Ce>>1];if(ge==0)break;WA+=String.fromCharCode(ge)}return WA},$s=(P,F,EA)=>{if(EA===void 0&&(EA=2147483647),EA<2)return 0;for(var RA=F,GA=(EA-=2)<2*P.length?EA/2:P.length,WA=0;WA>1]=Ce,F+=2}return sA[F>>1]=0,F-RA},Ha=P=>2*P.length,Gs=(P,F)=>{for(var EA=0,RA="";!(EA>=F/4);){var GA=X[P+4*EA>>2];if(GA==0)break;if(++EA,GA>=65536){var WA=GA-65536;RA+=String.fromCharCode(55296|WA>>10,56320|1023&WA)}else RA+=String.fromCharCode(GA)}return RA},Ga=(P,F,EA)=>{if(EA===void 0&&(EA=2147483647),EA<4)return 0;for(var RA=F,GA=RA+EA-4,WA=0;WA=55296&&Ce<=57343&&(Ce=65536+((1023&Ce)<<10)|1023&P.charCodeAt(++WA)),X[F>>2]=Ce,(F+=4)+4>GA)break}return X[F>>2]=0,F-RA},Rr=P=>{for(var F=0,EA=0;EA=55296&&RA<=57343&&++EA,F+=4}return F},Ia=(P,F)=>{var EA=lr[P];return EA===void 0&&wt(F+" has unknown type "+Es(P)),EA},fo=(P,F,EA)=>{var RA=[],GA=P.toWireType(RA,EA);return RA.length&&(QA[F>>2]=gr.toHandle(RA)),GA},aI={},en=[],qo=Reflect.construct,Gg=[null,[],[]],kg=(P,F)=>{var EA=Gg[P];F===0||F===10?((P===1?M:v)(Ja(EA,0)),EA.length=0):EA.push(F)};(()=>{for(var P=new Array(256),F=0;F<256;++F)P[F]=String.fromCharCode(F);Er=P})(),no=g.BindingError=class extends Error{constructor(P){super(P),this.name="BindingError"}},Kn=g.InternalError=class extends Error{constructor(P){super(P),this.name="InternalError"}},Object.assign(Xo.prototype,{isAliasOf(P){if(!(this instanceof Xo)||!(P instanceof Xo))return!1;var F=this.$$.ptrType.registeredClass,EA=this.$$.ptr;P.$$=P.$$;for(var RA=P.$$.ptrType.registeredClass,GA=P.$$.ptr;F.baseClass;)EA=F.upcast(EA),F=F.baseClass;for(;RA.baseClass;)GA=RA.upcast(GA),RA=RA.baseClass;return F===RA&&EA===GA},clone(){if(this.$$.ptr||YA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var P,F=ji(Object.create(Object.getPrototypeOf(this),{$$:{value:(P=this.$$,{count:P.count,deleteScheduled:P.deleteScheduled,preservePointerOnDelete:P.preservePointerOnDelete,ptr:P.ptr,ptrType:P.ptrType,smartPtr:P.smartPtr,smartPtrType:P.smartPtrType})}}));return F.$$.count.value+=1,F.$$.deleteScheduled=!1,F},delete(){this.$$.ptr||YA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&wt("Object already scheduled for deletion"),st(this),Te(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||YA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&wt("Object already scheduled for deletion"),ye.push(this),ye.length===1&&MA&&MA(Xe),this.$$.deleteScheduled=!0,this}}),g.getInheritedInstanceCount=ht,g.getLiveInheritedInstances=ae,g.flushPendingDeletes=Xe,g.setDelayFunction=ot,Object.assign(jn.prototype,{getPointee(P){return this.rawGetPointee&&(P=this.rawGetPointee(P)),P},destructor(P){this.rawDestructor&&this.rawDestructor(P)},argPackAdvance:8,readValueFromPointer:ho,deleteObject(P){P!==null&&P.delete()},fromWireType:Ei}),$r=g.UnboundTypeError=(Yo=Error,(So=sr(Tg="UnboundTypeError",function(P){this.name=Tg,this.message=P;var F=new Error(P).stack;F!==void 0&&(this.stack=this.toString()+` -`+F.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(Yo.prototype),So.prototype.constructor=So,So.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},So),Object.assign(hn.prototype,{get(P){return this.allocated[P]},has(P){return this.allocated[P]!==void 0},allocate(P){var F=this.freelist.pop()||this.allocated.length;return this.allocated[F]=P,F},free(P){this.allocated[P]=void 0,this.freelist.push(P)}}),Gi.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Gi.reserved=Gi.allocated.length,g.count_emval_handles=nI;var fn,ls={w:(P,F,EA)=>{throw new Ur(P).init(F,EA),P},q:(P,F,EA,RA,GA)=>{},u:(P,F,EA,RA)=>{ar(P,{name:F=Xi(F),fromWireType:function(GA){return!!GA},toWireType:function(GA,WA){return WA?EA:RA},argPackAdvance:8,readValueFromPointer:function(GA){return this.fromWireType(z[GA])},destructorFunction:null})},y:(P,F,EA,RA,GA,WA,Ce,ge,we,_e,Ke,Bt,Rt)=>{Ke=Xi(Ke),WA=ei(GA,WA),ge&&(ge=ei(Ce,ge)),_e&&(_e=ei(we,_e)),Rt=ei(Bt,Rt);var Ye=(nt=>{if(nt===void 0)return"_unknown";var ii=(nt=nt.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return ii>=48&&ii<=57?`_${nt}`:nt})(Ke);((nt,ii,oi)=>{g.hasOwnProperty(nt)?(wt(`Cannot register public name '${nt}' twice`),Lo(g,nt,nt),g.hasOwnProperty(oi)&&wt(`Cannot register multiple overloads of a function with the same number of arguments (${oi})!`),g[nt].overloadTable[oi]=ii):g[nt]=ii})(Ye,function(){jr(`Cannot construct ${Ke} due to unbound types`,[RA])}),Di([P,F,EA],RA?[RA]:[],function(nt){var ii,oi;nt=nt[0],oi=RA?(ii=nt.registeredClass).instancePrototype:Xo.prototype;var Ko=sr(Ke,function(){if(Object.getPrototypeOf(this)!==Kt)throw new no("Use 'new' to construct "+Ke);if(ro.constructor_body===void 0)throw new no(Ke+" has no accessible constructor");var xr=ro.constructor_body[arguments.length];if(xr===void 0)throw new no(`Tried to invoke ctor of ${Ke} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(ro.constructor_body).toString()}) parameters instead!`);return xr.apply(this,arguments)}),Kt=Object.create(oi,{constructor:{value:Ko}});Ko.prototype=Kt;var ro=new Nr(Ke,Ko,Kt,Rt,ii,WA,ge,_e);ro.baseClass&&(ro.baseClass.__derivedClasses===void 0&&(ro.baseClass.__derivedClasses=[]),ro.baseClass.__derivedClasses.push(ro));var ks=new jn(Ke,ro,!0,!1,!1),Zr=new jn(Ke+"*",ro,!1,!1,!1),In=new jn(Ke+" const*",ro,!1,!0,!1);return yt[P]={pointerType:Zr,constPointerType:In},((xr,sI,jo)=>{g.hasOwnProperty(xr)||Ji("Replacing nonexistant public symbol"),g[xr].overloadTable!==void 0&&jo!==void 0?g[xr].overloadTable[jo]=sI:(g[xr]=sI,g[xr].argCount=jo)})(Ye,Ko),[ks,Zr,In]})},x:(P,F,EA,RA,GA,WA)=>{var Ce=Gr(F,EA);GA=ei(RA,GA),Di([],[P],function(ge){var we=`constructor ${(ge=ge[0]).name}`;if(ge.registeredClass.constructor_body===void 0&&(ge.registeredClass.constructor_body=[]),ge.registeredClass.constructor_body[F-1]!==void 0)throw new no(`Cannot register multiple constructors with identical number of parameters (${F-1}) for class '${ge.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return ge.registeredClass.constructor_body[F-1]=()=>{jr(`Cannot construct ${ge.name} due to unbound types`,Ce)},Di([],Ce,_e=>(_e.splice(1,0,null),ge.registeredClass.constructor_body[F-1]=sn(we,_e,null,GA,WA),[])),[]})},i:(P,F,EA,RA,GA,WA,Ce,ge,we)=>{var _e=Gr(EA,RA);F=(Ke=>{const Bt=(Ke=Ke.trim()).indexOf("(");return Bt!==-1?Ke.substr(0,Bt):Ke})(F=Xi(F)),WA=ei(GA,WA),Di([],[P],function(Ke){var Bt=`${(Ke=Ke[0]).name}.${F}`;function Rt(){jr(`Cannot call ${Bt} due to unbound types`,_e)}F.startsWith("@@")&&(F=Symbol[F.substring(2)]),ge&&Ke.registeredClass.pureVirtualFunctions.push(F);var Ye=Ke.registeredClass.instancePrototype,nt=Ye[F];return nt===void 0||nt.overloadTable===void 0&&nt.className!==Ke.name&&nt.argCount===EA-2?(Rt.argCount=EA-2,Rt.className=Ke.name,Ye[F]=Rt):(Lo(Ye,F,Bt),Ye[F].overloadTable[EA-2]=Rt),Di([],_e,function(ii){var oi=sn(Bt,ii,Ke,WA,Ce);return Ye[F].overloadTable===void 0?(oi.argCount=EA-2,Ye[F]=oi):Ye[F].overloadTable[EA-2]=oi,[]}),[]})},k:(P,F,EA,RA,GA,WA,Ce,ge,we,_e)=>{F=Xi(F),GA=ei(RA,GA),Di([],[P],function(Ke){var Bt=`${(Ke=Ke[0]).name}.${F}`,Rt={get(){jr(`Cannot access ${Bt} due to unbound types`,[EA,Ce])},enumerable:!0,configurable:!0};return Rt.set=we?()=>jr(`Cannot access ${Bt} due to unbound types`,[EA,Ce]):Ye=>wt(Bt+" is a read-only property"),Object.defineProperty(Ke.registeredClass.instancePrototype,F,Rt),Di([],we?[EA,Ce]:[EA],function(Ye){var nt=Ye[0],ii={get(){var Ko=dn(this,Ke,Bt+" getter");return nt.fromWireType(GA(WA,Ko))},enumerable:!0};if(we){we=ei(ge,we);var oi=Ye[1];ii.set=function(Ko){var Kt=dn(this,Ke,Bt+" setter"),ro=[];we(_e,Kt,oi.toWireType(ro,Ko)),$o(ro)}}return Object.defineProperty(Ke.registeredClass.instancePrototype,F,ii),[]}),[]})},t:(P,F)=>{ar(P,{name:F=Xi(F),fromWireType:EA=>{var RA=gr.toValue(EA);return pn(EA),RA},toWireType:(EA,RA)=>gr.toHandle(RA),argPackAdvance:8,readValueFromPointer:gn,destructorFunction:null})},p:(P,F,EA)=>{ar(P,{name:F=Xi(F),fromWireType:RA=>RA,toWireType:(RA,GA)=>GA,argPackAdvance:8,readValueFromPointer:EE(F,EA),destructorFunction:null})},g:(P,F,EA,RA,GA)=>{F=Xi(F);var WA=we=>we;if(RA===0){var Ce=32-8*EA;WA=we=>we<>>Ce}var ge=F.includes("unsigned");ar(P,{name:F,fromWireType:WA,toWireType:ge?function(we,_e){return this.name,_e>>>0}:function(we,_e){return this.name,_e},argPackAdvance:8,readValueFromPointer:Ta(F,EA,RA!==0),destructorFunction:null})},a:(P,F,EA)=>{var RA=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][F];function GA(WA){var Ce=QA[WA>>2],ge=QA[WA+4>>2];return new RA(AA.buffer,ge,Ce)}ar(P,{name:EA=Xi(EA),fromWireType:GA,argPackAdvance:8,readValueFromPointer:GA},{ignoreDuplicateRegistrations:!0})},o:(P,F)=>{var EA=(F=Xi(F))==="std::string";ar(P,{name:F,fromWireType(RA){var GA,WA=QA[RA>>2],Ce=RA+4;if(EA)for(var ge=Ce,we=0;we<=WA;++we){var _e=Ce+we;if(we==WA||z[_e]==0){var Ke=Mc(ge,_e-ge);GA===void 0?GA=Ke:(GA+="\0",GA+=Ke),ge=_e+1}}else{var Bt=new Array(WA);for(we=0;we{for(var Rt=0,Ye=0;Ye=55296&&nt<=57343?(Rt+=4,++Ye):Rt+=3}return Rt})(GA):GA.length;var ge=Po(4+WA+1),we=ge+4;if(QA[ge>>2]=WA,EA&&Ce)((Bt,Rt,Ye,nt)=>{if(!(nt>0))return 0;for(var ii=Ye,oi=Ye+nt-1,Ko=0;Ko=55296&&Kt<=57343&&(Kt=65536+((1023&Kt)<<10)|1023&Bt.charCodeAt(++Ko)),Kt<=127){if(Ye>=oi)break;Rt[Ye++]=Kt}else if(Kt<=2047){if(Ye+1>=oi)break;Rt[Ye++]=192|Kt>>6,Rt[Ye++]=128|63&Kt}else if(Kt<=65535){if(Ye+2>=oi)break;Rt[Ye++]=224|Kt>>12,Rt[Ye++]=128|Kt>>6&63,Rt[Ye++]=128|63&Kt}else{if(Ye+3>=oi)break;Rt[Ye++]=240|Kt>>18,Rt[Ye++]=128|Kt>>12&63,Rt[Ye++]=128|Kt>>6&63,Rt[Ye++]=128|63&Kt}}Rt[Ye]=0})(GA,z,we,WA+1);else if(Ce)for(var _e=0;_e255&&(Mr(we),wt("String has UTF-16 code units that do not fit in 8 bits")),z[we+_e]=Ke}else for(_e=0;_e{var RA,GA,WA,Ce,ge;EA=Xi(EA),F===2?(RA=Fo,GA=$s,Ce=Ha,WA=()=>eA,ge=1):F===4&&(RA=Gs,GA=Ga,Ce=Rr,WA=()=>QA,ge=2),ar(P,{name:EA,fromWireType:we=>{for(var _e,Ke=QA[we>>2],Bt=WA(),Rt=we+4,Ye=0;Ye<=Ke;++Ye){var nt=we+4+Ye*F;if(Ye==Ke||Bt[nt>>ge]==0){var ii=RA(Rt,nt-Rt);_e===void 0?_e=ii:(_e+="\0",_e+=ii),Rt=nt+F}}return Mr(we),_e},toWireType:(we,_e)=>{typeof _e!="string"&&wt(`Cannot pass non-string to C++ string type ${EA}`);var Ke=Ce(_e),Bt=Po(4+Ke+F);return QA[Bt>>2]=Ke>>ge,GA(_e,Bt+4,Ke+F),we!==null&&we.push(Mr,Bt),Bt},argPackAdvance:8,readValueFromPointer:gn,destructorFunction(we){Mr(we)}})},v:(P,F)=>{ar(P,{isVoid:!0,name:F=Xi(F),argPackAdvance:0,fromWireType:()=>{},toWireType:(EA,RA)=>{}})},j:(P,F,EA)=>(P=gr.toValue(P),F=Ia(F,"emval::as"),fo(F,EA,P)),e:(P,F,EA,RA,GA)=>{var WA,Ce;return(P=en[P])(F=gr.toValue(F),F[EA=(Ce=aI[WA=EA])===void 0?Xi(WA):Ce],RA,GA)},d:pn,f:(P,F,EA)=>{var RA=((_e,Ke)=>{for(var Bt=new Array(_e),Rt=0;Rt<_e;++Rt)Bt[Rt]=Ia(QA[Ke+4*Rt>>2],"parameter "+Rt);return Bt})(P,F),GA=RA.shift();P--;var WA,Ce,ge=new Array(P),we=`methodCaller<(${RA.map(_e=>_e.name).join(", ")}) => ${GA.name}>`;return WA=sr(we,(_e,Ke,Bt,Rt)=>{for(var Ye=0,nt=0;nt{P>4&&(Gi.get(P).refcount+=1)},b:P=>{var F=gr.toValue(P);$o(F),pn(P)},h:(P,F)=>{var EA=(P=Ia(P,"_emval_take_value")).readValueFromPointer(F);return gr.toHandle(EA)},m:()=>{Je("")},s:(P,F,EA)=>z.copyWithin(P,F,F+EA),r:P=>{z.length,Je("OOM")},n:(P,F,EA,RA)=>{for(var GA=0,WA=0;WA>2],ge=QA[F+4>>2];F+=8;for(var we=0;we>2]=GA,0}},Or=function(){var P={a:ls};function F(EA,RA){var GA,WA;return Or=EA.exports,m=Or.z,GA=m.buffer,g.HEAP8=AA=new Int8Array(GA),g.HEAP16=sA=new Int16Array(GA),g.HEAPU8=z=new Uint8Array(GA),g.HEAPU16=eA=new Uint16Array(GA),g.HEAP32=X=new Int32Array(GA),g.HEAPU32=QA=new Uint32Array(GA),g.HEAPF32=wA=new Float32Array(GA),g.HEAPF64=HA=new Float64Array(GA),$t=Or.C,WA=Or.A,jA.unshift(WA),function(){if(qe--,g.monitorRunDependencies&&g.monitorRunDependencies(qe),qe==0&&Et){var Ce=Et;Et=null,Ce()}}(),Or}if(qe++,g.monitorRunDependencies&&g.monitorRunDependencies(qe),g.instantiateWasm)try{return g.instantiateWasm(P,F)}catch(EA){v(`Module.instantiateWasm callback failed with error: ${EA}`),s(EA)}return ai(0,$e,P,function(EA){F(EA.instance)}).catch(s),{}}(),Po=P=>(Po=Or.B)(P),Ba=P=>(Ba=Or.D)(P),Mr=P=>(Mr=Or.E)(P),Cs=P=>(Cs=Or.F)(P);g.dynCall_jiji=(P,F,EA,RA,GA)=>(g.dynCall_jiji=Or.G)(P,F,EA,RA,GA),g._vertexShaderSource=10688;function Va(){function P(){fn||(fn=!0,g.calledRun=!0,VA||(Ki(jA),r(g),g.onRuntimeInitialized&&g.onRuntimeInitialized(),function(){if(g.postRun)for(typeof g.postRun=="function"&&(g.postRun=[g.postRun]);g.postRun.length;)Me(g.postRun.shift());Ki(Ve)}()))}qe>0||(function(){if(g.preRun)for(typeof g.preRun=="function"&&(g.preRun=[g.preRun]);g.preRun.length;)Ze(g.preRun.shift());Ki(ue)}(),qe>0||(g.setStatus?(g.setStatus("Running..."),setTimeout(function(){setTimeout(function(){g.setStatus("")},1),P()},1)):P()))}if(Et=function P(){fn||Va(),fn||(Et=P)},g.preInit)for(typeof g.preInit=="function"&&(g.preInit=[g.preInit]);g.preInit.length>0;)g.preInit.pop()();return Va(),i.ready}})(),BnA=CnA,nd=typeof navigator>"u"?"":navigator.userAgent,_o=t=>new RegExp(t,"i").test(nd),Is=t=>{if(_o(t)){const i=new RegExp(`${t}\\/([\\d.]+)`),r=nd.match(i);if(r&&r[1])return r[1]}return""},fY=t=>{if(_o(t)){const i=new RegExp(`${t}\\/(\\d+)`),r=nd.match(i);if(r&&r[1])return parseFloat(r[1])}return NaN},d5=/AppleWebKit\/([\d.]+)/i.exec(nd);d5&&parseFloat(d5[1]);var g6=_o("iPad"),I6=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&_o("Macintosh"),c6=_o("iPhone")&&!g6,unA=_o("iPod"),E6=c6||g6||unA||I6,B3=_o("Android"),QnA=function(){if(B3){const t=nd.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(t){const i=t[1]&&parseFloat(t[1]),r=t[2]&&parseFloat(t[2]);if(i&&r)return parseFloat(`${t[1]}.${t[2]}`);if(i)return i}}return NaN}();B3&&_o("webkit")&&QnA<2.3;var dnA=_o("Firefox"),hnA=Is("Firefox");fY("Firefox");var l6=_o("Edge"),pnA=Is("Edge"),C6=_o("Edg"),fnA=Is("Edg");fY("Edg");var B6=_o("SogouMobileBrowser"),mnA=Is("SogouMobileBrowser"),u6=_o("MetaSr\\s"),DnA=Is("MetaSr\\s"),hD=_o("TBS"),ynA=Is("TBS"),Q6=_o("XWEB"),RnA=Is("XWEB");_o("MSIE\\s8\\.0");var MnA=_o("MSIE\\/\\d+");(function(){if(MnA){const t=/MSIE\s(\d+)\.\d/.exec(nd);let i=t&&parseFloat(t[1]);return!i&&/Trident\/7.0/i.test(nd)&&/rv:11.0/.test(nd)&&(i=11),i}return NaN})();var wnA=_o("(micromessenger|webbrowser)"),SnA=Is("MicroMessenger"),u3=!hD&&_o("MQQBrowser")&&_o("COVC"),Q3=!hD&&_o("MQQBrowser")&&!_o("COVC"),h5=Q3||u3?Is("MQQBrowser"):"",d6=!hD&&_o(" QQBrowser"),vnA=Is(" QQBrowser"),h6=!hD&&_o("QQBrowserLite"),NnA=Is("QQBrowserLite"),p6=!hD&&_o("MQBHD"),TnA=Is("MQBHD");_o("Windows");!E6&&_o("MAC OS X");!B3&&_o("Linux");_o("CrOS");_o("MicroMessenger");_o("UCBrowser");_o("Electron");var f6=_o("MiuiBrowser"),GnA=Is("MiuiBrowser"),m6=_o("HuaweiBrowser");_o("Huawei")||_o("HUAWEI");_o("Honor")||_o("HONOR");var knA=Is("HuaweiBrowser"),D6=_o("SamsungBrowser"),_nA=Is("SamsungBrowser"),y6=_o("HeyTapBrowser"),bnA=Is("HeyTapBrowser"),R6=_o("VivoBrowser"),LnA=Is("VivoBrowser");_o("OpenHarmony");Is("OpenHarmony");var FnA=()=>fY("Chrome"),p5=_o("CriOS"),M6=_o("Chrome"),UnA=!l6&&!u6&&!B6&&!hD&&!Q6&&!C6&&!d6&&!f6&&!m6&&!D6&&!y6&&!R6&&M6;_o("HeadlessChrome");var OnA=FnA(),xnA=Is("Chrome");fY("Electron");var YnA=!M6&&!Q3&&!u3&&!h6&&!p6&&_o("Safari"),w6=Is("Version"),S6=(()=>{if(I6)return w6;if(E6){const t=nd.match(/OS (\d+)_(\d+)/i);if(t&&t[1]){let i=t[1];return t[2]&&(i+=`.${t[2]}`),i}}return""})();Number(S6.split(".")[0]);(()=>{const t=Number(S6.split(".")[0]);return t===14||t===13})();PnA();function PnA(){const t=new Map([[dnA,["Firefox",hnA]],[C6,["Edg",fnA]],[UnA,["Chrome",xnA]],[p5,["ChiOS",Is("CriOS")]],[YnA&&!p5,["Safari",w6]],[hD,["TBS",ynA]],[Q6,["XWEB",RnA]],[wnA&&c6,["WeChat",SnA]],[d6,["QQ(Win)",vnA]],[Q3,["QQ(Mobile)",h5]],[u3,["QQ(Mobile X5)",h5]],[h6,["QQ(Mac)",NnA]],[p6,["QQ(iPad)",TnA]],[f6,["MI",GnA]],[m6,["HW",knA]],[D6,["Samsung",_nA]],[y6,["OPPO",bnA]],[R6,["VIVO",LnA]],[l6,["EDGE",pnA]],[B6,["SogouMobile",mnA]],[u6,["Sogou",DnA]]]);let i="unknown",r="unknown";return t.has(!0)&&([i,r]=t.get(!0)),{name:i,version:r}}var as=1e-6,Dw=typeof Float32Array<"u"?Float32Array:Array,v6={};function JnA(){var t=new Dw(16);return Dw!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function HnA(t){var i=new Dw(16);return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[3],i[4]=t[4],i[5]=t[5],i[6]=t[6],i[7]=t[7],i[8]=t[8],i[9]=t[9],i[10]=t[10],i[11]=t[11],i[12]=t[12],i[13]=t[13],i[14]=t[14],i[15]=t[15],i}function VnA(t,i){return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],t}function qnA(t,i,r,s,g,B,Q,f,m,M,v,U,AA,z,sA,eA){var X=new Dw(16);return X[0]=t,X[1]=i,X[2]=r,X[3]=s,X[4]=g,X[5]=B,X[6]=Q,X[7]=f,X[8]=m,X[9]=M,X[10]=v,X[11]=U,X[12]=AA,X[13]=z,X[14]=sA,X[15]=eA,X}function KnA(t,i,r,s,g,B,Q,f,m,M,v,U,AA,z,sA,eA,X){return t[0]=i,t[1]=r,t[2]=s,t[3]=g,t[4]=B,t[5]=Q,t[6]=f,t[7]=m,t[8]=M,t[9]=v,t[10]=U,t[11]=AA,t[12]=z,t[13]=sA,t[14]=eA,t[15]=X,t}function N6(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function jnA(t,i){if(t===i){var r=i[1],s=i[2],g=i[3],B=i[6],Q=i[7],f=i[11];t[1]=i[4],t[2]=i[8],t[3]=i[12],t[4]=r,t[6]=i[9],t[7]=i[13],t[8]=s,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A+jA*wA,HA=r[4],VA=r[5],ue=r[6],jA=r[7],t[4]=HA*s+VA*f+ue*U+jA*eA,t[5]=HA*g+VA*m+ue*AA+jA*X,t[6]=HA*B+VA*M+ue*z+jA*QA,t[7]=HA*Q+VA*v+ue*sA+jA*wA,HA=r[8],VA=r[9],ue=r[10],jA=r[11],t[8]=HA*s+VA*f+ue*U+jA*eA,t[9]=HA*g+VA*m+ue*AA+jA*X,t[10]=HA*B+VA*M+ue*z+jA*QA,t[11]=HA*Q+VA*v+ue*sA+jA*wA,HA=r[12],VA=r[13],ue=r[14],jA=r[15],t[12]=HA*s+VA*f+ue*U+jA*eA,t[13]=HA*g+VA*m+ue*AA+jA*X,t[14]=HA*B+VA*M+ue*z+jA*QA,t[15]=HA*Q+VA*v+ue*sA+jA*wA,t}function XnA(t,i,r){var s,g,B,Q,f,m,M,v,U,AA,z,sA,eA=r[0],X=r[1],QA=r[2];return i===t?(t[12]=i[0]*eA+i[4]*X+i[8]*QA+i[12],t[13]=i[1]*eA+i[5]*X+i[9]*QA+i[13],t[14]=i[2]*eA+i[6]*X+i[10]*QA+i[14],t[15]=i[3]*eA+i[7]*X+i[11]*QA+i[15]):(s=i[0],g=i[1],B=i[2],Q=i[3],f=i[4],m=i[5],M=i[6],v=i[7],U=i[8],AA=i[9],z=i[10],sA=i[11],t[0]=s,t[1]=g,t[2]=B,t[3]=Q,t[4]=f,t[5]=m,t[6]=M,t[7]=v,t[8]=U,t[9]=AA,t[10]=z,t[11]=sA,t[12]=s*eA+f*X+U*QA+i[12],t[13]=g*eA+m*X+AA*QA+i[13],t[14]=B*eA+M*X+z*QA+i[14],t[15]=Q*eA+v*X+sA*QA+i[15]),t}function $nA(t,i,r){var s=r[0],g=r[1],B=r[2];return t[0]=i[0]*s,t[1]=i[1]*s,t[2]=i[2]*s,t[3]=i[3]*s,t[4]=i[4]*g,t[5]=i[5]*g,t[6]=i[6]*g,t[7]=i[7]*g,t[8]=i[8]*B,t[9]=i[9]*B,t[10]=i[10]*B,t[11]=i[11]*B,t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],t}function AaA(t,i,r,s){var g,B,Q,f,m,M,v,U,AA,z,sA,eA,X,QA,wA,HA,VA,ue,jA,Ve,Ze,Me,qe,Et,Je=s[0],$e=s[1],Dt=s[2],Zi=Math.sqrt(Je*Je+$e*$e+Dt*Dt);return Zi0?(r[0]=2*(f*Q+v*s+m*B-M*g)/U,r[1]=2*(m*Q+v*g+M*s-f*B)/U,r[2]=2*(M*Q+v*B+f*g-m*s)/U):(r[0]=2*(f*Q+v*s+m*B-M*g),r[1]=2*(m*Q+v*g+M*s-f*B),r[2]=2*(M*Q+v*B+f*g-m*s)),G6(t,i,r),t}function caA(t,i){return t[0]=i[12],t[1]=i[13],t[2]=i[14],t}function k6(t,i){var r=i[0],s=i[1],g=i[2],B=i[4],Q=i[5],f=i[6],m=i[8],M=i[9],v=i[10];return t[0]=Math.sqrt(r*r+s*s+g*g),t[1]=Math.sqrt(B*B+Q*Q+f*f),t[2]=Math.sqrt(m*m+M*M+v*v),t}function EaA(t,i){var r=new Dw(3);k6(r,i);var s=1/r[0],g=1/r[1],B=1/r[2],Q=i[0]*s,f=i[1]*g,m=i[2]*B,M=i[4]*s,v=i[5]*g,U=i[6]*B,AA=i[8]*s,z=i[9]*g,sA=i[10]*B,eA=Q+v+sA,X=0;return eA>0?(X=2*Math.sqrt(eA+1),t[3]=.25*X,t[0]=(U-z)/X,t[1]=(AA-m)/X,t[2]=(f-M)/X):Q>v&&Q>sA?(X=2*Math.sqrt(1+Q-v-sA),t[3]=(U-z)/X,t[0]=.25*X,t[1]=(f+M)/X,t[2]=(AA+m)/X):v>sA?(X=2*Math.sqrt(1+v-Q-sA),t[3]=(AA-m)/X,t[0]=(f+M)/X,t[1]=.25*X,t[2]=(U+z)/X):(X=2*Math.sqrt(1+sA-Q-v),t[3]=(f-M)/X,t[0]=(AA+m)/X,t[1]=(U+z)/X,t[2]=.25*X),t}function laA(t,i,r,s){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,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,g!=null&&g!==1/0){var Q=1/(s-g);t[10]=(g+s)*Q,t[14]=2*g*s*Q}else t[10]=-1,t[14]=-2*s;return t}snA(v6,{add:()=>waA,adjoint:()=>znA,clone:()=>HnA,copy:()=>VnA,create:()=>JnA,decompose:()=>laA,determinant:()=>ZnA,equals:()=>TaA,exactEquals:()=>NaA,frob:()=>MaA,fromQuat:()=>uaA,fromQuat2:()=>IaA,fromRotation:()=>naA,fromRotationTranslation:()=>G6,fromRotationTranslationScale:()=>CaA,fromRotationTranslationScaleOrigin:()=>BaA,fromScaling:()=>raA,fromTranslation:()=>oaA,fromValues:()=>qnA,fromXRotation:()=>aaA,fromYRotation:()=>saA,fromZRotation:()=>gaA,frustum:()=>QaA,getRotation:()=>EaA,getScaling:()=>k6,getTranslation:()=>caA,identity:()=>N6,invert:()=>WnA,lookAt:()=>DaA,mul:()=>GaA,multiply:()=>T6,multiplyScalar:()=>SaA,multiplyScalarAndAdd:()=>vaA,ortho:()=>faA,orthoNO:()=>b6,orthoZO:()=>maA,perspective:()=>daA,perspectiveFromFieldOfView:()=>paA,perspectiveNO:()=>_6,perspectiveZO:()=>haA,rotate:()=>AaA,rotateX:()=>eaA,rotateY:()=>taA,rotateZ:()=>iaA,scale:()=>$nA,set:()=>KnA,str:()=>RaA,sub:()=>kaA,subtract:()=>L6,targetTo:()=>yaA,translate:()=>XnA,transpose:()=>jnA});var daA=_6;function haA(t,i,r,s,g){var B=1/Math.tan(i/2);if(t[0]=B/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=B,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,g!=null&&g!==1/0){var Q=1/(s-g);t[10]=g*Q,t[14]=g*s*Q}else t[10]=-1,t[14]=-s;return t}function paA(t,i,r,s){var g=Math.tan(i.upDegrees*Math.PI/180),B=Math.tan(i.downDegrees*Math.PI/180),Q=Math.tan(i.leftDegrees*Math.PI/180),f=Math.tan(i.rightDegrees*Math.PI/180),m=2/(Q+f),M=2/(g+B);return t[0]=m,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=M,t[6]=0,t[7]=0,t[8]=-(Q-f)*m*.5,t[9]=(g-B)*M*.5,t[10]=s/(r-s),t[11]=-1,t[12]=0,t[13]=0,t[14]=s*r/(r-s),t[15]=0,t}function b6(t,i,r,s,g,B,Q){var f=1/(i-r),m=1/(s-g),M=1/(B-Q);return t[0]=-2*f,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*m,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*M,t[11]=0,t[12]=(i+r)*f,t[13]=(g+s)*m,t[14]=(Q+B)*M,t[15]=1,t}var faA=b6;function maA(t,i,r,s,g,B,Q){var f=1/(i-r),m=1/(s-g),M=1/(B-Q);return t[0]=-2*f,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*m,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=M,t[11]=0,t[12]=(i+r)*f,t[13]=(g+s)*m,t[14]=B*M,t[15]=1,t}function DaA(t,i,r,s){var g,B,Q,f,m,M,v,U,AA,z,sA=i[0],eA=i[1],X=i[2],QA=s[0],wA=s[1],HA=s[2],VA=r[0],ue=r[1],jA=r[2];return Math.abs(sA-VA)0&&(v*=z=1/Math.sqrt(z),U*=z,AA*=z);var sA=m*AA-M*U,eA=M*v-f*AA,X=f*U-m*v;return(z=sA*sA+eA*eA+X*X)>0&&(sA*=z=1/Math.sqrt(z),eA*=z,X*=z),t[0]=sA,t[1]=eA,t[2]=X,t[3]=0,t[4]=U*X-AA*eA,t[5]=AA*sA-v*X,t[6]=v*eA-U*sA,t[7]=0,t[8]=v,t[9]=U,t[10]=AA,t[11]=0,t[12]=g,t[13]=B,t[14]=Q,t[15]=1,t}function RaA(t){return"mat4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+", "+t[9]+", "+t[10]+", "+t[11]+", "+t[12]+", "+t[13]+", "+t[14]+", "+t[15]+")"}function MaA(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]+t[4]*t[4]+t[5]*t[5]+t[6]*t[6]+t[7]*t[7]+t[8]*t[8]+t[9]*t[9]+t[10]*t[10]+t[11]*t[11]+t[12]*t[12]+t[13]*t[13]+t[14]*t[14]+t[15]*t[15])}function waA(t,i,r){return t[0]=i[0]+r[0],t[1]=i[1]+r[1],t[2]=i[2]+r[2],t[3]=i[3]+r[3],t[4]=i[4]+r[4],t[5]=i[5]+r[5],t[6]=i[6]+r[6],t[7]=i[7]+r[7],t[8]=i[8]+r[8],t[9]=i[9]+r[9],t[10]=i[10]+r[10],t[11]=i[11]+r[11],t[12]=i[12]+r[12],t[13]=i[13]+r[13],t[14]=i[14]+r[14],t[15]=i[15]+r[15],t}function L6(t,i,r){return t[0]=i[0]-r[0],t[1]=i[1]-r[1],t[2]=i[2]-r[2],t[3]=i[3]-r[3],t[4]=i[4]-r[4],t[5]=i[5]-r[5],t[6]=i[6]-r[6],t[7]=i[7]-r[7],t[8]=i[8]-r[8],t[9]=i[9]-r[9],t[10]=i[10]-r[10],t[11]=i[11]-r[11],t[12]=i[12]-r[12],t[13]=i[13]-r[13],t[14]=i[14]-r[14],t[15]=i[15]-r[15],t}function SaA(t,i,r){return t[0]=i[0]*r,t[1]=i[1]*r,t[2]=i[2]*r,t[3]=i[3]*r,t[4]=i[4]*r,t[5]=i[5]*r,t[6]=i[6]*r,t[7]=i[7]*r,t[8]=i[8]*r,t[9]=i[9]*r,t[10]=i[10]*r,t[11]=i[11]*r,t[12]=i[12]*r,t[13]=i[13]*r,t[14]=i[14]*r,t[15]=i[15]*r,t}function vaA(t,i,r,s){return t[0]=i[0]+r[0]*s,t[1]=i[1]+r[1]*s,t[2]=i[2]+r[2]*s,t[3]=i[3]+r[3]*s,t[4]=i[4]+r[4]*s,t[5]=i[5]+r[5]*s,t[6]=i[6]+r[6]*s,t[7]=i[7]+r[7]*s,t[8]=i[8]+r[8]*s,t[9]=i[9]+r[9]*s,t[10]=i[10]+r[10]*s,t[11]=i[11]+r[11]*s,t[12]=i[12]+r[12]*s,t[13]=i[13]+r[13]*s,t[14]=i[14]+r[14]*s,t[15]=i[15]+r[15]*s,t}function NaA(t,i){return t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]&&t[4]===i[4]&&t[5]===i[5]&&t[6]===i[6]&&t[7]===i[7]&&t[8]===i[8]&&t[9]===i[9]&&t[10]===i[10]&&t[11]===i[11]&&t[12]===i[12]&&t[13]===i[13]&&t[14]===i[14]&&t[15]===i[15]}function TaA(t,i){var r=t[0],s=t[1],g=t[2],B=t[3],Q=t[4],f=t[5],m=t[6],M=t[7],v=t[8],U=t[9],AA=t[10],z=t[11],sA=t[12],eA=t[13],X=t[14],QA=t[15],wA=i[0],HA=i[1],VA=i[2],ue=i[3],jA=i[4],Ve=i[5],Ze=i[6],Me=i[7],qe=i[8],Et=i[9],Je=i[10],$e=i[11],Dt=i[12],Zi=i[13],bi=i[14],qt=i[15];return Math.abs(r-wA)<=as*Math.max(1,Math.abs(r),Math.abs(wA))&&Math.abs(s-HA)<=as*Math.max(1,Math.abs(s),Math.abs(HA))&&Math.abs(g-VA)<=as*Math.max(1,Math.abs(g),Math.abs(VA))&&Math.abs(B-ue)<=as*Math.max(1,Math.abs(B),Math.abs(ue))&&Math.abs(Q-jA)<=as*Math.max(1,Math.abs(Q),Math.abs(jA))&&Math.abs(f-Ve)<=as*Math.max(1,Math.abs(f),Math.abs(Ve))&&Math.abs(m-Ze)<=as*Math.max(1,Math.abs(m),Math.abs(Ze))&&Math.abs(M-Me)<=as*Math.max(1,Math.abs(M),Math.abs(Me))&&Math.abs(v-qe)<=as*Math.max(1,Math.abs(v),Math.abs(qe))&&Math.abs(U-Et)<=as*Math.max(1,Math.abs(U),Math.abs(Et))&&Math.abs(AA-Je)<=as*Math.max(1,Math.abs(AA),Math.abs(Je))&&Math.abs(z-$e)<=as*Math.max(1,Math.abs(z),Math.abs($e))&&Math.abs(sA-Dt)<=as*Math.max(1,Math.abs(sA),Math.abs(Dt))&&Math.abs(eA-Zi)<=as*Math.max(1,Math.abs(eA),Math.abs(Zi))&&Math.abs(X-bi)<=as*Math.max(1,Math.abs(X),Math.abs(bi))&&Math.abs(QA-qt)<=as*Math.max(1,Math.abs(QA),Math.abs(qt))}var GaA=T6,kaA=L6,CG=`#version 300 es +`);return zrA(B)},ZrA="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",_K=(t=21)=>{let i="",r=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)i+=ZrA[63&r[t]];return i},rw=t=>typeof t=="function",XrA=0,$rA=1,f5=2;function AnA({retryFunction:t,settings:i,onError:r,onRetrying:s,onRetryFailed:g,onRetrySuccess:B,context:Q}){return function(...f){const{retries:m=5,timeout:M=1e3}=i;let v=0,U=-1,AA=XrA;const z=async(sA,eA)=>{const X=Q||this;try{const QA=await t.apply(X,f);v>0&&B&&B.call(this,v),v=0,sA(QA)}catch(QA){const wA=()=>{clearTimeout(U),v=0,AA=f5,eA(QA)},HA=()=>{AA!==f5&&v<(rw(m)?m():m)?(v++,AA=$rA,rw(s)&&s.call(this,v,wA),U=window.setTimeout(()=>{U=-1,z(sA,eA)},rw(M)?M(v):M)):(wA(),rw(g)&&g.call(this,QA))};rw(r)?r.call(this,{error:QA,retry:HA,reject:eA,retryFuncArgs:f,retriedCount:v}):HA()}};return new Promise(z)}}var enA=AnA,ku=new WeakMap;function tnA({settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:s}){return function(g,B,Q){const f=enA({retryFunction:Q.value,settings:t,onError({error:m,retry:M,reject:v,retryFuncArgs:U}){var AA;i?i.call(this,m,()=>{var z;(z=ku.get(g))!=null&&z.has(B)?M():v(m)},v,U):(AA=ku.get(g))!=null&&AA.has(B)?M():v(m)},onRetrying(m,M){var v;rw(r)&&r.call(this,m,M),(v=ku.get(g))!=null&&v.has(B)&&(ku.get(g).get(B).stopRetry=M)},onRetryFailed:s});return Q.value=function(...m){const M=ku.get(g);return M?M.set(B,{args:m}):ku.set(g,new Map([[B,{args:m}]])),f.apply(this,m).finally(()=>{var v;return(v=ku.get(g))==null?void 0:v.delete(B)})},Q}}function inA({fnName:t,callback:i,validateArgs:r=!0}){return function(s,g,B){const Q=B.value;return B.value=function(...f){var m,M;if((m=ku.get(s))!=null&&m.has(t)){const{stopRetry:v,args:U}=ku.get(s).get(t);let AA=!0;if(r){for(const z of U)if(!f.find(sA=>sA===z)){AA=!1;break}}AA&&(i&&i.apply(this,f),v&&v(),(M=ku.get(s))==null||M.delete(t))}return Q.apply(this,f)},B}}var onA=class{constructor(t,i){this.core=i,rr(this,"peerConnection"),rr(this,"audioTransceiver",null),rr(this,"videoTransceiver",null),rr(this,"timerId",null),rr(this,"callback",null),rr(this,"previousRawStats",null),rr(this,"_prevReportTime",0),rr(this,"_prevDecoderImplementation",""),rr(this,"_decodeMap",new Map),this.peerConnection=t,this.findTransceivers()}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}findTransceivers(){const t=this.peerConnection.getTransceivers();for(const i of t)if(i.receiver&&i.receiver.track){const{track:r}=i.receiver;r.kind==="audio"?this.audioTransceiver=i:r.kind==="video"&&(this.videoTransceiver=i)}}start(t,i=2e3){this.stop(),this.callback=t,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 t=await this.peerConnection.getStats(),i=new Set(["inbound-rtp","track","candidate-pair","media-source","codec"]),r=[];t.forEach(f=>i.has(f.type)&&r.push(f));const s=Date.now(),g=this.parseAudioStats(r),B=this.parseVideoStats(r),Q=this.parseNetworkStats(r);this._prevReportTime=s,this.callback({audio:g,video:B,network:Q})}catch(t){this.core.log.error("Failed to collect WebRTC stats:",t)}}getDifferenceValue(t,i){if(this.core.utils.isUndefined(t))return i;const r=(i||0)-t;return r<0?0:r}parseAudioStats(t){var i,r,s,g;const B={bitrate:0,volume:0,packetLossRate:0,jitterBufferDelay:0,bytesReceived:0,packetsReceived:0,packetsLost:0};for(const Q of t){if(Q.type==="inbound-rtp"&&(Q.mediaType==="audio"||Q.kind==="audio")){if(B.bytesReceived=Q.bytesReceived||0,B.packetsReceived=Q.packetsReceived||0,B.packetsLost=Q.packetsLost||0,this.previousRawStats&&this.previousRawStats.audio){const M=this.getDifferenceValue(this.previousRawStats.audio.bytesReceived,B.bytesReceived);B.bitrate=Math.round(8*M/this.statInterval/1e3)}const f=this.getDifferenceValue((i=this.previousRawStats)==null?void 0:i.audio.packetsLost,B.packetsLost),m=this.getDifferenceValue((r=this.previousRawStats)==null?void 0:r.audio.packetsReceived,B.packetsReceived)+f;if(m>0&&(B.packetLossRate=Math.round(f/m*100)),this.core.utils.isUndefined(Q.audioLevel)||(B.volume=Q.audioLevel||0),Q.jitterBufferDelay&&Q.jitterBufferEmittedCount){let{jitterBufferEmittedCount:M}=Q,{jitterBufferDelay:v}=Q;(s=this.previousRawStats)!=null&&s.audio&&(M=this.getDifferenceValue(this.previousRawStats.audio.jitterBufferEmittedCount,Q.jitterBufferEmittedCount),v=this.getDifferenceValue(this.previousRawStats.audio.jitterBufferDelay,Q.jitterBufferDelay)),M>0&&(B.jitterBufferDelay=Math.floor(v/M*1e3)),this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.audio.jitterBufferDelay=Q.jitterBufferDelay,this.previousRawStats.audio.jitterBufferEmittedCount=Q.jitterBufferEmittedCount}this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.audio.bytesReceived=B.bytesReceived,this.previousRawStats.audio.packetsReceived=B.packetsReceived,this.previousRawStats.audio.packetsLost=B.packetsLost}!this.core.utils.isUndefined(Q.audioLevel)&&((g=this.audioTransceiver)!=null&&g.receiver.track)&&Q.trackIdentifier===this.audioTransceiver.receiver.track.id&&(B.volume=Q.audioLevel||0)}return B}parseVideoStats(t){var i,r,s,g,B;const Q={bitrate:0,frameRate:0,width:0,height:0,packetLossRate:0,jitterBufferDelay:0,bytesReceived:0,packetsReceived:0,packetsLost:0,framesDecoded:0};for(const f of t){if(f.type==="codec"&&this._decodeMap.set(f.id,f),f.type==="inbound-rtp"&&(f.mediaType==="video"||f.kind==="video")){if(Q.bytesReceived=f.bytesReceived||0,Q.packetsReceived=f.packetsReceived||0,Q.packetsLost=f.packetsLost||0,Q.framesDecoded=f.framesDecoded||0,this.core.utils.isUndefined(f.framesPerSecond)||(Q.frameRate=Math.round(f.framesPerSecond)),f.decoderImplementation&&this._prevDecoderImplementation!==f.decoderImplementation){const v=this._decodeMap.get(f.codecId),U=((i=v?.mimeType)==null?void 0:i.split("/")[1])||"unknown",AA=f.powerEfficientDecoder;this.core.log.info(`decoderImplementation change to ${f.decoderImplementation}(${U}) HWDecoder: ${AA}`),this._prevDecoderImplementation=f.decoderImplementation}if(this.previousRawStats&&this.previousRawStats.video){const v=this.getDifferenceValue(this.previousRawStats.video.bytesReceived,Q.bytesReceived);Q.bitrate=Math.round(8*v/this.statInterval/1e3)}const m=this.getDifferenceValue((r=this.previousRawStats)==null?void 0:r.video.packetsLost,Q.packetsLost),M=this.getDifferenceValue((s=this.previousRawStats)==null?void 0:s.video.packetsReceived,Q.packetsReceived)+m;if(M>0&&(Q.packetLossRate=Math.round(m/M*100)),f.jitterBufferDelay&&f.jitterBufferEmittedCount){let{jitterBufferEmittedCount:v}=f,{jitterBufferDelay:U}=f;(g=this.previousRawStats)!=null&&g.video&&(v=this.getDifferenceValue(this.previousRawStats.video.jitterBufferEmittedCount,f.jitterBufferEmittedCount),U=this.getDifferenceValue(this.previousRawStats.video.jitterBufferDelay,f.jitterBufferDelay)),v>0&&(Q.jitterBufferDelay=Math.floor(U/v*1e3)),this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.video.jitterBufferDelay=f.jitterBufferDelay,this.previousRawStats.video.jitterBufferEmittedCount=f.jitterBufferEmittedCount}this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.video.bytesReceived=Q.bytesReceived,this.previousRawStats.video.packetsReceived=Q.packetsReceived,this.previousRawStats.video.packetsLost=Q.packetsLost}!this.core.utils.isUndefined(f.frameWidth)&&((B=this.videoTransceiver)!=null&&B.receiver.track)&&f.trackIdentifier===this.videoTransceiver.receiver.track.id&&(Q.width=f.frameWidth,Q.height=f.frameHeight)}return Q}parseNetworkStats(t){const i={rtt:0};for(const r of t)if(r.type==="candidate-pair"&&(r.selected||r.state==="succeeded")&&this.core.utils.isNumber(r.currentRoundTripTime)){i.rtt=Math.floor(1e3*r.currentRoundTripTime);break}return i}initPreviousRawStats(){this.previousRawStats={timestamp:Date.now(),audio:{bytesReceived:0,packetsReceived:0,packetsLost:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0}}}},rnA=KrA(jrA()),m5=Symbol("instance"),a2=Symbol("cacheResult"),bK=class{constructor(i,r,s){this.oldState=i,this.newState=r,this.action=s,this.aborted=!1}abort(i){this.aborted=!0,WG.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},LK=class extends Error{constructor(i,r,s){super(r),this.state=i,this.message=r,this.cause=s}};function nnA(t){return typeof t=="object"&&t&&"then"in t}var jG=new Map;function s2(t,i,r={}){return(s,g,B)=>{const Q=r.action||g;if(!r.context){const m=jG.get(s)||[];jG.has(s)||jG.set(s,m),m.push({from:t,to:i,action:Q})}const f=B.value;B.value=function(...m){let M=this;if(r.context&&(M=uC.get(typeof r.context=="function"?r.context.call(this,...m):r.context)),M.state===i)return r.sync?M[a2]:Promise.resolve(M[a2]);M.state instanceof bK&&M.state.action==r.abortAction&&M.state.abort(M);let v=null;Array.isArray(t)?t.length==0?M.state instanceof bK&&M.state.abort(M):typeof M.state=="string"&&t.includes(M.state)||(v=new LK(M._state,`${M.name} ${Q} to ${i} failed: current state ${M._state} not from ${t.join("|")}`)):t!==M.state&&(v=new LK(M._state,`${M.name} ${Q} to ${i} failed: current state ${M._state} not from ${t}`));const U=X=>{if(r.fail&&r.fail.call(this,X),r.sync){if(r.ignoreError)return X;throw X}return r.ignoreError?Promise.resolve(X):Promise.reject(X)};if(v)return U(v);const AA=M.state,z=new bK(AA,i,Q);WG.call(M,z);const sA=X=>{var QA;return M[a2]=X,z.aborted||(WG.call(M,i),(QA=r.success)===null||QA===void 0||QA.call(this,M[a2])),X},eA=X=>(WG.call(M,AA,X),U(X));try{const X=f.apply(this,m);return nnA(X)?X.then(sA).catch(eA):r.sync?sA(X):Promise.resolve(sA(X))}catch(X){return eA(new LK(M._state,`${M.name} ${Q} from ${t} to ${i} failed: ${X}`,X instanceof Error?X:new Error(String(X))))}}}}var anA=typeof window<"u"&&window.__AFSM__?(r,s)=>{window.dispatchEvent(new CustomEvent(r,{detail:s}))}:typeof importScripts<"u"?(r,s)=>{postMessage({type:r,payload:s})}:()=>{};function WG(t,i){const r=this._state;this._state=t;const s=t.toString();t&&this.emit(s,r),this.emit(uC.STATECHANGED,t,r,i),this.updateDevTools({value:t,old:r,err:i instanceof Error?i.message:String(i)})}var uC=class EC extends rnA.default{constructor(i,r,s){super(),this.name=i,this.groupName=r,this._state=EC.INIT,i||(i=Date.now().toString(36)),s?Object.setPrototypeOf(this,s):s=Object.getPrototypeOf(this),r||(this.groupName=this.constructor.name);const g=s[m5];g?this.name=g.name+"-"+g.count++:s[m5]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){const i=Object.getPrototypeOf(this),r=jG.get(i)||[];let s=new Set,g=[],B=[];const Q=new Set,f=Object.getPrototypeOf(i);jG.has(f)&&(f.stateDiagram.forEach(M=>s.add(M)),f.allStates.forEach(M=>Q.add(M))),r.forEach(({from:M,to:v,action:U})=>{typeof M=="string"?g.push({from:M,to:v,action:U}):M.length?M.forEach(AA=>{g.push({from:AA,to:v,action:U})}):B.push({to:v,action:U})}),g.forEach(({from:M,to:v,action:U})=>{Q.add(M),Q.add(v),Q.add(U+"ing"),s.add(`${M} --> ${U}ing : ${U}`),s.add(`${U}ing --> ${v} : ${U} 🟢`),s.add(`${U}ing --> ${M} : ${U} 🔴`)}),B.forEach(({to:M,action:v})=>{s.add(`${v}ing --> ${M} : ${v} 🟢`),Q.forEach(U=>{U!==M&&s.add(`${U} --> ${v}ing : ${v}`)})});const m=[...s];return Object.defineProperties(i,{stateDiagram:{value:m},allStates:{value:Q}}),m}static get(i){let r;return typeof i=="string"?(r=EC.instances.get(i),r||EC.instances.set(i,r=new EC(i,void 0,Object.create(EC.prototype)))):(r=EC.instances2.get(i),r||EC.instances2.set(i,r=new EC(i.constructor.name,void 0,Object.create(EC.prototype)))),r}static getState(i){var r;return(r=EC.get(i))===null||r===void 0?void 0:r.state}updateDevTools(i={}){anA(EC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){WG.call(this,i)}};uC.STATECHANGED="stateChanged",uC.UPDATEAFSM="updateAFSM",uC.INIT="[*]",uC.ON="on",uC.OFF="off",uC.instances=new Map,uC.instances2=new WeakMap;var NG=class extends uC{constructor(i,r){super(),this.core=i,rr(this,"audioPlayer"),rr(this,"videoPlayer"),rr(this,"callback"),rr(this,"avPlayerStateSyncManager"),rr(this,"_log"),rr(this,"_videoPlayerLog"),rr(this,"_audioPlayerLog"),rr(this,"lastPausedReason"),rr(this,"muted",!1),this._log=r,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,s=>this.handleAutoPlayFailed(this.audioPlayer,s)),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,r;await this.videoPlayer.enterPIPPromise,(r=(i=this.callback)==null?void 0:i.onPictureInPictureStateChanged)==null||r.call(i,{isPictureInPicture:!0,pictureInPictureWindow:this.videoPlayer.pipWindow})}handleLeavePictureInPicture(){var i,r;(r=(i=this.callback)==null?void 0:i.onPictureInPictureStateChanged)==null||r.call(i,{isPictureInPicture:!1})}handleEnterFullScreen(){var i,r;(r=(i=this.callback)==null?void 0:i.onFullScreenStateChanged)==null||r.call(i,{isFullScreen:!0})}handleLeaveFullScreen(){var i,r;(r=(i=this.callback)==null?void 0:i.onFullScreenStateChanged)==null||r.call(i,{isFullScreen:!1})}onLoadStart(){}onPlaying(){}onPaused(i){this.lastPausedReason=i}onStopped(){}setVideoContainer(i){if(this.core.utils.isString(i)){const r=document.getElementById(i);r&&this.videoPlayer.setContainer(r)}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(s=>{this.handleAutoPlayFailed(this.videoPlayer,s,"video")}),r=this.audioPlayer.play().catch(s=>{this.handleAutoPlayFailed(this.audioPlayer,s)});await Promise.all([i,r])}handleAutoPlayFailed(i,r,s="audio"){var g,B;this._log.warn("handleAutoPlayFailed",r);const Q=()=>{this.audioPlayer.resume().then(()=>{document.removeEventListener("click",Q,!0)})};document.addEventListener("click",Q,!0),(B=(g=this.callback)==null?void 0:g.onAutoPlayFailed)==null||B.call(g,{type:s,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))}};Ew([s2([uC.INIT,"PAUSED"],"LOADSTART",{ignoreError:!0,sync:!0,success(){var t,i;(i=(t=this.callback)==null?void 0:t.onLoadStart)==null||i.call(t)},fail(t){this._log.warn("onLoadStart",t)}})],NG.prototype,"onLoadStart"),Ew([s2(["LOADSTART","PAUSED"],"PLAYING",{ignoreError:!0,sync:!0,success(){var t,i;(i=(t=this.callback)==null?void 0:t.onPlaying)==null||i.call(t)},fail(t){this._log.warn("onPlaying",t)}})],NG.prototype,"onPlaying"),Ew([s2("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(){var t,i;(i=(t=this.callback)==null?void 0:t.onPaused)==null||i.call(t,{reason:this.lastPausedReason})},fail(t){this._log.warn("onPaused",t)}})],NG.prototype,"onPaused"),Ew([s2([],uC.INIT,{ignoreError:!0,sync:!0,success(){var t,i;(i=(t=this.callback)==null?void 0:t.onStopped)==null||i.call(t)},fail(t){this._log.warn("onStopped",t)}})],NG.prototype,"onStopped");var D5=NG,snA=["overseas-webrtc.tlivewebrtc.com","oswebrtc-lint.tliveplay.com"],S2=class B6{constructor(i){this.core=i,rr(this,"_sdkAppId"),rr(this,"_userId"),rr(this,"connectedRoomIdSet",new Set),rr(this,"updateSeq",0),rr(this,"_log"),rr(this,"player"),rr(this,"peerConnection"),rr(this,"svrSig"),rr(this,"streamURL"),rr(this,"signalURL"),rr(this,"insertableStreamsAbortMap",new Map),rr(this,"scriptTransformWorker"),rr(this,"connectionState","disconnected"),rr(this,"isStarted",!1),rr(this,"isStopped",!0),rr(this,"isReconnecting",!1),rr(this,"callback"),rr(this,"isFireWallErrorEmitted",!1),rr(this,"stat"),rr(this,"isH264DecodeSupported"),rr(this,"connectionTimeoutId"),rr(this,"streamHealthCheckTimeoutId"),rr(this,"streamHealthCheckReject"),i.loggerManager.startUpload(),this._log=this.core.log.createChild({id:`${this.getAlias()}`}),this.player=new D5(i,this._log),i.innerEmitter.on(i.INNER_EVENT.SEI_MESSAGE,this.onSEIMessage,this)}getName(){return B6.Name}getAlias(){return"LEB"}getGroup(){return""}getValidateRule(i){switch(i){case"start":return WrA;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 r={},s=["onStats","onSEIMessage"];for(const g of Object.keys(i)){const B=i[g];typeof B=="function"&&(s.includes(g)?r[g]=B:r[g]=(...Q)=>(this._log.debug(`callback ${g} called`,Q.length>0?Q[0]:""),B(...Q)))}return r}async start(i){var r;this.isStopped=!1;const{view:s,url:g,volume:B,muted:Q,fillMode:f,loggerConfig:m,callback:M}=i;this.callback=this.wrapCallback(M),this.player.setCallback(this.callback);const{errorModule:{RtcError:v,ErrorCode:U,ErrorCodeDictionary:AA},loggerManager:z,rtcDectection:sA}=this.core;if(this._sdkAppId=m.sdkAppId,this._userId=m.userId,this._log.setSdkAppId(m.sdkAppId),this._log.setUserId(m.userId),this.player.updateLogConfig(m),z.addJoinedUser(m),!sA.isWebRTCSupported()||!sA.isAddTransceiverSupported())throw new v({code:U.ENV_NOT_SUPPORTED,extraCode:AA.NOT_SUPPORTED_WEBRTC,message:"webrtc not supported"});if(!(await sA.decodeSupportStatus()).isH264DecodeSupported||this.isH264DecodeSupported===!1)throw this.isH264DecodeSupported=!1,new v({code:U.ENV_NOT_SUPPORTED,extraCode:AA.NOT_SUPPORTED_H264_DECODE,message:"h264 not supported"});!sA.IS_SEI_SUPPORTED&&M?.onSEIMessage&&((r=M.onError)==null||r.call(M,new v({code:U.ENV_NOT_SUPPORTED,extraCode:AA.NOT_SUPPORTED_SEI,message:"sei not supported"}))),this.player.setVideoContainer(s),this.player.setMuted(Q),this.player.setFillMode(f);try{await this.connect(g),this.stat=new onA(this.peerConnection,this.core),this.stat.start(QA=>{var wA,HA;return(HA=(wA=this.callback)==null?void 0:wA.onStats)==null?void 0:HA.call(wA,QA)});const eA=this.player.play();this.player.setVolume(B);const X=this.createStreamHealthCheckPromise();await Promise.race([eA,X]),this.clearStreamHealthCheck(),this.isStarted=!0}catch(eA){throw this.stop(),eA}}async update(i){const{view:r,url:s,volume:g,muted:B,fillMode:Q,action:f,fullScreen:m,pictureInPicture:M}=i;s&&s!==this.streamURL&&await this.switchStream(s),this.player.setMuted(B),this.player.setVolume(g),this.player.setFillMode(Q),r&&this.player.videoPlayer.setContainer(this.core.utils.isString(r)?document.getElementById(r):r),f==="pause"?this.player.pause():f==="resume"&&this.player.resume(),this.core.utils.isBoolean(m)&&(m?await this.player.enterFullscreen():await this.player.exitFullscreen()),this.core.utils.isBoolean(M)&&(M?await this.player.enterPictureInPicture():await this.player.exitPictureInPicture())}async switchStream(i){this._log.info("switchStream",i);const r=this.peerConnection,s=this.streamURL,g=this.signalURL,B=this.svrSig,Q=new Map(this.insertableStreamsAbortMap),f=this.player;delete this.peerConnection,delete this.streamURL,delete this.signalURL,delete this.svrSig,this.insertableStreamsAbortMap.clear();const m=new D5(this.core,this._log);m.setVideoContainer(f.videoPlayer.container),m.setFillMode(f.videoPlayer.objectFit),m.setMuted(f.muted),m.setCallback(this.callback);const M=v=>{const{track:U}=v;this.createEncodedStreams(v.receiver),this.initReceiverTransform(v.receiver,U.kind==="audio"),U.kind==="audio"?m.setAudioTrack(U):m.setVideoTrack(U)};try{await this.connectForSwitch(i,M),this._log.info("switchStream: new connection established"),await this.waitForNewPlayerFirstFrame(m),this._log.info("switchStream: new stream first frame received"),f.audioPlayer.setMuted(!0),f.stop(),this.player=m,r&&(clearTimeout(this.connectionTimeoutId),r.close(),r.getReceivers().forEach(v=>Q.delete(v)),s&&B&&g&&this.fetchStopStreamWithParams(s,g,B).catch(v=>{this._log.warn("switchStream: stop old stream failed",v)})),this._log.info("switchStream: switch completed successfully")}catch(v){this._log.error("switchStream failed",v),m.stop();const U=this.peerConnection;throw U&&(U.close(),U.getReceivers().forEach(AA=>this.insertableStreamsAbortMap.delete(AA))),this.peerConnection=r,this.streamURL=s,this.signalURL=g,this.svrSig=B,this.insertableStreamsAbortMap=Q,this.player=f,f.audioPlayer.setMuted(f.muted),v}}waitForNewPlayerFirstFrame(i){return new Promise((r,s)=>{let g=0,B=!1;const Q=i.videoPlayer.getElement();if(!Q)return void s(new Error("VideoPlayer has no video element"));const f=()=>{B=!0,clearInterval(v),Q.removeEventListener("loadeddata",m),Q.removeEventListener("playing",M)},m=()=>{B||(this._log.info("waitForNewPlayerFirstFrame: loadeddata event fired"),f(),r())},M=()=>{B||(this._log.info("waitForNewPlayerFirstFrame: playing event fired"),f(),r())};Q.addEventListener("loadeddata",m,{once:!0}),Q.addEventListener("playing",M,{once:!0}),i.play().catch(U=>{this._log.warn("waitForNewPlayerFirstFrame: play failed",U)});const v=setInterval(()=>{if(!B){if(g+=100,Q.videoWidth>0&&Q.videoHeight>0)return this._log.info(`waitForNewPlayerFirstFrame: video has valid dimensions ${Q.videoWidth}x${Q.videoHeight}`),f(),void r();g>=1e4&&(f(),s(new Error("waitForNewPlayerFirstFrame timeout")))}},100)})}connectForSwitch(i,r){return new Promise((s,g)=>{try{this.initScriptTransformWorker();const B={encodedInsertableStreams:this.enableSEI,iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},Q=new RTCPeerConnection(B);this.peerConnection=Q,Q.onconnectionstatechange=()=>{this.connectionState=Q.connectionState,this._log.info("connectForSwitch connectionState",Q.connectionState),Q.connectionState!=="failed"&&Q.connectionState!=="closed"||g(new Error(`connection is ${Q.connectionState}`)),Q.connectionState==="connected"&&(this.logSelectedCandidate(),s())},Q.ontrack=r,Q.addTransceiver("audio",{direction:"recvonly"}),Q.addTransceiver("video",{direction:"recvonly"}),this._log.info("connectForSwitch createOffer"),Q.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}).then(f=>(f.sdp=p5(f.sdp),this._log.info("connectForSwitch setOffer"),Q.setLocalDescription(f))).then(()=>{const f={sessionId:_K(),streamurl:i,clientinfo:this.core.environment.getOSString(),localsdp:Q.localDescription};return this.exchangeSDP(i,f)}).then(f=>(this._log.info("connectForSwitch setAnswer"),Q.setRemoteDescription(f))).catch(g)}catch(B){g(B)}this.connectionTimeoutId=setTimeout(()=>g(new Error("connection timeout")),1e4)})}async fetchStopStreamWithParams(i,r,s){try{const g=`${r}/webrtc/v1/stopstream`,B=await g2(g,{streamurl:i,svrsig:s},{timeout:3}),{errcode:Q,errmsg:f}=B;if(Q!==0)throw new Error(`errCode:${Q}, errmsg:${f}`);return B}catch(g){this._log.error("fetchStopStreamWithParams error",g)}}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,r)=>{this.streamHealthCheckReject=r,this.streamHealthCheckTimeoutId=window.setTimeout(()=>this.checkStreamHealth(r),5e3)})}clearStreamHealthCheck(){this.streamHealthCheckTimeoutId&&(clearTimeout(this.streamHealthCheckTimeoutId),delete this.streamHealthCheckTimeoutId),delete this.streamHealthCheckReject}async checkStreamHealth(i){if(!this.isStopped&&this.peerConnection)try{const r=this.peerConnection.getReceivers().find(U=>{var AA;return((AA=U.track)==null?void 0:AA.kind)==="video"});if(!r)return void this._log.warn("checkStreamHealth: no video receiver found");const s=await r.getStats();let g=0,B=0;s.forEach(U=>{U.type==="inbound-rtp"&&(U.mediaType==="video"||U.kind==="video")&&(g=U.bytesReceived||0,B=U.framesDecoded||0)});const{isPlaying:Q}=this.player,f=Q||B>0;this._log.info(`checkStreamHealth: bytesReceived=${g}, framesDecoded=${B}, isPlaying=${Q}`);const{RtcError:m,ErrorCode:M,ErrorCodeDictionary:v}=this.core.errorModule;g===0?(this._log.warn("checkStreamHealth: no stream data received after 5s"),i(new m({code:M.OPERATION_FAILED,message:"no stream data received"}))):f||(this._log.warn("checkStreamHealth: decode failed"),this.isH264DecodeSupported=!1,i(new m({code:M.ENV_NOT_SUPPORTED,extraCode:v.NOT_SUPPORTED_H264_DECODE,message:"h264 decode failed"})))}catch(r){this._log.warn("checkStreamHealth error",r)}}connect(i){return new Promise((r,s)=>{try{this.initScriptTransformWorker();const g={encodedInsertableStreams:this.enableSEI,iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},B=new RTCPeerConnection(g);this.peerConnection=B,B.onconnectionstatechange=()=>{this.connectionState=B.connectionState,this._log.info("connectionState",B.connectionState),B.connectionState!=="failed"&&B.connectionState!=="closed"||(this.isStarted?this.reconnect(i):s(new Error(`connection is ${B.connectionState}`))),B.connectionState==="connected"&&(this.logSelectedCandidate(),r())},B.ontrack=Q=>this.onTrack(Q),B.addTransceiver("audio",{direction:"recvonly"}),B.addTransceiver("video",{direction:"recvonly"}),this._log.info("createOffer"),B.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}).then(Q=>(Q.sdp=p5(Q.sdp),this._log.info("setOffer"),B.setLocalDescription(Q))).then(()=>{const Q={sessionId:_K(),streamurl:i,clientinfo:this.core.environment.getOSString(),localsdp:B.localDescription};return this.exchangeSDP(i,Q)}).then(Q=>(this._log.info("setAnswer"),B.setRemoteDescription(Q))).catch(s)}catch(g){s(g)}this.connectionTimeoutId=setTimeout(()=>s(new Error("connection timeout")),1e4)})}async exchangeSDP(i,r){let s,g,B;try{this._log.info("exchangeSDP");const Q=gnA(i);if(!Q)throw new Error("streamDomain is empty");const{signalDomain:f,cached:m}=await this.fetchSignalDomain(Q);if(!f)throw new Error("signalDomain is empty");{this._log.info("try exchangeSDP signalDomain:",f,m);const M=await this.doExchangeSDP(`https://${f}`,r,3);s=M.url,g=M.remoteSdp,B=M.svrSig}}catch(Q){this._log.warn("exchangeSDP failed, fallback",Q);try{const f=await this.core.utils.promiseAny(snA.map(m=>this.doExchangeSDP(`https://${m}`,r,3)));s=f.url,g=f.remoteSdp,B=f.svrSig}catch(f){throw this._log.error("exchangeSDP failed",f),f[0]||f}}return this.streamURL=i,this.signalURL=s,this.svrSig=B,g}async reconnect(i){var r,s;if(!this.isReconnecting){this.isReconnecting=!0;try{this._log.warn("start reconnect"),await this.connect(i),this._log.warn("reconnect success")}catch(g){this._log.error("reconnect error",g);const{RtcError:B,ErrorCode:Q}=this.core.errorModule;(s=(r=this.callback)==null?void 0:r.onError)==null||s.call(r,new B({code:Q.OPERATION_FAILED,message:"reconnect failed"}))}finally{this.isReconnecting=!1}}}async logSelectedCandidate(){if(!this.peerConnection)return;const i=await this.peerConnection.getStats();for(const[r,s]of i)if(this.core.rtcDectection.isSelectedCandidatePair(s)){const g=i.get(s.localCandidateId),B=i.get(s.remoteCandidateId);g&&this._log.info(`local candidate: ${g.candidateType} ${g.protocol}:${g.ip||g.address}:${g.port} ${g.networkType||""} ${g.relayProtocol?`relayProtocol:${g.relayProtocol} url: ${g.url}`:""}`),B&&this._log.info(`remote candidate: ${B.candidateType} ${B.protocol}:${B.ip||B.address}:${B.port}`);break}}async doExchangeSDP(i,r,s){const g=`${i}/webrtc/v1/pullstream`,B=await g2(g,r,{timeout:s}),{errcode:Q,errmsg:f,remotesdp:m,svrsig:M}=B;if(Q!==0){const v=new Error(`errCode:${Q}, errMsg:${f}`);throw v.name="RequestSignalError",v}return{url:i,remoteSdp:m,svrSig:M}}createEncodedStreams(i){var r;if(this.enableSEI&&this.core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED)try{if(this._log.warn("enableSEI",this.enableSEI),!this.insertableStreamsAbortMap.has(i)){const s=i.createEncodedStreams(),g=new AbortController,B={abortController:g,enqueue:Q=>i.track.kind==="audio"?Q:this.decodeVideoFrame(Q)};s.readable.pipeThrough(new TransformStream({transform:(Q,f)=>{const m=B.enqueue(Q);m&&f.enqueue(m)}})).pipeTo(s.writable,g).catch(Q=>{Q!=="destroy"&&this._log.warn(Q)}),(r=this.insertableStreamsAbortMap.get(i))==null||r.abort("destroy"),this.insertableStreamsAbortMap.set(i,g)}}catch(s){this._log.warn(`createEncodedStreams ${i.track.kind} failed`,s)}}initReceiverTransform(i,r){this.peerConnection&&this.enableSEI&&this.scriptTransformWorker&&!i.transform&&(i.transform=new RTCRtpScriptTransform(this.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:"",streamType:this.core.enums.RemoteStreamType.Main}))}initScriptTransformWorker(){const{room:i,rtcDectection:r,createScriptTransformWorker:s,trtc:g,TRTC:B}=this.core;!this.enableSEI||r.IS_INSERTABLE_STREAM_SUPPORTED||this.scriptTransformWorker||r.IS_SCRIPT_TRANSFORM_SUPPORTED&&(this._log.info("initScriptTransformWorker"),this.scriptTransformWorker=s({videoEncodePipeline:i.videoManager.encodePipeline,videoDecodePipeline:i.videoManager.decodePipeline,audioEncodePipeline:i.audioManager.encodePipeline,audioDecodePipeline:i.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=Q=>{var f,m;Q.data.type==="sei"&&((m=(f=this.callback)==null?void 0:f.onSEIMessage)==null||m.call(f,{data:Q.data.data,seiPayloadType:Q.data.seiPayloadType}))},this.scriptTransformWorker.onerror=Q=>{this._log.error("scriptTransformWorker error: ",Q.message)})}decodeVideoFrame(i){if(!this.core.room.videoManager)return i;for(const r of this.core.room.videoManager.decodePipeline)if(r&&!(i=r({frame:i})))return;return i}async fetchStopStream(){if(this.streamURL&&this.svrSig&&this.signalURL)try{const i=`${this.signalURL}/webrtc/v1/stopstream`,r=await g2(i,{streamurl:this.streamURL,svrsig:this.svrSig},{timeout:3}),{errcode:s,errmsg:g}=r;if(s!==0)throw new Error(`errCode:${s}, errmsg:${g}`);return r}catch(i){this._log.error("fetchStopStream error",i)}}onTrack(i){const{track:r}=i;this.createEncodedStreams(i.receiver),this.initReceiverTransform(i.receiver,r.kind==="audio"),r.kind==="audio"?this.player.setAudioTrack(r):this.player.setVideoTrack(r)}onSEIMessage({room:i,nalu:r}){var s,g;i===this.core.room&&((g=(s=this.callback)==null?void 0:s.onSEIMessage)==null||g.call(s,{data:r.seiPayload.buffer,seiPayloadType:r.seiPayloadType}))}async fetchSignalDomain(i,r=I2[0]){var s;const g=`https://${r}/signal_query`;try{const B=window.localStorage.getItem(FK);if(B){const v=JSON.parse(B);if(((s=v[i])==null?void 0:s.expire)-new Date().getTime()>0)return{signalDomain:v[i].signal,cached:!0}}const Q=await g2(g,{domain:i,requestid:_K(16),client_type:"Web",client_info:window.navigator.userAgent}),{errcode:f,errmsg:m,data:M}=Q;if(f===0){const{signal_domain:v,cache_time:U}=M;let AA={};const z=window.localStorage.getItem(FK);z&&(AA=JSON.parse(z)),AA[i]={signal:v,expire:new Date().getTime()+1e3*U};try{window.localStorage.setItem(FK,JSON.stringify(AA))}catch{}return{signalDomain:v,cached:!1}}throw new Error(`errCode:${f} errmsg:${m}`)}catch(B){return this._log.error("fetchSignalDomain error",B),I2[1]&&r!==I2[1]?this.fetchSignalDomain(i,I2[1]):{signalDomain:"",cached:!1}}}};rr(S2,"Name","LEBPlayer"),Ew([inA({fnName:"connect"})],S2.prototype,"stop"),Ew([tnA({settings:{retries:1/0,timeout:2e3},onRetrying(t){var i;if(this._log.warn(`retry connect ${t}`),t>=3&&((i=this.callback)==null?void 0:i.onError)&&!this.isFireWallErrorEmitted){const{RtcError:r,ErrorCode:s,ErrorCodeDictionary:g}=this.core.errorModule;this.isFireWallErrorEmitted=!0,this.callback.onError(new r({code:s.OPERATION_FAILED,extraCode:g.FIREWALL_RESTRICTION,message:"firewall restriction"}))}},onError(t,i,r,s){var g;if(this._log.warn("connect failed",t),this.peerConnection&&(this.peerConnection.close(),delete this.peerConnection),!this.isStopped&&((g=t.message||t)==null?void 0:g.includes("connection")))i();else{const{RtcError:B,ErrorCode:Q}=this.core.errorModule;r(new B({code:Q.UNKNOWN_ERROR,message:t.message}))}}})],S2.prototype,"connect");var u6=S2,g2=async(t,i,r={})=>{const{timeout:s=10}=r;let g,B=0,Q={};window.AbortController&&(g=new window.AbortController,Q={signal:g.signal},B=window.setTimeout(()=>g.abort(),1e3*s));const f=await fetch(t,HrA({body:JSON.stringify(i),cache:"no-cache",credentials:"same-origin",headers:{"content-type":"text/plain;charset=utf-8"},method:"POST",mode:"cors"},Q));if(B&&window.clearTimeout(B),f.status!==200)throw new Error(`Network Error, status code:${f.status}`);return f.json()},I2=["webrtc-signal-scheduler.tlivesource.com","bak-webrtc-signal-scheduler.tlivesource.com"],FK="LEB_PLAYER_STORAGE_KEY",gnA=t=>{const i=/^(?:webrtc:\/\/)([0-9.\-A-Za-z_]+)(?:\/)(?:[0-9.\-A-Za-z_=]+)(?:\/)(?:[^?#]*)(?:\?*)(?:[^?#]*)/.exec(t);return i?i[1]:""},InA=u6;const cnA=Object.freeze(Object.defineProperty({__proto__:null,LEBPlayer:u6,default:InA},Symbol.toStringTag,{value:"Module"})),EnA=Mk(cnA);var Q6=Object.defineProperty,lnA=Object.defineProperties,CnA=Object.getOwnPropertyDescriptors,y5=Object.getOwnPropertySymbols,BnA=Object.prototype.hasOwnProperty,unA=Object.prototype.propertyIsEnumerable,Gj=(t,i,r)=>i in t?Q6(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,QnA=(t,i)=>{for(var r in i||(i={}))BnA.call(i,r)&&Gj(t,r,i[r]);if(y5)for(var r of y5(i))unA.call(i,r)&&Gj(t,r,i[r]);return t},dnA=(t,i)=>lnA(t,CnA(i)),hnA=(t,i)=>{for(var r in i)Q6(t,r,{get:i[r],enumerable:!0})},Oa=(t,i,r)=>Gj(t,typeof i!="symbol"?i+"":i,r);async function pnA({sdkAppId:t,userId:i,userSig:r,core:s}){var g;const B=Math.round(new Date().getTime()/1e3);try{const Q=await s.schedule.getAbilityConfig(t,s.schedule.ScheduleRequestType.TRTC_AUTO_CONF,{sdkAppId:t,userId:i,userSig:r,timestamp:B});s.log.info(`virtual background ability response: ${JSON.stringify(Q)}`);const{data:f}=Q;return(g=f?.trtcAutoConf)!=null&&g.web_ar?{auth:!0,timestamp:B}:{auth:!1}}catch(Q){return s.log.error("virtual background fetch error",Q),{auth:!1}}}var fnA={sdkAppId:{required:!0,type:"number"},userId:{required:!0,type:"string"},userSig:{required:!0,type:"string"}};function mnA(t){return{name:"VirtualBackgroundOptions",type:"object",required:!0,allowEmpty:!1,properties:dnA(QnA({},fnA),{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,r,s,g){var B;const{RtcError:Q,ErrorCode:f,ErrorCodeDictionary:m}=t.errorModule;if(!i)return;const{type:M,src:v,onAbort:U}=i;if(M==="image"&&!v)throw new Q({code:f.INVALID_PARAMETER,extraCode:m.INVALID_PARAMETER_REQUIRED,fnName:s,messageParams:{key:"src"}});if(U&&!t.utils.isFunction(U))throw new Q({code:f.INVALID_PARAMETER,extraCode:m.INVALID_PARAMETER_TYPE,fnName:s,messageParams:{key:"onAbort",value:typeof U,rule:{type:"Function"}}});if(!((B=t.room.videoManager.cameraTrack)!=null&&B.mediaTrack))throw new Q({code:f.INVALID_OPERATION,extraCode:m.INVALID_OPERATION_NEED_VIDEO,fnName:s})}}}function DnA(t){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,r,s,g){if(!i)return;const{RtcError:B,ErrorCode:Q,ErrorCodeDictionary:f}=t.errorModule,{type:m,src:M}=i;if(m==="image"&&!M)throw new B({code:Q.INVALID_PARAMETER,extraCode:f.INVALID_PARAMETER_REQUIRED,fnName:s,messageParams:{key:"src"}})}}}function ynA(t){return{name:"StopVirtualBackgroundOptions",required:!1}}var RnA=(()=>{var t=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(i={}){var r,s,g=i;g.ready=new Promise((P,F)=>{r=P,s=F});var B=Object.assign({},g),Q="";typeof document<"u"&&document.currentScript&&(Q=document.currentScript.src),t&&(Q=t),Q=Q.indexOf("blob:")!==0?Q.substr(0,Q.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var f,m,M=g.print||console.log.bind(console),v=g.printErr||console.error.bind(console);function U(P){if(bi(P))return function(F){for(var EA=atob(F),RA=new Uint8Array(EA.length),GA=0;GAP.startsWith(Zi);function qt(P){return Promise.resolve().then(()=>function(F){if(F==$e&&f)return new Uint8Array(f);var EA=U(F);if(EA)return EA;throw"both async and sync fetching of the wasm failed"}(P))}function ai(P,F,EA,RA){return function(GA,WA,Ce){return qt(GA).then(ge=>WebAssembly.instantiate(ge,WA)).then(ge=>ge).then(Ce,ge=>{v(`failed to asynchronously prepare wasm: ${ge}`),Je(ge)})}(F,EA,RA)}bi($e="data:application/octet-stream;base64,AGFzbQEAAAAB8gEfYAJ/fwBgAX8Bf2ADf39/AX9gAX8AYAN/f38AYAJ/fwF/YAR/f39/AGAAAGAFf39/f38AYAZ/f39/f38AYAR/f39/AX9gB39/f39/f38AYAN/fn8BfmAFf3x8fHwAYAZ/fHx8fHwAYAV/f39/fwF8YAl/f39/f39/f38AYAN/f38BfGAKf39/f39/f39/fwBgDX9/f39/f39/f39/f38AYAJ/fAB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gAUYEQEEBDwsgASgCBCICLQAAIQECQCAAKAIEIgMtAAAiAEUNACAAIAFHDQADQCACLQABIQEgAy0AASIARQ0BIAJBAWohAiADQQFqIQMgACABRg0ACwsgACABRgtvAQF/IwBBgAJrIgUkAAJAIAIgA0wNACAEQYDABHENACAFIAFB/wFxIAIgA2siA0GAAiADQYACSSIBGxAmGiABRQRAA0AgACAFQYACEB0gA0GAAmsiA0H/AUsNAAsLIAAgBSADEB0LIAVBgAJqJAALgQMBBH8jAEHwAGsiAiQAIAAoAgAiA0EEaygCACEEIANBCGsoAgAhBSACQgA3AlAgAkIANwJYIAJCADcCYCACQgA3AGcgAkIANwJIIAJBADYCRCACQdzMADYCQCACIAA2AjwgAiABNgI4IAAgBWohAwJAIAQgAUEAEB4EQEEAIAMgBRshAAwBCyAAIANOBEAgAkIANwAvIAJCADcCGCACQgA3AiAgAkIANwIoIAJCADcCECACQQA2AgwgAiABNgIIIAIgADYCBCACIAQ2AgAgAkEBNgIwIAQgAiADIANBAUEAIAQoAgAoAhQRCQAgAigCGA0BC0EAIQAgBCACQThqIANBAUEAIAQoAgAoAhgRCAACQAJAIAIoAlwOAgABAgsgAigCTEEAIAIoAlhBAUYbQQAgAigCVEEBRhtBACACKAJgQQFGGyEADAELIAIoAlBBAUcEQCACKAJgDQEgAigCVEEBRw0BIAIoAlhBAUcNAQsgAigCSCEACyACQfAAaiQAIAAL0AEBBX8jAEEQayIGJAAgBkEEaiICED8jAEEQayIFJAACfyACLQALQQd2BEAgAigCBAwBCyACLQALQf8AcQshBANAAkACfyACLQALQQd2BEAgAigCAAwBCyACCyEDIAUgATkDACACAn8gAyAEQQFqIAUQRiIDQQBOBEAgAyAETQ0CIAMMAQsgBEEBdEEBcgsiBBArDAELCyACIAMQKyAAIAIpAgA3AgAgACACKAIINgIIIAJCADcCACACQQA2AgggBUEQaiQAIAIQQSAGQRBqJAALgAQBA38gAkGABE8EQCAAIAEgAhASIAAPCyAAIAJqIQMCQCAAIAFzQQNxRQRAAkAgAEEDcUUEQCAAIQIMAQsgAkUEQCAAIQIMAQsgACECA0AgAiABLQAAOgAAIAFBAWohASACQQFqIgJBA3FFDQEgAiADSQ0ACwsCQCADQXxxIgRBwABJDQAgAiAEQUBqIgVLDQADQCACIAEoAgA2AgAgAiABKAIENgIEIAIgASgCCDYCCCACIAEoAgw2AgwgAiABKAIQNgIQIAIgASgCFDYCFCACIAEoAhg2AhggAiABKAIcNgIcIAIgASgCIDYCICACIAEoAiQ2AiQgAiABKAIoNgIoIAIgASgCLDYCLCACIAEoAjA2AjAgAiABKAI0NgI0IAIgASgCODYCOCACIAEoAjw2AjwgAUFAayEBIAJBQGsiAiAFTQ0ACwsgAiAETw0BA0AgAiABKAIANgIAIAFBBGohASACQQRqIgIgBEkNAAsMAQsgA0EESQRAIAAhAgwBCyAAIANBBGsiBEsEQCAAIQIMAQsgACECA0AgAiABLQAAOgAAIAIgAS0AAToAASACIAEtAAI6AAIgAiABLQADOgADIAFBBGohASACQQRqIgIgBE0NAAsLIAIgA0kEQANAIAIgAS0AADoAACABQQFqIQEgAkEBaiICIANHDQALCyAACwsAIAEgAiAAEEIaCxIAIAFBAXRB8MoAakECIAAQQgv5AQEEfwJ/IAEQKiECIwBBEGsiBSQAAn8gAC0AC0EHdgRAIAAoAgQMAQsgAC0AC0H/AHELIgRBAE8EQAJAIAIgAC0AC0EHdgR/IAAoAghB/////wdxQQFrBUEKCyIDIARrTQRAIAJFDQECfyAALQALQQd2BEAgACgCAAwBCyAACyIDIAQEfyACIANqIAMgBBBFIAEgAkEAIAMgBGogAUsbQQAgASADTxtqBSABCyACEEUgACACIARqIgEQMSAFQQA6AA8gASADaiAFLQAPOgAADAELIAAgAyACIARqIANrIARBACACIAEQRAsgBUEQaiQAIAAMAQsQJwALC/ICAgJ/AX4CQCACRQ0AIAAgAToAACAAIAJqIgNBAWsgAToAACACQQNJDQAgACABOgACIAAgAToAASADQQNrIAE6AAAgA0ECayABOgAAIAJBB0kNACAAIAE6AAMgA0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/////B3FBAWsFQQoLECsLPQEBfyMAQRBrIgIkACACQQA6AA8DQCABBEAgACACLQAPOgAAIAFBAWshASAAQQFqIQAMAQsLIAJBEGokAAsaACAALQALQQd2BEAgACgCCBogACgCABAZCwvmAQEFfyMAQRBrIgUkACMAQSBrIgMkACMAQRBrIgQkACAEIAA2AgwgBCAAIAFqNgIIIAMgBCgCDDYCGCADIAQoAgg2AhwgBEEQaiQAIAMoAhghBCADKAIcIQYjAEEQayIBJAAgASAGNgIMIAIgBCAGIARrIgQQQyABIAIgBGo2AgggAyABKAIMNgIQIAMgASgCCDYCFCABQRBqJAAgAyAAIAMoAhAgAGtqNgIMIAMgAiADKAIUIAJrajYCCCAFIAMoAgw2AgggBSADKAIINgIMIANBIGokACAFKAIMIQcgBUEQaiQAIAcLDwAgAgRAIAAgASACEDILC/UCAQV/IwBBEGsiByQAIAIgAUF/c0Hv////B2pNBEACfyAALQALQQd2BEAgACgCAAwBCyAACyEIIAdBBGoiCSAAIAFB5////wNJBH8gByABQQF0NgIMIAcgASACajYCBCMAQRBrIgIkACAJKAIAIAdBDGoiCigCAEkhCyACQRBqJAAgCiAJIAsbKAIAIgJBC08EfyACQRBqQXBxIgIgAkEBayICIAJBC0YbBUEKC0EBagVB7////wcLEDAgBygCBCECIAcoAggaIAQEQCACIAggBBAjCyAFBEAgAiAEaiAGIAUQIwsgAyAEayEGIAMgBEcEQCACIARqIAVqIAQgCGogBhAjCyABQQpHBEAgCBAZCyAAIAI2AgAgACAAKAIIQYCAgIB4cSAHKAIIQf////8HcXI2AgggACAAKAIIQYCAgIB4cjYCCCAAIAQgBWogBmoiADYCBCAHQQA6AAwgACACaiAHLQAMOgAAIAdBEGokAA8LECcACwoAIAAgASACEEMLuQEBBH8jAEEQayIEJAAgBCACNgIMIwBBoAFrIgMkACADIAAgA0GeAWogARsiBjYClAFBfyEFIAMgAUEBayIAQQAgACABTRs2ApgBIANBAEGQARAmIgBBfzYCTCAAQSA2AiQgAEF/NgJQIAAgAEG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ABRAAAAAAAAAAAYg0AC0F/IQlB/f///wcgCyASIAprIgZqIg1rIANIDQAgAEEgIAIgDSADQQJqIAcgDEEQaiIHayIFIAVBAmsgA0gbIAUgAxsiCWoiAyAEEB8gACAIIAsQHSAAQTAgAiADIARBgIAEcxAfIAAgByAFEB0gAEEwIAkgBWtBAEEAEB8gACAKIAYQHSAAQSAgAiADIARBgMAAcxAfIAMgAiACIANIGyEJCyAMQbAEaiQAIAkLvAIAAkACQAJAAkACQAJAAkACQAJAAkACQCABQQlrDhIACAkKCAkBAgMECgkKCggJBQYHCyACIAIoAgAiAUEEajYCACAAIAEoAgA2AgAPCyACIAIoAgAiAUEEajYCACAAIAEyAQA3AwAPCyACIAIoAgAiAUEEajYCACAAIAEzAQA3AwAPCyACIAIoAgAiAUEEajYCACAAIAEwAAA3AwAPCyACIAIoAgAiAUEEajYCACAAIAExAAA3AwAPCyACIAIoAgBBB2pBeHEiAUEIajYCACAAIAErAwA5AwAPCyAAIAIgAxEAAAsPCyACIAIoAgAiAUEEajYCACAAIAE0AgA3AwAPCyACIAIoAgAiAUEEajYCACAAIAE1AgA3AwAPCyACIAIoAgBBB2pBeHEiAUEIajYCACAAIAEpAwA3AwALcgEDfyAAKAIALAAAQTBrQQpPBEBBAA8LA0AgACgCACEDQX8hASACQcyZs+YATQRAQX8gAywAAEEwayIBIAJBCmwiAmogASACQf////8Hc0obIQELIAAgA0EBajYCACABIQIgAywAAUEwa0EKSQ0ACyACC9AUAhh/AX4jAEHQAGsiByQAIAcgATYCTCAEQcABayEXIANBgANrIRggB0E3aiEZIAdBOGohEwJAAkACQANAQQAhBgNAIAEhDCAGIBJB/////wdzSg0CIAYgEmohEgJAAkACQCABIgYtAAAiCARAA0ACQAJAIAhB/wFxIgFFBEAgBiEBDAELIAFBJUcNASAGIQgDQCAILQABQSVHBEAgCCEBDAILIAZBAWohBiAILQACIRsgCEECaiIBIQggG0ElRg0ACwsgBiAMayIGIBJB/////wdzIhpKDQggAARAIAAgDCAGE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ECYaIARBATYCOCAEQX82AhQgBCABNgIQIAQgADYCCCAAIARBCGogAigCAEEBIAAoAgAoAhwRBgACQCAEKAIgIgBBAUcNACACKAIARQ0AIAIgBCgCGDYCAAsgAEEBRiEFDAELQQAhBQsgBEFAayQAIAULMQAgACABKAIIQQAQHgRAIAEgAiADED0PCyAAKAIIIgAgASACIAMgACgCACgCHBEGAAsYACAAIAEoAghBABAeBEAgASACIAMQPQsLnQEBAn8jAEFAaiIDJAACf0EBIAAgAUEAEB4NABpBACABRQ0AGkEAIAFBjM0AECAiAUUNABogA0EMakEAQTQQJhogA0EBNgI4IANBfzYCFCADIAA2AhAgAyABNgIIIAEgA0EIaiACKAIAQQEgASgCACgCHBEGACADKAIgIgBBAUYEQCACIAMoAhg2AgALIABBAUYLIQQgA0FAayQAIAQLCgAgACABQQAQHgtOAgF/AXwjAEEQayICJAAgAkEANgIMIAEoAgRB1M8AIAJBDGoQCSEDIAIoAgwiAQRAIAEQAQsgACADRAAAAAAAAAAAYjoAOCACQRBqJAALNwEBfyMAQRBrIgIkACACIAEtADg2AgggAEHUzwAgAkEIahAHNgIEIABB1NUANgIAIAJBEGokAAuoAQEFfyAAKAJUIgMoAgAhBSADKAIEIgQgACgCFCAAKAIcIgdrIgYgBCAGSRsiBgRAIAUgByAGECIaIAMgAygCACAGaiIFNgIAIAMgAygCBCAGayIENgIECyAEIAIgAiAESxsiBARAIAUgASAEECIaIAMgAygCACAEaiIFNgIAIAMgAygCBCAEazYCBAsgBUEAOgAAIAAgACgCLCIBNgIcIAAgATYCFCACC5wBAQJ/IwBBEGsiAiQAQcgAEBwhASAAKAIEIgAQAiACIAA2AgggAUHMLSACQQhqEAc2AgQgAUHU1QA2AgAgAUEBNgIcIAFB1NUANgIYIAFBATYCFCABQdTVADYCECABQQE2AgwgAUHU1QA2AgggAUEAOgAgIAFBADYCRCABQoCAgIAwNwI8IAFBADsANyABQQA7ACsgAkEQaiQAIAELigUCBn4CfyABIAEoAgBBB2pBeHEiAUEQajYCACAAIQkgASkDACEDIAEpAwghBSMAQSBrIgAkAAJAIAVC////////////AIMiBEKAgICAgIDAgDx9IARCgICAgICAwP/DAH1UBEAgBUIEhiADQjyIhCEEIANC//////////8PgyIDQoGAgICAgICACFoEQCAEQoGAgICAgICAwAB8IQIMAgsgBEKAgICAgICAgEB9IQIgA0KAgICAgICAgAhSDQEgAiAEQgGDfCECDAELIANQIARCgICAgICAwP//AFQgBEKAgICAgIDA//8AURtFBEAgBUIEhiADQjyIhEL/////////A4NCgICAgICAgPz/AIQhAgwBC0KAgICAgICA+P8AIQIgBEL///////+//8MAVg0AQgAhAiAEQjCIpyIBQZH3AEkNACADIQIgBUL///////8/g0KAgICAgIDAAIQiBCEGAkAgAUGB9wBrIghBwABxBEAgAyAIQUBqrYYhBkIAIQIMAQsgCEUNACAGIAitIgeGIAJBwAAgCGutiIQhBiACIAeGIQILIAAgAjcDECAAIAY3AxgCQEGB+AAgAWsiAUHAAHEEQCAEIAFBQGqtiCEDQgAhBAwBCyABRQ0AIARBwAAgAWuthiADIAGtIgKIhCEDIAQgAoghBAsgACADNwMAIAAgBDcDCCAAKQMIQgSGIAApAwAiA0I8iIQhAiAAKQMQIAApAxiEQgBSrSADQv//////////D4OEIgNCgYCAgICAgIAIWgRAIAJCAXwhAgwBCyADQoCAgICAgICACFINACACQgGDIAJ8IQILIABBIGokACAJIAIgBUKAgICAgICAgIB/g4S/OQMAC0ABAn8jAEEQayICJAAgAiABNgIMIAJB1NUANgIIIAJBCGogABEBACEDIAIoAgwiAQRAIAEQAwsgAkEQaiQAIAMLBABCAAsEAEEAC/YCAQh/IwBBIGsiAyQAIAMgACgCHCIENgIQIAAoAhQhBSADIAI2AhwgAyABNgIYIAMgBSAEayIBNgIUIAEgAmohBUECIQcCfwJAAkACQCAAKAI8IANBEGoiAUECIANBDGoQDSIEBH9B6N4AIAQ2AgBBfwVBAAsEQCABIQQMAQsDQCAFIAMoAgwiBkYNAiAGQQBIBEAgASEEDAQLIAEgBiABK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QezTAAsOHAAAAB0AAABoKwAAAAQAQYTUAAsBAQBBlNQACwX/////CgBB2NQACwNgMQE=")||(Dt=$e,$e=g.locateFile?g.locateFile(Dt,Q):Q+Dt);var Ki=P=>{for(;P.length>0;)P.shift()(g)};g.noExitRuntime;function Ur(P){this.excPtr=P,this.ptr=P-24,this.set_type=function(F){QA[this.ptr+4>>2]=F},this.get_type=function(){return QA[this.ptr+4>>2]},this.set_destructor=function(F){QA[this.ptr+8>>2]=F},this.get_destructor=function(){return QA[this.ptr+8>>2]},this.set_caught=function(F){F=F?1:0,AA[this.ptr+12|0]=F},this.get_caught=function(){return AA[this.ptr+12|0]!=0},this.set_rethrown=function(F){F=F?1:0,AA[this.ptr+13|0]=F},this.get_rethrown=function(){return AA[this.ptr+13|0]!=0},this.init=function(F,EA){this.set_adjusted_ptr(0),this.set_type(F),this.set_destructor(EA)},this.set_adjusted_ptr=function(F){QA[this.ptr+16>>2]=F},this.get_adjusted_ptr=function(){return QA[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Cs(this.get_type()))return QA[this.excPtr>>2];var F=this.get_adjusted_ptr();return F!==0?F:this.excPtr}}var Er,no,Kn,Xi=P=>{for(var F="",EA=P;z[EA];)F+=Er[z[EA++]];return F},yr={},lr={},Ni={},wt=P=>{throw new no(P)},Ji=P=>{throw new Kn(P)},Di=(P,F,EA)=>{function RA(ge){var we=EA(ge);we.length!==P.length&&Ji("Mismatched type converter count");for(var _e=0;_e{lr.hasOwnProperty(ge)?GA[we]=lr[ge]:(WA.push(ge),yr.hasOwnProperty(ge)||(yr[ge]=[]),yr[ge].push(()=>{GA[we]=lr[ge],++Ce===WA.length&&RA(GA)}))}),WA.length===0&&RA(GA)};function ar(P,F,EA={}){if(!("argPackAdvance"in F))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(RA,GA,WA={}){var Ce=GA.name;if(RA||wt(`type "${Ce}" must have a positive integer typeid pointer`),lr.hasOwnProperty(RA)){if(WA.ignoreDuplicateRegistrations)return;wt(`Cannot register type '${Ce}' twice`)}if(lr[RA]=GA,delete Ni[RA],yr.hasOwnProperty(RA)){var ge=yr[RA];delete yr[RA],ge.forEach(we=>we())}}(P,F,EA)}var MA,YA=P=>{wt(P.$$.ptrType.registeredClass.name+" instance already deleted")},pe=!1,st=P=>{},Te=P=>{P.count.value-=1,P.count.value===0&&(F=>{F.smartPtr?F.smartPtrType.rawDestructor(F.smartPtr):F.ptrType.registeredClass.rawDestructor(F.ptr)})(P)},be=(P,F,EA)=>{if(F===EA)return P;if(EA.baseClass===void 0)return null;var RA=be(P,F,EA.baseClass);return RA===null?null:EA.downcast(RA)},yt={},ht=()=>Object.keys(zt).length,ae=()=>{var P=[];for(var F in zt)zt.hasOwnProperty(F)&&P.push(zt[F]);return P},ye=[],Xe=()=>{for(;ye.length;){var P=ye.pop();P.$$.deleteScheduled=!1,P.delete()}},ot=P=>{MA=P,ye.length&&MA&&MA(Xe)},zt={},yi=(P,F)=>(F=((EA,RA)=>{for(RA===void 0&&wt("ptr should not be undefined");EA.baseClass;)RA=EA.upcast(RA),EA=EA.baseClass;return RA})(P,F),zt[F]),Hi=(P,F)=>(F.ptrType&&F.ptr||Ji("makeClassHandle requires ptr and ptrType"),!!F.smartPtrType!=!!F.smartPtr&&Ji("Both smartPtrType and smartPtr must be specified"),F.count={value:1},ji(Object.create(P,{$$:{value:F}})));function Ei(P){var F=this.getPointee(P);if(!F)return this.destructor(P),null;var EA=yi(this.registeredClass,F);if(EA!==void 0){if(EA.$$.count.value===0)return EA.$$.ptr=F,EA.$$.smartPtr=P,EA.clone();var RA=EA.clone();return this.destructor(P),RA}function GA(){return this.isSmartPointer?Hi(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:F,smartPtrType:this,smartPtr:P}):Hi(this.registeredClass.instancePrototype,{ptrType:this,ptr:P})}var WA,Ce=this.registeredClass.getActualType(F),ge=yt[Ce];if(!ge)return GA.call(this);WA=this.isConst?ge.constPointerType:ge.pointerType;var we=be(F,this.registeredClass,WA.registeredClass);return we===null?GA.call(this):this.isSmartPointer?Hi(WA.registeredClass.instancePrototype,{ptrType:WA,ptr:we,smartPtrType:this,smartPtr:P}):Hi(WA.registeredClass.instancePrototype,{ptrType:WA,ptr:we})}var ji=P=>typeof FinalizationRegistry>"u"?(ji=F=>F,P):(pe=new FinalizationRegistry(F=>{Te(F.$$)}),st=F=>pe.unregister(F),(ji=F=>{var EA=F.$$;if(EA.smartPtr){var RA={$$:EA};pe.register(F,RA,F)}return F})(P));function Xo(){}var sr=(P,F)=>Object.defineProperty(F,"name",{value:P}),Lo=(P,F,EA)=>{if(P[F].overloadTable===void 0){var RA=P[F];P[F]=function(){return P[F].overloadTable.hasOwnProperty(arguments.length)||wt(`Function '${EA}' called with an invalid number of arguments (${arguments.length}) - expects one of (${P[F].overloadTable})!`),P[F].overloadTable[arguments.length].apply(this,arguments)},P[F].overloadTable=[],P[F].overloadTable[RA.argCount]=RA}};function Nr(P,F,EA,RA,GA,WA,Ce,ge){this.name=P,this.constructor=F,this.instancePrototype=EA,this.rawDestructor=RA,this.baseClass=GA,this.getActualType=WA,this.upcast=Ce,this.downcast=ge,this.pureVirtualFunctions=[]}var Vo=(P,F,EA)=>{for(;F!==EA;)F.upcast||wt(`Expected null or instance of ${EA.name}, got an instance of ${F.name}`),P=F.upcast(P),F=F.baseClass;return P};function et(P,F){if(F===null)return this.isReference&&wt(`null is not a valid ${this.name}`),0;F.$$||wt(`Cannot pass "${ao(F)}" as a ${this.name}`),F.$$.ptr||wt(`Cannot pass deleted object as a pointer of type ${this.name}`);var EA=F.$$.ptrType.registeredClass;return Vo(F.$$.ptr,EA,this.registeredClass)}function Kr(P,F){var EA;if(F===null)return this.isReference&&wt(`null is not a valid ${this.name}`),this.isSmartPointer?(EA=this.rawConstructor(),P!==null&&P.push(this.rawDestructor,EA),EA):0;F.$$||wt(`Cannot pass "${ao(F)}" as a ${this.name}`),F.$$.ptr||wt(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&F.$$.ptrType.isConst&&wt(`Cannot convert argument of type ${F.$$.smartPtrType?F.$$.smartPtrType.name:F.$$.ptrType.name} to parameter type ${this.name}`);var RA=F.$$.ptrType.registeredClass;if(EA=Vo(F.$$.ptr,RA,this.registeredClass),this.isSmartPointer)switch(F.$$.smartPtr===void 0&&wt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:F.$$.smartPtrType===this?EA=F.$$.smartPtr:wt(`Cannot convert argument of type ${F.$$.smartPtrType?F.$$.smartPtrType.name:F.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:EA=F.$$.smartPtr;break;case 2:if(F.$$.smartPtrType===this)EA=F.$$.smartPtr;else{var GA=F.clone();EA=this.rawShare(EA,gr.toHandle(()=>GA.delete())),P!==null&&P.push(this.rawDestructor,EA)}break;default:wt("Unsupporting sharing policy")}return EA}function Qn(P,F){if(F===null)return this.isReference&&wt(`null is not a valid ${this.name}`),0;F.$$||wt(`Cannot pass "${ao(F)}" as a ${this.name}`),F.$$.ptr||wt(`Cannot pass deleted object as a pointer of type ${this.name}`),F.$$.ptrType.isConst&&wt(`Cannot convert argument of type ${F.$$.ptrType.name} to parameter type ${this.name}`);var EA=F.$$.ptrType.registeredClass;return Vo(F.$$.ptr,EA,this.registeredClass)}function ho(P){return this.fromWireType(QA[P>>2])}function jn(P,F,EA,RA,GA,WA,Ce,ge,we,_e,Ke){this.name=P,this.registeredClass=F,this.isReference=EA,this.isConst=RA,this.isSmartPointer=GA,this.pointeeType=WA,this.sharingPolicy=Ce,this.rawGetPointee=ge,this.rawConstructor=we,this.rawShare=_e,this.rawDestructor=Ke,GA||F.baseClass!==void 0?this.toWireType=Kr:RA?(this.toWireType=et,this.destructorFunction=null):(this.toWireType=Qn,this.destructorFunction=null)}var $t,$r,On=[],An=P=>{var F=On[P];return F||(P>=On.length&&(On.length=P+1),On[P]=F=$t.get(P)),F},Tr=(P,F,EA)=>P.includes("j")?((RA,GA,WA)=>{var Ce=g["dynCall_"+RA];return WA&&WA.length?Ce.apply(null,[GA].concat(WA)):Ce.call(null,GA)})(P,F,EA):An(F).apply(null,EA),ei=(P,F)=>{var EA,RA,GA,WA=(P=Xi(P)).includes("j")?(EA=P,RA=F,GA=[],function(){return GA.length=0,Object.assign(GA,arguments),Tr(EA,RA,GA)}):An(F);return typeof WA!="function"&&wt(`unknown function pointer with signature ${P}: ${F}`),WA},Es=P=>{var F=Ba(P),EA=Xi(F);return Mr(F),EA},jr=(P,F)=>{var EA=[],RA={};throw F.forEach(function GA(WA){RA[WA]||lr[WA]||(Ni[WA]?Ni[WA].forEach(GA):(EA.push(WA),RA[WA]=!0))}),new $r(`${P}: `+EA.map(Es).join([", "]))},Gr=(P,F)=>{for(var EA=[],RA=0;RA>2]);return EA},$o=P=>{for(;P.length;){var F=P.pop();P.pop()(F)}};function sn(P,F,EA,RA,GA,WA){var Ce=F.length;Ce<2&&wt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var ge=F[1]!==null&&EA!==null,we=!1,_e=1;_e(P instanceof Object||wt(`${EA} with invalid "this": ${P}`),P instanceof F.registeredClass.constructor||wt(`${EA} incompatible with "this" of type ${P.constructor.name}`),P.$$.ptr||wt(`cannot call emscripten binding method ${EA} on deleted object`),Vo(P.$$.ptr,P.$$.ptrType.registeredClass,F.registeredClass));function hn(){this.allocated=[void 0],this.freelist=[]}var Gi=new hn,pn=P=>{P>=Gi.reserved&&--Gi.get(P).refcount===0&&Gi.free(P)},nI=()=>{for(var P=0,F=Gi.reserved;F(P||wt("Cannot use deleted val. handle = "+P),Gi.get(P).value),toHandle:P=>{switch(P){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return Gi.allocate({refcount:1,value:P})}}};function gn(P){return this.fromWireType(X[P>>2])}var Yo,Tg,So,ao=P=>{if(P===null)return"null";var F=typeof P;return F==="object"||F==="array"||F==="function"?P.toString():""+P},lE=(P,F)=>{switch(F){case 4:return function(EA){return this.fromWireType(wA[EA>>2])};case 8:return function(EA){return this.fromWireType(HA[EA>>3])};default:throw new TypeError(`invalid float width (${F}): ${P}`)}},Ta=(P,F,EA)=>{switch(F){case 1:return EA?RA=>AA[RA|0]:RA=>z[RA|0];case 2:return EA?RA=>sA[RA>>1]:RA=>eA[RA>>1];case 4:return EA?RA=>X[RA>>2]:RA=>QA[RA>>2];default:throw new TypeError(`invalid integer width (${F}): ${P}`)}},po=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ja=(P,F,EA)=>{for(var RA=F+EA,GA=F;P[GA]&&!(GA>=RA);)++GA;if(GA-F>16&&P.buffer&&po)return po.decode(P.subarray(F,GA));for(var WA="";F>10,56320|1023&_e)}}else WA+=String.fromCharCode((31&Ce)<<6|ge)}else WA+=String.fromCharCode(Ce)}return WA},Mc=(P,F)=>P?Ja(z,P,F):"",Qr=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Fo=(P,F)=>{for(var EA=P,RA=EA>>1,GA=RA+F/2;!(RA>=GA)&&eA[RA];)++RA;if((EA=RA<<1)-P>32&&Qr)return Qr.decode(z.subarray(P,EA));for(var WA="",Ce=0;!(Ce>=F/2);++Ce){var ge=sA[P+2*Ce>>1];if(ge==0)break;WA+=String.fromCharCode(ge)}return WA},$s=(P,F,EA)=>{if(EA===void 0&&(EA=2147483647),EA<2)return 0;for(var RA=F,GA=(EA-=2)<2*P.length?EA/2:P.length,WA=0;WA>1]=Ce,F+=2}return sA[F>>1]=0,F-RA},Ha=P=>2*P.length,Gs=(P,F)=>{for(var EA=0,RA="";!(EA>=F/4);){var GA=X[P+4*EA>>2];if(GA==0)break;if(++EA,GA>=65536){var WA=GA-65536;RA+=String.fromCharCode(55296|WA>>10,56320|1023&WA)}else RA+=String.fromCharCode(GA)}return RA},Ga=(P,F,EA)=>{if(EA===void 0&&(EA=2147483647),EA<4)return 0;for(var RA=F,GA=RA+EA-4,WA=0;WA=55296&&Ce<=57343&&(Ce=65536+((1023&Ce)<<10)|1023&P.charCodeAt(++WA)),X[F>>2]=Ce,(F+=4)+4>GA)break}return X[F>>2]=0,F-RA},Rr=P=>{for(var F=0,EA=0;EA=55296&&RA<=57343&&++EA,F+=4}return F},Ia=(P,F)=>{var EA=lr[P];return EA===void 0&&wt(F+" has unknown type "+Es(P)),EA},fo=(P,F,EA)=>{var RA=[],GA=P.toWireType(RA,EA);return RA.length&&(QA[F>>2]=gr.toHandle(RA)),GA},aI={},en=[],qo=Reflect.construct,Gg=[null,[],[]],kg=(P,F)=>{var EA=Gg[P];F===0||F===10?((P===1?M:v)(Ja(EA,0)),EA.length=0):EA.push(F)};(()=>{for(var P=new Array(256),F=0;F<256;++F)P[F]=String.fromCharCode(F);Er=P})(),no=g.BindingError=class extends Error{constructor(P){super(P),this.name="BindingError"}},Kn=g.InternalError=class extends Error{constructor(P){super(P),this.name="InternalError"}},Object.assign(Xo.prototype,{isAliasOf(P){if(!(this instanceof Xo)||!(P instanceof Xo))return!1;var F=this.$$.ptrType.registeredClass,EA=this.$$.ptr;P.$$=P.$$;for(var RA=P.$$.ptrType.registeredClass,GA=P.$$.ptr;F.baseClass;)EA=F.upcast(EA),F=F.baseClass;for(;RA.baseClass;)GA=RA.upcast(GA),RA=RA.baseClass;return F===RA&&EA===GA},clone(){if(this.$$.ptr||YA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var P,F=ji(Object.create(Object.getPrototypeOf(this),{$$:{value:(P=this.$$,{count:P.count,deleteScheduled:P.deleteScheduled,preservePointerOnDelete:P.preservePointerOnDelete,ptr:P.ptr,ptrType:P.ptrType,smartPtr:P.smartPtr,smartPtrType:P.smartPtrType})}}));return F.$$.count.value+=1,F.$$.deleteScheduled=!1,F},delete(){this.$$.ptr||YA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&wt("Object already scheduled for deletion"),st(this),Te(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||YA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&wt("Object already scheduled for deletion"),ye.push(this),ye.length===1&&MA&&MA(Xe),this.$$.deleteScheduled=!0,this}}),g.getInheritedInstanceCount=ht,g.getLiveInheritedInstances=ae,g.flushPendingDeletes=Xe,g.setDelayFunction=ot,Object.assign(jn.prototype,{getPointee(P){return this.rawGetPointee&&(P=this.rawGetPointee(P)),P},destructor(P){this.rawDestructor&&this.rawDestructor(P)},argPackAdvance:8,readValueFromPointer:ho,deleteObject(P){P!==null&&P.delete()},fromWireType:Ei}),$r=g.UnboundTypeError=(Yo=Error,(So=sr(Tg="UnboundTypeError",function(P){this.name=Tg,this.message=P;var F=new Error(P).stack;F!==void 0&&(this.stack=this.toString()+` +`+F.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(Yo.prototype),So.prototype.constructor=So,So.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},So),Object.assign(hn.prototype,{get(P){return this.allocated[P]},has(P){return this.allocated[P]!==void 0},allocate(P){var F=this.freelist.pop()||this.allocated.length;return this.allocated[F]=P,F},free(P){this.allocated[P]=void 0,this.freelist.push(P)}}),Gi.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Gi.reserved=Gi.allocated.length,g.count_emval_handles=nI;var fn,ls={w:(P,F,EA)=>{throw new Ur(P).init(F,EA),P},q:(P,F,EA,RA,GA)=>{},u:(P,F,EA,RA)=>{ar(P,{name:F=Xi(F),fromWireType:function(GA){return!!GA},toWireType:function(GA,WA){return WA?EA:RA},argPackAdvance:8,readValueFromPointer:function(GA){return this.fromWireType(z[GA])},destructorFunction:null})},y:(P,F,EA,RA,GA,WA,Ce,ge,we,_e,Ke,Bt,Rt)=>{Ke=Xi(Ke),WA=ei(GA,WA),ge&&(ge=ei(Ce,ge)),_e&&(_e=ei(we,_e)),Rt=ei(Bt,Rt);var Ye=(nt=>{if(nt===void 0)return"_unknown";var ii=(nt=nt.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return ii>=48&&ii<=57?`_${nt}`:nt})(Ke);((nt,ii,oi)=>{g.hasOwnProperty(nt)?(wt(`Cannot register public name '${nt}' twice`),Lo(g,nt,nt),g.hasOwnProperty(oi)&&wt(`Cannot register multiple overloads of a function with the same number of arguments (${oi})!`),g[nt].overloadTable[oi]=ii):g[nt]=ii})(Ye,function(){jr(`Cannot construct ${Ke} due to unbound types`,[RA])}),Di([P,F,EA],RA?[RA]:[],function(nt){var ii,oi;nt=nt[0],oi=RA?(ii=nt.registeredClass).instancePrototype:Xo.prototype;var Ko=sr(Ke,function(){if(Object.getPrototypeOf(this)!==Kt)throw new no("Use 'new' to construct "+Ke);if(ro.constructor_body===void 0)throw new no(Ke+" has no accessible constructor");var xr=ro.constructor_body[arguments.length];if(xr===void 0)throw new no(`Tried to invoke ctor of ${Ke} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(ro.constructor_body).toString()}) parameters instead!`);return xr.apply(this,arguments)}),Kt=Object.create(oi,{constructor:{value:Ko}});Ko.prototype=Kt;var ro=new Nr(Ke,Ko,Kt,Rt,ii,WA,ge,_e);ro.baseClass&&(ro.baseClass.__derivedClasses===void 0&&(ro.baseClass.__derivedClasses=[]),ro.baseClass.__derivedClasses.push(ro));var ks=new jn(Ke,ro,!0,!1,!1),Zr=new jn(Ke+"*",ro,!1,!1,!1),In=new jn(Ke+" const*",ro,!1,!0,!1);return yt[P]={pointerType:Zr,constPointerType:In},((xr,sI,jo)=>{g.hasOwnProperty(xr)||Ji("Replacing nonexistant public symbol"),g[xr].overloadTable!==void 0&&jo!==void 0?g[xr].overloadTable[jo]=sI:(g[xr]=sI,g[xr].argCount=jo)})(Ye,Ko),[ks,Zr,In]})},x:(P,F,EA,RA,GA,WA)=>{var Ce=Gr(F,EA);GA=ei(RA,GA),Di([],[P],function(ge){var we=`constructor ${(ge=ge[0]).name}`;if(ge.registeredClass.constructor_body===void 0&&(ge.registeredClass.constructor_body=[]),ge.registeredClass.constructor_body[F-1]!==void 0)throw new no(`Cannot register multiple constructors with identical number of parameters (${F-1}) for class '${ge.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return ge.registeredClass.constructor_body[F-1]=()=>{jr(`Cannot construct ${ge.name} due to unbound types`,Ce)},Di([],Ce,_e=>(_e.splice(1,0,null),ge.registeredClass.constructor_body[F-1]=sn(we,_e,null,GA,WA),[])),[]})},i:(P,F,EA,RA,GA,WA,Ce,ge,we)=>{var _e=Gr(EA,RA);F=(Ke=>{const Bt=(Ke=Ke.trim()).indexOf("(");return Bt!==-1?Ke.substr(0,Bt):Ke})(F=Xi(F)),WA=ei(GA,WA),Di([],[P],function(Ke){var Bt=`${(Ke=Ke[0]).name}.${F}`;function Rt(){jr(`Cannot call ${Bt} due to unbound types`,_e)}F.startsWith("@@")&&(F=Symbol[F.substring(2)]),ge&&Ke.registeredClass.pureVirtualFunctions.push(F);var Ye=Ke.registeredClass.instancePrototype,nt=Ye[F];return nt===void 0||nt.overloadTable===void 0&&nt.className!==Ke.name&&nt.argCount===EA-2?(Rt.argCount=EA-2,Rt.className=Ke.name,Ye[F]=Rt):(Lo(Ye,F,Bt),Ye[F].overloadTable[EA-2]=Rt),Di([],_e,function(ii){var oi=sn(Bt,ii,Ke,WA,Ce);return Ye[F].overloadTable===void 0?(oi.argCount=EA-2,Ye[F]=oi):Ye[F].overloadTable[EA-2]=oi,[]}),[]})},k:(P,F,EA,RA,GA,WA,Ce,ge,we,_e)=>{F=Xi(F),GA=ei(RA,GA),Di([],[P],function(Ke){var Bt=`${(Ke=Ke[0]).name}.${F}`,Rt={get(){jr(`Cannot access ${Bt} due to unbound types`,[EA,Ce])},enumerable:!0,configurable:!0};return Rt.set=we?()=>jr(`Cannot access ${Bt} due to unbound types`,[EA,Ce]):Ye=>wt(Bt+" is a read-only property"),Object.defineProperty(Ke.registeredClass.instancePrototype,F,Rt),Di([],we?[EA,Ce]:[EA],function(Ye){var nt=Ye[0],ii={get(){var Ko=dn(this,Ke,Bt+" getter");return nt.fromWireType(GA(WA,Ko))},enumerable:!0};if(we){we=ei(ge,we);var oi=Ye[1];ii.set=function(Ko){var Kt=dn(this,Ke,Bt+" setter"),ro=[];we(_e,Kt,oi.toWireType(ro,Ko)),$o(ro)}}return Object.defineProperty(Ke.registeredClass.instancePrototype,F,ii),[]}),[]})},t:(P,F)=>{ar(P,{name:F=Xi(F),fromWireType:EA=>{var RA=gr.toValue(EA);return pn(EA),RA},toWireType:(EA,RA)=>gr.toHandle(RA),argPackAdvance:8,readValueFromPointer:gn,destructorFunction:null})},p:(P,F,EA)=>{ar(P,{name:F=Xi(F),fromWireType:RA=>RA,toWireType:(RA,GA)=>GA,argPackAdvance:8,readValueFromPointer:lE(F,EA),destructorFunction:null})},g:(P,F,EA,RA,GA)=>{F=Xi(F);var WA=we=>we;if(RA===0){var Ce=32-8*EA;WA=we=>we<>>Ce}var ge=F.includes("unsigned");ar(P,{name:F,fromWireType:WA,toWireType:ge?function(we,_e){return this.name,_e>>>0}:function(we,_e){return this.name,_e},argPackAdvance:8,readValueFromPointer:Ta(F,EA,RA!==0),destructorFunction:null})},a:(P,F,EA)=>{var RA=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][F];function GA(WA){var Ce=QA[WA>>2],ge=QA[WA+4>>2];return new RA(AA.buffer,ge,Ce)}ar(P,{name:EA=Xi(EA),fromWireType:GA,argPackAdvance:8,readValueFromPointer:GA},{ignoreDuplicateRegistrations:!0})},o:(P,F)=>{var EA=(F=Xi(F))==="std::string";ar(P,{name:F,fromWireType(RA){var GA,WA=QA[RA>>2],Ce=RA+4;if(EA)for(var ge=Ce,we=0;we<=WA;++we){var _e=Ce+we;if(we==WA||z[_e]==0){var Ke=Mc(ge,_e-ge);GA===void 0?GA=Ke:(GA+="\0",GA+=Ke),ge=_e+1}}else{var Bt=new Array(WA);for(we=0;we{for(var Rt=0,Ye=0;Ye=55296&&nt<=57343?(Rt+=4,++Ye):Rt+=3}return Rt})(GA):GA.length;var ge=Po(4+WA+1),we=ge+4;if(QA[ge>>2]=WA,EA&&Ce)((Bt,Rt,Ye,nt)=>{if(!(nt>0))return 0;for(var ii=Ye,oi=Ye+nt-1,Ko=0;Ko=55296&&Kt<=57343&&(Kt=65536+((1023&Kt)<<10)|1023&Bt.charCodeAt(++Ko)),Kt<=127){if(Ye>=oi)break;Rt[Ye++]=Kt}else if(Kt<=2047){if(Ye+1>=oi)break;Rt[Ye++]=192|Kt>>6,Rt[Ye++]=128|63&Kt}else if(Kt<=65535){if(Ye+2>=oi)break;Rt[Ye++]=224|Kt>>12,Rt[Ye++]=128|Kt>>6&63,Rt[Ye++]=128|63&Kt}else{if(Ye+3>=oi)break;Rt[Ye++]=240|Kt>>18,Rt[Ye++]=128|Kt>>12&63,Rt[Ye++]=128|Kt>>6&63,Rt[Ye++]=128|63&Kt}}Rt[Ye]=0})(GA,z,we,WA+1);else if(Ce)for(var _e=0;_e255&&(Mr(we),wt("String has UTF-16 code units that do not fit in 8 bits")),z[we+_e]=Ke}else for(_e=0;_e{var RA,GA,WA,Ce,ge;EA=Xi(EA),F===2?(RA=Fo,GA=$s,Ce=Ha,WA=()=>eA,ge=1):F===4&&(RA=Gs,GA=Ga,Ce=Rr,WA=()=>QA,ge=2),ar(P,{name:EA,fromWireType:we=>{for(var _e,Ke=QA[we>>2],Bt=WA(),Rt=we+4,Ye=0;Ye<=Ke;++Ye){var nt=we+4+Ye*F;if(Ye==Ke||Bt[nt>>ge]==0){var ii=RA(Rt,nt-Rt);_e===void 0?_e=ii:(_e+="\0",_e+=ii),Rt=nt+F}}return Mr(we),_e},toWireType:(we,_e)=>{typeof _e!="string"&&wt(`Cannot pass non-string to C++ string type ${EA}`);var Ke=Ce(_e),Bt=Po(4+Ke+F);return QA[Bt>>2]=Ke>>ge,GA(_e,Bt+4,Ke+F),we!==null&&we.push(Mr,Bt),Bt},argPackAdvance:8,readValueFromPointer:gn,destructorFunction(we){Mr(we)}})},v:(P,F)=>{ar(P,{isVoid:!0,name:F=Xi(F),argPackAdvance:0,fromWireType:()=>{},toWireType:(EA,RA)=>{}})},j:(P,F,EA)=>(P=gr.toValue(P),F=Ia(F,"emval::as"),fo(F,EA,P)),e:(P,F,EA,RA,GA)=>{var WA,Ce;return(P=en[P])(F=gr.toValue(F),F[EA=(Ce=aI[WA=EA])===void 0?Xi(WA):Ce],RA,GA)},d:pn,f:(P,F,EA)=>{var RA=((_e,Ke)=>{for(var Bt=new Array(_e),Rt=0;Rt<_e;++Rt)Bt[Rt]=Ia(QA[Ke+4*Rt>>2],"parameter "+Rt);return Bt})(P,F),GA=RA.shift();P--;var WA,Ce,ge=new Array(P),we=`methodCaller<(${RA.map(_e=>_e.name).join(", ")}) => ${GA.name}>`;return WA=sr(we,(_e,Ke,Bt,Rt)=>{for(var Ye=0,nt=0;nt{P>4&&(Gi.get(P).refcount+=1)},b:P=>{var F=gr.toValue(P);$o(F),pn(P)},h:(P,F)=>{var EA=(P=Ia(P,"_emval_take_value")).readValueFromPointer(F);return gr.toHandle(EA)},m:()=>{Je("")},s:(P,F,EA)=>z.copyWithin(P,F,F+EA),r:P=>{z.length,Je("OOM")},n:(P,F,EA,RA)=>{for(var GA=0,WA=0;WA>2],ge=QA[F+4>>2];F+=8;for(var we=0;we>2]=GA,0}},Or=function(){var P={a:ls};function F(EA,RA){var GA,WA;return Or=EA.exports,m=Or.z,GA=m.buffer,g.HEAP8=AA=new Int8Array(GA),g.HEAP16=sA=new Int16Array(GA),g.HEAPU8=z=new Uint8Array(GA),g.HEAPU16=eA=new Uint16Array(GA),g.HEAP32=X=new Int32Array(GA),g.HEAPU32=QA=new Uint32Array(GA),g.HEAPF32=wA=new Float32Array(GA),g.HEAPF64=HA=new Float64Array(GA),$t=Or.C,WA=Or.A,jA.unshift(WA),function(){if(qe--,g.monitorRunDependencies&&g.monitorRunDependencies(qe),qe==0&&Et){var Ce=Et;Et=null,Ce()}}(),Or}if(qe++,g.monitorRunDependencies&&g.monitorRunDependencies(qe),g.instantiateWasm)try{return g.instantiateWasm(P,F)}catch(EA){v(`Module.instantiateWasm callback failed with error: ${EA}`),s(EA)}return ai(0,$e,P,function(EA){F(EA.instance)}).catch(s),{}}(),Po=P=>(Po=Or.B)(P),Ba=P=>(Ba=Or.D)(P),Mr=P=>(Mr=Or.E)(P),Cs=P=>(Cs=Or.F)(P);g.dynCall_jiji=(P,F,EA,RA,GA)=>(g.dynCall_jiji=Or.G)(P,F,EA,RA,GA),g._vertexShaderSource=10688;function Va(){function P(){fn||(fn=!0,g.calledRun=!0,qA||(Ki(jA),r(g),g.onRuntimeInitialized&&g.onRuntimeInitialized(),function(){if(g.postRun)for(typeof g.postRun=="function"&&(g.postRun=[g.postRun]);g.postRun.length;)Me(g.postRun.shift());Ki(Ve)}()))}qe>0||(function(){if(g.preRun)for(typeof g.preRun=="function"&&(g.preRun=[g.preRun]);g.preRun.length;)ze(g.preRun.shift());Ki(ue)}(),qe>0||(g.setStatus?(g.setStatus("Running..."),setTimeout(function(){setTimeout(function(){g.setStatus("")},1),P()},1)):P()))}if(Et=function P(){fn||Va(),fn||(Et=P)},g.preInit)for(typeof g.preInit=="function"&&(g.preInit=[g.preInit]);g.preInit.length>0;)g.preInit.pop()();return Va(),i.ready}})(),MnA=RnA,gd=typeof navigator>"u"?"":navigator.userAgent,_o=t=>new RegExp(t,"i").test(gd),Is=t=>{if(_o(t)){const i=new RegExp(`${t}\\/([\\d.]+)`),r=gd.match(i);if(r&&r[1])return r[1]}return""},wY=t=>{if(_o(t)){const i=new RegExp(`${t}\\/(\\d+)`),r=gd.match(i);if(r&&r[1])return parseFloat(r[1])}return NaN},R5=/AppleWebKit\/([\d.]+)/i.exec(gd);R5&&parseFloat(R5[1]);var d6=_o("iPad"),h6=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&_o("Macintosh"),p6=_o("iPhone")&&!d6,wnA=_o("iPod"),f6=p6||d6||wnA||h6,f3=_o("Android"),SnA=function(){if(f3){const t=gd.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(t){const i=t[1]&&parseFloat(t[1]),r=t[2]&&parseFloat(t[2]);if(i&&r)return parseFloat(`${t[1]}.${t[2]}`);if(i)return i}}return NaN}();f3&&_o("webkit")&&SnA<2.3;var vnA=_o("Firefox"),NnA=Is("Firefox");wY("Firefox");var m6=_o("Edge"),TnA=Is("Edge"),D6=_o("Edg"),GnA=Is("Edg");wY("Edg");var y6=_o("SogouMobileBrowser"),knA=Is("SogouMobileBrowser"),R6=_o("MetaSr\\s"),_nA=Is("MetaSr\\s"),mD=_o("TBS"),bnA=Is("TBS"),M6=_o("XWEB"),LnA=Is("XWEB");_o("MSIE\\s8\\.0");var FnA=_o("MSIE\\/\\d+");(function(){if(FnA){const t=/MSIE\s(\d+)\.\d/.exec(gd);let i=t&&parseFloat(t[1]);return!i&&/Trident\/7.0/i.test(gd)&&/rv:11.0/.test(gd)&&(i=11),i}return NaN})();var UnA=_o("(micromessenger|webbrowser)"),OnA=Is("MicroMessenger"),m3=!mD&&_o("MQQBrowser")&&_o("COVC"),D3=!mD&&_o("MQQBrowser")&&!_o("COVC"),M5=D3||m3?Is("MQQBrowser"):"",w6=!mD&&_o(" QQBrowser"),xnA=Is(" QQBrowser"),S6=!mD&&_o("QQBrowserLite"),YnA=Is("QQBrowserLite"),v6=!mD&&_o("MQBHD"),PnA=Is("MQBHD");_o("Windows");!f6&&_o("MAC OS X");!f3&&_o("Linux");_o("CrOS");_o("MicroMessenger");_o("UCBrowser");_o("Electron");var N6=_o("MiuiBrowser"),JnA=Is("MiuiBrowser"),T6=_o("HuaweiBrowser");_o("Huawei")||_o("HUAWEI");_o("Honor")||_o("HONOR");var HnA=Is("HuaweiBrowser"),G6=_o("SamsungBrowser"),VnA=Is("SamsungBrowser"),k6=_o("HeyTapBrowser"),qnA=Is("HeyTapBrowser"),_6=_o("VivoBrowser"),KnA=Is("VivoBrowser");_o("OpenHarmony");Is("OpenHarmony");var jnA=()=>wY("Chrome"),w5=_o("CriOS"),b6=_o("Chrome"),WnA=!m6&&!R6&&!y6&&!mD&&!M6&&!D6&&!w6&&!N6&&!T6&&!G6&&!k6&&!_6&&b6;_o("HeadlessChrome");var znA=jnA(),ZnA=Is("Chrome");wY("Electron");var XnA=!b6&&!D3&&!m3&&!S6&&!v6&&_o("Safari"),L6=Is("Version"),F6=(()=>{if(h6)return L6;if(f6){const t=gd.match(/OS (\d+)_(\d+)/i);if(t&&t[1]){let i=t[1];return t[2]&&(i+=`.${t[2]}`),i}}return""})();Number(F6.split(".")[0]);(()=>{const t=Number(F6.split(".")[0]);return t===14||t===13})();$nA();function $nA(){const t=new Map([[vnA,["Firefox",NnA]],[D6,["Edg",GnA]],[WnA,["Chrome",ZnA]],[w5,["ChiOS",Is("CriOS")]],[XnA&&!w5,["Safari",L6]],[mD,["TBS",bnA]],[M6,["XWEB",LnA]],[UnA&&p6,["WeChat",OnA]],[w6,["QQ(Win)",xnA]],[D3,["QQ(Mobile)",M5]],[m3,["QQ(Mobile X5)",M5]],[S6,["QQ(Mac)",YnA]],[v6,["QQ(iPad)",PnA]],[N6,["MI",JnA]],[T6,["HW",HnA]],[G6,["Samsung",VnA]],[k6,["OPPO",qnA]],[_6,["VIVO",KnA]],[m6,["EDGE",TnA]],[y6,["SogouMobile",knA]],[R6,["Sogou",_nA]]]);let i="unknown",r="unknown";return t.has(!0)&&([i,r]=t.get(!0)),{name:i,version:r}}var as=1e-6,ww=typeof Float32Array<"u"?Float32Array:Array,U6={};function AaA(){var t=new ww(16);return ww!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function eaA(t){var i=new ww(16);return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[3],i[4]=t[4],i[5]=t[5],i[6]=t[6],i[7]=t[7],i[8]=t[8],i[9]=t[9],i[10]=t[10],i[11]=t[11],i[12]=t[12],i[13]=t[13],i[14]=t[14],i[15]=t[15],i}function taA(t,i){return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],t}function iaA(t,i,r,s,g,B,Q,f,m,M,v,U,AA,z,sA,eA){var X=new ww(16);return X[0]=t,X[1]=i,X[2]=r,X[3]=s,X[4]=g,X[5]=B,X[6]=Q,X[7]=f,X[8]=m,X[9]=M,X[10]=v,X[11]=U,X[12]=AA,X[13]=z,X[14]=sA,X[15]=eA,X}function oaA(t,i,r,s,g,B,Q,f,m,M,v,U,AA,z,sA,eA,X){return t[0]=i,t[1]=r,t[2]=s,t[3]=g,t[4]=B,t[5]=Q,t[6]=f,t[7]=m,t[8]=M,t[9]=v,t[10]=U,t[11]=AA,t[12]=z,t[13]=sA,t[14]=eA,t[15]=X,t}function O6(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function raA(t,i){if(t===i){var r=i[1],s=i[2],g=i[3],B=i[6],Q=i[7],f=i[11];t[1]=i[4],t[2]=i[8],t[3]=i[12],t[4]=r,t[6]=i[9],t[7]=i[13],t[8]=s,t[9]=B,t[11]=i[14],t[12]=g,t[13]=Q,t[14]=f}else t[0]=i[0],t[1]=i[4],t[2]=i[8],t[3]=i[12],t[4]=i[1],t[5]=i[5],t[6]=i[9],t[7]=i[13],t[8]=i[2],t[9]=i[6],t[10]=i[10],t[11]=i[14],t[12]=i[3],t[13]=i[7],t[14]=i[11],t[15]=i[15];return t}function naA(t,i){var r=i[0],s=i[1],g=i[2],B=i[3],Q=i[4],f=i[5],m=i[6],M=i[7],v=i[8],U=i[9],AA=i[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A,HA=r[12],qA=r[13],ue=r[14],jA=r[15],t[12]=HA*s+qA*f+ue*U+jA*eA,t[13]=HA*g+qA*m+ue*AA+jA*X,t[14]=HA*B+qA*M+ue*z+jA*QA,t[15]=HA*Q+qA*v+ue*sA+jA*wA,t}function gaA(t,i,r){var s,g,B,Q,f,m,M,v,U,AA,z,sA,eA=r[0],X=r[1],QA=r[2];return i===t?(t[12]=i[0]*eA+i[4]*X+i[8]*QA+i[12],t[13]=i[1]*eA+i[5]*X+i[9]*QA+i[13],t[14]=i[2]*eA+i[6]*X+i[10]*QA+i[14],t[15]=i[3]*eA+i[7]*X+i[11]*QA+i[15]):(s=i[0],g=i[1],B=i[2],Q=i[3],f=i[4],m=i[5],M=i[6],v=i[7],U=i[8],AA=i[9],z=i[10],sA=i[11],t[0]=s,t[1]=g,t[2]=B,t[3]=Q,t[4]=f,t[5]=m,t[6]=M,t[7]=v,t[8]=U,t[9]=AA,t[10]=z,t[11]=sA,t[12]=s*eA+f*X+U*QA+i[12],t[13]=g*eA+m*X+AA*QA+i[13],t[14]=B*eA+M*X+z*QA+i[14],t[15]=Q*eA+v*X+sA*QA+i[15]),t}function IaA(t,i,r){var s=r[0],g=r[1],B=r[2];return t[0]=i[0]*s,t[1]=i[1]*s,t[2]=i[2]*s,t[3]=i[3]*s,t[4]=i[4]*g,t[5]=i[5]*g,t[6]=i[6]*g,t[7]=i[7]*g,t[8]=i[8]*B,t[9]=i[9]*B,t[10]=i[10]*B,t[11]=i[11]*B,t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],t}function caA(t,i,r,s){var g,B,Q,f,m,M,v,U,AA,z,sA,eA,X,QA,wA,HA,qA,ue,jA,Ve,ze,Me,qe,Et,Je=s[0],$e=s[1],Dt=s[2],Zi=Math.sqrt(Je*Je+$e*$e+Dt*Dt);return Zi0?(r[0]=2*(f*Q+v*s+m*B-M*g)/U,r[1]=2*(m*Q+v*g+M*s-f*B)/U,r[2]=2*(M*Q+v*B+f*g-m*s)/U):(r[0]=2*(f*Q+v*s+m*B-M*g),r[1]=2*(m*Q+v*g+M*s-f*B),r[2]=2*(M*Q+v*B+f*g-m*s)),Y6(t,i,r),t}function maA(t,i){return t[0]=i[12],t[1]=i[13],t[2]=i[14],t}function P6(t,i){var r=i[0],s=i[1],g=i[2],B=i[4],Q=i[5],f=i[6],m=i[8],M=i[9],v=i[10];return t[0]=Math.sqrt(r*r+s*s+g*g),t[1]=Math.sqrt(B*B+Q*Q+f*f),t[2]=Math.sqrt(m*m+M*M+v*v),t}function DaA(t,i){var r=new ww(3);P6(r,i);var s=1/r[0],g=1/r[1],B=1/r[2],Q=i[0]*s,f=i[1]*g,m=i[2]*B,M=i[4]*s,v=i[5]*g,U=i[6]*B,AA=i[8]*s,z=i[9]*g,sA=i[10]*B,eA=Q+v+sA,X=0;return eA>0?(X=2*Math.sqrt(eA+1),t[3]=.25*X,t[0]=(U-z)/X,t[1]=(AA-m)/X,t[2]=(f-M)/X):Q>v&&Q>sA?(X=2*Math.sqrt(1+Q-v-sA),t[3]=(U-z)/X,t[0]=.25*X,t[1]=(f+M)/X,t[2]=(AA+m)/X):v>sA?(X=2*Math.sqrt(1+v-Q-sA),t[3]=(AA-m)/X,t[0]=(f+M)/X,t[1]=.25*X,t[2]=(U+z)/X):(X=2*Math.sqrt(1+sA-Q-v),t[3]=(f-M)/X,t[0]=(AA+m)/X,t[1]=(U+z)/X,t[2]=.25*X),t}function yaA(t,i,r,s){i[0]=s[12],i[1]=s[13],i[2]=s[14];var g=s[0],B=s[1],Q=s[2],f=s[4],m=s[5],M=s[6],v=s[8],U=s[9],AA=s[10];r[0]=Math.sqrt(g*g+B*B+Q*Q),r[1]=Math.sqrt(f*f+m*m+M*M),r[2]=Math.sqrt(v*v+U*U+AA*AA);var z=1/r[0],sA=1/r[1],eA=1/r[2],X=g*z,QA=B*sA,wA=Q*eA,HA=f*z,qA=m*sA,ue=M*eA,jA=v*z,Ve=U*sA,ze=AA*eA,Me=X+qA+ze,qe=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,t[2]=$e,t[3]=0,t[4]=Dt,t[5]=Zi,t[6]=bi,t[7]=0,t[8]=qt,t[9]=ai,t[10]=Ki,t[11]=0,t[12]=r[0]+ze-(Et*ze+Dt*Me+qt*qe),t[13]=r[1]+Me-(Je*ze+Zi*Me+ai*qe),t[14]=r[2]+qe-($e*ze+bi*Me+Ki*qe),t[15]=1,t}function waA(t,i){var r=i[0],s=i[1],g=i[2],B=i[3],Q=r+r,f=s+s,m=g+g,M=r*Q,v=s*Q,U=s*f,AA=g*Q,z=g*f,sA=g*m,eA=B*Q,X=B*f,QA=B*m;return t[0]=1-U-sA,t[1]=v+QA,t[2]=AA-X,t[3]=0,t[4]=v-QA,t[5]=1-M-sA,t[6]=z+eA,t[7]=0,t[8]=AA+X,t[9]=z-eA,t[10]=1-M-U,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function SaA(t,i,r,s,g,B,Q){var f=1/(r-i),m=1/(g-s),M=1/(B-Q);return t[0]=2*B*f,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=2*B*m,t[6]=0,t[7]=0,t[8]=(r+i)*f,t[9]=(g+s)*m,t[10]=(Q+B)*M,t[11]=-1,t[12]=0,t[13]=0,t[14]=Q*B*2*M,t[15]=0,t}function J6(t,i,r,s,g){var B=1/Math.tan(i/2);if(t[0]=B/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=B,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,g!=null&&g!==1/0){var Q=1/(s-g);t[10]=(g+s)*Q,t[14]=2*g*s*Q}else t[10]=-1,t[14]=-2*s;return t}hnA(U6,{add:()=>UaA,adjoint:()=>aaA,clone:()=>eaA,copy:()=>taA,create:()=>AaA,decompose:()=>yaA,determinant:()=>saA,equals:()=>PaA,exactEquals:()=>YaA,frob:()=>FaA,fromQuat:()=>waA,fromQuat2:()=>faA,fromRotation:()=>QaA,fromRotationTranslation:()=>Y6,fromRotationTranslationScale:()=>RaA,fromRotationTranslationScaleOrigin:()=>MaA,fromScaling:()=>uaA,fromTranslation:()=>BaA,fromValues:()=>iaA,fromXRotation:()=>daA,fromYRotation:()=>haA,fromZRotation:()=>paA,frustum:()=>SaA,getRotation:()=>DaA,getScaling:()=>P6,getTranslation:()=>maA,identity:()=>O6,invert:()=>naA,lookAt:()=>_aA,mul:()=>JaA,multiply:()=>x6,multiplyScalar:()=>OaA,multiplyScalarAndAdd:()=>xaA,ortho:()=>GaA,orthoNO:()=>H6,orthoZO:()=>kaA,perspective:()=>vaA,perspectiveFromFieldOfView:()=>TaA,perspectiveNO:()=>J6,perspectiveZO:()=>NaA,rotate:()=>caA,rotateX:()=>EaA,rotateY:()=>laA,rotateZ:()=>CaA,scale:()=>IaA,set:()=>oaA,str:()=>LaA,sub:()=>HaA,subtract:()=>V6,targetTo:()=>baA,translate:()=>gaA,transpose:()=>raA});var vaA=J6;function NaA(t,i,r,s,g){var B=1/Math.tan(i/2);if(t[0]=B/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=B,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,g!=null&&g!==1/0){var Q=1/(s-g);t[10]=g*Q,t[14]=g*s*Q}else t[10]=-1,t[14]=-s;return t}function TaA(t,i,r,s){var g=Math.tan(i.upDegrees*Math.PI/180),B=Math.tan(i.downDegrees*Math.PI/180),Q=Math.tan(i.leftDegrees*Math.PI/180),f=Math.tan(i.rightDegrees*Math.PI/180),m=2/(Q+f),M=2/(g+B);return t[0]=m,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=M,t[6]=0,t[7]=0,t[8]=-(Q-f)*m*.5,t[9]=(g-B)*M*.5,t[10]=s/(r-s),t[11]=-1,t[12]=0,t[13]=0,t[14]=s*r/(r-s),t[15]=0,t}function H6(t,i,r,s,g,B,Q){var f=1/(i-r),m=1/(s-g),M=1/(B-Q);return t[0]=-2*f,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*m,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*M,t[11]=0,t[12]=(i+r)*f,t[13]=(g+s)*m,t[14]=(Q+B)*M,t[15]=1,t}var GaA=H6;function kaA(t,i,r,s,g,B,Q){var f=1/(i-r),m=1/(s-g),M=1/(B-Q);return t[0]=-2*f,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*m,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=M,t[11]=0,t[12]=(i+r)*f,t[13]=(g+s)*m,t[14]=B*M,t[15]=1,t}function _aA(t,i,r,s){var g,B,Q,f,m,M,v,U,AA,z,sA=i[0],eA=i[1],X=i[2],QA=s[0],wA=s[1],HA=s[2],qA=r[0],ue=r[1],jA=r[2];return Math.abs(sA-qA)0&&(v*=z=1/Math.sqrt(z),U*=z,AA*=z);var sA=m*AA-M*U,eA=M*v-f*AA,X=f*U-m*v;return(z=sA*sA+eA*eA+X*X)>0&&(sA*=z=1/Math.sqrt(z),eA*=z,X*=z),t[0]=sA,t[1]=eA,t[2]=X,t[3]=0,t[4]=U*X-AA*eA,t[5]=AA*sA-v*X,t[6]=v*eA-U*sA,t[7]=0,t[8]=v,t[9]=U,t[10]=AA,t[11]=0,t[12]=g,t[13]=B,t[14]=Q,t[15]=1,t}function LaA(t){return"mat4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+", "+t[9]+", "+t[10]+", "+t[11]+", "+t[12]+", "+t[13]+", "+t[14]+", "+t[15]+")"}function FaA(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]+t[4]*t[4]+t[5]*t[5]+t[6]*t[6]+t[7]*t[7]+t[8]*t[8]+t[9]*t[9]+t[10]*t[10]+t[11]*t[11]+t[12]*t[12]+t[13]*t[13]+t[14]*t[14]+t[15]*t[15])}function UaA(t,i,r){return t[0]=i[0]+r[0],t[1]=i[1]+r[1],t[2]=i[2]+r[2],t[3]=i[3]+r[3],t[4]=i[4]+r[4],t[5]=i[5]+r[5],t[6]=i[6]+r[6],t[7]=i[7]+r[7],t[8]=i[8]+r[8],t[9]=i[9]+r[9],t[10]=i[10]+r[10],t[11]=i[11]+r[11],t[12]=i[12]+r[12],t[13]=i[13]+r[13],t[14]=i[14]+r[14],t[15]=i[15]+r[15],t}function V6(t,i,r){return t[0]=i[0]-r[0],t[1]=i[1]-r[1],t[2]=i[2]-r[2],t[3]=i[3]-r[3],t[4]=i[4]-r[4],t[5]=i[5]-r[5],t[6]=i[6]-r[6],t[7]=i[7]-r[7],t[8]=i[8]-r[8],t[9]=i[9]-r[9],t[10]=i[10]-r[10],t[11]=i[11]-r[11],t[12]=i[12]-r[12],t[13]=i[13]-r[13],t[14]=i[14]-r[14],t[15]=i[15]-r[15],t}function OaA(t,i,r){return t[0]=i[0]*r,t[1]=i[1]*r,t[2]=i[2]*r,t[3]=i[3]*r,t[4]=i[4]*r,t[5]=i[5]*r,t[6]=i[6]*r,t[7]=i[7]*r,t[8]=i[8]*r,t[9]=i[9]*r,t[10]=i[10]*r,t[11]=i[11]*r,t[12]=i[12]*r,t[13]=i[13]*r,t[14]=i[14]*r,t[15]=i[15]*r,t}function xaA(t,i,r,s){return t[0]=i[0]+r[0]*s,t[1]=i[1]+r[1]*s,t[2]=i[2]+r[2]*s,t[3]=i[3]+r[3]*s,t[4]=i[4]+r[4]*s,t[5]=i[5]+r[5]*s,t[6]=i[6]+r[6]*s,t[7]=i[7]+r[7]*s,t[8]=i[8]+r[8]*s,t[9]=i[9]+r[9]*s,t[10]=i[10]+r[10]*s,t[11]=i[11]+r[11]*s,t[12]=i[12]+r[12]*s,t[13]=i[13]+r[13]*s,t[14]=i[14]+r[14]*s,t[15]=i[15]+r[15]*s,t}function YaA(t,i){return t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]&&t[4]===i[4]&&t[5]===i[5]&&t[6]===i[6]&&t[7]===i[7]&&t[8]===i[8]&&t[9]===i[9]&&t[10]===i[10]&&t[11]===i[11]&&t[12]===i[12]&&t[13]===i[13]&&t[14]===i[14]&&t[15]===i[15]}function PaA(t,i){var r=t[0],s=t[1],g=t[2],B=t[3],Q=t[4],f=t[5],m=t[6],M=t[7],v=t[8],U=t[9],AA=t[10],z=t[11],sA=t[12],eA=t[13],X=t[14],QA=t[15],wA=i[0],HA=i[1],qA=i[2],ue=i[3],jA=i[4],Ve=i[5],ze=i[6],Me=i[7],qe=i[8],Et=i[9],Je=i[10],$e=i[11],Dt=i[12],Zi=i[13],bi=i[14],qt=i[15];return Math.abs(r-wA)<=as*Math.max(1,Math.abs(r),Math.abs(wA))&&Math.abs(s-HA)<=as*Math.max(1,Math.abs(s),Math.abs(HA))&&Math.abs(g-qA)<=as*Math.max(1,Math.abs(g),Math.abs(qA))&&Math.abs(B-ue)<=as*Math.max(1,Math.abs(B),Math.abs(ue))&&Math.abs(Q-jA)<=as*Math.max(1,Math.abs(Q),Math.abs(jA))&&Math.abs(f-Ve)<=as*Math.max(1,Math.abs(f),Math.abs(Ve))&&Math.abs(m-ze)<=as*Math.max(1,Math.abs(m),Math.abs(ze))&&Math.abs(M-Me)<=as*Math.max(1,Math.abs(M),Math.abs(Me))&&Math.abs(v-qe)<=as*Math.max(1,Math.abs(v),Math.abs(qe))&&Math.abs(U-Et)<=as*Math.max(1,Math.abs(U),Math.abs(Et))&&Math.abs(AA-Je)<=as*Math.max(1,Math.abs(AA),Math.abs(Je))&&Math.abs(z-$e)<=as*Math.max(1,Math.abs(z),Math.abs($e))&&Math.abs(sA-Dt)<=as*Math.max(1,Math.abs(sA),Math.abs(Dt))&&Math.abs(eA-Zi)<=as*Math.max(1,Math.abs(eA),Math.abs(Zi))&&Math.abs(X-bi)<=as*Math.max(1,Math.abs(X),Math.abs(bi))&&Math.abs(QA-qt)<=as*Math.max(1,Math.abs(QA),Math.abs(qt))}var JaA=x6,HaA=V6,dG=`#version 300 es in vec2 a_position; in vec2 a_texCoord; out vec2 v_texCoord; void main() { gl_Position = vec4(a_position.x, a_position.y, 0, 1); v_texCoord = a_texCoord; -}`,d3=t=>`precision highp float; +}`,y3=t=>`precision highp float; uniform sampler2D mask;in vec2 v_texCoord; out vec4 outColor; -void main() {${t}}`,_aA=`#version 300 es +void main() {${t}}`,VaA=`#version 300 es uniform sampler2D lastMask; -${d3(`highp float current = texture(mask, v_texCoord).r; +${y3(`highp float current = texture(mask, v_texCoord).r; highp float previous = texture(lastMask, v_texCoord).r; highp float diff = abs(current - previous); const float smoothFactor = 0.05; @@ -292,8 +292,8 @@ ${d3(`highp float current = texture(mask, v_texCoord).r; ? previous * (1.0 - smoothFactor) + current * smoothFactor : current; outColor = vec4(blendedMask,0.0,0.0, 1.0);`)} -`,baA=`#version 300 es -${d3(` vec2 o = 1.0 / vec2(textureSize(mask, 0)); +`,qaA=`#version 300 es +${y3(` vec2 o = 1.0 / vec2(textureSize(mask, 0)); float size = 3.0; int sizeDb = int(size*size); float samples[9]; @@ -317,8 +317,8 @@ ${d3(` vec2 o = 1.0 / vec2(textureSize(mask, 0)); } float endR=samples[sizeDb/2]>0.5?1.0:0.0; outColor = vec4(endR, 0.0, 0.0, 1.0);`)} -`,LaA=`#version 300 es -${d3(` vec2 o = 1.0 / vec2(textureSize(mask, 0)); +`,KaA=`#version 300 es +${y3(` vec2 o = 1.0 / vec2(textureSize(mask, 0)); float size = 3.0; float side = (size - 1.0) / 2.0; float stronglyEroded = 1.0; @@ -329,7 +329,7 @@ ${d3(` vec2 o = 1.0 / vec2(textureSize(mask, 0)); } } outColor = vec4(stronglyEroded, 0.0, 0.0, 1.0);`)} -`,FaA=`#version 300 es +`,jaA=`#version 300 es precision highp float; uniform sampler2D mask; uniform sampler2D originalMask; @@ -382,7 +382,7 @@ void main() { } outColor = vec4(finalAlpha, 0.0, 0.0, 1.0); } -`,UaA=`#version 300 es +`,WaA=`#version 300 es precision highp float; uniform sampler2D mask; in vec2 v_texCoord; @@ -424,18 +424,18 @@ void main() { float edge = nmsEdge > 0.0 ? 1.0 : 0.0; outColor = vec4(edge, 0.0, 0.0, 1.0); } -`,OaA=class{constructor(){Oa(this,"gl"),Oa(this,"positionBuffer"),Oa(this,"texCoordBuffer"),Oa(this,"ratio"),Oa(this,"_tdProgram"),Oa(this,"_kcProgram"),Oa(this,"_mdProgram"),Oa(this,"_edgeProgram"),Oa(this,"_borderProgram"),Oa(this,"_lastMaskTexture")}init(t,i,r,s){this.initParams(t,i,r,s),this.initPrograms()}initParams(t,i,r,s){this.gl=t,this.positionBuffer=i,this.texCoordBuffer=r,this.ratio=s}initPrograms(){this._tdProgram=this.createProgram(CG,_aA,["mask","lastMask"]),this._mdProgram=this.createProgram(CG,baA,["mask"]),this._kcProgram=this.createProgram(CG,LaA,["mask"]),this._borderProgram=this.createProgram(CG,FaA,["mask","maskEdge","originalMask"]),this._edgeProgram=this.createProgram(CG,UaA,["mask"])}setAttributes(...t){const{gl:i}=this;t.forEach((r,s)=>{i.enableVertexAttribArray(s),i.bindBuffer(i.ARRAY_BUFFER,r),i.vertexAttribPointer(s,2,i.FLOAT,!1,0,0)})}createShader(t,i){const{gl:r}=this,s=r.createShader(t);return r.shaderSource(s,i),r.compileShader(s),s}createProgram(t,i,r){const{gl:s}=this,g=this.createShader(s.FRAGMENT_SHADER,i),B=this.createShader(s.VERTEX_SHADER,t),Q=s.createProgram();if(s.attachShader(Q,B),s.attachShader(Q,g),s.linkProgram(Q),!s.getProgramParameter(Q,s.LINK_STATUS))throw new Error(`${s.getProgramInfoLog(Q)}`);return s.useProgram(Q),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.forEach((f,m)=>{s.uniform1i(s.getUniformLocation(Q,f),1+m)}),Q}createFramebuffer(t){const{gl:i}=this,r=i.createFramebuffer();return i.bindFramebuffer(i.FRAMEBUFFER,r),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,t,0),r}getTempTexture(t,i,r=!0,s){const{gl:g}=this;let B,Q;g.useProgram(t),this.ratio===16/9?(B=640,Q=360):(B=640,Q=480);const f=g.createTexture();g.activeTexture(g.TEXTURE0),g.bindTexture(g.TEXTURE_2D,f),g.texParameteri(g.TEXTURE_2D,g.TEXTURE_MIN_FILTER,g.LINEAR),g.texParameteri(g.TEXTURE_2D,g.TEXTURE_MAG_FILTER,g.LINEAR),g.texParameteri(g.TEXTURE_2D,g.TEXTURE_WRAP_S,g.CLAMP_TO_EDGE),g.texParameteri(g.TEXTURE_2D,g.TEXTURE_WRAP_T,g.CLAMP_TO_EDGE),g.pixelStorei(g.PACK_ALIGNMENT,1),g.pixelStorei(g.UNPACK_ALIGNMENT,1),g.texImage2D(g.TEXTURE_2D,0,g.RGBA,B,Q,0,g.RGBA,g.UNSIGNED_BYTE,null);const m=this.createFramebuffer(f);return i.forEach((M,v)=>{M&&(g.activeTexture(g.TEXTURE1+v),g.bindTexture(g.TEXTURE_2D,M||null))}),this.setAttributes(this.positionBuffer,this.texCoordBuffer),g.viewport(0,0,B,Q),g.drawArrays(g.TRIANGLE_STRIP,0,4),r&&i.forEach((M,v)=>{M&&s!==v&&g.deleteTexture(M)}),g.deleteFramebuffer(m),f}postProcessing(t){this._lastMaskTexture=this.getTempTexture(this._tdProgram,[t,this._lastMaskTexture]);let i=this.getTempTexture(this._kcProgram,[this._lastMaskTexture],!1);for(let r=0;r<3;r++){i=this.getTempTexture(this._mdProgram,[i]);const s=this.getTempTexture(this._edgeProgram,[i],!1);i=this.getTempTexture(this._borderProgram,[i,s,this._lastMaskTexture],!0,2)}return i}close(){const{gl:t}=this;this._borderProgram&&t.deleteProgram(this._borderProgram),this._edgeProgram&&t.deleteProgram(this._edgeProgram),this._kcProgram&&t.deleteProgram(this._kcProgram),this._mdProgram&&t.deleteProgram(this._mdProgram),this._tdProgram&&t.deleteProgram(this._tdProgram)}},xaA=new OaA,YaA=(t=>(t[t.TRACE=0]="TRACE",t[t.DEBUG=1]="DEBUG",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.NONE=5]="NONE",t))(YaA||{}),PaA={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},jM=570703,GK=0,F6=class U6{constructor(i){this.core=i,Oa(this,"seq"),Oa(this,"_core"),Oa(this,"log"),Oa(this,"preLoadPromise"),Oa(this,"startResolve"),Oa(this,"startReject"),Oa(this,"mediaPipeSolutions"),Oa(this,"assetsPath"),Oa(this,"currentType"),Oa(this,"onAbort"),Oa(this,"isAborted",!1),GK+=1,this.seq=GK,this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${GK}`}),this.log.info("created"),i.assetsPath&&(this.preLoadPromise=this.preload(i.assetsPath))}static isSupported(){if(OnA<90)return!1;const i=document.createElement("canvas").getContext("webgl2",PaA);return!!(i&&i instanceof WebGL2RenderingContext)}async preload(i){try{this._core.room.videoManager.Wasm||(this._core.room.videoManager.Wasm=await BnA());const r=s=>{var g;this.core.kvStatManager.addEnum({key:jM,value:this.getKVTypeValue(!1,this.isAborted,"ABORT_IN_INFERENCE")}),this.isAborted=!0,this.log.error("mediaPipeSolutions abort",s),this.core.clearStarted(this,this.getGroup()),this.stop(),(g=this.onAbort)==null||g.call(this,s)};this._core.room.videoManager.initVirtualBackground(r,v6,xaA),await this._core.initVisionTaskRegistry(i,["ImageSegmenter"])}catch(r){const{RtcError:s,ErrorCode:g}=this._core.errorModule;throw new s({code:g.INVALID_OPERATION,message:`VirtualBackground preload error, please redeploy the assets of the npm package. detail: ${r}`})}}getName(){return U6.Name}getAlias(){return"vb"}getValidateRule(i){switch(i){case"start":return cnA(this._core);case"update":return EnA(this._core);case"stop":return lnA(this._core)}}getGroup(){return"vb"}getKVTypeValue(i=!1,r=!1,s="NONE"){let g=0;switch(this.currentType){case"blur":g|=0;break;case"image":g|=1;break;case"color":g|=2}switch(i&&(g|=256),r&&(g|=512),s){case"ABORT_IN_INFERENCE":g|=4096;break;case"ABORT_IN_VIDEO_MANAGER":g|=8192;break;case"OTHER":g|=61440}return g}hexToRgb(i){const r=i.replace("#","");return[parseInt(r.slice(0,2),16)/255,parseInt(r.slice(2,4),16)/255,parseInt(r.slice(4,6),16)/255]}async start(i){const{type:r="blur",src:s,blurLevel:g=3,onAbort:B}=i;this.currentType=r,this.onAbort=B,r==="color"&&typeof i.color=="string"&&(i.color=this.hexToRgb(i.color));const{auth:Q}=await gnA({sdkAppId:i.sdkAppId,userId:i.userId,userSig:i.userSig,core:this._core}),{RtcError:f,ErrorCodeDictionary:m,ErrorCode:M}=this._core.errorModule;if(!Q){const v=this._core.utils.isOverseaSdkAppId(i.sdkAppId)?"https://trtc.io/document/56025":"https://cloud.tencent.com/document/product/647/85386";throw new f({code:m.NEED_TO_BUY,messageParams:{value:"Virtual Background",url:v}})}if(!this.preLoadPromise){if(!this._core.assetsPath)throw new f({code:M.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:r,imageUrl:s,blurLevel:g,enableFaceCentering:i.enableFaceCentering,enableEffectOptimization:i.enableEffectOptimization,color:i.color,onAbort:v=>{var U;this.core.kvStatManager.addEnum({key:jM,value:this.getKVTypeValue(!0,this.isAborted,"ABORT_IN_VIDEO_MANAGER")}),this.isAborted=!0,this.core.clearStarted(this,this.getGroup()),this.stop(),delete this.preLoadPromise,(U=this.onAbort)==null||U.call(this,v)}}).then(()=>{this.core.kvStatManager.addEnum({key:jM,value:this.getKVTypeValue(!1,this.isAborted,"NONE")})}).catch(v=>{throw this.core.kvStatManager.addEnum({key:jM,value:this.getKVTypeValue(!0,this.isAborted,"OTHER")}),v})}async update(i){const{type:r,src:s}=i;return r!==this.currentType&&(this.currentType=r),r==="color"&&typeof i.color=="string"&&(i.color=this.hexToRgb(i.color)),this.core.room.videoManager.setVirtualBackground({type:r,imageUrl:s,blurLevel:i.blurLevel,enableFaceCentering:i.enableFaceCentering,enableEffectOptimization:i.enableEffectOptimization,color:i.color}).then(()=>{this.core.kvStatManager.addEnum({key:jM,value:this.getKVTypeValue(!1,!1,"NONE")})}).catch(()=>{this.core.kvStatManager.addEnum({key:jM,value:this.getKVTypeValue(!0,!1,"OTHER")})})}async stop(){return this.core.room.videoManager.setVirtualBackground()}};Oa(F6,"Name","VirtualBackground");var O6=F6,JaA=O6;const HaA=Object.freeze(Object.defineProperty({__proto__:null,VirtualBackground:O6,default:JaA},Symbol.toStringTag,{value:"Module"})),VaA=hk(HaA);var qaA=Object.defineProperty,KaA=(t,i,r)=>i in t?qaA(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,wG=(t,i,r)=>KaA(t,typeof i!="symbol"?i+"":i,r);function jaA(t){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,r,s,g){const{RtcError:B,ErrorCode:Q,ErrorCodeDictionary:f}=t.errorModule;if(t.utils.isOverseaSdkAppId(i.sdkAppId))throw new B({code:Q.INVALID_OPERATION,extraCode:f.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 WaA(t){return{name:"StopBasicBeautyOptions",required:!1}}var zaA=(()=>{var t=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(i={}){var r,s,g=i;g.ready=new Promise((P,F)=>{r=P,s=F});var B=Object.assign({},g),Q="";typeof document<"u"&&document.currentScript&&(Q=document.currentScript.src),t&&(Q=t),Q=Q.indexOf("blob:")!==0?Q.substr(0,Q.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var f,m,M=g.print||console.log.bind(console),v=g.printErr||console.error.bind(console);function U(P){if(bi(P))return function(F){for(var EA=atob(F),RA=new Uint8Array(EA.length),GA=0;GAP.startsWith(Zi);function qt(P){return Promise.resolve().then(()=>function(F){if(F==$e&&f)return new Uint8Array(f);var EA=U(F);if(EA)return EA;throw"both async and sync fetching of the wasm failed"}(P))}function ai(P,F,EA,RA){return function(GA,WA,Ce){return qt(GA).then(ge=>WebAssembly.instantiate(ge,WA)).then(ge=>ge).then(Ce,ge=>{v(`failed to asynchronously prepare wasm: ${ge}`),Je(ge)})}(F,EA,RA)}bi($e="data:application/octet-stream;base64,AGFzbQEAAAAB8gEfYAJ/fwBgAX8Bf2ADf39/AX9gAX8AYAN/f38AYAJ/fwF/YAR/f39/AGAAAGAFf39/f38AYAZ/f39/f38AYAR/f39/AX9gB39/f39/f38AYAN/fn8BfmAFf3x8fHwAYAZ/fHx8fHwAYAV/f39/fwF8YAl/f39/f39/f38AYAN/f38BfGAKf39/f39/f39/fwBgDX9/f39/f39/f39/f38AYAJ/fABgAn5/AX9gAn99AGABfAF8YAZ/fH9/f38Bf2AGf39/f39/AX9gAnx/AXxgBH9/fn4AYAZ/f3x8fHwAYAd/f3x8fHx8AGAFf39/f38BfwKXARkBYQFhAAQBYQFiAAMBYQFjAAMBYQFkAAMBYQFlAA8BYQFmAAIBYQFnAAgBYQFoAAUBYQFpABABYQFqABEBYQFrABIBYQFsAAQBYQFtAAcBYQFuAAoBYQFvAAABYQFwAAQBYQFxAAsBYQFyAAEBYQFzAAQBYQF0AAABYQF1AAYBYQF2AAABYQF3AAQBYQF4AAkBYQF5ABMDZmUDBQIBBAIIBRQCBAUFAgcBFQEAAwEWAAQABAUFBRcHBwMBBgUEBQMAAwIECwQCAQUYBgEZChoBAwcDBhsHAQEBCQkICAQCBgYCAgAAAgEABQwBAgMBAAMAAwEcDR0OAAAAAAAeAAQFAXABNzcFBgEBgAKAAgYNAn8BQeDiBAt/AUEACwchCAF6AgABQQA4AUIALQFDAQABRABtAUUAGQFGAFgBRwB8CTwBAEEBCzZ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HI6AAAgAEL/////nwFWIQUgByEAIAUNAAsLIAenIgIEQANAIAFBAWsiASACIAJBCm4iA0EKbGtBMHI6AAAgAkEJSyEGIAMhAiAGDQALCyABC3oBA38CQAJAIAAiAUEDcUUNACABLQAARQRAQQAPCwNAIAFBAWoiAUEDcUUNASABLQAADQALDAELA0AgASICQQRqIQEgAigCACIDQX9zIANBgYKECGtxQYCBgoR4cUUNAAsDQCACIgFBAWohAiABLQAADQALCyABIABrC78EAQl/AkACfyAALQALQQd2BEAgACgCBAwBCyAALQALQf8AcQsiAiABSQRAIwBBEGsiBiQAIAEgAmsiBQRAIAUgAC0AC0EHdgR/IAAoAghB/////wdxQQFrBUEKCyICAn8gAC0AC0EHdgRAIAAoAgQMAQsgAC0AC0H/AHELIgFrSwRAIwBBEGsiBCQAAkAgBSACayABaiIDQe////8HIAJrTQRAAn8gAC0AC0EHdgRAIAAoAgAMAQsgAAshByAEQQRqIgggACACQef///8DSQR/IAQgAkEBdDYCDCAEIAIgA2o2AgQjAEEQayIDJAAgCCgCACAEQQxqIgkoAgBJIQogA0EQaiQAIAkgCCAKGygCACIDQQtPBH8gA0EQakFwcSIDIANBAWsiAyADQQtGGwVBCgtBAWoFQe////8HCxAwIAQoAgQhAyAEKAIIGiABBEAgAyAHIAEQIwsgAkEKRwRAIAcQGQsgACADNgIAIAAgACgCCEGAgICAeHEgBCgCCEH/////B3FyNgIIIAAgACgCCEGAgICAeHI2AgggBEEQaiQADAELECcACyAAIAE2AgQLIAECfyAALQALQQd2BEAgACgCAAwBCyAACyICaiAFEEAgACABIAVqIgAQMSAGQQA6AA8gACACaiAGLQAPOgAACyAGQRBqJAAMAQsCfyAALQALQQd2BEAgACgCAAwBCyAACyEEIwBBEGsiAiQAIAAgARAxIAJBADoADyABIARqIAItAA86AAAgAkEQaiQACwsGACAAEBkL0igBDH8jAEEQayIKJAACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEHs3gAoAgAiBkEQIABBC2pBeHEgAEELSRsiBU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EBRw0CIAAoAjBBAUYNAQwCCyABIAJGBEAgACgCGCICQQJGBEAgACADNgIYIAMhAgsgACgCMEEBRw0CIAJBAUYNAQwCCyAAIAAoAiRBAWo2AiQLIABBAToANgsLTAEBfwJAIAFFDQAgAUHczgAQICIBRQ0AIAEoAgggACgCCEF/c3ENACAAKAIMIAEoAgxBABAeRQ0AIAAoAhAgASgCEEEAEB4hAgsgAgtdAQF/IAAoAhAiA0UEQCAAQQE2AiQgACACNgIYIAAgATYCEA8LAkAgASADRgRAIAAoAhhBAkcNASAAIAI2AhgPCyAAQQE6ADYgAEECNgIYIAAgACgCJEEBajYCJAsLYwECfyMAQRBrIgIkACABIAAoAgQiA0EBdWohASAAKAIAIQAgAkEIaiABIANBAXEEfyABKAIAIABqKAIABSAACxEAACACKAIMIgAQAiACKAIMIgEEQCABEAMLIAJBEGokACAAC0MBAX8jAEEQayIBJAAgAEIANwIAIABBADYCCCABQRBqJAAgACAALQALQQd2BH8gACgCCEH/////B3FBAWsFQQoLECsLPQEBfyMAQRBrIgIkACACQQA6AA8DQCABBEAgACACLQAPOgAAIAFBAWshASAAQQFqIQAMAQsLIAJBEGokAAsaACAALQALQQd2BEAgACgCCBogACgCABAZCwvmAQEFfyMAQRBrIgUkACMAQSBrIgMkACMAQRBrIgQkACAEIAA2AgwgBCAAIAFqNgIIIAMgBCgCDDYCGCADIAQoAgg2AhwgBEEQaiQAIAMoAhghBCADKAIcIQYjAEEQayIBJAAgASAGNgIMIAIgBCAGIARrIgQQQyABIAIgBGo2AgggAyABKAIMNgIQIAMgASgCCDYCFCABQRBqJAAgAyAAIAMoAhAgAGtqNgIMIAMgAiADKAIUIAJrajYCCCAFIAMoAgw2AgggBSADKAIINgIMIANBIGokACAFKAIMIQcgBUEQaiQAIAcLDwAgAgRAIAAgASACEDILC/UCAQV/IwBBEGsiByQAIAIgAUF/c0Hv////B2pNBEACfyAALQALQQd2BEAgACgCAAwBCyAACyEIIAdBBGoiCSAAIAFB5////wNJBH8gByAB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KAIANgIADAELAkAgAUUNACABQezNABAgIgZFDQEgAigCACIBBEAgAiABKAIANgIACyAGKAIIIgMgACgCCCIBQX9zcUEHcQ0BIANBf3MgAXFB4ABxDQFBASEFIAAoAgwgBigCDEEAEB4NASAAKAIMQbzPAEEAEB4EQCAGKAIMIgBFDQIgAEGgzgAQIEUhBQwCCyAAKAIMIgNFDQBBACEFIANB7M0AECAiAQRAIAAtAAhBAXFFDQICfyAGKAIMIQBBACECAkADQEEAIABFDQIaIABB7M0AECAiA0UNASADKAIIIAEoAghBf3NxDQFBASABKAIMIAMoAgxBABAeDQIaIAEtAAhBAXFFDQEgASgCDCIARQ0BIABB7M0AECAiAQRAIAMoAgwhAAwBCwsgAEHczgAQICIARQ0AIAAgAygCDBA8IQILIAILIQUMAgsgA0HczgAQICIBBEAgAC0ACEEBcUUNAiABIAYoAgwQPCEFDAILIANBjM0AECAiAUUNASAGKAIMIgBFDQEgAEGMzQAQICIARQ0BIARBDGpBAEE0ECYaIARBATYCOCAEQX82AhQgBCABNgIQIAQgADYCCCAAIARBCGogAigCAEEBIAAoAgAoAhwRBgACQCAEKAIgIgBBAUcNACACKAIARQ0AIAIgBCgCGDYCAAsgAEEBRiEFDAELQQAhBQsgBEFAayQAIAULMQAgACABKAIIQQAQHgRAIAEgAiADED0PCyAAKAIIIgAgASACIAMgACgCACgCHBEGAAsYACAAIAEoAghBABAeBEAgASACIAMQPQsLnQEBAn8jAEFAaiIDJAACf0EBIAAgAUEAEB4NABpBACABRQ0AGkEAIAFBjM0AECAiAUUNABogA0EMakEAQTQQJhogA0EBNgI4IANBfzYCFCADIAA2AhAgAyABNgIIIAEgA0EIaiACKAIAQQEgASgCACgCHBEGACADKAIgIgBBAUYEQCACIAMoAhg2AgALIABBAUYLIQQgA0FAayQAIAQLCgAgACABQQAQHgtOAgF/AXwjAEEQayICJAAgAkEANgIMIAEoAgRB1M8AIAJBDGoQCSEDIAIoAgwiAQRAIAEQAQsgACADRAAAAAAAAAAAYjoAOCACQRBqJAALNwEBfyMAQRBrIgIkACACIAEtADg2AgggAEHUzwAgAkEIahAHNgIEIABB1NUANgIAIAJBEGokAAuoAQEFfyAAKAJUIgMoAgAhBSADKAIEIgQgACgCFCAAKAIcIgdrIgYgBCAGSRsiBgRAIAUgByAGECIaIAMgAygCACAGaiIFNgIAIAMgAygCBCAGayIENgIECyAEIAIgAiAESxsiBARAIAUgASAEECIaIAMgAygCACAEaiIFNgIAIAMgAygCBCAEazYCBAsgBUEAOgAAIAAgACgCLCIBNgIcIAAgATYCFCACC5wBAQJ/IwBBEGsiAiQAQcgAEBwhASAAKAIEIgAQAiACIAA2AgggAUHMLSACQQhqEAc2AgQgAUHU1QA2AgAgAUEBNgIcIAFB1NUANgIYIAFBATYCFCABQdTVADYCECABQQE2AgwgAUHU1QA2AgggAUEAOgAgIAFBADYCRCABQoCAgIAwNwI8IAFBADsANyABQQA7ACsgAkEQaiQAIAELigUCBn4CfyABIAEoAgBBB2pBeHEiAUEQajYCACAAIQkgASkDACEDIAEpAwghBSMAQSBrIgAkAAJAIAVC////////////AIMiBEKAgICAgIDAgDx9IARCgICAgICAwP/DAH1UBEAgBUIEhiADQjyIhCEEIANC//////////8PgyIDQoGAgICAgICACFoEQCAEQoGAgICAgICAwAB8IQIMAgsgBEKAgICAgICAgEB9IQIgA0KAgICAgICAgAhSDQEgAiAEQgGDfCECDAELIANQIARCgICAgICAwP//AFQgBEKAgICAgIDA//8AURtFBEAgBUIEhiADQjyIhEL/////////A4NCgICAgICAgPz/AIQhAgwBC0KAgICAgICA+P8AIQIgBEL///////+//8MAVg0AQgAhAiAEQjCIpyIBQZH3AEkNACADIQIgBUL///////8/g0KAgICAgIDAAIQiBCEGAkAgAUGB9wBrIghBwABxBEAgAyAIQUBqrYYhBkIAIQIMAQsgCEUNACAGIAitIgeGIAJBwAAgCGutiIQhBiACIAeGIQILIAAgAjcDECAAIAY3AxgCQEGB+AAgAWsiAUHAAHEEQCAEIAFBQGqtiCEDQgAhBAwBCyAB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YgBaiIFLQALQQd2BEAgBSgCBAwBCyAFLQALQf8AcQshCAJ/An8jAEEQayIJJAAgBkH4AGohAiAHIAhqIgRB7////wdNBEACQCAEQQtJBEAgAkIANwIAIAJBADYCCCACIAItAAtBgAFxIARB/wBxcjoACyACIAItAAtB/wBxOgALDAELIARBC08EfyAEQRBqQXBxIgogCkEBayIKIApBC0YbBUEKC0EBaiIKEBwhCyACIAIoAghBgICAgHhxIApB/////wdxcjYCCCACIAIoAghBgICAgHhyNgIIIAIgCzYCACACIAQ2AgQLIAlBEGokACACDAELECcACyIELQALQQd2BEAgBCgCAAwBCyAECyIEQZkmIAcQIyAEIAdqIgQCfyAFLQALQQd2BEAgBSgCAAwBCyAFCyAIECMgBCAIakEBEEAgDEEQaiQAIA0gAkHzKRAaIgIpAgA3AgAgDSACKAIINgIIIAJCADcCACACQQA2AgggBiwAgwFBAEgEQCAGKAJ4EBkLIAYsAJMBQQBIBEAgBigCiAEQGQsgBigClAEiBQRAIAYoApgBIgQgBSICRwRAA0AgBEEMayICKAIAIgcEQCAEQQhrIAc2AgAgBxAZCyACIgQgBUcNAAsgBigClAEhAgsgBiAFNgKYASACEBkLIAZBoAFqJAAgA0EcaiADKAIoIA0gAy0AMyICwEEASCIFGyADKAIsIAIgBRsQGxogAywAM0EATg0DIAMoAigQGQwDCyADQRxqQcwhEBoaDAILIANBHGpBrywQGhoMAQsgA0EcakGYLBAaGgsCQAJAIAEoAjAgAS0ANyICIALAIgZBAEgbIgRBAWoiBUHw////B0kEQAJAAkAgBUELTwRAIAVBD3JBAWoiBxAcIQIgAyAFNgIsIAMgAjYCKCADIAdBgICAgHhyNgIwDAELIANBADYCMCADQgA3AyggAyAFOgAzIANBKGohAiAERQ0BCyACIAFBLGoiBSgCACAFIAZBAEgbIAQQMgsgAiAEakEKOwAAIANBHGogAygCKCADQShqIAMtADMiAsBBAEgiBRsgAygCLCACIAUbEBsaIAMsADNBAEgEQCADKAIoEBkLIAEoAiQgAS0AKyICIALAIgZB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AAAHAnAABIKAAAeQAAAHAnAABUKAAAZgAAAHAnAABgKAAAZAAAAHAnAABsKAAAAAAAAIwmAAAhAAAAJgAAACMAAAAkAAAAJwAAACgAAAApAAAAKgAAAAAAAADwKAAAIQAAACsAAAAjAAAAJAAAACcAAAAsAAAALQAAAC4AAABOMTBfX2N4eGFiaXYxMjBfX3NpX2NsYXNzX3R5cGVfaW5mb0UAAAAAqCgAAMgoAACMJgAAAAAAAOwmAAAhAAAALwAAACMAAAAkAAAAMAAAAAAAAAA8KQAAMQAAADIAAAAzAAAAU3Q5ZXhjZXB0aW9uAAAAAIAoAAAsKQAAAAAAAGgpAAAYAAAANAAAADUAAABTdDExbG9naWNfZXJyb3IAqCgAAFgpAAA8KQAAAAAAAJwpAAAYAAAANgAAADUAAABTdDEybGVuZ3RoX2Vycm9yAAAAAKgoAACIKQAAaCkAAFN0OXR5cGVfaW5mbwAAAACAKAAAqCkAQcDTAAsJCxUAAAAAAAAFAEHU0wALARsAQezTAAsOHAAAAB0AAABoKwAAAAQAQYTUAAsBAQBBlNQACwX/////CgBB2NQACwNgMQE=")||(Dt=$e,$e=g.locateFile?g.locateFile(Dt,Q):Q+Dt);var Ki=P=>{for(;P.length>0;)P.shift()(g)};g.noExitRuntime;function Ur(P){this.excPtr=P,this.ptr=P-24,this.set_type=function(F){QA[this.ptr+4>>2]=F},this.get_type=function(){return QA[this.ptr+4>>2]},this.set_destructor=function(F){QA[this.ptr+8>>2]=F},this.get_destructor=function(){return QA[this.ptr+8>>2]},this.set_caught=function(F){F=F?1:0,AA[this.ptr+12|0]=F},this.get_caught=function(){return AA[this.ptr+12|0]!=0},this.set_rethrown=function(F){F=F?1:0,AA[this.ptr+13|0]=F},this.get_rethrown=function(){return AA[this.ptr+13|0]!=0},this.init=function(F,EA){this.set_adjusted_ptr(0),this.set_type(F),this.set_destructor(EA)},this.set_adjusted_ptr=function(F){QA[this.ptr+16>>2]=F},this.get_adjusted_ptr=function(){return QA[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Cs(this.get_type()))return QA[this.excPtr>>2];var F=this.get_adjusted_ptr();return F!==0?F:this.excPtr}}var Er,no,Kn,Xi=P=>{for(var F="",EA=P;z[EA];)F+=Er[z[EA++]];return F},yr={},lr={},Ni={},wt=P=>{throw new no(P)},Ji=P=>{throw new Kn(P)},Di=(P,F,EA)=>{function RA(ge){var we=EA(ge);we.length!==P.length&&Ji("Mismatched type converter count");for(var _e=0;_e{lr.hasOwnProperty(ge)?GA[we]=lr[ge]:(WA.push(ge),yr.hasOwnProperty(ge)||(yr[ge]=[]),yr[ge].push(()=>{GA[we]=lr[ge],++Ce===WA.length&&RA(GA)}))}),WA.length===0&&RA(GA)};function ar(P,F,EA={}){if(!("argPackAdvance"in F))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(RA,GA,WA={}){var Ce=GA.name;if(RA||wt(`type "${Ce}" must have a positive integer typeid pointer`),lr.hasOwnProperty(RA)){if(WA.ignoreDuplicateRegistrations)return;wt(`Cannot register type '${Ce}' twice`)}if(lr[RA]=GA,delete Ni[RA],yr.hasOwnProperty(RA)){var ge=yr[RA];delete yr[RA],ge.forEach(we=>we())}}(P,F,EA)}var MA,YA=P=>{wt(P.$$.ptrType.registeredClass.name+" instance already deleted")},pe=!1,st=P=>{},Te=P=>{P.count.value-=1,P.count.value===0&&(F=>{F.smartPtr?F.smartPtrType.rawDestructor(F.smartPtr):F.ptrType.registeredClass.rawDestructor(F.ptr)})(P)},be=(P,F,EA)=>{if(F===EA)return P;if(EA.baseClass===void 0)return null;var RA=be(P,F,EA.baseClass);return RA===null?null:EA.downcast(RA)},yt={},ht=()=>Object.keys(zt).length,ae=()=>{var P=[];for(var F in zt)zt.hasOwnProperty(F)&&P.push(zt[F]);return P},ye=[],Xe=()=>{for(;ye.length;){var P=ye.pop();P.$$.deleteScheduled=!1,P.delete()}},ot=P=>{MA=P,ye.length&&MA&&MA(Xe)},zt={},yi=(P,F)=>(F=((EA,RA)=>{for(RA===void 0&&wt("ptr should not be undefined");EA.baseClass;)RA=EA.upcast(RA),EA=EA.baseClass;return RA})(P,F),zt[F]),Hi=(P,F)=>(F.ptrType&&F.ptr||Ji("makeClassHandle requires ptr and ptrType"),!!F.smartPtrType!=!!F.smartPtr&&Ji("Both smartPtrType and smartPtr must be specified"),F.count={value:1},ji(Object.create(P,{$$:{value:F}})));function Ei(P){var F=this.getPointee(P);if(!F)return this.destructor(P),null;var EA=yi(this.registeredClass,F);if(EA!==void 0){if(EA.$$.count.value===0)return EA.$$.ptr=F,EA.$$.smartPtr=P,EA.clone();var RA=EA.clone();return this.destructor(P),RA}function GA(){return this.isSmartPointer?Hi(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:F,smartPtrType:this,smartPtr:P}):Hi(this.registeredClass.instancePrototype,{ptrType:this,ptr:P})}var WA,Ce=this.registeredClass.getActualType(F),ge=yt[Ce];if(!ge)return GA.call(this);WA=this.isConst?ge.constPointerType:ge.pointerType;var we=be(F,this.registeredClass,WA.registeredClass);return we===null?GA.call(this):this.isSmartPointer?Hi(WA.registeredClass.instancePrototype,{ptrType:WA,ptr:we,smartPtrType:this,smartPtr:P}):Hi(WA.registeredClass.instancePrototype,{ptrType:WA,ptr:we})}var ji=P=>typeof FinalizationRegistry>"u"?(ji=F=>F,P):(pe=new FinalizationRegistry(F=>{Te(F.$$)}),st=F=>pe.unregister(F),(ji=F=>{var EA=F.$$;if(EA.smartPtr){var RA={$$:EA};pe.register(F,RA,F)}return F})(P));function Xo(){}var sr=(P,F)=>Object.defineProperty(F,"name",{value:P}),Lo=(P,F,EA)=>{if(P[F].overloadTable===void 0){var RA=P[F];P[F]=function(){return P[F].overloadTable.hasOwnProperty(arguments.length)||wt(`Function '${EA}' called with an invalid number of arguments (${arguments.length}) - expects one of (${P[F].overloadTable})!`),P[F].overloadTable[arguments.length].apply(this,arguments)},P[F].overloadTable=[],P[F].overloadTable[RA.argCount]=RA}};function Nr(P,F,EA,RA,GA,WA,Ce,ge){this.name=P,this.constructor=F,this.instancePrototype=EA,this.rawDestructor=RA,this.baseClass=GA,this.getActualType=WA,this.upcast=Ce,this.downcast=ge,this.pureVirtualFunctions=[]}var Vo=(P,F,EA)=>{for(;F!==EA;)F.upcast||wt(`Expected null or instance of ${EA.name}, got an instance of ${F.name}`),P=F.upcast(P),F=F.baseClass;return P};function et(P,F){if(F===null)return this.isReference&&wt(`null is not a valid ${this.name}`),0;F.$$||wt(`Cannot pass "${ao(F)}" as a ${this.name}`),F.$$.ptr||wt(`Cannot pass deleted object as a pointer of type ${this.name}`);var EA=F.$$.ptrType.registeredClass;return Vo(F.$$.ptr,EA,this.registeredClass)}function Kr(P,F){var EA;if(F===null)return this.isReference&&wt(`null is not a valid ${this.name}`),this.isSmartPointer?(EA=this.rawConstructor(),P!==null&&P.push(this.rawDestructor,EA),EA):0;F.$$||wt(`Cannot pass "${ao(F)}" as a ${this.name}`),F.$$.ptr||wt(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&F.$$.ptrType.isConst&&wt(`Cannot convert argument of type ${F.$$.smartPtrType?F.$$.smartPtrType.name:F.$$.ptrType.name} to parameter type ${this.name}`);var RA=F.$$.ptrType.registeredClass;if(EA=Vo(F.$$.ptr,RA,this.registeredClass),this.isSmartPointer)switch(F.$$.smartPtr===void 0&&wt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:F.$$.smartPtrType===this?EA=F.$$.smartPtr:wt(`Cannot convert argument of type ${F.$$.smartPtrType?F.$$.smartPtrType.name:F.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:EA=F.$$.smartPtr;break;case 2:if(F.$$.smartPtrType===this)EA=F.$$.smartPtr;else{var GA=F.clone();EA=this.rawShare(EA,gr.toHandle(()=>GA.delete())),P!==null&&P.push(this.rawDestructor,EA)}break;default:wt("Unsupporting sharing policy")}return EA}function Qn(P,F){if(F===null)return this.isReference&&wt(`null is not a valid ${this.name}`),0;F.$$||wt(`Cannot pass "${ao(F)}" as a ${this.name}`),F.$$.ptr||wt(`Cannot pass deleted object as a pointer of type ${this.name}`),F.$$.ptrType.isConst&&wt(`Cannot convert argument of type ${F.$$.ptrType.name} to parameter type ${this.name}`);var EA=F.$$.ptrType.registeredClass;return Vo(F.$$.ptr,EA,this.registeredClass)}function ho(P){return this.fromWireType(QA[P>>2])}function jn(P,F,EA,RA,GA,WA,Ce,ge,we,_e,Ke){this.name=P,this.registeredClass=F,this.isReference=EA,this.isConst=RA,this.isSmartPointer=GA,this.pointeeType=WA,this.sharingPolicy=Ce,this.rawGetPointee=ge,this.rawConstructor=we,this.rawShare=_e,this.rawDestructor=Ke,GA||F.baseClass!==void 0?this.toWireType=Kr:RA?(this.toWireType=et,this.destructorFunction=null):(this.toWireType=Qn,this.destructorFunction=null)}var $t,$r,On=[],An=P=>{var F=On[P];return F||(P>=On.length&&(On.length=P+1),On[P]=F=$t.get(P)),F},Tr=(P,F,EA)=>P.includes("j")?((RA,GA,WA)=>{var Ce=g["dynCall_"+RA];return WA&&WA.length?Ce.apply(null,[GA].concat(WA)):Ce.call(null,GA)})(P,F,EA):An(F).apply(null,EA),ei=(P,F)=>{var EA,RA,GA,WA=(P=Xi(P)).includes("j")?(EA=P,RA=F,GA=[],function(){return GA.length=0,Object.assign(GA,arguments),Tr(EA,RA,GA)}):An(F);return typeof WA!="function"&&wt(`unknown function pointer with signature ${P}: ${F}`),WA},Es=P=>{var F=Ba(P),EA=Xi(F);return Mr(F),EA},jr=(P,F)=>{var EA=[],RA={};throw F.forEach(function GA(WA){RA[WA]||lr[WA]||(Ni[WA]?Ni[WA].forEach(GA):(EA.push(WA),RA[WA]=!0))}),new $r(`${P}: `+EA.map(Es).join([", "]))},Gr=(P,F)=>{for(var EA=[],RA=0;RA>2]);return EA},$o=P=>{for(;P.length;){var F=P.pop();P.pop()(F)}};function sn(P,F,EA,RA,GA,WA){var Ce=F.length;Ce<2&&wt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var ge=F[1]!==null&&EA!==null,we=!1,_e=1;_e(P instanceof Object||wt(`${EA} with invalid "this": ${P}`),P instanceof F.registeredClass.constructor||wt(`${EA} incompatible with "this" of type ${P.constructor.name}`),P.$$.ptr||wt(`cannot call emscripten binding method ${EA} on deleted object`),Vo(P.$$.ptr,P.$$.ptrType.registeredClass,F.registeredClass));function hn(){this.allocated=[void 0],this.freelist=[]}var Gi=new hn,pn=P=>{P>=Gi.reserved&&--Gi.get(P).refcount===0&&Gi.free(P)},nI=()=>{for(var P=0,F=Gi.reserved;F(P||wt("Cannot use deleted val. handle = "+P),Gi.get(P).value),toHandle:P=>{switch(P){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return Gi.allocate({refcount:1,value:P})}}};function gn(P){return this.fromWireType(X[P>>2])}var Yo,Tg,So,ao=P=>{if(P===null)return"null";var F=typeof P;return F==="object"||F==="array"||F==="function"?P.toString():""+P},EE=(P,F)=>{switch(F){case 4:return function(EA){return this.fromWireType(wA[EA>>2])};case 8:return function(EA){return this.fromWireType(HA[EA>>3])};default:throw new TypeError(`invalid float width (${F}): ${P}`)}},Ta=(P,F,EA)=>{switch(F){case 1:return EA?RA=>AA[RA|0]:RA=>z[RA|0];case 2:return EA?RA=>sA[RA>>1]:RA=>eA[RA>>1];case 4:return EA?RA=>X[RA>>2]:RA=>QA[RA>>2];default:throw new TypeError(`invalid integer width (${F}): ${P}`)}},po=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ja=(P,F,EA)=>{for(var RA=F+EA,GA=F;P[GA]&&!(GA>=RA);)++GA;if(GA-F>16&&P.buffer&&po)return po.decode(P.subarray(F,GA));for(var WA="";F>10,56320|1023&_e)}}else WA+=String.fromCharCode((31&Ce)<<6|ge)}else WA+=String.fromCharCode(Ce)}return WA},Mc=(P,F)=>P?Ja(z,P,F):"",Qr=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Fo=(P,F)=>{for(var EA=P,RA=EA>>1,GA=RA+F/2;!(RA>=GA)&&eA[RA];)++RA;if((EA=RA<<1)-P>32&&Qr)return Qr.decode(z.subarray(P,EA));for(var WA="",Ce=0;!(Ce>=F/2);++Ce){var ge=sA[P+2*Ce>>1];if(ge==0)break;WA+=String.fromCharCode(ge)}return WA},$s=(P,F,EA)=>{if(EA===void 0&&(EA=2147483647),EA<2)return 0;for(var RA=F,GA=(EA-=2)<2*P.length?EA/2:P.length,WA=0;WA>1]=Ce,F+=2}return sA[F>>1]=0,F-RA},Ha=P=>2*P.length,Gs=(P,F)=>{for(var EA=0,RA="";!(EA>=F/4);){var GA=X[P+4*EA>>2];if(GA==0)break;if(++EA,GA>=65536){var WA=GA-65536;RA+=String.fromCharCode(55296|WA>>10,56320|1023&WA)}else RA+=String.fromCharCode(GA)}return RA},Ga=(P,F,EA)=>{if(EA===void 0&&(EA=2147483647),EA<4)return 0;for(var RA=F,GA=RA+EA-4,WA=0;WA=55296&&Ce<=57343&&(Ce=65536+((1023&Ce)<<10)|1023&P.charCodeAt(++WA)),X[F>>2]=Ce,(F+=4)+4>GA)break}return X[F>>2]=0,F-RA},Rr=P=>{for(var F=0,EA=0;EA=55296&&RA<=57343&&++EA,F+=4}return F},Ia=(P,F)=>{var EA=lr[P];return EA===void 0&&wt(F+" has unknown type "+Es(P)),EA},fo=(P,F,EA)=>{var RA=[],GA=P.toWireType(RA,EA);return RA.length&&(QA[F>>2]=gr.toHandle(RA)),GA},aI={},en=[],qo=Reflect.construct,Gg=[null,[],[]],kg=(P,F)=>{var EA=Gg[P];F===0||F===10?((P===1?M:v)(Ja(EA,0)),EA.length=0):EA.push(F)};(()=>{for(var P=new Array(256),F=0;F<256;++F)P[F]=String.fromCharCode(F);Er=P})(),no=g.BindingError=class extends Error{constructor(P){super(P),this.name="BindingError"}},Kn=g.InternalError=class extends Error{constructor(P){super(P),this.name="InternalError"}},Object.assign(Xo.prototype,{isAliasOf(P){if(!(this instanceof Xo)||!(P instanceof Xo))return!1;var F=this.$$.ptrType.registeredClass,EA=this.$$.ptr;P.$$=P.$$;for(var RA=P.$$.ptrType.registeredClass,GA=P.$$.ptr;F.baseClass;)EA=F.upcast(EA),F=F.baseClass;for(;RA.baseClass;)GA=RA.upcast(GA),RA=RA.baseClass;return F===RA&&EA===GA},clone(){if(this.$$.ptr||YA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var P,F=ji(Object.create(Object.getPrototypeOf(this),{$$:{value:(P=this.$$,{count:P.count,deleteScheduled:P.deleteScheduled,preservePointerOnDelete:P.preservePointerOnDelete,ptr:P.ptr,ptrType:P.ptrType,smartPtr:P.smartPtr,smartPtrType:P.smartPtrType})}}));return F.$$.count.value+=1,F.$$.deleteScheduled=!1,F},delete(){this.$$.ptr||YA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&wt("Object already scheduled for deletion"),st(this),Te(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||YA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&wt("Object already scheduled for deletion"),ye.push(this),ye.length===1&&MA&&MA(Xe),this.$$.deleteScheduled=!0,this}}),g.getInheritedInstanceCount=ht,g.getLiveInheritedInstances=ae,g.flushPendingDeletes=Xe,g.setDelayFunction=ot,Object.assign(jn.prototype,{getPointee(P){return this.rawGetPointee&&(P=this.rawGetPointee(P)),P},destructor(P){this.rawDestructor&&this.rawDestructor(P)},argPackAdvance:8,readValueFromPointer:ho,deleteObject(P){P!==null&&P.delete()},fromWireType:Ei}),$r=g.UnboundTypeError=(Yo=Error,(So=sr(Tg="UnboundTypeError",function(P){this.name=Tg,this.message=P;var F=new Error(P).stack;F!==void 0&&(this.stack=this.toString()+` -`+F.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(Yo.prototype),So.prototype.constructor=So,So.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},So),Object.assign(hn.prototype,{get(P){return this.allocated[P]},has(P){return this.allocated[P]!==void 0},allocate(P){var F=this.freelist.pop()||this.allocated.length;return this.allocated[F]=P,F},free(P){this.allocated[P]=void 0,this.freelist.push(P)}}),Gi.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Gi.reserved=Gi.allocated.length,g.count_emval_handles=nI;var fn,ls={w:(P,F,EA)=>{throw new Ur(P).init(F,EA),P},q:(P,F,EA,RA,GA)=>{},u:(P,F,EA,RA)=>{ar(P,{name:F=Xi(F),fromWireType:function(GA){return!!GA},toWireType:function(GA,WA){return WA?EA:RA},argPackAdvance:8,readValueFromPointer:function(GA){return this.fromWireType(z[GA])},destructorFunction:null})},y:(P,F,EA,RA,GA,WA,Ce,ge,we,_e,Ke,Bt,Rt)=>{Ke=Xi(Ke),WA=ei(GA,WA),ge&&(ge=ei(Ce,ge)),_e&&(_e=ei(we,_e)),Rt=ei(Bt,Rt);var Ye=(nt=>{if(nt===void 0)return"_unknown";var ii=(nt=nt.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return ii>=48&&ii<=57?`_${nt}`:nt})(Ke);((nt,ii,oi)=>{g.hasOwnProperty(nt)?(wt(`Cannot register public name '${nt}' twice`),Lo(g,nt,nt),g.hasOwnProperty(oi)&&wt(`Cannot register multiple overloads of a function with the same number of arguments (${oi})!`),g[nt].overloadTable[oi]=ii):g[nt]=ii})(Ye,function(){jr(`Cannot construct ${Ke} due to unbound types`,[RA])}),Di([P,F,EA],RA?[RA]:[],function(nt){var ii,oi;nt=nt[0],oi=RA?(ii=nt.registeredClass).instancePrototype:Xo.prototype;var Ko=sr(Ke,function(){if(Object.getPrototypeOf(this)!==Kt)throw new no("Use 'new' to construct "+Ke);if(ro.constructor_body===void 0)throw new no(Ke+" has no accessible constructor");var xr=ro.constructor_body[arguments.length];if(xr===void 0)throw new no(`Tried to invoke ctor of ${Ke} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(ro.constructor_body).toString()}) parameters instead!`);return xr.apply(this,arguments)}),Kt=Object.create(oi,{constructor:{value:Ko}});Ko.prototype=Kt;var ro=new Nr(Ke,Ko,Kt,Rt,ii,WA,ge,_e);ro.baseClass&&(ro.baseClass.__derivedClasses===void 0&&(ro.baseClass.__derivedClasses=[]),ro.baseClass.__derivedClasses.push(ro));var ks=new jn(Ke,ro,!0,!1,!1),Zr=new jn(Ke+"*",ro,!1,!1,!1),In=new jn(Ke+" const*",ro,!1,!0,!1);return yt[P]={pointerType:Zr,constPointerType:In},((xr,sI,jo)=>{g.hasOwnProperty(xr)||Ji("Replacing nonexistant public symbol"),g[xr].overloadTable!==void 0&&jo!==void 0?g[xr].overloadTable[jo]=sI:(g[xr]=sI,g[xr].argCount=jo)})(Ye,Ko),[ks,Zr,In]})},x:(P,F,EA,RA,GA,WA)=>{var Ce=Gr(F,EA);GA=ei(RA,GA),Di([],[P],function(ge){var we=`constructor ${(ge=ge[0]).name}`;if(ge.registeredClass.constructor_body===void 0&&(ge.registeredClass.constructor_body=[]),ge.registeredClass.constructor_body[F-1]!==void 0)throw new no(`Cannot register multiple constructors with identical number of parameters (${F-1}) for class '${ge.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return ge.registeredClass.constructor_body[F-1]=()=>{jr(`Cannot construct ${ge.name} due to unbound types`,Ce)},Di([],Ce,_e=>(_e.splice(1,0,null),ge.registeredClass.constructor_body[F-1]=sn(we,_e,null,GA,WA),[])),[]})},i:(P,F,EA,RA,GA,WA,Ce,ge,we)=>{var _e=Gr(EA,RA);F=(Ke=>{const Bt=(Ke=Ke.trim()).indexOf("(");return Bt!==-1?Ke.substr(0,Bt):Ke})(F=Xi(F)),WA=ei(GA,WA),Di([],[P],function(Ke){var Bt=`${(Ke=Ke[0]).name}.${F}`;function Rt(){jr(`Cannot call ${Bt} due to unbound types`,_e)}F.startsWith("@@")&&(F=Symbol[F.substring(2)]),ge&&Ke.registeredClass.pureVirtualFunctions.push(F);var Ye=Ke.registeredClass.instancePrototype,nt=Ye[F];return nt===void 0||nt.overloadTable===void 0&&nt.className!==Ke.name&&nt.argCount===EA-2?(Rt.argCount=EA-2,Rt.className=Ke.name,Ye[F]=Rt):(Lo(Ye,F,Bt),Ye[F].overloadTable[EA-2]=Rt),Di([],_e,function(ii){var oi=sn(Bt,ii,Ke,WA,Ce);return Ye[F].overloadTable===void 0?(oi.argCount=EA-2,Ye[F]=oi):Ye[F].overloadTable[EA-2]=oi,[]}),[]})},k:(P,F,EA,RA,GA,WA,Ce,ge,we,_e)=>{F=Xi(F),GA=ei(RA,GA),Di([],[P],function(Ke){var Bt=`${(Ke=Ke[0]).name}.${F}`,Rt={get(){jr(`Cannot access ${Bt} due to unbound types`,[EA,Ce])},enumerable:!0,configurable:!0};return Rt.set=we?()=>jr(`Cannot access ${Bt} due to unbound types`,[EA,Ce]):Ye=>wt(Bt+" is a read-only property"),Object.defineProperty(Ke.registeredClass.instancePrototype,F,Rt),Di([],we?[EA,Ce]:[EA],function(Ye){var nt=Ye[0],ii={get(){var Ko=dn(this,Ke,Bt+" getter");return nt.fromWireType(GA(WA,Ko))},enumerable:!0};if(we){we=ei(ge,we);var oi=Ye[1];ii.set=function(Ko){var Kt=dn(this,Ke,Bt+" setter"),ro=[];we(_e,Kt,oi.toWireType(ro,Ko)),$o(ro)}}return Object.defineProperty(Ke.registeredClass.instancePrototype,F,ii),[]}),[]})},t:(P,F)=>{ar(P,{name:F=Xi(F),fromWireType:EA=>{var RA=gr.toValue(EA);return pn(EA),RA},toWireType:(EA,RA)=>gr.toHandle(RA),argPackAdvance:8,readValueFromPointer:gn,destructorFunction:null})},p:(P,F,EA)=>{ar(P,{name:F=Xi(F),fromWireType:RA=>RA,toWireType:(RA,GA)=>GA,argPackAdvance:8,readValueFromPointer:EE(F,EA),destructorFunction:null})},g:(P,F,EA,RA,GA)=>{F=Xi(F);var WA=we=>we;if(RA===0){var Ce=32-8*EA;WA=we=>we<>>Ce}var ge=F.includes("unsigned");ar(P,{name:F,fromWireType:WA,toWireType:ge?function(we,_e){return this.name,_e>>>0}:function(we,_e){return this.name,_e},argPackAdvance:8,readValueFromPointer:Ta(F,EA,RA!==0),destructorFunction:null})},a:(P,F,EA)=>{var RA=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][F];function GA(WA){var Ce=QA[WA>>2],ge=QA[WA+4>>2];return new RA(AA.buffer,ge,Ce)}ar(P,{name:EA=Xi(EA),fromWireType:GA,argPackAdvance:8,readValueFromPointer:GA},{ignoreDuplicateRegistrations:!0})},o:(P,F)=>{var EA=(F=Xi(F))==="std::string";ar(P,{name:F,fromWireType(RA){var GA,WA=QA[RA>>2],Ce=RA+4;if(EA)for(var ge=Ce,we=0;we<=WA;++we){var _e=Ce+we;if(we==WA||z[_e]==0){var Ke=Mc(ge,_e-ge);GA===void 0?GA=Ke:(GA+="\0",GA+=Ke),ge=_e+1}}else{var Bt=new Array(WA);for(we=0;we{for(var Rt=0,Ye=0;Ye=55296&&nt<=57343?(Rt+=4,++Ye):Rt+=3}return Rt})(GA):GA.length;var ge=Po(4+WA+1),we=ge+4;if(QA[ge>>2]=WA,EA&&Ce)((Bt,Rt,Ye,nt)=>{if(!(nt>0))return 0;for(var ii=Ye,oi=Ye+nt-1,Ko=0;Ko=55296&&Kt<=57343&&(Kt=65536+((1023&Kt)<<10)|1023&Bt.charCodeAt(++Ko)),Kt<=127){if(Ye>=oi)break;Rt[Ye++]=Kt}else if(Kt<=2047){if(Ye+1>=oi)break;Rt[Ye++]=192|Kt>>6,Rt[Ye++]=128|63&Kt}else if(Kt<=65535){if(Ye+2>=oi)break;Rt[Ye++]=224|Kt>>12,Rt[Ye++]=128|Kt>>6&63,Rt[Ye++]=128|63&Kt}else{if(Ye+3>=oi)break;Rt[Ye++]=240|Kt>>18,Rt[Ye++]=128|Kt>>12&63,Rt[Ye++]=128|Kt>>6&63,Rt[Ye++]=128|63&Kt}}Rt[Ye]=0})(GA,z,we,WA+1);else if(Ce)for(var _e=0;_e255&&(Mr(we),wt("String has UTF-16 code units that do not fit in 8 bits")),z[we+_e]=Ke}else for(_e=0;_e{var RA,GA,WA,Ce,ge;EA=Xi(EA),F===2?(RA=Fo,GA=$s,Ce=Ha,WA=()=>eA,ge=1):F===4&&(RA=Gs,GA=Ga,Ce=Rr,WA=()=>QA,ge=2),ar(P,{name:EA,fromWireType:we=>{for(var _e,Ke=QA[we>>2],Bt=WA(),Rt=we+4,Ye=0;Ye<=Ke;++Ye){var nt=we+4+Ye*F;if(Ye==Ke||Bt[nt>>ge]==0){var ii=RA(Rt,nt-Rt);_e===void 0?_e=ii:(_e+="\0",_e+=ii),Rt=nt+F}}return Mr(we),_e},toWireType:(we,_e)=>{typeof _e!="string"&&wt(`Cannot pass non-string to C++ string type ${EA}`);var Ke=Ce(_e),Bt=Po(4+Ke+F);return QA[Bt>>2]=Ke>>ge,GA(_e,Bt+4,Ke+F),we!==null&&we.push(Mr,Bt),Bt},argPackAdvance:8,readValueFromPointer:gn,destructorFunction(we){Mr(we)}})},v:(P,F)=>{ar(P,{isVoid:!0,name:F=Xi(F),argPackAdvance:0,fromWireType:()=>{},toWireType:(EA,RA)=>{}})},j:(P,F,EA)=>(P=gr.toValue(P),F=Ia(F,"emval::as"),fo(F,EA,P)),e:(P,F,EA,RA,GA)=>{var WA,Ce;return(P=en[P])(F=gr.toValue(F),F[EA=(Ce=aI[WA=EA])===void 0?Xi(WA):Ce],RA,GA)},d:pn,f:(P,F,EA)=>{var RA=((_e,Ke)=>{for(var Bt=new Array(_e),Rt=0;Rt<_e;++Rt)Bt[Rt]=Ia(QA[Ke+4*Rt>>2],"parameter "+Rt);return Bt})(P,F),GA=RA.shift();P--;var WA,Ce,ge=new Array(P),we=`methodCaller<(${RA.map(_e=>_e.name).join(", ")}) => ${GA.name}>`;return WA=sr(we,(_e,Ke,Bt,Rt)=>{for(var Ye=0,nt=0;nt{P>4&&(Gi.get(P).refcount+=1)},b:P=>{var F=gr.toValue(P);$o(F),pn(P)},h:(P,F)=>{var EA=(P=Ia(P,"_emval_take_value")).readValueFromPointer(F);return gr.toHandle(EA)},m:()=>{Je("")},s:(P,F,EA)=>z.copyWithin(P,F,F+EA),r:P=>{z.length,Je("OOM")},n:(P,F,EA,RA)=>{for(var GA=0,WA=0;WA>2],ge=QA[F+4>>2];F+=8;for(var we=0;we>2]=GA,0}},Or=function(){var P={a:ls};function F(EA,RA){var GA,WA;return Or=EA.exports,m=Or.z,GA=m.buffer,g.HEAP8=AA=new Int8Array(GA),g.HEAP16=sA=new Int16Array(GA),g.HEAPU8=z=new Uint8Array(GA),g.HEAPU16=eA=new Uint16Array(GA),g.HEAP32=X=new Int32Array(GA),g.HEAPU32=QA=new Uint32Array(GA),g.HEAPF32=wA=new Float32Array(GA),g.HEAPF64=HA=new Float64Array(GA),$t=Or.C,WA=Or.A,jA.unshift(WA),function(){if(qe--,g.monitorRunDependencies&&g.monitorRunDependencies(qe),qe==0&&Et){var Ce=Et;Et=null,Ce()}}(),Or}if(qe++,g.monitorRunDependencies&&g.monitorRunDependencies(qe),g.instantiateWasm)try{return g.instantiateWasm(P,F)}catch(EA){v(`Module.instantiateWasm callback failed with error: ${EA}`),s(EA)}return ai(0,$e,P,function(EA){F(EA.instance)}).catch(s),{}}(),Po=P=>(Po=Or.B)(P),Ba=P=>(Ba=Or.D)(P),Mr=P=>(Mr=Or.E)(P),Cs=P=>(Cs=Or.F)(P);g.dynCall_jiji=(P,F,EA,RA,GA)=>(g.dynCall_jiji=Or.G)(P,F,EA,RA,GA),g._vertexShaderSource=10688;function Va(){function P(){fn||(fn=!0,g.calledRun=!0,VA||(Ki(jA),r(g),g.onRuntimeInitialized&&g.onRuntimeInitialized(),function(){if(g.postRun)for(typeof g.postRun=="function"&&(g.postRun=[g.postRun]);g.postRun.length;)Me(g.postRun.shift());Ki(Ve)}()))}qe>0||(function(){if(g.preRun)for(typeof g.preRun=="function"&&(g.preRun=[g.preRun]);g.preRun.length;)Ze(g.preRun.shift());Ki(ue)}(),qe>0||(g.setStatus?(g.setStatus("Running..."),setTimeout(function(){setTimeout(function(){g.setStatus("")},1),P()},1)):P()))}if(Et=function P(){fn||Va(),fn||(Et=P)},g.preInit)for(typeof g.preInit=="function"&&(g.preInit=[g.preInit]);g.preInit.length>0;)g.preInit.pop()();return Va(),i.ready}})(),ZaA=zaA,kK=0,x6=class Y6{constructor(i){this.core=i,wG(this,"seq"),wG(this,"_core"),wG(this,"log"),wG(this,"beautyParams"),kK+=1,this.seq=kK,this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${kK}`}),this.log.info("created")}getName(){return Y6.Name}getAlias(){return"bb"}getValidateRule(i){switch(i){case"start":case"update":return jaA(this._core);case"stop":return WaA(this._core)}}getGroup(){return"bb"}async start(i){this._core.room.videoManager.Wasm||(this._core.room.videoManager.Wasm=await ZaA()),this._core.room.videoManager.renderMode="webgl";const r=this._core.utils.isUndefined(i.beauty)?.5:i.beauty,s=this._core.utils.isUndefined(i.brightness)?.5:i.brightness,g=this._core.utils.isUndefined(i.ruddy)?.5:i.ruddy;return this._core.room.videoManager.setBeautyParams({beauty:r,brightness:s,ruddy:g})}async update(i){const r=this._core.utils.isUndefined(i.beauty)?.5:i.beauty,s=this._core.utils.isUndefined(i.brightness)?.5:i.brightness,g=this._core.utils.isUndefined(i.ruddy)?.5:i.ruddy;return this._core.room.videoManager.setBeautyParams({beauty:r,brightness:s,ruddy:g})}async stop(){return this._core.room.videoManager.renderMode="auto",this._core.room.videoManager.stopBeauty()}destroy(){this._core.room.videoManager.renderMode="auto"}};wG(x6,"Name","BasicBeauty");var P6=x6,XaA=P6;const $aA=Object.freeze(Object.defineProperty({__proto__:null,BasicBeauty:P6,default:XaA},Symbol.toStringTag,{value:"Module"})),AsA=hk($aA);var esA=Object.defineProperty,tsA=(t,i,r)=>i in t?esA(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,m2=(t,i,r)=>tsA(t,typeof i!="symbol"?i+"":i,r),isA={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}}},osA={name:"option",required:!0,properties:{transcriberRobotId:{type:"string",required:!0}}},rsA=new Set([2002,4003]),J6=class H6{constructor(i){this.core=i,m2(this,"disableRandomCall",!0),m2(this,"activeTranscriberMap",new Map),m2(this,"_log"),this._log=this.core.log.createChild({id:`${this.getAlias()}`})}getName(){return H6.Name}getAlias(){return"rt-trans"}getGroup(){return"*"}getValidateRule(i){switch(i){case"start":return isA;case"update":return{};case"stop":return osA}}async start(i){var r;const{RtcError:s,ErrorCode:g}=this.core.errorModule;if(!this.core.room.sendSignalMessage)throw new s({code:g.ENV_NOT_SUPPORTED});const{sourceLanguage:B,translationLanguages:Q,userIdsToTranscribe:f="all",transcriberRobotId:m}=i,M=m||`transcriber_${this.core.room.roomId}_robot_${this.core.room.userId}`,v={sdkappid:this.core.room.sdkAppId,roomid:String(this.core.room.roomId),roomType:this.core.room.useStringRoomId?1:0,agentParam:{cdnRobotUserid:M,lifecycleUserid:this.core.room.userId,maxIdletime:30},subscribeParams:{subUsers:[]},asrParams:{lang:B,vadSilenceTime:1e3},translationParams:{mode:1,targetLangs:[""]}};Q&&Q.length>0&&(v.translationParams.mode=1,v.translationParams.targetLangs=Array.isArray(Q)?Q:[Q]),f==="all"?v.subscribeParams.subUsers=[]:Array.isArray(f)?v.subscribeParams.subUsers=f.map(U=>({userId:U,roomType:this.core.room.useStringRoomId?1:0,roomid:String(this.core.room.roomId)})):f&&(v.subscribeParams.subUsers=[{userId:f,roomType:this.core.room.useStringRoomId?1:0,roomid:String(this.core.room.roomId)}]);try{this._log.info(`start_cloud_transcription ${JSON.stringify(v)}`);const U=await this.core.room.sendSignalMessage({command:"start_cloud_transcription",responseCommand:String(8268),data:v,retries:0}),{code:AA,data:z}=U.data;if(AA!==0){const eA=((r=U.data)==null?void 0:r.message)||"";throw this._log.error("start_cloud_transcription failed",{extraCode:AA,reason:eA,data:z}),new s({code:g.SERVER_ERROR,extraCode:AA,message:eA})}const{taskId:sA}=z;if(!sA)throw this._log.error("taskId is required",{data:U.data}),new s({code:g.SERVER_ERROR,message:"taskId is required"});return this.activeTranscriberMap.set(sA,i),this._log.info(`start_cloud_transcription success ${sA}, activeSize: ${this.activeTranscriberMap.size}`),sA}catch(U){throw this._log.error("start_cloud_transcription failed",{error:U}),U}}async update(){}async stop({transcriberRobotId:i}){var r;const{RtcError:s,ErrorCode:g}=this.core.errorModule;if(!this.core.room.sendSignalMessage)throw new s({code:g.ENV_NOT_SUPPORTED});try{const B=await this.core.room.sendSignalMessage({command:"stop_cloud_transcription",responseCommand:String(8270),data:{taskId:i},retries:3});if(B.data.code!==0){const Q=B.data.code,f=((r=B.data)==null?void 0:r.message)||"";if(!rsA.has(Q))throw this._log.error("stop_cloud_transcription failed",{extraCode:Q,reason:f,data:B.data.data}),new s({code:g.SERVER_ERROR,extraCode:Q,message:f});this._log.warn("stop_cloud_transcription ignored error",{extraCode:Q,reason:f,data:B.data.data})}this.activeTranscriberMap.delete(i)}catch(B){throw this._log.error("stop_cloud_transcription failed",{error:B}),B}}destroy(){this.activeTranscriberMap.clear()}};m2(J6,"Name","RealtimeTranscriber");var V6=J6,nsA=V6;const asA=Object.freeze(Object.defineProperty({__proto__:null,RealtimeTranscriber:V6,default:nsA},Symbol.toStringTag,{value:"Module"})),ssA=hk(asA);var gsA=Object.create,pk=Object.defineProperty,IsA=Object.defineProperties,q6=Object.getOwnPropertyDescriptor,csA=Object.getOwnPropertyDescriptors,K6=Object.getOwnPropertyNames,O2=Object.getOwnPropertySymbols,EsA=Object.getPrototypeOf,h3=Object.prototype.hasOwnProperty,j6=Object.prototype.propertyIsEnumerable,wj=(t,i,r)=>i in t?pk(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,cr=(t,i)=>{for(var r in i||(i={}))h3.call(i,r)&&wj(t,r,i[r]);if(O2)for(var r of O2(i))j6.call(i,r)&&wj(t,r,i[r]);return t},lB=(t,i)=>IsA(t,csA(i)),lsA=(t,i)=>{var r={};for(var s in t)h3.call(t,s)&&i.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&O2)for(var s of O2(t))i.indexOf(s)<0&&j6.call(t,s)&&(r[s]=t[s]);return r},fk=(t,i)=>function(){return i||(0,t[K6(t)[0]])((i={exports:{}}).exports,i),i.exports},p3=(t,i)=>{for(var r in i)pk(t,r,{get:i[r],enumerable:!0})},CsA=(t,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let g of K6(i))h3.call(t,g)||g===r||pk(t,g,{get:()=>i[g],enumerable:!(s=q6(i,g))||s.enumerable});return t},Tw=(t,i,r)=>(r=t!=null?gsA(EsA(t)):{},CsA(pk(r,"default",{value:t,enumerable:!0}),t)),ss=(t,i,r,s)=>{for(var g,B=q6(i,r),Q=t.length-1;Q>=0;Q--)(g=t[Q])&&(B=g(i,r,B)||B);return B&&pk(i,r,B),B},OA=(t,i,r)=>wj(t,typeof i!="symbol"?i+"":i,r),mk=fk({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(t,i){var r=Object.prototype.hasOwnProperty,s="~";function g(){}function B(M,v,U){this.fn=M,this.context=v,this.once=U||!1}function Q(M,v,U,AA,z){if(typeof U!="function")throw new TypeError("The listener must be a function");var sA=new B(U,AA||M,z),eA=s?s+v:v;return M._events[eA]?M._events[eA].fn?M._events[eA]=[M._events[eA],sA]:M._events[eA].push(sA):(M._events[eA]=sA,M._eventsCount++),M}function f(M,v){--M._eventsCount===0?M._events=new g:delete M._events[v]}function m(){this._events=new g,this._eventsCount=0}Object.create&&(g.prototype=Object.create(null),new g().__proto__||(s=!1)),m.prototype.eventNames=function(){var M,v,U=[];if(this._eventsCount===0)return U;for(v in M=this._events)r.call(M,v)&&U.push(s?v.slice(1):v);return Object.getOwnPropertySymbols?U.concat(Object.getOwnPropertySymbols(M)):U},m.prototype.listeners=function(M){var v=s?s+M:M,U=this._events[v];if(!U)return[];if(U.fn)return[U.fn];for(var AA=0,z=U.length,sA=new Array(z);AA1&&(Q[m[0]]=void 0),Q};t.parseParams=function(Q){return Q.split(/;\s?/).reduce(B,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(Q){return Q.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(Q){for(var f=[],m=Q.split(" ").map(i),M=0;M=U)return AA;var z=v[M];switch(M+=1,AA){case"%%":return"%";case"%s":return String(z);case"%d":return Number(z);case"%v":return""}})},B=function(m,M,v){var U=[m+"="+(M.format instanceof Function?M.format(M.push?v:v[M.name]):M.format)];if(M.names)for(var AA=0;AA{i.enableVertexAttribArray(s),i.bindBuffer(i.ARRAY_BUFFER,r),i.vertexAttribPointer(s,2,i.FLOAT,!1,0,0)})}createShader(t,i){const{gl:r}=this,s=r.createShader(t);return r.shaderSource(s,i),r.compileShader(s),s}createProgram(t,i,r){const{gl:s}=this,g=this.createShader(s.FRAGMENT_SHADER,i),B=this.createShader(s.VERTEX_SHADER,t),Q=s.createProgram();if(s.attachShader(Q,B),s.attachShader(Q,g),s.linkProgram(Q),!s.getProgramParameter(Q,s.LINK_STATUS))throw new Error(`${s.getProgramInfoLog(Q)}`);return s.useProgram(Q),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.forEach((f,m)=>{s.uniform1i(s.getUniformLocation(Q,f),1+m)}),Q}createFramebuffer(t){const{gl:i}=this,r=i.createFramebuffer();return i.bindFramebuffer(i.FRAMEBUFFER,r),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,t,0),r}getTempTexture(t,i,r=!0,s){const{gl:g}=this;let B,Q;g.useProgram(t),this.ratio===16/9?(B=640,Q=360):(B=640,Q=480);const f=g.createTexture();g.activeTexture(g.TEXTURE0),g.bindTexture(g.TEXTURE_2D,f),g.texParameteri(g.TEXTURE_2D,g.TEXTURE_MIN_FILTER,g.LINEAR),g.texParameteri(g.TEXTURE_2D,g.TEXTURE_MAG_FILTER,g.LINEAR),g.texParameteri(g.TEXTURE_2D,g.TEXTURE_WRAP_S,g.CLAMP_TO_EDGE),g.texParameteri(g.TEXTURE_2D,g.TEXTURE_WRAP_T,g.CLAMP_TO_EDGE),g.pixelStorei(g.PACK_ALIGNMENT,1),g.pixelStorei(g.UNPACK_ALIGNMENT,1),g.texImage2D(g.TEXTURE_2D,0,g.RGBA,B,Q,0,g.RGBA,g.UNSIGNED_BYTE,null);const m=this.createFramebuffer(f);return i.forEach((M,v)=>{M&&(g.activeTexture(g.TEXTURE1+v),g.bindTexture(g.TEXTURE_2D,M||null))}),this.setAttributes(this.positionBuffer,this.texCoordBuffer),g.viewport(0,0,B,Q),g.drawArrays(g.TRIANGLE_STRIP,0,4),r&&i.forEach((M,v)=>{M&&s!==v&&g.deleteTexture(M)}),g.deleteFramebuffer(m),f}postProcessing(t){this._lastMaskTexture=this.getTempTexture(this._tdProgram,[t,this._lastMaskTexture]);let i=this.getTempTexture(this._kcProgram,[this._lastMaskTexture],!1);for(let r=0;r<3;r++){i=this.getTempTexture(this._mdProgram,[i]);const s=this.getTempTexture(this._edgeProgram,[i],!1);i=this.getTempTexture(this._borderProgram,[i,s,this._lastMaskTexture],!0,2)}return i}close(){const{gl:t}=this;this._borderProgram&&t.deleteProgram(this._borderProgram),this._edgeProgram&&t.deleteProgram(this._edgeProgram),this._kcProgram&&t.deleteProgram(this._kcProgram),this._mdProgram&&t.deleteProgram(this._mdProgram),this._tdProgram&&t.deleteProgram(this._tdProgram)}},ZaA=new zaA,XaA=(t=>(t[t.TRACE=0]="TRACE",t[t.DEBUG=1]="DEBUG",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.NONE=5]="NONE",t))(XaA||{}),$aA={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},ZM=570703,UK=0,q6=class K6{constructor(i){this.core=i,Oa(this,"seq"),Oa(this,"_core"),Oa(this,"log"),Oa(this,"preLoadPromise"),Oa(this,"startResolve"),Oa(this,"startReject"),Oa(this,"mediaPipeSolutions"),Oa(this,"assetsPath"),Oa(this,"currentType"),Oa(this,"onAbort"),Oa(this,"isAborted",!1),UK+=1,this.seq=UK,this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${UK}`}),this.log.info("created"),i.assetsPath&&(this.preLoadPromise=this.preload(i.assetsPath))}static isSupported(){if(znA<90)return!1;const i=document.createElement("canvas").getContext("webgl2",$aA);return!!(i&&i instanceof WebGL2RenderingContext)}async preload(i){try{this._core.room.videoManager.Wasm||(this._core.room.videoManager.Wasm=await MnA());const r=s=>{var g;this.core.kvStatManager.addEnum({key:ZM,value:this.getKVTypeValue(!1,this.isAborted,"ABORT_IN_INFERENCE")}),this.isAborted=!0,this.log.error("mediaPipeSolutions abort",s),this.core.clearStarted(this,this.getGroup()),this.stop(),(g=this.onAbort)==null||g.call(this,s)};this._core.room.videoManager.initVirtualBackground(r,U6,ZaA),await this._core.initVisionTaskRegistry(i,["ImageSegmenter"])}catch(r){const{RtcError:s,ErrorCode:g}=this._core.errorModule;throw new s({code:g.INVALID_OPERATION,message:`VirtualBackground preload error, please redeploy the assets of the npm package. detail: ${r}`})}}getName(){return K6.Name}getAlias(){return"vb"}getValidateRule(i){switch(i){case"start":return mnA(this._core);case"update":return DnA(this._core);case"stop":return ynA(this._core)}}getGroup(){return"vb"}getKVTypeValue(i=!1,r=!1,s="NONE"){let g=0;switch(this.currentType){case"blur":g|=0;break;case"image":g|=1;break;case"color":g|=2}switch(i&&(g|=256),r&&(g|=512),s){case"ABORT_IN_INFERENCE":g|=4096;break;case"ABORT_IN_VIDEO_MANAGER":g|=8192;break;case"OTHER":g|=61440}return g}hexToRgb(i){const r=i.replace("#","");return[parseInt(r.slice(0,2),16)/255,parseInt(r.slice(2,4),16)/255,parseInt(r.slice(4,6),16)/255]}async start(i){const{type:r="blur",src:s,blurLevel:g=3,onAbort:B}=i;this.currentType=r,this.onAbort=B,r==="color"&&typeof i.color=="string"&&(i.color=this.hexToRgb(i.color));const{auth:Q}=await pnA({sdkAppId:i.sdkAppId,userId:i.userId,userSig:i.userSig,core:this._core}),{RtcError:f,ErrorCodeDictionary:m,ErrorCode:M}=this._core.errorModule;if(!Q){const v=this._core.utils.isOverseaSdkAppId(i.sdkAppId)?"https://trtc.io/document/56025":"https://cloud.tencent.com/document/product/647/85386";throw new f({code:m.NEED_TO_BUY,messageParams:{value:"Virtual Background",url:v}})}if(!this.preLoadPromise){if(!this._core.assetsPath)throw new f({code:M.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:r,imageUrl:s,blurLevel:g,enableFaceCentering:i.enableFaceCentering,enableEffectOptimization:i.enableEffectOptimization,color:i.color,onAbort:v=>{var U;this.core.kvStatManager.addEnum({key:ZM,value:this.getKVTypeValue(!0,this.isAborted,"ABORT_IN_VIDEO_MANAGER")}),this.isAborted=!0,this.core.clearStarted(this,this.getGroup()),this.stop(),delete this.preLoadPromise,(U=this.onAbort)==null||U.call(this,v)}}).then(()=>{this.core.kvStatManager.addEnum({key:ZM,value:this.getKVTypeValue(!1,this.isAborted,"NONE")})}).catch(v=>{throw this.core.kvStatManager.addEnum({key:ZM,value:this.getKVTypeValue(!0,this.isAborted,"OTHER")}),v})}async update(i){const{type:r,src:s}=i;return r!==this.currentType&&(this.currentType=r),r==="color"&&typeof i.color=="string"&&(i.color=this.hexToRgb(i.color)),this.core.room.videoManager.setVirtualBackground({type:r,imageUrl:s,blurLevel:i.blurLevel,enableFaceCentering:i.enableFaceCentering,enableEffectOptimization:i.enableEffectOptimization,color:i.color}).then(()=>{this.core.kvStatManager.addEnum({key:ZM,value:this.getKVTypeValue(!1,!1,"NONE")})}).catch(()=>{this.core.kvStatManager.addEnum({key:ZM,value:this.getKVTypeValue(!0,!1,"OTHER")})})}async stop(){return this.core.room.videoManager.setVirtualBackground()}};Oa(q6,"Name","VirtualBackground");var j6=q6,AsA=j6;const esA=Object.freeze(Object.defineProperty({__proto__:null,VirtualBackground:j6,default:AsA},Symbol.toStringTag,{value:"Module"})),tsA=Mk(esA);var isA=Object.defineProperty,osA=(t,i,r)=>i in t?isA(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,TG=(t,i,r)=>osA(t,typeof i!="symbol"?i+"":i,r);function rsA(t){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,r,s,g){const{RtcError:B,ErrorCode:Q,ErrorCodeDictionary:f}=t.errorModule;if(t.utils.isOverseaSdkAppId(i.sdkAppId))throw new B({code:Q.INVALID_OPERATION,extraCode:f.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 nsA(t){return{name:"StopBasicBeautyOptions",required:!1}}var asA=(()=>{var t=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(i={}){var r,s,g=i;g.ready=new Promise((P,F)=>{r=P,s=F});var B=Object.assign({},g),Q="";typeof document<"u"&&document.currentScript&&(Q=document.currentScript.src),t&&(Q=t),Q=Q.indexOf("blob:")!==0?Q.substr(0,Q.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var f,m,M=g.print||console.log.bind(console),v=g.printErr||console.error.bind(console);function U(P){if(bi(P))return function(F){for(var EA=atob(F),RA=new Uint8Array(EA.length),GA=0;GAP.startsWith(Zi);function qt(P){return Promise.resolve().then(()=>function(F){if(F==$e&&f)return new Uint8Array(f);var EA=U(F);if(EA)return EA;throw"both async and sync fetching of the wasm failed"}(P))}function ai(P,F,EA,RA){return function(GA,WA,Ce){return qt(GA).then(ge=>WebAssembly.instantiate(ge,WA)).then(ge=>ge).then(Ce,ge=>{v(`failed to asynchron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AgACgCAAwBCyAACyIDIAQEfyACIANqIAMgBBBFIAEgAkEAIAMgBGogAUsbQQAgASADTxtqBSABCyACEEUgACACIARqIgEQMSAFQQA6AA8gASADaiAFLQAPOgAADAELIAAgAyACIARqIANrIARBACACIAEQRAsgBUEQaiQAIAAMAQsQJwALC/ICAgJ/AX4CQCACRQ0AIAAgAToAACAAIAJqIgNBAWsgAToAACACQQNJDQAgACABOgACIAAgAToAASADQQNrIAE6AAAgA0ECayABOgAAIAJBB0kNACAAIAE6AAMgA0EEayABOgAAIAJBCUkNACAAQQAgAGtBA3EiBGoiAyABQf8BcUGBgoQIbCIBNgIAIAMgAiAEa0F8cSIEaiICQQRrIAE2AgAgBEEJSQ0AIAMgATYCCCADIAE2AgQgAkEIayABNgIAIAJBDGsgATYCACAEQRlJDQAgAyABNgIYIAMgATYCFCADIAE2AhAgAyABNgIMIAJBEGsgATYCACACQRRrIAE2AgAgAkEYayABNgIAIAJBHGsgATYCACAEIANBBHFBGHIiBGsiAkEgSQ0AIAGtQoGAgIAQfiEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkEgayICQR9LDQALCyAACwUAEAwAC1IBAn9B2NQAKAIAIgEgAEEHakF4cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQEUUNAQtB2NQAIAA2AgAgAQ8LQejeAEEwNgIAQX8LgwECBX8BfgJAIABCgICAgBBUBEAgACEHDAELA0AgAUEBayIBIAAgAEIKgCIHQgp+fadBMHI6AAAgAEL/////nwFWIQUgByEAIAUNAAsLIAenIgIEQANAIAFBAWsiASACIAJBCm4iA0EKbGtBMHI6AAAgAkEJSyEGIAMhAiAGDQALCyABC3oBA38CQAJAIAAiAUEDcUUNACABLQAARQRAQQAPCwNAIAFBAWoiAUEDcUUNASABLQAADQALDAELA0AgASICQQRqIQEgAigCACIDQX9zIANBgYKECGtxQYCBgoR4cUUNAAsDQCACIgFBAWohAiABLQAADQALCyABIABrC78EAQl/AkACfyAALQALQQd2BEAgACgCBAwBCyAALQALQf8AcQsiAiABSQRAIwBBEGsiBiQAIAEgAmsiBQRAIAUgAC0AC0EHdgR/IAAoAghB/////wdxQQFrBUEKCyICAn8gAC0AC0EHdgRAIAAoAgQMAQsgAC0AC0H/AHELIgFrSwRAIwBBEGsiBCQAAkAgBSACayABaiIDQe////8HIAJrTQRAAn8gAC0AC0EHdgRAIAAoAgAMAQsgAAshByAEQQRqIgggACACQef///8DSQR/IAQgAkEBdDYCDCAEIAIgA2o2AgQjAEEQayIDJAAgCCgCACAEQQxqIgkoAgBJIQogA0EQaiQAIAkgCCAKGygCACIDQQtPBH8gA0EQakFwcSIDIANBAWsiAyADQQtGGwVBCgtBAWoFQe////8HCxAwIAQoAgQhAyAEKAIIGiABBEAgAyAHIAEQIwsgAkEKRwRAIAcQGQsgACADNgIAIAAgACgCCEGAgICAeHEgBCgCCEH/////B3FyNgIIIAAgACgCCEGAgICAeHI2AgggBEEQaiQADAELECcACyAAIAE2AgQLIAECfyAALQALQQd2BEAgACgCAAwBCyAACyICaiAFEEAgACABIAVqIgAQMSAGQQA6AA8gACACaiAGLQAPOgAACyAGQRBqJAAMAQsCfyAALQALQQd2BEAgACgCAAwBCyAACyEEIwBBEGsiAiQAIAAgARAxIAJBADoADyABIARqIAItAA86AAAgAkEQaiQACwsGACAAEBkL0igBDH8jAEEQayIKJAACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEHs3gAoAgAiBkEQIABBC2pBeHEgAEELSRsiBUEDdiIAdiIBQQNxBEACQCABQX9zQQFxIABqIgJBA3QiAUGU3wBqIgAgAUGc3wBqKAIAIgEoAggiA0YEQEHs3gAgBkF+IAJ3cTYCAAwBCyADIAA2AgwgACADNgIICyABQQhqIQAgASACQQN0IgJBA3I2AgQgASACaiIBIAEoAgRBAXI2AgQMCgsgBUH03gAoAgAiB00NASABBEACQEECIAB0IgJBACACa3IgASAAdHFoIgFBA3QiAEGU3wBqIgIgAEG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AiQgACACNgIYIAAgATYCEA8LAkAgASADRgRAIAAoAhhBAkcNASAAIAI2AhgPCyAAQQE6ADYgAEECNgIYIAAgACgCJEEBajYCJAsLYwECfyMAQRBrIgIkACABIAAoAgQiA0EBdWohASAAKAIAIQAgAkEIaiABIANBAXEEfyABKAIAIABqKAIABSAACxEAACACKAIMIgAQAiACKAIMIgEEQCABEAMLIAJBEGokACAAC0MBAX8jAEEQayIBJAAgAEIANwIAIABBADYCCCABQRBqJAAgACAALQALQQd2BH8gACgCCEH/////B3FBAWsFQQoLECsLPQEBfyMAQRBrIgIkACACQQA6AA8DQCABBEAgACACLQAPOgAAIAFBAWshASAAQQFqIQAMAQsLIAJBEGokAAsaACAALQALQQd2BEAgACgCCBogACgCABAZCwvmAQEFfyMAQRBrIgUkACMAQSBrIgMkACMAQRBrIgQkACAEIAA2AgwgBCAAIAFqNgIIIAMgBCgCDDYCGCADIAQoAgg2AhwgBEEQaiQAIAMoAhghBCADKAIcIQYjAEEQayIBJAAgASAGNgIMIAIgBCAGIARrIgQQQyABIAIgBGo2AgggAyABKAIMNgIQIAMgASgCCDYCFCABQRBqJAAgAyAAIAMoAhAgAGtqNgIMIAMgAiADKAIUIAJrajYCCCAFIAMoAgw2AgggBSADKAIINgIMIANBIGokACAFKAIMIQcgBUEQaiQAIAcLDwAgAgRAIAAgASACEDILC/UCAQV/IwBBEGsiByQAIAIgAUF/c0Hv////B2pNBEACfyAALQALQQd2BEAgACgCAAwBCyAACyEIIAdBBGoiCSAAIAFB5////wNJBH8gByABQQF0NgIMIAcgASACajYCBCMAQRBrIgIkACAJKAIAIAdBDGoiCigCAEkhCyACQRBqJAAgCiAJIAsbKAIAIgJBC08EfyACQRBqQXBxIgIgAkEBayICIAJBC0YbBUEKC0EBagVB7////wcLEDAgBygCBCECIAcoAggaIAQEQCACIAggBBAjCyAFBEAgAiAEaiAGIAUQIwsgAyAEayEGIAMgBEcEQCACIARqIAVqIAQgCGogBhAjCyABQQpHBEAgCBAZCyAA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ACECAkADQEEAIABFDQIaIABB7M0AECAiA0UNASADKAIIIAEoAghBf3NxDQFBASABKAIMIAMoAgxBABAeDQIaIAEtAAhBAXFFDQEgASgCDCIARQ0BIABB7M0AECAiAQRAIAMoAgwhAAwBCwsgAEHczgAQICIARQ0AIAAgAygCDBA8IQILIAILIQUMAgsgA0HczgAQICIBBEAgAC0ACEEBcUUNAiABIAYoAgwQPCEFDAILIANBjM0AECAiAUUNASAGKAIMIgBFDQEgAEGMzQAQICIARQ0BIARBDGpBAEE0ECYaIARBATYCOCAEQX82AhQgBCABNgIQIAQgADYCCCAAIARBCGogAigCAEEBIAAoAgAoAhwRBgACQCAEKAIgIgBBAUcNACACKAIARQ0AIAIgBCgCGDYCAAsgAEEBRiEFDAELQQAhBQsgBEFAayQAIAULMQAgACABKAIIQQAQHgRAIAEgAiADED0PCyAAKAIIIgAgASACIAMgACgCACgCHBEGAAsYACAAIAEoAghBABAeBEAgASACIAMQPQsLnQEBAn8jAEFAaiIDJAACf0EBIAAgAUEAEB4NABpBACABRQ0AGkEAIAFBjM0AECAiAUUNABogA0EMakEAQTQQJhogA0EBNgI4IANBfzYCFCADIAA2AhAgAyABNgIIIAEgA0EIaiACKAIAQQEgASgCACgCHBEGACADKAIgIgBBAUYEQCACIAMoAhg2AgALIABBAUYLIQQgA0FAayQAIAQLCgAgACABQQAQHgtOAgF/AXwjAEEQayICJAAgAkEANgIMIAEoAgRB1M8AIAJBDGoQCSEDIAIoAgwiAQRAIAEQAQsgACADRAAAAAAAAAAAYjoAOCACQRBqJAALNwEBfyMAQRBrIgIkACACIAEtADg2AgggAEHUzwAgAkEIahAHNgIEIABB1NUANgIAIAJBEGokAAuoAQEFfyAAKAJUIgMoAgAhBSADKAIEIgQgACgCFCAAKAIcIgdrIgYgBCAGSRsiBgRAIAUgByAGECIaIAMgAygCACAGaiIFNgIAIAMgAygCBCAGayIENgIECyAEIAIgAiAESxsiBARAIAUgASAEECIaIAMgAygCACAEaiIFNgIAIAMgAygCBCAEazYCBAsgBUEAOgAAIAAgACgCLCIBNgIcIAAgATYCFCACC5wBAQJ/IwBBEGsiAiQAQcgAEBwhASAAKAIEIgAQAiACIAA2AgggAUHMLSACQQhqEAc2AgQgAUHU1QA2AgAgAUEBNgIcIAFB1NUANgIYIAFBATYCFCABQdTVADYCECABQQE2AgwgAUHU1QA2AgggAUEAOgAgIAFBADYCRCABQoCAgIAwNwI8IAFBADsANyABQQA7ACsgAkEQaiQAIAELigUCBn4CfyABIAEoAgBBB2pBeHEiAUEQajYCACAAIQkgASkDACEDIAEpAwghBSMAQSBrIgAkAAJAIAVC////////////AIMiBEKAgICAgIDAgDx9IARCgICAgICAwP/DAH1UBEAgBUIEhiADQjyIhCEEIANC//////////8PgyIDQoGAgICAgICACFoEQCAEQoGAgICAgICAwAB8IQIMAgsgBEKAgICAgICAgEB9IQIgA0KAgICAgICAgAhSDQEgAiAEQgGDfCECDAELIANQIARCgICAgICAwP//AFQgBEKAgICAgIDA//8AURtFBEAgBUIEhiADQjyIhEL/////////A4NCgICAgICAgPz/AIQhAgwBC0KAgICAgICA+P8AIQIgBEL///////+//8MAVg0AQgAhAiAEQjCIpyIBQZH3AEkNACADIQIgBUL///////8/g0KAgICAgIDAAIQiBCEGAkAgAUGB9wBrIghBwABxBEAgAyAIQUBqrYYhBkIAIQIMAQsgCEUNACAGIAitIgeGIAJBwAAgCGutiIQhBiACIAeGIQILIAAgAjcDECAAIAY3AxgCQEGB+AAgAWsiAUHAAHEEQCAEIAFBQGqtiCEDQgAhBAwBCyABRQ0AIARBwAAgAWuthiADIAGtIgKIhCEDIAQgAoghBAsgACADNwMAIAAgBDcDCCAAKQMIQgSGIAApAwAiA0I8iIQhAiAAKQMQIAApAxiEQgBSrSADQv//////////D4OEIgNCgYCAgICAgIAIWgRAIAJCAXwhAgwBCyADQoCAgICAgICACFINACACQgGDIAJ8IQILIABBIGokACAJIAIgBUKAgICAgICAgIB/g4S/OQMAC0ABAn8jAEEQayICJAAgAiABNgIMIAJ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hAAAALwAAACMAAAAkAAAAMAAAAAAAAAA8KQAAMQAAADIAAAAzAAAAU3Q5ZXhjZXB0aW9uAAAAAIAoAAAsKQAAAAAAAGgpAAAYAAAANAAAADUAAABTdDExbG9naWNfZXJyb3IAqCgAAFgpAAA8KQAAAAAAAJwpAAAYAAAANgAAADUAAABTdDEybGVuZ3RoX2Vycm9yAAAAAKgoAACIKQAAaCkAAFN0OXR5cGVfaW5mbwAAAACAKAAAqCkAQcDTAAsJCxUAAAAAAAAFAEHU0wALARsAQezTAAsOHAAAAB0AAABoKwAAAAQAQYTUAAsBAQBBlNQACwX/////CgBB2NQACwNgMQE=")||(Dt=$e,$e=g.locateFile?g.locateFile(Dt,Q):Q+Dt);var Ki=P=>{for(;P.length>0;)P.shift()(g)};g.noExitRuntime;function Ur(P){this.excPtr=P,this.ptr=P-24,this.set_type=function(F){QA[this.ptr+4>>2]=F},this.get_type=function(){return QA[this.ptr+4>>2]},this.set_destructor=function(F){QA[this.ptr+8>>2]=F},this.get_destructor=function(){return QA[this.ptr+8>>2]},this.set_caught=function(F){F=F?1:0,AA[this.ptr+12|0]=F},this.get_caught=function(){return AA[this.ptr+12|0]!=0},this.set_rethrown=function(F){F=F?1:0,AA[this.ptr+13|0]=F},this.get_rethrown=function(){return AA[this.ptr+13|0]!=0},this.init=function(F,EA){this.set_adjusted_ptr(0),this.set_type(F),this.set_destructor(EA)},this.set_adjusted_ptr=function(F){QA[this.ptr+16>>2]=F},this.get_adjusted_ptr=function(){return QA[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Cs(this.get_type()))return QA[this.excPtr>>2];var F=this.get_adjusted_ptr();return F!==0?F:this.excPtr}}var Er,no,Kn,Xi=P=>{for(var F="",EA=P;z[EA];)F+=Er[z[EA++]];return F},yr={},lr={},Ni={},wt=P=>{throw new no(P)},Ji=P=>{throw new Kn(P)},Di=(P,F,EA)=>{function RA(ge){var we=EA(ge);we.length!==P.length&&Ji("Mismatched type converter count");for(var _e=0;_e{lr.hasOwnProperty(ge)?GA[we]=lr[ge]:(WA.push(ge),yr.hasOwnProperty(ge)||(yr[ge]=[]),yr[ge].push(()=>{GA[we]=lr[ge],++Ce===WA.length&&RA(GA)}))}),WA.length===0&&RA(GA)};function ar(P,F,EA={}){if(!("argPackAdvance"in F))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(RA,GA,WA={}){var Ce=GA.name;if(RA||wt(`type "${Ce}" must have a positive integer typeid pointer`),lr.hasOwnProperty(RA)){if(WA.ignoreDuplicateRegistrations)return;wt(`Cannot register type '${Ce}' twice`)}if(lr[RA]=GA,delete Ni[RA],yr.hasOwnProperty(RA)){var ge=yr[RA];delete yr[RA],ge.forEach(we=>we())}}(P,F,EA)}var MA,YA=P=>{wt(P.$$.ptrType.registeredClass.name+" instance already deleted")},pe=!1,st=P=>{},Te=P=>{P.count.value-=1,P.count.value===0&&(F=>{F.smartPtr?F.smartPtrType.rawDestructor(F.smartPtr):F.ptrType.registeredClass.rawDestructor(F.ptr)})(P)},be=(P,F,EA)=>{if(F===EA)return P;if(EA.baseClass===void 0)return null;var RA=be(P,F,EA.baseClass);return RA===null?null:EA.downcast(RA)},yt={},ht=()=>Object.keys(zt).length,ae=()=>{var P=[];for(var F in zt)zt.hasOwnProperty(F)&&P.push(zt[F]);return P},ye=[],Xe=()=>{for(;ye.length;){var P=ye.pop();P.$$.deleteScheduled=!1,P.delete()}},ot=P=>{MA=P,ye.length&&MA&&MA(Xe)},zt={},yi=(P,F)=>(F=((EA,RA)=>{for(RA===void 0&&wt("ptr should not be undefined");EA.baseClass;)RA=EA.upcast(RA),EA=EA.baseClass;return RA})(P,F),zt[F]),Hi=(P,F)=>(F.ptrType&&F.ptr||Ji("makeClassHandle requires ptr and ptrType"),!!F.smartPtrType!=!!F.smartPtr&&Ji("Both smartPtrType and smartPtr must be specified"),F.count={value:1},ji(Object.create(P,{$$:{value:F}})));function Ei(P){var F=this.getPointee(P);if(!F)return this.destructor(P),null;var EA=yi(this.registeredClass,F);if(EA!==void 0){if(EA.$$.count.value===0)return EA.$$.ptr=F,EA.$$.smartPtr=P,EA.clone();var RA=EA.clone();return this.destructor(P),RA}function GA(){return this.isSmartPointer?Hi(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:F,smartPtrType:this,smartPtr:P}):Hi(this.registeredClass.instancePrototype,{ptrType:this,ptr:P})}var WA,Ce=this.registeredClass.getActualType(F),ge=yt[Ce];if(!ge)return GA.call(this);WA=this.isConst?ge.constPointerType:ge.pointerType;var we=be(F,this.registeredClass,WA.registeredClass);return we===null?GA.call(this):this.isSmartPointer?Hi(WA.registeredClass.instancePrototype,{ptrType:WA,ptr:we,smartPtrType:this,smartPtr:P}):Hi(WA.registeredClass.instancePrototype,{ptrType:WA,ptr:we})}var ji=P=>typeof FinalizationRegistry>"u"?(ji=F=>F,P):(pe=new FinalizationRegistry(F=>{Te(F.$$)}),st=F=>pe.unregister(F),(ji=F=>{var EA=F.$$;if(EA.smartPtr){var RA={$$:EA};pe.register(F,RA,F)}return F})(P));function Xo(){}var sr=(P,F)=>Object.defineProperty(F,"name",{value:P}),Lo=(P,F,EA)=>{if(P[F].overloadTable===void 0){var RA=P[F];P[F]=function(){return P[F].overloadTable.hasOwnProperty(arguments.length)||wt(`Function '${EA}' called with an invalid number of arguments (${arguments.length}) - expects one of (${P[F].overloadTable})!`),P[F].overloadTable[arguments.length].apply(this,arguments)},P[F].overloadTable=[],P[F].overloadTable[RA.argCount]=RA}};function Nr(P,F,EA,RA,GA,WA,Ce,ge){this.name=P,this.constructor=F,this.instancePrototype=EA,this.rawDestructor=RA,this.baseClass=GA,this.getActualType=WA,this.upcast=Ce,this.downcast=ge,this.pureVirtualFunctions=[]}var Vo=(P,F,EA)=>{for(;F!==EA;)F.upcast||wt(`Expected null or instance of ${EA.name}, got an instance of ${F.name}`),P=F.upcast(P),F=F.baseClass;return P};function et(P,F){if(F===null)return this.isReference&&wt(`null is not a valid ${this.name}`),0;F.$$||wt(`Cannot pass "${ao(F)}" as a ${this.name}`),F.$$.ptr||wt(`Cannot pass deleted object as a pointer of type ${this.name}`);var EA=F.$$.ptrType.registeredClass;return Vo(F.$$.ptr,EA,this.registeredClass)}function Kr(P,F){var EA;if(F===null)return this.isReference&&wt(`null is not a valid ${this.name}`),this.isSmartPointer?(EA=this.rawConstructor(),P!==null&&P.push(this.rawDestructor,EA),EA):0;F.$$||wt(`Cannot pass "${ao(F)}" as a ${this.name}`),F.$$.ptr||wt(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&F.$$.ptrType.isConst&&wt(`Cannot convert argument of type ${F.$$.smartPtrType?F.$$.smartPtrType.name:F.$$.ptrType.name} to parameter type ${this.name}`);var RA=F.$$.ptrType.registeredClass;if(EA=Vo(F.$$.ptr,RA,this.registeredClass),this.isSmartPointer)switch(F.$$.smartPtr===void 0&&wt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:F.$$.smartPtrType===this?EA=F.$$.smartPtr:wt(`Cannot convert argument of type ${F.$$.smartPtrType?F.$$.smartPtrType.name:F.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:EA=F.$$.smartPtr;break;case 2:if(F.$$.smartPtrType===this)EA=F.$$.smartPtr;else{var GA=F.clone();EA=this.rawShare(EA,gr.toHandle(()=>GA.delete())),P!==null&&P.push(this.rawDestructor,EA)}break;default:wt("Unsupporting sharing policy")}return EA}function Qn(P,F){if(F===null)return this.isReference&&wt(`null is not a valid ${this.name}`),0;F.$$||wt(`Cannot pass "${ao(F)}" as a ${this.name}`),F.$$.ptr||wt(`Cannot pass deleted object as a pointer of type ${this.name}`),F.$$.ptrType.isConst&&wt(`Cannot convert argument of type ${F.$$.ptrType.name} to parameter type ${this.name}`);var EA=F.$$.ptrType.registeredClass;return Vo(F.$$.ptr,EA,this.registeredClass)}function ho(P){return this.fromWireType(QA[P>>2])}function jn(P,F,EA,RA,GA,WA,Ce,ge,we,_e,Ke){this.name=P,this.registeredClass=F,this.isReference=EA,this.isConst=RA,this.isSmartPointer=GA,this.pointeeType=WA,this.sharingPolicy=Ce,this.rawGetPointee=ge,this.rawConstructor=we,this.rawShare=_e,this.rawDestructor=Ke,GA||F.baseClass!==void 0?this.toWireType=Kr:RA?(this.toWireType=et,this.destructorFunction=null):(this.toWireType=Qn,this.destructorFunction=null)}var $t,$r,On=[],An=P=>{var F=On[P];return F||(P>=On.length&&(On.length=P+1),On[P]=F=$t.get(P)),F},Tr=(P,F,EA)=>P.includes("j")?((RA,GA,WA)=>{var Ce=g["dynCall_"+RA];return WA&&WA.length?Ce.apply(null,[GA].concat(WA)):Ce.call(null,GA)})(P,F,EA):An(F).apply(null,EA),ei=(P,F)=>{var EA,RA,GA,WA=(P=Xi(P)).includes("j")?(EA=P,RA=F,GA=[],function(){return GA.length=0,Object.assign(GA,arguments),Tr(EA,RA,GA)}):An(F);return typeof WA!="function"&&wt(`unknown function pointer with signature ${P}: ${F}`),WA},Es=P=>{var F=Ba(P),EA=Xi(F);return Mr(F),EA},jr=(P,F)=>{var EA=[],RA={};throw F.forEach(function GA(WA){RA[WA]||lr[WA]||(Ni[WA]?Ni[WA].forEach(GA):(EA.push(WA),RA[WA]=!0))}),new $r(`${P}: `+EA.map(Es).join([", "]))},Gr=(P,F)=>{for(var EA=[],RA=0;RA>2]);return EA},$o=P=>{for(;P.length;){var F=P.pop();P.pop()(F)}};function sn(P,F,EA,RA,GA,WA){var Ce=F.length;Ce<2&&wt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var ge=F[1]!==null&&EA!==null,we=!1,_e=1;_e(P instanceof Object||wt(`${EA} with invalid "this": ${P}`),P instanceof F.registeredClass.constructor||wt(`${EA} incompatible with "this" of type ${P.constructor.name}`),P.$$.ptr||wt(`cannot call emscripten binding method ${EA} on deleted object`),Vo(P.$$.ptr,P.$$.ptrType.registeredClass,F.registeredClass));function hn(){this.allocated=[void 0],this.freelist=[]}var Gi=new hn,pn=P=>{P>=Gi.reserved&&--Gi.get(P).refcount===0&&Gi.free(P)},nI=()=>{for(var P=0,F=Gi.reserved;F(P||wt("Cannot use deleted val. handle = "+P),Gi.get(P).value),toHandle:P=>{switch(P){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return Gi.allocate({refcount:1,value:P})}}};function gn(P){return this.fromWireType(X[P>>2])}var Yo,Tg,So,ao=P=>{if(P===null)return"null";var F=typeof P;return F==="object"||F==="array"||F==="function"?P.toString():""+P},lE=(P,F)=>{switch(F){case 4:return function(EA){return this.fromWireType(wA[EA>>2])};case 8:return function(EA){return this.fromWireType(HA[EA>>3])};default:throw new TypeError(`invalid float width (${F}): ${P}`)}},Ta=(P,F,EA)=>{switch(F){case 1:return EA?RA=>AA[RA|0]:RA=>z[RA|0];case 2:return EA?RA=>sA[RA>>1]:RA=>eA[RA>>1];case 4:return EA?RA=>X[RA>>2]:RA=>QA[RA>>2];default:throw new TypeError(`invalid integer width (${F}): ${P}`)}},po=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,Ja=(P,F,EA)=>{for(var RA=F+EA,GA=F;P[GA]&&!(GA>=RA);)++GA;if(GA-F>16&&P.buffer&&po)return po.decode(P.subarray(F,GA));for(var WA="";F>10,56320|1023&_e)}}else WA+=String.fromCharCode((31&Ce)<<6|ge)}else WA+=String.fromCharCode(Ce)}return WA},Mc=(P,F)=>P?Ja(z,P,F):"",Qr=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Fo=(P,F)=>{for(var EA=P,RA=EA>>1,GA=RA+F/2;!(RA>=GA)&&eA[RA];)++RA;if((EA=RA<<1)-P>32&&Qr)return Qr.decode(z.subarray(P,EA));for(var WA="",Ce=0;!(Ce>=F/2);++Ce){var ge=sA[P+2*Ce>>1];if(ge==0)break;WA+=String.fromCharCode(ge)}return WA},$s=(P,F,EA)=>{if(EA===void 0&&(EA=2147483647),EA<2)return 0;for(var RA=F,GA=(EA-=2)<2*P.length?EA/2:P.length,WA=0;WA>1]=Ce,F+=2}return sA[F>>1]=0,F-RA},Ha=P=>2*P.length,Gs=(P,F)=>{for(var EA=0,RA="";!(EA>=F/4);){var GA=X[P+4*EA>>2];if(GA==0)break;if(++EA,GA>=65536){var WA=GA-65536;RA+=String.fromCharCode(55296|WA>>10,56320|1023&WA)}else RA+=String.fromCharCode(GA)}return RA},Ga=(P,F,EA)=>{if(EA===void 0&&(EA=2147483647),EA<4)return 0;for(var RA=F,GA=RA+EA-4,WA=0;WA=55296&&Ce<=57343&&(Ce=65536+((1023&Ce)<<10)|1023&P.charCodeAt(++WA)),X[F>>2]=Ce,(F+=4)+4>GA)break}return X[F>>2]=0,F-RA},Rr=P=>{for(var F=0,EA=0;EA=55296&&RA<=57343&&++EA,F+=4}return F},Ia=(P,F)=>{var EA=lr[P];return EA===void 0&&wt(F+" has unknown type "+Es(P)),EA},fo=(P,F,EA)=>{var RA=[],GA=P.toWireType(RA,EA);return RA.length&&(QA[F>>2]=gr.toHandle(RA)),GA},aI={},en=[],qo=Reflect.construct,Gg=[null,[],[]],kg=(P,F)=>{var EA=Gg[P];F===0||F===10?((P===1?M:v)(Ja(EA,0)),EA.length=0):EA.push(F)};(()=>{for(var P=new Array(256),F=0;F<256;++F)P[F]=String.fromCharCode(F);Er=P})(),no=g.BindingError=class extends Error{constructor(P){super(P),this.name="BindingError"}},Kn=g.InternalError=class extends Error{constructor(P){super(P),this.name="InternalError"}},Object.assign(Xo.prototype,{isAliasOf(P){if(!(this instanceof Xo)||!(P instanceof Xo))return!1;var F=this.$$.ptrType.registeredClass,EA=this.$$.ptr;P.$$=P.$$;for(var RA=P.$$.ptrType.registeredClass,GA=P.$$.ptr;F.baseClass;)EA=F.upcast(EA),F=F.baseClass;for(;RA.baseClass;)GA=RA.upcast(GA),RA=RA.baseClass;return F===RA&&EA===GA},clone(){if(this.$$.ptr||YA(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var P,F=ji(Object.create(Object.getPrototypeOf(this),{$$:{value:(P=this.$$,{count:P.count,deleteScheduled:P.deleteScheduled,preservePointerOnDelete:P.preservePointerOnDelete,ptr:P.ptr,ptrType:P.ptrType,smartPtr:P.smartPtr,smartPtrType:P.smartPtrType})}}));return F.$$.count.value+=1,F.$$.deleteScheduled=!1,F},delete(){this.$$.ptr||YA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&wt("Object already scheduled for deletion"),st(this),Te(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||YA(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&wt("Object already scheduled for deletion"),ye.push(this),ye.length===1&&MA&&MA(Xe),this.$$.deleteScheduled=!0,this}}),g.getInheritedInstanceCount=ht,g.getLiveInheritedInstances=ae,g.flushPendingDeletes=Xe,g.setDelayFunction=ot,Object.assign(jn.prototype,{getPointee(P){return this.rawGetPointee&&(P=this.rawGetPointee(P)),P},destructor(P){this.rawDestructor&&this.rawDestructor(P)},argPackAdvance:8,readValueFromPointer:ho,deleteObject(P){P!==null&&P.delete()},fromWireType:Ei}),$r=g.UnboundTypeError=(Yo=Error,(So=sr(Tg="UnboundTypeError",function(P){this.name=Tg,this.message=P;var F=new Error(P).stack;F!==void 0&&(this.stack=this.toString()+` +`+F.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(Yo.prototype),So.prototype.constructor=So,So.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},So),Object.assign(hn.prototype,{get(P){return this.allocated[P]},has(P){return this.allocated[P]!==void 0},allocate(P){var F=this.freelist.pop()||this.allocated.length;return this.allocated[F]=P,F},free(P){this.allocated[P]=void 0,this.freelist.push(P)}}),Gi.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),Gi.reserved=Gi.allocated.length,g.count_emval_handles=nI;var fn,ls={w:(P,F,EA)=>{throw new Ur(P).init(F,EA),P},q:(P,F,EA,RA,GA)=>{},u:(P,F,EA,RA)=>{ar(P,{name:F=Xi(F),fromWireType:function(GA){return!!GA},toWireType:function(GA,WA){return WA?EA:RA},argPackAdvance:8,readValueFromPointer:function(GA){return this.fromWireType(z[GA])},destructorFunction:null})},y:(P,F,EA,RA,GA,WA,Ce,ge,we,_e,Ke,Bt,Rt)=>{Ke=Xi(Ke),WA=ei(GA,WA),ge&&(ge=ei(Ce,ge)),_e&&(_e=ei(we,_e)),Rt=ei(Bt,Rt);var Ye=(nt=>{if(nt===void 0)return"_unknown";var ii=(nt=nt.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return ii>=48&&ii<=57?`_${nt}`:nt})(Ke);((nt,ii,oi)=>{g.hasOwnProperty(nt)?(wt(`Cannot register public name '${nt}' twice`),Lo(g,nt,nt),g.hasOwnProperty(oi)&&wt(`Cannot register multiple overloads of a function with the same number of arguments (${oi})!`),g[nt].overloadTable[oi]=ii):g[nt]=ii})(Ye,function(){jr(`Cannot construct ${Ke} due to unbound types`,[RA])}),Di([P,F,EA],RA?[RA]:[],function(nt){var ii,oi;nt=nt[0],oi=RA?(ii=nt.registeredClass).instancePrototype:Xo.prototype;var Ko=sr(Ke,function(){if(Object.getPrototypeOf(this)!==Kt)throw new no("Use 'new' to construct "+Ke);if(ro.constructor_body===void 0)throw new no(Ke+" has no accessible constructor");var xr=ro.constructor_body[arguments.length];if(xr===void 0)throw new no(`Tried to invoke ctor of ${Ke} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(ro.constructor_body).toString()}) parameters instead!`);return xr.apply(this,arguments)}),Kt=Object.create(oi,{constructor:{value:Ko}});Ko.prototype=Kt;var ro=new Nr(Ke,Ko,Kt,Rt,ii,WA,ge,_e);ro.baseClass&&(ro.baseClass.__derivedClasses===void 0&&(ro.baseClass.__derivedClasses=[]),ro.baseClass.__derivedClasses.push(ro));var ks=new jn(Ke,ro,!0,!1,!1),Zr=new jn(Ke+"*",ro,!1,!1,!1),In=new jn(Ke+" const*",ro,!1,!0,!1);return yt[P]={pointerType:Zr,constPointerType:In},((xr,sI,jo)=>{g.hasOwnProperty(xr)||Ji("Replacing nonexistant public symbol"),g[xr].overloadTable!==void 0&&jo!==void 0?g[xr].overloadTable[jo]=sI:(g[xr]=sI,g[xr].argCount=jo)})(Ye,Ko),[ks,Zr,In]})},x:(P,F,EA,RA,GA,WA)=>{var Ce=Gr(F,EA);GA=ei(RA,GA),Di([],[P],function(ge){var we=`constructor ${(ge=ge[0]).name}`;if(ge.registeredClass.constructor_body===void 0&&(ge.registeredClass.constructor_body=[]),ge.registeredClass.constructor_body[F-1]!==void 0)throw new no(`Cannot register multiple constructors with identical number of parameters (${F-1}) for class '${ge.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return ge.registeredClass.constructor_body[F-1]=()=>{jr(`Cannot construct ${ge.name} due to unbound types`,Ce)},Di([],Ce,_e=>(_e.splice(1,0,null),ge.registeredClass.constructor_body[F-1]=sn(we,_e,null,GA,WA),[])),[]})},i:(P,F,EA,RA,GA,WA,Ce,ge,we)=>{var _e=Gr(EA,RA);F=(Ke=>{const Bt=(Ke=Ke.trim()).indexOf("(");return Bt!==-1?Ke.substr(0,Bt):Ke})(F=Xi(F)),WA=ei(GA,WA),Di([],[P],function(Ke){var Bt=`${(Ke=Ke[0]).name}.${F}`;function Rt(){jr(`Cannot call ${Bt} due to unbound types`,_e)}F.startsWith("@@")&&(F=Symbol[F.substring(2)]),ge&&Ke.registeredClass.pureVirtualFunctions.push(F);var Ye=Ke.registeredClass.instancePrototype,nt=Ye[F];return nt===void 0||nt.overloadTable===void 0&&nt.className!==Ke.name&&nt.argCount===EA-2?(Rt.argCount=EA-2,Rt.className=Ke.name,Ye[F]=Rt):(Lo(Ye,F,Bt),Ye[F].overloadTable[EA-2]=Rt),Di([],_e,function(ii){var oi=sn(Bt,ii,Ke,WA,Ce);return Ye[F].overloadTable===void 0?(oi.argCount=EA-2,Ye[F]=oi):Ye[F].overloadTable[EA-2]=oi,[]}),[]})},k:(P,F,EA,RA,GA,WA,Ce,ge,we,_e)=>{F=Xi(F),GA=ei(RA,GA),Di([],[P],function(Ke){var Bt=`${(Ke=Ke[0]).name}.${F}`,Rt={get(){jr(`Cannot access ${Bt} due to unbound types`,[EA,Ce])},enumerable:!0,configurable:!0};return Rt.set=we?()=>jr(`Cannot access ${Bt} due to unbound types`,[EA,Ce]):Ye=>wt(Bt+" is a read-only property"),Object.defineProperty(Ke.registeredClass.instancePrototype,F,Rt),Di([],we?[EA,Ce]:[EA],function(Ye){var nt=Ye[0],ii={get(){var Ko=dn(this,Ke,Bt+" getter");return nt.fromWireType(GA(WA,Ko))},enumerable:!0};if(we){we=ei(ge,we);var oi=Ye[1];ii.set=function(Ko){var Kt=dn(this,Ke,Bt+" setter"),ro=[];we(_e,Kt,oi.toWireType(ro,Ko)),$o(ro)}}return Object.defineProperty(Ke.registeredClass.instancePrototype,F,ii),[]}),[]})},t:(P,F)=>{ar(P,{name:F=Xi(F),fromWireType:EA=>{var RA=gr.toValue(EA);return pn(EA),RA},toWireType:(EA,RA)=>gr.toHandle(RA),argPackAdvance:8,readValueFromPointer:gn,destructorFunction:null})},p:(P,F,EA)=>{ar(P,{name:F=Xi(F),fromWireType:RA=>RA,toWireType:(RA,GA)=>GA,argPackAdvance:8,readValueFromPointer:lE(F,EA),destructorFunction:null})},g:(P,F,EA,RA,GA)=>{F=Xi(F);var WA=we=>we;if(RA===0){var Ce=32-8*EA;WA=we=>we<>>Ce}var ge=F.includes("unsigned");ar(P,{name:F,fromWireType:WA,toWireType:ge?function(we,_e){return this.name,_e>>>0}:function(we,_e){return this.name,_e},argPackAdvance:8,readValueFromPointer:Ta(F,EA,RA!==0),destructorFunction:null})},a:(P,F,EA)=>{var RA=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][F];function GA(WA){var Ce=QA[WA>>2],ge=QA[WA+4>>2];return new RA(AA.buffer,ge,Ce)}ar(P,{name:EA=Xi(EA),fromWireType:GA,argPackAdvance:8,readValueFromPointer:GA},{ignoreDuplicateRegistrations:!0})},o:(P,F)=>{var EA=(F=Xi(F))==="std::string";ar(P,{name:F,fromWireType(RA){var GA,WA=QA[RA>>2],Ce=RA+4;if(EA)for(var ge=Ce,we=0;we<=WA;++we){var _e=Ce+we;if(we==WA||z[_e]==0){var Ke=Mc(ge,_e-ge);GA===void 0?GA=Ke:(GA+="\0",GA+=Ke),ge=_e+1}}else{var Bt=new Array(WA);for(we=0;we{for(var Rt=0,Ye=0;Ye=55296&&nt<=57343?(Rt+=4,++Ye):Rt+=3}return Rt})(GA):GA.length;var ge=Po(4+WA+1),we=ge+4;if(QA[ge>>2]=WA,EA&&Ce)((Bt,Rt,Ye,nt)=>{if(!(nt>0))return 0;for(var ii=Ye,oi=Ye+nt-1,Ko=0;Ko=55296&&Kt<=57343&&(Kt=65536+((1023&Kt)<<10)|1023&Bt.charCodeAt(++Ko)),Kt<=127){if(Ye>=oi)break;Rt[Ye++]=Kt}else if(Kt<=2047){if(Ye+1>=oi)break;Rt[Ye++]=192|Kt>>6,Rt[Ye++]=128|63&Kt}else if(Kt<=65535){if(Ye+2>=oi)break;Rt[Ye++]=224|Kt>>12,Rt[Ye++]=128|Kt>>6&63,Rt[Ye++]=128|63&Kt}else{if(Ye+3>=oi)break;Rt[Ye++]=240|Kt>>18,Rt[Ye++]=128|Kt>>12&63,Rt[Ye++]=128|Kt>>6&63,Rt[Ye++]=128|63&Kt}}Rt[Ye]=0})(GA,z,we,WA+1);else if(Ce)for(var _e=0;_e255&&(Mr(we),wt("String has UTF-16 code units that do not fit in 8 bits")),z[we+_e]=Ke}else for(_e=0;_e{var RA,GA,WA,Ce,ge;EA=Xi(EA),F===2?(RA=Fo,GA=$s,Ce=Ha,WA=()=>eA,ge=1):F===4&&(RA=Gs,GA=Ga,Ce=Rr,WA=()=>QA,ge=2),ar(P,{name:EA,fromWireType:we=>{for(var _e,Ke=QA[we>>2],Bt=WA(),Rt=we+4,Ye=0;Ye<=Ke;++Ye){var nt=we+4+Ye*F;if(Ye==Ke||Bt[nt>>ge]==0){var ii=RA(Rt,nt-Rt);_e===void 0?_e=ii:(_e+="\0",_e+=ii),Rt=nt+F}}return Mr(we),_e},toWireType:(we,_e)=>{typeof _e!="string"&&wt(`Cannot pass non-string to C++ string type ${EA}`);var Ke=Ce(_e),Bt=Po(4+Ke+F);return QA[Bt>>2]=Ke>>ge,GA(_e,Bt+4,Ke+F),we!==null&&we.push(Mr,Bt),Bt},argPackAdvance:8,readValueFromPointer:gn,destructorFunction(we){Mr(we)}})},v:(P,F)=>{ar(P,{isVoid:!0,name:F=Xi(F),argPackAdvance:0,fromWireType:()=>{},toWireType:(EA,RA)=>{}})},j:(P,F,EA)=>(P=gr.toValue(P),F=Ia(F,"emval::as"),fo(F,EA,P)),e:(P,F,EA,RA,GA)=>{var WA,Ce;return(P=en[P])(F=gr.toValue(F),F[EA=(Ce=aI[WA=EA])===void 0?Xi(WA):Ce],RA,GA)},d:pn,f:(P,F,EA)=>{var RA=((_e,Ke)=>{for(var Bt=new Array(_e),Rt=0;Rt<_e;++Rt)Bt[Rt]=Ia(QA[Ke+4*Rt>>2],"parameter "+Rt);return Bt})(P,F),GA=RA.shift();P--;var WA,Ce,ge=new Array(P),we=`methodCaller<(${RA.map(_e=>_e.name).join(", ")}) => ${GA.name}>`;return WA=sr(we,(_e,Ke,Bt,Rt)=>{for(var Ye=0,nt=0;nt{P>4&&(Gi.get(P).refcount+=1)},b:P=>{var F=gr.toValue(P);$o(F),pn(P)},h:(P,F)=>{var EA=(P=Ia(P,"_emval_take_value")).readValueFromPointer(F);return gr.toHandle(EA)},m:()=>{Je("")},s:(P,F,EA)=>z.copyWithin(P,F,F+EA),r:P=>{z.length,Je("OOM")},n:(P,F,EA,RA)=>{for(var GA=0,WA=0;WA>2],ge=QA[F+4>>2];F+=8;for(var we=0;we>2]=GA,0}},Or=function(){var P={a:ls};function F(EA,RA){var GA,WA;return Or=EA.exports,m=Or.z,GA=m.buffer,g.HEAP8=AA=new Int8Array(GA),g.HEAP16=sA=new Int16Array(GA),g.HEAPU8=z=new Uint8Array(GA),g.HEAPU16=eA=new Uint16Array(GA),g.HEAP32=X=new Int32Array(GA),g.HEAPU32=QA=new Uint32Array(GA),g.HEAPF32=wA=new Float32Array(GA),g.HEAPF64=HA=new Float64Array(GA),$t=Or.C,WA=Or.A,jA.unshift(WA),function(){if(qe--,g.monitorRunDependencies&&g.monitorRunDependencies(qe),qe==0&&Et){var Ce=Et;Et=null,Ce()}}(),Or}if(qe++,g.monitorRunDependencies&&g.monitorRunDependencies(qe),g.instantiateWasm)try{return g.instantiateWasm(P,F)}catch(EA){v(`Module.instantiateWasm callback failed with error: ${EA}`),s(EA)}return ai(0,$e,P,function(EA){F(EA.instance)}).catch(s),{}}(),Po=P=>(Po=Or.B)(P),Ba=P=>(Ba=Or.D)(P),Mr=P=>(Mr=Or.E)(P),Cs=P=>(Cs=Or.F)(P);g.dynCall_jiji=(P,F,EA,RA,GA)=>(g.dynCall_jiji=Or.G)(P,F,EA,RA,GA),g._vertexShaderSource=10688;function Va(){function P(){fn||(fn=!0,g.calledRun=!0,qA||(Ki(jA),r(g),g.onRuntimeInitialized&&g.onRuntimeInitialized(),function(){if(g.postRun)for(typeof g.postRun=="function"&&(g.postRun=[g.postRun]);g.postRun.length;)Me(g.postRun.shift());Ki(Ve)}()))}qe>0||(function(){if(g.preRun)for(typeof g.preRun=="function"&&(g.preRun=[g.preRun]);g.preRun.length;)ze(g.preRun.shift());Ki(ue)}(),qe>0||(g.setStatus?(g.setStatus("Running..."),setTimeout(function(){setTimeout(function(){g.setStatus("")},1),P()},1)):P()))}if(Et=function P(){fn||Va(),fn||(Et=P)},g.preInit)for(typeof g.preInit=="function"&&(g.preInit=[g.preInit]);g.preInit.length>0;)g.preInit.pop()();return Va(),i.ready}})(),ssA=asA,OK=0,W6=class z6{constructor(i){this.core=i,TG(this,"seq"),TG(this,"_core"),TG(this,"log"),TG(this,"beautyParams"),OK+=1,this.seq=OK,this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${OK}`}),this.log.info("created")}getName(){return z6.Name}getAlias(){return"bb"}getValidateRule(i){switch(i){case"start":case"update":return rsA(this._core);case"stop":return nsA(this._core)}}getGroup(){return"bb"}async start(i){this._core.room.videoManager.Wasm||(this._core.room.videoManager.Wasm=await ssA()),this._core.room.videoManager.renderMode="webgl";const r=this._core.utils.isUndefined(i.beauty)?.5:i.beauty,s=this._core.utils.isUndefined(i.brightness)?.5:i.brightness,g=this._core.utils.isUndefined(i.ruddy)?.5:i.ruddy;return this._core.room.videoManager.setBeautyParams({beauty:r,brightness:s,ruddy:g})}async update(i){const r=this._core.utils.isUndefined(i.beauty)?.5:i.beauty,s=this._core.utils.isUndefined(i.brightness)?.5:i.brightness,g=this._core.utils.isUndefined(i.ruddy)?.5:i.ruddy;return this._core.room.videoManager.setBeautyParams({beauty:r,brightness:s,ruddy:g})}async stop(){return this._core.room.videoManager.renderMode="auto",this._core.room.videoManager.stopBeauty()}destroy(){this._core.room.videoManager.renderMode="auto"}};TG(W6,"Name","BasicBeauty");var Z6=W6,gsA=Z6;const IsA=Object.freeze(Object.defineProperty({__proto__:null,BasicBeauty:Z6,default:gsA},Symbol.toStringTag,{value:"Module"})),csA=Mk(IsA);var EsA=Object.defineProperty,lsA=(t,i,r)=>i in t?EsA(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,v2=(t,i,r)=>lsA(t,typeof i!="symbol"?i+"":i,r),CsA={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}}},BsA={name:"option",required:!0,properties:{transcriberRobotId:{type:"string",required:!0}}},usA=new Set([2002,4003]),X6=class $6{constructor(i){this.core=i,v2(this,"disableRandomCall",!0),v2(this,"activeTranscriberMap",new Map),v2(this,"_log"),this._log=this.core.log.createChild({id:`${this.getAlias()}`})}getName(){return $6.Name}getAlias(){return"rt-trans"}getGroup(){return"*"}getValidateRule(i){switch(i){case"start":return CsA;case"update":return{};case"stop":return BsA}}async start(i){var r;const{RtcError:s,ErrorCode:g}=this.core.errorModule;if(!this.core.room.sendSignalMessage)throw new s({code:g.ENV_NOT_SUPPORTED});const{sourceLanguage:B,translationLanguages:Q,userIdsToTranscribe:f="all",transcriberRobotId:m}=i,M=m||`transcriber_${this.core.room.roomId}_robot_${this.core.room.userId}`,v={sdkappid:this.core.room.sdkAppId,roomid:String(this.core.room.roomId),roomType:this.core.room.useStringRoomId?1:0,agentParam:{cdnRobotUserid:M,lifecycleUserid:this.core.room.userId,maxIdletime:30},subscribeParams:{subUsers:[]},asrParams:{lang:B,vadSilenceTime:1e3},translationParams:{mode:1,targetLangs:[""]}};Q&&Q.length>0&&(v.translationParams.mode=1,v.translationParams.targetLangs=Array.isArray(Q)?Q:[Q]),f==="all"?v.subscribeParams.subUsers=[]:Array.isArray(f)?v.subscribeParams.subUsers=f.map(U=>({userId:U,roomType:this.core.room.useStringRoomId?1:0,roomid:String(this.core.room.roomId)})):f&&(v.subscribeParams.subUsers=[{userId:f,roomType:this.core.room.useStringRoomId?1:0,roomid:String(this.core.room.roomId)}]);try{this._log.info(`start_cloud_transcription ${JSON.stringify(v)}`);const U=await this.core.room.sendSignalMessage({command:"start_cloud_transcription",responseCommand:String(8268),data:v,retries:0}),{code:AA,data:z}=U.data;if(AA!==0){const eA=((r=U.data)==null?void 0:r.message)||"";throw this._log.error("start_cloud_transcription failed",{extraCode:AA,reason:eA,data:z}),new s({code:g.SERVER_ERROR,extraCode:AA,message:eA})}const{taskId:sA}=z;if(!sA)throw this._log.error("taskId is required",{data:U.data}),new s({code:g.SERVER_ERROR,message:"taskId is required"});return this.activeTranscriberMap.set(sA,i),this._log.info(`start_cloud_transcription success ${sA}, activeSize: ${this.activeTranscriberMap.size}`),sA}catch(U){throw this._log.error("start_cloud_transcription failed",{error:U}),U}}async update(){}async stop({transcriberRobotId:i}){var r;const{RtcError:s,ErrorCode:g}=this.core.errorModule;if(!this.core.room.sendSignalMessage)throw new s({code:g.ENV_NOT_SUPPORTED});try{const B=await this.core.room.sendSignalMessage({command:"stop_cloud_transcription",responseCommand:String(8270),data:{taskId:i},retries:3});if(B.data.code!==0){const Q=B.data.code,f=((r=B.data)==null?void 0:r.message)||"";if(!usA.has(Q))throw this._log.error("stop_cloud_transcription failed",{extraCode:Q,reason:f,data:B.data.data}),new s({code:g.SERVER_ERROR,extraCode:Q,message:f});this._log.warn("stop_cloud_transcription ignored error",{extraCode:Q,reason:f,data:B.data.data})}this.activeTranscriberMap.delete(i)}catch(B){throw this._log.error("stop_cloud_transcription failed",{error:B}),B}}destroy(){this.activeTranscriberMap.clear()}};v2(X6,"Name","RealtimeTranscriber");var A9=X6,QsA=A9;const dsA=Object.freeze(Object.defineProperty({__proto__:null,RealtimeTranscriber:A9,default:QsA},Symbol.toStringTag,{value:"Module"})),hsA=Mk(dsA);var psA=Object.create,wk=Object.defineProperty,fsA=Object.defineProperties,e9=Object.getOwnPropertyDescriptor,msA=Object.getOwnPropertyDescriptors,t9=Object.getOwnPropertyNames,V2=Object.getOwnPropertySymbols,DsA=Object.getPrototypeOf,R3=Object.prototype.hasOwnProperty,i9=Object.prototype.propertyIsEnumerable,kj=(t,i,r)=>i in t?wk(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,cr=(t,i)=>{for(var r in i||(i={}))R3.call(i,r)&&kj(t,r,i[r]);if(V2)for(var r of V2(i))i9.call(i,r)&&kj(t,r,i[r]);return t},lB=(t,i)=>fsA(t,msA(i)),ysA=(t,i)=>{var r={};for(var s in t)R3.call(t,s)&&i.indexOf(s)<0&&(r[s]=t[s]);if(t!=null&&V2)for(var s of V2(t))i.indexOf(s)<0&&i9.call(t,s)&&(r[s]=t[s]);return r},Sk=(t,i)=>function(){return i||(0,t[t9(t)[0]])((i={exports:{}}).exports,i),i.exports},M3=(t,i)=>{for(var r in i)wk(t,r,{get:i[r],enumerable:!0})},RsA=(t,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let g of t9(i))R3.call(t,g)||g===r||wk(t,g,{get:()=>i[g],enumerable:!(s=e9(i,g))||s.enumerable});return t},bw=(t,i,r)=>(r=t!=null?psA(DsA(t)):{},RsA(wk(r,"default",{value:t,enumerable:!0}),t)),ss=(t,i,r,s)=>{for(var g,B=e9(i,r),Q=t.length-1;Q>=0;Q--)(g=t[Q])&&(B=g(i,r,B)||B);return B&&wk(i,r,B),B},OA=(t,i,r)=>kj(t,typeof i!="symbol"?i+"":i,r),vk=Sk({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(t,i){var r=Object.prototype.hasOwnProperty,s="~";function g(){}function B(M,v,U){this.fn=M,this.context=v,this.once=U||!1}function Q(M,v,U,AA,z){if(typeof U!="function")throw new TypeError("The listener must be a function");var sA=new B(U,AA||M,z),eA=s?s+v:v;return M._events[eA]?M._events[eA].fn?M._events[eA]=[M._events[eA],sA]:M._events[eA].push(sA):(M._events[eA]=sA,M._eventsCount++),M}function f(M,v){--M._eventsCount===0?M._events=new g:delete M._events[v]}function m(){this._events=new g,this._eventsCount=0}Object.create&&(g.prototype=Object.create(null),new g().__proto__||(s=!1)),m.prototype.eventNames=function(){var M,v,U=[];if(this._eventsCount===0)return U;for(v in M=this._events)r.call(M,v)&&U.push(s?v.slice(1):v);return Object.getOwnPropertySymbols?U.concat(Object.getOwnPropertySymbols(M)):U},m.prototype.listeners=function(M){var v=s?s+M:M,U=this._events[v];if(!U)return[];if(U.fn)return[U.fn];for(var AA=0,z=U.length,sA=new Array(z);AA1&&(Q[m[0]]=void 0),Q};t.parseParams=function(Q){return Q.split(/;\s?/).reduce(B,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(Q){return Q.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(Q){for(var f=[],m=Q.split(" ").map(i),M=0;M=U)return AA;var z=v[M];switch(M+=1,AA){case"%%":return"%";case"%s":return String(z);case"%d":return Number(z);case"%v":return""}})},B=function(m,M,v){var U=[m+"="+(M.format instanceof Function?M.format(M.push?v:v[M.name]):M.format)];if(M.names)for(var AA=0;AA({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(r,s,g){const{RtcError:B,ErrorCode:Q,ErrorCodeDictionary:f}=t.errorModule;if(!r)return;const{width:m,height:M}=r;if(m&&M&&m*M>8294400)throw new B({code:Q.INVALID_PARAMETER,message:"The mix resolution cannot be set higher than 3840 * 2160."})}}),z6=t=>({required:!1,type:["string",HTMLElement,null],validate(i,r,s){const{RtcError:g,ErrorCode:B,ErrorCodeDictionary:Q}=t.errorModule;if(t.utils.isString(i)&&!document.getElementById(i))throw new g({code:B.INVALID_PARAMETER,extraCode:Q.INVALID_ELEMENT_ID,fnName:s,messageParams:{key:r}})}}),Dk=(t,i=!0)=>({type:"object",required:i,properties:cr({},dsA),validate(r,s,g){const{RtcError:B,ErrorCode:Q,ErrorCodeDictionary:f}=t.errorModule;if(r){if(r.fillMode&&!["contain","cover","fill"].includes(r.fillMode))throw new B({code:Q.INVALID_PARAMETER,extraCode:f.INVALID_PARAMETER_TYPE,message:"The fillMode parameter must be 'contain', 'cover' or 'fill'",fnName:g});if(r.rotation&&![0,90,180,270].includes(r.rotation))throw new B({code:Q.INVALID_PARAMETER,extraCode:f.INVALID_PARAMETER_TYPE,message:"The rotation parameter must be 0, 90, 180 or 270",fnName:g})}}}),Z6=t=>({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:cr({},Dk(t))}}}),X6=t=>({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:cr({},Dk(t))},validate(i,r,s){const{RtcError:g,ErrorCode:B,ErrorCodeDictionary:Q}=t.errorModule;if(!t.rtcDectection.isScreenCaptureApiAvailable())throw new g({code:B.ENV_NOT_SUPPORTED,fnName:s,extraCode:Q.NOT_SUPPORTED_SCREEN_SHARE})}}}),$6=t=>({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:cr({},Dk(t))}}}),A9=t=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},url:{required:!0,type:"string"},layout:cr({},Dk(t))}}}),e9=t=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},url:{required:!0,type:"string"},layout:cr({},Dk(t))}}});function hsA(t){return{name:"VideoMixerOptions",type:"object",required:!0,allowEmpty:!1,properties:{view:cr({},z6(t)),canvasInfo:cr({},W6(t,!0)),camera:cr({},Z6(t)),screen:cr({},X6(t)),text:cr({},$6(t)),image:cr({},A9(t)),video:cr({},e9(t))},validate(i,r,s,g){const{RtcError:B,ErrorCode:Q,ErrorCodeDictionary:f}=t.errorModule;if(t.environment.isMobile())throw new B({code:Q.ENV_NOT_SUPPORTED,message:"VideoMixer is not supported on mobile devices currently"});const{onScreenShareStop:m}=i;if(m&&!t.utils.isFunction(m))throw new B({code:Q.INVALID_PARAMETER,extraCode:f.INVALID_PARAMETER_TYPE,fnName:s,messageParams:{key:"onScreenShareStop",value:typeof m,rule:{type:"Function"}}})}}}function psA(t){return{name:"VideoMixerOptions",type:"object",required:!1,allowEmpty:!1,properties:{view:cr({},z6(t)),canvasInfo:cr({},W6(t)),camera:cr({},Z6(t)),screen:cr({},X6(t)),text:cr({},$6(t)),image:cr({},A9(t)),video:cr({},e9(t))}}}function fsA(t){return{name:"StopVideoMixerOptions",required:!1}}var t9=(t=>(t[t.INVALID_PARAMETER=4096]="INVALID_PARAMETER",t[t.INVALID_OPERATION=4097]="INVALID_OPERATION",t[t.NOT_SUPPORTED=4098]="NOT_SUPPORTED",t[t.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",t[t.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",t[t.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",t[t.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",t[t.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",t[t.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",t[t.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",t[t.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",t[t.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",t[t.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",t[t.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",t[t.CLIENT_BANNED=16448]="CLIENT_BANNED",t[t.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",t[t.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",t[t.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",t[t.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",t[t.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",t[t.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",t[t.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",t[t.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",t[t.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",t[t.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",t[t.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",t[t.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",t[t.API_CALL_ABORTED=16461]="API_CALL_ABORTED",t[t.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",t[t.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",t[t.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",t[t.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",t[t.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",t[t.UNKNOWN=65535]="UNKNOWN",t))(t9||{}),xa=t9,msA=function(t){for(const i in xa)if(xa[i]===t)return i;return"UNKNOWN"},DsA=class extends Error{constructor({name:t="RtcError",message:i,code:r=xa.UNKNOWN,extraCode:s=0,constraint:g}){const B=`<${msA(r)} 0x${r.toString(16)}>`,Q=`${i}${g?` constraint: ${g}`:""}${i?.includes(B)?"":` ${B}`}`;super(Q),OA(this,"code"),OA(this,"extraCode"),OA(this,"message"),OA(this,"originMessage"),OA(this,"name"),OA(this,"constraint"),this.code=r,this.extraCode=s,this.name=t,this.message=Q,this.constraint=g,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},Ws=DsA,ysA=0,m3=function(){return Date.now()+ysA},i9=function(){const t=new Date;return t.setTime(m3()),t.toLocaleString()},RsA=function(t){let i=String(t.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`},MsA={};p3(MsA,{REPORT_TYPE:()=>y9,buildSSOPackage:()=>M3,bytes2ms:()=>AgA,calculateScaleResolutionDownNumber:()=>m9,concatArrayBuffers:()=>RgA,convertObjectNumberToInt:()=>p9,copyProperties:()=>$sA,deepClone:()=>P2,deepCloneBasic:()=>Lj,deepMerge:()=>Q9,delay:()=>Rw,fibonacci:()=>R3,formatedTime:()=>dgA,getConstructorName:()=>ngA,getContainerFromElement:()=>ugA,getEnv:()=>qsA,getFirst16Bits:()=>wgA,getInternalVersion:()=>IgA,getLast16Bits:()=>MgA,getLoggerUrl:()=>D3,getMediaStreamTrackInfo:()=>mgA,getMuteStateFromFlag:()=>u9,getNetworkType:()=>y3,getNumNetworkType:()=>XsA,getReconnectionTimeout:()=>igA,getStringByteLength:()=>hgA,getTestSignalDomain:()=>jsA,getTurnServer:()=>lgA,getUint32Version:()=>h9,getValueType:()=>BD,getViewListFromView:()=>BgA,glog:()=>tgA,ipv4ToUint32:()=>CgA,isArray:()=>dC,isAudioWorkletSupported:()=>agA,isBoolean:()=>rD,isConstructor:()=>B9,isEmpty:()=>EgA,isFunction:()=>oD,isLangChinese:()=>Bp,isMediaStreamTrack:()=>ogA,isNumber:()=>uD,isObject:()=>$m,isOverseaSdkAppId:()=>Y2,isPlainObject:()=>yw,isPortrait:()=>d9,isPromise:()=>C9,isRemoteTrack:()=>rgA,isRotate90Or270:()=>D9,isSetSinkIdSupported:()=>sgA,isString:()=>pC,isUndefined:()=>Fr,isVideoMixerOutputTrack:()=>w3,loadImage:()=>pgA,loadVideo:()=>DgA,ms2bytes:()=>egA,ms2samples:()=>l9,normalizeUrl:()=>fgA,performanceNow:()=>Ns,promiseAny:()=>ggA,samples2ms:()=>E9,setNetworkTypeFromWebRTC:()=>ZsA,stringify:()=>up,stringifyIncludeValue:()=>bj,throttlePromise:()=>f9});var x2="5.0.0",o9=typeof importScripts<"u",r9=typeof registerProcessor<"u",wsA="web.sdk.qcloud.com",Sj=`https://${wsA}/trtc/webrtc/doc`,f5="https://cloud.tencent.com/document/product/647/85386",m5="https://trtc.io/document/56025",SsA="https://yun.tim.qq.com",vsA="https://apisgp.my-imcloud.com",NsA="trtc_error_assistance",n9={LOG:"jssdk_log"},_K={QCLOUD:"qcloud"},iw=(t=>(t[t.TRACE=0]="TRACE",t[t.DEBUG=1]="DEBUG",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.NONE=5]="NONE",t))(iw||{}),a9={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},TsA=6048e5,GsA={"480p_2":{width:640,height:480,frameRate:15,bitrate:500}},ksA=GsA["480p_2"],gt={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"},D5=1,_sA=2,bsA=4,y5=8,R5=64,M5=16,LsA=256,VG={PLAYER_ERROR:"player-error",LOAD_WORKLET:"load-worklet",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},FsA="unified-plan",ow=5,s9="default",o2=2e3,g9=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],UsA={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},OsA=function(t,i,r,s){return new(r||(r=Promise))(function(g,B){function Q(M){try{m(s.next(M))}catch(v){B(v)}}function f(M){try{m(s.throw(M))}catch(v){B(v)}}function m(M){var v;M.done?g(M.value):(v=M.value,v instanceof r?v:new r(function(U){U(v)})).then(Q,f)}m((s=s.apply(t,[])).next())})},vj=Symbol(32),Nj=Symbol(16),Tj=Symbol(8),pw=class{constructor(t){this.g=t,this.consumed=0,t&&(this.need=t.next().value)}setG(t){this.g=t,this.demand(t.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(t,i){return i&&this.consume(),this.need=t,this.flush()}read(t){return OsA(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((i,r)=>{var s;this.reject=r,this.resolve=g=>{delete this.lastReadPromise,delete this.resolve,delete this.need,i(g)},this.demand(t,!0)||(s=this.pull)===null||s===void 0||s.call(this,t)})})}readU32(){return this.read(vj)}readU16(){return this.read(Nj)}readU8(){return this.read(Tj)}close(){var t;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(t=this.reject)===null||t===void 0||t.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let t=null;const i=this.buffer.subarray(this.consumed);let r=0;const s=g=>i.length<(r=g);if(typeof this.need=="number"){if(s(this.need))return;t=i.subarray(0,r)}else if(this.need===vj){if(s(4))return;t=i[0]<<24|i[1]<<16|i[2]<<8|i[3]}else if(this.need===Nj){if(s(2))return;t=i[0]<<8|i[1]}else if(this.need===Tj){if(s(1))return;t=i[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(s(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(i.subarray(0,r)),t=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(s(this.need.byteLength))return;new Uint8Array(this.need).set(i.subarray(0,r)),t=this.need}return this.consumed+=r,this.g?this.demand(this.g.next(t).value,!0):this.resolve&&this.resolve(t),t}write(t){if(t instanceof Uint8Array?this.malloc(t.length).set(t):"buffer"in t?this.malloc(t.byteLength).set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):this.malloc(t.byteLength).set(new Uint8Array(t)),!this.g&&!this.resolve)return new Promise(i=>this.pull=i);this.flush()}writeU32(t){this.malloc(4).set([t>>24&255,t>>16&255,t>>8&255,255&t]),this.flush()}writeU16(t){this.malloc(2).set([t>>8&255,255&t]),this.flush()}writeU8(t){this.malloc(1)[0]=t,this.flush()}malloc(t){if(this.buffer){const i=this.buffer.length,r=i+t;if(r<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,r);else{const s=new Uint8Array(r);s.set(this.buffer),this.buffer=s}return this.buffer.subarray(i,r)}return this.buffer=new Uint8Array(t),this.buffer}};pw.U32=vj,pw.U16=Nj,pw.U8=Tj;var xsA=128;function bK(t){const i=new pw;for(;t>=128;)i.malloc(1)[0]=255&t|xsA,t>>>=7;return i.malloc(1)[0]=255&t,i.buffer||new Uint8Array(0)}function Gj(t,i=0){const r=new pw,s=i<<3;switch(typeof t){case"boolean":const g=r.malloc(2);g[0]=s,g[1]=t?1:0;break;case"number":r.malloc(1)[0]=s,r.write(bK(t));break;case"string":r.malloc(1)[0]=2|s;const B=new TextEncoder().encode(t);r.write(bK(B.length));const Q=r.malloc(B.length);for(let m=0;m>>24&255),this.buffer.push(t>>>16&255),this.buffer.push(t>>>8&255),this.buffer.push(255&t)}writeInt16(t){this.buffer.push(t>>>8&255),this.buffer.push(255&t)}writeByte(t){this.buffer.push(255&t)}writeBytes(t){for(let i=0;i>>24&255,t[r+1]=i>>>16&255,t[r+2]=i>>>8&255,t[r+3]=255&i}function sE(t,i){return t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3]}function v5(t,i){return t[i]}function BG(t,i,r){return new TextDecoder().decode(YsA(t,i,r))}function YsA(t,i,r){return t.slice(i,i+r)}var LK=0,kj=2654435769,_j=16,N5=4,qG=2,KG=7;function PsA(t,i,r,s="AVQualityReportSvc.C2S",g=2e3,B=2,Q=30){return{version:g,encryption:B,d2:"",d2Len:0,uinType:Q,uin:"",uinLen:0,reqHead:{seqNumber:r,appId:t,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:s,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:i}}function JsA(t,i){const r=new w5,s=PsA(i,t,LK);LK=LK+1&2147483647,r.writeInt32(0),r.writeInt32(s.version),r.writeByte(s.encryption);const g=new TextEncoder().encode(s.d2);r.writeInt32(g.length+4),g&&r.writeBytes(g),r.writeByte(s.uinType);const B=new TextEncoder().encode(s.uin);r.writeInt32(B.length+4),B.length&&r.writeBytes(B);const Q=new w5;Q.writeInt32(0),Q.writeInt32(s.reqHead.seqNumber),Q.writeInt32(s.reqHead.appId),Q.writeByte(s.reqHead.appId>>>24&255),Q.writeByte(s.reqHead.appId>>>16&255),Q.writeByte(s.reqHead.appId>>>8&255),Q.writeByte(255&s.reqHead.appId);for(let wA=4;wA<16;wA++)Q.writeByte(0);const f=new TextEncoder().encode(s.reqHead.a2);Q.writeInt32(f.length+4),f.length&&Q.writeBytes(f);const m=new TextEncoder().encode(s.reqHead.serviceCmd);Q.writeInt32(m.length+4),m.length&&Q.writeBytes(m);const M=new TextEncoder().encode(s.reqHead.cookie);Q.writeInt32(M.length+4),M.length&&Q.writeBytes(M);const v=new TextEncoder().encode(s.reqHead.imei);Q.writeInt32(v.length+4),v.length&&Q.writeBytes(v);const U=new TextEncoder().encode(s.reqHead.ksid);Q.writeInt32(U.length+4),U.length&&Q.writeBytes(U);const AA=new TextEncoder().encode(s.reqHead.clientVersionInfo);Q.writeInt16(AA.length+2),AA.length&&Q.writeBytes(AA);const z=Q.length;Q.data[0]=z>>>24&255,Q.data[1]=z>>>16&255,Q.data[2]=z>>>8&255,Q.data[3]=255&z,pC(t)&&(t=new TextEncoder().encode(t)),Q.writeInt32(t.length+4),t.length&&Q.writeBytes(t);let sA=new Uint8Array(Q.data),eA=null;s.encryption===1?eA=new TextEncoder().encode(s.uin):s.encryption===2&&(eA=new Uint8Array(16)),eA&&(sA=HsA(sA,eA)),r.writeBytes(sA);const X=new Uint8Array(r.data),QA=X.length;return X[0]=QA>>>24&255,X[1]=QA>>>16&255,X[2]=QA>>>8&255,X[3]=255&QA,X}function HsA(t,i){const r=t.length;let s=(r+1+qG+KG)%8;s&&(s=8-s);const g=new Uint8Array(r+1+qG+KG+s);let B=0;const Q=new Uint8Array(8),f=new Uint8Array(8),m=new Uint8Array(8);let M=0;Q[0]=248&Math.floor(256*Math.random())|s,M=1;for(let U=0;U>>=0,g+=(B<<4)+Q[0]^B+f^(B>>>5)+Q[1],g>>>=0,B+=(g<<4)+Q[2]^g+f^(g>>>5)+Q[3],B>>>=0;S5(r,g,s),S5(r,B,s+4)}var qsA=function(){return new URLSearchParams(location.search).get("trtc_env")||""},KsA=".rtc.qq.com",jsA=function(t){return t.includes(".")?t:`${t}${KsA}`},Y2=t=>Number(t)<14e8,D3=function(t,i){let r;return r=Y2(t)?vsA:SsA,`${r}/v5/AVQualityReportSvc/C2S?random=${Math.floor(Math.random()*2**31)}&sdkappid=${t}&cmdtype=${i}`},I9="unknown";function y3(){zsA();const{userAgent:t,connection:i}=navigator;let r=(t.match(/NetType\/\S+/)||[])[0]||"";r=r.toLowerCase().replace("nettype/",""),r==="3gnet"&&(r="3g");const s=i&&i.type&&i.type.toLowerCase();let g=i&&i.effectiveType&&i.effectiveType.toLowerCase();return g==="slow-2"&&(g="2g"),s?c9(s,g):I9}function WsA(){qi.warn("netType changed",y3())}var T5=!1;function zsA(){var t;T5||(T5=!0,(t=navigator.connection)==null||t.addEventListener("typechange",WsA))}function c9(t,i){if(a9[t])return t;switch(t){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";default:return"unknown"}}function ZsA(t){I9=c9(t)}function XsA(){return a9[y3()]}function $sA(t,i){for(const r of Reflect.ownKeys(i))if(r!=="constructor"&&r!=="prototype"&&r!=="name"){const s=Object.getOwnPropertyDescriptor(i,r)||"";Object.defineProperty(t,r,s)}return t}function AgA(t,i=48e3){return E9(t/4,i)}function E9(t,i=48e3){return 1e3*t/i}function egA(t,i=48e3){return 4*l9(t,i)}function l9(t,i=48e3){return t*i/1e3}var tgA=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},Bp=()=>{let t=navigator.language;return t=t.substring(0,2),t==="zh"},yw=function(t){if(!t||typeof t!="object"||Object.prototype.toString.call(t)!="[object Object]")return!1;const i=Object.getPrototypeOf(t);if(i===null)return!0;const r=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.toString.call(r)===Function.prototype.toString.call(Object)};function R3(t,i=1,r=1){return t<=1?r:R3(t-1,r,i+r)}function igA(t){return t>8?3e4:1e3*R3(t)}function BD(t){return Reflect.apply(Object.prototype.toString,t,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var oD=t=>typeof t=="function",Fr=t=>t===void 0,pC=t=>typeof t=="string",uD=t=>typeof t=="number",rD=t=>typeof t=="boolean",$m=t=>BD(t)==="object",dC=t=>BD(t)==="array",ogA=t=>BD(t)==="MediaStreamTrack".toLowerCase(),rgA=t=>t.isRemote,C9=t=>BD(t)==="promise",B9=t=>oD(t)&&t.prototype.constructor===t,ngA=t=>B9(t)?t.prototype.constructor.name:"",agA=typeof AudioWorkletNode<"u",sgA=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype;function ggA(t){return new Promise((i,r)=>{const s=[];t.forEach(g=>{g.then(i).catch(B=>{s.push(B),s.length===t.length&&r(s)})})})}function Ns(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var G5=t=>+t<10?`0${t}`:t,IgA=t=>{const i=t.match(/^\d+\.\d+\.\d+/)[0];if(!i)return t;const r=i.split("."),s=G5(r[1])+G5(r[2]);return r[1]-15>0&&(r[1]="15"),r[2]-15>0&&(r[2]="15"),`${r.join(".")}.${s}`},cgA=Object.prototype.hasOwnProperty;function EgA(t){if(t==null)return!0;if(typeof t=="boolean")return!1;if(typeof t=="number")return t===0;if(typeof t=="string"||typeof t=="function"||Array.isArray(t))return t.length===0;if(t instanceof Error)return t.message==="";if(yw(t))switch(Object.prototype.toString.call(t)){case"[object File]":case"[object Map]":case"[object Set]":return t.size===0;case"[object Object]":for(const i in t)if(cgA.call(t,i))return!1;return!0}return!1}function u9(t,i){return{userId:i,hasAudio:!!(t&y5),hasVideo:!!(t&D5),hasAuxiliary:!!(t&bsA),hasSmall:!!(t&_sA),audioMuted:!!(t&R5),videoMuted:!!(t&M5),audioAvailable:!(!(t&y5)||t&R5),videoAvailable:!(!(t&D5)||t&M5),hasDatachannel:!!(t&LsA)}}function lgA(t){const i={urls:t.url.startsWith("turn:")||t.url.startsWith("turns:")?t.url:`turn:${t.url}`};return Fr(t.username)||Fr(t.credential)||(i.username=t.username,i.credential=t.credential,i.credentialType="password",Fr(t.credentialType)||(i.credentialType=t.credentialType)),i}function CgA(t,i=!0){if(!pC(t))return 0;const r=t.split(".");return i?(Number(r[0])<<24|Number(r[1])<<16|Number(r[2])<<8|Number(r[3]))>>>0:(Number(r[3])<<24|Number(r[2])<<16|Number(r[1])<<8|Number(r[0]))>>>0}var Q9=function(t,i,r,s){if(!$m(t)||!$m(i))return 0;let g=0;const B=Object.keys(i);let Q;for(let f=0,m=B.length;f{i[s]=P2(r)}),i}if($m(t)){const i={};return Object.keys(t).forEach(r=>{i[r]=P2(t[r])}),i}return t}var BgA=t=>{let i=[];if(dC(t))i=[...t];else if(pC(t)){const r=document.getElementById(t);r&&i.push(r)}else t&&i.push(t);return i},ugA=t=>pC(t)?document.getElementById(t):t,QgA=t=>{const i=r=>r<10?`0${r}`:`${r}`;return`${t.getFullYear()}/${t.getMonth()+1}/${t.getDate()} ${i(t.getHours())}:${i(t.getMinutes())}:${i(t.getSeconds())}`},dgA=()=>QgA(new Date);function up(t,{keysToInclude:i,keysToExclude:r}){try{if(dC(t))return`[${t.map(Q=>up(Q,{keysToInclude:i,keysToExclude:r})).join(",")}]`;if(!yw(t)||!dC(i)&&!dC(r))return JSON.stringify(t);const s={},g=new Set(i),B=new Set(r);return Object.keys(t).forEach(Q=>{(B.size===0&&g.has(Q)||g.size===0&&!B.has(Q))&&(s[Q]=yw(t[Q])||dC(t[Q])?JSON.parse(up(t[Q],{keysToExclude:r,keysToInclude:i})):t[Q])}),JSON.stringify(s)}catch{return"{}"}}function bj(t,i=!1){const r=[];return Object.keys(t).forEach(s=>{i===t[s]&&r.push(s)}),up(t,{keysToInclude:r})}function hgA(t){return t.replace(/[\u4e00-\u9fa5]/g,"aa").length}var d9=()=>{var t,i,r,s;return(t=window.screen)!=null&&t.orientation?!!((s=(r=(i=window.screen)==null?void 0:i.orientation)==null?void 0:r.type)!=null&&s.includes("portrait")):window.orientation===0||window.orientation===180},pgA=async t=>new Promise((i,r)=>{let s;if(pC(t))s=new Image,s.crossOrigin="anonymous",s.src=t;else if(s=t,s.complete)return void i(s);s.onload=()=>i(s),s.onerror=()=>{r(new Ws({code:xa.INVALID_PARAMETER,message:`load image failed, url: ${t}`}))}}),h9=t=>{const i=t.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]},p9=t=>(Object.keys(t).forEach(i=>{uD(t[i])&&(i.startsWith("uint")||i.startsWith("int"))?t[i]=Math.floor(t[i]):(yw(t[i])||dC(t[i]))&&p9(t[i])}),t);function Rw(t,i){return new Promise(r=>{const s=setTimeout(r,t);i&&i(s)})}function f9(t,i){let r=null;return function(...s){return r||(r=t.apply(i||this,s),r.finally(()=>r=null),r)}}function fgA(t){return t.replace(/(^|[^:])\/{2,}/g,"$1/")}function mgA(t){var i;try{const{width:r,height:s,frameRate:g,sampleRate:B,sampleSize:Q,channelCount:f}=(i=t.getSettings)==null?void 0:i.call(t),m=t.kind===gt.AUDIO?`${B}x${Q}@${f}`:`${r}x${s}@${g}`,M=t.stats?` stats: ${JSON.stringify(t.stats).replaceAll('"',"")}`:"";return`${t.id} ${t.readyState} muted:${t.muted} ${t.kind} ${t.label} ${m}${M}`}catch{return""}}function m9(t,i){return t.width*t.height===i.width*i.height?1:d9()&&i.width>i.height&&t.height>i.width?Math.max(t.width/i.height,t.height/i.width,1):Math.max(t.width/i.width,t.height/i.height,1)}function D9(t){return t===90||t===270}async function DgA(t){return new Promise((i,r)=>{const s=document.createElement("video");s.crossOrigin="anonymous",s.src=t,s.muted=!0,s.loop=!0,s.playsInline=!0,s.play().then(()=>i(s)),s.onerror=()=>{r(s.error)}})}function Lj(t,i=new WeakMap){if(typeof t!="object"||t===null)return t;if(i.has(t))return i.get(t);if(Array.isArray(t)){const r=[];return i.set(t,r),t.forEach((s,g)=>{r[g]=Lj(s,i)}),r}if(Object.prototype.toString.call(t)==="[object Object]"){const r={};return i.set(t,r),Reflect.ownKeys(t).forEach(s=>{r[s]=Lj(t[s],i)}),r}return t}var y9=(t=>(t[t.END_REPORT=2001]="END_REPORT",t[t.LOG=2002]="LOG",t[t.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",t))(y9||{});function ygA(t,i,r,s){let g={data:t,random:Math.floor(Math.random()*2147483648),sdkAppId:r};return Fr(s)||(g=lB(cr({},g),{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:i,bytes_report_data:JSON.stringify(g)}}}function M3(t,i,r,s){try{const g=ygA(t,i,r,s);return JsA(Gj(g),r)}catch{return JSON.stringify(t)}}function RgA(t,i){const r=new Uint8Array(t.byteLength+i.byteLength);return r.set(new Uint8Array(t),0),r.set(new Uint8Array(i),t.byteLength),r.buffer}function MgA(t){return(65535&t)>>>0}function wgA(t){return(4294901760&t)>>>0}function w3(t){return!!(t&&t instanceof CanvasCaptureMediaStreamTrack&&t.canvas.id.includes("trtc_mix"))}function SgA(t){const i=vgA(t);return i?.busiBuff}function vgA(t){try{const i={};let r=0;i.totalLength=sE(t,r),r+=4,i.version=sE(t,r),r+=4,i.encryption=v5(t,r),r+=1,i.uinType=v5(t,r),r+=1,i.uinLength=sE(t,r),r+=4,i.uin=i.uinLength>4?BG(t,r,i.uinLength-4):"",r+=i.uinLength-4;const s=t.slice(r);if(i.encryption===2){const g=new Uint8Array(16).fill(0);t=NgA(s,g),i.decrypted=!0,r=0}else t=s,r=0;return i.rspHeadLength=sE(t,r),r+=4,i.seqNo=sE(t,r),r+=4,i.retCode=sE(t,r),r+=4,i.retStrLength=sE(t,r),r+=4,i.retStr=i.retStrLength?BG(t,r,i.retStrLength-4):"",r+=i.retStrLength-4,i.serviceCmdLength=sE(t,r),r+=4,i.serviceCmd=i.serviceCmdLength?BG(t,r,i.serviceCmdLength-4):"",r+=i.serviceCmdLength-4,i.cookieLength=sE(t,r),r+=4,i.cookie=i.cookieLength?BG(t,r,i.cookieLength-4):"",r+=i.cookieLength-4,i.flag=sE(t,r),r+=4,i.busiBuffLength=sE(t,r),r+=4,i.busiBuff=i.busiBuffLength?BG(t,r,i.busiBuffLength-4):"",r+=i.busiBuffLength-4,i}catch{}}function R9(t,i){let r=t[0]<<24|t[1]<<16|t[2]<<8|t[3],s=t[4]<<24|t[5]<<16|t[6]<<8|t[7];r>>>=0,s>>>=0;let g=kj*_j>>>0;for(let B=0;B<_j;B++)s-=(r<>>5)+i[3],s>>>=0,r-=(s<>>5)+i[1],r>>>=0,g-=kj,g>>>=0;return new Uint8Array([r>>>24&255,r>>>16&255,r>>>8&255,255&r,s>>>24&255,s>>>16&255,s>>>8&255,255&s])}function NgA(t,i){let r=0;const s=new Uint8Array(8).fill(0);let g=R9(new Uint8Array(t.slice(0,8)),i);const B=7&g[0],Q=t.length-1-B-qG-KG,f=new Uint8Array(Q);let m=0,M=s,v=t.slice(0,8);r=8;let U=1;U+=B;for(let z=1;z<=qG;)if(U<8)U++,z++;else if(U===8){const sA=UK(t,r,M,v,g,i);M=sA.ivPreCrypt,v=sA.ivCurCrypt,g=sA.debiBuf,r=sA.bufPos,U=0}let AA=Q;for(;AA>0;)if(U<8)f[m++]=g[U]^M[U],U++,AA--;else if(U===8){const z=UK(t,r,M,v,g,i);M=z.ivPreCrypt,v=z.ivCurCrypt,g=z.debiBuf,r=z.bufPos,U=0}for(let z=1;z<=KG;)if(U<8)g[U],M[U],U++,z++;else if(U===8){if(r>=t.length)break;const sA=UK(t,r,M,v,g,i);if(!sA.success)break;M=sA.ivPreCrypt,v=sA.ivCurCrypt,g=sA.debiBuf,r=sA.bufPos,U=0}return f}function UK(t,i,r,s,g,B){if(i+8>t.length)return{success:!1};const Q=new Uint8Array(s),f=t.slice(i,i+8),m=new Uint8Array(8);for(let M=0;M<8;M++)m[M]=g[M]^f[M];return{success:!0,ivPreCrypt:Q,ivCurCrypt:f,debiBuf:R9(m,B),bufPos:i+8}}var k5=typeof TextDecoder<"u"?new TextDecoder:void 0;function M9({url:t,body:i,method:r="POST",timeout:s,priority:g}){return new Promise((B,Q)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:g}).then(m=>m.clone().json().then(M=>({data:M}),()=>m.arrayBuffer().then(M=>({data:SgA(new Uint8Array(M))||(k5?k5.decode(M):M)})))).then(B,Q);const f=new XMLHttpRequest;f.onreadystatechange=()=>{if(f.readyState===4)if(f.status>=200&&f.status<300)try{const m=JSON.parse(f.response);B({data:m})}catch{B({data:f.response})}else Q({status:f.status,statusText:f.statusText||"request failed!"})},f.timeout=s||5e3,f.open(r,t,!0),f.send(i)})}var TgA=Object.prototype.hasOwnProperty,rw=t=>typeof t=="function",WM=t=>t===void 0,GgA=t=>typeof t=="boolean",OK=t=>t.isRemote,kgA=function(t){if(!t||typeof t!="object"||Object.prototype.toString.call(t)!="[object Object]")return!1;const i=Object.getPrototypeOf(t);if(i===null)return!0;const r=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.toString.call(r)===Function.prototype.toString.call(Object)};function _gA(t){if(t==null)return!0;if(typeof t=="boolean")return!1;if(typeof t=="number")return t===0;if(typeof t=="string"||typeof t=="function"||Array.isArray(t))return t.length===0;if(t instanceof Error)return t.message==="";if(kgA(t))switch(Object.prototype.toString.call(t)){case"[object File]":case"[object Map]":case"[object Set]":return t.size===0;case"[object Object]":for(const i in t)if(TgA.call(t,i))return!1;return!0}return!1}var bgA=0,LgA=1,_5=2;function FgA({retryFunction:t,settings:i,onError:r,onRetrying:s,onRetryFailed:g,onRetrySuccess:B,context:Q}){return function(...f){const{retries:m=5,timeout:M=1e3}=i;let v=0,U=-1,AA=bgA;const z=async(sA,eA)=>{const X=Q||this;try{const QA=await t.apply(X,f);v>0&&B&&B.call(this,v),v=0,sA(QA)}catch(QA){const wA=()=>{clearTimeout(U),v=0,AA=_5,eA(QA)},HA=()=>{AA!==_5&&v<(rw(m)?m():m)?(v++,AA=LgA,rw(s)&&s.call(this,v,wA),U=window.setTimeout(()=>{U=-1,z(sA,eA)},rw(M)?M(v):M)):(wA(),rw(g)&&g.call(this,QA))};rw(r)?r.call(this,{error:QA,retry:HA,reject:eA,retryFuncArgs:f,retriedCount:v}):HA()}};return new Promise(z)}}var S3=FgA,xK=class w9{constructor(i){OA(this,"_parentPath"),OA(this,"userId"),OA(this,"remoteUserId"),OA(this,"id"),OA(this,"sdkAppId"),OA(this,"type"),OA(this,"isLocal"),this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=!GgA(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 r=new w9({id:i.id,userId:WM(i.userId)?this.userId:i.userId,sdkAppId:WM(i.sdkAppId)?this.sdkAppId:i.sdkAppId,type:WM(i.type)?this.type:i.type,isLocal:WM(i.isLocal)?this.isLocal:i.isLocal,remoteUserId:WM(i.remoteUserId)?this.remoteUserId:i.remoteUserId});return r.bindParent(this),r}bindParent(i){const r=i.getFullId();this._parentPath!==r&&(this.debug(`bind logger parent: ${i.id}`),this._parentPath=r,this.userId=i.userId||this.userId,this.sdkAppId=i.sdkAppId||this.sdkAppId)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,r){const s=this.isLocal?this.userId:this.remoteUserId,g=this.getFullId();r.unshift(`[${this.isLocal?"↑":"↓"}${this.type&&this.type!=="main"?"*":""}${g}${s?`|${s}`:""}]`),qi.log(i,r,WM(this.userId)||_gA(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)}},Fu=typeof navigator>"u"?"":navigator.userAgent,bo=t=>new RegExp(t,"i").test(Fu),cs=t=>{if(bo(t)){const i=new RegExp(`${t}\\/([\\d.]+)`),r=Fu.match(i);if(r&&r[1])return r[1]}return""},mY=t=>{if(bo(t)){const i=new RegExp(`${t}\\/(\\d+)`),r=Fu.match(i);if(r&&r[1])return parseFloat(r[1])}return NaN},b5=/AppleWebKit\/([\d.]+)/i.exec(Fu);b5&&parseFloat(b5[1]);var v3=bo("iPad"),S9=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&bo("Macintosh"),DY=bo("iPhone")&&!v3,UgA=bo("iPod"),UI=DY||v3||UgA||S9,J2=()=>{try{return UI&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch{return UI}},hl=bo("Android"),v9=function(){if(hl){const t=Fu.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(t){const i=t[1]&&parseFloat(t[1]),r=t[2]&&parseFloat(t[2]);if(i&&r)return parseFloat(`${t[1]}.${t[2]}`);if(i)return i}}return NaN}();hl&&bo("webkit")&&v9<2.3;var Ql=bo("Firefox"),N9=cs("Firefox"),T9=mY("Firefox"),yk=bo("Edge"),G9=cs("Edge"),yY=bo("Edg"),k9=cs("Edg"),OgA=mY("Edg"),N3=bo("SogouMobileBrowser"),_9=cs("SogouMobileBrowser"),T3=bo("MetaSr\\s"),b9=cs("MetaSr\\s"),Id=bo("TBS"),L9=cs("TBS"),Gw=bo("XWEB"),F9=cs("XWEB");bo("MSIE\\s8\\.0");var xgA=bo("MSIE\\/\\d+");(function(){if(xgA){const t=/MSIE\s(\d+)\.\d/.exec(Fu);let i=t&&parseFloat(t[1]);return!i&&/Trident\/7.0/i.test(Fu)&&/rv:11.0/.test(Fu)&&(i=11),i}return NaN})();var Rk=bo("(micromessenger|webbrowser)"),U9=cs("MicroMessenger"),RY=!Id&&bo("MQQBrowser")&&bo("COVC"),MY=!Id&&bo("MQQBrowser")&&!bo("COVC"),H2=MY||RY?cs("MQQBrowser"):"",G3=!Id&&bo(" QQBrowser"),O9=cs(" QQBrowser"),k3=!Id&&bo("QQBrowserLite"),x9=cs("QQBrowserLite"),_3=!Id&&bo("MQBHD"),Y9=cs("MQBHD"),P9=bo("Windows"),wY=!UI&&bo("MAC OS X"),J9=!hl&&bo("Linux"),H9=bo("CrOS");bo("MicroMessenger");var YgA=bo("UCBrowser");bo("Electron");var b3=bo("MiuiBrowser"),V9=cs("MiuiBrowser"),L3=bo("HuaweiBrowser"),q9=bo("Huawei")||bo("HUAWEI"),PgA=bo("Honor")||bo("HONOR"),K9=cs("HuaweiBrowser"),F3=bo("SamsungBrowser"),j9=cs("SamsungBrowser"),SY=bo("HeyTapBrowser"),W9=cs("HeyTapBrowser"),U3=bo("VivoBrowser"),z9=cs("VivoBrowser"),O3=bo("OpenHarmony");cs("OpenHarmony");var Z9=()=>mY("Chrome"),V2=bo("CriOS"),pp=bo("Chrome"),x3=!yk&&!T3&&!N3&&!Id&&!Gw&&!yY&&!G3&&!b3&&!L3&&!F3&&!SY&&!U3&&pp,JgA=bo("HeadlessChrome"),fp=Z9(),YK=pp&&fp>=128&&fp<=143,X9=cs("Chrome");mY("Electron");var IE=!pp&&!MY&&!RY&&!k3&&!_3&&bo("Safari"),$9=IE||UI,Mk=cs("Version"),_u=(()=>{if(S9)return Mk;if(UI){const t=Fu.match(/OS (\d+)_(\d+)/i);if(t&&t[1]){let i=t[1];return t[2]&&(i+=`.${t[2]}`),i}}return""})();function HgA(t,i){const r=t.split(".").map(g=>Number(g)),s=i.split(".").map(g=>Number(g));for(let g=0;gQ)return!1}return!1}function AX(t,i,r=!1){const s=t.split(".").map(B=>Number(B)),g=i.split(".").map(B=>Number(B));for(let B=0;Bf)return!0;if(Q{const t=Number(_u.split(".")[0]);return t===14||t===13})(),KgA=V2&&Mk==="11.1.1",q2=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),zM=(()=>{let t;return()=>{if(t===void 0)try{t=!!window.localStorage}catch{t=!1}return t}})(),nD=jgA();function jgA(){const t=new Map([[Ql,["Firefox",N9]],[yY,["Edg",k9]],[x3,["Chrome",X9]],[V2,["ChiOS",cs("CriOS")]],[IE&&!V2,["Safari",Mk]],[Id,["TBS",L9]],[Gw,["XWEB",F9]],[Rk&&DY,["WeChat",U9]],[G3,["QQ(Win)",O9]],[MY,["QQ(Mobile)",H2]],[RY,["QQ(Mobile X5)",H2]],[k3,["QQ(Mac)",x9]],[_3,["QQ(iPad)",Y9]],[b3,["MI",V9]],[L3,["HW",K9]],[F3,["Samsung",j9]],[SY,["OPPO",W9]],[U3,["VIVO",z9]],[yk,["EDGE",G9]],[N3,["SogouMobile",_9]],[T3,["Sogou",b9]]]);let i="unknown",r="unknown";return t.has(!0)&&([i,r]=t.get(!0)),{name:i,version:r}}function WgA(){return hl||UI||DY||v3||O3}var zgA="";function eX(){return ZgA()||""}function ZgA(){const t=Fu.match(/;\s*([^;)]+)\s+Build\//);return t?.[1]?t[1].trim():null}var L5=new Map([[hl,"Android"],[UI,"iOS"],[P9,"Windows"],[wY,"MacOS"],[J9,"Linux"],[H9,"ChromeOS"]]),tX=function(){return L5.get(!0)?L5.get(!0):"unknown"};function Y3(){return P9?1:hl?2:wY?3:UI?4:J9?5:H9?6:O3?7:0}function XgA(){return Rk||Gw?4:pp?1:IE?2:Ql?3:0}var iX=()=>{let t=tX();return UI?t+=`/${_u}`:hl&&(t+=`/${v9}`),t+=`/${nD.name}/${IE&&!V2?nD.version:nD.version.split(".")[0]}`,t},$gA=Tw(mk()),AIA=new $gA.default,Eo=AIA,oX=(t=>(t.ROOM_DESTROY="1",t.JOIN_START="21",t.JOIN_SCHEDULE_SUCCESS="22",t.JOIN_SIGNAL_CONNECTION_START="23",t.JOIN_SIGNAL_CONNECTION_END="24",t.JOIN_SEND_CMD="25",t.JOIN_RECEIVED_CMD_RES="26",t.JOIN_SUCCESS="27",t.JOIN_FAILED="28",t.LEAVE_START="51",t.LEAVE_SEND_CMD="52",t.LEAVE_SUCCESS="53",t.PUBLISH_START="61",t.SEND_FIRST_VIDEO_FRAME="62",t.PUBLISH_FAILED="63",t.SUBSCRIBE_START="81",t.SUBSCRIBE_SUCCESS="82",t.SUBSCRIBE_FAILED="84",t.UNSUBSCRIBE_SUCCESS="83",t.LOCAL_TRACK_CAPTURE_START="101",t.LOCAL_TRACK_CAPTURE_SUCCESS="102",t.LOCAL_TRACK_CAPTURE_FAILED="103",t.LOCAL_TRACK_PUBLISHED="104",t.LOCAL_TRACK_UNPUBLISHED="105",t.LOCAL_TRACK_REPLACED="106",t.SWITCH_DEVICE_SUCCESS="107",t.TRACK_MUTED="108",t.TRACK_UNMUTED="109",t.REMOTE_TRACK_SUBSCRIBED="110",t.REMOTE_TRACK_UNSUBSCRIBED="111",t.LOCAL_TRACK_RECAPTURE="112",t.LOCAL_AUDIO_STARTED="113",t.LOCAL_AUDIO_STOPPED="114",t.REMOTE_AUDIO_STARTED="115",t.REMOTE_AUDIO_STOPPED="116",t.LOCAL_TRACK_STOPPED="117",t.LOCAL_VIDEO_TRACK_PREPROCESSED="118",t.PLAY_TRACK_START="151",t.PLAYER_STATE_CHANGED="152",t.VIDEO_LOADED_DATA="153",t.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",t.AUDIO_CONTEXT_LONG_SUSPENDED="155",t.REMOTE_VIDEO_PLAY_START="156",t.REMOTE_VIDEO_PLAY_FINISH="157",t.SIGNAL_CONNECTION_STATE_CHANGED="201",t.PEER_CONNECTION_STATE_CHANGED="202",t.SINGLE_CONNECTION_STAT="203",t.SPC_RECONNECTED="204",t.HEARTBEAT_REPORT="251",t.RECEIVED_PUBLISHED_USER_LIST="252",t.REMOTE_PUBLISH_STATE_CHANGED="253",t.AUDIO_LEVEL_INTERVAL="260",t.NETWORK_QUALITY="261",t.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",t.QUALITY_LIMITATION_CHANGED="263",t.LOG="264",t.AUDIO_PROCESSOR_DEBUG="265",t.SSO_SWITCH="266",t.SEI_MESSAGE="267",t.USER_PAUSE_IN_PIP="268",t.USER_RESUME_IN_PIP="269",t.ENTER_PICTURE_IN_PICTURE="270",t.LEAVE_PICTURE_IN_PICTURE="271",t.SWITCH_ROOM_START="401",t.SWITCH_ROOM_SUCCESS="407",t.SWITCH_ROOM_FAILED="408",t))(oX||{}),nr=oX,eIA=class{constructor(){OA(this,"enable",!1),OA(this,"ssoFailCount",0),Eo.on("22",({schedule:t})=>{var i;(i=t?.config)!=null&&i.sso&&Eo.emit("266",{enable:!0})}),Eo.on("266",({enable:t})=>{this.enable=t})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&Eo.emit("266",{enable:!1})}},Fj=new eIA,tIA="%cTRTC%c%s",iIA="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",oIA="display: inline",rX=class nX{constructor(){OA(this,"_isEnableUploadLog",!0),OA(this,"_localJoinedUser",new Map),OA(this,"_queue",[]),OA(this,"_timeoutId",-1),OA(this,"_logLevel",1),OA(this,"_logLevelToUpload",2),o9||r9||(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){Eo.on(nr.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var r;(r=i?.config)!=null&&r.logLevelToUpload&&iw[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),Eo.on(nr.JOIN_START,({params:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),Eo.on(nr.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 r=0;for(;r{i.map.has(g)?i.map.get(g).logs.push(s):i.map.set(g,{userId:g,sdkAppId:B,logs:[s]})});else if(pC(s.userId)&&uD(s.sdkAppId)){const{userId:g,sdkAppId:B}=s;i.map.has(g)?i.map.get(g).logs.push(s):i.map.set(g,{userId:g,sdkAppId:B,logs:[s]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,r)),i}async upload(){if(this._queue.length===0||!this._isEnableUploadLog)return;const{map:i,splicedQueue:r}=this.getLogsToUpload();if(i.size===0)return;try{const g=[...i.values()];for(let B=0;BAA.log).join(` -`)},v=JSON.stringify(M),U=Fj.enable?M3(M,2002,f):v;await this.uploadLogWithRetry(U,f,U instanceof Uint8Array,v),m.forEach(AA=>AA.uploaded=!0)}}catch{}const s=r.filter(g=>!g.uploaded);s.length>0&&(this._queue=s.concat(this._queue))}uploadLogWithRetry(i,r,s,g){return S3({retryFunction:()=>M9({url:D3(r,n9.LOG),body:i,timeout:5e3,priority:"low"}).then(B=>{s&&B.data!=="ok"&&(Fj.handleUploadFailed(),this.uploadLogWithRetry(g,r,!1,g))}),settings:{retries:3,timeout:2e3},onError:({retry:B})=>{B()}})()}getPrefix(i){const r=new Date;return r.setTime(m3()),`[${RsA(r)}] <${iw[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){Fr(iw[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(pC(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch{return""}}addLogToQueue(i,r,s=!0,g,B){const Q={log:r.reduce((f,m)=>`${f} ${this.logChunkToString(m)}`.trim(),""),level:i,userId:g,sdkAppId:B,forAllJoinedClients:s};Eo.emit(nr.LOG,{log:Q}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(Q)}log(i,r,s=!0,g,B){var Q;if(r.unshift(this.getPrefix(i)),this.addLogToQueue(i,r,s,g,B),i{const i=16*Math.random()|0;return(t=="x"?i:3&i|8).toString(16)})},aX=nIA,aIA=class{constructor(){OA(this,"_prefix","TRTC"),OA(this,"_queue",new Map)}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){zM()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix))try{const i=localStorage.getItem(t);if(!i)return!1;const r=JSON.parse(i);if(r&&r.expiresInlocalStorage.removeItem(t)))}doFlush(){if(zM())try{for(const[t,i]of this._queue)localStorage.setItem(t,JSON.stringify(i))}catch(t){qi.warn(t)}}getItem(t){if(!zM())return null;try{const i=localStorage.getItem(this.getRealKey(t));if(!i)return null;const r=JSON.parse(i);return r&&r.expiresIn>=Date.now()?r.value:null}catch(i){qi.warn(i)}}setItem(t,i){if(zM())try{const r={expiresIn:Date.now()+TsA,value:i};this._queue.set(this.getRealKey(t),r)}catch(r){qi.warn(r)}}deleteItem(t){if(!zM())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(i){return qi.warn(i),!1}}clear(){if(zM())try{localStorage.clear()}catch(t){qi.warn(t)}}},sX=new aIA,sIA={};p3(sIA,{HTTPS_API:()=>fIA,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>DX,IS_GET_CAPABILITIES_SUPPORTED:()=>mX,IS_GET_SETTINGS_SUPPORTED:()=>W2,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>NIA,IS_INSERTABLE_STREAM_SUPPORTED:()=>yX,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>LIA,IS_RTC_RTP_SENDER_SUPPORTED:()=>wk,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>RX,IS_SEI_SUPPORTED:()=>TIA,IS_SPC_SUPPORTED:()=>MIA,basis:()=>kIA,capabilityCheck:()=>_IA,checkSystemRequirementsInternal:()=>EX,decodeSupportStatus:()=>cX,detectH264SupportedByFakeStreaming:()=>lX,detectVideoCodecCapabilities:()=>FIA,detectVideoDecoderCapabilities:()=>TX,detectVideoEncoderCapabilities:()=>NX,encodeSupportStatus:()=>V3,getBrowserInfo:()=>CIA,getDisplayResolution:()=>CX,getH264ProfileLevelIds:()=>GX,isAddTransceiverSupported:()=>NY,isBrowserSupported:()=>P3,isCanvasCaptureStreamAPISupported:()=>QX,isCanvasSmallStreamSupported:()=>dX,isGetReceiversSupported:()=>yIA,isGetSendersSupported:()=>fX,isGetTransceiversSupported:()=>RIA,isGetUserMediaSupported:()=>BX,isMediaDevicesSupported:()=>H3,isMediaSessionSupported:()=>wX,isMediaStreamTrackGeneratorSupported:()=>uIA,isMediaStreamTrackProcessorSupported:()=>BIA,isReplaceTrackSupported:()=>SIA,isRequestVideoFrameCallbackSupported:()=>j3,isSIMDSupported:()=>GIA,isScaleResolutionDownBySupported:()=>hX,isScreenCaptureApiAvailable:()=>q3,isSelectedCandidatePair:()=>mIA,isSetParametersSupported:()=>vIA,isSetSinkIdSupported:()=>hIA,isSmallStreamSupported:()=>pX,isStopTransceiverSupported:()=>wIA,isTRTCSupported:()=>dIA,isUnifiedPlanDefault:()=>DIA,isUsedInHttpProtocol:()=>vY,isWebAudioSupported:()=>uX,isWebCodecSupported:()=>MX,isWebCodecsSupported:()=>J3,isWebRTCSupported:()=>K3,isWebTransportSupported:()=>SX});var K2={PLAY_FAILED:"PLAY_FAILED",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND"},Iw={AVOID_REPEATED_CALL:t=>`previous ${t.name}() is ongoing, please avoid repeated calls.`,INVALID_PARAMETER_REQUIRED:({key:t,rule:i,fnName:r,value:s})=>`'${t||i.name}' is a required param when calling ${r}(), received: ${s}.`,INVALID_PARAMETER_TYPE({key:t,rule:i,fnName:r,value:s}){const g=`${t||i.name}`;let B="";return B=Array.isArray(i.type)?i.type.join("|"):i.type,`'${g}' must be type of ${B} when calling ${r}(), received type: ${BD(s)}.`},INVALID_PARAMETER_EMPTY:({key:t,rule:i,fnName:r,value:s})=>`'${t||i.name}' cannot be '${s}' when calling ${r}().`,INVALID_PARAMETER_INSTANCE:({key:t,rule:i,fnName:r,value:s})=>`'${`${t||i.name}`}' must be instanceof ${`${i.instanceOf.name||i.instanceOf}`} when calling ${r}(), received type: ${BD(s)}.`,INVALID_PARAMETER_RANGE:({key:t,rule:i,fnName:r,value:s})=>`'${t||i.name}' must be one of ${i.values.join("|")} when calling ${r}(), received: ${s}.`,INVALID_PARAMETER_MIN:({key:t,rule:i,fnName:r,value:s})=>`the min value of ${t||i.name} is ${i.min}, received: ${s}.`,INVALID_PARAMETER_MAX:({key:t,rule:i,fnName:r,value:s})=>`the max value of ${t||i.name} is ${i.max}, received: ${s}.`,API_CALL_TIMEOUT:t=>`${t.commandDesc||t.command} timeout observed.`,SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:t=>`SignalChannel setup failure: (errorCode: ${t.errorCode}, errorMsg: ${t.errorMsg} }).`,ERROR_MESSAGE(t){let i=`${t.type} failed`;return t.message&&(i=`${i}: ${t.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:t=>`exchange sdp failed ${t.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:t=>`'${t}' must be validate string when useStringRoomId is true.`,INVALID_ROOMID_INTEGER:t=>`'${t}' 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:t,code:i})=>`Failed to join room - ${t} code: ${i}`,REJOIN_ROOM_FAILED:t=>`reJoin room: ${t.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:t=>`duplicate ${t} stream publishing, please unpublish your prev ${t} 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:t,userId:i,streamType:r})=>`failed to subscribe ${i} ${r} stream, reason: ${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:t=>`switchRole failed, errCode: ${t.code} errMsg: ${t.message}.`,CLIENT_BANNED:t=>`client was banned because of ${t.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:t=>`startPublishCDNStream failed, errMsg: ${t.message}.`,STOP_PUBLISH_CDN_FAILED:t=>`stopPublishCDNStream failed, errMsg: ${t.message}.`,INVALID_STREAM_ID:t=>`'${t}' 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:t=>`cannot replace ${t.kind} track because stream has not ${t.kind} track`,NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:t=>`startMixTranscode failed, errMsg: ${t.message}.`,STOP_MIX_TRANSCODE_FAILED:t=>`stopMixTranscode failed, errMsg: ${t.message}.`,MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO:({key:t,rule:i,fnName:r,value:s})=>`'${t||i.name}' cannot be less than 0 when calling ${r}().`,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:t=>`'${t}' 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:t,fnName:i})=>`'${t}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:t,fnName:i,type:r})=>`the element corresponding to '${t}' must be instanceof HTMLElement when calling ${i}(), received: ${r}.`,PLAY_FAILED:t=>`${t.media} play failed, browser exception: ${t.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:t=>`${t}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:t=>`${t.signalResponse} failed, response code is ${t.code} , errMsg: ${t.message}.`,CATCH_HANDLER_ERROR:({name:t,event:i})=>`an error was caught in ${t}.on('${i}', handler), please check your code in 'handler'.`,API_NOT_EXIST:({name:t})=>`experimental api ${t} does not exist.`,REPEAT_JOIN:t=>"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:t})=>`failed to call ${t}() because client was destroyed.`,SEI_NOT_SUPPORT:t=>"not support to sendSEIMessage"+(t===!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:t,name:i,timesInSecond:r,maxSizeInSecond:s})=>`api ${i} call ${t?"size":"times"} is over ${t?`${s} bytes`:r} in a second.`,CONNECTION_ABORTED:t=>`connection aborted due to: ${t}`,API_CALL_ABORTED(t){let i;return i=t.message.includes("REMOTE_STREAM_NOT_EXIST")?`Subscribe ${t.userId} ${t.streamType} stream aborted, reason: remote user ${t.userId} unpublished stream.`:`API aborted, reason: ${t.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:t=>`'streamType' is required when 'userId' is not '*', calling ${t}()`,SWITCH_PLAYBACK_QUALITY_TIMEOUT:t=>`switchPlaybackQuality timeout: waiting for first frame of user ${t.userId}.`},F5=(t,i)=>i?`${Sj}/${t}/${i}`:`${Sj}/${t}/index.html`,gIA=()=>{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 t=localStorage==null?void 0:localStorage.getItem(NsA);if(t){t=JSON.parse(t);const i=document.createElement("script");i.type="text/javascript",i.text=t.message,document.body.appendChild(i);const r=window.TRTC_ERROR_INFO,s=window.TRTC_ERROR_LINK;return document.body.removeChild(i),{TRTC_ERROR_INFO:r,TRTC_ERROR_LINK:s}}return{}};function j2(t){const{key:i,data:r,link:s,addDocLink:g=!0}=t;let B="",Q="",f="";oD(Iw[i])?B=Iw[i](r):pC(Iw[i])&&(B=Iw[i]);const{TRTC_ERROR_INFO:m,TRTC_ERROR_LINK:M}=gIA();s?f=`${s.className}.html#${s.fnName}`:M&&M[i]&&(oD(M[i])?f=M[i](r):pC(M[i])&&(f=M[i]));let v=B;return Bp()&&(m&&m[i]&&(oD(m[i])?Q=m[i](r):pC(m[i])&&(Q=m[i])),Q&&(v=g?`${Q} -请查看文档: ${F5("zh-cn",f)} +`}}}),SsA=Sk({"../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/index.js"(t){var i=MsA(),r=wsA(),s=w3();t.grammar=s,t.write=r,t.parse=i.parse,t.parseParams=i.parseParams,t.parseFmtpConfig=i.parseFmtpConfig,t.parsePayloads=i.parsePayloads,t.parseRemoteCandidates=i.parseRemoteCandidates,t.parseImageAttributes=i.parseImageAttributes,t.parseSimulcastStreamList=i.parseSimulcastStreamList}}),vsA={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"}},o9=(t,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(r,s,g){const{RtcError:B,ErrorCode:Q,ErrorCodeDictionary:f}=t.errorModule;if(!r)return;const{width:m,height:M}=r;if(m&&M&&m*M>8294400)throw new B({code:Q.INVALID_PARAMETER,message:"The mix resolution cannot be set higher than 3840 * 2160."})}}),r9=t=>({required:!1,type:["string",HTMLElement,null],validate(i,r,s){const{RtcError:g,ErrorCode:B,ErrorCodeDictionary:Q}=t.errorModule;if(t.utils.isString(i)&&!document.getElementById(i))throw new g({code:B.INVALID_PARAMETER,extraCode:Q.INVALID_ELEMENT_ID,fnName:s,messageParams:{key:r}})}}),Nk=(t,i=!0)=>({type:"object",required:i,properties:cr({},vsA),validate(r,s,g){const{RtcError:B,ErrorCode:Q,ErrorCodeDictionary:f}=t.errorModule;if(r){if(r.fillMode&&!["contain","cover","fill"].includes(r.fillMode))throw new B({code:Q.INVALID_PARAMETER,extraCode:f.INVALID_PARAMETER_TYPE,message:"The fillMode parameter must be 'contain', 'cover' or 'fill'",fnName:g});if(r.rotation&&![0,90,180,270].includes(r.rotation))throw new B({code:Q.INVALID_PARAMETER,extraCode:f.INVALID_PARAMETER_TYPE,message:"The rotation parameter must be 0, 90, 180 or 270",fnName:g})}}}),n9=t=>({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:cr({},Nk(t))}}}),a9=t=>({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:cr({},Nk(t))},validate(i,r,s){const{RtcError:g,ErrorCode:B,ErrorCodeDictionary:Q}=t.errorModule;if(!t.rtcDectection.isScreenCaptureApiAvailable())throw new g({code:B.ENV_NOT_SUPPORTED,fnName:s,extraCode:Q.NOT_SUPPORTED_SCREEN_SHARE})}}}),s9=t=>({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:cr({},Nk(t))}}}),g9=t=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},url:{required:!0,type:"string"},layout:cr({},Nk(t))}}}),I9=t=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},url:{required:!0,type:"string"},layout:cr({},Nk(t))}}});function NsA(t){return{name:"VideoMixerOptions",type:"object",required:!0,allowEmpty:!1,properties:{view:cr({},r9(t)),canvasInfo:cr({},o9(t,!0)),camera:cr({},n9(t)),screen:cr({},a9(t)),text:cr({},s9(t)),image:cr({},g9(t)),video:cr({},I9(t))},validate(i,r,s,g){const{RtcError:B,ErrorCode:Q,ErrorCodeDictionary:f}=t.errorModule;if(t.environment.isMobile())throw new B({code:Q.ENV_NOT_SUPPORTED,message:"VideoMixer is not supported on mobile devices currently"});const{onScreenShareStop:m}=i;if(m&&!t.utils.isFunction(m))throw new B({code:Q.INVALID_PARAMETER,extraCode:f.INVALID_PARAMETER_TYPE,fnName:s,messageParams:{key:"onScreenShareStop",value:typeof m,rule:{type:"Function"}}})}}}function TsA(t){return{name:"VideoMixerOptions",type:"object",required:!1,allowEmpty:!1,properties:{view:cr({},r9(t)),canvasInfo:cr({},o9(t)),camera:cr({},n9(t)),screen:cr({},a9(t)),text:cr({},s9(t)),image:cr({},g9(t)),video:cr({},I9(t))}}}function GsA(t){return{name:"StopVideoMixerOptions",required:!1}}var c9=(t=>(t[t.INVALID_PARAMETER=4096]="INVALID_PARAMETER",t[t.INVALID_OPERATION=4097]="INVALID_OPERATION",t[t.NOT_SUPPORTED=4098]="NOT_SUPPORTED",t[t.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",t[t.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",t[t.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",t[t.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",t[t.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",t[t.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",t[t.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",t[t.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",t[t.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",t[t.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",t[t.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",t[t.CLIENT_BANNED=16448]="CLIENT_BANNED",t[t.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",t[t.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",t[t.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",t[t.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",t[t.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",t[t.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",t[t.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",t[t.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",t[t.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",t[t.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",t[t.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",t[t.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",t[t.API_CALL_ABORTED=16461]="API_CALL_ABORTED",t[t.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",t[t.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",t[t.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",t[t.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",t[t.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",t[t.UNKNOWN=65535]="UNKNOWN",t))(c9||{}),xa=c9,ksA=function(t){for(const i in xa)if(xa[i]===t)return i;return"UNKNOWN"},_sA=class extends Error{constructor({name:t="RtcError",message:i,code:r=xa.UNKNOWN,extraCode:s=0,constraint:g}){const B=`<${ksA(r)} 0x${r.toString(16)}>`,Q=`${i}${g?` constraint: ${g}`:""}${i?.includes(B)?"":` ${B}`}`;super(Q),OA(this,"code"),OA(this,"extraCode"),OA(this,"message"),OA(this,"originMessage"),OA(this,"name"),OA(this,"constraint"),this.code=r,this.extraCode=s,this.name=t,this.message=Q,this.constraint=g,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},Ws=_sA,bsA=0,S3=function(){return Date.now()+bsA},E9=function(){const t=new Date;return t.setTime(S3()),t.toLocaleString()},LsA=function(t){let i=String(t.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`},FsA={};M3(FsA,{REPORT_TYPE:()=>k9,buildSSOPackage:()=>G3,bytes2ms:()=>cgA,calculateScaleResolutionDownNumber:()=>T9,concatArrayBuffers:()=>LgA,convertObjectNumberToInt:()=>v9,copyProperties:()=>IgA,deepClone:()=>j2,deepCloneBasic:()=>Pj,deepMerge:()=>M9,delay:()=>vw,fibonacci:()=>T3,formatedTime:()=>vgA,getConstructorName:()=>QgA,getContainerFromElement:()=>wgA,getEnv:()=>igA,getFirst16Bits:()=>UgA,getInternalVersion:()=>fgA,getLast16Bits:()=>FgA,getLoggerUrl:()=>v3,getMediaStreamTrackInfo:()=>kgA,getMuteStateFromFlag:()=>R9,getNetworkType:()=>N3,getNumNetworkType:()=>ggA,getReconnectionTimeout:()=>CgA,getStringByteLength:()=>NgA,getTestSignalDomain:()=>rgA,getTurnServer:()=>ygA,getUint32Version:()=>S9,getValueType:()=>dD,getViewListFromView:()=>MgA,glog:()=>lgA,ipv4ToUint32:()=>RgA,isArray:()=>dC,isAudioWorkletSupported:()=>dgA,isBoolean:()=>gD,isConstructor:()=>y9,isEmpty:()=>DgA,isFunction:()=>sD,isLangChinese:()=>dp,isMediaStreamTrack:()=>BgA,isNumber:()=>hD,isObject:()=>iD,isOverseaSdkAppId:()=>K2,isPlainObject:()=>Sw,isPortrait:()=>w9,isPromise:()=>D9,isRemoteTrack:()=>ugA,isRotate90Or270:()=>G9,isSetSinkIdSupported:()=>hgA,isString:()=>pC,isUndefined:()=>Fr,isVideoMixerOutputTrack:()=>k3,loadImage:()=>TgA,loadVideo:()=>_gA,ms2bytes:()=>EgA,ms2samples:()=>m9,normalizeUrl:()=>GgA,performanceNow:()=>Ns,promiseAny:()=>pgA,samples2ms:()=>f9,setNetworkTypeFromWebRTC:()=>sgA,stringify:()=>hp,stringifyIncludeValue:()=>Yj,throttlePromise:()=>N9});var q2="5.0.0",l9=typeof importScripts<"u",C9=typeof registerProcessor<"u",UsA="web.sdk.qcloud.com",_j=`https://${UsA}/trtc/webrtc/doc`,S5="https://cloud.tencent.com/document/product/647/85386",v5="https://trtc.io/document/56025",OsA="https://yun.tim.qq.com",xsA="https://apisgp.my-imcloud.com",YsA="trtc_error_assistance",B9={LOG:"jssdk_log"},xK={QCLOUD:"qcloud"},nw=(t=>(t[t.TRACE=0]="TRACE",t[t.DEBUG=1]="DEBUG",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.NONE=5]="NONE",t))(nw||{}),u9={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},PsA=6048e5,JsA={"480p_2":{width:640,height:480,frameRate:15,bitrate:500}},HsA=JsA["480p_2"],gt={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"},N5=1,VsA=2,qsA=4,T5=8,G5=64,k5=16,KsA=256,zG={PLAYER_ERROR:"player-error",LOAD_WORKLET:"load-worklet",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},jsA="unified-plan",aw=5,Q9="default",c2=2e3,d9=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],WsA={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},zsA=function(t,i,r,s){return new(r||(r=Promise))(function(g,B){function Q(M){try{m(s.next(M))}catch(v){B(v)}}function f(M){try{m(s.throw(M))}catch(v){B(v)}}function m(M){var v;M.done?g(M.value):(v=M.value,v instanceof r?v:new r(function(U){U(v)})).then(Q,f)}m((s=s.apply(t,[])).next())})},bj=Symbol(32),Lj=Symbol(16),Fj=Symbol(8),Dw=class{constructor(t){this.g=t,this.consumed=0,t&&(this.need=t.next().value)}setG(t){this.g=t,this.demand(t.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(t,i){return i&&this.consume(),this.need=t,this.flush()}read(t){return zsA(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((i,r)=>{var s;this.reject=r,this.resolve=g=>{delete this.lastReadPromise,delete this.resolve,delete this.need,i(g)},this.demand(t,!0)||(s=this.pull)===null||s===void 0||s.call(this,t)})})}readU32(){return this.read(bj)}readU16(){return this.read(Lj)}readU8(){return this.read(Fj)}close(){var t;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(t=this.reject)===null||t===void 0||t.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let t=null;const i=this.buffer.subarray(this.consumed);let r=0;const s=g=>i.length<(r=g);if(typeof this.need=="number"){if(s(this.need))return;t=i.subarray(0,r)}else if(this.need===bj){if(s(4))return;t=i[0]<<24|i[1]<<16|i[2]<<8|i[3]}else if(this.need===Lj){if(s(2))return;t=i[0]<<8|i[1]}else if(this.need===Fj){if(s(1))return;t=i[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(s(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(i.subarray(0,r)),t=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(s(this.need.byteLength))return;new Uint8Array(this.need).set(i.subarray(0,r)),t=this.need}return this.consumed+=r,this.g?this.demand(this.g.next(t).value,!0):this.resolve&&this.resolve(t),t}write(t){if(t instanceof Uint8Array?this.malloc(t.length).set(t):"buffer"in t?this.malloc(t.byteLength).set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):this.malloc(t.byteLength).set(new Uint8Array(t)),!this.g&&!this.resolve)return new Promise(i=>this.pull=i);this.flush()}writeU32(t){this.malloc(4).set([t>>24&255,t>>16&255,t>>8&255,255&t]),this.flush()}writeU16(t){this.malloc(2).set([t>>8&255,255&t]),this.flush()}writeU8(t){this.malloc(1)[0]=t,this.flush()}malloc(t){if(this.buffer){const i=this.buffer.length,r=i+t;if(r<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,r);else{const s=new Uint8Array(r);s.set(this.buffer),this.buffer=s}return this.buffer.subarray(i,r)}return this.buffer=new Uint8Array(t),this.buffer}};Dw.U32=bj,Dw.U16=Lj,Dw.U8=Fj;var ZsA=128;function YK(t){const i=new Dw;for(;t>=128;)i.malloc(1)[0]=255&t|ZsA,t>>>=7;return i.malloc(1)[0]=255&t,i.buffer||new Uint8Array(0)}function Uj(t,i=0){const r=new Dw,s=i<<3;switch(typeof t){case"boolean":const g=r.malloc(2);g[0]=s,g[1]=t?1:0;break;case"number":r.malloc(1)[0]=s,r.write(YK(t));break;case"string":r.malloc(1)[0]=2|s;const B=new TextEncoder().encode(t);r.write(YK(B.length));const Q=r.malloc(B.length);for(let m=0;m>>24&255),this.buffer.push(t>>>16&255),this.buffer.push(t>>>8&255),this.buffer.push(255&t)}writeInt16(t){this.buffer.push(t>>>8&255),this.buffer.push(255&t)}writeByte(t){this.buffer.push(255&t)}writeBytes(t){for(let i=0;i>>24&255,t[r+1]=i>>>16&255,t[r+2]=i>>>8&255,t[r+3]=255&i}function sE(t,i){return t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3]}function L5(t,i){return t[i]}function hG(t,i,r){return new TextDecoder().decode(XsA(t,i,r))}function XsA(t,i,r){return t.slice(i,i+r)}var PK=0,Oj=2654435769,xj=16,F5=4,ZG=2,XG=7;function $sA(t,i,r,s="AVQualityReportSvc.C2S",g=2e3,B=2,Q=30){return{version:g,encryption:B,d2:"",d2Len:0,uinType:Q,uin:"",uinLen:0,reqHead:{seqNumber:r,appId:t,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:s,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:i}}function AgA(t,i){const r=new _5,s=$sA(i,t,PK);PK=PK+1&2147483647,r.writeInt32(0),r.writeInt32(s.version),r.writeByte(s.encryption);const g=new TextEncoder().encode(s.d2);r.writeInt32(g.length+4),g&&r.writeBytes(g),r.writeByte(s.uinType);const B=new TextEncoder().encode(s.uin);r.writeInt32(B.length+4),B.length&&r.writeBytes(B);const Q=new _5;Q.writeInt32(0),Q.writeInt32(s.reqHead.seqNumber),Q.writeInt32(s.reqHead.appId),Q.writeByte(s.reqHead.appId>>>24&255),Q.writeByte(s.reqHead.appId>>>16&255),Q.writeByte(s.reqHead.appId>>>8&255),Q.writeByte(255&s.reqHead.appId);for(let wA=4;wA<16;wA++)Q.writeByte(0);const f=new TextEncoder().encode(s.reqHead.a2);Q.writeInt32(f.length+4),f.length&&Q.writeBytes(f);const m=new TextEncoder().encode(s.reqHead.serviceCmd);Q.writeInt32(m.length+4),m.length&&Q.writeBytes(m);const M=new TextEncoder().encode(s.reqHead.cookie);Q.writeInt32(M.length+4),M.length&&Q.writeBytes(M);const v=new TextEncoder().encode(s.reqHead.imei);Q.writeInt32(v.length+4),v.length&&Q.writeBytes(v);const U=new TextEncoder().encode(s.reqHead.ksid);Q.writeInt32(U.length+4),U.length&&Q.writeBytes(U);const AA=new TextEncoder().encode(s.reqHead.clientVersionInfo);Q.writeInt16(AA.length+2),AA.length&&Q.writeBytes(AA);const z=Q.length;Q.data[0]=z>>>24&255,Q.data[1]=z>>>16&255,Q.data[2]=z>>>8&255,Q.data[3]=255&z,pC(t)&&(t=new TextEncoder().encode(t)),Q.writeInt32(t.length+4),t.length&&Q.writeBytes(t);let sA=new Uint8Array(Q.data),eA=null;s.encryption===1?eA=new TextEncoder().encode(s.uin):s.encryption===2&&(eA=new Uint8Array(16)),eA&&(sA=egA(sA,eA)),r.writeBytes(sA);const X=new Uint8Array(r.data),QA=X.length;return X[0]=QA>>>24&255,X[1]=QA>>>16&255,X[2]=QA>>>8&255,X[3]=255&QA,X}function egA(t,i){const r=t.length;let s=(r+1+ZG+XG)%8;s&&(s=8-s);const g=new Uint8Array(r+1+ZG+XG+s);let B=0;const Q=new Uint8Array(8),f=new Uint8Array(8),m=new Uint8Array(8);let M=0;Q[0]=248&Math.floor(256*Math.random())|s,M=1;for(let U=0;U>>=0,g+=(B<<4)+Q[0]^B+f^(B>>>5)+Q[1],g>>>=0,B+=(g<<4)+Q[2]^g+f^(g>>>5)+Q[3],B>>>=0;b5(r,g,s),b5(r,B,s+4)}var igA=function(){return new URLSearchParams(location.search).get("trtc_env")||""},ogA=".rtc.qq.com",rgA=function(t){return t.includes(".")?t:`${t}${ogA}`},K2=t=>Number(t)<14e8,v3=function(t,i){let r;return r=K2(t)?xsA:OsA,`${r}/v5/AVQualityReportSvc/C2S?random=${Math.floor(Math.random()*2**31)}&sdkappid=${t}&cmdtype=${i}`},h9="unknown";function N3(){agA();const{userAgent:t,connection:i}=navigator;let r=(t.match(/NetType\/\S+/)||[])[0]||"";r=r.toLowerCase().replace("nettype/",""),r==="3gnet"&&(r="3g");const s=i&&i.type&&i.type.toLowerCase();let g=i&&i.effectiveType&&i.effectiveType.toLowerCase();return g==="slow-2"&&(g="2g"),s?p9(s,g):h9}function ngA(){qi.warn("netType changed",N3())}var U5=!1;function agA(){var t;U5||(U5=!0,(t=navigator.connection)==null||t.addEventListener("typechange",ngA))}function p9(t,i){if(u9[t])return t;switch(t){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";default:return"unknown"}}function sgA(t){h9=p9(t)}function ggA(){return u9[N3()]}function IgA(t,i){for(const r of Reflect.ownKeys(i))if(r!=="constructor"&&r!=="prototype"&&r!=="name"){const s=Object.getOwnPropertyDescriptor(i,r)||"";Object.defineProperty(t,r,s)}return t}function cgA(t,i=48e3){return f9(t/4,i)}function f9(t,i=48e3){return 1e3*t/i}function EgA(t,i=48e3){return 4*m9(t,i)}function m9(t,i=48e3){return t*i/1e3}var lgA=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},dp=()=>{let t=navigator.language;return t=t.substring(0,2),t==="zh"},Sw=function(t){if(!t||typeof t!="object"||Object.prototype.toString.call(t)!="[object Object]")return!1;const i=Object.getPrototypeOf(t);if(i===null)return!0;const r=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.toString.call(r)===Function.prototype.toString.call(Object)};function T3(t,i=1,r=1){return t<=1?r:T3(t-1,r,i+r)}function CgA(t){return t>8?3e4:1e3*T3(t)}function dD(t){return Reflect.apply(Object.prototype.toString,t,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var sD=t=>typeof t=="function",Fr=t=>t===void 0,pC=t=>typeof t=="string",hD=t=>typeof t=="number",gD=t=>typeof t=="boolean",iD=t=>dD(t)==="object",dC=t=>dD(t)==="array",BgA=t=>dD(t)==="MediaStreamTrack".toLowerCase(),ugA=t=>t.isRemote,D9=t=>dD(t)==="promise",y9=t=>sD(t)&&t.prototype.constructor===t,QgA=t=>y9(t)?t.prototype.constructor.name:"",dgA=typeof AudioWorkletNode<"u",hgA=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype;function pgA(t){return new Promise((i,r)=>{const s=[];t.forEach(g=>{g.then(i).catch(B=>{s.push(B),s.length===t.length&&r(s)})})})}function Ns(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var O5=t=>+t<10?`0${t}`:t,fgA=t=>{const i=t.match(/^\d+\.\d+\.\d+/)[0];if(!i)return t;const r=i.split("."),s=O5(r[1])+O5(r[2]);return r[1]-15>0&&(r[1]="15"),r[2]-15>0&&(r[2]="15"),`${r.join(".")}.${s}`},mgA=Object.prototype.hasOwnProperty;function DgA(t){if(t==null)return!0;if(typeof t=="boolean")return!1;if(typeof t=="number")return t===0;if(typeof t=="string"||typeof t=="function"||Array.isArray(t))return t.length===0;if(t instanceof Error)return t.message==="";if(Sw(t))switch(Object.prototype.toString.call(t)){case"[object File]":case"[object Map]":case"[object Set]":return t.size===0;case"[object Object]":for(const i in t)if(mgA.call(t,i))return!1;return!0}return!1}function R9(t,i){return{userId:i,hasAudio:!!(t&T5),hasVideo:!!(t&N5),hasAuxiliary:!!(t&qsA),hasSmall:!!(t&VsA),audioMuted:!!(t&G5),videoMuted:!!(t&k5),audioAvailable:!(!(t&T5)||t&G5),videoAvailable:!(!(t&N5)||t&k5),hasDatachannel:!!(t&KsA)}}function ygA(t){const i={urls:t.url.startsWith("turn:")||t.url.startsWith("turns:")?t.url:`turn:${t.url}`};return Fr(t.username)||Fr(t.credential)||(i.username=t.username,i.credential=t.credential,i.credentialType="password",Fr(t.credentialType)||(i.credentialType=t.credentialType)),i}function RgA(t,i=!0){if(!pC(t))return 0;const r=t.split(".");return i?(Number(r[0])<<24|Number(r[1])<<16|Number(r[2])<<8|Number(r[3]))>>>0:(Number(r[3])<<24|Number(r[2])<<16|Number(r[1])<<8|Number(r[0]))>>>0}var M9=function(t,i,r,s){if(!iD(t)||!iD(i))return 0;let g=0;const B=Object.keys(i);let Q;for(let f=0,m=B.length;f{i[s]=j2(r)}),i}if(iD(t)){const i={};return Object.keys(t).forEach(r=>{i[r]=j2(t[r])}),i}return t}var MgA=t=>{let i=[];if(dC(t))i=[...t];else if(pC(t)){const r=document.getElementById(t);r&&i.push(r)}else t&&i.push(t);return i},wgA=t=>pC(t)?document.getElementById(t):t,SgA=t=>{const i=r=>r<10?`0${r}`:`${r}`;return`${t.getFullYear()}/${t.getMonth()+1}/${t.getDate()} ${i(t.getHours())}:${i(t.getMinutes())}:${i(t.getSeconds())}`},vgA=()=>SgA(new Date);function hp(t,{keysToInclude:i,keysToExclude:r}){try{if(dC(t))return`[${t.map(Q=>hp(Q,{keysToInclude:i,keysToExclude:r})).join(",")}]`;if(!Sw(t)||!dC(i)&&!dC(r))return JSON.stringify(t);const s={},g=new Set(i),B=new Set(r);return Object.keys(t).forEach(Q=>{(B.size===0&&g.has(Q)||g.size===0&&!B.has(Q))&&(s[Q]=Sw(t[Q])||dC(t[Q])?JSON.parse(hp(t[Q],{keysToExclude:r,keysToInclude:i})):t[Q])}),JSON.stringify(s)}catch{return"{}"}}function Yj(t,i=!1){const r=[];return Object.keys(t).forEach(s=>{i===t[s]&&r.push(s)}),hp(t,{keysToInclude:r})}function NgA(t){return t.replace(/[\u4e00-\u9fa5]/g,"aa").length}var w9=()=>{var t,i,r,s;return(t=window.screen)!=null&&t.orientation?!!((s=(r=(i=window.screen)==null?void 0:i.orientation)==null?void 0:r.type)!=null&&s.includes("portrait")):window.orientation===0||window.orientation===180},TgA=async t=>new Promise((i,r)=>{let s;if(pC(t))s=new Image,s.crossOrigin="anonymous",s.src=t;else if(s=t,s.complete)return void i(s);s.onload=()=>i(s),s.onerror=()=>{r(new Ws({code:xa.INVALID_PARAMETER,message:`load image failed, url: ${t}`}))}}),S9=t=>{const i=t.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]},v9=t=>(Object.keys(t).forEach(i=>{hD(t[i])&&(i.startsWith("uint")||i.startsWith("int"))?t[i]=Math.floor(t[i]):(Sw(t[i])||dC(t[i]))&&v9(t[i])}),t);function vw(t,i){return new Promise(r=>{const s=setTimeout(r,t);i&&i(s)})}function N9(t,i){let r=null;return function(...s){return r||(r=t.apply(i||this,s),r.finally(()=>r=null),r)}}function GgA(t){return t.replace(/(^|[^:])\/{2,}/g,"$1/")}function kgA(t){var i;try{const{width:r,height:s,frameRate:g,sampleRate:B,sampleSize:Q,channelCount:f}=(i=t.getSettings)==null?void 0:i.call(t),m=t.kind===gt.AUDIO?`${B}x${Q}@${f}`:`${r}x${s}@${g}`,M=t.stats?` stats: ${JSON.stringify(t.stats).replaceAll('"',"")}`:"";return`${t.id} ${t.readyState} muted:${t.muted} ${t.kind} ${t.label} ${m}${M}`}catch{return""}}function T9(t,i){return t.width*t.height===i.width*i.height?1:w9()&&i.width>i.height&&t.height>i.width?Math.max(t.width/i.height,t.height/i.width,1):Math.max(t.width/i.width,t.height/i.height,1)}function G9(t){return t===90||t===270}async function _gA(t){return new Promise((i,r)=>{const s=document.createElement("video");s.crossOrigin="anonymous",s.src=t,s.muted=!0,s.loop=!0,s.playsInline=!0,s.play().then(()=>i(s)),s.onerror=()=>{r(s.error)}})}function Pj(t,i=new WeakMap){if(typeof t!="object"||t===null)return t;if(i.has(t))return i.get(t);if(Array.isArray(t)){const r=[];return i.set(t,r),t.forEach((s,g)=>{r[g]=Pj(s,i)}),r}if(Object.prototype.toString.call(t)==="[object Object]"){const r={};return i.set(t,r),Reflect.ownKeys(t).forEach(s=>{r[s]=Pj(t[s],i)}),r}return t}var k9=(t=>(t[t.END_REPORT=2001]="END_REPORT",t[t.LOG=2002]="LOG",t[t.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",t))(k9||{});function bgA(t,i,r,s){let g={data:t,random:Math.floor(Math.random()*2147483648),sdkAppId:r};return Fr(s)||(g=lB(cr({},g),{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:i,bytes_report_data:JSON.stringify(g)}}}function G3(t,i,r,s){try{const g=bgA(t,i,r,s);return AgA(Uj(g),r)}catch{return JSON.stringify(t)}}function LgA(t,i){const r=new Uint8Array(t.byteLength+i.byteLength);return r.set(new Uint8Array(t),0),r.set(new Uint8Array(i),t.byteLength),r.buffer}function FgA(t){return(65535&t)>>>0}function UgA(t){return(4294901760&t)>>>0}function k3(t){return!!(t&&t instanceof CanvasCaptureMediaStreamTrack&&t.canvas.id.includes("trtc_mix"))}function OgA(t){const i=xgA(t);return i?.busiBuff}function xgA(t){try{const i={};let r=0;i.totalLength=sE(t,r),r+=4,i.version=sE(t,r),r+=4,i.encryption=L5(t,r),r+=1,i.uinType=L5(t,r),r+=1,i.uinLength=sE(t,r),r+=4,i.uin=i.uinLength>4?hG(t,r,i.uinLength-4):"",r+=i.uinLength-4;const s=t.slice(r);if(i.encryption===2){const g=new Uint8Array(16).fill(0);t=YgA(s,g),i.decrypted=!0,r=0}else t=s,r=0;return i.rspHeadLength=sE(t,r),r+=4,i.seqNo=sE(t,r),r+=4,i.retCode=sE(t,r),r+=4,i.retStrLength=sE(t,r),r+=4,i.retStr=i.retStrLength?hG(t,r,i.retStrLength-4):"",r+=i.retStrLength-4,i.serviceCmdLength=sE(t,r),r+=4,i.serviceCmd=i.serviceCmdLength?hG(t,r,i.serviceCmdLength-4):"",r+=i.serviceCmdLength-4,i.cookieLength=sE(t,r),r+=4,i.cookie=i.cookieLength?hG(t,r,i.cookieLength-4):"",r+=i.cookieLength-4,i.flag=sE(t,r),r+=4,i.busiBuffLength=sE(t,r),r+=4,i.busiBuff=i.busiBuffLength?hG(t,r,i.busiBuffLength-4):"",r+=i.busiBuffLength-4,i}catch{}}function _9(t,i){let r=t[0]<<24|t[1]<<16|t[2]<<8|t[3],s=t[4]<<24|t[5]<<16|t[6]<<8|t[7];r>>>=0,s>>>=0;let g=Oj*xj>>>0;for(let B=0;B>>5)+i[3],s>>>=0,r-=(s<>>5)+i[1],r>>>=0,g-=Oj,g>>>=0;return new Uint8Array([r>>>24&255,r>>>16&255,r>>>8&255,255&r,s>>>24&255,s>>>16&255,s>>>8&255,255&s])}function YgA(t,i){let r=0;const s=new Uint8Array(8).fill(0);let g=_9(new Uint8Array(t.slice(0,8)),i);const B=7&g[0],Q=t.length-1-B-ZG-XG,f=new Uint8Array(Q);let m=0,M=s,v=t.slice(0,8);r=8;let U=1;U+=B;for(let z=1;z<=ZG;)if(U<8)U++,z++;else if(U===8){const sA=HK(t,r,M,v,g,i);M=sA.ivPreCrypt,v=sA.ivCurCrypt,g=sA.debiBuf,r=sA.bufPos,U=0}let AA=Q;for(;AA>0;)if(U<8)f[m++]=g[U]^M[U],U++,AA--;else if(U===8){const z=HK(t,r,M,v,g,i);M=z.ivPreCrypt,v=z.ivCurCrypt,g=z.debiBuf,r=z.bufPos,U=0}for(let z=1;z<=XG;)if(U<8)g[U],M[U],U++,z++;else if(U===8){if(r>=t.length)break;const sA=HK(t,r,M,v,g,i);if(!sA.success)break;M=sA.ivPreCrypt,v=sA.ivCurCrypt,g=sA.debiBuf,r=sA.bufPos,U=0}return f}function HK(t,i,r,s,g,B){if(i+8>t.length)return{success:!1};const Q=new Uint8Array(s),f=t.slice(i,i+8),m=new Uint8Array(8);for(let M=0;M<8;M++)m[M]=g[M]^f[M];return{success:!0,ivPreCrypt:Q,ivCurCrypt:f,debiBuf:_9(m,B),bufPos:i+8}}var x5=typeof TextDecoder<"u"?new TextDecoder:void 0;function b9({url:t,body:i,method:r="POST",timeout:s,priority:g}){return new Promise((B,Q)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:g}).then(m=>m.clone().json().then(M=>({data:M}),()=>m.arrayBuffer().then(M=>({data:OgA(new Uint8Array(M))||(x5?x5.decode(M):M)})))).then(B,Q);const f=new XMLHttpRequest;f.onreadystatechange=()=>{if(f.readyState===4)if(f.status>=200&&f.status<300)try{const m=JSON.parse(f.response);B({data:m})}catch{B({data:f.response})}else Q({status:f.status,statusText:f.statusText||"request failed!"})},f.timeout=s||5e3,f.open(r,t,!0),f.send(i)})}var PgA=Object.prototype.hasOwnProperty,sw=t=>typeof t=="function",XM=t=>t===void 0,JgA=t=>typeof t=="boolean",VK=t=>t.isRemote,HgA=function(t){if(!t||typeof t!="object"||Object.prototype.toString.call(t)!="[object Object]")return!1;const i=Object.getPrototypeOf(t);if(i===null)return!0;const r=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.toString.call(r)===Function.prototype.toString.call(Object)};function VgA(t){if(t==null)return!0;if(typeof t=="boolean")return!1;if(typeof t=="number")return t===0;if(typeof t=="string"||typeof t=="function"||Array.isArray(t))return t.length===0;if(t instanceof Error)return t.message==="";if(HgA(t))switch(Object.prototype.toString.call(t)){case"[object File]":case"[object Map]":case"[object Set]":return t.size===0;case"[object Object]":for(const i in t)if(PgA.call(t,i))return!1;return!0}return!1}var qgA=0,KgA=1,Y5=2;function jgA({retryFunction:t,settings:i,onError:r,onRetrying:s,onRetryFailed:g,onRetrySuccess:B,context:Q}){return function(...f){const{retries:m=5,timeout:M=1e3}=i;let v=0,U=-1,AA=qgA;const z=async(sA,eA)=>{const X=Q||this;try{const QA=await t.apply(X,f);v>0&&B&&B.call(this,v),v=0,sA(QA)}catch(QA){const wA=()=>{clearTimeout(U),v=0,AA=Y5,eA(QA)},HA=()=>{AA!==Y5&&v<(sw(m)?m():m)?(v++,AA=KgA,sw(s)&&s.call(this,v,wA),U=window.setTimeout(()=>{U=-1,z(sA,eA)},sw(M)?M(v):M)):(wA(),sw(g)&&g.call(this,QA))};sw(r)?r.call(this,{error:QA,retry:HA,reject:eA,retryFuncArgs:f,retriedCount:v}):HA()}};return new Promise(z)}}var _3=jgA,qK=class L9{constructor(i){OA(this,"_parentPath"),OA(this,"userId"),OA(this,"remoteUserId"),OA(this,"id"),OA(this,"sdkAppId"),OA(this,"type"),OA(this,"isLocal"),this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=!JgA(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 r=new L9({id:i.id,userId:XM(i.userId)?this.userId:i.userId,sdkAppId:XM(i.sdkAppId)?this.sdkAppId:i.sdkAppId,type:XM(i.type)?this.type:i.type,isLocal:XM(i.isLocal)?this.isLocal:i.isLocal,remoteUserId:XM(i.remoteUserId)?this.remoteUserId:i.remoteUserId});return r.bindParent(this),r}bindParent(i){const r=i.getFullId();this._parentPath!==r&&(this.debug(`bind logger parent: ${i.id}`),this._parentPath=r,this.userId=i.userId||this.userId,this.sdkAppId=i.sdkAppId||this.sdkAppId)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,r){const s=this.isLocal?this.userId:this.remoteUserId,g=this.getFullId();r.unshift(`[${this.isLocal?"↑":"↓"}${this.type&&this.type!=="main"?"*":""}${g}${s?`|${s}`:""}]`),qi.log(i,r,XM(this.userId)||VgA(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)}},xu=typeof navigator>"u"?"":navigator.userAgent,bo=t=>new RegExp(t,"i").test(xu),cs=t=>{if(bo(t)){const i=new RegExp(`${t}\\/([\\d.]+)`),r=xu.match(i);if(r&&r[1])return r[1]}return""},SY=t=>{if(bo(t)){const i=new RegExp(`${t}\\/(\\d+)`),r=xu.match(i);if(r&&r[1])return parseFloat(r[1])}return NaN},P5=/AppleWebKit\/([\d.]+)/i.exec(xu);P5&&parseFloat(P5[1]);var b3=bo("iPad"),F9=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&bo("Macintosh"),vY=bo("iPhone")&&!b3,WgA=bo("iPod"),UI=vY||b3||WgA||F9,W2=()=>{try{return UI&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch{return UI}},hl=bo("Android"),U9=function(){if(hl){const t=xu.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(t){const i=t[1]&&parseFloat(t[1]),r=t[2]&&parseFloat(t[2]);if(i&&r)return parseFloat(`${t[1]}.${t[2]}`);if(i)return i}}return NaN}();hl&&bo("webkit")&&U9<2.3;var Ql=bo("Firefox"),O9=cs("Firefox"),x9=SY("Firefox"),Tk=bo("Edge"),Y9=cs("Edge"),NY=bo("Edg"),P9=cs("Edg"),zgA=SY("Edg"),L3=bo("SogouMobileBrowser"),J9=cs("SogouMobileBrowser"),F3=bo("MetaSr\\s"),H9=cs("MetaSr\\s"),ld=bo("TBS"),V9=cs("TBS"),Lw=bo("XWEB"),q9=cs("XWEB");bo("MSIE\\s8\\.0");var ZgA=bo("MSIE\\/\\d+");(function(){if(ZgA){const t=/MSIE\s(\d+)\.\d/.exec(xu);let i=t&&parseFloat(t[1]);return!i&&/Trident\/7.0/i.test(xu)&&/rv:11.0/.test(xu)&&(i=11),i}return NaN})();var Gk=bo("(micromessenger|webbrowser)"),K9=cs("MicroMessenger"),TY=!ld&&bo("MQQBrowser")&&bo("COVC"),GY=!ld&&bo("MQQBrowser")&&!bo("COVC"),z2=GY||TY?cs("MQQBrowser"):"",U3=!ld&&bo(" QQBrowser"),j9=cs(" QQBrowser"),O3=!ld&&bo("QQBrowserLite"),W9=cs("QQBrowserLite"),x3=!ld&&bo("MQBHD"),z9=cs("MQBHD"),Z9=bo("Windows"),kY=!UI&&bo("MAC OS X"),X9=!hl&&bo("Linux"),$9=bo("CrOS");bo("MicroMessenger");var XgA=bo("UCBrowser");bo("Electron");var Y3=bo("MiuiBrowser"),AX=cs("MiuiBrowser"),P3=bo("HuaweiBrowser"),eX=bo("Huawei")||bo("HUAWEI"),$gA=bo("Honor")||bo("HONOR"),tX=cs("HuaweiBrowser"),J3=bo("SamsungBrowser"),iX=cs("SamsungBrowser"),_Y=bo("HeyTapBrowser"),oX=cs("HeyTapBrowser"),H3=bo("VivoBrowser"),rX=cs("VivoBrowser"),V3=bo("OpenHarmony");cs("OpenHarmony");var nX=()=>SY("Chrome"),Z2=bo("CriOS"),yp=bo("Chrome"),q3=!Tk&&!F3&&!L3&&!ld&&!Lw&&!NY&&!U3&&!Y3&&!P3&&!J3&&!_Y&&!H3&&yp,AIA=bo("HeadlessChrome"),Rp=nX(),KK=yp&&Rp>=128&&Rp<=143,aX=cs("Chrome");SY("Electron");var cE=!yp&&!GY&&!TY&&!O3&&!x3&&bo("Safari"),sX=cE||UI,kk=cs("Version"),Fu=(()=>{if(F9)return kk;if(UI){const t=xu.match(/OS (\d+)_(\d+)/i);if(t&&t[1]){let i=t[1];return t[2]&&(i+=`.${t[2]}`),i}}return""})();function eIA(t,i){const r=t.split(".").map(g=>Number(g)),s=i.split(".").map(g=>Number(g));for(let g=0;gQ)return!1}return!1}function gX(t,i,r=!1){const s=t.split(".").map(B=>Number(B)),g=i.split(".").map(B=>Number(B));for(let B=0;Bf)return!0;if(Q{const t=Number(Fu.split(".")[0]);return t===14||t===13})(),oIA=Z2&&kk==="11.1.1",X2=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),$M=(()=>{let t;return()=>{if(t===void 0)try{t=!!window.localStorage}catch{t=!1}return t}})(),ID=rIA();function rIA(){const t=new Map([[Ql,["Firefox",O9]],[NY,["Edg",P9]],[q3,["Chrome",aX]],[Z2,["ChiOS",cs("CriOS")]],[cE&&!Z2,["Safari",kk]],[ld,["TBS",V9]],[Lw,["XWEB",q9]],[Gk&&vY,["WeChat",K9]],[U3,["QQ(Win)",j9]],[GY,["QQ(Mobile)",z2]],[TY,["QQ(Mobile X5)",z2]],[O3,["QQ(Mac)",W9]],[x3,["QQ(iPad)",z9]],[Y3,["MI",AX]],[P3,["HW",tX]],[J3,["Samsung",iX]],[_Y,["OPPO",oX]],[H3,["VIVO",rX]],[Tk,["EDGE",Y9]],[L3,["SogouMobile",J9]],[F3,["Sogou",H9]]]);let i="unknown",r="unknown";return t.has(!0)&&([i,r]=t.get(!0)),{name:i,version:r}}function nIA(){return hl||UI||vY||b3||V3}var aIA="";function IX(){return sIA()||""}function sIA(){const t=xu.match(/;\s*([^;)]+)\s+Build\//);return t?.[1]?t[1].trim():null}var J5=new Map([[hl,"Android"],[UI,"iOS"],[Z9,"Windows"],[kY,"MacOS"],[X9,"Linux"],[$9,"ChromeOS"]]),cX=function(){return J5.get(!0)?J5.get(!0):"unknown"};function K3(){return Z9?1:hl?2:kY?3:UI?4:X9?5:$9?6:V3?7:0}function gIA(){return Gk||Lw?4:yp?1:cE?2:Ql?3:0}var EX=()=>{let t=cX();return UI?t+=`/${Fu}`:hl&&(t+=`/${U9}`),t+=`/${ID.name}/${cE&&!Z2?ID.version:ID.version.split(".")[0]}`,t},IIA=bw(vk()),cIA=new IIA.default,Eo=cIA,lX=(t=>(t.ROOM_DESTROY="1",t.JOIN_START="21",t.JOIN_SCHEDULE_SUCCESS="22",t.JOIN_SIGNAL_CONNECTION_START="23",t.JOIN_SIGNAL_CONNECTION_END="24",t.JOIN_SEND_CMD="25",t.JOIN_RECEIVED_CMD_RES="26",t.JOIN_SUCCESS="27",t.JOIN_FAILED="28",t.LEAVE_START="51",t.LEAVE_SEND_CMD="52",t.LEAVE_SUCCESS="53",t.PUBLISH_START="61",t.SEND_FIRST_VIDEO_FRAME="62",t.PUBLISH_FAILED="63",t.SUBSCRIBE_START="81",t.SUBSCRIBE_SUCCESS="82",t.SUBSCRIBE_FAILED="84",t.UNSUBSCRIBE_SUCCESS="83",t.LOCAL_TRACK_CAPTURE_START="101",t.LOCAL_TRACK_CAPTURE_SUCCESS="102",t.LOCAL_TRACK_CAPTURE_FAILED="103",t.LOCAL_TRACK_PUBLISHED="104",t.LOCAL_TRACK_UNPUBLISHED="105",t.LOCAL_TRACK_REPLACED="106",t.SWITCH_DEVICE_SUCCESS="107",t.TRACK_MUTED="108",t.TRACK_UNMUTED="109",t.REMOTE_TRACK_SUBSCRIBED="110",t.REMOTE_TRACK_UNSUBSCRIBED="111",t.LOCAL_TRACK_RECAPTURE="112",t.LOCAL_AUDIO_STARTED="113",t.LOCAL_AUDIO_STOPPED="114",t.REMOTE_AUDIO_STARTED="115",t.REMOTE_AUDIO_STOPPED="116",t.LOCAL_TRACK_STOPPED="117",t.LOCAL_VIDEO_TRACK_PREPROCESSED="118",t.PLAY_TRACK_START="151",t.PLAYER_STATE_CHANGED="152",t.VIDEO_LOADED_DATA="153",t.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",t.AUDIO_CONTEXT_LONG_SUSPENDED="155",t.REMOTE_VIDEO_PLAY_START="156",t.REMOTE_VIDEO_PLAY_FINISH="157",t.SIGNAL_CONNECTION_STATE_CHANGED="201",t.PEER_CONNECTION_STATE_CHANGED="202",t.SINGLE_CONNECTION_STAT="203",t.SPC_RECONNECTED="204",t.HEARTBEAT_REPORT="251",t.RECEIVED_PUBLISHED_USER_LIST="252",t.REMOTE_PUBLISH_STATE_CHANGED="253",t.AUDIO_LEVEL_INTERVAL="260",t.NETWORK_QUALITY="261",t.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",t.QUALITY_LIMITATION_CHANGED="263",t.LOG="264",t.AUDIO_PROCESSOR_DEBUG="265",t.SSO_SWITCH="266",t.SEI_MESSAGE="267",t.USER_PAUSE_IN_PIP="268",t.USER_RESUME_IN_PIP="269",t.ENTER_PICTURE_IN_PICTURE="270",t.LEAVE_PICTURE_IN_PICTURE="271",t.SWITCH_ROOM_START="401",t.SWITCH_ROOM_SUCCESS="407",t.SWITCH_ROOM_FAILED="408",t))(lX||{}),nr=lX,EIA=class{constructor(){OA(this,"enable",!1),OA(this,"ssoFailCount",0),Eo.on("22",({schedule:t})=>{var i;(i=t?.config)!=null&&i.sso&&Eo.emit("266",{enable:!0})}),Eo.on("266",({enable:t})=>{this.enable=t})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&Eo.emit("266",{enable:!1})}},Jj=new EIA,lIA="%cTRTC%c%s",CIA="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",BIA="display: inline",CX=class BX{constructor(){OA(this,"_isEnableUploadLog",!0),OA(this,"_localJoinedUser",new Map),OA(this,"_queue",[]),OA(this,"_timeoutId",-1),OA(this,"_logLevel",1),OA(this,"_logLevelToUpload",2),l9||C9||(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){Eo.on(nr.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var r;(r=i?.config)!=null&&r.logLevelToUpload&&nw[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),Eo.on(nr.JOIN_START,({params:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),Eo.on(nr.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 r=0;for(;r{i.map.has(g)?i.map.get(g).logs.push(s):i.map.set(g,{userId:g,sdkAppId:B,logs:[s]})});else if(pC(s.userId)&&hD(s.sdkAppId)){const{userId:g,sdkAppId:B}=s;i.map.has(g)?i.map.get(g).logs.push(s):i.map.set(g,{userId:g,sdkAppId:B,logs:[s]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,r)),i}async upload(){if(this._queue.length===0||!this._isEnableUploadLog)return;const{map:i,splicedQueue:r}=this.getLogsToUpload();if(i.size===0)return;try{const g=[...i.values()];for(let B=0;BAA.log).join(` +`)},v=JSON.stringify(M),U=Jj.enable?G3(M,2002,f):v;await this.uploadLogWithRetry(U,f,U instanceof Uint8Array,v),m.forEach(AA=>AA.uploaded=!0)}}catch{}const s=r.filter(g=>!g.uploaded);s.length>0&&(this._queue=s.concat(this._queue))}uploadLogWithRetry(i,r,s,g){return _3({retryFunction:()=>b9({url:v3(r,B9.LOG),body:i,timeout:5e3,priority:"low"}).then(B=>{s&&B.data!=="ok"&&(Jj.handleUploadFailed(),this.uploadLogWithRetry(g,r,!1,g))}),settings:{retries:3,timeout:2e3},onError:({retry:B})=>{B()}})()}getPrefix(i){const r=new Date;return r.setTime(S3()),`[${LsA(r)}] <${nw[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){Fr(nw[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(pC(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch{return""}}addLogToQueue(i,r,s=!0,g,B){const Q={log:r.reduce((f,m)=>`${f} ${this.logChunkToString(m)}`.trim(),""),level:i,userId:g,sdkAppId:B,forAllJoinedClients:s};Eo.emit(nr.LOG,{log:Q}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(Q)}log(i,r,s=!0,g,B){var Q;if(r.unshift(this.getPrefix(i)),this.addLogToQueue(i,r,s,g,B),i{const i=16*Math.random()|0;return(t=="x"?i:3&i|8).toString(16)})},uX=QIA,dIA=class{constructor(){OA(this,"_prefix","TRTC"),OA(this,"_queue",new Map)}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){$M()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix))try{const i=localStorage.getItem(t);if(!i)return!1;const r=JSON.parse(i);if(r&&r.expiresInlocalStorage.removeItem(t)))}doFlush(){if($M())try{for(const[t,i]of this._queue)localStorage.setItem(t,JSON.stringify(i))}catch(t){qi.warn(t)}}getItem(t){if(!$M())return null;try{const i=localStorage.getItem(this.getRealKey(t));if(!i)return null;const r=JSON.parse(i);return r&&r.expiresIn>=Date.now()?r.value:null}catch(i){qi.warn(i)}}setItem(t,i){if($M())try{const r={expiresIn:Date.now()+PsA,value:i};this._queue.set(this.getRealKey(t),r)}catch(r){qi.warn(r)}}deleteItem(t){if(!$M())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(i){return qi.warn(i),!1}}clear(){if($M())try{localStorage.clear()}catch(t){qi.warn(t)}}},QX=new dIA,hIA={};M3(hIA,{HTTPS_API:()=>GIA,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>GX,IS_GET_CAPABILITIES_SUPPORTED:()=>TX,IS_GET_SETTINGS_SUPPORTED:()=>eY,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>YIA,IS_INSERTABLE_STREAM_SUPPORTED:()=>kX,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>KIA,IS_RTC_RTP_SENDER_SUPPORTED:()=>_k,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>_X,IS_SEI_SUPPORTED:()=>PIA,IS_SPC_SUPPORTED:()=>FIA,basis:()=>HIA,capabilityCheck:()=>VIA,checkSystemRequirementsInternal:()=>fX,decodeSupportStatus:()=>pX,detectH264SupportedByFakeStreaming:()=>mX,detectVideoCodecCapabilities:()=>jIA,detectVideoDecoderCapabilities:()=>xX,detectVideoEncoderCapabilities:()=>OX,encodeSupportStatus:()=>Z3,getBrowserInfo:()=>RIA,getDisplayResolution:()=>DX,getH264ProfileLevelIds:()=>YX,isAddTransceiverSupported:()=>LY,isBrowserSupported:()=>j3,isCanvasCaptureStreamAPISupported:()=>MX,isCanvasSmallStreamSupported:()=>wX,isGetReceiversSupported:()=>bIA,isGetSendersSupported:()=>NX,isGetTransceiversSupported:()=>LIA,isGetUserMediaSupported:()=>yX,isMediaDevicesSupported:()=>z3,isMediaSessionSupported:()=>LX,isMediaStreamTrackGeneratorSupported:()=>wIA,isMediaStreamTrackProcessorSupported:()=>MIA,isReplaceTrackSupported:()=>OIA,isRequestVideoFrameCallbackSupported:()=>AW,isSIMDSupported:()=>JIA,isScaleResolutionDownBySupported:()=>SX,isScreenCaptureApiAvailable:()=>X3,isSelectedCandidatePair:()=>kIA,isSetParametersSupported:()=>xIA,isSetSinkIdSupported:()=>NIA,isSmallStreamSupported:()=>vX,isStopTransceiverSupported:()=>UIA,isTRTCSupported:()=>vIA,isUnifiedPlanDefault:()=>_IA,isUsedInHttpProtocol:()=>bY,isWebAudioSupported:()=>RX,isWebCodecSupported:()=>bX,isWebCodecsSupported:()=>W3,isWebRTCSupported:()=>$3,isWebTransportSupported:()=>FX});var $2={PLAY_FAILED:"PLAY_FAILED",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND"},lw={AVOID_REPEATED_CALL:t=>`previous ${t.name}() is ongoing, please avoid repeated calls.`,INVALID_PARAMETER_REQUIRED:({key:t,rule:i,fnName:r,value:s})=>`'${t||i.name}' is a required param when calling ${r}(), received: ${s}.`,INVALID_PARAMETER_TYPE({key:t,rule:i,fnName:r,value:s}){const g=`${t||i.name}`;let B="";return B=Array.isArray(i.type)?i.type.join("|"):i.type,`'${g}' must be type of ${B} when calling ${r}(), received type: ${dD(s)}.`},INVALID_PARAMETER_EMPTY:({key:t,rule:i,fnName:r,value:s})=>`'${t||i.name}' cannot be '${s}' when calling ${r}().`,INVALID_PARAMETER_INSTANCE:({key:t,rule:i,fnName:r,value:s})=>`'${`${t||i.name}`}' must be instanceof ${`${i.instanceOf.name||i.instanceOf}`} when calling ${r}(), received type: ${dD(s)}.`,INVALID_PARAMETER_RANGE:({key:t,rule:i,fnName:r,value:s})=>`'${t||i.name}' must be one of ${i.values.join("|")} when calling ${r}(), received: ${s}.`,INVALID_PARAMETER_MIN:({key:t,rule:i,fnName:r,value:s})=>`the min value of ${t||i.name} is ${i.min}, received: ${s}.`,INVALID_PARAMETER_MAX:({key:t,rule:i,fnName:r,value:s})=>`the max value of ${t||i.name} is ${i.max}, received: ${s}.`,API_CALL_TIMEOUT:t=>`${t.commandDesc||t.command} timeout observed.`,SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:t=>`SignalChannel setup failure: (errorCode: ${t.errorCode}, errorMsg: ${t.errorMsg} }).`,ERROR_MESSAGE(t){let i=`${t.type} failed`;return t.message&&(i=`${i}: ${t.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:t=>`exchange sdp failed ${t.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:t=>`'${t}' must be validate string when useStringRoomId is true.`,INVALID_ROOMID_INTEGER:t=>`'${t}' 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:t,code:i})=>`Failed to join room - ${t} code: ${i}`,REJOIN_ROOM_FAILED:t=>`reJoin room: ${t.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:t=>`duplicate ${t} stream publishing, please unpublish your prev ${t} 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:t,userId:i,streamType:r})=>`failed to subscribe ${i} ${r} stream, reason: ${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:t=>`switchRole failed, errCode: ${t.code} errMsg: ${t.message}.`,CLIENT_BANNED:t=>`client was banned because of ${t.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:t=>`startPublishCDNStream failed, errMsg: ${t.message}.`,STOP_PUBLISH_CDN_FAILED:t=>`stopPublishCDNStream failed, errMsg: ${t.message}.`,INVALID_STREAM_ID:t=>`'${t}' 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:t=>`cannot replace ${t.kind} track because stream has not ${t.kind} track`,NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:t=>`startMixTranscode failed, errMsg: ${t.message}.`,STOP_MIX_TRANSCODE_FAILED:t=>`stopMixTranscode failed, errMsg: ${t.message}.`,MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO:({key:t,rule:i,fnName:r,value:s})=>`'${t||i.name}' cannot be less than 0 when calling ${r}().`,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:t=>`'${t}' 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:t,fnName:i})=>`'${t}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:t,fnName:i,type:r})=>`the element corresponding to '${t}' must be instanceof HTMLElement when calling ${i}(), received: ${r}.`,PLAY_FAILED:t=>`${t.media} play failed, browser exception: ${t.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:t=>`${t}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:t=>`${t.signalResponse} failed, response code is ${t.code} , errMsg: ${t.message}.`,CATCH_HANDLER_ERROR:({name:t,event:i})=>`an error was caught in ${t}.on('${i}', handler), please check your code in 'handler'.`,API_NOT_EXIST:({name:t})=>`experimental api ${t} does not exist.`,REPEAT_JOIN:t=>"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:t})=>`failed to call ${t}() because client was destroyed.`,SEI_NOT_SUPPORT:t=>"not support to sendSEIMessage"+(t===!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:t,name:i,timesInSecond:r,maxSizeInSecond:s})=>`api ${i} call ${t?"size":"times"} is over ${t?`${s} bytes`:r} in a second.`,CONNECTION_ABORTED:t=>`connection aborted due to: ${t}`,API_CALL_ABORTED(t){let i;return i=t.message.includes("REMOTE_STREAM_NOT_EXIST")?`Subscribe ${t.userId} ${t.streamType} stream aborted, reason: remote user ${t.userId} unpublished stream.`:`API aborted, reason: ${t.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:t=>`'streamType' is required when 'userId' is not '*', calling ${t}()`,SWITCH_PLAYBACK_QUALITY_TIMEOUT:t=>`switchPlaybackQuality timeout: waiting for first frame of user ${t.userId}.`},H5=(t,i)=>i?`${_j}/${t}/${i}`:`${_j}/${t}/index.html`,pIA=()=>{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 t=localStorage==null?void 0:localStorage.getItem(YsA);if(t){t=JSON.parse(t);const i=document.createElement("script");i.type="text/javascript",i.text=t.message,document.body.appendChild(i);const r=window.TRTC_ERROR_INFO,s=window.TRTC_ERROR_LINK;return document.body.removeChild(i),{TRTC_ERROR_INFO:r,TRTC_ERROR_LINK:s}}return{}};function AY(t){const{key:i,data:r,link:s,addDocLink:g=!0}=t;let B="",Q="",f="";sD(lw[i])?B=lw[i](r):pC(lw[i])&&(B=lw[i]);const{TRTC_ERROR_INFO:m,TRTC_ERROR_LINK:M}=pIA();s?f=`${s.className}.html#${s.fnName}`:M&&M[i]&&(sD(M[i])?f=M[i](r):pC(M[i])&&(f=M[i]));let v=B;return dp()&&(m&&m[i]&&(sD(m[i])?Q=m[i](r):pC(m[i])&&(Q=m[i])),Q&&(v=g?`${Q} +请查看文档: ${H5("zh-cn",f)} `:`${Q} `,v+=B)),g&&(v+=` -Refer to: ${F5("en",f)} -`),v}var U5=Tw(QsA()),IIA=1,cIA=0,gX=class{constructor(t=!0){OA(this,"countMap",new Map),OA(this,"distributionMap",new Map),OA(this,"version"),OA(this,"log",qi.createLogger({id:"kv"})),t&&(Eo.on("102",({track:i,cost:r})=>{this.addSuccessEvent({key:i.kind===gt.AUDIO?501700:511700,cost:r})}),Eo.on("103",({track:i,error:r})=>{this.addFailedEvent({key:i.kind===gt.AUDIO?501700:511700,error:r})}),Eo.on("266",({enable:i})=>{this.log.info((i?"enable":"disable")+" sso"),i?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(t,i){const r={msg_sdk_basic_info:{uint32_sdk_version:h9(this.version||x2),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([s,g])=>({uint32_key:s,uint32_count:g})),stats_distribution:[...this.distributionMap.entries()].map(([s,g])=>({uint32_key:s,distribution_items:[...g.entries()].map(([B,Q])=>({uint32_item_key:B,uint32_item_value:Q}))})),str_user_sig:t,bytes_report_token:i};return this.countMap.clear(),this.distributionMap.clear(),r}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(t){const i=+String(t).slice(-3);return i>=700&&i<799}isErrorCodeKey(t){const i=+String(t).slice(-3);return i>=600&&i<699}isCountKey(t){const i=+String(t).slice(-3);return i>=0&&i<599}isNumberKey(t){const i=+String(t).slice(-3);return i>=800&&i<899}addCount({key:t,useUV:i=!1}){this.isCountKey(t)?i&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug(`${t} is not count key, last 3 number should be 0~599`)}addEnum({key:t,value:i,useUV:r=!0}){var s;if(!this.isEnumKey(t))return this.log.debug(`${t} is not enum key, last 3 number should be 700~799`);if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);const g=((s=this.distributionMap)==null?void 0:s.get(t))||new Map;g.set(i,(g.get(i)||0)+1),this.distributionMap.set(t,g)}addNumber({key:t,value:i,split:r=100,useUV:s=!1,max:g=5e3}){var B;if(!this.isNumberKey(t))return this.log.debug(`${t} is not number key, last 3 number should be 800~899`);if(s&&this.countMap.has(t))return;i>g&&(i=g),this.countMap.set(t,(this.countMap.get(t)||0)+1);const Q=((B=this.distributionMap)==null?void 0:B.get(t))||new Map;let f=0;if(uD(r))f=Math.floor(i/r);else for(let m=r.length-1;m>0;m--)if(i>r[m]){f=m;break}Q.set(f,(Q.get(f)||0)+1),this.distributionMap.set(t,Q)}addSuccessEvent({key:t,cost:i,timeKey:r,split:s}){if(t&&(this.addEnum({key:t,value:IIA,useUV:!1}),i)){const g=+String(t).slice(-3);g<800&&g>=700?this.addNumber({key:r||t+100,value:i,split:s}):r||this.log.debug(`time stat ignored, ${t}`)}}addFailedEvent({key:t,error:i}){if(!t)return;let r=xa.UNKNOWN;i&&(uD(i)?r=i:Fr(i.extraCode)&&Fr(i.code)||(r=i.extraCode||i.code)),this.addEnum({key:t,value:cIA,useUV:!1}),this.addEnum({key:t,value:Math.abs(r),useUV:!1})}},IX=(t=>(t[t.DECODER_TYPE=514700]="DECODER_TYPE",t[t.DECODER_HW_SW=514701]="DECODER_HW_SW",t[t.DECODE_RESULT=514702]="DECODE_RESULT",t[t.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",t[t.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",t[t.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",t[t.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",t[t.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",t[t.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",t[t.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",t[t.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",t[t.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",t[t.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",t[t.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",t[t.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",t[t.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",t[t.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",t[t.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",t[t.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",t))(IX||{}),EIA=new gX(!0);new gX(!1);var qr=EIA,Oo={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}},lIA=new Map([[Ql,["Firefox",N9]],[yY,["Edg",k9]],[x3,["Chrome",X9]],[IE,["Safari",Mk]],[Id,["TBS",L9]],[Gw,["XWEB",F9]],[Rk&&DY,["WeChat",U9]],[G3,["QQ(Win)",O9]],[MY,["QQ(Mobile)",H2]],[RY,["QQ(Mobile X5)",H2]],[k3,["QQ(Mac)",x9]],[_3,["QQ(iPad)",Y9]],[b3,["MI",V9]],[L3,["HW",K9]],[F3,["Samsung",j9]],[SY,["OPPO",W9]],[U3,["VIVO",z9]],[yk,["EDGE",G9]],[N3,["SogouMobile",_9]],[T3,["Sogou",b9]]]);function CIA(){const t=lIA.get(!0);return{browserName:t?t[0]:"unknown",browserVersion:t?t[1]:"unknown"}}var P3=function(){return!YgA&&!yk&&!(yY&&OgA<80)&&!(Ql&&T9<56)},J3=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(t=>t in window)},H3=function(){if(!navigator.mediaDevices)return vY()||qi.error(Iw.NOT_SUPPORTED_MEDIA),!1;const t=["getUserMedia","enumerateDevices"];return t.filter(i=>i in navigator.mediaDevices).length===t.length},O5=!1;function vY(){return location.protocol==="http:"&&!q2&&(O5||qi.error(j2({key:K2.NOT_SUPPORTED_HTTP})),O5=!0,!0)}var BIA=function(){return window?.OffscreenCanvas&&window?.MediaStreamTrackProcessor&&window?.MediaStreamTrackGenerator},uIA=function(){return!!window?.MediaStreamTrackGenerator},V3=async function(){var t,i,r;if(Oo.detail.isH264EncodeSupported&&Oo.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Oo.detail.isH264EncodeSupported,isVp8EncodeSupported:Oo.detail.isVp8EncodeSupported,isH265EncodeSupported:Oo.detail.isH265EncodeSupported};let s,g=!1,B=!1,Q=!1;try{const f=new RTCPeerConnection,m=document.createElement(gt.CANVAS);m.getContext("2d");const M=m.captureStream(0);return f.addTrack(M.getVideoTracks()[0],M),s=await f.createOffer(),g=((t=s.sdp)==null?void 0:t.toLowerCase().indexOf("h264"))!==-1,B=((i=s.sdp)==null?void 0:i.toLowerCase().indexOf("vp8"))!==-1,Q=((r=s.sdp)==null?void 0:r.toLowerCase().indexOf("h265"))!==-1,f.close(),{isH264EncodeSupported:g,isVp8EncodeSupported:B,isH265EncodeSupported:Q}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}},cX=async function(){var t;if(Oo.detail.isH264DecodeSupported&&Oo.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Oo.detail.isH264DecodeSupported,isVp8DecodeSupported:Oo.detail.isVp8DecodeSupported,isH265DecodeSupported:Oo.detail.isH265DecodeSupported};let i,r=!1,s=!1;try{const g=new RTCPeerConnection;NY()?(g.addTransceiver(gt.VIDEO,{direction:"recvonly"}),i=await g.createOffer()):i=await g.createOffer({offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(r=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(s=!0);const B=((t=i.sdp)==null?void 0:t.toLowerCase().indexOf("h265"))!==-1;return g.close(),{isH264DecodeSupported:r,isVp8DecodeSupported:s,isH265DecodeSupported:B}}catch{return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}};async function QIA(){const[t,i]=await Promise.all([V3(),cX()]);return{encode:{h264:t.isH264EncodeSupported,vp8:t.isVp8EncodeSupported,h265:t.isH265EncodeSupported},decode:{h264:i.isH264DecodeSupported,vp8:i.isVp8DecodeSupported,h265:i.isH265DecodeSupported}}}var EX=f9(async t=>{const i=Date.now(),r=K3(),s=H3(),g=J3();if(Oo.detail.isWebRTCSupported=r,Oo.detail.isMediaDevicesSupported=s,Oo.detail.isWebCodecsSupported=g,Oo.detail.isScreenShareSupported=q3(),Oo.detail.isSmallStreamSupported=pX(),t===37)return Object.assign(Oo.detail,await pIA()),Oo.detail.isBrowserSupported=g,Oo.result=s&&g,Oo.result||qi.error(`${navigator.userAgent} ${bj(Oo.detail,!1)}`),P5(t),qr.addNumber({key:523800,value:Date.now()-i}),Oo;if(Oo.result&&Oo.detail.isH264EncodeSupported&&Oo.detail.isVp8EncodeSupported&&Oo.detail.isH265EncodeSupported&&Oo.detail.isH264DecodeSupported&&Oo.detail.isVp8DecodeSupported&&Oo.detail.isH265DecodeSupported)return Oo;const B=P3(),{encode:Q,decode:f}=await QIA();let{h264:m,vp8:M}=Q,{h264:v}=f;const{h265:U}=Q,{vp8:AA,h265:z}=f;if(!m||!M){const sA=await V3();qi.warn(`detect encode again h264:${m} vp8:${M} result: ${JSON.stringify(sA)}`),m=sA.isH264EncodeSupported,M=sA.isVp8EncodeSupported}if(m&&v&&hl&&pp&&!Gw&&!Id&&(!SY||fp!==115)){const{encode:sA,decode:eA}=await lX();m=sA,v=eA}return Oo.result=B&&r&&s&&(m||M)&&(v||AA),Oo.detail.isBrowserSupported=B,Oo.detail.isWebRTCSupported=r,Oo.detail.isH264EncodeSupported=m,Oo.detail.isVp8EncodeSupported=M,Oo.detail.isH265EncodeSupported=U,Oo.detail.isH264DecodeSupported=v,Oo.detail.isVp8DecodeSupported=AA,Oo.detail.isH265DecodeSupported=z,Oo.result||qi.error(`${navigator.userAgent} ${bj(Oo.detail,!1)}`),P5(),qr.addNumber({key:523800,value:Date.now()-i}),Oo}),dIA=function(){return Oo.result},q3=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},hIA=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype,x5=null;async function lX(t=2e3){return x5||(x5=new Promise(async i=>{const r={encode:!1,decode:!1};let s=()=>{};try{const g=document.createElement("canvas"),B=g.getContext("2d");g.width=640,g.height=480;const Q=setInterval(()=>{B.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))},66);let f=-1,m=-1;s=()=>{clearInterval(f),clearInterval(Q),clearTimeout(m),v.close(),U.close(),M.getTracks().forEach(X=>X.stop())},m=setTimeout(()=>{s(),i(r)},t);const M=g.captureStream(),v=new RTCPeerConnection({}),U=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});v.addEventListener("icecandidate",X=>U.addIceCandidate(X.candidate)),U.addEventListener("icecandidate",X=>v.addIceCandidate(X.candidate)),v.addTrack(M.getVideoTracks()[0],M);const AA=await v.createOffer();await v.setLocalDescription(AA),await U.setRemoteDescription(AA);const z=await U.createAnswer(),sA=U5.default.parse(z.sdp),eA=sA.media[0].rtp.findIndex(X=>X.codec==="H264");sA.media[0].rtp=[sA.media[0].rtp[eA]],sA.media[0].fmtp=sA.media[0].fmtp.filter(X=>X.payload===sA.media[0].rtp[0].payload),sA.media[0].rtcpFb&&(sA.media[0].rtcpFb=sA.media[0].rtcpFb.filter(X=>X.payload===sA.media[0].rtp[0].payload)),z.sdp=U5.default.write(sA),await U.setLocalDescription(z),await v.setRemoteDescription(z),f=setInterval(async()=>{r.encode&&r.decode&&(s(),i(r));const[X,QA]=await Promise.all([v.getSenders()[0].getStats(),U.getReceivers()[0].getStats()]);r.encode||X.forEach(wA=>{wA.type==="outbound-rtp"&&(wA.mediaType===gt.VIDEO||wA.kind===gt.VIDEO)&&wA.bytesSent>0&&(r.encode=!0)}),r.decode||QA.forEach(wA=>{wA.type==="inbound-rtp"&&(wA.mediaType===gt.VIDEO||wA.kind===gt.VIDEO)&&wA.bytesReceived>0&&(r.decode=!0)})},100)}catch(g){s(),qi.warn("detectH264Supported failed",g),i({encode:!0,decode:!0})}}).then(i=>(i.encode||(i.decode=!0),i.encode&&i.decode||qi.warn(`detectH264Supported encode: ${i.encode} decode: ${i.decode} ${zgA}`),i)))}var Y5=null;async function pIA(){return Y5||(Y5=new Promise(async t=>{const i={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!J3())return void t(i);let r=null,s=null,g=null;const B=()=>{g&&clearTimeout(g),r=null,s=null};try{r=document.createElement("canvas"),s=r.getContext("2d"),r.width=320,r.height=240;let Q=0;const f=()=>{s&&r&&(s.fillStyle=`hsl(${Q%360}, 50%, 50%)`,s.fillRect(0,0,r.width,r.height),s.fillStyle="white",s.font="20px Arial",s.fillText(`Frame ${Q}`,10,30),Q++)};g=setTimeout(()=>{B(),t(i)},5e3);const m=[{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(m.map(async M=>{const v={type:M.type,encodeSupported:!1,decodeSupported:!1};let U;try{U=await new Promise(async(AA,z)=>{try{const sA=new VideoEncoder({output:X=>{AA(X),v.encodeSupported=!0},error:z});sA.configure(M.encodeConfig),f();const eA=new VideoFrame(r,{timestamp:0});sA.encode(eA,{keyFrame:!0}),eA.close(),await sA.flush(),sA.close()}catch(sA){z(sA)}})}catch(AA){return qi.warn(`${M.type} encoder error:`,AA),v}try{await new Promise(async(AA,z)=>{try{const sA=new VideoDecoder({output:eA=>{v.decodeSupported=!0,AA(0),eA.close()},error:z});sA.configure(M.decodeConfig),sA.decode(U),await sA.flush(),sA.close()}catch(sA){z(sA)}})}catch(AA){qi.warn(`${M.type} decoder error:`,AA)}return v}))).forEach(M=>{M.type==="h264"?(i.isH264EncodeSupported=M.encodeSupported,i.isH264DecodeSupported=M.decodeSupported):M.type==="vp8"&&(i.isVp8EncodeSupported=M.encodeSupported,i.isVp8DecodeSupported=M.decodeSupported)}),B(),t(i)}catch(Q){B(),qi.warn("detectWebCodecsSupported failed:",Q),t(i)}}))}var fIA=(t,i,r)=>{location.protocol!=="http:"||q2||(t[i]=()=>{throw new Ws({code:xa.INVALID_OPERATION,message:Iw.NOT_SUPPORTED_HTTP})})},mIA=function(t){return!(t.type!=="candidate-pair"||!t.nominated||t.state!=="in-progress"&&t.state!=="succeeded")&&!(rD(t.selected)&&!t.selected)};function CX(){let t="";return screen.width&&(t+=`${screen.width?screen.width*window.devicePixelRatio:""} * ${screen.height?screen.height*window.devicePixelRatio:""}`),t}function BX(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function uX(){const t={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let r=0;r=86,RX="RTCRtpScriptTransform"in window,TIA=wk&&(yX||RX),K3=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t in window).length>0};function MX(){const t={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return Fr(window.AudioDecoder)||(t.AudioDecoder=!0),Fr(window.AudioEncoder)||(t.AudioEncoder=!0),Fr(window.VideoDecoder)||(t.VideoDecoder=!0),Fr(window.VideoEncoder)||(t.VideoEncoder=!0),Fr(window.ImageDecoder)||(t.ImageDecoder=!0),t}function wX(){return"mediaSession"in navigator&&!Fr(navigator.mediaSession.setActionHandler)}function SX(){return!Fr(window.WebTransport)}function GIA(){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 kIA(){const t={browser:`${nD.name}/${nD.version}`,os:tX(),displayResolution:CX(),isScreenShareSupported:q3(),isWebRTCSupported:K3(),isGetUserMediaSupported:BX(),isWebAudioSupported:uX(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:MX(),isMediaSessionSupported:wX(),isWebTransportSupported:SX()};return navigator.userAgent.includes("miniProgram")&&(t.browser=`mini/${t.browser}`),t}var vX="checkResult";function P5(t=30){sX.setItem(vX+t,{ua:navigator.userAgent,checkResult:Oo})}function _IA(t){vY();const i=sX.getItem(vX+t);i&&i.ua===navigator.userAgent&&i.checkResult&&bIA(i.checkResult.detail,Oo.detail)&&(Oo=i.checkResult),EX(t)}function bIA(t,i){return!!$m(t)&&Object.keys(i).every(r=>r in t)}function j3(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var LIA="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function J5(t){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[t]}var H5=!1;async function FIA(){var t;try{if(H5||!((t=navigator?.mediaCapabilities)!=null&&t.encodingInfo))return;const i=Y3(),r=XgA();if(i===0||r===0)return;H5=!0;const s=["H264","VP8","VP9","AV1","H265"],[g,B]=await Promise.all([NX(s),TX(s)]);g&&Object.keys(g).forEach(m=>{const M=J5(m.toLowerCase());qr.addEnum({key:513707,value:+`${M}${+g[m].supported}${+g[m].powerEfficient}${i}${r}`,useUV:!1})}),B&&Object.keys(B).forEach(m=>{const M=J5(m.toLowerCase());qr.addEnum({key:514713,value:+`${M}${+B[m].supported}${+B[m].powerEfficient}${i}${r}`,useUV:!1})});const{sender:Q,receiver:f}=GX();qr.addEnum({key:513708,value:+`${i}${r}${+Q.high}`,useUV:!1}),qr.addEnum({key:513709,value:+`${i}${r}${+Q.main}`,useUV:!1}),qr.addEnum({key:514714,value:+`${i}${r}${+f.high}`,useUV:!1}),qr.addEnum({key:514715,value:+`${i}${r}${+f.main}`,useUV:!1})}catch(i){qi.info("detectVideoCodecCapabilities failed",i)}}async function NX(t,i=1920,r=1080,s=30,g=3e3){const B={};try{for(const Q of t){const f=await navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:`video/${Q}`,width:i,height:r,bitrate:g,framerate:s}});B[Q]=f}}catch{}return B}async function TX(t,i=1920,r=1080,s=30,g=3e3){const B={};try{for(const Q of t){const f=await navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:`video/${Q}`,width:i,height:r,bitrate:g,framerate:s}});B[Q]=f}}catch{}return B}function GX(){const t={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(r=>r.mimeType.toLowerCase()==="video/h264").forEach(r=>{if(r.sdpFmtpLine){const s=r.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(s&&s[1])switch(s[1].slice(0,2)){case"42":t.sender.base=!0;break;case"4d":t.sender.main=!0;break;case"64":t.sender.high=!0}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){const i=RTCRtpReceiver.getCapabilities("video");i&&i.codecs&&i.codecs.filter(r=>r.mimeType.toLowerCase()==="video/h264").forEach(r=>{if(r.sdpFmtpLine){const s=r.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(s&&s[1])switch(s[1].slice(0,2)){case"42":t.receiver.base=!0;break;case"4d":t.receiver.main=!0;break;case"64":t.receiver.high=!0}}})}}catch(i){qi.warn("get H264 profile levelId failed",i)}return t}var UIA=Tw(mk()),V5=Symbol("instance"),r2=Symbol("cacheResult"),PK=class{constructor(t,i,r){this.oldState=t,this.newState=i,this.action=r,this.aborted=!1}abort(t){this.aborted=!0,WG.call(t,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},JK=class extends Error{constructor(t,i,r){super(i),this.state=t,this.message=i,this.cause=r}};function OIA(t){return typeof t=="object"&&t&&"then"in t}var jG=new Map;function FI(t,i,r={}){return(s,g,B)=>{const Q=r.action||g;if(!r.context){const m=jG.get(s)||[];jG.has(s)||jG.set(s,m),m.push({from:t,to:i,action:Q})}const f=B.value;B.value=function(...m){let M=this;if(r.context&&(M=Lr.get(typeof r.context=="function"?r.context.call(this,...m):r.context)),M.state===i)return r.sync?M[r2]:Promise.resolve(M[r2]);M.state instanceof PK&&M.state.action==r.abortAction&&M.state.abort(M);let v=null;Array.isArray(t)?t.length==0?M.state instanceof PK&&M.state.abort(M):typeof M.state=="string"&&t.includes(M.state)||(v=new JK(M._state,`${M.name} ${Q} to ${i} failed: current state ${M._state} not from ${t.join("|")}`)):t!==M.state&&(v=new JK(M._state,`${M.name} ${Q} to ${i} failed: current state ${M._state} not from ${t}`));const U=X=>{if(r.fail&&r.fail.call(this,X),r.sync){if(r.ignoreError)return X;throw X}return r.ignoreError?Promise.resolve(X):Promise.reject(X)};if(v)return U(v);const AA=M.state,z=new PK(AA,i,Q);WG.call(M,z);const sA=X=>{var QA;return M[r2]=X,z.aborted||(WG.call(M,i),(QA=r.success)===null||QA===void 0||QA.call(this,M[r2])),X},eA=X=>(WG.call(M,AA,X),U(X));try{const X=f.apply(this,m);return OIA(X)?X.then(sA).catch(eA):r.sync?sA(X):Promise.resolve(sA(X))}catch(X){return eA(new JK(M._state,`${M.name} ${Q} from ${t} to ${i} failed: ${X}`,X instanceof Error?X:new Error(String(X))))}}}}var xIA=typeof window<"u"&&window.__AFSM__?(r,s)=>{window.dispatchEvent(new CustomEvent(r,{detail:s}))}:typeof importScripts<"u"?(r,s)=>{postMessage({type:r,payload:s})}:()=>{};function WG(t,i){const r=this._state;this._state=t;const s=t.toString();t&&this.emit(s,r),this.emit(Lr.STATECHANGED,t,r,i),this.updateDevTools({value:t,old:r,err:i instanceof Error?i.message:String(i)})}var Lr=class lC extends UIA.default{constructor(i,r,s){super(),this.name=i,this.groupName=r,this._state=lC.INIT,i||(i=Date.now().toString(36)),s?Object.setPrototypeOf(this,s):s=Object.getPrototypeOf(this),r||(this.groupName=this.constructor.name);const g=s[V5];g?this.name=g.name+"-"+g.count++:s[V5]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){const i=Object.getPrototypeOf(this),r=jG.get(i)||[];let s=new Set,g=[],B=[];const Q=new Set,f=Object.getPrototypeOf(i);jG.has(f)&&(f.stateDiagram.forEach(M=>s.add(M)),f.allStates.forEach(M=>Q.add(M))),r.forEach(({from:M,to:v,action:U})=>{typeof M=="string"?g.push({from:M,to:v,action:U}):M.length?M.forEach(AA=>{g.push({from:AA,to:v,action:U})}):B.push({to:v,action:U})}),g.forEach(({from:M,to:v,action:U})=>{Q.add(M),Q.add(v),Q.add(U+"ing"),s.add(`${M} --> ${U}ing : ${U}`),s.add(`${U}ing --> ${v} : ${U} 🟢`),s.add(`${U}ing --> ${M} : ${U} 🔴`)}),B.forEach(({to:M,action:v})=>{s.add(`${v}ing --> ${M} : ${v} 🟢`),Q.forEach(U=>{U!==M&&s.add(`${U} --> ${v}ing : ${v}`)})});const m=[...s];return Object.defineProperties(i,{stateDiagram:{value:m},allStates:{value:Q}}),m}static get(i){let r;return typeof i=="string"?(r=lC.instances.get(i),r||lC.instances.set(i,r=new lC(i,void 0,Object.create(lC.prototype)))):(r=lC.instances2.get(i),r||lC.instances2.set(i,r=new lC(i.constructor.name,void 0,Object.create(lC.prototype)))),r}static getState(i){var r;return(r=lC.get(i))===null||r===void 0?void 0:r.state}updateDevTools(i={}){xIA(lC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){WG.call(this,i)}};Lr.STATECHANGED="stateChanged",Lr.UPDATEAFSM="updateAFSM",Lr.INIT="[*]",Lr.ON="on",Lr.OFF="off",Lr.instances=new Map,Lr.instances2=new WeakMap;var W3=typeof window<"u",q5=W3&&window.requestIdleCallback||function(t){const i=Date.now();return setTimeout(()=>{t({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-i))})},1e3)},YIA=W3&&window.cancelIdleCallback||function(t){clearTimeout(t)},K5=W3&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),SG=class pc{static generateTaskID(){return this.currentTaskID++}static run(i,r,s){s?.fps&&(s.delay=s.delay||Number((1e3/s.fps).toFixed(2))),s=cr(cr({},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}),s);const g=lB(cr({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:r},s),{delay:s.delay});return this.taskMap.set(g.taskID,g),this[i](g),g.taskID}static interval(i){return i.intervalID=setInterval(()=>{i.callback(),i.loopCount+=1,pc.isBreakLoop(i)},i.delay)}static intervalInWorker(i){pc.sharedWorker||(pc.sharedWorker=new Worker(URL.createObjectURL(new Blob([` +Refer to: ${H5("en",f)} +`),v}var V5=bw(SsA()),fIA=1,mIA=0,dX=class{constructor(t=!0){OA(this,"countMap",new Map),OA(this,"distributionMap",new Map),OA(this,"version"),OA(this,"log",qi.createLogger({id:"kv"})),t&&(Eo.on("102",({track:i,cost:r})=>{this.addSuccessEvent({key:i.kind===gt.AUDIO?501700:511700,cost:r})}),Eo.on("103",({track:i,error:r})=>{this.addFailedEvent({key:i.kind===gt.AUDIO?501700:511700,error:r})}),Eo.on("266",({enable:i})=>{this.log.info((i?"enable":"disable")+" sso"),i?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(t,i){const r={msg_sdk_basic_info:{uint32_sdk_version:S9(this.version||q2),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([s,g])=>({uint32_key:s,uint32_count:g})),stats_distribution:[...this.distributionMap.entries()].map(([s,g])=>({uint32_key:s,distribution_items:[...g.entries()].map(([B,Q])=>({uint32_item_key:B,uint32_item_value:Q}))})),str_user_sig:t,bytes_report_token:i};return this.countMap.clear(),this.distributionMap.clear(),r}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(t){const i=+String(t).slice(-3);return i>=700&&i<799}isErrorCodeKey(t){const i=+String(t).slice(-3);return i>=600&&i<699}isCountKey(t){const i=+String(t).slice(-3);return i>=0&&i<599}isNumberKey(t){const i=+String(t).slice(-3);return i>=800&&i<899}addCount({key:t,useUV:i=!1}){this.isCountKey(t)?i&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug(`${t} is not count key, last 3 number should be 0~599`)}addEnum({key:t,value:i,useUV:r=!0}){var s;if(!this.isEnumKey(t))return this.log.debug(`${t} is not enum key, last 3 number should be 700~799`);if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);const g=((s=this.distributionMap)==null?void 0:s.get(t))||new Map;g.set(i,(g.get(i)||0)+1),this.distributionMap.set(t,g)}addNumber({key:t,value:i,split:r=100,useUV:s=!1,max:g=5e3}){var B;if(!this.isNumberKey(t))return this.log.debug(`${t} is not number key, last 3 number should be 800~899`);if(s&&this.countMap.has(t))return;i>g&&(i=g),this.countMap.set(t,(this.countMap.get(t)||0)+1);const Q=((B=this.distributionMap)==null?void 0:B.get(t))||new Map;let f=0;if(hD(r))f=Math.floor(i/r);else for(let m=r.length-1;m>0;m--)if(i>r[m]){f=m;break}Q.set(f,(Q.get(f)||0)+1),this.distributionMap.set(t,Q)}addSuccessEvent({key:t,cost:i,timeKey:r,split:s}){if(t&&(this.addEnum({key:t,value:fIA,useUV:!1}),i)){const g=+String(t).slice(-3);g<800&&g>=700?this.addNumber({key:r||t+100,value:i,split:s}):r||this.log.debug(`time stat ignored, ${t}`)}}addFailedEvent({key:t,error:i}){if(!t)return;let r=xa.UNKNOWN;i&&(hD(i)?r=i:Fr(i.extraCode)&&Fr(i.code)||(r=i.extraCode||i.code)),this.addEnum({key:t,value:mIA,useUV:!1}),this.addEnum({key:t,value:Math.abs(r),useUV:!1})}},hX=(t=>(t[t.DECODER_TYPE=514700]="DECODER_TYPE",t[t.DECODER_HW_SW=514701]="DECODER_HW_SW",t[t.DECODE_RESULT=514702]="DECODE_RESULT",t[t.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",t[t.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",t[t.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",t[t.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",t[t.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",t[t.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",t[t.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",t[t.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",t[t.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",t[t.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",t[t.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",t[t.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",t[t.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",t[t.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",t[t.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",t[t.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",t))(hX||{}),DIA=new dX(!0);new dX(!1);var qr=DIA,Oo={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}},yIA=new Map([[Ql,["Firefox",O9]],[NY,["Edg",P9]],[q3,["Chrome",aX]],[cE,["Safari",kk]],[ld,["TBS",V9]],[Lw,["XWEB",q9]],[Gk&&vY,["WeChat",K9]],[U3,["QQ(Win)",j9]],[GY,["QQ(Mobile)",z2]],[TY,["QQ(Mobile X5)",z2]],[O3,["QQ(Mac)",W9]],[x3,["QQ(iPad)",z9]],[Y3,["MI",AX]],[P3,["HW",tX]],[J3,["Samsung",iX]],[_Y,["OPPO",oX]],[H3,["VIVO",rX]],[Tk,["EDGE",Y9]],[L3,["SogouMobile",J9]],[F3,["Sogou",H9]]]);function RIA(){const t=yIA.get(!0);return{browserName:t?t[0]:"unknown",browserVersion:t?t[1]:"unknown"}}var j3=function(){return!XgA&&!Tk&&!(NY&&zgA<80)&&!(Ql&&x9<56)},W3=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(t=>t in window)},z3=function(){if(!navigator.mediaDevices)return bY()||qi.error(lw.NOT_SUPPORTED_MEDIA),!1;const t=["getUserMedia","enumerateDevices"];return t.filter(i=>i in navigator.mediaDevices).length===t.length},q5=!1;function bY(){return location.protocol==="http:"&&!X2&&(q5||qi.error(AY({key:$2.NOT_SUPPORTED_HTTP})),q5=!0,!0)}var MIA=function(){return window?.OffscreenCanvas&&window?.MediaStreamTrackProcessor&&window?.MediaStreamTrackGenerator},wIA=function(){return!!window?.MediaStreamTrackGenerator},Z3=async function(){var t,i,r;if(Oo.detail.isH264EncodeSupported&&Oo.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Oo.detail.isH264EncodeSupported,isVp8EncodeSupported:Oo.detail.isVp8EncodeSupported,isH265EncodeSupported:Oo.detail.isH265EncodeSupported};let s,g=!1,B=!1,Q=!1;try{const f=new RTCPeerConnection,m=document.createElement(gt.CANVAS);m.getContext("2d");const M=m.captureStream(0);return f.addTrack(M.getVideoTracks()[0],M),s=await f.createOffer(),g=((t=s.sdp)==null?void 0:t.toLowerCase().indexOf("h264"))!==-1,B=((i=s.sdp)==null?void 0:i.toLowerCase().indexOf("vp8"))!==-1,Q=((r=s.sdp)==null?void 0:r.toLowerCase().indexOf("h265"))!==-1,f.close(),{isH264EncodeSupported:g,isVp8EncodeSupported:B,isH265EncodeSupported:Q}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}},pX=async function(){var t;if(Oo.detail.isH264DecodeSupported&&Oo.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Oo.detail.isH264DecodeSupported,isVp8DecodeSupported:Oo.detail.isVp8DecodeSupported,isH265DecodeSupported:Oo.detail.isH265DecodeSupported};let i,r=!1,s=!1;try{const g=new RTCPeerConnection;LY()?(g.addTransceiver(gt.VIDEO,{direction:"recvonly"}),i=await g.createOffer()):i=await g.createOffer({offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(r=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(s=!0);const B=((t=i.sdp)==null?void 0:t.toLowerCase().indexOf("h265"))!==-1;return g.close(),{isH264DecodeSupported:r,isVp8DecodeSupported:s,isH265DecodeSupported:B}}catch{return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}};async function SIA(){const[t,i]=await Promise.all([Z3(),pX()]);return{encode:{h264:t.isH264EncodeSupported,vp8:t.isVp8EncodeSupported,h265:t.isH265EncodeSupported},decode:{h264:i.isH264DecodeSupported,vp8:i.isVp8DecodeSupported,h265:i.isH265DecodeSupported}}}var fX=N9(async t=>{const i=Date.now(),r=$3(),s=z3(),g=W3();if(Oo.detail.isWebRTCSupported=r,Oo.detail.isMediaDevicesSupported=s,Oo.detail.isWebCodecsSupported=g,Oo.detail.isScreenShareSupported=X3(),Oo.detail.isSmallStreamSupported=vX(),t===37)return Object.assign(Oo.detail,await TIA()),Oo.detail.isBrowserSupported=g,Oo.result=s&&g,Oo.result||qi.error(`${navigator.userAgent} ${Yj(Oo.detail,!1)}`),W5(t),qr.addNumber({key:523800,value:Date.now()-i}),Oo;if(Oo.result&&Oo.detail.isH264EncodeSupported&&Oo.detail.isVp8EncodeSupported&&Oo.detail.isH265EncodeSupported&&Oo.detail.isH264DecodeSupported&&Oo.detail.isVp8DecodeSupported&&Oo.detail.isH265DecodeSupported)return Oo;const B=j3(),{encode:Q,decode:f}=await SIA();let{h264:m,vp8:M}=Q,{h264:v}=f;const{h265:U}=Q,{vp8:AA,h265:z}=f;if(!m||!M){const sA=await Z3();qi.warn(`detect encode again h264:${m} vp8:${M} result: ${JSON.stringify(sA)}`),m=sA.isH264EncodeSupported,M=sA.isVp8EncodeSupported}if(m&&v&&hl&&yp&&!Lw&&!ld&&(!_Y||Rp!==115)){const{encode:sA,decode:eA}=await mX();m=sA,v=eA}return Oo.result=B&&r&&s&&(m||M)&&(v||AA),Oo.detail.isBrowserSupported=B,Oo.detail.isWebRTCSupported=r,Oo.detail.isH264EncodeSupported=m,Oo.detail.isVp8EncodeSupported=M,Oo.detail.isH265EncodeSupported=U,Oo.detail.isH264DecodeSupported=v,Oo.detail.isVp8DecodeSupported=AA,Oo.detail.isH265DecodeSupported=z,Oo.result||qi.error(`${navigator.userAgent} ${Yj(Oo.detail,!1)}`),W5(),qr.addNumber({key:523800,value:Date.now()-i}),Oo}),vIA=function(){return Oo.result},X3=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},NIA=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype,K5=null;async function mX(t=2e3){return K5||(K5=new Promise(async i=>{const r={encode:!1,decode:!1};let s=()=>{};try{const g=document.createElement("canvas"),B=g.getContext("2d");g.width=640,g.height=480;const Q=setInterval(()=>{B.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))},66);let f=-1,m=-1;s=()=>{clearInterval(f),clearInterval(Q),clearTimeout(m),v.close(),U.close(),M.getTracks().forEach(X=>X.stop())},m=setTimeout(()=>{s(),i(r)},t);const M=g.captureStream(),v=new RTCPeerConnection({}),U=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});v.addEventListener("icecandidate",X=>U.addIceCandidate(X.candidate)),U.addEventListener("icecandidate",X=>v.addIceCandidate(X.candidate)),v.addTrack(M.getVideoTracks()[0],M);const AA=await v.createOffer();await v.setLocalDescription(AA),await U.setRemoteDescription(AA);const z=await U.createAnswer(),sA=V5.default.parse(z.sdp),eA=sA.media[0].rtp.findIndex(X=>X.codec==="H264");sA.media[0].rtp=[sA.media[0].rtp[eA]],sA.media[0].fmtp=sA.media[0].fmtp.filter(X=>X.payload===sA.media[0].rtp[0].payload),sA.media[0].rtcpFb&&(sA.media[0].rtcpFb=sA.media[0].rtcpFb.filter(X=>X.payload===sA.media[0].rtp[0].payload)),z.sdp=V5.default.write(sA),await U.setLocalDescription(z),await v.setRemoteDescription(z),f=setInterval(async()=>{r.encode&&r.decode&&(s(),i(r));const[X,QA]=await Promise.all([v.getSenders()[0].getStats(),U.getReceivers()[0].getStats()]);r.encode||X.forEach(wA=>{wA.type==="outbound-rtp"&&(wA.mediaType===gt.VIDEO||wA.kind===gt.VIDEO)&&wA.bytesSent>0&&(r.encode=!0)}),r.decode||QA.forEach(wA=>{wA.type==="inbound-rtp"&&(wA.mediaType===gt.VIDEO||wA.kind===gt.VIDEO)&&wA.bytesReceived>0&&(r.decode=!0)})},100)}catch(g){s(),qi.warn("detectH264Supported failed",g),i({encode:!0,decode:!0})}}).then(i=>(i.encode||(i.decode=!0),i.encode&&i.decode||qi.warn(`detectH264Supported encode: ${i.encode} decode: ${i.decode} ${aIA}`),i)))}var j5=null;async function TIA(){return j5||(j5=new Promise(async t=>{const i={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!W3())return void t(i);let r=null,s=null,g=null;const B=()=>{g&&clearTimeout(g),r=null,s=null};try{r=document.createElement("canvas"),s=r.getContext("2d"),r.width=320,r.height=240;let Q=0;const f=()=>{s&&r&&(s.fillStyle=`hsl(${Q%360}, 50%, 50%)`,s.fillRect(0,0,r.width,r.height),s.fillStyle="white",s.font="20px Arial",s.fillText(`Frame ${Q}`,10,30),Q++)};g=setTimeout(()=>{B(),t(i)},5e3);const m=[{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(m.map(async M=>{const v={type:M.type,encodeSupported:!1,decodeSupported:!1};let U;try{U=await new Promise(async(AA,z)=>{try{const sA=new VideoEncoder({output:X=>{AA(X),v.encodeSupported=!0},error:z});sA.configure(M.encodeConfig),f();const eA=new VideoFrame(r,{timestamp:0});sA.encode(eA,{keyFrame:!0}),eA.close(),await sA.flush(),sA.close()}catch(sA){z(sA)}})}catch(AA){return qi.warn(`${M.type} encoder error:`,AA),v}try{await new Promise(async(AA,z)=>{try{const sA=new VideoDecoder({output:eA=>{v.decodeSupported=!0,AA(0),eA.close()},error:z});sA.configure(M.decodeConfig),sA.decode(U),await sA.flush(),sA.close()}catch(sA){z(sA)}})}catch(AA){qi.warn(`${M.type} decoder error:`,AA)}return v}))).forEach(M=>{M.type==="h264"?(i.isH264EncodeSupported=M.encodeSupported,i.isH264DecodeSupported=M.decodeSupported):M.type==="vp8"&&(i.isVp8EncodeSupported=M.encodeSupported,i.isVp8DecodeSupported=M.decodeSupported)}),B(),t(i)}catch(Q){B(),qi.warn("detectWebCodecsSupported failed:",Q),t(i)}}))}var GIA=(t,i,r)=>{location.protocol!=="http:"||X2||(t[i]=()=>{throw new Ws({code:xa.INVALID_OPERATION,message:lw.NOT_SUPPORTED_HTTP})})},kIA=function(t){return!(t.type!=="candidate-pair"||!t.nominated||t.state!=="in-progress"&&t.state!=="succeeded")&&!(gD(t.selected)&&!t.selected)};function DX(){let t="";return screen.width&&(t+=`${screen.width?screen.width*window.devicePixelRatio:""} * ${screen.height?screen.height*window.devicePixelRatio:""}`),t}function yX(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function RX(){const t={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let r=0;r=86,_X="RTCRtpScriptTransform"in window,PIA=_k&&(kX||_X),$3=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t in window).length>0};function bX(){const t={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return Fr(window.AudioDecoder)||(t.AudioDecoder=!0),Fr(window.AudioEncoder)||(t.AudioEncoder=!0),Fr(window.VideoDecoder)||(t.VideoDecoder=!0),Fr(window.VideoEncoder)||(t.VideoEncoder=!0),Fr(window.ImageDecoder)||(t.ImageDecoder=!0),t}function LX(){return"mediaSession"in navigator&&!Fr(navigator.mediaSession.setActionHandler)}function FX(){return!Fr(window.WebTransport)}function JIA(){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 HIA(){const t={browser:`${ID.name}/${ID.version}`,os:cX(),displayResolution:DX(),isScreenShareSupported:X3(),isWebRTCSupported:$3(),isGetUserMediaSupported:yX(),isWebAudioSupported:RX(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:bX(),isMediaSessionSupported:LX(),isWebTransportSupported:FX()};return navigator.userAgent.includes("miniProgram")&&(t.browser=`mini/${t.browser}`),t}var UX="checkResult";function W5(t=30){QX.setItem(UX+t,{ua:navigator.userAgent,checkResult:Oo})}function VIA(t){bY();const i=QX.getItem(UX+t);i&&i.ua===navigator.userAgent&&i.checkResult&&qIA(i.checkResult.detail,Oo.detail)&&(Oo=i.checkResult),fX(t)}function qIA(t,i){return!!iD(t)&&Object.keys(i).every(r=>r in t)}function AW(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var KIA="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function z5(t){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[t]}var Z5=!1;async function jIA(){var t;try{if(Z5||!((t=navigator?.mediaCapabilities)!=null&&t.encodingInfo))return;const i=K3(),r=gIA();if(i===0||r===0)return;Z5=!0;const s=["H264","VP8","VP9","AV1","H265"],[g,B]=await Promise.all([OX(s),xX(s)]);g&&Object.keys(g).forEach(m=>{const M=z5(m.toLowerCase());qr.addEnum({key:513707,value:+`${M}${+g[m].supported}${+g[m].powerEfficient}${i}${r}`,useUV:!1})}),B&&Object.keys(B).forEach(m=>{const M=z5(m.toLowerCase());qr.addEnum({key:514713,value:+`${M}${+B[m].supported}${+B[m].powerEfficient}${i}${r}`,useUV:!1})});const{sender:Q,receiver:f}=YX();qr.addEnum({key:513708,value:+`${i}${r}${+Q.high}`,useUV:!1}),qr.addEnum({key:513709,value:+`${i}${r}${+Q.main}`,useUV:!1}),qr.addEnum({key:514714,value:+`${i}${r}${+f.high}`,useUV:!1}),qr.addEnum({key:514715,value:+`${i}${r}${+f.main}`,useUV:!1})}catch(i){qi.info("detectVideoCodecCapabilities failed",i)}}async function OX(t,i=1920,r=1080,s=30,g=3e3){const B={};try{for(const Q of t){const f=await navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:`video/${Q}`,width:i,height:r,bitrate:g,framerate:s}});B[Q]=f}}catch{}return B}async function xX(t,i=1920,r=1080,s=30,g=3e3){const B={};try{for(const Q of t){const f=await navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:`video/${Q}`,width:i,height:r,bitrate:g,framerate:s}});B[Q]=f}}catch{}return B}function YX(){const t={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(r=>r.mimeType.toLowerCase()==="video/h264").forEach(r=>{if(r.sdpFmtpLine){const s=r.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(s&&s[1])switch(s[1].slice(0,2)){case"42":t.sender.base=!0;break;case"4d":t.sender.main=!0;break;case"64":t.sender.high=!0}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){const i=RTCRtpReceiver.getCapabilities("video");i&&i.codecs&&i.codecs.filter(r=>r.mimeType.toLowerCase()==="video/h264").forEach(r=>{if(r.sdpFmtpLine){const s=r.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(s&&s[1])switch(s[1].slice(0,2)){case"42":t.receiver.base=!0;break;case"4d":t.receiver.main=!0;break;case"64":t.receiver.high=!0}}})}}catch(i){qi.warn("get H264 profile levelId failed",i)}return t}var WIA=bw(vk()),X5=Symbol("instance"),E2=Symbol("cacheResult"),jK=class{constructor(t,i,r){this.oldState=t,this.newState=i,this.action=r,this.aborted=!1}abort(t){this.aborted=!0,Ak.call(t,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},WK=class extends Error{constructor(t,i,r){super(i),this.state=t,this.message=i,this.cause=r}};function zIA(t){return typeof t=="object"&&t&&"then"in t}var $G=new Map;function FI(t,i,r={}){return(s,g,B)=>{const Q=r.action||g;if(!r.context){const m=$G.get(s)||[];$G.has(s)||$G.set(s,m),m.push({from:t,to:i,action:Q})}const f=B.value;B.value=function(...m){let M=this;if(r.context&&(M=Lr.get(typeof r.context=="function"?r.context.call(this,...m):r.context)),M.state===i)return r.sync?M[E2]:Promise.resolve(M[E2]);M.state instanceof jK&&M.state.action==r.abortAction&&M.state.abort(M);let v=null;Array.isArray(t)?t.length==0?M.state instanceof jK&&M.state.abort(M):typeof M.state=="string"&&t.includes(M.state)||(v=new WK(M._state,`${M.name} ${Q} to ${i} failed: current state ${M._state} not from ${t.join("|")}`)):t!==M.state&&(v=new WK(M._state,`${M.name} ${Q} to ${i} failed: current state ${M._state} not from ${t}`));const U=X=>{if(r.fail&&r.fail.call(this,X),r.sync){if(r.ignoreError)return X;throw X}return r.ignoreError?Promise.resolve(X):Promise.reject(X)};if(v)return U(v);const AA=M.state,z=new jK(AA,i,Q);Ak.call(M,z);const sA=X=>{var QA;return M[E2]=X,z.aborted||(Ak.call(M,i),(QA=r.success)===null||QA===void 0||QA.call(this,M[E2])),X},eA=X=>(Ak.call(M,AA,X),U(X));try{const X=f.apply(this,m);return zIA(X)?X.then(sA).catch(eA):r.sync?sA(X):Promise.resolve(sA(X))}catch(X){return eA(new WK(M._state,`${M.name} ${Q} from ${t} to ${i} failed: ${X}`,X instanceof Error?X:new Error(String(X))))}}}}var ZIA=typeof window<"u"&&window.__AFSM__?(r,s)=>{window.dispatchEvent(new CustomEvent(r,{detail:s}))}:typeof importScripts<"u"?(r,s)=>{postMessage({type:r,payload:s})}:()=>{};function Ak(t,i){const r=this._state;this._state=t;const s=t.toString();t&&this.emit(s,r),this.emit(Lr.STATECHANGED,t,r,i),this.updateDevTools({value:t,old:r,err:i instanceof Error?i.message:String(i)})}var Lr=class lC extends WIA.default{constructor(i,r,s){super(),this.name=i,this.groupName=r,this._state=lC.INIT,i||(i=Date.now().toString(36)),s?Object.setPrototypeOf(this,s):s=Object.getPrototypeOf(this),r||(this.groupName=this.constructor.name);const g=s[X5];g?this.name=g.name+"-"+g.count++:s[X5]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){const i=Object.getPrototypeOf(this),r=$G.get(i)||[];let s=new Set,g=[],B=[];const Q=new Set,f=Object.getPrototypeOf(i);$G.has(f)&&(f.stateDiagram.forEach(M=>s.add(M)),f.allStates.forEach(M=>Q.add(M))),r.forEach(({from:M,to:v,action:U})=>{typeof M=="string"?g.push({from:M,to:v,action:U}):M.length?M.forEach(AA=>{g.push({from:AA,to:v,action:U})}):B.push({to:v,action:U})}),g.forEach(({from:M,to:v,action:U})=>{Q.add(M),Q.add(v),Q.add(U+"ing"),s.add(`${M} --> ${U}ing : ${U}`),s.add(`${U}ing --> ${v} : ${U} 🟢`),s.add(`${U}ing --> ${M} : ${U} 🔴`)}),B.forEach(({to:M,action:v})=>{s.add(`${v}ing --> ${M} : ${v} 🟢`),Q.forEach(U=>{U!==M&&s.add(`${U} --> ${v}ing : ${v}`)})});const m=[...s];return Object.defineProperties(i,{stateDiagram:{value:m},allStates:{value:Q}}),m}static get(i){let r;return typeof i=="string"?(r=lC.instances.get(i),r||lC.instances.set(i,r=new lC(i,void 0,Object.create(lC.prototype)))):(r=lC.instances2.get(i),r||lC.instances2.set(i,r=new lC(i.constructor.name,void 0,Object.create(lC.prototype)))),r}static getState(i){var r;return(r=lC.get(i))===null||r===void 0?void 0:r.state}updateDevTools(i={}){ZIA(lC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){Ak.call(this,i)}};Lr.STATECHANGED="stateChanged",Lr.UPDATEAFSM="updateAFSM",Lr.INIT="[*]",Lr.ON="on",Lr.OFF="off",Lr.instances=new Map,Lr.instances2=new WeakMap;var eW=typeof window<"u",$5=eW&&window.requestIdleCallback||function(t){const i=Date.now();return setTimeout(()=>{t({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-i))})},1e3)},XIA=eW&&window.cancelIdleCallback||function(t){clearTimeout(t)},A8=eW&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),GG=class pc{static generateTaskID(){return this.currentTaskID++}static run(i,r,s){s?.fps&&(s.delay=s.delay||Number((1e3/s.fps).toFixed(2))),s=cr(cr({},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}),s);const g=lB(cr({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:r},s),{delay:s.delay});return this.taskMap.set(g.taskID,g),this[i](g),g.taskID}static interval(i){return i.intervalID=setInterval(()=>{i.callback(),i.loopCount+=1,pc.isBreakLoop(i)},i.delay)}static intervalInWorker(i){pc.sharedWorker||(pc.sharedWorker=new Worker(URL.createObjectURL(new Blob([` const timers = new Map(); self.onmessage = function(e) { const { taskId, delay, type } = e.data; @@ -448,15 +448,15 @@ Refer to: ${F5("en",f)} timers.delete(taskId); } }; - `],{type:"application/javascript"}))),pc.sharedWorker.onmessage=r=>{var s;if(r.data.type==="tick"){const g=pc.workerTasks.get(r.data.taskId);g&&(pc.isBreakLoop(g)?((s=pc.sharedWorker)==null||s.postMessage({type:"stop",taskId:g.taskID}),pc.workerTasks.delete(g.taskID)):(g.callback(),g.loopCount+=1))}}),pc.workerTasks.set(i.taskID,i),pc.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){const r=()=>{if(i.callback(),i.loopCount+=1,!pc.isBreakLoop(i))return i.timeoutID=setTimeout(r,i.delay)};return i.timeoutID=setTimeout(r,i.delay)}static ric(i){let r,s=Ns();const g=()=>{if(r=Ns()-s,r>=i.delay&&(s=Ns()-Math.floor(r%i.delay),i.callback(),i.loopCount+=1),!pc.isBreakLoop(i))return i.ricID=q5(g,{timeout:i.delay})};return i.ricID=q5(g,{timeout:i.delay})}static raf(i){let r,s=Ns();const g=()=>{if(document.hidden&&i.backgroundTask)return r=Ns()-s,s=Ns(),i.callback(),i.loopCount+=1,pc.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(g,i.delay-Math.floor(r%i.delay));if(r=Ns()-s,r>=i.delay&&(s=Ns()-Math.floor(r%i.delay),i.callback(),i.loopCount+=1),!pc.isBreakLoop(i))return i.rafID=requestAnimationFrame(g)};if(i.rafID=requestAnimationFrame(g),i.backgroundTask){const B=()=>{if(document.hidden){const Q=Ns()-s;Q>=i.delay?g():i.timeoutID=setTimeout(g,i.delay-Q)}};document.addEventListener("visibilitychange",B),i.onVisibilitychange=B,document.hidden&&B()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;const{intervalID:r,timeoutID:s,rafID:g,ricID:B,onVisibilitychange:Q}=this.taskMap.get(i);return r&&clearInterval(r),s&&clearTimeout(s),g&&K5&&K5(g),B&&YIA(B),Q&&document.removeEventListener("visibilitychange",Q),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)}};OA(SG,"taskMap",new Map),OA(SG,"currentTaskID",1),OA(SG,"sharedWorker",null),OA(SG,"workerTasks",new Map);var PIA=SG,ku=PIA,vr={LOAD_START:gt.LOADSTART,LOADED_DATA:gt.LOADEDDATA,LOADED_META_DATA:gt.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:gt.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:gt.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:gt.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"},Uj={};p3(Uj,{create:()=>z3,remove:()=>gk});var zG=new WeakMap;function z3(t,i){zG.has(t)||zG.set(t,[]);const r=zG.get(t),s={add:(g,B)=>("addEventListener"in i?(r.push(i.removeEventListener.bind(i,g,B)),i.addEventListener(g,B)):(r.push(i.off.bind(i,g,B)),i.on(g,B)),s)};return s}function gk(t){const i=zG.get(t);i&&(i.forEach(r=>r()),zG.delete(t))}var JIA=class{constructor(){OA(this,"_roomIdMap",new Map),OA(this,"_configs"),typeof registerProcessor>"u"&&(this._configs={sdkAppId:"",userId:"",version:x2,env:_K.QCLOUD,browserVersion:nD.name+nD.version,ua:navigator.userAgent})}setConfig({sdkAppId:t,env:i,userId:r,roomId:s}){t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=r,this._roomIdMap.set(r,String(s))}logSuccessEvent(t){!q2&&qi.isAbleToUpload&&this._configs.env===_K.QCLOUD&&this.uploadEventToKibana(lB(cr({},t),{result:"success"}))}logFailedEvent(t){if(q2||!qi.isAbleToUpload)return;const{eventType:i,code:r,error:s,userId:g}=t,B={roomId:this._roomIdMap.get(g||this._configs.userId),userId:g,eventType:i,result:"failed",code:r||s?.extraCode||s?.code||xa.UNKNOWN};this._configs.env===_K.QCLOUD&&this.uploadEventToKibana(lB(cr({},B),{error:s}))}uploadEventToKibana(t){let i=`stat-${t.eventType}-${t.result}`;t.eventType!=="delta-join"&&t.eventType!=="delta-leave"&&t.eventType!=="delta-publish"||(i=`${t.eventType}:${t.delta}`),this.uploadEvent({log:i,userId:t.userId}),t.result==="failed"&&(i=`stat-${t.eventType}-${t.result}-${t.code}`,this.uploadEvent({log:i,userId:t.userId,error:t.error}))}uploadEvent({log:t,userId:i,error:r}){const s={timestamp:i9(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:x2,log:t};r&&(s.errorInfo=r.message,r.stack&&(s.errorInfo+=` -${r.stack}`));const g=Fj.enable?M3(s,2002,Number(this._configs.sdkAppId)):JSON.stringify(s);this.sendRequest(D3(this._configs.sdkAppId,n9.LOG),g)}sendRequest(t,i){setTimeout(()=>M9({url:t,body:i,priority:"low"}).catch(()=>{}),2e3)}},fC=new JIA,Jm=new WeakMap;function HIA({settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:s}){return function(g,B,Q){const f=S3({retryFunction:Q.value,settings:t,onError({error:m,retry:M,reject:v,retryFuncArgs:U}){var AA;i?i.call(this,m,()=>{var z;(z=Jm.get(g))!=null&&z.has(B)?M():v(m)},v,U):(AA=Jm.get(g))!=null&&AA.has(B)?M():v(m)},onRetrying(m,M){var v;rw(r)&&r.call(this,m,M),(v=Jm.get(g))!=null&&v.has(B)&&(Jm.get(g).get(B).stopRetry=M)},onRetryFailed:s});return Q.value=function(...m){const M=Jm.get(g);return M?M.set(B,{args:m}):Jm.set(g,new Map([[B,{args:m}]])),f.apply(this,m).finally(()=>{var v;return(v=Jm.get(g))==null?void 0:v.delete(B)})},Q}}var jm=class extends Lr{constructor(t,i){super(t.id,`${i}-player`),this.options=t,this.kind=i,OA(this,"id"),OA(this,"element",null),OA(this,"track"),OA(this,"url"),OA(this,"attr"),OA(this,"mode"),OA(this,"muted"),OA(this,"_log"),OA(this,"isPausedByUserCall",!1),OA(this,"_pausedRetryCount"),OA(this,"_isElementPlayingFired",!1),OA(this,"_interval"),OA(this,"_delayDestroyTimeoutId",0),OA(this,"_playSuccessResolve"),OA(this,"_isReplayByRecreateMediaStreamCalled",!1),OA(this,"isPlayCalled",!1),OA(this,"isInAutoPlayFailedState",!1),OA(this,"isBindAutoPlayEvent",!1),this.id=t.id,this._log=t.log,this.track=t.track,this.muted=t.muted,this._pausedRetryCount=ow,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${i}-player ${this.id}`)}get isPlaying(){var t;return this._state==="PLAYING"&&((t=this.element)==null?void 0:t.paused)===!1}get isPaused(){var t;return this._state==="PAUSED"||((t=this.element)==null?void 0:t.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(t){this.attr=t}setUrl(t){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),t!==this.url&&(this.url=t,t!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=t))}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((t,i)=>{this._playSuccessResolve=t,this.element.play().then(t,i)})}catch(t){const i=j2({key:K2.PLAY_FAILED,data:{media:this.kind,error:t}});if(this._log.warn(t),i.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new Ws({code:xa.PLAY_NOT_ALLOWED,message:i})}}stop(t=0){var i;this.isPlayCalled=!1,this.isPausedByUserCall=!1,this._isElementPlayingFired=!1,this.unbindEvents(),t>0&&!$9?this._delayDestroyTimeoutId||((i=this.element)==null||i.remove(),this._log.info(`destroy element after 3 * ${t}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*t)):this.destroyElement(),this.handleStopped(gt.ENDED),this._interval>0&&ku.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 t;(t=this.element)==null||t.pause()}resume(t=!1){return this.isPausedByUserCall=!1,this.doResume(t)}doResume(t=!1){return this._log.info("resume"),this.isPausedByUserCall||this.isPlaying?Promise.resolve():VgA?this.replay():this.play().catch(()=>{})}setMuted(t){this.element&&(this.element.muted=t),this.muted=t}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){const t=this.handleElementEvent.bind(this);return z3(this.element,this.element).add(gt.PLAYING,t).add(gt.ENDED,t).add(gt.PAUSE,t).add(gt.ERROR,t).add(gt.LOADSTART,t).add(gt.LOADEDDATA,t).add(gt.LOADEDMETADATA,t)}}bindTrackEvents(t=this.track){if(t){const i=this.handleTrackEvent.bind(this);Uj?.create(t,t).add(gt.ENDED,i).add(gt.MUTE,i).add(gt.UNMUTE,i),t.readyState===gt.ENDED&&this.handleTrackEvent({type:gt.ENDED}),t.muted&&this.handleTrackEvent({type:gt.MUTE})}}bindAutoPlayEvent(){this.isBindAutoPlayEvent||(this._log.warn("bindAutoPlayEvent"),Eo.on(nr.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!0)}unbindTrackEvents(t=this.track){t&&gk(t)}unbindEvents(){this.element&&gk(this.element),this.unbindTrackEvents(),Eo.off(nr.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!1}handleElementEvent(t){switch(t.type){case gt.PLAYING:Ik()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(gt.PLAYING),this._interval&&(ku.clearTask(this._interval),this._interval=-1);break;case gt.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(gt.ENDED);break;case gt.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(gt.PAUSE);break;case gt.ERROR:if(this.element&&this.element.error){this.handlePaused(gt.ERROR);const{code:i,message:r}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${i} message: ${r} userAgent: ${navigator.userAgent}`),fC.uploadEvent({log:`stat-${this.kind}-${VG.PLAYER_ERROR}-${i}-${navigator.userAgent}`,error:this.element.error}),PgA||q9?this.emit(vr.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case gt.LOADEDDATA:this.kind===gt.VIDEO&&this.emit(vr.LOADED_DATA);break;case gt.LOADEDMETADATA:this.kind===gt.VIDEO&&this.emit(vr.LOADED_META_DATA);break;case gt.LOADSTART:this.emit(vr.LOAD_START)}}replayByRecreateMediaStream(t){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),fC.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),qr.addSuccessEvent({key:this.kind===gt.AUDIO?506700:516700})}).catch(()=>{var i;this._log.error("replayByRecreateMediaStream failed"),fC.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),qr.addFailedEvent({key:this.kind===gt.AUDIO?506700:516700,error:(i=this.element)==null?void 0:i.error}),this.emit(vr.ERROR,t)})}doReplayByRecreateMediaStream(t){return this._log.warn(`delay ${t}ms to recreate mediaStream`),new Promise((i,r)=>{Rw(t).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var s,g,B;this._log.warn(`element onerror ${(g=(s=this.element)==null?void 0:s.error)==null?void 0:g.code} fired after recreated mediaStream`),r((B=this.element)==null?void 0:B.error)}),Rw(5e3).then(()=>{var s,g;this.isPlaying&&!((s=this.element)!=null&&s.error)||r((g=this.element)==null?void 0:g.error),i()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}async handleTrackEvent(t){const i=t.type;switch(this.options.enableLogTrackState&&this._log[i===gt.UNMUTE?"info":"warn"](`track ${i}`),i){case gt.ENDED:this.handleStopped(gt.ENDED);break;case gt.MUTE:this.handlePaused(gt.MUTE);break;case gt.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(gt.UNMUTE))}}handlePlaying(t){var i;return this._log.debug("handlePlaying",t),(i=this._playSuccessResolve)==null||i.call(this,t),t}handlePaused(t){return this._log.debug("handlePaused",t),t}handleStopped(t){return this._log.debug("handleStopped",t),t}getElement(){return this.element}};OA(jm,"PlayerEvent",vr),ss([HIA({settings:{retries:2,timeout:0},onError(t,i,r,s){s[0]=(s[0]||1e3)+1e3,i()}})],jm.prototype,"doReplayByRecreateMediaStream"),ss([FI([],"PLAYING",{sync:!0,success(t){this.emit(vr.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:t})}})],jm.prototype,"handlePlaying"),ss([FI("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(t){this.emit(vr.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:t})}})],jm.prototype,"handlePaused"),ss([FI([],"STOPPED",{sync:!0,success(t){this.emit(vr.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:t})}})],jm.prototype,"handleStopped");var cd="trtc_autoplay",HK=`${cd}_mask`,uG=`${cd}_wrapper`,j5=`${cd}_header`,VK=`${cd}_content`,n2=`${cd}_action_wrapper`,qK=`${cd}_question`,KK=`${cd}_collapse`,a2=`${cd}_action_confirm`,W5=`${cd}_detail`,z5="#2473E8",Z3="dialog",VIA=`${Z3}-show`,qIA=`${Z3}-1`,KIA=`${Z3}-2`,Z5=!1,Oj=!1,Ik=()=>Oj,kX=`${Sj}/${Bp()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,X5=`
${Bp()?"其他方案?":"Any other solution?"}`,jIA=Bp()?`浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。${X5}`:`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. ${X5}`,WIA=class{constructor(){if(OA(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),OA(this,"_dialogNode",null),OA(this,"_bodyPosition",""),OA(this,"_showDetail",!1),OA(this,"_isCollapseClicked",!1),OA(this,"_isQuestionClicked",!1),Bp()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Z5){const t=document.createElement("style");t.innerHTML=`.${HK}{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;}.${HK} div:not(.${n2}){display:block !important;}.${uG}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${uG} a{color:${z5};}.${j5}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${VK}{margin:8px 0;}.${n2}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${KK}{margin-right:auto;cursor:pointer}.${qK}{height:100%;line-height:16px;cursor:pointer;}.${a2}{margin-left:8px;color:#fff;background:${z5};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${a2}:hover{opacity:0.9;}.${KK},.${a2},.${VK},.${qK}{font-size:14px;}@media screen and (max-width:750px){.${uG}{width:80vw;}}`,document.head.appendChild(t),Z5=!0}this.addDiaLog()}createDiaLog(){const t=document.createElement("template");t.innerHTML=`
${location.host}
${this.content}
`.trim();const i=document.createElement("button");i.className=a2,i.innerText=Bp()?"恢复播放":"Resume",i.onclick=this.onConfirm.bind(this);const r=document.createElement("div");r.className=qK,r.innerHTML=` + `],{type:"application/javascript"}))),pc.sharedWorker.onmessage=r=>{var s;if(r.data.type==="tick"){const g=pc.workerTasks.get(r.data.taskId);g&&(pc.isBreakLoop(g)?((s=pc.sharedWorker)==null||s.postMessage({type:"stop",taskId:g.taskID}),pc.workerTasks.delete(g.taskID)):(g.callback(),g.loopCount+=1))}}),pc.workerTasks.set(i.taskID,i),pc.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){const r=()=>{if(i.callback(),i.loopCount+=1,!pc.isBreakLoop(i))return i.timeoutID=setTimeout(r,i.delay)};return i.timeoutID=setTimeout(r,i.delay)}static ric(i){let r,s=Ns();const g=()=>{if(r=Ns()-s,r>=i.delay&&(s=Ns()-Math.floor(r%i.delay),i.callback(),i.loopCount+=1),!pc.isBreakLoop(i))return i.ricID=$5(g,{timeout:i.delay})};return i.ricID=$5(g,{timeout:i.delay})}static raf(i){let r,s=Ns();const g=()=>{if(document.hidden&&i.backgroundTask)return r=Ns()-s,s=Ns(),i.callback(),i.loopCount+=1,pc.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(g,i.delay-Math.floor(r%i.delay));if(r=Ns()-s,r>=i.delay&&(s=Ns()-Math.floor(r%i.delay),i.callback(),i.loopCount+=1),!pc.isBreakLoop(i))return i.rafID=requestAnimationFrame(g)};if(i.rafID=requestAnimationFrame(g),i.backgroundTask){const B=()=>{if(document.hidden){const Q=Ns()-s;Q>=i.delay?g():i.timeoutID=setTimeout(g,i.delay-Q)}};document.addEventListener("visibilitychange",B),i.onVisibilitychange=B,document.hidden&&B()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;const{intervalID:r,timeoutID:s,rafID:g,ricID:B,onVisibilitychange:Q}=this.taskMap.get(i);return r&&clearInterval(r),s&&clearTimeout(s),g&&A8&&A8(g),B&&XIA(B),Q&&document.removeEventListener("visibilitychange",Q),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)}};OA(GG,"taskMap",new Map),OA(GG,"currentTaskID",1),OA(GG,"sharedWorker",null),OA(GG,"workerTasks",new Map);var $IA=GG,Lu=$IA,vr={LOAD_START:gt.LOADSTART,LOADED_DATA:gt.LOADEDDATA,LOADED_META_DATA:gt.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:gt.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:gt.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:gt.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"},Hj={};M3(Hj,{create:()=>tW,remove:()=>Bk});var ek=new WeakMap;function tW(t,i){ek.has(t)||ek.set(t,[]);const r=ek.get(t),s={add:(g,B)=>("addEventListener"in i?(r.push(i.removeEventListener.bind(i,g,B)),i.addEventListener(g,B)):(r.push(i.off.bind(i,g,B)),i.on(g,B)),s)};return s}function Bk(t){const i=ek.get(t);i&&(i.forEach(r=>r()),ek.delete(t))}var AcA=class{constructor(){OA(this,"_roomIdMap",new Map),OA(this,"_configs"),typeof registerProcessor>"u"&&(this._configs={sdkAppId:"",userId:"",version:q2,env:xK.QCLOUD,browserVersion:ID.name+ID.version,ua:navigator.userAgent})}setConfig({sdkAppId:t,env:i,userId:r,roomId:s}){t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=r,this._roomIdMap.set(r,String(s))}logSuccessEvent(t){!X2&&qi.isAbleToUpload&&this._configs.env===xK.QCLOUD&&this.uploadEventToKibana(lB(cr({},t),{result:"success"}))}logFailedEvent(t){if(X2||!qi.isAbleToUpload)return;const{eventType:i,code:r,error:s,userId:g}=t,B={roomId:this._roomIdMap.get(g||this._configs.userId),userId:g,eventType:i,result:"failed",code:r||s?.extraCode||s?.code||xa.UNKNOWN};this._configs.env===xK.QCLOUD&&this.uploadEventToKibana(lB(cr({},B),{error:s}))}uploadEventToKibana(t){let i=`stat-${t.eventType}-${t.result}`;t.eventType!=="delta-join"&&t.eventType!=="delta-leave"&&t.eventType!=="delta-publish"||(i=`${t.eventType}:${t.delta}`),this.uploadEvent({log:i,userId:t.userId}),t.result==="failed"&&(i=`stat-${t.eventType}-${t.result}-${t.code}`,this.uploadEvent({log:i,userId:t.userId,error:t.error}))}uploadEvent({log:t,userId:i,error:r}){const s={timestamp:E9(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:q2,log:t};r&&(s.errorInfo=r.message,r.stack&&(s.errorInfo+=` +${r.stack}`));const g=Jj.enable?G3(s,2002,Number(this._configs.sdkAppId)):JSON.stringify(s);this.sendRequest(v3(this._configs.sdkAppId,B9.LOG),g)}sendRequest(t,i){setTimeout(()=>b9({url:t,body:i,priority:"low"}).catch(()=>{}),2e3)}},fC=new AcA,Km=new WeakMap;function ecA({settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:s}){return function(g,B,Q){const f=_3({retryFunction:Q.value,settings:t,onError({error:m,retry:M,reject:v,retryFuncArgs:U}){var AA;i?i.call(this,m,()=>{var z;(z=Km.get(g))!=null&&z.has(B)?M():v(m)},v,U):(AA=Km.get(g))!=null&&AA.has(B)?M():v(m)},onRetrying(m,M){var v;sw(r)&&r.call(this,m,M),(v=Km.get(g))!=null&&v.has(B)&&(Km.get(g).get(B).stopRetry=M)},onRetryFailed:s});return Q.value=function(...m){const M=Km.get(g);return M?M.set(B,{args:m}):Km.set(g,new Map([[B,{args:m}]])),f.apply(this,m).finally(()=>{var v;return(v=Km.get(g))==null?void 0:v.delete(B)})},Q}}var Xm=class extends Lr{constructor(t,i){super(t.id,`${i}-player`),this.options=t,this.kind=i,OA(this,"id"),OA(this,"element",null),OA(this,"track"),OA(this,"url"),OA(this,"attr"),OA(this,"mode"),OA(this,"muted"),OA(this,"_log"),OA(this,"isPausedByUserCall",!1),OA(this,"_pausedRetryCount"),OA(this,"_isElementPlayingFired",!1),OA(this,"_interval"),OA(this,"_delayDestroyTimeoutId",0),OA(this,"_playSuccessResolve"),OA(this,"_isReplayByRecreateMediaStreamCalled",!1),OA(this,"isPlayCalled",!1),OA(this,"isInAutoPlayFailedState",!1),OA(this,"isBindAutoPlayEvent",!1),this.id=t.id,this._log=t.log,this.track=t.track,this.muted=t.muted,this._pausedRetryCount=aw,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${i}-player ${this.id}`)}get isPlaying(){var t;return this._state==="PLAYING"&&((t=this.element)==null?void 0:t.paused)===!1}get isPaused(){var t;return this._state==="PAUSED"||((t=this.element)==null?void 0:t.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(t){this.attr=t}setUrl(t){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),t!==this.url&&(this.url=t,t!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=t))}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((t,i)=>{this._playSuccessResolve=t,this.element.play().then(t,i)})}catch(t){const i=AY({key:$2.PLAY_FAILED,data:{media:this.kind,error:t}});if(this._log.warn(t),i.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new Ws({code:xa.PLAY_NOT_ALLOWED,message:i})}}stop(t=0){var i;this.isPlayCalled=!1,this.isPausedByUserCall=!1,this._isElementPlayingFired=!1,this.unbindEvents(),t>0&&!sX?this._delayDestroyTimeoutId||((i=this.element)==null||i.remove(),this._log.info(`destroy element after 3 * ${t}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*t)):this.destroyElement(),this.handleStopped(gt.ENDED),this._interval>0&&Lu.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 t;(t=this.element)==null||t.pause()}resume(t=!1){return this.isPausedByUserCall=!1,this.doResume(t)}doResume(t=!1){return this._log.info("resume"),this.isPausedByUserCall||this.isPlaying?Promise.resolve():tIA?this.replay():this.play().catch(()=>{})}setMuted(t){this.element&&(this.element.muted=t),this.muted=t}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){const t=this.handleElementEvent.bind(this);return tW(this.element,this.element).add(gt.PLAYING,t).add(gt.ENDED,t).add(gt.PAUSE,t).add(gt.ERROR,t).add(gt.LOADSTART,t).add(gt.LOADEDDATA,t).add(gt.LOADEDMETADATA,t)}}bindTrackEvents(t=this.track){if(t){const i=this.handleTrackEvent.bind(this);Hj?.create(t,t).add(gt.ENDED,i).add(gt.MUTE,i).add(gt.UNMUTE,i),t.readyState===gt.ENDED&&this.handleTrackEvent({type:gt.ENDED}),t.muted&&this.handleTrackEvent({type:gt.MUTE})}}bindAutoPlayEvent(){this.isBindAutoPlayEvent||(this._log.warn("bindAutoPlayEvent"),Eo.on(nr.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!0)}unbindTrackEvents(t=this.track){t&&Bk(t)}unbindEvents(){this.element&&Bk(this.element),this.unbindTrackEvents(),Eo.off(nr.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!1}handleElementEvent(t){switch(t.type){case gt.PLAYING:uk()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(gt.PLAYING),this._interval&&(Lu.clearTask(this._interval),this._interval=-1);break;case gt.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(gt.ENDED);break;case gt.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(gt.PAUSE);break;case gt.ERROR:if(this.element&&this.element.error){this.handlePaused(gt.ERROR);const{code:i,message:r}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${i} message: ${r} userAgent: ${navigator.userAgent}`),fC.uploadEvent({log:`stat-${this.kind}-${zG.PLAYER_ERROR}-${i}-${navigator.userAgent}`,error:this.element.error}),$gA||eX?this.emit(vr.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case gt.LOADEDDATA:this.kind===gt.VIDEO&&this.emit(vr.LOADED_DATA);break;case gt.LOADEDMETADATA:this.kind===gt.VIDEO&&this.emit(vr.LOADED_META_DATA);break;case gt.LOADSTART:this.emit(vr.LOAD_START)}}replayByRecreateMediaStream(t){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),fC.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),qr.addSuccessEvent({key:this.kind===gt.AUDIO?506700:516700})}).catch(()=>{var i;this._log.error("replayByRecreateMediaStream failed"),fC.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),qr.addFailedEvent({key:this.kind===gt.AUDIO?506700:516700,error:(i=this.element)==null?void 0:i.error}),this.emit(vr.ERROR,t)})}doReplayByRecreateMediaStream(t){return this._log.warn(`delay ${t}ms to recreate mediaStream`),new Promise((i,r)=>{vw(t).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var s,g,B;this._log.warn(`element onerror ${(g=(s=this.element)==null?void 0:s.error)==null?void 0:g.code} fired after recreated mediaStream`),r((B=this.element)==null?void 0:B.error)}),vw(5e3).then(()=>{var s,g;this.isPlaying&&!((s=this.element)!=null&&s.error)||r((g=this.element)==null?void 0:g.error),i()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}async handleTrackEvent(t){const i=t.type;switch(this.options.enableLogTrackState&&this._log[i===gt.UNMUTE?"info":"warn"](`track ${i}`),i){case gt.ENDED:this.handleStopped(gt.ENDED);break;case gt.MUTE:this.handlePaused(gt.MUTE);break;case gt.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(gt.UNMUTE))}}handlePlaying(t){var i;return this._log.debug("handlePlaying",t),(i=this._playSuccessResolve)==null||i.call(this,t),t}handlePaused(t){return this._log.debug("handlePaused",t),t}handleStopped(t){return this._log.debug("handleStopped",t),t}getElement(){return this.element}};OA(Xm,"PlayerEvent",vr),ss([ecA({settings:{retries:2,timeout:0},onError(t,i,r,s){s[0]=(s[0]||1e3)+1e3,i()}})],Xm.prototype,"doReplayByRecreateMediaStream"),ss([FI([],"PLAYING",{sync:!0,success(t){this.emit(vr.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:t})}})],Xm.prototype,"handlePlaying"),ss([FI("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(t){this.emit(vr.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:t})}})],Xm.prototype,"handlePaused"),ss([FI([],"STOPPED",{sync:!0,success(t){this.emit(vr.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:t})}})],Xm.prototype,"handleStopped");var Cd="trtc_autoplay",zK=`${Cd}_mask`,pG=`${Cd}_wrapper`,e8=`${Cd}_header`,ZK=`${Cd}_content`,l2=`${Cd}_action_wrapper`,XK=`${Cd}_question`,$K=`${Cd}_collapse`,C2=`${Cd}_action_confirm`,t8=`${Cd}_detail`,i8="#2473E8",iW="dialog",tcA=`${iW}-show`,icA=`${iW}-1`,ocA=`${iW}-2`,o8=!1,Vj=!1,uk=()=>Vj,PX=`${_j}/${dp()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,r8=`
${dp()?"其他方案?":"Any other solution?"}`,rcA=dp()?`浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。${r8}`:`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. ${r8}`,ncA=class{constructor(){if(OA(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),OA(this,"_dialogNode",null),OA(this,"_bodyPosition",""),OA(this,"_showDetail",!1),OA(this,"_isCollapseClicked",!1),OA(this,"_isQuestionClicked",!1),dp()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!o8){const t=document.createElement("style");t.innerHTML=`.${zK}{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;}.${zK} div:not(.${l2}){display:block !important;}.${pG}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${pG} a{color:${i8};}.${e8}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${ZK}{margin:8px 0;}.${l2}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${$K}{margin-right:auto;cursor:pointer}.${XK}{height:100%;line-height:16px;cursor:pointer;}.${C2}{margin-left:8px;color:#fff;background:${i8};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${C2}:hover{opacity:0.9;}.${$K},.${C2},.${ZK},.${XK}{font-size:14px;}@media screen and (max-width:750px){.${pG}{width:80vw;}}`,document.head.appendChild(t),o8=!0}this.addDiaLog()}createDiaLog(){const t=document.createElement("template");t.innerHTML=`
${location.host}
${this.content}
`.trim();const i=document.createElement("button");i.className=C2,i.innerText=dp()?"恢复播放":"Resume",i.onclick=this.onConfirm.bind(this);const r=document.createElement("div");r.className=XK,r.innerHTML=` - `,r.onclick=this.onQuestionClick.bind(this);const s=document.createElement("div");s.className=KK,s.innerText=Bp()?"详情 >":"Detail >",s.onclick=this.onCollapseClick.bind(this);const g=t.content.firstChild,B=g.querySelector(`.${n2}`);return B.appendChild(s),B.appendChild(r),B.appendChild(i),g}addDiaLog(){Ik()||(Oj=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${uG}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",qi.info("show autoplay dialog"),fC.uploadEvent({log:VIA}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Oj=!1),ck=null}onConfirm(){qi.warn("confirm clicked, try resume stream"),Eo.emit(nr.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){const t=this._dialogNode.querySelector(`.${W5}`);t.style.visibility=this._showDetail?"hidden":"visible",t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||fC.uploadEvent({log:qIA}),this._isCollapseClicked=!0}onQuestionClick(){window.open(kX,"_blank"),this._isQuestionClicked||fC.uploadEvent({log:KIA}),this._isQuestionClicked=!0}},ck=null;function zIA(){ck||(ck=new WIA)}function ZIA(){ck&&ck.deleteDialog()}var ZG,Ip=class extends jm{constructor(t){super(t,gt.VIDEO),OA(this,"stat",{}),OA(this,"_calculateTimeout",-1),OA(this,"viewMirror",!1),OA(this,"objectFit","cover"),OA(this,"container"),OA(this,"canvas"),OA(this,"shouldRenderAlpha",!1),OA(this,"_preSize",{width:0,height:0}),OA(this,"posterImg"),OA(this,"pipWindow"),OA(this,"enterPIPPromise"),OA(this,"_originContainerPosition"),OA(this,"_isResettingSrcObject",!1),OA(this,"_wrapper",null),OA(this,"_useWrapper",!1),OA(this,"_isFirstFrameRenderEmitted",!1),this.mode=t.canvas?1:0,this.container=t.container,this.canvas=t.canvas,Fr(t.viewMirror)||(this.viewMirror=t.viewMirror),Fr(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(){const t=document.createElement(gt.VIDEO);this.track&&this.mode!==2&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id",`video_${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,hl&&(t.poster="data:,"),this._appendToWrapper(),this.bindElementEvents(),this.calculateStat(),this._bindFirstFrameRenderEvent(t)}_bindFirstFrameRenderEvent(t){const i=()=>{if(this._isFirstFrameRenderEmitted)return;this._isFirstFrameRenderEmitted=!0;const r=t.videoWidth||0,s=t.videoHeight||0;this._log.info(`first frame render: ${r}x${s}`),this.emit(vr.FIRST_FRAME_RENDER,{width:r,height:s})};typeof t.requestVideoFrameCallback=="function"?t.requestVideoFrameCallback(i):t.addEventListener("loadeddata",i,{once:!0})}get styleAttribute(){let t=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&&(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){const i=this._getOrCreateWrapper();i.insertBefore(this.elementToRender,i.firstChild)}else this.container.appendChild(this.elementToRender),this._cleanupWrapper()}setContainer(t){if(this.container===t)return;const i=this._wrapper,r=this.container;this.container=t,this._pausedRetryCount=ow,this.track&&this.elementToRender&&this._appendToWrapper(),i&&r&&r!==this.container&&i.isConnected&&i.children.length===0&&i.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){const i=t??this.elementToRender;if(this.container&&i)if(this._useWrapper){const r=this._getOrCreateWrapper();r.insertBefore(i,r.firstChild)}else this.container.appendChild(i)}bindElementEvents(){const t=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),this.handleFullscreenChange=this.handleFullscreenChange.bind(this),this.handleVolumeChange=this.handleVolumeChange.bind(this),t&&t.add(gt.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(gt.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(gt.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener(gt.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 i;return t.type===gt.MUTE&&((i=this.stat)!=null&&i.fps&&(this.stat.fps=0),this.isFullscreen()&&this.resetSrcObjectToReplay()),super.handleTrackEvent(t)}handleFullscreenChange(){this.isFullscreen()?(this._log.info("enter fullscreen"),this.emit(vr.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(vr.LEAVE_FULL_SCREEN))}handleVolumeChange(){var t;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(vr.VOLUME_CHANGE,{muted:(t=this.element)==null?void 0:t.muted})}handleElementEvent(t){var i,r,s,g,B,Q;if(this.mode===2)return;super.handleElementEvent(t);const f=t.type,m=this.isPictureInPicture(),M=this.isFullscreen(),v=t.isTrusted&&(m&&IE||M);if(f===gt.PLAYING&&v&&!this._isResettingSrcObject&&(this._log.warn("user resume in "+(M?"fullscreen":"pip")),this.emit(vr.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),f===gt.PAUSE&&(v&&(this._log.warn("user pause in "+(M?"fullscreen":"pip")),this.emit(vr.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}`),Rw(500).then(()=>{var U;(U=this.container)!=null&&U.isConnected&&(this._pausedRetryCount=ow,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!Ik()&&!this.isPausedByUserCall&&!v&&(this._log.info(`[${ow-this._pausedRetryCount+1}/${ow}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),UI&&!v&&(this._interval=ku.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 U=this.element.style.transform;f===gt.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=U.replace("scaleX(-1)",""):f!==gt.LEAVE_PICTURE_IN_PICTURE||U.includes("scaleX")||(this.element.style.transform=`${U} scaleX(-1)`)}f===gt.RESIZE&&(this._preSize.height===((i=this.element)==null?void 0:i.videoHeight)&&this._preSize.width===((r=this.element)==null?void 0:r.videoWidth)||(this._log.info(`video size changed to ${(s=this.element)==null?void 0:s.videoWidth}x${(g=this.element)==null?void 0:g.videoHeight}`),this._preSize.height=((B=this.element)==null?void 0:B.videoHeight)||0,this._preSize.width=((Q=this.element)==null?void 0:Q.videoWidth)||0,this.emit(vr.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))),f===gt.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(vr.LEAVE_PICTURE_IN_PICTURE)),f===gt.ENTER_PICTURE_IN_PICTURE&&this.emit(vr.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){hl&&YK&&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,i=1){var r,s;this.canvas!==t&&((r=this.canvas)==null||r.remove(),t?.setAttribute("style",this.styleAttribute),this.canvas=t,this.mode=t?i:0,this.mode===2&&this.setTrack(t.captureStream().getVideoTracks()[0]),t?((s=this.element)==null||s.remove(),this._appendToWrapper(t)):this.element&&this._appendToWrapper(this.element))}setAttr(t){const i=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},t);i.style=Object.assign({width:"100%",height:"100%"},i.style),super.setAttr(i)}get mirror(){return this.viewMirror}setRect(t,i){this.elementToRender&&(this.elementToRender.style.width=`${t}px`,this.elementToRender.style.height=`${i}px`)}setViewMirror(t){this.elementToRender&&(this.elementToRender.style.transform=t?"scaleX(-1)":""),this.viewMirror=t}setObjectFit(t){this.elementToRender&&(this.elementToRender.style.objectFit=`${t}`),this.objectFit=t}setPoster(t,i=!1){return new Promise(r=>{if(!this.element||(this._log.info("setPoster",t.slice(0,10)),t===""?this.element.removeAttribute("poster"):this.element.poster=t,!(i&&(IE||Ql))))return r();if(t==="")return this.removePosterImg(),r();if(this.posterImg)return r();const s=document.createElement("img");s.src=t;const g=window.getComputedStyle(this.element),B=g.objectFit||this.objectFit;let Q=1;if(this._useWrapper){const f=parseInt(g.zIndex,10);isNaN(f)||(Q=f+1)}s.style.cssText=this._useWrapper?`grid-area:1/1;z-index:${Q};width:100%;height:100%;object-fit:${B};`:`position:absolute;top:0;left:0;width:100%;height:100%;object-fit:${B};`,s.onload=async()=>{try{s.decode&&await s.decode(),this.container&&!this._useWrapper&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=s;const f=this._useWrapper?this._wrapper:this.container;f?.appendChild(s),J2()&&QD<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(f){this._log.warn("decode poster image error",f)}return r()},s.onerror=()=>(this._log.warn("load poster image error"),r())})}removePosterImg(){this.posterImg&&(J2()&&QD<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),this._useWrapper||!this.container||Fr(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"))}async pause(t=!0){super.pause(),this.isPictureInPicture()||this.hasPoster||!(YK||t&&(Ql||IE))||await this.setPoster(this.getVideoFrame(),!0)}resume(t=!1){return super.resume(t).then(()=>{var i;(this.posterImg||(i=this.element)!=null&&i.poster)&&this.setPoster("",!0)})}doResume(t=!1){return this.isPaused&&t&&this.element&&this.track&&YK&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(t=0){var i;this.isPictureInPicture()&&this.exitPictureInPicture().catch(r=>{}),this.isFullscreen()&&this.exitFullscreen().catch(r=>{}),this.element&&(this.element.removeEventListener(gt.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),(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(t){if(Fr(t?.isLiveStream)||this.setLiveMode(t.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(t){t!==this.track&&(this.unbindTrackEvents(),this.track=t,this.emit(vr.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"";const 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(j3()&&this.element&&this._calculateTimeout<0){let t=0,i=null;const r=(s,g)=>{this.stat.width=g.width,this.stat.height=g.height,i&&(this.stat.fps=Math.round((g.presentedFrames-i.presentedFrames)/(s-t)*1e3)),t=s,i=g,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var B;return(B=this.element)==null?void 0:B.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(t){this._log.warn("init stat failed",t)}}async enterFullscreen(){const t=this.elementToRender;if(!t)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");if(UI&&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(t.requestFullscreen)await t.requestFullscreen();else if(t.webkitRequestFullscreen)await t.webkitRequestFullscreen();else if(t.webkitEnterFullscreen)await t.webkitEnterFullscreen();else if(t.mozRequestFullScreen)await t.mozRequestFullScreen();else{if(!t.msRequestFullscreen)throw new Error("Fullscreen API not supported");await t.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(t){throw this._log.error("failed to exit fullscreen:",t),t}}isFullscreen(){const t=this.elementToRender;return t?this.element&&this.element.webkitDisplayingFullscreen?!this.isPictureInPicture():(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===t:!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:t}=this;if(t.requestPictureInPicture){this._log.info("requestPictureInPicture");const i=await t.requestPictureInPicture();return this.pipWindow=i,this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),this._appendToWrapper(this.element)),i}if(t.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),await 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}}async exitPictureInPicture(){var t;try{if(!this.isPictureInPicture())return;if(delete this.pipWindow,document.pictureInPictureElement&&document.exitPictureInPicture)await document.exitPictureInPicture(),this.elementToRender===this.canvas&&((t=this.element)==null||t.remove(),this._pausedRetryCount=ow,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:t}=this;return document.pictureInPictureElement?document.pictureInPictureElement===t:!!t.webkitPresentationMode&&t.webkitPresentationMode==="picture-in-picture"}async togglePictureInPicture(){this.isPictureInPicture()?await this.exitPictureInPicture():await this.enterPictureInPicture()}};async function XIA(t,i){if(!t.audioWorklet)return Promise.reject("audioWorklet is not supported");try{await t.audioWorklet.addModule(i),qi.info("worklet addModule success")}catch(r){throw qi.info(`worklet addModule catch error. ${r.message}`),r}}typeof AudioContext<"u"?ZG=AudioContext:typeof webkitAudioContext<"u"?ZG=webkitAudioContext:typeof mozAudioContext<"u"&&(ZG=mozAudioContext);var LI,$IA=1500,$5=-1,s2=0,XG=-1,xj=!1,A8=0,e8=-1,t8=-1;function _X(){try{if(LI)return;(LI=new ZG({sampleRate:48e3})).onstatechange=()=>{qi.info(`context state: ${LI.state}${LI.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),fw()},clearTimeout($5)}catch(t){qi.error(`initAudioContext failed: ${t} typeof AudioContextClass: ${typeof ZG}`),$5=setTimeout(_X,1e3)}}_X();var fw=()=>{LI.state==="suspended"?(s2=Ns(),AcA(),z2(),document.addEventListener("click",fw)):LI.state==="interrupted"?z2():(s2&&(qr.addNumber({key:507800,value:Ns()-s2,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),s2=0),ecA(),document.removeEventListener("visibilitychange",fw),document.removeEventListener("click",fw))},jK=0,WK=-1;function z2(){return new Promise((t,i)=>{if(LI.state==="running")return t();Date.now()-jK<1e3?(clearTimeout(WK),WK=setTimeout(()=>{jK=Date.now(),LI.resume().then(t,i)},1e3)):(clearTimeout(WK),jK=Date.now(),LI.resume().then(t,i))}).catch(t=>{qi.warn(`context resume failed: ${t}`),document.addEventListener("visibilitychange",fw)})}function AcA(){XG===-1&&(XG=setTimeout(()=>{LI.state==="suspended"&&(xj=!0,Eo.emit("155",{isSuspended:!0}))},$IA))}function ecA(){XG!==-1&&(clearTimeout(XG),XG=-1,xj&&(xj=!1,Eo.emit("155",{isSuspended:!1})))}function tcA(){if(!UI||t8!==-1)return;const t=()=>{Ns()-A8<500||(LI&&LI.state==="running"&&LI.currentTime===e8&&(qi.warn("context is fake running, auto resume"),LI.suspend().catch(i=>{qi.warn(`context suspend failed: ${i}`)})),e8=LI.currentTime,A8=Ns())};t8=setInterval(()=>{t()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()})}document.addEventListener("click",fw);var mp=t=>LI,aD=class{constructor(t){this.name=t,OA(this,"node"),OA(this,"node2"),OA(this,"pre",new Set),OA(this,"next",new Set),OA(this,"context"),OA(this,"connectedNodes",new Set),OA(this,"nextInputChannelMap",new Map),OA(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(t){this._channelCount=t,this.setChannelCount(this.node,t),this.setChannelCount(this.node2,t),this.next.forEach(i=>i.channelCount=t)}setChannelCount(t,i){!t||t instanceof ScriptProcessorNode||(t.channelCountMode="explicit",t.channelCount=i||this.channelCount||1)}setContext(t){this.context=t,this.node&&t.addMixWeight()}removeContext(){var t;this.node&&((t=this.context)==null||t.reduceMixWeight()),delete this.context}replaceNode(t){var i;if(t!==this.node)try{this.node?this._disconnect():(i=this.context)==null||i.addMixWeight(),this.node=t,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(r){qi.error(r)}}setNode(t,i){var r;if(!this.node)try{(r=this.context)==null||r.addMixWeight(),this.node=t,this.setChannelCount(this.node),i&&(this.node2=i,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),qr.addSuccessEvent({key:502701})}catch(s){qi.error(s),qr.addFailedEvent({key:502701,error:s})}}deleteNode(){var t;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(t=this.context)==null||t.reduceMixWeight(),this.preNodeReconnect(),qr.addSuccessEvent({key:502702})}catch(i){qi.error(i),qr.addFailedEvent({key:502702,error:i})}}preNodeReconnect(){this.pre.forEach(t=>{t.node?t.reconnect():t.preNodeReconnect()})}connectNext(t){this.next.forEach(i=>{const r=this.nextInputChannelMap.get(i);t._connect(i.node,r)||i.connectNext(t)})}_connect(t,i=0){return!(!this.node||!t)&&((this.node2||this.node).connect(t,0,i),this.connectedNodes.add(t),!0)}_disconnect(){this.connectedNodes.forEach(t=>{var i;return(i=this.node2||this.node)==null?void 0:i.disconnect(t)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(t,i=0){return this.next.add(t),t.pre.add(this),this.nextInputChannelMap.set(t,i),t}},icA=class extends aD{constructor(t=256){super(),this.fftSize=t,OA(this,"dataArray",new Uint8Array(0))}setNode(t){t.fftSize=this.fftSize,this.dataArray=new Uint8Array(t.frequencyBinCount),super.setNode(t)}getByteTimeDomainData(){var t;return(t=this.node)==null||t.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var t;return(t=this.node)==null||t.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){const t=this.getByteTimeDomainData();let i=0,r=0,s=`M${i},${r}`;for(let g=0;gthis.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Ad.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=r=>{Ad.lastMessageTime=Date.now(),this._volume=r.data.volume||0,this._volumeDb=r.data.volumeDb||0,!i&&r.data.cacheLen&&r.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}`),fC.logFailedEvent({userId:this._log.userId,eventType:VG.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=mp("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{Ad.lastMessageTime=Date.now();const r=i.inputBuffer.getChannelData(0);let s=0;for(let g=0;g>2);t.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),t.close()}}},acA=Tw(mk()),r8=t=>i=>i.deviceId===t,zK=class{constructor(t,i){OA(this,"kind"),OA(this,"type"),OA(this,"devices",[]),this.kind=t,this.type=i}update(t,i){const r=t.filter(s=>s.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);this.devices.length===1&&bX(this.devices[0])||i&&(r.forEach(s=>{if(s.deviceId&&!this.devices.find(r8(s.deviceId))){const g=`${this.kind}${this.type}Added`;qi.warn(`${g}: ${JSON.stringify(s)}`),i.emit(g,s)}}),this.devices.forEach(s=>{if(s.deviceId&&!r.find(r8(s.deviceId))){const g=`${this.kind}${this.type}Removed`;qi.warn(`${g}: ${JSON.stringify(s)}`),i.emit(g,s)}})),this.devices=r}hasDevice(t){return!!this.devices.find(i=>i.deviceId===t)}},scA=class extends acA.EventEmitter{constructor(){super(),OA(this,"audioInputs",new zK(gt.AUDIO,"Input")),OA(this,"videoInputs",new zK(gt.VIDEO,"Input")),OA(this,"audioOutputs",new zK(gt.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||ku.run("interval",()=>{this.update()},{delay:1e4}))}init(){Yj().then(t=>{this.audioInputs.update(t),this.videoInputs.update(t),this.audioOutputs.update(t)})}async update(t=0){const i=await Yj(t);return this.audioInputs.update(i,this),this.videoInputs.update(i,this),this.audioOutputs.update(i,this),this}hasBlueTooth(){var t;if(1e3*((t=mp())==null?void 0:t.outputLatency)>150)return!0;const i=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(r=>i.some(s=>r.label.toLowerCase().includes(s)))||this.audioInputs.devices.some(r=>i.some(s=>r.label.toLowerCase().includes(s)))}},Tu=r9||o9?null:new scA;function bX(t){return t.deviceId===t.groupId&&t.groupId===""}async function Yj(t=0){if(vY()||!H3())return[];let i=await navigator.mediaDevices.enumerateDevices();if(t!==0){const r={audio:!1,video:!1};if(i.forEach(s=>{bX(s)&&(s.kind===gt.AUDIO_INPUT?r.audio=!0:s.kind===gt.VIDEO_INPUT&&(r.video=!0))}),t===2&&(r.audio=!1),t===1&&(r.video=!1),r.audio||r.video){let s;try{s=await navigator.mediaDevices.getUserMedia(r),r.audio&&z2()}catch(g){qi.debug("capture before getDevices failed: ",g)}i=await navigator.mediaDevices.enumerateDevices(),s?.getTracks().forEach(g=>g.stop())}}return i.map((r,s)=>{const g={kind:r.kind,deviceId:r.deviceId,groupId:r.groupId,label:r.label||`${r.kind}_${s}`};return r.deviceId.length>0&&X3.add(`${r.deviceId}_${r.kind}`),r.getCapabilities&&(g.getCapabilities=()=>r.getCapabilities()),g})}function Ek(t=!1){return Tu.update(t?1:0).then(i=>i.audioInputs.devices)}function sD(t=!1){return Tu.update(t?2:0).then(i=>i.videoInputs.devices)}var n8=!1;async function gcA(){try{n8||(n8=!0,qi.info(`speakers:${(await IcA()).map(t=>` ${t.deviceId.slice(0,8)}: ${t.label}`)}`))}catch{}}async function IcA(t=!1){return(UI||IE)&&(t=!1),Tu.update(t?1:0).then(i=>i.audioOutputs.devices)}var y2,X3=new Set;function ccA(t){if(t instanceof CanvasCaptureMediaStreamTrack||!(t instanceof MediaStreamTrack))return!1;const i=t.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;const r=`${(t?.getSettings()||{}).deviceId}_${gt.VIDEO_INPUT}`;return!!X3.has(r)}function EcA(t){if(t instanceof CanvasCaptureMediaStreamTrack||!(t instanceof MediaStreamTrack))return!1;const i=t.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("麦克风"))return!0;const r=`${(t?.getSettings()||{}).deviceId}_${gt.AUDIO_INPUT}`;return!!X3.has(r)}async function lcA(t,i){const r=(await Ek()).find(s=>s.deviceId===s9);return!i&&r?.groupId===t||r?.groupId===t&&r.label===i}async function CcA({newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:s,kind:g}){return t===i&&(g!==gt.AUDIO||t!==s9||await lcA(r,s))}var BcA=class extends ocA{constructor(t){super(),this.log=t,OA(this,"volumeMeter"),OA(this,"volumeMeterAfter3A"),OA(this,"volumeDestination"),OA(this,"analyser",new icA),this.volumeMeter=new o8({log:this.log}),this.volumeMeterAfter3A=new o8({log:this.log}),this.volumeDestination=new aD,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},ucA=class extends jm{constructor(t){super(t,gt.AUDIO),OA(this,"_outputDeviceId"),OA(this,"_floatVolume",1),OA(this,"_destination"),OA(this,"pipeline"),OA(this,"volumeMeterMode","worklet"),OA(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=t.enableVolumeControlInIOS,this.mode=0,t.url&&(this.url=t.url),this.pipeline=new BcA(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((_u==="15.2"||_u==="15.3"||_u==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");this._log.info("audio player initializeElement");const i=y2||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(uD(t)?t/100:this._floatVolume),i===y2&&(y2=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(vr.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}async play(t){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&&await this.setSinkId(this._outputDeviceId),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(mp("player").createAnalyser()),gcA()}catch(i){throw this._log.warn(`audio play error: ${i}`),AX(_u,"18.7",!0)&&this.bindAutoPlayEvent(),i}return super.play()}}stop(t=0){this.pipeline.destroy(),super.stop(t)}setVolume(t){this._floatVolume=t,this.element&&(this.element.volume=t)}async setSinkId(t){var i,r;this._outputDeviceId!==t&&(this._outputDeviceId=t),this.element&&this.element.sinkId!==t&&await((r=(i=this.element).setSinkId)==null?void 0:r.call(i,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()}},QcA=class extends ucA{constructor(t){super(t),OA(this,"_sourceElement"),OA(this,"_output",new aD),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(mp().destination)}write(t){this.pipeline.volumeMeter.write(t)}setTrack(t){var i,r,s;((r=(i=this.element)==null?void 0:i.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==t&&(this.unbindTrackEvents(),this.track=t,this.emit(vr.MEDIA_TRACK_CHANGED,t),t?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([t]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([t])),this.pipeline.source.channelCount=((s=t.getSettings())==null?void 0:s.channelCount)||1,this.pipeline.replaceSource(t)):this.pipeline.source.deleteNode())}setVolume(t){var i;const r=t<=1&&!J2();if(!(this._floatVolume===t&&(r&&((i=this.element)==null?void 0:i.volume)===t||!r&&this.pipeline.volume===t)))if(this._floatVolume=t,this.useDestination)this.pipeline.setVolume(t),this._log.info(`set pipeline volume: ${t}`);else if(r)this.element?(this._log.info(`set element volume: ${t}`),this.element.volume=t):this._log.info("set element volume: no element");else{if(J2()){if(!this.enableVolumeControlInIOS)return;tcA()}if(Ql&&!this.pipeline.source.node)return void this._log.warn("set pipeline volume failed: no source node");this._log.info(`start set pipeline volume: ${t}`),this.pipeline.setVolume(t),this.element&&!this._sourceElement&&(this._destination||(this._destination=mp().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),gk(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(s=>{this.emit(vr.AUTOPLAY_FAILED,s)}))}}stop(t=0){this.pipeline.destroy();const i=this._sourceElement||this.element;i&&$9&&(y2=i),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(t)}},$3=class extends Lr{constructor({userId:t,sdkAppId:i,mediaType:r,room:s,PlayerClass:g=r===1?QcA:Ip}){var B;super(),OA(this,"id",aX()),OA(this,"userId",""),OA(this,"isRemote"),OA(this,"mediaType"),OA(this,"room"),OA(this,"user"),OA(this,"_log"),OA(this,"_inputTrack"),OA(this,"_outputTrack"),OA(this,"isPlayCalled"),OA(this,"container",null),OA(this,"player"),OA(this,"subVideoPlayerMap"),OA(this,"muted",!1),OA(this,"abortCtrl"),OA(this,"objectFit","cover"),OA(this,"mirror"),OA(this,"rotation"),OA(this,"isScreen",!1),OA(this,"manager"),OA(this,"trackSettings"),OA(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=r,this._log=qi.createLogger({parent:s?.getLogger(),id:`${this.kind[0]}t`,userId:(B=s||this.room)==null?void 0:B.userId,remoteUserId:this instanceof AD?void 0:this.userId,sdkAppId:i,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof AD}),this.player=new g({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:s?.enableVolumeControlInIOS}),this.player.on(vr.PLAYER_STATE_CHANGED,Q=>{if(Eo.emit(nr.PLAYER_STATE_CHANGED,cr({track:this},Q)),this.emit("player-state-changed",Q),Q.state==="PLAYING"&&this.room){let f=!0;for(const{remoteAudioTrack:m,remoteVideoTrack:M,remoteAuxiliaryTrack:v}of[...this.room.remotePublishedUserMap.values()])if(m.isAvailable&&!m.player.isPlaying||M.isAvailable&&!M.player.isPlaying||v.isAvailable&&!v.player.isPlaying){f=!1;break}f&&Ik()&&ZIA()}}),this.kind===gt.VIDEO&&(this.player.on(vr.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(vr.LOADED_DATA),Eo.emit(nr.VIDEO_LOADED_DATA,{track:this})}),this.player.on(vr.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(vr.LOADED_META_DATA)}),this.player.on(vr.MEDIA_TRACK_CHANGED,Q=>{var f;(f=this.subVideoPlayerMap)==null||f.forEach(m=>m.setTrack(Q))}),this.player.on(vr.RESIZE,Q=>{this.emitFirstVideoFrameEvent(vr.RESIZE),this.emit("video-size-changed",cr({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},Q))}),this.player.on(vr.FIRST_FRAME_RENDER,Q=>{this.emit("first-frame-render",lB(cr({},Q),{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(vr.ERROR,this.onPlayerError.bind(this)),this.player.on(vr.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||qi}get kind(){return this.mediaType===1?gt.AUDIO:gt.VIDEO}get isAudio(){return this.kind===gt.AUDIO}get strMediaType(){return this.mediaType===4?gt.VIDEO:this.mediaType===2?gt.SCREEN:gt.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(t,i){const r=dC(t)?t[0]:t;if(this.isPlayCalled)return this.log.info(`play update options: ${JSON.stringify(i)}`),i&&!Fr(i.muted)&&this.setPlayerMute(i.muted),i&&!Fr(i.objectFit)&&(this.objectFit=i.objectFit),void(this.player instanceof Ip&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(dC(t)&&t.length>=1&&this.container&&t.includes(this.container)&&this.container.contains(this.player.elementToRender)?(t.splice(t.indexOf(this.container),1),t.unshift(this.container)):(this.container=r,this.player.setContainer(r))),dC(t)&&t.length>=1&&await this.playSubContainer(t.slice(1),i)));if(i&&!Fr(i.muted)?this.setPlayerMute(i.muted):this.isRemote&&this.kind!==gt.VIDEO||this.setPlayerMute(!0),i&&!Fr(i.objectFit)&&(this.objectFit=i.objectFit),this.player instanceof Ip&&(Fr(i?.isLiveStream)||this.player.setLiveMode(i.isLiveStream),this.player.setObjectFit(this.objectFit),i&&!Fr(i.poster)&&this.player.setPoster(i.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof Ip&&this.player.setContainer(r)),Eo.emit(nr.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),dC(t)&&t.length>1&&await this.playSubContainer(t.slice(1),i)}catch(s){throw this.handleAutoPlayFailed(s),s}}else this.log.info("play has not mediaTrack, abort")}setMirror(t,i){if(this.isScreen||this.kind!==gt.VIDEO||Fr(t)||t===this.mirror)return;this.mirror=t;let r=this.player;i&&(r=i);const s=this.manager;if(rD(this.mirror))return r.setViewMirror(this.mirror),void(!this.isRemote&&s&&(s.mirror=!1));switch(this.mirror){case"view":s&&(s.mirror=!1),r.setViewMirror(!0);break;case"publish":s&&(s.mirror=!0),r.setViewMirror(!0);break;case"both":s&&(s.mirror=!0),r.setViewMirror(!1)}}async playSubContainer(t,i){if(!this._outputTrack||this.kind===gt.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,g)=>{var B;t.find(Q=>g===Q)||(s.stop(),(B=this.subVideoPlayerMap)==null||B.delete(g))});for(const[s,g]of t.entries()){const B=this.subVideoPlayerMap.get(g);B?i&&(Fr(i.objectFit)||B.setObjectFit(i.objectFit)):this.subVideoPlayerMap.set(g,new Ip({id:this.userId||this.id,track:this.playerMediaTrack,container:g,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}const r=[...this.subVideoPlayerMap.values()];for(const s of r)s.setViewMirror(this.player.mirror),await s.play()}setAudioOutput(t){return this.player.setSinkId(t)}setAudioVolume(t){this.player.setVolume(t)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var t;return((t=this.player)==null?void 0:t.getInternalAudioLevel())||0}stop(t=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(OK(this)&&!t?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(i=>{i.stop()}),this.container=null)}async resume(){var t;this.isPlayCalled&&await((t=this.player)==null?void 0:t.resume())}close(){this._toInitState(),this.log.info("close"),this.isPlayCalled&&this.stop(!0)}_toInitState(){}setMute(t){this.muted=t,this._inputTrack&&(this._inputTrack.enabled=!t),this._outputTrack&&(this._outputTrack.enabled=!t),this.emit(t?"mute":"unmute",this),Eo.emit(t?nr.TRACK_MUTED:nr.TRACK_UNMUTED,{track:this})}setPlayerMute(t){this.player.setMuted(t)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(t){z3(t,t).add(gt.MUTE,this.onTrackMuted).add(gt.UNMUTE,this.onTrackUnmuted).add(gt.ENDED,this.onTrackEnded),t.muted&&this.onTrackMuted(),t.readyState===gt.ENDED&&this.onTrackEnded()}uninstallTrackEvent(t){gk(t)}setInputMediaStreamTrack(t){var i;const r=this._inputTrack;if(t!==r)return this._inputTrack=t,this.trackSettings=(i=t.getSettings)==null?void 0:i.call(t),t.enabled=!this.muted,r&&this.uninstallTrackEvent(r),this.installTrackEvent(t),this.emit("input-media-track-changed",t||null,r||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(t)}setOutputMediaStreamTrack(t){var i;const r=this._outputTrack;this instanceof GY&&w3(r)||t!==r&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",t.label):this.log.info("setOutputMediaStreamTrack",(i=t.getSettings)==null?void 0:i.call(t).deviceId,t.label),this._outputTrack=t,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!t),this.emit("output-media-track-changed",t))}setMediaType(t){this.mediaType=t}updatePlayingState(t){var i,r;if(this.isPlayCalled){if(t){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch(s=>this.handleAutoPlayFailed(s)),void this.log.info(`playing state updated, play ${this.kind}`)}else if(!this.player.isStopped)return OK(this)&&this.isAudio&&((i=this.user)!=null&&i.muteState.hasAudio)&&((r=this.user)!=null&&r.muteState.audioMuted)?void 0:(this.player.stop(OK(this)?this.jitterBufferDelay:0),void this.log.info(`playing state updated, stop ${this.kind}`))}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${t} ${this.player.isStopped}`)}async handleAutoPlayFailed(t){var i;this.log.warn("handleAutoPlayFailed",t);const r=()=>{this.resume().then(()=>{document.removeEventListener("click",r,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((Gw||Rk)&&(await Rw(100),(i=this.player)==null?void 0:i.isPlaying))return;zIA()}else document.addEventListener("click",r,!0);Eo.once(nr.LOCAL_TRACK_CAPTURE_SUCCESS,({track:s})=>{s.kind==="audio"&&Ik()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&r()}),this.emit("error",t)}getVideoFrame(){return this.player instanceof Ip?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(t){var i,r,s;if(this.isFirstVideoFrameEmitted)return;const g=(i=this.mediaTrack)==null?void 0:i.getSettings();let B=g?.width||((r=this.player.element)==null?void 0:r.videoWidth)||0,Q=g?.height||((s=this.player.element)==null?void 0:s.videoHeight)||0;(t!==vr.RESIZE||B||Q)&&(t!==vr.LOADED_META_DATA||B||Q)&&(t!==vr.LOADED_DATA||B||Q||this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,D9(this.rotation)&&([B,Q]=[Q,B]),this.emit("first-video-frame",{width:B,height:Q,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`)}};ss([FI([],Lr.INIT,{sync:!0})],$3.prototype,"_toInitState");var dcA=Object.prototype.hasOwnProperty;function hcA(t){if(t==null)return!0;if(typeof t=="boolean")return!1;if(typeof t=="number")return t===0;if(typeof t=="string"||typeof t=="function"||Array.isArray(t))return t.length===0;if(t instanceof Error)return t.message==="";if(yw(t))switch(Object.prototype.toString.call(t)){case"[object File]":case"[object Map]":case"[object Set]":return t.size===0;case"[object Object]":for(const i in t)if(dcA.call(t,i))return!1;return!0}return!1}var Z2=hcA,pcA=async function(t){const i=mcA(t);qi.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let r=[],s=[];const g=["label","deviceId","groupId"];if(i.audio&&(r=await Ek(),qi.info(`microphones: ${up(r.map(B=>lB(cr({},B),{groupId:B.groupId.substring(0,8)})),{keysToInclude:g})}`)),i.video&&(s=await sD(),qi.info(`cameras: ${up(s,{keysToInclude:g})}`),!rD(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){const B=s.filter(Q=>!Q.label.includes("infrared")).find(Q=>Q.label.includes("facing front"));B&&(i.video.deviceId=B.deviceId,qi.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{const B=await navigator.mediaDevices.getUserMedia(i);return mX&&B.getTracks().forEach(Q=>{var f;const m=Q.getCapabilities();qi.info(`${Q.kind} capabilities: ${up(m,{keysToInclude:g9})}`),Fr(t.echoCancellation)||((f=m.echoCancellation)==null?void 0:f.indexOf(t.echoCancellation))!==-1||qi.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(m.echoCancellation)}], but received '${t.echoCancellation}'`)}),i.audio&&z2(),B}catch(B){let{message:Q}=B;throw B.name==="NotFoundError"&&(t.video&&s&&s.length===0&&(Q=j2({key:K2.CAMERA_NOT_FOUND})),t.audio&&r&&r.length===0&&(Q=j2({key:K2.MICROPHONE_NOT_FOUND}))),new Ws({code:xa.INITIALIZE_FAILED,name:B.name,message:Q,constraint:B.constraint})}},fcA=S3({retryFunction:pcA,settings:{retries:3,timeout:500},onError:({error:t,retry:i,reject:r,retryFuncArgs:s,retriedCount:g})=>{const B=g+1;t.name==="NotReadableError"||t.name==="OverconstrainedError"||t.name==="AbortError"?(B===1?(s[0].video&&(s[0].maxResolution=!1,(!IE||s[0].width*s[0].height<=2073600)&&s[0].frameRate&&(s[0].frameRate=s[0].frameRate>10?10:5)),s[0].retryWhenExactFailed&&s[0].useExactDeviceId&&(s[0].useExactDeviceId=!1)):B===2?s[0].useDeviceIdOnly=!0:B!==3||s[0].useExactDeviceId||(s[0].useTrueAsConstraint=!0),i()):r(t),s[0].microphoneId&&a8(s[0].microphoneId,!1),s[0].cameraId&&a8(s[0].cameraId,!0)},onRetrying:t=>{qi.warn(`getUserMedia NotReadableError observed, retrying [${t}/3]`)},onRetryFailed:t=>{fC.logFailedEvent({eventType:VG.GET_USER_MEDIA_RETRY,error:t})},onRetrySuccess:t=>{fC.logSuccessEvent({eventType:VG.GET_USER_MEDIA_RETRY}),fC.uploadEvent({log:`stat-${VG.GET_USER_MEDIA_RETRY}-success-${t}`})}});async function a8(t,i){const r=(i?await sD():await Ek()).find(s=>s.deviceId===t);r&&oD(r.getCapabilities)&&qi.warn(up(r.getCapabilities(),{keysToInclude:g9}))}function mcA(t){return{audio:DcA(t),video:ycA(t)}}function DcA(t){if(!t.audio)return!1;if(t.useTrueAsConstraint)return!0;const i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:t.sampleRate};return!Z2(t.microphoneId)&&(i.deviceId=t.useExactDeviceId?{exact:t.microphoneId}:t.microphoneId,t.useDeviceIdOnly)?i:(uD(t.channelCount)&&(i.channelCount=t.channelCount),(rD(t.echoCancellation)||t.echoCancellation==="remote-only"||t.echoCancellation==="all")&&(i.echoCancellation=t.echoCancellation),rD(t.noiseSuppression)&&!t.noiseSuppression&&(i.noiseSuppression=!1),rD(t.autoGainControl)&&!t.autoGainControl&&(i.autoGainControl=!1),!!Z2(i)||i)}function ycA(t){if(!t.video)return!1;if(t.useTrueAsConstraint)return!0;const{maxResolution:i=!0}=t,r={};return t.cameraId?r.deviceId=t.useExactDeviceId?{exact:t.cameraId}:t.cameraId:t.facingMode&&(r.facingMode=t.facingMode),t.useDeviceIdOnly&&!Z2(r)?r:(t.width&&(r.width={ideal:t.width},i&&!Ql&&(r.width.max=t.width)),t.height&&(r.height={ideal:t.height},i&&!Ql&&(r.height.max=t.height)),Ql&&wY&&t.width&&t.height&&t.width*t.height<101376&&(r.width=t.width,r.height=t.height),t.frameRate&&(r.frameRate=t.frameRate),!!Z2(r)||r)}var RcA=fcA;function LX(t){return TY((i,r)=>async function(...s){const g=await i.apply(this,s);return await t.call(this,...s),g})}function TY(t){return function(i,r,s){return s.value=t(s.value,r),s}}var McA=(()=>{let t=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&qi.info(`visibility change: ${document.visibilityState}`),t||(document.addEventListener("visibilitychange",()=>{qi.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),t=!0)}})(),wcA=0,ScA=class{constructor(t){OA(this,"log"),OA(this,"isRunning",!1),OA(this,"queue",[]);let i="fq"+ ++wcA;t&&(i+=`|${t}`),this.log=qi.createLogger({id:i})}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(t,i=!1){var r,s;const g=cr({},t),B=new Promise((Q,f)=>{g.resolve=Q,g.reject=f});return g.promise=B,i?this.length<=1?this.queue.push(g):(s=(r=this.lastQueueItem)==null?void 0:r.promise)==null||s.then(g.resolve,g.reject):this.queue.push(g),this.log.debug(`push ${this.length}`,t.funcName,t.args),this.isRunning||this.callNext(),B}shift(){const t=this.queue.shift();return this.log.debug(`shift ${this.length}`,t?.funcName,t?.args),t}callNext(){if(this.isRunning||this.length===0)return;const{fn:t,args:i,context:r,resolve:s,reject:g,funcName:B}=this.queue[0];this.log.debug("callNext",this.length,B,i),this.isRunning=!0,t.apply(r,i).then(s,g).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},s8=new WeakMap;function vcA(t=!1){return function(i,r,s){const g=s.value;return s.value=function(...B){const Q=s8.get(this)||new ScA;return s8.set(this,Q),Q.push({fn:g,args:B,context:this,funcName:r},t)},s}}function FX(t,i){return TY((r,s)=>function(...g){const B=t;try{const Q=r.apply(this,g),f=Ns();return C9(Q)?Q.then(m=>(i?qr.addSuccessEvent({key:B,cost:Ns()-f}):qr.addSuccessEvent({key:B}),m)).catch(m=>{throw qr.addFailedEvent({key:B,error:m}),m}):(qr.addSuccessEvent({key:B}),Q)}catch(Q){throw qr.addFailedEvent({key:B,error:Q}),Q}})}function Rg(...t){}var NcA=t=>t();function TcA(){this.dispose()}var GcA=()=>typeof __FASTRX_DEVTOOLS__<"u",kcA=1,Mw=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){const i=new bcA(t,this,this.streamId++);return js.subscribe({id:this.id,end:!1},{nodeId:i.sourceId,streamId:i.id}),this(i),i}},AW=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=Rg,this.error=Rg,this.next=Rg,this.dispose=Rg,this.subscribe=Rg,this.doDefer()}subscribe(t){return t instanceof Mw?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(NcA),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}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}},BB=class extends AW{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}},_cA=class extends AW{constructor(t,i=Rg,r=Rg,s=Rg){if(super(),this._next=i,this._error=r,this._complete=s,this.then=Rg,t instanceof Mw){const g={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{js.defer(g,0)}),js.create(g),js.pipe(g),this.sourceId=g.id,this.subscribe(t),js.subscribe({id:g.id,end:!0}),i==Rg?this._next=B=>js.next(g,0,B):this.next=B=>{js.next(g,0,B),i(B)},s==Rg?this._complete=()=>js.complete(g,0):this.complete=()=>{this.dispose(),js.complete(g,0),s()},r==Rg?this._error=B=>js.complete(g,0,B):this.error=B=>{this.dispose(),js.complete(g,0,B),r(B)}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function QC(t,...i){return i.reduce((r,s)=>s(r),t)}function dl(t,i,r){if(GcA()){const s=Object.defineProperties(Object.setPrototypeOf(t,Mw.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:r,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});js.create(s);for(let g=0;g{if(s instanceof Mw){const g=dl(B=>{const Q=new t(B,...r);Q.sourceId=g.id,Q.subscribe(s)},i,arguments);return g.source=s,js.pipe(g),g}return g=>s(new t(g,...r))}}}function ip(t,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:t,payload:i}})}var bcA=class extends BB{constructor(t,i,r){super(t),this.source=i,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{js.defer(this.source,this.id)})}next(t){js.next(this.source,this.id,t),this.sink.next(t)}complete(){js.complete(this.source,this.id),this.sink.complete()}error(t){js.complete(this.source,this.id,t),this.sink.error(t)}},js={addSource(t,i){ip("addSource",{id:t.id,name:t.toString(),source:{id:i.id,name:i.toString()}})},next(t,i,r){ip("next",{id:t.id,streamId:i,data:r&&r.toString()})},subscribe({id:t,end:i},r){ip("subscribe",{id:t,end:i,sink:{nodeId:r&&r.nodeId,streamId:r&&r.streamId}})},complete(t,i,r){ip("complete",{id:t.id,streamId:i,err:r?r.toString():null})},defer(t,i){ip("defer",{id:t.id,streamId:i})},pipe(t){ip("pipe",{name:t.toString(),id:t.id,source:{id:t.source.id,name:t.source.toString()}})},update(t){ip("update",{id:t.id,name:t.toString()})},create(t){t.id||(t.id=kcA++),ip("create",{name:t.toString(),id:t.id})}},LcA=class extends AW{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(i=>i.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(i=>i.error(t)),this.sinks.clear()}};function UX(){return t=>{const i=new LcA(t);if(t instanceof Mw){const r=dl(s=>{i.add(s)},"share",arguments);return i.sourceId=r.id,r.source=t,js.pipe(r),r}return dl(i.add.bind(i),"share",arguments)}}function OX(...t){return dl(i=>{const r=new BB(i);let s=t.length;r.complete=()=>{--s===0&&i.complete()},t.forEach(r.bindSubscribe)},"merge",arguments)}function FcA(...t){return dl(i=>{const r=new Map;t.forEach(s=>{const g=new BB(i);r.set(s,g),g.complete=()=>{r.delete(s),r.size===0?i.complete():g.dispose()},g.next=B=>{r.delete(s),r.forEach(Q=>Q.dispose()),g.resetNext(),g.resetComplete(),g.next(B)}}),t.forEach(s=>r.get(s).subscribe(s))},"race",arguments)}function UcA(...t){return i=>dl((r,s=0,g=t.length)=>{for(;s{r.next=g=>s.next(g),r.complete=()=>s.complete(),r.error=g=>s.error(g),t&&s.subscribe(t)},"subject",i));return r.next=Rg,r.complete=Rg,r.error=Rg,r}function OcA(t){return dl(i=>{let r=0;const s=setInterval(()=>i.next(r++),t);return i.defer(()=>{clearInterval(s)}),"interval"},"interval",arguments)}function xcA(t,i){return dl(r=>{let s=0;const g=setTimeout(()=>{r.removeDefer(B),r.next(s++),i||r.complete()},t),B=()=>clearTimeout(g);r.defer(B)},"timer",arguments)}function ZK(t,i){return r=>{const s=g=>r.next(g);r.defer(()=>i(s)),t(s)}}function Rc(t,i){if("on"in t&&"off"in t)return dl(ZK(r=>t.on(i,r),r=>t.off(i,r)),"fromEvent",arguments);if("addListener"in t&&"removeListener"in t)return dl(ZK(r=>t.addListener(i,r),r=>t.removeListener(i,r)),"fromEvent",arguments);if("addEventListener"in t)return dl(ZK(r=>t.addEventListener(i,r),r=>t.removeEventListener(i,r)),"fromEvent",arguments);throw"target is not a EventDispachter"}function YcA(){return dl(t=>t.complete(),"empty",arguments)}var PcA=class extends BB{constructor(t,i,r){super(t),this.filter=i,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},mw=pD(PcA,"filter"),JcA=class extends BB{constructor(t,i){super(t),this.count=i}next(t){this.sink.next(t),--this.count===0&&(this.doDefer(),this.complete())}},HcA=pD(JcA,"take"),VcA=class extends BB{constructor(t,i){super(t);const r=new BB(t);r.next=()=>{r.doDefer(),t.complete()},r.complete=TcA,r.subscribe(i)}},ww=pD(VcA,"takeUntil"),qcA=class extends BB{constructor(t,i){super(t),this.f=i}next(t){this.f(t)||(this.next=super.next,this.next(t))}},KcA=pD(qcA,"skipWhile"),jcA=class extends BB{constructor(t,i,r){super(t),this.mapper=i,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},YX=pD(jcA,"map"),WcA=class extends BB{constructor(t,i,r){super(t),this.data=i,this.context=r}next(t){const i=this.context.combineResults;i?this.sink.next(i(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},zcA=class PX extends BB{constructor(i,r,s){super(i),this.makeSource=r,this.combineResults=s,this.index=0}subInner(i,r){const s=this.currentSink=new r(this.sink,i,this);this.complete===PX.prototype.complete&&(this.complete=this.tryComplete),s.complete=s.tryComplete,s.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},g8=class extends WcA{},JX=class extends zcA{next(t){this.subInner(t,g8),this.next=i=>{this.currentSink.dispose(),this.subInner(i,g8)}}},ZcA=pD(JX,"switchMap");function XcA(t){return(i,r)=>t(()=>i,r)}var HX=XcA(pD(JX,"switchMapTo")),dD=(t=Rg,i=Rg,r=Rg)=>s=>new _cA(s,t,i,r),VX=(t=>(t[t.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",t[t.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",t))(VX||{}),AD=class extends $3{constructor(t,i){super({mediaType:t,PlayerClass:i}),OA(this,"isRemote",!1),OA(this,"deviceId"),OA(this,"groupId",""),OA(this,"label",""),OA(this,"sourceTrack"),OA(this,"enableAutoSwitchWhenRecapturing",!0),OA(this,"_isRecapturing",!1),OA(this,"_lastRecaptureTime",0),OA(this,"_onMuteTimeoutId",-1),OA(this,"_encodeCheckTimeoutId",-1),OA(this,"recaptureMode",0),OA(this,"profile"),OA(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,i){throw new Error("Method not implemented.")}installTrackEvent(t){t.addEventListener(gt.MUTE,this.onTrackMuted),t.addEventListener(gt.UNMUTE,this.onTrackUnmuted),t.addEventListener(gt.ENDED,this.onTrackEnded),t.muted&&this.onTrackMuted(),t.readyState===gt.ENDED&&this.onTrackEnded()}uninstallTrackEvent(t){t.removeEventListener(gt.MUTE,this.onTrackMuted),t.removeEventListener(gt.UNMUTE,this.onTrackUnmuted),t.removeEventListener(gt.ENDED,this.onTrackEnded)}setStateToReady(){}async capture(t,i=!1){var r,s;const g=this.sourceTrack;try{const B=Ns();let Q;Eo.emit(nr.LOCAL_TRACK_CAPTURE_START,{track:this}),t.customSource?(Q=new MediaStream,Q.addTrack(t.customSource)):(i||(r=this.sourceTrack)==null||r.stop(),Q=await RcA(t));const f=Q.getTracks()[0];return await this.setInputMediaStreamTrack(f),t.customSource||(this.sourceTrack=f,this.updateDeviceIdInUse(),this.listenDeviceChange()),Eo.emit(nr.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Ns()-B,profile:this.profile,room:(s=this.manager)==null?void 0:s.room}),Q}catch(B){throw Eo.emit(nr.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:B}),this.log.error(`getUserMedia error observed ${B}`),B}finally{i&&g?.stop()}}setOutputMediaStreamTrack(t){var i;if(super.setOutputMediaStreamTrack(t),this.setStateToReady(),this.isPublishing||this.isPublished)return(i=this.room)==null?void 0:i.replaceTrack(this)}get hasFlag(){var t,i;const r=u9(((t=this.room)==null?void 0:t.localPublishFlag)||0,((i=this.room)==null?void 0:i.userId)||"");return this.mediaType===4&&r.hasVideo||this.mediaType===1&&r.hasAudio||this.mediaType===2&&r.hasAuxiliary}async publish(t,i){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()),await i,this._checkPublishFlag(t)}_checkPublishFlag(t){return new Promise(async(i,r)=>{var s,g,B,Q,f;const m=()=>r(new Ws({code:xa.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?i():(this.state!==Lr.INIT&&this.state!=="ready"||m(),QC(Rc(t,"local-publish-flag-changed"),mw(()=>this.hasFlag),ww(OX(Rc(this,Lr.INIT),Rc(this,"ready"))),dD(i,r,m))),(B=(g=(s=this.room)==null?void 0:s.networkQuality)==null?void 0:g.hadRecentBadUplink)==null?void 0:B.call(g,2))return i();const M=t.heartbeatCount,v=((f=(Q=this.mediaTrack)==null?void 0:Q.stats)==null?void 0:f.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(async()=>{var U,AA,z,sA,eA,X,QA,wA;if((z=(AA=(U=this.room)==null?void 0:U.networkQuality)==null?void 0:AA.hadRecentBadUplink)!=null&&z.call(AA,2)||t.heartbeatCount-M<3)return i();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((sA=this.mediaTrack)!=null&&sA.stats){const ue=this.mediaTrack.stats.totalFrames||0;ue-v===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",ue)}const HA=this.kind===gt.AUDIO,VA=this.stat.bytesSent>0;if(qr[VA?"addSuccessEvent":"addFailedEvent"]({key:HA?503700:513702}),!HA){const ue={H264:513704,H265:513705,VP8:513706}[((X=(eA=this.room)==null?void 0:eA.videoCodec)==null?void 0:X.toUpperCase())||"H264"];ue&&qr[VA?"addSuccessEvent":"addFailedEvent"]({key:ue})}if(!VA){if(qr.addEnum({key:HA?503701:513703,value:Y3()}),fC.uploadEvent({log:`stat-encode-failed-${this.kind}-${eX()||iX()}`,userId:this.userId}),this.log.warn(HA?"encode failed":`${(wA=(QA=this.room)==null?void 0:QA.videoCodec)==null?void 0:wA.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),await this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(await Rw(5e3),this.stat.bytesSent>0||this.hasFlag)))return i();this.emit("6",this),r(new Ws({message:`${this.strMediaType} encode failed`,code:HA?xa.AUDIO_ENCODE_FAILED:xa.VIDEO_ENCODE_FAILED}))}}},1e4)})}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),Eo.emit(nr.LOCAL_TRACK_UNPUBLISHED,{track:this})}async updateDeviceIdInUse(){if(this.sourceTrack&&W2){const{deviceId:t,groupId:i}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;await CcA({newDeviceId:t,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind})||(this.deviceId=t,this.label=r,i&&(this.groupId=i),Yj().then(s=>{const g=s.find(B=>{let Q=B.deviceId===t;return i&&(Q=Q&&B.groupId===i),Q});g&&this.emit("2",g)}))}}setProfile(t){this.log.info("setProfile",t),Object.assign(this.profile,t)}isNeedToRecapture(t=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===gt.AUDIO&&!EcA(this.sourceTrack)||this.kind===gt.VIDEO&&!ccA(this.sourceTrack)||this._isRecapturing||t&&wY&&IE)}onTrackMuted(){super.onTrackMuted(),McA(),this.isNeedToRecapture(!0)&&(Date.now()-this._lastRecaptureTimethis.onTrackMuted(),o2):this._onMuteTimeoutId=setTimeout(async()=>{var t;if((t=this.sourceTrack)!=null&&t.muted){if((UI||hl)&&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(),o2);this.emit("7"),this.recapture(await this.getRecoverCaptureDeviceId())}}async recapture(t,i=!1){var r;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");const s=this.sourceTrack;i||(r=this.sourceTrack)==null||r.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();const g={useExactDeviceId:!0};if(t==="user"||t==="environment")g.facingMode=t;else{let B;(this.kind==="audio"?await Ek():await sD()).find(Q=>Q.deviceId===t)&&(B=t),g.deviceId=B}return this.capture(g,i).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),Eo.emit(nr.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(B=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${B.message}`),this.emit("5",B),Eo.emit(nr.LOCAL_TRACK_RECAPTURE,{track:this,error:B})}).finally(()=>{i&&s?.stop()})}async getRecoverCaptureDeviceId(){const t=this instanceof GY;if(t&&this.facingMode)return this.facingMode;let{deviceId:i}=this;if(i){const r=(vG.get(i)||0)+1;if(vG.set(i,r),r>=3&&this.enableAutoSwitchWhenRecapturing){const s=t?(await sD()).find(g=>!vG.has(g.deviceId)):(await Ek()).find(g=>!vG.has(g.deviceId));s&&(this.log.warn(`${i} capture fail ${r} times, change new ${s.deviceId}`),i=s.deviceId)}}return i}stopCapture(){var t;this.sourceTrack&&(this.sourceTrack.stop(),Eo.emit(nr.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()}};ss([FI(Lr.INIT,"ready",{ignoreError:!0,sync:!0})],AD.prototype,"setStateToReady"),ss([vcA()],AD.prototype,"capture"),ss([FI("ready","publish",{ignoreError:!0,success(){Eo.emit(nr.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(t){var i;(i=this.room)==null||i.localTracks.delete(this);let r="error";const s=t instanceof Ws?t:t.cause instanceof Ws?t.cause:t;let g=!1;s instanceof Ws&&(s.message.includes("timeout")?r="timeout":s.code===xa.API_CALL_ABORTED&&(g=!0,r="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:r,error:s}),this.log[g?"info":"error"]("publish failed",s)}}),FX(521714,!1)],AD.prototype,"publish"),ss([TY(t=>async function(){const i=this.state==="publish"?"started":"starting";t.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)}),FI([],"ready",{sync:!0})],AD.prototype,"unpublish");var vG=new Map;Eo.on(nr.SWITCH_DEVICE_SUCCESS,t=>{t.track.deviceId&&vG.delete(t.track.deviceId)});var $cA=class{constructor(t,i=!1){this.dataView=t,this.isSEI&&(i?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){const{seiPayloadStartIndex:t}=this,i=this.dataView.byteLength-2,r=[];let s=0;for(let B=t;B<=i;B++){const Q=this.dataView.getInt8(B);switch(Q){case 0:case 1:case 2:case 3:s===2&&(r.push(3),s=0),Q===0?s+=1:s=0,r.push(Q);break;default:s=0,r.push(Q)}}r.push(this.dataView.getInt8(this.dataView.byteLength-1));const g=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=g}removePreventionByte(){const{seiPayloadStartIndex:t}=this,i=this.dataView.byteLength-1,r=[];let s=0;for(let B=t;B<=i;B++)switch(this.dataView.getInt8(B)){case 0:s++,r.push(this.dataView.getInt8(B));break;case 3:s!==2&&r.push(this.dataView.getInt8(B)),s=0;break;default:r.push(this.dataView.getInt8(B)),s=0}const g=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=g}get seiPayloadStartIndex(){let t=6;for(let i=6;i=this.dataView.byteLength?0:31&this.dataView.getUint8(t)}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}},AEA=class{constructor(){OA(this,"_seiMessageList",[]),OA(this,"_smallSeiMessageList",[]),OA(this,"_seiPayloadType",243)}encodeSEINalu(t){const i=t.byteLength,r=parseInt(String(i/255),10),s=i%255,g=[];g.push(0,0,0,1,6,this._seiPayloadType);for(let Q=0;Q0&&t.data.byteLength>0){const s=9-this.getNaluCount(t.data);if(s<=0)return 0;const g=r.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),B=g.reduce((v,U)=>v+U.dataView.byteLength,0),Q=new ArrayBuffer(B+t.data.byteLength),f=new DataView(Q),m=new DataView(t.data);let M=0;for(let v=0;v{var s;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{const g=Y2(((s=this.room)==null?void 0:s.sdkAppId)||0)?m5:f5;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${g}`),this.setProfile(lB(cr({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(W2&&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)}async setMute(t){var i,r,s;if(pC(t)){if(this.muteImage===t)return;await((i=this.manager)==null?void 0:i.deleteWatermark("mute")),await((r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:t,fillVideo:!0})),this.muteImage=t,super.setMute(!1)}else this.muteImage&&(await((s=this.manager)==null?void 0:s.deleteWatermark("mute")),this.muteImage=void 0),super.setMute(t)}async capture({deviceId:t,facingMode:i,useExactDeviceId:r=!0,customSource:s,retryWhenExactFailed:g=!0}){const B={audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:g,customSource:s};if(B.facingMode==="environment"){const Q=await this.getDeviceIdWhenUsingBackCamera();Q&&(B.cameraId=Q)}return super.capture(B)}setProfile(t){var i;const r=this.fallbackProfile(t);if(r.bitrate&&(this.isNeedToSetBandwidth=r.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(r);else{const s=Y2(((i=this.room)==null?void 0:i.sdkAppId)||0)?m5:f5;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${s}`),super.setProfile(lB(cr({},this.profile),{width:1920,height:1080}))}}async applyProfile(){var t,i;if(!this.mediaTrack)return;const{width:r=0,height:s=0}=(this.sourceTrack||this.mediaTrack).getSettings(),g=r*s,B=this.settings,Q=B.height!==this.profile.height||B.width!==this.profile.width||B.frameRate!==this.profile.frameRate;if(Q&&(QD===16&&this.deviceId?await this.recapture(this.deviceId):(w3(this.outMediaTrack)?await((t=this.outMediaTrack)==null?void 0:t.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:f=0,height:m=0}=(this.sourceTrack||this.mediaTrack).getSettings(),M=f*m;return Q&&M&&g&&M===g?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:gt.VIDEO,videoType:gt.BIG})}}get settings(){const t={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},i=this.sourceTrack||this.mediaTrack;return W2&&i&&Object.assign(t,i.getSettings()),t}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:m9(this.settings,this.profile)}isAllowed2k4k(t){var i;return!this.room||!this.room.scheduleResult||!!this.isScreen||t.height*t.width<3686400||((i=this.room.scheduleResult.trtcAutoConf)==null?void 0:i["2k4k"])===1}isNeedToSwitchDevice(t){return!(!this.mediaTrack||this.deviceId===t||this.facingMode===t)}async switchDevice(t){try{if(!this.isNeedToSwitchDevice(t)&&!this.isUseCustomSource)return;const i={useExactDeviceId:!0,retryWhenExactFailed:!1};t==="user"||t==="environment"?i.facingMode=t:i.deviceId=t,this.sourceTrack&&this.sourceTrack.stop(),await this.capture(i),Eo.emit(nr.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 t;try{if(q9&&!O3&&DX){const i=(await sD(!0)).map(s=>{var g;return lB(cr({},s),{capabilities:(g=s.getCapabilities)==null?void 0:g.call(s)})}).filter(s=>{var g,B;return(B=(g=s.capabilities)==null?void 0:g.facingMode)==null?void 0:B.includes("environment")});let r=i[0];i.forEach(s=>{var g,B,Q,f;const{capabilities:m}=s;((g=m.width)!=null&&g.max&&((B=m.height)!=null&&B.max)?m.width.max*m.height.max:0)>((Q=r.capabilities.width)!=null&&Q.max&&((f=r.capabilities.height)!=null&&f.max)?r.capabilities.width.max*r.capabilities.height.max:0)&&(r=s)}),r?.capabilities&&(this._log.info("use max resolution back camera",r),t=r.deviceId)}}catch(i){this._log.warn("get max res camera failed",i)}return t}async updateSmallConfig(t){var i,r;this._log.info(`update small stream config: ${JSON.stringify(t)}`);const s=!this.small;this.small=this.fallbackProfile(t,!0),await((i=this.manager)==null?void 0:i.update()),s&&await((r=this.room)==null?void 0:r.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(t,i=!1){const r=t.width>t.height,s=cr({},t);return t.width*t.height<=19200&&hl&&pp&&(this.log.warn(`${i?"small ":""}resolution is ${t.width}*${t.height}, fallback to 240*180 for android chrome`),s.width=r?240:180,s.height=r?180:240,s.bitrate=Math.max(t.bitrate,150)),t.width*t.height>921600&&qgA&&(s.width=r?1280:720,s.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),HgA(_u,"14.3")&&AX(_u,"14.0",!0)&&this.on("7",()=>{const g=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=g?640:480,this.profile.height=g?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=g?640:360,this.profile.height=g?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!i&&this.avoidCropping&&(pp||Ql)&&!WgA()&&t.width*t.height<=230400&&t.width/t.height===16/9&&(this._scaleResolutionDownBy=1280/t.width,s.width=1280,s.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),s}stopSmall(){var t,i;this.small&&(delete this.small,(t=this.manager)==null||t.update(),(i=this.room)==null||i.enableSmall(!1))}listenDeviceChange(){Tu&&!Tu.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Tu.on("videoInputRemoved",this.handleCameraRemoved,this)}async handleCameraRemoved(t){if(t.deviceId===this.deviceId){let i=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${VX[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(t)}`),this.recaptureMode===0){ns(this.userId,{eventId:2003,param1:7,streamType:2});const r=await sD();r[0]?this.recapture(r[0].deviceId):i=!0}i&&Tu.on("videoInputAdded",this.handleCameraAdded,this)}}async handleCameraAdded(t){this.recaptureMode===1&&t.deviceId!==this.deviceId||(Tu.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(t)}`),this.recapture(t.deviceId))}encodeFrame(t,i){if(!this.manager)return t;const r=i?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,g)=>g?g({frame:s,mediaType:r}):s,t)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(t=>t)}play(t,i){return Fr(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(t,i)}close(){Tu.off("videoInputAdded",this.handleCameraAdded,this),Tu.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}async recapture(t){try{await super.recapture(t)}catch(i){const r=(await sD()).find(s=>s.deviceId!==t);if(!r)throw i;await super.recapture(r.deviceId)}}setContentHint(t){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==t&&(this.log.info(`setContentHint ${t}`),this.mediaTrack.contentHint=t),this.outMediaTrack&&this.outMediaTrack.contentHint!==t&&(this.outMediaTrack.contentHint=t))}setRotation(t){this.manager&&(this.isScreen||Fr(t)||t!==this.rotation&&(this.rotation=t,this.manager.rotation=t))}};ss([LX(function(t){this.setContentHint(t.contentHint||"motion")})],GY.prototype,"capture");var eEA=[-1,-1,1,-1,-1,1,1,1],tEA=[0,0,1,0,0,1,1,1],NG=class Pj extends Lr{constructor(i,r){if(super(),this.context=i,OA(this,"name"),OA(this,"input"),OA(this,"output"),OA(this,"texture"),OA(this,"ctx2d",null),OA(this,"fbo"),OA(this,"width",0),OA(this,"height",0),OA(this,"x",0),OA(this,"y",0),OA(this,"program"),OA(this,"vertexShader"),OA(this,"fragmentShader"),OA(this,"totalFrames",0),OA(this,"dropFrames",0),OA(this,"matchInputSize",!0),OA(this,"texCoordBuffer"),OA(this,"positionBuffer"),OA(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),OA(this,"cost",0),OA(this,"_canvas",null),OA(this,"_image"),OA(this,"log"),this.context.on("disconnect",this.close,this),this.name=r.name,this.log=r.logger,this.matchInputSize=r.matchInputSize!==!1,this.width=r.width||i.width,this.height=r.height||i.height,this._image=r.image,i instanceof Ck)i.ctx&&r.create2d&&(typeof OffscreenCanvas=="function"&&QD!==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 s=i.ctx;this.texCoordBuffer=this.createBuffer(tEA),this.positionBuffer=this.createBuffer(eEA),r.createTexture!==!1&&(this.texture=s.createTexture(),this.useTexture(),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.pixelStorei(s.UNPACK_ALIGNMENT,1)),r.useFbo&&(this.fbo=s.createFramebuffer(),this.useBufferFrame(),this.useTexture(),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this.width,this.height,0,s.RGBA,s.UNSIGNED_BYTE,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,this.texture,0)),r.useDefaultProgram?this.program=i.defaultProgam:(r.vertexShaderSource||r.fragmentShaderSource)&&(this.vertexShader=r.vertexShaderSource?i.createShader(s.VERTEX_SHADER,r.vertexShaderSource):i.defaultVShader,this.fragmentShader=r.fragmentShaderSource?i.createShader(s.FRAGMENT_SHADER,r.fragmentShaderSource):i.defaultFShader,this.program=i.createProgram(this.vertexShader,this.fragmentShader))}catch(s){this.context.destroy(new Ws({code:xa.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${s.message||s}`}))}}get image(){return this._image}set image(i){this._image=i}createFramebuffer(i){const r=this.context.ctx,s=r.createFramebuffer();return r.bindFramebuffer(r.FRAMEBUFFER,s),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,i,0),s}connect(i,...r){return i.addInput(this,...r),this.output=i,i}addInput(i,...r){this.input=i,this.matchInputSize&&i.width&&i.height&&this.resize(i.width,i.height)}requestFrame(i){const r=Date.now();return!!(this.context instanceof Jj&&this.render(i)||this.context instanceof Ck&&this.render2d(i))&&(this.totalFrames++,this.cost=Date.now()-r,!0)}render2d(i){var r;return!!((r=this.input)!=null&&r.requestFrame(i))&&this.draw2d(this.input.image,0,0,this.width,this.height)}update(i=0){var r;(r=this.output)==null||r.update(i)}disconnect(...i){var r;(r=this.output)==null||r.removeInput(this,...i),delete this.output}removeInput(i,...r){delete this.input}close(){var i,r;if(this.context.off("disconnect",this.close,this),(i=this.output)==null||i.removeInput(this),delete this.output,(r=this.input)==null||r.disconnect(),this.context instanceof Jj){const s=this.context.ctx;s.deleteBuffer(this.texCoordBuffer),s.deleteBuffer(this.positionBuffer),this.fbo&&s.deleteFramebuffer(this.fbo),this.texture&&s.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&s.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&s.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&s.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 r=this.context.ctx;i.forEach((s,g)=>{s&&(r.activeTexture(r.TEXTURE0+g),r.bindTexture(r.TEXTURE_2D,s))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){const i=this.context.ctx;i.bindFramebuffer(i.FRAMEBUFFER,this.fbo||null)}createBuffer(i){const r=this.context.ctx,s=r.createBuffer();return r.bindBuffer(r.ARRAY_BUFFER,s),r.bufferData(r.ARRAY_BUFFER,new Float32Array(i),r.STATIC_DRAW),s}setTexBuffer(i){const r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.texCoordBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(i),r.STATIC_DRAW)}setPosBuffer(i){const r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.positionBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(i),r.STATIC_DRAW)}changeBufferData(i,r){const s=this.context.ctx;s.bindBuffer(s.ARRAY_BUFFER,i),s.bufferData(s.ARRAY_BUFFER,new Float32Array(r),s.STATIC_DRAW)}setAttributes(...i){const r=this.context.ctx;i.forEach((s,g)=>{r.enableVertexAttribArray(g),r.bindBuffer(r.ARRAY_BUFFER,s),r.vertexAttribPointer(g,2,r.FLOAT,!1,0,0)})}getVertexPoint(i,r){return[i/this.width*2-1,r/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,r){if(this.width!==i||this.height!==r){if(this.width=i,this.height=r,this._canvas&&(this._canvas.width=i,this._canvas.height=r),this.texture&&this.fbo){this.useTexture();const s=this.context.ctx;s.texImage2D(s.TEXTURE_2D,0,s.RGBA,i,r,0,s.RGBA,s.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(i,r)}}draw(i,r){this.setAttributes(i||this.positionBuffer,r||this.texCoordBuffer);const s=this.context.ctx;s.drawArrays(s.TRIANGLE_STRIP,0,4)}draw2d(i,r,s,g,B,Q,f,m,M){const v=!(Fr(Q)||Fr(f)||Fr(m)||Fr(M));return!(!this.ctx2d||!i)&&(i instanceof ImageData?(v?this.ctx2d.putImageData(i,r,s,Q,f,m,M):this.ctx2d.putImageData(i,r,s),this.emit(Pj.RENDER,this.ctx2d.canvas)):(v?this.ctx2d.drawImage(i,Q,f,m,M,r,s,g,B):this.ctx2d.drawImage(i,r,s,g,B),this.emit(Pj.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:r,x:s,y:g,width:B,height:Q,name:f,cost:m}=this,M=Date.now(),v=(r-this.lastInfo.totalFrames)/((M-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:r,x:s,y:g,width:B,height:Q,timestamp:M,fps:v,name:f,cost:m},cr({parent:(i=this.input)==null?void 0:i.getInfo()},this.lastInfo)}createTexture(i){const r=this.context.ctx,s=r.createTexture();return this.useTextures(s),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,i),s}};OA(NG,"RENDER","render"),ss([FI(Lr.INIT,"connected",{sync:!0})],NG.prototype,"connect"),ss([FI("connected",Lr.INIT,{ignoreError:!0,sync:!0})],NG.prototype,"disconnect"),ss([FI([],"closed",{sync:!0})],NG.prototype,"close");var X2=NG,iEA=QC(OcA(250),YX(()=>performance.now()),UX()),oEA=t=>i=>{const r=performance.now();QC(iEA,KcA(s=>s-r{if(t!==this.context.frameRate&&(ku.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Jj){const i=this.context.ctx.getError();i&&this.context.destroy(new Ws({code:xa.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${i}`}))}},{fps:this.context.frameRate})}render(t){var i;return!!((i=this.input)!=null&&i.requestFrame(t))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(X2.RENDER,this.context._canvas),!0)}addInput(t,...i){super.addInput(t,...i),this.start(this.context.frameRate)}update(t=0){this.state!=="closed"&&(this._intervalId&&(ku.clearTask(this._intervalId),this._intervalId=0,t===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(t){super.removeInput(t),ku.clearTask(this._intervalId)}resize(t,i){super.resize(t,i),this.context.setSize(t,i)}close(){super.close(),ku.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},aEA=class extends nEA{constructor(t,i){super(t,i),OA(this,"_videoTrack"),OA(this,"_muteOb"),OA(this,"_closedOb",Rc(this,"closed")),OA(this,"_subscription"),OA(this,"_canvasContainer"),Number(Mk)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=t.canvas.captureStream().getVideoTracks(),this._muteOb=Rc(this._videoTrack,"mute"),QC(Rc(this._videoTrack,"ended"),ww(this._closedOb),dD(()=>{this.context.destroy(new Ws({code:xa.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=QC(this._muteOb,ww(this._closedOb),HX(oEA(5e3)),mw(()=>{var t;return!!((t=this._videoTrack)!=null&&t.muted)&&!document.hidden}),dD(()=>{this.context.destroy(new Ws({code:xa.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var t;(t=this._subscription)==null||t.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(t){return this.putCanvasIntoDom(),super.render(t)}render2d(t){return this.putCanvasIntoDom(),super.render2d(t)}close(){var t,i;super.close(),(t=this._videoTrack)==null||t.stop(),delete this._videoTrack,(i=this._canvasContainer)==null||i.remove()}},qX=class extends X2{constructor(t,i){super(t,cr({name:"imageSource"},i)),OA(this,"_lastImage"),OA(this,"_totalFrames",0),OA(this,"_autoResize",!1),OA(this,"_canvasRendered"),OA(this,"videoCallbackId",0),OA(this,"waitingFirstFrame",!0),OA(this,"shouldUpdate",!0),this._autoResize=i?.autoResize!==!1,QD===16&&(this._canvasRendered=xX(),QC(this._canvasRendered,UcA(this._image),ZcA(r=>r instanceof HTMLCanvasElement?Rc(r,"rendered"):YcA()),ww(Rc(this,"closed")),dD(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;const t=this.image;this.videoCallbackId&&t.cancelVideoFrameCallback(this.videoCallbackId),j3()&&!document.hidden&&(this.videoCallbackId=t.requestVideoFrameCallback((i,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(t,i){var r;let{width:s,height:g}=this;const{image:B}=this;if(B instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:s,videoHeight:g}=B,!s||!g)return!1;B.width=s,B.height=g}else if(B instanceof HTMLImageElement||B instanceof ImageData||B instanceof ImageBitmap){if({width:s,height:g}=B,B!==this._lastImage)this._lastImage=B;else if(s===this.width&&g===this.height)return!0}else B instanceof HTMLCanvasElement||B instanceof OffscreenCanvas?({width:s,height:g}=B,this._lastImage=B):typeof VideoFrame<"u"&&B instanceof VideoFrame&&({displayWidth:s,displayHeight:g}=B,(r=this._lastImage)==null||r.close(),this._lastImage=B);if(!this._autoResize)return!0;if(this.width===s&&this.height===g&&this.totalFrames){if(i){this.useTexture();const Q=this.context.ctx;Q.texSubImage2D(Q.TEXTURE_2D,0,0,0,Q.RGBA,Q.UNSIGNED_BYTE,B)}}else{if(i){this.useTexture();const Q=this.context.ctx;Q.texImage2D(Q.TEXTURE_2D,0,Q.RGBA,Q.RGBA,Q.UNSIGNED_BYTE,B)}this.resize(s,g)}return!0}get image(){return this._image}set image(t){var i;(i=this._canvasRendered)==null||i.next(t),this._image=t}render(t){return this._render(t,!0)}render2d(t){return this._render(t,!1)}},KX=class extends qX{constructor(t,i,r){super(t,r),this._player=i,this.name="videoPlayerSource",QC(Rc(this._player,vr.PLAYER_STATE_CHANGED),ww(Rc(this,"closed")),mw(({state:s})=>s==="PLAYING"),dD(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},sEA=class extends KX{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(t,i,r){super(t,new Ip({id:r.name,track:i,muted:!0,container:null,objectFit:"contain",log:r.logger}),r),this.name="videoTrackSource",this._player.play()}replaceTrack(t){this.waitingFirstFrame=!0,this._player.setTrack(t),this._player.play()}close(){super.close(),this._player.stop()}},gEA=class extends X2{constructor(t,i,r){super(t,lB(cr({name:"textSource"},r),{create2d:!0})),OA(this,"hasChange",!0),OA(this,"content",""),this.ctx2d.textBaseline="top",this.content=i.content||"",i.font&&(this.font=i.font),i.color&&(this.color=i.color)}set font(t){this.ctx2d&&(this.ctx2d.font=t,this.hasChange=!0)}get font(){var t;return((t=this.ctx2d)==null?void 0:t.font)||""}set color(t){this.ctx2d&&(this.ctx2d.fillStyle=t,this.hasChange=!0)}get color(){var t;return((t=this.ctx2d)==null?void 0:t.fillStyle)||""}render2d(t){return!(!this.ctx2d||!this.hasChange)&&(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0)}render(t){return!1}resize(t,i){if(!this.ctx2d)return;const{color:r,font:s}=this;super.resize(t,i),this.color=r,this.font=s}drawMultilineText(t=0,i=0,r=1.2){if(!this.ctx2d)return;const s=this.ctx2d.measureText(this.content);i+=s.fontBoundingBoxAscent||s.actualBoundingBoxAscent||0;const g=this.font.match(/(\d+)px/),B=(g?parseInt(g[1],10):16)*r,Q=this.content.split(` -`);for(let f=0;f":"Detail >",s.onclick=this.onCollapseClick.bind(this);const g=t.content.firstChild,B=g.querySelector(`.${l2}`);return B.appendChild(s),B.appendChild(r),B.appendChild(i),g}addDiaLog(){uk()||(Vj=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${pG}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",qi.info("show autoplay dialog"),fC.uploadEvent({log:tcA}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Vj=!1),Qk=null}onConfirm(){qi.warn("confirm clicked, try resume stream"),Eo.emit(nr.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){const t=this._dialogNode.querySelector(`.${t8}`);t.style.visibility=this._showDetail?"hidden":"visible",t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||fC.uploadEvent({log:icA}),this._isCollapseClicked=!0}onQuestionClick(){window.open(PX,"_blank"),this._isQuestionClicked||fC.uploadEvent({log:ocA}),this._isQuestionClicked=!0}},Qk=null;function acA(){Qk||(Qk=new ncA)}function scA(){Qk&&Qk.deleteDialog()}var tk,lp=class extends Xm{constructor(t){super(t,gt.VIDEO),OA(this,"stat",{}),OA(this,"_calculateTimeout",-1),OA(this,"viewMirror",!1),OA(this,"objectFit","cover"),OA(this,"container"),OA(this,"canvas"),OA(this,"shouldRenderAlpha",!1),OA(this,"_preSize",{width:0,height:0}),OA(this,"posterImg"),OA(this,"pipWindow"),OA(this,"enterPIPPromise"),OA(this,"_originContainerPosition"),OA(this,"_isResettingSrcObject",!1),OA(this,"_wrapper",null),OA(this,"_useWrapper",!1),OA(this,"_isFirstFrameRenderEmitted",!1),this.mode=t.canvas?1:0,this.container=t.container,this.canvas=t.canvas,Fr(t.viewMirror)||(this.viewMirror=t.viewMirror),Fr(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(){const t=document.createElement(gt.VIDEO);this.track&&this.mode!==2&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id",`video_${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,hl&&(t.poster="data:,"),this._appendToWrapper(),this.bindElementEvents(),this.calculateStat(),this._bindFirstFrameRenderEvent(t)}_bindFirstFrameRenderEvent(t){const i=()=>{if(this._isFirstFrameRenderEmitted)return;this._isFirstFrameRenderEmitted=!0;const r=t.videoWidth||0,s=t.videoHeight||0;this._log.info(`first frame render: ${r}x${s}`),this.emit(vr.FIRST_FRAME_RENDER,{width:r,height:s})};typeof t.requestVideoFrameCallback=="function"?t.requestVideoFrameCallback(i):t.addEventListener("loadeddata",i,{once:!0})}get styleAttribute(){let t=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&&(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){const i=this._getOrCreateWrapper();i.insertBefore(this.elementToRender,i.firstChild)}else this.container.appendChild(this.elementToRender),this._cleanupWrapper()}setContainer(t){if(this.container===t)return;const i=this._wrapper,r=this.container;this.container=t,this._pausedRetryCount=aw,this.track&&this.elementToRender&&this._appendToWrapper(),i&&r&&r!==this.container&&i.isConnected&&i.children.length===0&&i.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){const i=t??this.elementToRender;if(this.container&&i)if(this._useWrapper){const r=this._getOrCreateWrapper();r.insertBefore(i,r.firstChild)}else this.container.appendChild(i)}bindElementEvents(){const t=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),this.handleFullscreenChange=this.handleFullscreenChange.bind(this),this.handleVolumeChange=this.handleVolumeChange.bind(this),t&&t.add(gt.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(gt.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(gt.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener(gt.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 i;return t.type===gt.MUTE&&((i=this.stat)!=null&&i.fps&&(this.stat.fps=0),this.isFullscreen()&&this.resetSrcObjectToReplay()),super.handleTrackEvent(t)}handleFullscreenChange(){this.isFullscreen()?(this._log.info("enter fullscreen"),this.emit(vr.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(vr.LEAVE_FULL_SCREEN))}handleVolumeChange(){var t;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(vr.VOLUME_CHANGE,{muted:(t=this.element)==null?void 0:t.muted})}handleElementEvent(t){var i,r,s,g,B,Q;if(this.mode===2)return;super.handleElementEvent(t);const f=t.type,m=this.isPictureInPicture(),M=this.isFullscreen(),v=t.isTrusted&&(m&&cE||M);if(f===gt.PLAYING&&v&&!this._isResettingSrcObject&&(this._log.warn("user resume in "+(M?"fullscreen":"pip")),this.emit(vr.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),f===gt.PAUSE&&(v&&(this._log.warn("user pause in "+(M?"fullscreen":"pip")),this.emit(vr.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}`),vw(500).then(()=>{var U;(U=this.container)!=null&&U.isConnected&&(this._pausedRetryCount=aw,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!uk()&&!this.isPausedByUserCall&&!v&&(this._log.info(`[${aw-this._pausedRetryCount+1}/${aw}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),UI&&!v&&(this._interval=Lu.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 U=this.element.style.transform;f===gt.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=U.replace("scaleX(-1)",""):f!==gt.LEAVE_PICTURE_IN_PICTURE||U.includes("scaleX")||(this.element.style.transform=`${U} scaleX(-1)`)}f===gt.RESIZE&&(this._preSize.height===((i=this.element)==null?void 0:i.videoHeight)&&this._preSize.width===((r=this.element)==null?void 0:r.videoWidth)||(this._log.info(`video size changed to ${(s=this.element)==null?void 0:s.videoWidth}x${(g=this.element)==null?void 0:g.videoHeight}`),this._preSize.height=((B=this.element)==null?void 0:B.videoHeight)||0,this._preSize.width=((Q=this.element)==null?void 0:Q.videoWidth)||0,this.emit(vr.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))),f===gt.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(vr.LEAVE_PICTURE_IN_PICTURE)),f===gt.ENTER_PICTURE_IN_PICTURE&&this.emit(vr.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){hl&&KK&&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,i=1){var r,s;this.canvas!==t&&((r=this.canvas)==null||r.remove(),t?.setAttribute("style",this.styleAttribute),this.canvas=t,this.mode=t?i:0,this.mode===2&&this.setTrack(t.captureStream().getVideoTracks()[0]),t?((s=this.element)==null||s.remove(),this._appendToWrapper(t)):this.element&&this._appendToWrapper(this.element))}setAttr(t){const i=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},t);i.style=Object.assign({width:"100%",height:"100%"},i.style),super.setAttr(i)}get mirror(){return this.viewMirror}setRect(t,i){this.elementToRender&&(this.elementToRender.style.width=`${t}px`,this.elementToRender.style.height=`${i}px`)}setViewMirror(t){this.elementToRender&&(this.elementToRender.style.transform=t?"scaleX(-1)":""),this.viewMirror=t}setObjectFit(t){this.elementToRender&&(this.elementToRender.style.objectFit=`${t}`),this.objectFit=t}setPoster(t,i=!1){return new Promise(r=>{if(!this.element||(this._log.info("setPoster",t.slice(0,10)),t===""?this.element.removeAttribute("poster"):this.element.poster=t,!(i&&(cE||Ql))))return r();if(t==="")return this.removePosterImg(),r();if(this.posterImg)return r();const s=document.createElement("img");s.src=t;const g=window.getComputedStyle(this.element),B=g.objectFit||this.objectFit;let Q=1;if(this._useWrapper){const f=parseInt(g.zIndex,10);isNaN(f)||(Q=f+1)}s.style.cssText=this._useWrapper?`grid-area:1/1;z-index:${Q};width:100%;height:100%;object-fit:${B};`:`position:absolute;top:0;left:0;width:100%;height:100%;object-fit:${B};`,s.onload=async()=>{try{s.decode&&await s.decode(),this.container&&!this._useWrapper&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=s;const f=this._useWrapper?this._wrapper:this.container;f?.appendChild(s),W2()&&pD<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(f){this._log.warn("decode poster image error",f)}return r()},s.onerror=()=>(this._log.warn("load poster image error"),r())})}removePosterImg(){this.posterImg&&(W2()&&pD<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),this._useWrapper||!this.container||Fr(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"))}async pause(t=!0){super.pause(),this.isPictureInPicture()||this.hasPoster||!(KK||t&&(Ql||cE))||await this.setPoster(this.getVideoFrame(),!0)}resume(t=!1){return super.resume(t).then(()=>{var i;(this.posterImg||(i=this.element)!=null&&i.poster)&&this.setPoster("",!0)})}doResume(t=!1){return this.isPaused&&t&&this.element&&this.track&&KK&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(t=0){var i;this.isPictureInPicture()&&this.exitPictureInPicture().catch(r=>{}),this.isFullscreen()&&this.exitFullscreen().catch(r=>{}),this.element&&(this.element.removeEventListener(gt.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),(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(t){if(Fr(t?.isLiveStream)||this.setLiveMode(t.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(t){t!==this.track&&(this.unbindTrackEvents(),this.track=t,this.emit(vr.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"";const 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(AW()&&this.element&&this._calculateTimeout<0){let t=0,i=null;const r=(s,g)=>{this.stat.width=g.width,this.stat.height=g.height,i&&(this.stat.fps=Math.round((g.presentedFrames-i.presentedFrames)/(s-t)*1e3)),t=s,i=g,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var B;return(B=this.element)==null?void 0:B.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(t){this._log.warn("init stat failed",t)}}async enterFullscreen(){const t=this.elementToRender;if(!t)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");if(UI&&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(t.requestFullscreen)await t.requestFullscreen();else if(t.webkitRequestFullscreen)await t.webkitRequestFullscreen();else if(t.webkitEnterFullscreen)await t.webkitEnterFullscreen();else if(t.mozRequestFullScreen)await t.mozRequestFullScreen();else{if(!t.msRequestFullscreen)throw new Error("Fullscreen API not supported");await t.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(t){throw this._log.error("failed to exit fullscreen:",t),t}}isFullscreen(){const t=this.elementToRender;return t?this.element&&this.element.webkitDisplayingFullscreen?!this.isPictureInPicture():(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===t:!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:t}=this;if(t.requestPictureInPicture){this._log.info("requestPictureInPicture");const i=await t.requestPictureInPicture();return this.pipWindow=i,this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),this._appendToWrapper(this.element)),i}if(t.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),await 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}}async exitPictureInPicture(){var t;try{if(!this.isPictureInPicture())return;if(delete this.pipWindow,document.pictureInPictureElement&&document.exitPictureInPicture)await document.exitPictureInPicture(),this.elementToRender===this.canvas&&((t=this.element)==null||t.remove(),this._pausedRetryCount=aw,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:t}=this;return document.pictureInPictureElement?document.pictureInPictureElement===t:!!t.webkitPresentationMode&&t.webkitPresentationMode==="picture-in-picture"}async togglePictureInPicture(){this.isPictureInPicture()?await this.exitPictureInPicture():await this.enterPictureInPicture()}};async function gcA(t,i){if(!t.audioWorklet)return Promise.reject("audioWorklet is not supported");try{await t.audioWorklet.addModule(i),qi.info("worklet addModule success")}catch(r){throw qi.info(`worklet addModule catch error. ${r.message}`),r}}typeof AudioContext<"u"?tk=AudioContext:typeof webkitAudioContext<"u"?tk=webkitAudioContext:typeof mozAudioContext<"u"&&(tk=mozAudioContext);var LI,IcA=1500,n8=-1,B2=0,ik=-1,qj=!1,a8=0,s8=-1,g8=-1;function JX(){try{if(LI)return;(LI=new tk({sampleRate:48e3})).onstatechange=()=>{qi.info(`context state: ${LI.state}${LI.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),yw()},clearTimeout(n8)}catch(t){qi.error(`initAudioContext failed: ${t} typeof AudioContextClass: ${typeof tk}`),n8=setTimeout(JX,1e3)}}JX();var yw=()=>{LI.state==="suspended"?(B2=Ns(),ccA(),tY(),document.addEventListener("click",yw)):LI.state==="interrupted"?tY():(B2&&(qr.addNumber({key:507800,value:Ns()-B2,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),B2=0),EcA(),document.removeEventListener("visibilitychange",yw),document.removeEventListener("click",yw))},Aj=0,ej=-1;function tY(){return new Promise((t,i)=>{if(LI.state==="running")return t();Date.now()-Aj<1e3?(clearTimeout(ej),ej=setTimeout(()=>{Aj=Date.now(),LI.resume().then(t,i)},1e3)):(clearTimeout(ej),Aj=Date.now(),LI.resume().then(t,i))}).catch(t=>{qi.warn(`context resume failed: ${t}`),document.addEventListener("visibilitychange",yw)})}function ccA(){ik===-1&&(ik=setTimeout(()=>{LI.state==="suspended"&&(qj=!0,Eo.emit("155",{isSuspended:!0}))},IcA))}function EcA(){ik!==-1&&(clearTimeout(ik),ik=-1,qj&&(qj=!1,Eo.emit("155",{isSuspended:!1})))}function lcA(){if(!UI||g8!==-1)return;const t=()=>{Ns()-a8<500||(LI&&LI.state==="running"&&LI.currentTime===s8&&(qi.warn("context is fake running, auto resume"),LI.suspend().catch(i=>{qi.warn(`context suspend failed: ${i}`)})),s8=LI.currentTime,a8=Ns())};g8=setInterval(()=>{t()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()})}document.addEventListener("click",yw);var Mp=t=>LI,cD=class{constructor(t){this.name=t,OA(this,"node"),OA(this,"node2"),OA(this,"pre",new Set),OA(this,"next",new Set),OA(this,"context"),OA(this,"connectedNodes",new Set),OA(this,"nextInputChannelMap",new Map),OA(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(t){this._channelCount=t,this.setChannelCount(this.node,t),this.setChannelCount(this.node2,t),this.next.forEach(i=>i.channelCount=t)}setChannelCount(t,i){!t||t instanceof ScriptProcessorNode||(t.channelCountMode="explicit",t.channelCount=i||this.channelCount||1)}setContext(t){this.context=t,this.node&&t.addMixWeight()}removeContext(){var t;this.node&&((t=this.context)==null||t.reduceMixWeight()),delete this.context}replaceNode(t){var i;if(t!==this.node)try{this.node?this._disconnect():(i=this.context)==null||i.addMixWeight(),this.node=t,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(r){qi.error(r)}}setNode(t,i){var r;if(!this.node)try{(r=this.context)==null||r.addMixWeight(),this.node=t,this.setChannelCount(this.node),i&&(this.node2=i,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),qr.addSuccessEvent({key:502701})}catch(s){qi.error(s),qr.addFailedEvent({key:502701,error:s})}}deleteNode(){var t;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(t=this.context)==null||t.reduceMixWeight(),this.preNodeReconnect(),qr.addSuccessEvent({key:502702})}catch(i){qi.error(i),qr.addFailedEvent({key:502702,error:i})}}preNodeReconnect(){this.pre.forEach(t=>{t.node?t.reconnect():t.preNodeReconnect()})}connectNext(t){this.next.forEach(i=>{const r=this.nextInputChannelMap.get(i);t._connect(i.node,r)||i.connectNext(t)})}_connect(t,i=0){return!(!this.node||!t)&&((this.node2||this.node).connect(t,0,i),this.connectedNodes.add(t),!0)}_disconnect(){this.connectedNodes.forEach(t=>{var i;return(i=this.node2||this.node)==null?void 0:i.disconnect(t)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(t,i=0){return this.next.add(t),t.pre.add(this),this.nextInputChannelMap.set(t,i),t}},CcA=class extends cD{constructor(t=256){super(),this.fftSize=t,OA(this,"dataArray",new Uint8Array(0))}setNode(t){t.fftSize=this.fftSize,this.dataArray=new Uint8Array(t.frequencyBinCount),super.setNode(t)}getByteTimeDomainData(){var t;return(t=this.node)==null||t.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var t;return(t=this.node)==null||t.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){const t=this.getByteTimeDomainData();let i=0,r=0,s=`M${i},${r}`;for(let g=0;gthis.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(id.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=r=>{id.lastMessageTime=Date.now(),this._volume=r.data.volume||0,this._volumeDb=r.data.volumeDb||0,!i&&r.data.cacheLen&&r.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}`),fC.logFailedEvent({userId:this._log.userId,eventType:zG.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Mp("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{id.lastMessageTime=Date.now();const r=i.inputBuffer.getChannelData(0);let s=0;for(let g=0;g>2);t.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),t.close()}}},dcA=bw(vk()),E8=t=>i=>i.deviceId===t,tj=class{constructor(t,i){OA(this,"kind"),OA(this,"type"),OA(this,"devices",[]),this.kind=t,this.type=i}update(t,i){const r=t.filter(s=>s.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);this.devices.length===1&&HX(this.devices[0])||i&&(r.forEach(s=>{if(s.deviceId&&!this.devices.find(E8(s.deviceId))){const g=`${this.kind}${this.type}Added`;qi.warn(`${g}: ${JSON.stringify(s)}`),i.emit(g,s)}}),this.devices.forEach(s=>{if(s.deviceId&&!r.find(E8(s.deviceId))){const g=`${this.kind}${this.type}Removed`;qi.warn(`${g}: ${JSON.stringify(s)}`),i.emit(g,s)}})),this.devices=r}hasDevice(t){return!!this.devices.find(i=>i.deviceId===t)}},hcA=class extends dcA.EventEmitter{constructor(){super(),OA(this,"audioInputs",new tj(gt.AUDIO,"Input")),OA(this,"videoInputs",new tj(gt.VIDEO,"Input")),OA(this,"audioOutputs",new tj(gt.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||Lu.run("interval",()=>{this.update()},{delay:1e4}))}init(){Kj().then(t=>{this.audioInputs.update(t),this.videoInputs.update(t),this.audioOutputs.update(t)})}async update(t=0){const i=await Kj(t);return this.audioInputs.update(i,this),this.videoInputs.update(i,this),this.audioOutputs.update(i,this),this}hasBlueTooth(){var t;if(1e3*((t=Mp())==null?void 0:t.outputLatency)>150)return!0;const i=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(r=>i.some(s=>r.label.toLowerCase().includes(s)))||this.audioInputs.devices.some(r=>i.some(s=>r.label.toLowerCase().includes(s)))}},_u=C9||l9?null:new hcA;function HX(t){return t.deviceId===t.groupId&&t.groupId===""}async function Kj(t=0){if(bY()||!z3())return[];let i=await navigator.mediaDevices.enumerateDevices();if(t!==0){const r={audio:!1,video:!1};if(i.forEach(s=>{HX(s)&&(s.kind===gt.AUDIO_INPUT?r.audio=!0:s.kind===gt.VIDEO_INPUT&&(r.video=!0))}),t===2&&(r.audio=!1),t===1&&(r.video=!1),r.audio||r.video){let s;try{s=await navigator.mediaDevices.getUserMedia(r),r.audio&&tY()}catch(g){qi.debug("capture before getDevices failed: ",g)}i=await navigator.mediaDevices.enumerateDevices(),s?.getTracks().forEach(g=>g.stop())}}return i.map((r,s)=>{const g={kind:r.kind,deviceId:r.deviceId,groupId:r.groupId,label:r.label||`${r.kind}_${s}`};return r.deviceId.length>0&&oW.add(`${r.deviceId}_${r.kind}`),r.getCapabilities&&(g.getCapabilities=()=>r.getCapabilities()),g})}function dk(t=!1){return _u.update(t?1:0).then(i=>i.audioInputs.devices)}function ED(t=!1){return _u.update(t?2:0).then(i=>i.videoInputs.devices)}var l8=!1;async function pcA(){try{l8||(l8=!0,qi.info(`speakers:${(await fcA()).map(t=>` ${t.deviceId.slice(0,8)}: ${t.label}`)}`))}catch{}}async function fcA(t=!1){return(UI||cE)&&(t=!1),_u.update(t?1:0).then(i=>i.audioOutputs.devices)}var T2,oW=new Set;function mcA(t){if(t instanceof CanvasCaptureMediaStreamTrack||!(t instanceof MediaStreamTrack))return!1;const i=t.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;const r=`${(t?.getSettings()||{}).deviceId}_${gt.VIDEO_INPUT}`;return!!oW.has(r)}function DcA(t){if(t instanceof CanvasCaptureMediaStreamTrack||!(t instanceof MediaStreamTrack))return!1;const i=t.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("麦克风"))return!0;const r=`${(t?.getSettings()||{}).deviceId}_${gt.AUDIO_INPUT}`;return!!oW.has(r)}async function ycA(t,i){const r=(await dk()).find(s=>s.deviceId===Q9);return!i&&r?.groupId===t||r?.groupId===t&&r.label===i}async function RcA({newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:s,kind:g}){return t===i&&(g!==gt.AUDIO||t!==Q9||await ycA(r,s))}var McA=class extends BcA{constructor(t){super(),this.log=t,OA(this,"volumeMeter"),OA(this,"volumeMeterAfter3A"),OA(this,"volumeDestination"),OA(this,"analyser",new CcA),this.volumeMeter=new c8({log:this.log}),this.volumeMeterAfter3A=new c8({log:this.log}),this.volumeDestination=new cD,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},wcA=class extends Xm{constructor(t){super(t,gt.AUDIO),OA(this,"_outputDeviceId"),OA(this,"_floatVolume",1),OA(this,"_destination"),OA(this,"pipeline"),OA(this,"volumeMeterMode","worklet"),OA(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=t.enableVolumeControlInIOS,this.mode=0,t.url&&(this.url=t.url),this.pipeline=new McA(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((Fu==="15.2"||Fu==="15.3"||Fu==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");this._log.info("audio player initializeElement");const i=T2||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(hD(t)?t/100:this._floatVolume),i===T2&&(T2=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(vr.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}async play(t){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&&await this.setSinkId(this._outputDeviceId),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(Mp("player").createAnalyser()),pcA()}catch(i){throw this._log.warn(`audio play error: ${i}`),gX(Fu,"18.7",!0)&&this.bindAutoPlayEvent(),i}return super.play()}}stop(t=0){this.pipeline.destroy(),super.stop(t)}setVolume(t){this._floatVolume=t,this.element&&(this.element.volume=t)}async setSinkId(t){var i,r;this._outputDeviceId!==t&&(this._outputDeviceId=t),this.element&&this.element.sinkId!==t&&await((r=(i=this.element).setSinkId)==null?void 0:r.call(i,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()}},ScA=class extends wcA{constructor(t){super(t),OA(this,"_sourceElement"),OA(this,"_output",new cD),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(Mp().destination)}write(t){this.pipeline.volumeMeter.write(t)}setTrack(t){var i,r,s;((r=(i=this.element)==null?void 0:i.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==t&&(this.unbindTrackEvents(),this.track=t,this.emit(vr.MEDIA_TRACK_CHANGED,t),t?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([t]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([t])),this.pipeline.source.channelCount=((s=t.getSettings())==null?void 0:s.channelCount)||1,this.pipeline.replaceSource(t)):this.pipeline.source.deleteNode())}setVolume(t){var i;const r=t<=1&&!W2();if(!(this._floatVolume===t&&(r&&((i=this.element)==null?void 0:i.volume)===t||!r&&this.pipeline.volume===t)))if(this._floatVolume=t,this.useDestination)this.pipeline.setVolume(t),this._log.info(`set pipeline volume: ${t}`);else if(r)this.element?(this._log.info(`set element volume: ${t}`),this.element.volume=t):this._log.info("set element volume: no element");else{if(W2()){if(!this.enableVolumeControlInIOS)return;lcA()}if(Ql&&!this.pipeline.source.node)return void this._log.warn("set pipeline volume failed: no source node");this._log.info(`start set pipeline volume: ${t}`),this.pipeline.setVolume(t),this.element&&!this._sourceElement&&(this._destination||(this._destination=Mp().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),Bk(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(s=>{this.emit(vr.AUTOPLAY_FAILED,s)}))}}stop(t=0){this.pipeline.destroy();const i=this._sourceElement||this.element;i&&sX&&(T2=i),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(t)}},rW=class extends Lr{constructor({userId:t,sdkAppId:i,mediaType:r,room:s,PlayerClass:g=r===1?ScA:lp}){var B;super(),OA(this,"id",uX()),OA(this,"userId",""),OA(this,"isRemote"),OA(this,"mediaType"),OA(this,"room"),OA(this,"user"),OA(this,"_log"),OA(this,"_inputTrack"),OA(this,"_outputTrack"),OA(this,"isPlayCalled"),OA(this,"container",null),OA(this,"player"),OA(this,"subVideoPlayerMap"),OA(this,"muted",!1),OA(this,"abortCtrl"),OA(this,"objectFit","cover"),OA(this,"mirror"),OA(this,"rotation"),OA(this,"isScreen",!1),OA(this,"manager"),OA(this,"trackSettings"),OA(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=r,this._log=qi.createLogger({parent:s?.getLogger(),id:`${this.kind[0]}t`,userId:(B=s||this.room)==null?void 0:B.userId,remoteUserId:this instanceof oD?void 0:this.userId,sdkAppId:i,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof oD}),this.player=new g({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:s?.enableVolumeControlInIOS}),this.player.on(vr.PLAYER_STATE_CHANGED,Q=>{if(Eo.emit(nr.PLAYER_STATE_CHANGED,cr({track:this},Q)),this.emit("player-state-changed",Q),Q.state==="PLAYING"&&this.room){let f=!0;for(const{remoteAudioTrack:m,remoteVideoTrack:M,remoteAuxiliaryTrack:v}of[...this.room.remotePublishedUserMap.values()])if(m.isAvailable&&!m.player.isPlaying||M.isAvailable&&!M.player.isPlaying||v.isAvailable&&!v.player.isPlaying){f=!1;break}f&&uk()&&scA()}}),this.kind===gt.VIDEO&&(this.player.on(vr.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(vr.LOADED_DATA),Eo.emit(nr.VIDEO_LOADED_DATA,{track:this})}),this.player.on(vr.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(vr.LOADED_META_DATA)}),this.player.on(vr.MEDIA_TRACK_CHANGED,Q=>{var f;(f=this.subVideoPlayerMap)==null||f.forEach(m=>m.setTrack(Q))}),this.player.on(vr.RESIZE,Q=>{this.emitFirstVideoFrameEvent(vr.RESIZE),this.emit("video-size-changed",cr({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},Q))}),this.player.on(vr.FIRST_FRAME_RENDER,Q=>{this.emit("first-frame-render",lB(cr({},Q),{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(vr.ERROR,this.onPlayerError.bind(this)),this.player.on(vr.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||qi}get kind(){return this.mediaType===1?gt.AUDIO:gt.VIDEO}get isAudio(){return this.kind===gt.AUDIO}get strMediaType(){return this.mediaType===4?gt.VIDEO:this.mediaType===2?gt.SCREEN:gt.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(t,i){const r=dC(t)?t[0]:t;if(this.isPlayCalled)return this.log.info(`play update options: ${JSON.stringify(i)}`),i&&!Fr(i.muted)&&this.setPlayerMute(i.muted),i&&!Fr(i.objectFit)&&(this.objectFit=i.objectFit),void(this.player instanceof lp&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(dC(t)&&t.length>=1&&this.container&&t.includes(this.container)&&this.container.contains(this.player.elementToRender)?(t.splice(t.indexOf(this.container),1),t.unshift(this.container)):(this.container=r,this.player.setContainer(r))),dC(t)&&t.length>=1&&await this.playSubContainer(t.slice(1),i)));if(i&&!Fr(i.muted)?this.setPlayerMute(i.muted):this.isRemote&&this.kind!==gt.VIDEO||this.setPlayerMute(!0),i&&!Fr(i.objectFit)&&(this.objectFit=i.objectFit),this.player instanceof lp&&(Fr(i?.isLiveStream)||this.player.setLiveMode(i.isLiveStream),this.player.setObjectFit(this.objectFit),i&&!Fr(i.poster)&&this.player.setPoster(i.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof lp&&this.player.setContainer(r)),Eo.emit(nr.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),dC(t)&&t.length>1&&await this.playSubContainer(t.slice(1),i)}catch(s){throw this.handleAutoPlayFailed(s),s}}else this.log.info("play has not mediaTrack, abort")}setMirror(t,i){if(this.isScreen||this.kind!==gt.VIDEO||Fr(t)||t===this.mirror)return;this.mirror=t;let r=this.player;i&&(r=i);const s=this.manager;if(gD(this.mirror))return r.setViewMirror(this.mirror),void(!this.isRemote&&s&&(s.mirror=!1));switch(this.mirror){case"view":s&&(s.mirror=!1),r.setViewMirror(!0);break;case"publish":s&&(s.mirror=!0),r.setViewMirror(!0);break;case"both":s&&(s.mirror=!0),r.setViewMirror(!1)}}async playSubContainer(t,i){if(!this._outputTrack||this.kind===gt.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((s,g)=>{var B;t.find(Q=>g===Q)||(s.stop(),(B=this.subVideoPlayerMap)==null||B.delete(g))});for(const[s,g]of t.entries()){const B=this.subVideoPlayerMap.get(g);B?i&&(Fr(i.objectFit)||B.setObjectFit(i.objectFit)):this.subVideoPlayerMap.set(g,new lp({id:this.userId||this.id,track:this.playerMediaTrack,container:g,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${s+1}`})}))}const r=[...this.subVideoPlayerMap.values()];for(const s of r)s.setViewMirror(this.player.mirror),await s.play()}setAudioOutput(t){return this.player.setSinkId(t)}setAudioVolume(t){this.player.setVolume(t)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var t;return((t=this.player)==null?void 0:t.getInternalAudioLevel())||0}stop(t=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(VK(this)&&!t?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(i=>{i.stop()}),this.container=null)}async resume(){var t;this.isPlayCalled&&await((t=this.player)==null?void 0:t.resume())}close(){this._toInitState(),this.log.info("close"),this.isPlayCalled&&this.stop(!0)}_toInitState(){}setMute(t){this.muted=t,this._inputTrack&&(this._inputTrack.enabled=!t),this._outputTrack&&(this._outputTrack.enabled=!t),this.emit(t?"mute":"unmute",this),Eo.emit(t?nr.TRACK_MUTED:nr.TRACK_UNMUTED,{track:this})}setPlayerMute(t){this.player.setMuted(t)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(t){tW(t,t).add(gt.MUTE,this.onTrackMuted).add(gt.UNMUTE,this.onTrackUnmuted).add(gt.ENDED,this.onTrackEnded),t.muted&&this.onTrackMuted(),t.readyState===gt.ENDED&&this.onTrackEnded()}uninstallTrackEvent(t){Bk(t)}setInputMediaStreamTrack(t){var i;const r=this._inputTrack;if(t!==r)return this._inputTrack=t,this.trackSettings=(i=t.getSettings)==null?void 0:i.call(t),t.enabled=!this.muted,r&&this.uninstallTrackEvent(r),this.installTrackEvent(t),this.emit("input-media-track-changed",t||null,r||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(t)}setOutputMediaStreamTrack(t){var i;const r=this._outputTrack;this instanceof UY&&k3(r)||t!==r&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",t.label):this.log.info("setOutputMediaStreamTrack",(i=t.getSettings)==null?void 0:i.call(t).deviceId,t.label),this._outputTrack=t,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!t),this.emit("output-media-track-changed",t))}setMediaType(t){this.mediaType=t}updatePlayingState(t){var i,r;if(this.isPlayCalled){if(t){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch(s=>this.handleAutoPlayFailed(s)),void this.log.info(`playing state updated, play ${this.kind}`)}else if(!this.player.isStopped)return VK(this)&&this.isAudio&&((i=this.user)!=null&&i.muteState.hasAudio)&&((r=this.user)!=null&&r.muteState.audioMuted)?void 0:(this.player.stop(VK(this)?this.jitterBufferDelay:0),void this.log.info(`playing state updated, stop ${this.kind}`))}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${t} ${this.player.isStopped}`)}async handleAutoPlayFailed(t){var i;this.log.warn("handleAutoPlayFailed",t);const r=()=>{this.resume().then(()=>{document.removeEventListener("click",r,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((Lw||Gk)&&(await vw(100),(i=this.player)==null?void 0:i.isPlaying))return;acA()}else document.addEventListener("click",r,!0);Eo.once(nr.LOCAL_TRACK_CAPTURE_SUCCESS,({track:s})=>{s.kind==="audio"&&uk()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&r()}),this.emit("error",t)}getVideoFrame(){return this.player instanceof lp?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(t){var i,r,s;if(this.isFirstVideoFrameEmitted)return;const g=(i=this.mediaTrack)==null?void 0:i.getSettings();let B=g?.width||((r=this.player.element)==null?void 0:r.videoWidth)||0,Q=g?.height||((s=this.player.element)==null?void 0:s.videoHeight)||0;(t!==vr.RESIZE||B||Q)&&(t!==vr.LOADED_META_DATA||B||Q)&&(t!==vr.LOADED_DATA||B||Q||this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,G9(this.rotation)&&([B,Q]=[Q,B]),this.emit("first-video-frame",{width:B,height:Q,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`)}};ss([FI([],Lr.INIT,{sync:!0})],rW.prototype,"_toInitState");var vcA=Object.prototype.hasOwnProperty;function NcA(t){if(t==null)return!0;if(typeof t=="boolean")return!1;if(typeof t=="number")return t===0;if(typeof t=="string"||typeof t=="function"||Array.isArray(t))return t.length===0;if(t instanceof Error)return t.message==="";if(Sw(t))switch(Object.prototype.toString.call(t)){case"[object File]":case"[object Map]":case"[object Set]":return t.size===0;case"[object Object]":for(const i in t)if(vcA.call(t,i))return!1;return!0}return!1}var iY=NcA,TcA=async function(t){const i=kcA(t);qi.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let r=[],s=[];const g=["label","deviceId","groupId"];if(i.audio&&(r=await dk(),qi.info(`microphones: ${hp(r.map(B=>lB(cr({},B),{groupId:B.groupId.substring(0,8)})),{keysToInclude:g})}`)),i.video&&(s=await ED(),qi.info(`cameras: ${hp(s,{keysToInclude:g})}`),!gD(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){const B=s.filter(Q=>!Q.label.includes("infrared")).find(Q=>Q.label.includes("facing front"));B&&(i.video.deviceId=B.deviceId,qi.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{const B=await navigator.mediaDevices.getUserMedia(i);return TX&&B.getTracks().forEach(Q=>{var f;const m=Q.getCapabilities();qi.info(`${Q.kind} capabilities: ${hp(m,{keysToInclude:d9})}`),Fr(t.echoCancellation)||((f=m.echoCancellation)==null?void 0:f.indexOf(t.echoCancellation))!==-1||qi.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(m.echoCancellation)}], but received '${t.echoCancellation}'`)}),i.audio&&tY(),B}catch(B){let{message:Q}=B;throw B.name==="NotFoundError"&&(t.video&&s&&s.length===0&&(Q=AY({key:$2.CAMERA_NOT_FOUND})),t.audio&&r&&r.length===0&&(Q=AY({key:$2.MICROPHONE_NOT_FOUND}))),new Ws({code:xa.INITIALIZE_FAILED,name:B.name,message:Q,constraint:B.constraint})}},GcA=_3({retryFunction:TcA,settings:{retries:3,timeout:500},onError:({error:t,retry:i,reject:r,retryFuncArgs:s,retriedCount:g})=>{const B=g+1;t.name==="NotReadableError"||t.name==="OverconstrainedError"||t.name==="AbortError"?(B===1?(s[0].video&&(s[0].maxResolution=!1,(!cE||s[0].width*s[0].height<=2073600)&&s[0].frameRate&&(s[0].frameRate=s[0].frameRate>10?10:5)),s[0].retryWhenExactFailed&&s[0].useExactDeviceId&&(s[0].useExactDeviceId=!1)):B===2?s[0].useDeviceIdOnly=!0:B!==3||s[0].useExactDeviceId||(s[0].useTrueAsConstraint=!0),i()):r(t),s[0].microphoneId&&C8(s[0].microphoneId,!1),s[0].cameraId&&C8(s[0].cameraId,!0)},onRetrying:t=>{qi.warn(`getUserMedia NotReadableError observed, retrying [${t}/3]`)},onRetryFailed:t=>{fC.logFailedEvent({eventType:zG.GET_USER_MEDIA_RETRY,error:t})},onRetrySuccess:t=>{fC.logSuccessEvent({eventType:zG.GET_USER_MEDIA_RETRY}),fC.uploadEvent({log:`stat-${zG.GET_USER_MEDIA_RETRY}-success-${t}`})}});async function C8(t,i){const r=(i?await ED():await dk()).find(s=>s.deviceId===t);r&&sD(r.getCapabilities)&&qi.warn(hp(r.getCapabilities(),{keysToInclude:d9}))}function kcA(t){return{audio:_cA(t),video:bcA(t)}}function _cA(t){if(!t.audio)return!1;if(t.useTrueAsConstraint)return!0;const i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:t.sampleRate};return!iY(t.microphoneId)&&(i.deviceId=t.useExactDeviceId?{exact:t.microphoneId}:t.microphoneId,t.useDeviceIdOnly)?i:(hD(t.channelCount)&&(i.channelCount=t.channelCount),(gD(t.echoCancellation)||t.echoCancellation==="remote-only"||t.echoCancellation==="all")&&(i.echoCancellation=t.echoCancellation),gD(t.noiseSuppression)&&!t.noiseSuppression&&(i.noiseSuppression=!1),gD(t.autoGainControl)&&!t.autoGainControl&&(i.autoGainControl=!1),!!iY(i)||i)}function bcA(t){if(!t.video)return!1;if(t.useTrueAsConstraint)return!0;const{maxResolution:i=!0}=t,r={};return t.cameraId?r.deviceId=t.useExactDeviceId?{exact:t.cameraId}:t.cameraId:t.facingMode&&(r.facingMode=t.facingMode),t.useDeviceIdOnly&&!iY(r)?r:(t.width&&(r.width={ideal:t.width},i&&!Ql&&(r.width.max=t.width)),t.height&&(r.height={ideal:t.height},i&&!Ql&&(r.height.max=t.height)),Ql&&kY&&t.width&&t.height&&t.width*t.height<101376&&(r.width=t.width,r.height=t.height),t.frameRate&&(r.frameRate=t.frameRate),!!iY(r)||r)}var LcA=GcA;function VX(t){return FY((i,r)=>async function(...s){const g=await i.apply(this,s);return await t.call(this,...s),g})}function FY(t){return function(i,r,s){return s.value=t(s.value,r),s}}var FcA=(()=>{let t=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&qi.info(`visibility change: ${document.visibilityState}`),t||(document.addEventListener("visibilitychange",()=>{qi.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),t=!0)}})(),UcA=0,OcA=class{constructor(t){OA(this,"log"),OA(this,"isRunning",!1),OA(this,"queue",[]);let i="fq"+ ++UcA;t&&(i+=`|${t}`),this.log=qi.createLogger({id:i})}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(t,i=!1){var r,s;const g=cr({},t),B=new Promise((Q,f)=>{g.resolve=Q,g.reject=f});return g.promise=B,i?this.length<=1?this.queue.push(g):(s=(r=this.lastQueueItem)==null?void 0:r.promise)==null||s.then(g.resolve,g.reject):this.queue.push(g),this.log.debug(`push ${this.length}`,t.funcName,t.args),this.isRunning||this.callNext(),B}shift(){const t=this.queue.shift();return this.log.debug(`shift ${this.length}`,t?.funcName,t?.args),t}callNext(){if(this.isRunning||this.length===0)return;const{fn:t,args:i,context:r,resolve:s,reject:g,funcName:B}=this.queue[0];this.log.debug("callNext",this.length,B,i),this.isRunning=!0,t.apply(r,i).then(s,g).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},B8=new WeakMap;function xcA(t=!1){return function(i,r,s){const g=s.value;return s.value=function(...B){const Q=B8.get(this)||new OcA;return B8.set(this,Q),Q.push({fn:g,args:B,context:this,funcName:r},t)},s}}function qX(t,i){return FY((r,s)=>function(...g){const B=t;try{const Q=r.apply(this,g),f=Ns();return D9(Q)?Q.then(m=>(i?qr.addSuccessEvent({key:B,cost:Ns()-f}):qr.addSuccessEvent({key:B}),m)).catch(m=>{throw qr.addFailedEvent({key:B,error:m}),m}):(qr.addSuccessEvent({key:B}),Q)}catch(Q){throw qr.addFailedEvent({key:B,error:Q}),Q}})}function Rg(...t){}var YcA=t=>t();function PcA(){this.dispose()}var JcA=()=>typeof __FASTRX_DEVTOOLS__<"u",HcA=1,Nw=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){const i=new qcA(t,this,this.streamId++);return js.subscribe({id:this.id,end:!1},{nodeId:i.sourceId,streamId:i.id}),this(i),i}},nW=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=Rg,this.error=Rg,this.next=Rg,this.dispose=Rg,this.subscribe=Rg,this.doDefer()}subscribe(t){return t instanceof Nw?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(YcA),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}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}},QB=class extends nW{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}},VcA=class extends nW{constructor(t,i=Rg,r=Rg,s=Rg){if(super(),this._next=i,this._error=r,this._complete=s,this.then=Rg,t instanceof Nw){const g={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{js.defer(g,0)}),js.create(g),js.pipe(g),this.sourceId=g.id,this.subscribe(t),js.subscribe({id:g.id,end:!0}),i==Rg?this._next=B=>js.next(g,0,B):this.next=B=>{js.next(g,0,B),i(B)},s==Rg?this._complete=()=>js.complete(g,0):this.complete=()=>{this.dispose(),js.complete(g,0),s()},r==Rg?this._error=B=>js.complete(g,0,B):this.error=B=>{this.dispose(),js.complete(g,0,B),r(B)}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function QC(t,...i){return i.reduce((r,s)=>s(r),t)}function dl(t,i,r){if(JcA()){const s=Object.defineProperties(Object.setPrototypeOf(t,Nw.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:r,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});js.create(s);for(let g=0;g{if(s instanceof Nw){const g=dl(B=>{const Q=new t(B,...r);Q.sourceId=g.id,Q.subscribe(s)},i,arguments);return g.source=s,js.pipe(g),g}return g=>s(new t(g,...r))}}}function np(t,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:t,payload:i}})}var qcA=class extends QB{constructor(t,i,r){super(t),this.source=i,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{js.defer(this.source,this.id)})}next(t){js.next(this.source,this.id,t),this.sink.next(t)}complete(){js.complete(this.source,this.id),this.sink.complete()}error(t){js.complete(this.source,this.id,t),this.sink.error(t)}},js={addSource(t,i){np("addSource",{id:t.id,name:t.toString(),source:{id:i.id,name:i.toString()}})},next(t,i,r){np("next",{id:t.id,streamId:i,data:r&&r.toString()})},subscribe({id:t,end:i},r){np("subscribe",{id:t,end:i,sink:{nodeId:r&&r.nodeId,streamId:r&&r.streamId}})},complete(t,i,r){np("complete",{id:t.id,streamId:i,err:r?r.toString():null})},defer(t,i){np("defer",{id:t.id,streamId:i})},pipe(t){np("pipe",{name:t.toString(),id:t.id,source:{id:t.source.id,name:t.source.toString()}})},update(t){np("update",{id:t.id,name:t.toString()})},create(t){t.id||(t.id=HcA++),np("create",{name:t.toString(),id:t.id})}},KcA=class extends nW{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(i=>i.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(i=>i.error(t)),this.sinks.clear()}};function KX(){return t=>{const i=new KcA(t);if(t instanceof Nw){const r=dl(s=>{i.add(s)},"share",arguments);return i.sourceId=r.id,r.source=t,js.pipe(r),r}return dl(i.add.bind(i),"share",arguments)}}function jX(...t){return dl(i=>{const r=new QB(i);let s=t.length;r.complete=()=>{--s===0&&i.complete()},t.forEach(r.bindSubscribe)},"merge",arguments)}function jcA(...t){return dl(i=>{const r=new Map;t.forEach(s=>{const g=new QB(i);r.set(s,g),g.complete=()=>{r.delete(s),r.size===0?i.complete():g.dispose()},g.next=B=>{r.delete(s),r.forEach(Q=>Q.dispose()),g.resetNext(),g.resetComplete(),g.next(B)}}),t.forEach(s=>r.get(s).subscribe(s))},"race",arguments)}function WcA(...t){return i=>dl((r,s=0,g=t.length)=>{for(;s{r.next=g=>s.next(g),r.complete=()=>s.complete(),r.error=g=>s.error(g),t&&s.subscribe(t)},"subject",i));return r.next=Rg,r.complete=Rg,r.error=Rg,r}function zcA(t){return dl(i=>{let r=0;const s=setInterval(()=>i.next(r++),t);return i.defer(()=>{clearInterval(s)}),"interval"},"interval",arguments)}function ZcA(t,i){return dl(r=>{let s=0;const g=setTimeout(()=>{r.removeDefer(B),r.next(s++),i||r.complete()},t),B=()=>clearTimeout(g);r.defer(B)},"timer",arguments)}function ij(t,i){return r=>{const s=g=>r.next(g);r.defer(()=>i(s)),t(s)}}function Rc(t,i){if("on"in t&&"off"in t)return dl(ij(r=>t.on(i,r),r=>t.off(i,r)),"fromEvent",arguments);if("addListener"in t&&"removeListener"in t)return dl(ij(r=>t.addListener(i,r),r=>t.removeListener(i,r)),"fromEvent",arguments);if("addEventListener"in t)return dl(ij(r=>t.addEventListener(i,r),r=>t.removeEventListener(i,r)),"fromEvent",arguments);throw"target is not a EventDispachter"}function XcA(){return dl(t=>t.complete(),"empty",arguments)}var $cA=class extends QB{constructor(t,i,r){super(t),this.filter=i,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},Rw=DD($cA,"filter"),AEA=class extends QB{constructor(t,i){super(t),this.count=i}next(t){this.sink.next(t),--this.count===0&&(this.doDefer(),this.complete())}},eEA=DD(AEA,"take"),tEA=class extends QB{constructor(t,i){super(t);const r=new QB(t);r.next=()=>{r.doDefer(),t.complete()},r.complete=PcA,r.subscribe(i)}},Tw=DD(tEA,"takeUntil"),iEA=class extends QB{constructor(t,i){super(t),this.f=i}next(t){this.f(t)||(this.next=super.next,this.next(t))}},oEA=DD(iEA,"skipWhile"),rEA=class extends QB{constructor(t,i,r){super(t),this.mapper=i,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},zX=DD(rEA,"map"),nEA=class extends QB{constructor(t,i,r){super(t),this.data=i,this.context=r}next(t){const i=this.context.combineResults;i?this.sink.next(i(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},aEA=class ZX extends QB{constructor(i,r,s){super(i),this.makeSource=r,this.combineResults=s,this.index=0}subInner(i,r){const s=this.currentSink=new r(this.sink,i,this);this.complete===ZX.prototype.complete&&(this.complete=this.tryComplete),s.complete=s.tryComplete,s.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},u8=class extends nEA{},XX=class extends aEA{next(t){this.subInner(t,u8),this.next=i=>{this.currentSink.dispose(),this.subInner(i,u8)}}},sEA=DD(XX,"switchMap");function gEA(t){return(i,r)=>t(()=>i,r)}var $X=gEA(DD(XX,"switchMapTo")),fD=(t=Rg,i=Rg,r=Rg)=>s=>new VcA(s,t,i,r),A7=(t=>(t[t.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",t[t.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",t))(A7||{}),oD=class extends rW{constructor(t,i){super({mediaType:t,PlayerClass:i}),OA(this,"isRemote",!1),OA(this,"deviceId"),OA(this,"groupId",""),OA(this,"label",""),OA(this,"sourceTrack"),OA(this,"enableAutoSwitchWhenRecapturing",!0),OA(this,"_isRecapturing",!1),OA(this,"_lastRecaptureTime",0),OA(this,"_onMuteTimeoutId",-1),OA(this,"_encodeCheckTimeoutId",-1),OA(this,"recaptureMode",0),OA(this,"profile"),OA(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,i){throw new Error("Method not implemented.")}installTrackEvent(t){t.addEventListener(gt.MUTE,this.onTrackMuted),t.addEventListener(gt.UNMUTE,this.onTrackUnmuted),t.addEventListener(gt.ENDED,this.onTrackEnded),t.muted&&this.onTrackMuted(),t.readyState===gt.ENDED&&this.onTrackEnded()}uninstallTrackEvent(t){t.removeEventListener(gt.MUTE,this.onTrackMuted),t.removeEventListener(gt.UNMUTE,this.onTrackUnmuted),t.removeEventListener(gt.ENDED,this.onTrackEnded)}setStateToReady(){}async capture(t,i=!1){var r,s;const g=this.sourceTrack;try{const B=Ns();let Q;Eo.emit(nr.LOCAL_TRACK_CAPTURE_START,{track:this}),t.customSource?(Q=new MediaStream,Q.addTrack(t.customSource)):(i||(r=this.sourceTrack)==null||r.stop(),Q=await LcA(t));const f=Q.getTracks()[0];return await this.setInputMediaStreamTrack(f),t.customSource||(this.sourceTrack=f,this.updateDeviceIdInUse(),this.listenDeviceChange()),Eo.emit(nr.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Ns()-B,profile:this.profile,room:(s=this.manager)==null?void 0:s.room}),Q}catch(B){throw Eo.emit(nr.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:B}),this.log.error(`getUserMedia error observed ${B}`),B}finally{i&&g?.stop()}}setOutputMediaStreamTrack(t){var i;if(super.setOutputMediaStreamTrack(t),this.setStateToReady(),this.isPublishing||this.isPublished)return(i=this.room)==null?void 0:i.replaceTrack(this)}get hasFlag(){var t,i;const r=R9(((t=this.room)==null?void 0:t.localPublishFlag)||0,((i=this.room)==null?void 0:i.userId)||"");return this.mediaType===4&&r.hasVideo||this.mediaType===1&&r.hasAudio||this.mediaType===2&&r.hasAuxiliary}async publish(t,i){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()),await i,this._checkPublishFlag(t)}_checkPublishFlag(t){return new Promise(async(i,r)=>{var s,g,B,Q,f;const m=()=>r(new Ws({code:xa.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?i():(this.state!==Lr.INIT&&this.state!=="ready"||m(),QC(Rc(t,"local-publish-flag-changed"),Rw(()=>this.hasFlag),Tw(jX(Rc(this,Lr.INIT),Rc(this,"ready"))),fD(i,r,m))),(B=(g=(s=this.room)==null?void 0:s.networkQuality)==null?void 0:g.hadRecentBadUplink)==null?void 0:B.call(g,2))return i();const M=t.heartbeatCount,v=((f=(Q=this.mediaTrack)==null?void 0:Q.stats)==null?void 0:f.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(async()=>{var U,AA,z,sA,eA,X,QA,wA;if((z=(AA=(U=this.room)==null?void 0:U.networkQuality)==null?void 0:AA.hadRecentBadUplink)!=null&&z.call(AA,2)||t.heartbeatCount-M<3)return i();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((sA=this.mediaTrack)!=null&&sA.stats){const ue=this.mediaTrack.stats.totalFrames||0;ue-v===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",ue)}const HA=this.kind===gt.AUDIO,qA=this.stat.bytesSent>0;if(qr[qA?"addSuccessEvent":"addFailedEvent"]({key:HA?503700:513702}),!HA){const ue={H264:513704,H265:513705,VP8:513706}[((X=(eA=this.room)==null?void 0:eA.videoCodec)==null?void 0:X.toUpperCase())||"H264"];ue&&qr[qA?"addSuccessEvent":"addFailedEvent"]({key:ue})}if(!qA){if(qr.addEnum({key:HA?503701:513703,value:K3()}),fC.uploadEvent({log:`stat-encode-failed-${this.kind}-${IX()||EX()}`,userId:this.userId}),this.log.warn(HA?"encode failed":`${(wA=(QA=this.room)==null?void 0:QA.videoCodec)==null?void 0:wA.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),await this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(await vw(5e3),this.stat.bytesSent>0||this.hasFlag)))return i();this.emit("6",this),r(new Ws({message:`${this.strMediaType} encode failed`,code:HA?xa.AUDIO_ENCODE_FAILED:xa.VIDEO_ENCODE_FAILED}))}}},1e4)})}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),Eo.emit(nr.LOCAL_TRACK_UNPUBLISHED,{track:this})}async updateDeviceIdInUse(){if(this.sourceTrack&&eY){const{deviceId:t,groupId:i}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;await RcA({newDeviceId:t,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind})||(this.deviceId=t,this.label=r,i&&(this.groupId=i),Kj().then(s=>{const g=s.find(B=>{let Q=B.deviceId===t;return i&&(Q=Q&&B.groupId===i),Q});g&&this.emit("2",g)}))}}setProfile(t){this.log.info("setProfile",t),Object.assign(this.profile,t)}isNeedToRecapture(t=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===gt.AUDIO&&!DcA(this.sourceTrack)||this.kind===gt.VIDEO&&!mcA(this.sourceTrack)||this._isRecapturing||t&&kY&&cE)}onTrackMuted(){super.onTrackMuted(),FcA(),this.isNeedToRecapture(!0)&&(Date.now()-this._lastRecaptureTimethis.onTrackMuted(),c2):this._onMuteTimeoutId=setTimeout(async()=>{var t;if((t=this.sourceTrack)!=null&&t.muted){if((UI||hl)&&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(),c2);this.emit("7"),this.recapture(await this.getRecoverCaptureDeviceId())}}async recapture(t,i=!1){var r;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");const s=this.sourceTrack;i||(r=this.sourceTrack)==null||r.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();const g={useExactDeviceId:!0};if(t==="user"||t==="environment")g.facingMode=t;else{let B;(this.kind==="audio"?await dk():await ED()).find(Q=>Q.deviceId===t)&&(B=t),g.deviceId=B}return this.capture(g,i).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),Eo.emit(nr.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(B=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${B.message}`),this.emit("5",B),Eo.emit(nr.LOCAL_TRACK_RECAPTURE,{track:this,error:B})}).finally(()=>{i&&s?.stop()})}async getRecoverCaptureDeviceId(){const t=this instanceof UY;if(t&&this.facingMode)return this.facingMode;let{deviceId:i}=this;if(i){const r=(kG.get(i)||0)+1;if(kG.set(i,r),r>=3&&this.enableAutoSwitchWhenRecapturing){const s=t?(await ED()).find(g=>!kG.has(g.deviceId)):(await dk()).find(g=>!kG.has(g.deviceId));s&&(this.log.warn(`${i} capture fail ${r} times, change new ${s.deviceId}`),i=s.deviceId)}}return i}stopCapture(){var t;this.sourceTrack&&(this.sourceTrack.stop(),Eo.emit(nr.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()}};ss([FI(Lr.INIT,"ready",{ignoreError:!0,sync:!0})],oD.prototype,"setStateToReady"),ss([xcA()],oD.prototype,"capture"),ss([FI("ready","publish",{ignoreError:!0,success(){Eo.emit(nr.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(t){var i;(i=this.room)==null||i.localTracks.delete(this);let r="error";const s=t instanceof Ws?t:t.cause instanceof Ws?t.cause:t;let g=!1;s instanceof Ws&&(s.message.includes("timeout")?r="timeout":s.code===xa.API_CALL_ABORTED&&(g=!0,r="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:r,error:s}),this.log[g?"info":"error"]("publish failed",s)}}),qX(521714,!1)],oD.prototype,"publish"),ss([FY(t=>async function(){const i=this.state==="publish"?"started":"starting";t.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)}),FI([],"ready",{sync:!0})],oD.prototype,"unpublish");var kG=new Map;Eo.on(nr.SWITCH_DEVICE_SUCCESS,t=>{t.track.deviceId&&kG.delete(t.track.deviceId)});var IEA=class{constructor(t,i=!1){this.dataView=t,this.isSEI&&(i?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){const{seiPayloadStartIndex:t}=this,i=this.dataView.byteLength-2,r=[];let s=0;for(let B=t;B<=i;B++){const Q=this.dataView.getInt8(B);switch(Q){case 0:case 1:case 2:case 3:s===2&&(r.push(3),s=0),Q===0?s+=1:s=0,r.push(Q);break;default:s=0,r.push(Q)}}r.push(this.dataView.getInt8(this.dataView.byteLength-1));const g=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=g}removePreventionByte(){const{seiPayloadStartIndex:t}=this,i=this.dataView.byteLength-1,r=[];let s=0;for(let B=t;B<=i;B++)switch(this.dataView.getInt8(B)){case 0:s++,r.push(this.dataView.getInt8(B));break;case 3:s!==2&&r.push(this.dataView.getInt8(B)),s=0;break;default:r.push(this.dataView.getInt8(B)),s=0}const g=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=g}get seiPayloadStartIndex(){let t=6;for(let i=6;i=this.dataView.byteLength?0:31&this.dataView.getUint8(t)}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}},cEA=class{constructor(){OA(this,"_seiMessageList",[]),OA(this,"_smallSeiMessageList",[]),OA(this,"_seiPayloadType",243)}encodeSEINalu(t){const i=t.byteLength,r=parseInt(String(i/255),10),s=i%255,g=[];g.push(0,0,0,1,6,this._seiPayloadType);for(let Q=0;Q0&&t.data.byteLength>0){const s=9-this.getNaluCount(t.data);if(s<=0)return 0;const g=r.splice(0,s).reverse().map(this.encodeSEINalu.bind(this)),B=g.reduce((v,U)=>v+U.dataView.byteLength,0),Q=new ArrayBuffer(B+t.data.byteLength),f=new DataView(Q),m=new DataView(t.data);let M=0;for(let v=0;v{var s;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{const g=K2(((s=this.room)==null?void 0:s.sdkAppId)||0)?v5:S5;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${g}`),this.setProfile(lB(cr({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(eY&&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)}async setMute(t){var i,r,s;if(pC(t)){if(this.muteImage===t)return;await((i=this.manager)==null?void 0:i.deleteWatermark("mute")),await((r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:t,fillVideo:!0})),this.muteImage=t,super.setMute(!1)}else this.muteImage&&(await((s=this.manager)==null?void 0:s.deleteWatermark("mute")),this.muteImage=void 0),super.setMute(t)}async capture({deviceId:t,facingMode:i,useExactDeviceId:r=!0,customSource:s,retryWhenExactFailed:g=!0}){const B={audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:g,customSource:s};if(B.facingMode==="environment"){const Q=await this.getDeviceIdWhenUsingBackCamera();Q&&(B.cameraId=Q)}return super.capture(B)}setProfile(t){var i;const r=this.fallbackProfile(t);if(r.bitrate&&(this.isNeedToSetBandwidth=r.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(r);else{const s=K2(((i=this.room)==null?void 0:i.sdkAppId)||0)?v5:S5;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${s}`),super.setProfile(lB(cr({},this.profile),{width:1920,height:1080}))}}async applyProfile(){var t,i;if(!this.mediaTrack)return;const{width:r=0,height:s=0}=(this.sourceTrack||this.mediaTrack).getSettings(),g=r*s,B=this.settings,Q=B.height!==this.profile.height||B.width!==this.profile.width||B.frameRate!==this.profile.frameRate;if(Q&&(pD===16&&this.deviceId?await this.recapture(this.deviceId):(k3(this.outMediaTrack)?await((t=this.outMediaTrack)==null?void 0:t.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:f=0,height:m=0}=(this.sourceTrack||this.mediaTrack).getSettings(),M=f*m;return Q&&M&&g&&M===g?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:gt.VIDEO,videoType:gt.BIG})}}get settings(){const t={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},i=this.sourceTrack||this.mediaTrack;return eY&&i&&Object.assign(t,i.getSettings()),t}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:T9(this.settings,this.profile)}isAllowed2k4k(t){var i;return!this.room||!this.room.scheduleResult||!!this.isScreen||t.height*t.width<3686400||((i=this.room.scheduleResult.trtcAutoConf)==null?void 0:i["2k4k"])===1}isNeedToSwitchDevice(t){return!(!this.mediaTrack||this.deviceId===t||this.facingMode===t)}async switchDevice(t){try{if(!this.isNeedToSwitchDevice(t)&&!this.isUseCustomSource)return;const i={useExactDeviceId:!0,retryWhenExactFailed:!1};t==="user"||t==="environment"?i.facingMode=t:i.deviceId=t,this.sourceTrack&&this.sourceTrack.stop(),await this.capture(i),Eo.emit(nr.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 t;try{if(eX&&!V3&&GX){const i=(await ED(!0)).map(s=>{var g;return lB(cr({},s),{capabilities:(g=s.getCapabilities)==null?void 0:g.call(s)})}).filter(s=>{var g,B;return(B=(g=s.capabilities)==null?void 0:g.facingMode)==null?void 0:B.includes("environment")});let r=i[0];i.forEach(s=>{var g,B,Q,f;const{capabilities:m}=s;((g=m.width)!=null&&g.max&&((B=m.height)!=null&&B.max)?m.width.max*m.height.max:0)>((Q=r.capabilities.width)!=null&&Q.max&&((f=r.capabilities.height)!=null&&f.max)?r.capabilities.width.max*r.capabilities.height.max:0)&&(r=s)}),r?.capabilities&&(this._log.info("use max resolution back camera",r),t=r.deviceId)}}catch(i){this._log.warn("get max res camera failed",i)}return t}async updateSmallConfig(t){var i,r;this._log.info(`update small stream config: ${JSON.stringify(t)}`);const s=!this.small;this.small=this.fallbackProfile(t,!0),await((i=this.manager)==null?void 0:i.update()),s&&await((r=this.room)==null?void 0:r.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(t,i=!1){const r=t.width>t.height,s=cr({},t);return t.width*t.height<=19200&&hl&&yp&&(this.log.warn(`${i?"small ":""}resolution is ${t.width}*${t.height}, fallback to 240*180 for android chrome`),s.width=r?240:180,s.height=r?180:240,s.bitrate=Math.max(t.bitrate,150)),t.width*t.height>921600&&iIA&&(s.width=r?1280:720,s.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),eIA(Fu,"14.3")&&gX(Fu,"14.0",!0)&&this.on("7",()=>{const g=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=g?640:480,this.profile.height=g?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=g?640:360,this.profile.height=g?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!i&&this.avoidCropping&&(yp||Ql)&&!nIA()&&t.width*t.height<=230400&&t.width/t.height===16/9&&(this._scaleResolutionDownBy=1280/t.width,s.width=1280,s.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),s}stopSmall(){var t,i;this.small&&(delete this.small,(t=this.manager)==null||t.update(),(i=this.room)==null||i.enableSmall(!1))}listenDeviceChange(){_u&&!_u.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&_u.on("videoInputRemoved",this.handleCameraRemoved,this)}async handleCameraRemoved(t){if(t.deviceId===this.deviceId){let i=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${A7[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(t)}`),this.recaptureMode===0){ns(this.userId,{eventId:2003,param1:7,streamType:2});const r=await ED();r[0]?this.recapture(r[0].deviceId):i=!0}i&&_u.on("videoInputAdded",this.handleCameraAdded,this)}}async handleCameraAdded(t){this.recaptureMode===1&&t.deviceId!==this.deviceId||(_u.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(t)}`),this.recapture(t.deviceId))}encodeFrame(t,i){if(!this.manager)return t;const r=i?8:this.mediaType;return this.manager.encodePipeline.reduceRight((s,g)=>g?g({frame:s,mediaType:r}):s,t)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(t=>t)}play(t,i){return Fr(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(t,i)}close(){_u.off("videoInputAdded",this.handleCameraAdded,this),_u.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}async recapture(t){try{await super.recapture(t)}catch(i){const r=(await ED()).find(s=>s.deviceId!==t);if(!r)throw i;await super.recapture(r.deviceId)}}setContentHint(t){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==t&&(this.log.info(`setContentHint ${t}`),this.mediaTrack.contentHint=t),this.outMediaTrack&&this.outMediaTrack.contentHint!==t&&(this.outMediaTrack.contentHint=t))}setRotation(t){this.manager&&(this.isScreen||Fr(t)||t!==this.rotation&&(this.rotation=t,this.manager.rotation=t))}};ss([VX(function(t){this.setContentHint(t.contentHint||"motion")})],UY.prototype,"capture");var EEA=[-1,-1,1,-1,-1,1,1,1],lEA=[0,0,1,0,0,1,1,1],_G=class jj extends Lr{constructor(i,r){if(super(),this.context=i,OA(this,"name"),OA(this,"input"),OA(this,"output"),OA(this,"texture"),OA(this,"ctx2d",null),OA(this,"fbo"),OA(this,"width",0),OA(this,"height",0),OA(this,"x",0),OA(this,"y",0),OA(this,"program"),OA(this,"vertexShader"),OA(this,"fragmentShader"),OA(this,"totalFrames",0),OA(this,"dropFrames",0),OA(this,"matchInputSize",!0),OA(this,"texCoordBuffer"),OA(this,"positionBuffer"),OA(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),OA(this,"cost",0),OA(this,"_canvas",null),OA(this,"_image"),OA(this,"log"),this.context.on("disconnect",this.close,this),this.name=r.name,this.log=r.logger,this.matchInputSize=r.matchInputSize!==!1,this.width=r.width||i.width,this.height=r.height||i.height,this._image=r.image,i instanceof pk)i.ctx&&r.create2d&&(typeof OffscreenCanvas=="function"&&pD!==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 s=i.ctx;this.texCoordBuffer=this.createBuffer(lEA),this.positionBuffer=this.createBuffer(EEA),r.createTexture!==!1&&(this.texture=s.createTexture(),this.useTexture(),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.pixelStorei(s.UNPACK_ALIGNMENT,1)),r.useFbo&&(this.fbo=s.createFramebuffer(),this.useBufferFrame(),this.useTexture(),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,this.width,this.height,0,s.RGBA,s.UNSIGNED_BYTE,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,this.texture,0)),r.useDefaultProgram?this.program=i.defaultProgam:(r.vertexShaderSource||r.fragmentShaderSource)&&(this.vertexShader=r.vertexShaderSource?i.createShader(s.VERTEX_SHADER,r.vertexShaderSource):i.defaultVShader,this.fragmentShader=r.fragmentShaderSource?i.createShader(s.FRAGMENT_SHADER,r.fragmentShaderSource):i.defaultFShader,this.program=i.createProgram(this.vertexShader,this.fragmentShader))}catch(s){this.context.destroy(new Ws({code:xa.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${s.message||s}`}))}}get image(){return this._image}set image(i){this._image=i}createFramebuffer(i){const r=this.context.ctx,s=r.createFramebuffer();return r.bindFramebuffer(r.FRAMEBUFFER,s),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,i,0),s}connect(i,...r){return i.addInput(this,...r),this.output=i,i}addInput(i,...r){this.input=i,this.matchInputSize&&i.width&&i.height&&this.resize(i.width,i.height)}requestFrame(i){const r=Date.now();return!!(this.context instanceof Wj&&this.render(i)||this.context instanceof pk&&this.render2d(i))&&(this.totalFrames++,this.cost=Date.now()-r,!0)}render2d(i){var r;return!!((r=this.input)!=null&&r.requestFrame(i))&&this.draw2d(this.input.image,0,0,this.width,this.height)}update(i=0){var r;(r=this.output)==null||r.update(i)}disconnect(...i){var r;(r=this.output)==null||r.removeInput(this,...i),delete this.output}removeInput(i,...r){delete this.input}close(){var i,r;if(this.context.off("disconnect",this.close,this),(i=this.output)==null||i.removeInput(this),delete this.output,(r=this.input)==null||r.disconnect(),this.context instanceof Wj){const s=this.context.ctx;s.deleteBuffer(this.texCoordBuffer),s.deleteBuffer(this.positionBuffer),this.fbo&&s.deleteFramebuffer(this.fbo),this.texture&&s.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&s.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&s.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&s.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 r=this.context.ctx;i.forEach((s,g)=>{s&&(r.activeTexture(r.TEXTURE0+g),r.bindTexture(r.TEXTURE_2D,s))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){const i=this.context.ctx;i.bindFramebuffer(i.FRAMEBUFFER,this.fbo||null)}createBuffer(i){const r=this.context.ctx,s=r.createBuffer();return r.bindBuffer(r.ARRAY_BUFFER,s),r.bufferData(r.ARRAY_BUFFER,new Float32Array(i),r.STATIC_DRAW),s}setTexBuffer(i){const r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.texCoordBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(i),r.STATIC_DRAW)}setPosBuffer(i){const r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.positionBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(i),r.STATIC_DRAW)}changeBufferData(i,r){const s=this.context.ctx;s.bindBuffer(s.ARRAY_BUFFER,i),s.bufferData(s.ARRAY_BUFFER,new Float32Array(r),s.STATIC_DRAW)}setAttributes(...i){const r=this.context.ctx;i.forEach((s,g)=>{r.enableVertexAttribArray(g),r.bindBuffer(r.ARRAY_BUFFER,s),r.vertexAttribPointer(g,2,r.FLOAT,!1,0,0)})}getVertexPoint(i,r){return[i/this.width*2-1,r/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,r){if(this.width!==i||this.height!==r){if(this.width=i,this.height=r,this._canvas&&(this._canvas.width=i,this._canvas.height=r),this.texture&&this.fbo){this.useTexture();const s=this.context.ctx;s.texImage2D(s.TEXTURE_2D,0,s.RGBA,i,r,0,s.RGBA,s.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(i,r)}}draw(i,r){this.setAttributes(i||this.positionBuffer,r||this.texCoordBuffer);const s=this.context.ctx;s.drawArrays(s.TRIANGLE_STRIP,0,4)}draw2d(i,r,s,g,B,Q,f,m,M){const v=!(Fr(Q)||Fr(f)||Fr(m)||Fr(M));return!(!this.ctx2d||!i)&&(i instanceof ImageData?(v?this.ctx2d.putImageData(i,r,s,Q,f,m,M):this.ctx2d.putImageData(i,r,s),this.emit(jj.RENDER,this.ctx2d.canvas)):(v?this.ctx2d.drawImage(i,Q,f,m,M,r,s,g,B):this.ctx2d.drawImage(i,r,s,g,B),this.emit(jj.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:r,x:s,y:g,width:B,height:Q,name:f,cost:m}=this,M=Date.now(),v=(r-this.lastInfo.totalFrames)/((M-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:r,x:s,y:g,width:B,height:Q,timestamp:M,fps:v,name:f,cost:m},cr({parent:(i=this.input)==null?void 0:i.getInfo()},this.lastInfo)}createTexture(i){const r=this.context.ctx,s=r.createTexture();return this.useTextures(s),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,i),s}};OA(_G,"RENDER","render"),ss([FI(Lr.INIT,"connected",{sync:!0})],_G.prototype,"connect"),ss([FI("connected",Lr.INIT,{ignoreError:!0,sync:!0})],_G.prototype,"disconnect"),ss([FI([],"closed",{sync:!0})],_G.prototype,"close");var oY=_G,CEA=QC(zcA(250),zX(()=>performance.now()),KX()),BEA=t=>i=>{const r=performance.now();QC(CEA,oEA(s=>s-r{if(t!==this.context.frameRate&&(Lu.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof Wj){const i=this.context.ctx.getError();i&&this.context.destroy(new Ws({code:xa.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${i}`}))}},{fps:this.context.frameRate})}render(t){var i;return!!((i=this.input)!=null&&i.requestFrame(t))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(oY.RENDER,this.context._canvas),!0)}addInput(t,...i){super.addInput(t,...i),this.start(this.context.frameRate)}update(t=0){this.state!=="closed"&&(this._intervalId&&(Lu.clearTask(this._intervalId),this._intervalId=0,t===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(t){super.removeInput(t),Lu.clearTask(this._intervalId)}resize(t,i){super.resize(t,i),this.context.setSize(t,i)}close(){super.close(),Lu.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},dEA=class extends QEA{constructor(t,i){super(t,i),OA(this,"_videoTrack"),OA(this,"_muteOb"),OA(this,"_closedOb",Rc(this,"closed")),OA(this,"_subscription"),OA(this,"_canvasContainer"),Number(kk)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=t.canvas.captureStream().getVideoTracks(),this._muteOb=Rc(this._videoTrack,"mute"),QC(Rc(this._videoTrack,"ended"),Tw(this._closedOb),fD(()=>{this.context.destroy(new Ws({code:xa.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=QC(this._muteOb,Tw(this._closedOb),$X(BEA(5e3)),Rw(()=>{var t;return!!((t=this._videoTrack)!=null&&t.muted)&&!document.hidden}),fD(()=>{this.context.destroy(new Ws({code:xa.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var t;(t=this._subscription)==null||t.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(t){return this.putCanvasIntoDom(),super.render(t)}render2d(t){return this.putCanvasIntoDom(),super.render2d(t)}close(){var t,i;super.close(),(t=this._videoTrack)==null||t.stop(),delete this._videoTrack,(i=this._canvasContainer)==null||i.remove()}},e7=class extends oY{constructor(t,i){super(t,cr({name:"imageSource"},i)),OA(this,"_lastImage"),OA(this,"_totalFrames",0),OA(this,"_autoResize",!1),OA(this,"_canvasRendered"),OA(this,"videoCallbackId",0),OA(this,"waitingFirstFrame",!0),OA(this,"shouldUpdate",!0),this._autoResize=i?.autoResize!==!1,pD===16&&(this._canvasRendered=WX(),QC(this._canvasRendered,WcA(this._image),sEA(r=>r instanceof HTMLCanvasElement?Rc(r,"rendered"):XcA()),Tw(Rc(this,"closed")),fD(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;const t=this.image;this.videoCallbackId&&t.cancelVideoFrameCallback(this.videoCallbackId),AW()&&!document.hidden&&(this.videoCallbackId=t.requestVideoFrameCallback((i,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(t,i){var r;let{width:s,height:g}=this;const{image:B}=this;if(B instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:s,videoHeight:g}=B,!s||!g)return!1;B.width=s,B.height=g}else if(B instanceof HTMLImageElement||B instanceof ImageData||B instanceof ImageBitmap){if({width:s,height:g}=B,B!==this._lastImage)this._lastImage=B;else if(s===this.width&&g===this.height)return!0}else B instanceof HTMLCanvasElement||B instanceof OffscreenCanvas?({width:s,height:g}=B,this._lastImage=B):typeof VideoFrame<"u"&&B instanceof VideoFrame&&({displayWidth:s,displayHeight:g}=B,(r=this._lastImage)==null||r.close(),this._lastImage=B);if(!this._autoResize)return!0;if(this.width===s&&this.height===g&&this.totalFrames){if(i){this.useTexture();const Q=this.context.ctx;Q.texSubImage2D(Q.TEXTURE_2D,0,0,0,Q.RGBA,Q.UNSIGNED_BYTE,B)}}else{if(i){this.useTexture();const Q=this.context.ctx;Q.texImage2D(Q.TEXTURE_2D,0,Q.RGBA,Q.RGBA,Q.UNSIGNED_BYTE,B)}this.resize(s,g)}return!0}get image(){return this._image}set image(t){var i;(i=this._canvasRendered)==null||i.next(t),this._image=t}render(t){return this._render(t,!0)}render2d(t){return this._render(t,!1)}},t7=class extends e7{constructor(t,i,r){super(t,r),this._player=i,this.name="videoPlayerSource",QC(Rc(this._player,vr.PLAYER_STATE_CHANGED),Tw(Rc(this,"closed")),Rw(({state:s})=>s==="PLAYING"),fD(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},hEA=class extends t7{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(t,i,r){super(t,new lp({id:r.name,track:i,muted:!0,container:null,objectFit:"contain",log:r.logger}),r),this.name="videoTrackSource",this._player.play()}replaceTrack(t){this.waitingFirstFrame=!0,this._player.setTrack(t),this._player.play()}close(){super.close(),this._player.stop()}},pEA=class extends oY{constructor(t,i,r){super(t,lB(cr({name:"textSource"},r),{create2d:!0})),OA(this,"hasChange",!0),OA(this,"content",""),this.ctx2d.textBaseline="top",this.content=i.content||"",i.font&&(this.font=i.font),i.color&&(this.color=i.color)}set font(t){this.ctx2d&&(this.ctx2d.font=t,this.hasChange=!0)}get font(){var t;return((t=this.ctx2d)==null?void 0:t.font)||""}set color(t){this.ctx2d&&(this.ctx2d.fillStyle=t,this.hasChange=!0)}get color(){var t;return((t=this.ctx2d)==null?void 0:t.fillStyle)||""}render2d(t){return!(!this.ctx2d||!this.hasChange)&&(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0)}render(t){return!1}resize(t,i){if(!this.ctx2d)return;const{color:r,font:s}=this;super.resize(t,i),this.color=r,this.font=s}drawMultilineText(t=0,i=0,r=1.2){if(!this.ctx2d)return;const s=this.ctx2d.measureText(this.content);i+=s.fontBoundingBoxAscent||s.actualBoundingBoxAscent||0;const g=this.font.match(/(\d+)px/),B=(g?parseInt(g[1],10):16)*r,Q=this.content.split(` +`);for(let f=0;f{this.destroy(new Ws({code:xa.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(t){let i="";return t&&(i=t.message,this.error=t,qr.addFailedEvent({key:512702,error:t})),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),t}set width(t){var i;(i=this.ctx)==null||i.viewport(0,0,t,this.height),super.width=t,this._canvas2d&&(this._canvas2d.width=t)}set height(t){var i;(i=this.ctx)==null||i.viewport(0,0,this.width,t),super.height=t,this._canvas2d&&(this._canvas2d.height=t)}setSize(t,i){var r;(r=this.ctx)==null||r.viewport(0,0,t,i),super.setSize(t,i),this._canvas2d&&(this._canvas2d.width=t,this._canvas2d.height=i)}createShader(t,i){const r=this.ctx,s=r.createShader(t);return r.shaderSource(s,i),r.compileShader(s),s}createProgram(t,i){const r=this.ctx,s=r.createProgram();return r.attachShader(s,t),r.attachShader(s,i),r.linkProgram(s),r.getProgramParameter(s,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(s)),s}};OA(TG,"UNAVAILABLE","unavailable"),ss([FI(Lr.INIT,"created",{sync:!0,fail(t){this.log.error("video gl context create failed",t.cause),qr.addFailedEvent({key:512700,error:t.cause||t})},success(){this.log.info("video context created use webgl"),qr.addSuccessEvent({key:512700})}})],TG.prototype,"create"),ss([FI("created",Lr.INIT,{ignoreError:!0,sync:!0,success(t){t&&this.emit(TG.UNAVAILABLE,t),this.removeAllListeners()}})],TG.prototype,"destroy");var Jj=TG,Ck=class extends lk{constructor(){super(...arguments),OA(this,"ctx")}create(t){if(this.hasAlpha=t.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${lk._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:t.alpha,willReadFrequently:t.willReadFrequently}),!this.ctx)throw new Ws({code:xa.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(t){let i="";t&&(i=t.message,this.error=t,qr.addFailedEvent({key:512703,error:t})),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(),qr.addSuccessEvent({key:512703})}};ss([FI(Lr.INIT,"created",{sync:!0,fail(t){this.log.error("video 2d context create failed",t.cause),qr.addFailedEvent({key:512701,error:t.cause||t})},success(){this.log.info("video context created use 2d"),qr.addSuccessEvent({key:512701})}})],Ck.prototype,"create"),ss([FI("created",Lr.INIT,{ignoreError:!0,sync:!0})],Ck.prototype,"destroy");var eW=aX();if(typeof navigator<"u"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:eW,exposeOrigin:!0,permittedOrigins:["*"]})}catch{}var EEA=async function(t){let i=null;const r=BEA(t);qi.info(`getDisplayMedia with constraints: ${JSON.stringify(r)}`);const s=await navigator.mediaDevices.getDisplayMedia(r);t.systemAudio&&s.getAudioTracks().length===0&&(x3&&fp<74||IE||Ql)&&qi.warn("Your browser not support capture system audio");const g=s.getVideoTracks()[0];if(g){if(t.frameRate)try{await g.applyConstraints({frameRate:{min:t.frameRate,ideal:t.frameRate},width:t.width,height:t.height})}catch(B){qi.warn(`screen applyConstraints failed: ${B}`)}t.captureElement&&await lEA(g,t.captureElement)}if(t.audio){const B=CEA(t);qi.info(`getUserMedia with constraints: ${JSON.stringify(B)}`),i=await navigator.mediaDevices.getUserMedia(B),s.addTrack(i.getAudioTracks()[0])}return s};async function lEA(t,i){var r;if("CropTarget"in window&&"fromElement"in CropTarget&&oD(t.cropTo))try{if(((r=t.getCaptureHandle())==null?void 0:r.handle)!==eW)return;const s=await CropTarget.fromElement(i);await t.cropTo(s)}catch(s){qi.warn(`cropTo target failed ${s}`)}}function CEA(t){const i={echoCancellation:t.echoCancellation,autoGainControl:t.autoGainControl,noiseSuppression:t.noiseSuppression,sampleRate:t.sampleRate,channelCount:t.channelCount};return Fr(t.microphoneId)||(i.deviceId=t.microphoneId),{audio:i,video:!1}}function BEA(t){const i={preferCurrentTab:t.preferDisplaySurface==="current-tab"||!!t.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},r={width:IE?{max:t.width}:{ideal:t.width,max:t.width},height:IE?{max:t.height}:{ideal:t.height,max:t.height},frameRate:t.frameRate,displaySurface:t.preferDisplaySurface||"monitor"};if(i.video=r,t.systemAudio){const{echoCancellation:s=!0,noiseSuppression:g=!1,autoGainControl:B=!1}=t;i.audio={echoCancellation:s,noiseSuppression:g,autoGainControl:B,sampleRate:48e3}}return i}var uEA=EEA,QEA=class extends GY{constructor(t){super(t,2),OA(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),OA(this,"objectFit","contain"),OA(this,"isScreen",!0),this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var t,i;try{return eW===((i=(t=this.mediaTrack)==null?void 0:t.getCaptureHandle())==null?void 0:i.handle)}catch{return}}async capture({systemAudio:t=!1,autoGainControl:i,echoCancellation:r,noiseSuppression:s,audioTrack:g,videoTrack:B,captureElement:Q,preferDisplaySurface:f}){var m;try{const M=Ns();let v;return B||g?(v=new MediaStream,B&&v.addTrack(B),g&&v.addTrack(g)):(v=await uEA({audio:!1,systemAudio:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:i,echoCancellation:r,noiseSuppression:s,captureElement:Q,preferDisplaySurface:f}),this.sourceTrack=v.getVideoTracks()[0]),await this.setInputMediaStreamTrack(v.getVideoTracks()[0]),Eo.emit(nr.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Ns()-M,profile:this.profile,room:(m=this.manager)==null?void 0:m.room}),v}catch(M){throw this.log.error(`getDisplayMedia error observed ${M}`),M instanceof Ws?M:new Ws({code:xa.INITIALIZE_FAILED,name:M.name,message:M.message})}}async switchDevice(t){throw new Error("Method not implemented.")}};function dEA(t=30,i=2){return TY((r,s)=>function(...g){return new Promise((B,Q)=>{const f=setTimeout(()=>{const m=new Ws({code:xa.API_CALL_TIMEOUT,message:`checkPendingPromise ${s}() timeout ${t}s`});(this.log||this._log||qi).warn(m),i===2?Q(m):i===1&&B()},1e3*t);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(f),r.apply(this,g).then(B,Q).finally(()=>{clearTimeout(f),this._checkPendingPromiseSet&&f&&this._checkPendingPromiseSet.delete(f)})})})}ss([LX(function(t){this.setContentHint(t.contentHint||"detail")})],QEA.prototype,"capture");var ZM=class Hj extends $3{constructor(i,r,s){super({userId:r.userId,sdkAppId:i.sdkAppId,mediaType:s,room:i}),this.room=i,this.user=r,OA(this,"tinyId"),OA(this,"isRemote",!0),OA(this,"jitterBufferDelay",0),OA(this,"availableState"),OA(this,"remotePublishState"),OA(this,"_triggerCheckDecodeSubject",xX(Rc(this,Hj.STATE_SUBSCRIBE))),OA(this,"ignoreUpdatePlayingState"),this.tinyId=r.tinyId,this.availableState=new Lr(`${r.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new Lr(`${r.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),QC(OX(Rc(this,Lr.STATECHANGED),Rc(this.remotePublishState,Lr.STATECHANGED)),YX(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),dD(f=>{this.availableState.state!==(f?Lr.ON:Lr.OFF)&&(this.availableState.state=f?Lr.ON:Lr.OFF),this.isRemotePublished&&this.ignoreUpdatePlayingState||this.updatePlayingState(f)}));const g=QC(Rc(this.player,vr.ERROR),mw(f=>f.code===MediaError.MEDIA_ERR_DECODE)),B=QC(xcA(5e3),mw(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived||!this.isRemotePublished?!1:!(this.player.isPlaying||(this.kind===gt.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0))||(this.reportDecodeResult(!0),!1))),Q=QC(FcA(g,B),ww(Rc(this,Lr.INIT)));QC(this._triggerCheckDecodeSubject,mw(()=>!this.ignoreDecodeError),HX(Q),dD(f=>{this.reportDecodeResult(!1,f)}))}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,r,s,g;return(g=(s=(r=(i=this.room)==null?void 0:i.networkQuality)==null?void 0:r.hadRecentBadDownlink)==null?void 0:s.call(r,2))!=null&&g||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===Hj.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===Lr.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,r){var s,g;const B=this.kind===gt.AUDIO;if(qr[i?"addSuccessEvent":"addFailedEvent"]({key:B?504700:514702}),!B){const Q=((s=this.room)==null?void 0:s.downlinkVideoCodec.toUpperCase())||"H264";qr[i?"addSuccessEvent":"addFailedEvent"]({key:IX[`DECODE_${Q}_RESULT`]}),i||this.log.warn(`${(g=this.room)==null?void 0:g.downlinkVideoCodec} decode failed`)}i||(qr.addEnum({key:B?504701:514703,value:Y3()}),fC.uploadEvent({log:`stat-decode-failed-${this.kind}-${eX()||iX()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===gt.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:r}))}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?Lr.ON:Lr.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};OA(ZM,"STATE_SUBSCRIBE","subscribe"),ss([dEA(5,1)],ZM.prototype,"waitHasMediaTrack"),ss([FI(Lr.INIT,ZM.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),Eo.emit(nr.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),FX(521716,!1)],ZM.prototype,"subscribe"),ss([FI(ZM.STATE_SUBSCRIBE,Lr.INIT,{sync:!0,success(){this.log.info("unsubscribed"),Eo.emit(nr.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],ZM.prototype,"unsubscribe");var XK=new Map;function ns(t,i){const r=lB(cr({},i),{timestamp:m3()});XK.has(t)?XK.get(t).push(r):XK.set(t,[r])}Eo.on(nr.JOIN_SUCCESS,({room:t})=>{ns(t.userId,{eventId:32788})}),Eo.on(nr.LEAVE_START,({room:t})=>{ns(t.userId,{eventId:32789})}),Eo.on(nr.LOCAL_TRACK_PUBLISHED,({track:t})=>{if(t.room){let i=32769;t.mediaType===4?i=32768:t.mediaType===2&&(i=32805),ns(t.room.userId,{eventId:i})}}),Eo.on(nr.LOCAL_TRACK_UNPUBLISHED,({track:t})=>{if(t.room){let i=32771;t.mediaType===4?i=32770:t.mediaType===2&&(i=32806),ns(t.room.userId,{eventId:i})}}),Eo.on(nr.TRACK_MUTED,({track:t})=>{t.room&&(t.kind===gt.AUDIO?ns(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):ns(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))}),Eo.on(nr.TRACK_UNMUTED,({track:t})=>{t.room&&(t.kind===gt.AUDIO?ns(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):ns(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))}),Eo.on(nr.REMOTE_TRACK_SUBSCRIBED,({track:t})=>{t.room&&(t.mediaType===1&&ns(t.room.userId,{eventId:32777,remoteUserId:t.userId}),t.mediaType===4&&ns(t.room.userId,{eventId:32776,remoteUserId:t.userId}),t.mediaType===8&&ns(t.room.userId,{eventId:32803,remoteUserId:t.userId}))}),Eo.on(nr.REMOTE_TRACK_UNSUBSCRIBED,({track:t})=>{t.room&&(t.mediaType===1&&ns(t.room.userId,{eventId:32779,remoteUserId:t.userId}),t.mediaType===4&&ns(t.room.userId,{eventId:32778,remoteUserId:t.userId}),t.mediaType===8&&ns(t.room.userId,{eventId:32804,remoteUserId:t.userId}))}),Eo.on(nr.SWITCH_DEVICE_SUCCESS,({track:t})=>{t.room&&ns(t.room.userId,{eventId:t.kind===gt.VIDEO?32780:32781})}),Eo.on(nr.LOCAL_TRACK_REPLACED,({track:t})=>{t.room&&ns(t.room.userId,{eventId:t.kind===gt.VIDEO?32782:32783})}),Eo.on(nr.SIGNAL_CONNECTION_STATE_CHANGED,({room:t,prevState:i,state:r})=>{let s;switch(r){case"CONNECTED":s=i==="RECONNECTING"?32795:32791;break;case"DISCONNECTED":s=i==="RECONNECTING"?32796:32790;break;case"RECONNECTING":s=32794}s&&ns(t.userId,{eventId:s})}),Eo.on(nr.PEER_CONNECTION_STATE_CHANGED,({room:t,prevState:i,state:r,remoteUserId:s})=>{const g=!!s;let B;switch(r){case"CONNECTED":B=i==="RECONNECTING"?g?32801:32798:g?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(B=g?32802:32799);break;case"RECONNECTING":B=g?32800:32797}B&&ns(t.userId,{eventId:B,remoteUserId:s})}),Eo.on(nr.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:t,userId:i,remoteUserId:r,codec:s,isHWCodec:g,prevImplementation:B,streamType:Q})=>{let f=g?1:0;B||(f=g?3:2);const m={H264:0,H265:1,VP8:2}[s.toUpperCase()],M={eventId:4004,param1:f,param2:m,streamType:Q||2};r&&(M.remoteUserId=r,M.eventId=4005),ns(i,M),qr.addEnum({key:r?514701:513701,value:f}),qr.addEnum({key:r?514700:513700,value:m})}),Eo.on(nr.LOCAL_TRACK_RECAPTURE,({track:t,error:i})=>{if(t.userId){const r={eventId:2003,param1:0};t.kind===gt.AUDIO?(r.streamType=1,i&&(r.param1=2)):(r.streamType=t.streamType==="auxiliary"?7:2,i&&(r.param1=8)),ns(t.userId,r)}});Tw(mk());Tw(mk());var $K=0,jX=class WX{constructor(i){this.core=i,OA(this,"seq"),OA(this,"log"),OA(this,"localMixVideoTrack",null),OA(this,"systemAudioTrackList",{}),OA(this,"_mixVideoConfig"),OA(this,"onScreenShareStop"),OA(this,"eventListeners",new Map),$K+=1,this.seq=$K,this.log=i.log.createChild({id:`${this.getAlias()}${$K}`}),this.log.info("created")}getName(){return WX.Name}getAlias(){return"vmix"}getValidateRule(i){switch(i){case"start":return hsA(this.core);case"update":return psA(this.core);case"stop":return fsA(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:r,onScreenShareStop:s}=i,g=await this.parseMixOptions(i);return s&&(this.onScreenShareStop=s,this._mixVideoConfig.onScreenShareStop=s),this._updatePreview({view:r,track:this.localMixVideoTrack}),this.core.utils.isUndefined(r)||(this._mixVideoConfig.view=r),await this.localMixVideoTrack.startMix(),{track:this.localMixVideoTrack.outMediaTrack,systemAudioTrackList:this.systemAudioTrackList,result:g}}async update(i){const{RtcError:r,ErrorCode:s}=this.core.errorModule;if(!this.localMixVideoTrack)throw new r({code:s.INVALID_OPERATION,message:"mixTrack doesn't initialize!"});i=this.core.utils.deepCloneBasic(i);const{view:g}=i,B=await this.parseMixOptions(i);return await this._updatePreview({view:g,track:this.localMixVideoTrack,prevConfig:this._mixVideoConfig}),this.core.utils.isUndefined(g)||(this._mixVideoConfig.view=g),{track:this.localMixVideoTrack.outMediaTrack,systemAudioTrackList:this.systemAudioTrackList,result:B}}stop(){var i;this.eventListeners.forEach((r,s)=>{this.removeEventListeners(s)}),this.eventListeners.clear(),(i=this.localMixVideoTrack)==null||i.close(),this.localMixVideoTrack=null,Object.values(this.systemAudioTrackList).forEach(r=>r.stop()),this.systemAudioTrackList={},delete this.onScreenShareStop,delete this._mixVideoConfig}async parseMixOptions(i){const{RtcError:r,ErrorCode:s}=this.core.errorModule;if(!this.localMixVideoTrack||!this._mixVideoConfig)return{successOptions:{},failedDetails:[]};const g=[],B=cr({},i),{canvasInfo:Q,camera:f,screen:m,text:M,image:v,video:U}=i;Q&&this.parseCanvasOptions(Q);let AA=0,z=0;const sA=[{key:"camera",options:f,parser:this.parseCameraOptions.bind(this)},{key:"screen",options:m,parser:this.parseScreenOptions.bind(this)},{key:"text",options:M,parser:this.parseTextOptions.bind(this)},{key:"image",options:v,parser:this.parseImageOptions.bind(this)},{key:"video",options:U,parser:this.parseVideoOptions.bind(this)}];for(const{key:eA,options:X,parser:QA}of sA)if(X){AA++;const wA=await QA(this.localMixVideoTrack,X,this._mixVideoConfig[eA]||[]);this._mixVideoConfig[eA]=wA.finalOptions,B[eA]=wA.finalOptions,wA.errors.length>0&&(g.push(...wA.errors),wA.errors.length===X.length&&z++)}if(z>0&&z===AA)throw new r({code:s.INVALID_PARAMETER,message:"all sources mix failed",data:{failedDetails:g}});return{successOptions:B,failedDetails:g}}parseCanvasOptions(i){if(!this.localMixVideoTrack||!this._mixVideoConfig)return;const{canvasColor:r,width:s,height:g,frameRate:B}=i;r&&this.localMixVideoTrack.setMixBackground(r),B&&this.localMixVideoTrack.setFps(B),this.localMixVideoTrack.resizeMixCanvas(s,g),this._mixVideoConfig.canvasInfo=i}prepareSourceOptions(i,r){const s=new Set(i.map(g=>g.id));return{removeIdList:r.filter(g=>!s.has(g.id)).map(g=>g.id),preOptionsMap:new Map(r.map(g=>[g.id,g]))}}recordSourceError(i,r,s,g,B){B.push({id:i,error:r}),s.has(i)&&g.push(s.get(i))}async parseCameraOptions(i,r,s=[]){const{removeIdList:g,preOptionsMap:B}=this.prepareSourceOptions(r,s);this.log.debug("videomixer removeIdList",r,g,B);for(const m of g)i.removeCameraSource(m),this.removeEventListeners(m);const Q=[],f=[];for(const m of r)try{await this.processSingleCameraSource(i,m),Q.push(m)}catch(M){this.recordSourceError(m.id,M,B,Q,f)}return{finalOptions:Q,errors:f}}async processSingleCameraSource(i,r){const{id:s}=r;this.resolveCameraInternalTrack(i,r),i.inputLocalVideoTracks.has(s)?await this.updateExistingCameraSource(i,r):await this.addNewCameraSource(i,r)}async updateExistingCameraSource(i,r){var s,g;const{id:B,layout:Q,profile:f}=r,m=(s=i.inputLocalVideoTracks.get(B))==null?void 0:s.mediaTrack;await this.updateCameraProfile(r);const M=(g=i.inputLocalVideoTracks.get(B))==null?void 0:g.mediaTrack,v=this.resolveVideoProfile(f);M!==m?i.updateCameraSource(B,Q,M,v):i.updateCameraSource(B,Q,null,v)}resolveCameraInternalTrack(i,r){var s;const{id:g,layout:B,profile:Q,useInternalTrack:f}=r;if(f){if(i.inputLocalVideoTracks.get(g))return r;this.log.debug("resolve camera internal track",r,r.id,r.videoTrack),(s=this.core.trtc.localVideoTrack)!=null&&s.sourceTrack?(this.log.debug("resolve camera internal track outMediaTrack:",this.core.trtc.localVideoTrack.outMediaTrack,"sourceTrack:",this.core.trtc.localVideoTrack.sourceTrack),r.videoTrack=this.core.trtc.localVideoTrack.outMediaTrack,r.profile=this.core.trtc.localVideoTrack.profile):r.videoTrack=this.createPlaceholderVideoTrack(),this.removeEventListeners(g);const m=v=>{var U,AA;const z=i.inputLocalVideoTracks.get(g);this.log.debug(`camera internal track preprocessed event from ${(U=v.room)==null?void 0:U.userId} to ${this.core.room.userId}, is same instance:${v.room===this.core.room} ,new track:`,v.mediaTrack,z?.mediaTrack,i.outMediaTrack),((AA=v.mediaTrack)==null?void 0:AA.kind)!==gt.AUDIO&&z?.mediaTrack!==v.mediaTrack&&i.outMediaTrack!==v.mediaTrack&&v.room===this.core.room?z&&v.mediaTrack&&i.updateCameraSource(g,B,v.mediaTrack):this.log.debug("camera internal track preprocessed event return")},M=v=>{var U,AA,z,sA,eA,X,QA,wA;const HA=i.inputLocalVideoTracks.get(g);this.log.debug(`camera internal track stopped ${((U=v.track)==null?void 0:U.mediaTrack)===HA?.mediaTrack||((AA=v.track)==null?void 0:AA.outMediaTrack)===HA?.mediaTrack||((z=v.track)==null?void 0:z.outMediaTrack)===i.outMediaTrack}`,(sA=v.track)==null?void 0:sA.mediaTrack,(eA=v.track)==null?void 0:eA.outMediaTrack,HA?.mediaTrack,i.outMediaTrack),!HA||((X=v.track)==null?void 0:X.mediaTrack)!==HA?.mediaTrack&&((QA=v.track)==null?void 0:QA.outMediaTrack)!==HA?.mediaTrack&&((wA=v.track)==null?void 0:wA.outMediaTrack)!==i.outMediaTrack||i.updateCameraSource(g,B,this.createPlaceholderVideoTrack())};this.core.innerEmitter.on("118",m),this.core.innerEmitter.on("117",M),this.eventListeners.has(g)||this.eventListeners.set(g,{}),this.eventListeners.get(g).captureSuccess=()=>{this.core.innerEmitter.off("118",m)},this.eventListeners.get(g).trackStop=()=>{this.core.innerEmitter.off("117",M)}}return r}async addNewCameraSource(i,r){const{id:s,layout:g,useInternalTrack:B}=r,Q=await this.captureCamera(r);try{i.addCameraSource(s,Q,g)}catch(f){throw Q.close(),f}}resolveVideoProfile(i){if(!this.core.utils.isUndefined(i))return this.core.utils.isString(i)?this.core.constants.videoProfileMap[i]:i}async parseScreenOptions(i,r,s=[]){const{removeIdList:g,preOptionsMap:B}=this.prepareSourceOptions(r,s);for(const m of g)i.removeScreenSource(m),this.removeSystemAudioTrack(m),this.removeEventListeners(m);const Q=[],f=[];for(const m of r)try{await this.processSingleScreenSource(i,m,B),Q.push(m)}catch(M){this.recordSourceError(m.id,M,B,Q,f)}return{finalOptions:Q,errors:f}}async processSingleScreenSource(i,r,s){const{id:g,layout:B,useInternalTrack:Q}=r;this.resolveScreenInternalTrack(i,r);const f=s.get(g),m=i.inputLocalScreenTracks.has(g),M=!f?.systemAudio&&r.systemAudio;m&&!M?this.updateExistingScreenSource(i,g,B,f,r):await this.addNewScreenSource(i,r,f)}updateExistingScreenSource(i,r,s,g,B){i.updateScreenSource(r,s),g?.systemAudio&&!B.systemAudio&&this.removeSystemAudioTrack(r)}resolveScreenInternalTrack(i,r){var s,g;const{id:B,layout:Q,useInternalTrack:f}=r;if(f){if(i.inputLocalScreenTracks.get(B))return r;this.log.debug("resolve screen internal track",r,r.id,r.videoTrack),(s=this.core.trtc.localScreenTrack)!=null&&s.sourceTrack?(r.videoTrack=this.core.trtc.localScreenTrack.sourceTrack,r.profile=this.core.trtc.localScreenTrack.profile,(g=this.core.trtc.localScreenAudioTrack)!=null&&g.mediaTrack&&(r.audioTrack=this.core.trtc.localScreenAudioTrack.mediaTrack),delete r.captureElement,delete r.preferDisplaySurface,delete r.systemAudio):r.videoTrack=this.createPlaceholderVideoTrack(),this.removeEventListeners(B);const m=v=>{var U,AA,z,sA,eA,X,QA;const wA=i.inputLocalScreenTracks.get(B);this.log.debug(`screen internal track capture success event from ${(U=v.room)==null?void 0:U.userId} to ${this.core.room.userId}, is same instance:${v.room===this.core.room}, isScreen:${(AA=v.track)==null?void 0:AA.isScreen} kind:${(z=v.track)==null?void 0:z.kind}`,wA,v.track.sourceTrack),(sA=v.track)!=null&&sA.isScreen&&((eA=v.track)==null?void 0:eA.kind)!==gt.AUDIO&&wA&&(this.log.debug("screen internal track capture success event ",(X=v.track)==null?void 0:X.sourceTrack),(QA=v.track)!=null&&QA.sourceTrack&&i.updateScreenSource(B,Q,v.track.sourceTrack))},M=v=>{var U,AA;const z=i.inputLocalScreenTracks.get(B);this.log.debug(`screen internal track stopped, is same track:${((U=v.track)==null?void 0:U.sourceTrack)===z?.mediaTrack}, isScreen:${v.track.isScreen}`),v.track.isScreen&&((AA=v.track)==null?void 0:AA.sourceTrack)===z?.mediaTrack&&i.updateScreenSource(B,Q,this.createPlaceholderVideoTrack())};this.core.innerEmitter.on("102",m),this.core.innerEmitter.on("117",M),this.eventListeners.has(B)||this.eventListeners.set(B,{}),this.eventListeners.get(B).captureSuccess=()=>{this.core.innerEmitter.off("102",m)},this.eventListeners.get(B).trackStop=()=>{this.core.innerEmitter.off("117",M)}}return r}async addNewScreenSource(i,r,s){const{id:g,layout:B}=r,Q=await this.captureScreen(r);!s?.systemAudio&&r.systemAudio&&i.inputLocalScreenTracks.has(g)&&i.removeScreenSource(g);try{i.addScreenSource(g,Q,B)}catch(f){throw Q.close(),f}}async parseTextOptions(i,r,s=[]){const{removeIdList:g,preOptionsMap:B}=this.prepareSourceOptions(r,s);for(const m of g)i.removeTextSource(m);const Q=[],f=[];for(const m of r)try{B.has(m.id)?i.updateTextSource(m):i.addTextSource(m),Q.push(m)}catch(M){this.recordSourceError(m.id,M,B,Q,f)}return{finalOptions:Q,errors:f}}async parseImageOptions(i,r,s=[]){const{removeIdList:g,preOptionsMap:B}=this.prepareSourceOptions(r,s);for(const m of g)i.removeImageSource(m);const Q=[],f=[];for(const m of r)try{await this.processSingleImageSource(i,m,B),Q.push(m)}catch(M){this.recordSourceError(m.id,M,B,Q,f)}return{finalOptions:Q,errors:f}}async processSingleImageSource(i,r,s){const{id:g,url:B,layout:Q}=r,f=s.get(g);if(f){let m;f.url!==B&&(m=await this.core.utils.loadImage(B)),i.updateImageSource(g,Q,m)}else{const m=await this.core.utils.loadImage(B);i.addImageSource(g,m,Q)}}async parseVideoOptions(i,r,s=[]){const{removeIdList:g,preOptionsMap:B}=this.prepareSourceOptions(r,s);for(const m of g)i.removeVideoSource(m);const Q=[],f=[];for(const m of r)try{await this.processSingleVideoSource(i,m,B),Q.push(m)}catch(M){this.recordSourceError(m.id,M,B,Q,f)}return{finalOptions:Q,errors:f}}async processSingleVideoSource(i,r,s){const{id:g,url:B,layout:Q}=r,f=s.get(g);if(f){let m;f.url!==B&&(m=await this.core.utils.loadVideo(B)),i.updateVideoSource(g,Q,m)}else{const m=await this.core.utils.loadVideo(B);i.addVideoSource(g,m,Q)}}createPlaceholderVideoTrack(){const i=document.createElement("canvas");i.width=1,i.height=1;const r=i.getContext("2d");if(!r)return i.captureStream(30).getVideoTracks()[0];let s=null;const g=1e3/30,B=i.captureStream(30).getVideoTracks()[0],Q=()=>{r.fillStyle="rgba(255, 255, 255, 0)",r.fillRect(0,0,i.width,i.height),B.readyState==="live"&&(s=setTimeout(Q,g))};Q();const f=B.stop.bind(B);return B.stop=()=>{s&&(clearTimeout(s),s=null),f()},B}removeEventListeners(i){const r=this.eventListeners.get(i);r&&(r.captureSuccess&&r.captureSuccess(),r.trackStop&&r.trackStop(),this.eventListeners.delete(i))}async captureCamera(i){const{id:r,cameraId:s,videoTrack:g,profile:B}=i,Q=new this.core.LocalVideoTrack;Q.log.id+=`-${r}`;const f={};if(s?f.deviceId=s:this.core.utils.isUndefined(g)||(f.customSource=g),!this.core.utils.isUndefined(B)){const m=this.resolveVideoProfile(B);m&&Q.setProfile(m)}return await Q.capture(f),Q}async updateCameraProfile(i){var r;const{id:s,cameraId:g,videoTrack:B,profile:Q}=i,f=(r=this.localMixVideoTrack)==null?void 0:r.inputLocalVideoTracks.get(s);if(f&&(g?await f.switchDevice(g):this.core.utils.isUndefined(B)||await f.setInputMediaStreamTrack(B),!this.core.utils.isUndefined(Q))){const m=this.resolveVideoProfile(Q);m&&f.setProfile(m),g&&f.isNeedToSwitchDevice(g)||await f.applyProfile()}}async captureScreen(i){const{id:r,profile:s,captureElement:g,preferDisplaySurface:B,systemAudio:Q,videoTrack:f,audioTrack:m}=i,M=new this.core.LocalScreenTrack;M.log.id+=`-${r}`;const v={captureElement:g,preferDisplaySurface:B,systemAudio:Q,videoTrack:f,audioTrack:m};if(!this.core.utils.isUndefined(s))if(this.core.utils.isString(s)){const AA=this.core.constants.screenProfileMap[s];AA&&M.setProfile(AA)}else M.setProfile(s);const U=await M.capture(v);return Q&&U.getAudioTracks().length>0?(this.systemAudioTrackList[r]=U.getAudioTracks()[0],this.log.info(`${r} system audio track captured`)):this.removeSystemAudioTrack(r),M.mediaTrack.addEventListener(this.core.constants.NAME.ENDED,()=>{this.handleScreenShareEnded(r)}),M}handleScreenShareEnded(i){var r,s,g;(r=this.localMixVideoTrack)==null||r.removeScreenSource(i),(s=this._mixVideoConfig)!=null&&s.screen&&(this._mixVideoConfig.screen=this._mixVideoConfig.screen.filter(B=>B.id!==i)),(g=this.onScreenShareStop)==null||g.call(this,i)}async _updatePreview({view:i,track:r,prevConfig:s}){if(this.core.utils.isUndefined(i)&&s?.view){const g=this.core.utils.getViewListFromView(s.view);return void(g.length>0&&await r.play(g))}if(!this.core.utils.isUndefined(i)){const g=this.core.utils.getViewListFromView(i);g.length>0?await r.play(g):r.stop()}}removeSystemAudioTrack(i){const r=this.systemAudioTrackList[i];r&&(r.stop(),this.log.info(`${i} system audio track stop`),delete this.systemAudioTrackList[i])}};OA(jX,"Name","VideoMixer");var zX=jX,hEA=zX;const pEA=Object.freeze(Object.defineProperty({__proto__:null,VideoMixer:zX,default:hEA},Symbol.toStringTag,{value:"Module"})),fEA=hk(pEA);var mEA=fG.exports,I8;function DEA(){return I8||(I8=1,function(t,i){(function(r,s){s(i,vrA(),enA,VaA,AsA,ssA,fEA)})(mEA,function(r,s,g,B,Q,f,m){function M(L){return L&&typeof L=="object"&&"default"in L?L:{default:L}}var v=M(s),U=M(m),AA=function(L,w){return AA=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(q,y){q.__proto__=y}||function(q,y){for(var T in y)Object.prototype.hasOwnProperty.call(y,T)&&(q[T]=y[T])},AA(L,w)},z=function(){return z=Object.assign||function(L){for(var w,q=1,y=arguments.length;q=0;CA--)(T=L[CA])&&($=(V<3?T($):V>3?T(w,q,$):T(w,q))||$);return V>3&&$&&Object.defineProperty(w,q,$),$}function eA(L,w,q,y){return new(q||(q=Promise))(function(T,V){function $(KA){try{NA(y.next(KA))}catch(C){V(C)}}function CA(KA){try{NA(y.throw(KA))}catch(C){V(C)}}function NA(KA){var C;KA.done?T(KA.value):(C=KA.value,C instanceof q?C:new q(function(E){E(C)})).then($,CA)}NA((y=y.apply(L,[])).next())})}function X(L,w){var q,y,T,V,$={label:0,sent:function(){if(1&T[0])throw T[1];return T[1]},trys:[],ops:[]};return V={next:CA(0),throw:CA(1),return:CA(2)},typeof Symbol=="function"&&(V[Symbol.iterator]=function(){return this}),V;function CA(NA){return function(KA){return function(C){if(q)throw new TypeError("Generator is already executing.");for(;V&&(V=0,C[0]&&($=0)),$;)try{if(q=1,y&&(T=2&C[0]?y.return:C[0]?y.throw||((T=y.return)&&T.call(y),0):y.next)&&!(T=T.call(y,C[1])).done)return T;switch(y=0,T&&(C=[2&C[0],T.value]),C[0]){case 0:case 1:T=C;break;case 4:return $.label++,{value:C[1],done:!1};case 5:$.label++,y=C[1],C=[0];continue;case 7:C=$.ops.pop(),$.trys.pop();continue;default:if(T=$.trys,!((T=T.length>0&&T[T.length-1])||C[0]!==6&&C[0]!==2)){$=0;continue}if(C[0]===3&&(!T||C[1]>T[0]&&C[1]=L.length&&(L=void 0),{value:L&&L[y++],done:!L}}};throw new TypeError(w?"Object is not iterable.":"Symbol.iterator is not defined.")}function wA(L,w,q){if(q||arguments.length===2)for(var y,T=0,V=w.length;T0&&ei[0]<4?1:+(ei[0]+ei[1])),!Es&&kg&&(!(ei=kg.match(/Edge\/(\d+)/))||ei[1]>=74)&&(ei=kg.match(/Chrome\/(\d+)/))&&(Es=+ei[1]);var Ba=Es,Mr=Gr.String,Cs=!!Object.getOwnPropertySymbols&&!$o(function(){var L=Symbol("symbol detection");return!Mr(L)||!(Object(L)instanceof Symbol)||!Symbol.sham&&Ba&&Ba<41}),Va=Cs&&!Symbol.sham&&typeof Symbol.iterator=="symbol",P=Object,F=Va?function(L){return typeof L=="symbol"}:function(L){var w=qo("Symbol");return fo(w)&&Gg(w.prototype,P(L))},EA=String,RA=TypeError,GA=function(L){if(fo(L))return L;throw RA(function(w){try{return EA(w)}catch{return"Object"}}(L)+" is not a function")},WA=function(L,w){var q=L[w];return Fo(q)?void 0:GA(q)},Ce=TypeError,ge=Object.defineProperty,we=function(L,w){try{ge(Gr,L,{value:w,configurable:!0,writable:!0})}catch{Gr[L]=w}return w},_e="__core-js_shared__",Ke=Gr[_e]||we(_e,{}),Bt=ue(function(L){(L.exports=function(w,q){return Ke[w]||(Ke[w]=q!==void 0?q:{})})("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"})}),Rt=Object,Ye=function(L){return Rt(Ha(L))},nt=ao({}.hasOwnProperty),ii=Object.hasOwn||function(L,w){return nt(Ye(L),w)},oi=0,Ko=Math.random(),Kt=ao(1 .toString),ro=function(L){return"Symbol("+(L===void 0?"":L)+")_"+Kt(++oi+Ko,36)},ks=Gr.Symbol,Zr=Bt("wks"),In=Va?ks.for||ks:ks&&ks.withoutSetter||ro,xr=function(L){return ii(Zr,L)||(Zr[L]=Cs&&ii(ks,L)?ks[L]:In("Symbol."+L)),Zr[L]},sI=TypeError,jo=xr("toPrimitive"),OI=function(L,w){if(!en(L)||F(L))return L;var q,y=WA(L,jo);if(y){if(q=Gi(y,L,w),!en(q)||F(q))return q;throw sI("Can't convert object to primitive value")}return function(T,V){var $,CA;if(fo($=T.toString)&&!en(CA=Gi($,T))||fo($=T.valueOf)&&!en(CA=Gi($,T)))return CA;throw Ce("Can't convert object to primitive value")}(L)},_g=function(L){var w=OI(L,"string");return F(w)?w:w+""},gI=Gr.document,ml=en(gI)&&en(gI.createElement),ua=function(L){return ml?gI.createElement(L):{}},II=!sn&&!$o(function(){return Object.defineProperty(ua("div"),"a",{get:function(){return 7}}).a!==7}),ZA=Object.getOwnPropertyDescriptor,Ag={f:sn?ZA:function(L,w){if(L=Gs(L),w=_g(w),II)try{return ZA(L,w)}catch{}if(ii(L,w))return gn(!Gi(gr.f,L,w),L[w])}},cI=sn&&$o(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),Bs=String,eg=TypeError,kr=function(L){if(en(L))return L;throw eg(Bs(L)+" is not an object")},EI=TypeError,Gt=Object.defineProperty,Dl=Object.getOwnPropertyDescriptor,xI="enumerable",_s="configurable",tg="writable",ka={f:sn?cI?function(L,w,q){if(kr(L),w=_g(w),kr(q),typeof L=="function"&&w==="prototype"&&"value"in q&&tg in q&&!q[tg]){var y=Dl(L,w);y&&y[tg]&&(L[w]=q.value,q={configurable:_s in q?q[_s]:y[_s],enumerable:xI in q?q[xI]:y[xI],writable:!1})}return Gt(L,w,q)}:Gt:function(L,w,q){if(kr(L),w=_g(w),kr(q),II)try{return Gt(L,w,q)}catch{}if("get"in q||"set"in q)throw EI("Accessors not supported");return"value"in q&&(L[w]=q.value),L}},wc=sn?function(L,w,q){return ka.f(L,w,gn(1,q))}:function(L,w,q){return L[w]=q,L},lE=Function.prototype,qa=sn&&Object.getOwnPropertyDescriptor,CE=ii(lE,"name"),yC={CONFIGURABLE:CE&&(!sn||sn&&qa(lE,"name").configurable)},us=ao(Function.toString);fo(Ke.inspectSource)||(Ke.inspectSource=function(L){return us(L)});var lI,ig,yl,_a=Ke.inspectSource,Qs=Gr.WeakMap,Rl=fo(Qs)&&/native code/.test(String(Qs)),YI=Bt("keys"),vo=function(L){return YI[L]||(YI[L]=ro(L))},Qa={},BE="Object already initialized",cn=Gr.TypeError,kt=Gr.WeakMap;if(Rl||Ke.state){var Gn=Ke.state||(Ke.state=new kt);Gn.get=Gn.get,Gn.has=Gn.has,Gn.set=Gn.set,lI=function(L,w){if(Gn.has(L))throw cn(BE);return w.facade=L,Gn.set(L,w),w},ig=function(L){return Gn.get(L)||{}},yl=function(L){return Gn.has(L)}}else{var PI=vo("state");Qa[PI]=!0,lI=function(L,w){if(ii(L,PI))throw cn(BE);return w.facade=L,wc(L,PI,w),w},ig=function(L){return ii(L,PI)?L[PI]:{}},yl=function(L){return ii(L,PI)}}var Sc={get:ig,enforce:function(L){return yl(L)?ig(L):lI(L,{})}},tn=ue(function(L){var w=yC.CONFIGURABLE,q=Sc.enforce,y=Sc.get,T=String,V=Object.defineProperty,$=ao("".slice),CA=ao("".replace),NA=ao([].join),KA=sn&&!$o(function(){return V(function(){},"length",{value:8}).length!==8}),C=String(String).split("String"),E=L.exports=function(h,D,N){$(T(D),0,7)==="Symbol("&&(D="["+CA(T(D),/^Symbol\(([^)]*)\)/,"$1")+"]"),N&&N.getter&&(D="get "+D),N&&N.setter&&(D="set "+D),(!ii(h,"name")||w&&h.name!==D)&&(sn?V(h,"name",{value:D,configurable:!0}):h.name=D),KA&&N&&ii(N,"arity")&&h.length!==N.arity&&V(h,"length",{value:N.arity});try{N&&ii(N,"constructor")&&N.constructor?sn&&V(h,"prototype",{writable:!1}):h.prototype&&(h.prototype=void 0)}catch{}var O=q(h);return ii(O,"source")||(O.source=NA(C,typeof D=="string"?D:"")),h};Function.prototype.toString=E(function(){return fo(this)&&y(this).source||_a(this)},"toString")}),Ml=function(L,w,q,y){y||(y={});var T=y.enumerable,V=y.name!==void 0?y.name:w;if(fo(q)&&tn(q,V,y),y.global)T?L[w]=q:we(w,q);else{try{y.unsafe?L[w]&&(T=!0):delete L[w]}catch{}T?L[w]=q:ka.f(L,w,{value:q,enumerable:!1,configurable:!y.nonConfigurable,writable:!y.nonWritable})}return L},ba=Math.ceil,da=Math.floor,on=Math.trunc||function(L){var w=+L;return(w>0?da:ba)(w)},Xr=function(L){var w=+L;return w!=w||w===0?0:on(w)},wl=Math.max,bs=Math.min,vc=Math.min,CI=function(L){return L>0?vc(Xr(L),9007199254740991):0},uE=function(L){return CI(L.length)},RC=function(L){return function(w,q,y){var T,V=Gs(w),$=uE(V),CA=function(NA,KA){var C=Xr(NA);return C<0?wl(C+KA,0):bs(C,KA)}(y,$);if(L&&q!=q){for(;$>CA;)if((T=V[CA++])!=T)return!0}else for(;$>CA;CA++)if((L||CA in V)&&V[CA]===q)return L||CA||0;return!L&&-1}},Nc={indexOf:RC(!1)}.indexOf,Sl=ao([].push),JI=function(L,w){var q,y=Gs(L),T=0,V=[];for(q in y)!ii(Qa,q)&&ii(y,q)&&Sl(V,q);for(;w.length>T;)ii(y,q=w[T++])&&(~Nc(V,q)||Sl(V,q));return V},bg=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],QE=bg.concat("length","prototype"),vl={f:Object.getOwnPropertyNames||function(L){return JI(L,QE)}},Tc={f:Object.getOwnPropertySymbols},lo=ao([].concat),ds=qo("Reflect","ownKeys")||function(L){var w=vl.f(kr(L)),q=Tc.f;return q?lo(w,q(L)):w},QB=function(L,w,q){for(var y=ds(w),T=ka.f,V=Ag.f,$=0;$$;)ka.f(L,q=T[$++],y[q]);return L},bc={f:Nl},VI=qo("document","documentElement"),BI="prototype",pE="script",Lc=vo("IE_PROTO"),uI=function(){},Fg=function(L){return"<"+pE+">"+L+""},ja=function(L){L.write(Fg("")),L.close();var w=L.parentWindow.Object;return L=null,w},Fs=function(){try{Ka=new ActiveXObject("htmlfile")}catch{}var L,w,q;Fs=typeof document<"u"?document.domain&&Ka?ja(Ka):(w=ua("iframe"),q="java"+pE+":",w.style.display="none",VI.appendChild(w),w.src=String(q),(L=w.contentWindow.document).open(),L.write(Fg("document.F=Object")),L.close(),L.F):ja(Ka);for(var y=bg.length;y--;)delete Fs[BI][bg[y]];return Fs()};Qa[Lc]=!0;var No,Fc,Ug=Object.create||function(L,w){var q;return L!==null?(uI[BI]=kr(L),q=new uI,uI[BI]=null,q[Lc]=L):q=Fs(),w===void 0?q:bc.f(q,w)},vC=Gr.RegExp,fE=$o(function(){var L=vC(".","s");return!(L.dotAll&&L.exec(` -`)&&L.flags==="s")}),Tl=Gr.RegExp,Ou=$o(function(){var L=Tl("(?b)","g");return L.exec("b").groups.a!=="b"||"b".replace(L,"$c")!=="bc"}),fB=Sc.get,xu=Bt("native-string-replace",String.prototype.replace),Og=RegExp.prototype.exec,QI=Og,pi=ao("".charAt),mB=ao("".indexOf),Gl=ao("".replace),kl=ao("".slice),NC=(Fc=/b*/g,Gi(Og,No=/a/,"a"),Gi(Og,Fc,"a"),No.lastIndex!==0||Fc.lastIndex!==0),_l=hB.BROKEN_CARET,xg=/()??/.exec("")[1]!==void 0;(NC||xg||_l||fE||Ou)&&(QI=function(L){var w,q,y,T,V,$,CA,NA=this,KA=fB(NA),C=rg(L),E=KA.raw;if(E)return E.lastIndex=NA.lastIndex,w=Gi(QI,E,C),NA.lastIndex=E.lastIndex,w;var h=KA.groups,D=_l&&NA.sticky,N=Gi(Wr,NA),O=NA.source,Y=0,j=C;if(D&&(N=Gl(N,"y",""),mB(N,"g")===-1&&(N+="g"),j=kl(C,NA.lastIndex),NA.lastIndex>0&&(!NA.multiline||NA.multiline&&pi(C,NA.lastIndex-1)!==` -`)&&(O="(?: "+O+")",j=" "+j,Y++),q=new RegExp("^(?:"+O+")",N)),xg&&(q=new RegExp("^"+O+"$(?!\\s)",N)),NC&&(y=NA.lastIndex),T=Gi(Og,D?q:NA,j),D?T?(T.input=kl(T.input,Y),T[0]=kl(T[0],Y),T.index=NA.lastIndex,NA.lastIndex+=T[0].length):NA.lastIndex=0:NC&&T&&(NA.lastIndex=NA.global?T.index+T[0].length:y),xg&&T&&T.length>1&&Gi(xu,T[0],q,function(){for(V=1;V=CA?L?"":void 0:(y=jI(V,$))<55296||y>56319||$+1===CA||(T=jI(V,$+1))<56320||T>57343?L?TC(V,$):y:L?ha(V,$,$+2):T-56320+(y-55296<<10)+65536}},pa={charAt:wB(!0)}.charAt,sg=function(L,w,q){return w+(q?pa(L,w).length:1)},GC=TypeError,bl=function(L,w){var q=L.exec;if(fo(q)){var y=Gi(q,L,w);return y!==null&&kr(y),y}if(po(L)==="RegExp")return Gi(qI,L,w);throw GC("RegExp#exec called on incompatible receiver")};(function(L,w,q,y){var T=xr(L),V=!$o(function(){var KA={};return KA[T]=function(){return 7},""[L](KA)!==7}),$=V&&!$o(function(){var KA=!1,C=/a/;return L==="split"&&((C={}).constructor={},C.constructor[MB]=function(){return C},C.flags="",C[T]=/./[T]),C.exec=function(){return KA=!0,null},C[T](""),!KA});if(!V||!$||q){var CA=wr(/./[T]),NA=w(T,""[L],function(KA,C,E,h,D){var N=wr(KA),O=C.exec;return O===qI||O===Yg.exec?V&&!D?{done:!0,value:CA(C,E,h)}:{done:!0,value:N(E,C,h)}:{done:!1}});Ml(String.prototype,L,NA[0]),Ml(Yg,T,NA[1])}})("match",function(L,w,q){return[function(y){var T=Ha(this),V=Fo(y)?void 0:WA(y,L);return V?Gi(V,y,T):new RegExp(y)[L](rg(T))},function(y){var T=kr(this),V=rg(y),$=q(w,T,V);if($.done)return $.value;if(!T.global)return bl(T,V);var CA=T.unicode;T.lastIndex=0;for(var NA,KA=[],C=0;(NA=bl(T,V))!==null;){var E=rg(NA[0]);KA[C]=E,E===""&&(T.lastIndex=sg(V,CI(T.lastIndex),CA)),C++}return C===0?null:KA}]});var Mn=Array.isArray||function(L){return po(L)==="Array"},WI=TypeError,RE=function(L){if(L>9007199254740991)throw WI("Maximum allowed index exceeded");return L},dI=function(L,w,q){var y=_g(w);y in L?ka.f(L,y,gn(0,q)):L[y]=q},fs=function(){},Uc=[],ms=qo("Reflect","construct"),zI=/^\s*(?:class|function)\b/,xn=ao(zI.exec),Yu=!zI.exec(fs),Wo=function(L){if(!fo(L))return!1;try{return ms(fs,Uc,L),!0}catch{return!1}},Oc=function(L){if(!fo(L))return!1;switch(_c(L)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Yu||!!xn(zI,_a(L))}catch{return!0}};Oc.sham=!0;var ME,Pg=!ms||$o(function(){var L;return Wo(Wo.call)||!Wo(Object)||!Wo(function(){L=!0})||L})?Oc:Wo,gg=xr("species"),En=Array,Ds=function(L,w){return new(function(q){var y;return Mn(q)&&(y=q.constructor,(Pg(y)&&(y===En||Mn(y.prototype))||en(y)&&(y=y[gg])===null)&&(y=void 0)),y===void 0?En:y}(L))(0)},Wa=xr("species"),Ll=xr("isConcatSpreadable"),SB=Ba>=51||!$o(function(){var L=[];return L[Ll]=!1,L.concat()[0]!==L}),Pu=function(L){if(!en(L))return!1;var w=L[Ll];return w!==void 0?!!w:Mn(L)};Ir({target:"Array",proto:!0,arity:1,forced:!(SB&&(ME="concat",Ba>=51||!$o(function(){var L=[];return(L.constructor={})[Wa]=function(){return{foo:1}},L[ME](Boolean).foo!==1})))},{concat:function(L){var w,q,y,T,V,$=Ye(this),CA=Ds($),NA=0;for(w=-1,y=arguments.length;w=5||Math.abs(y)>=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)):Za.debug("".concat(this.logPrefix,"on Movable mouse move less than 5px"))},L.prototype.onMouseUp5px=function(){document.removeEventListener("mousemove",this.onMouseMove5px,!1),document.removeEventListener("mouseup",this.onMouseUp5px,!1)},L.prototype.onMouseMove=function(w){if(this.movable&&this.container){var q=w.screenX-this.moveStartOfLeft,y=w.screenY-this.moveStartOfTop,T=this.originLeft+q,V=this.originTop+y,$=this.movable.offsetWidth,CA=this.movable.offsetHeight,NA=this.container.offsetWidth,KA=this.container.offsetHeight;this.options.canExceedContainer||(T<0?T=0:T>NA-$&&(T=NA-$),V<0?V=0:V>KA-CA&&(V=KA-CA)),!this.options.calcPositionOnly&&this.movable&&(this.movable.style.left="".concat(T,"px"),this.movable.style.top="".concat(V,"px")),this.emit("move",T,V)}else Za.debug("".concat(this.logPrefix,"onMouseMove error:No 'movable' and 'container'."))},L.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},L.prototype.on=function(w,q){var y=this.callbacksMap.get(w);y?y.push(q):this.callbacksMap.set(w,[q])},L.prototype.off=function(w,q){var y=this.callbacksMap.get(w);y&&(y=y.filter(function(T){return T!=q}),this.callbacksMap.set(w,y))},L.prototype.emit=function(w){for(var q=[],y=1;y ").concat(w)),this.enabled=w,this.movable&&(this.movable.style.cursor=w?"move":"default",Za.debug("".concat(this.logPrefix,"setEnabled: cursor updated to '").concat(w?"move":"default","'")))},L.prototype.isEnabled=function(){return this.enabled},L}();(function(L){L[L.Both=0]="Both",L[L.Corner=1]="Corner",L[L.Edge=2]="Edge"})(Zn||(Zn={}));var Yl="trtc-resizable-top-left-anchor",UE="trtc-resizable-top-anchor",OE="trtc-resizable-top-right-anchor",Ac="trtc-resizable-left-anchor",ec="trtc-resizable-right-anchor",Xn="trtc-resizable-bottom-left-anchor",kn="trtc-resizable-bottom-anchor",ys="trtc-resizable-bottom-right-anchor",ln={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 wn(L,w){for(var q in w)L.style[q]=w[q]}var Kg=function(){function L(w,q,y){y===void 0&&(y={keepRatio:!1,stopPropagation:!1,anchorMode:Zn.Both,canExceedContainer:!1}),this.logPrefix="[Resizable]",this.container=null,this.options={keepRatio:!1,stopPropagation:!1,anchorMode:Zn.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=w,this.container=q||document.body,this.options={keepRatio:!!y.keepRatio||!1,stopPropagation:!!y.stopPropagation||!1,anchorMode:y.anchorMode||Zn.Both,canExceedContainer:!!y.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 L.prototype.createResizeAnchor=function(){var w,q,y,T,V,$,CA,NA,KA=document.createElement("div");KA.className="trtc-resizable-resize-anchor ".concat(Yl),wn(KA,Object.assign({},ln.resizeAnchor,ln.topLeftAnchor)),this.topLeftAnchor=KA;var C=document.createElement("div");C.className="trtc-resizable-resize-anchor ".concat(UE),wn(C,Object.assign({},ln.resizeAnchor,ln.topAnchor)),this.topAnchor=C;var E=document.createElement("div");E.className="trtc-resizable-resize-anchor ".concat(OE),wn(E,Object.assign({},ln.resizeAnchor,ln.topRightAnchor)),this.topRightAnchor=E;var h=document.createElement("div");h.className="trtc-resizable-resize-anchor ".concat(Ac),wn(h,Object.assign({},ln.resizeAnchor,ln.leftAnchor)),this.leftAnchor=h;var D=document.createElement("div");D.className="trtc-resizable-resize-anchor ".concat(ec),wn(D,Object.assign({},ln.resizeAnchor,ln.rightAnchor)),this.rightAnchor=D;var N=document.createElement("div");N.className="trtc-resizable-resize-anchor ".concat(Xn),wn(N,Object.assign({},ln.resizeAnchor,ln.bottomLeftAnchor)),this.bottomLeftAnchor=N;var O=document.createElement("div");O.className="trtc-resizable-resize-anchor ".concat(kn),wn(O,Object.assign({},ln.resizeAnchor,ln.bottomAnchor)),this.bottomAnchor=O;var Y=document.createElement("div");Y.className="trtc-resizable-resize-anchor ".concat(ys),wn(Y,Object.assign({},ln.resizeAnchor,ln.bottomRightAnchor)),this.bottomRightAnchor=Y,this.options.anchorMode!==Zn.Both&&this.options.anchorMode!==Zn.Edge||((w=this.resizeTarget)===null||w===void 0||w.appendChild(C),(q=this.resizeTarget)===null||q===void 0||q.appendChild(h),(y=this.resizeTarget)===null||y===void 0||y.appendChild(D),(T=this.resizeTarget)===null||T===void 0||T.appendChild(O)),this.options.anchorMode!==Zn.Both&&this.options.anchorMode!==Zn.Corner||((V=this.resizeTarget)===null||V===void 0||V.appendChild(KA),($=this.resizeTarget)===null||$===void 0||$.appendChild(E),(CA=this.resizeTarget)===null||CA===void 0||CA.appendChild(N),(NA=this.resizeTarget)===null||NA===void 0||NA.appendChild(Y))},L.prototype.initResizeEvent=function(){var w,q,y,T,V,$,CA,NA;(w=this.topLeftAnchor)===null||w===void 0||w.addEventListener("mousedown",this.mousedown,!1),(q=this.topAnchor)===null||q===void 0||q.addEventListener("mousedown",this.mousedown,!1),(y=this.topRightAnchor)===null||y===void 0||y.addEventListener("mousedown",this.mousedown,!1),(T=this.leftAnchor)===null||T===void 0||T.addEventListener("mousedown",this.mousedown,!1),(V=this.rightAnchor)===null||V===void 0||V.addEventListener("mousedown",this.mousedown,!1),($=this.bottomLeftAnchor)===null||$===void 0||$.addEventListener("mousedown",this.mousedown,!1),(CA=this.bottomAnchor)===null||CA===void 0||CA.addEventListener("mousedown",this.mousedown,!1),(NA=this.bottomRightAnchor)===null||NA===void 0||NA.addEventListener("mousedown",this.mousedown,!1)},L.prototype.mousedown=function(w){if(w.button===0){if(w.preventDefault(),this.options.stopPropagation&&w.stopPropagation(),this.currentAnchor=w.target,this.resizeStartLeft=w.screenX,this.resizeStartTop=w.screenY,document.defaultView&&this.resizeTarget){var q=document.defaultView.getComputedStyle(this.resizeTarget);this.originTop=window.parseInt(q.top),this.originLeft=window.parseInt(q.left),this.originWidth=this.resizeTarget.offsetWidth,this.originHeight=this.resizeTarget.offsetHeight,Za.debug("resize origin:",this.originTop,this.originLeft,this.originWidth,this.originHeight)}else Za.debug("".concat(this.logPrefix,"mouseDown 'resizeTarget' is null"));document.addEventListener("mousemove",this.mousemove,!1),document.addEventListener("mouseup",this.mouseup,!1)}},L.prototype.mousemove=function(w){if(this.container&&this.resizeTarget&&this.currentAnchor){var q,y=this.currentAnchor.classList[1],T=this.originLeft,V=this.originTop,$=this.originWidth,CA=this.originHeight;switch(y){case Yl:V=(q=this._resizeTop(w)).top,CA=q.height,T=(q=this._resizeLeft(w)).left,$=q.width,this.options.keepRatio&&($/this.originWidththis.container.offsetWidth-this.originLeft&&($=this.container.offsetWidth-this.originLeft,CA=this.originHeight*$/this.originWidth,V=this.originTop+this.originHeight-CA));break;case OE:V=(q=this._resizeTop(w)).top,CA=q.height,$=this._resizeRight(w),this.options.keepRatio&&($/this.originWidththis.container.offsetHeight-this.originTop&&(CA=this.container.offsetHeight-this.originTop,$=this.originWidth*CA/this.originHeight,T=this.originLeft+this.originWidth-$));break;case ec:$=this._resizeRight(w),this.options.keepRatio&&((CA=$*this.originHeight/this.originWidth)<20?$=(CA=20)*this.originWidth/this.originHeight:!this.options.canExceedContainer&&CA>this.container.offsetHeight-this.originTop&&($=(CA=this.container.offsetHeight-this.originTop)*this.originWidth/this.originHeight));break;case Xn:CA=this._resizeBottom(w),T=(q=this._resizeLeft(w)).left,$=q.width,this.options.keepRatio&&($/this.originWidththis.container.offsetWidth-this.originLeft&&(CA=($=this.container.offsetWidth-this.originLeft)*this.originHeight/this.originWidth));break;case ys:CA=this._resizeBottom(w),$=this._resizeRight(w),this.options.keepRatio&&($/this.originWidththis.originLeft+this.originWidth-20&&(y=this.originLeft+this.originWidth-20,T=20),{left:y,width:T}},L.prototype._resizeTop=function(w){var q=w.screenY-this.resizeStartTop,y=this.originTop+q,T=this.originHeight-q;return!this.options.canExceedContainer&&y<0?(y=0,T=this.originHeight+this.originTop):y>this.originTop+this.originHeight-20&&(y=this.originTop+this.originHeight-20,T=20),{top:y,height:T}},L.prototype._resizeRight=function(w){if(!this.container)return Za.debug("".concat(this.logPrefix,"_resizeRight error. No container:"),this.container),0;var q=w.screenX-this.resizeStartLeft,y=this.originWidth+q;return y<20?y=20:!this.options.canExceedContainer&&y>this.container.offsetWidth-this.originLeft&&(y=this.container.offsetWidth-this.originLeft),y},L.prototype._resizeBottom=function(w){if(!this.container)return Za.debug("".concat(this.logPrefix,"_resizeBottom error. No container:"),this.container),0;var q=w.screenY-this.resizeStartTop,y=this.originHeight+q;return y<20?y=20:!this.options.canExceedContainer&&y>this.container.offsetHeight-this.originTop&&(y=this.container.offsetHeight-this.originTop),y},L.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},L.prototype.on=function(w,q){var y=this.callbacksMap.get(w);y?y.push(q):this.callbacksMap.set(w,[q])},L.prototype.off=function(w,q){var y=this.callbacksMap.get(w);y&&(y=y.filter(function(T){return T!=q}),this.callbacksMap.set(w,y))},L.prototype.emit=function(w){for(var q=[],y=1;yT?y:T,this.previewWidth=this.mixingVideoWidth*this.previewScale,this.previewHeight=this.mixingVideoHeight*this.previewScale,this.previewLeft=(w-this.previewWidth)/2,this.previewTop=(q-this.previewHeight)/2}else console.debug("".concat(this.logPrefix,"calcPreviewScale failed, no HTML element to display"))},L.prototype.updateOverlay=function(){if(this.moveAndResizeOverlay){var w=void 0,q=void 0,y=void 0,T=void 0;if(this.selectedMediaIndex>=0){var V=this.mediaList[this.selectedMediaIndex],$={left:V.rect.left*this.previewScale,top:V.rect.top*this.previewScale,right:V.rect.right*this.previewScale,bottom:V.rect.bottom*this.previewScale};w="".concat($.left+this.previewLeft,"px"),q="".concat($.top+this.previewTop,"px"),y="".concat($.right-$.left,"px"),T="".concat($.bottom-$.top,"px");var CA=V.interaction||{},NA=CA.showBorder!==!1,KA=CA.showResizeAnchors!==!1,C=CA.draggable!==!1,E=CA.canExceedCanvas!==!1;this.logger.debug("".concat(this.logPrefix,"updateOverlay: interaction config -"),{showBorder:NA,showResizeAnchors:KA,draggable:C,canExceedCanvas:E}),this.updateCanExceedContainer(E),this.moveAndResizeOverlay.style.display="block",this.moveAndResizeOverlay.style.border=NA?"1px solid #3D7EFD":"none",this.resizableHandler&&this.resizableHandler.setVisible(KA),this.movableHandler&&(this.logger.debug("".concat(this.logPrefix,"updateOverlay: setting movableHandler.setEnabled(").concat(C,")")),this.movableHandler.setEnabled(C))}else w="".concat(this.previewLeft,"px"),q="".concat(this.previewTop,"px"),y="0px",T="0px",this.moveAndResizeOverlay.style.display="none";this.moveAndResizeOverlay.style.left=w,this.moveAndResizeOverlay.style.top=q,this.moveAndResizeOverlay.style.width=y,this.moveAndResizeOverlay.style.height=T}},L.prototype.onMove=function(w,q){var y;console.debug("".concat(this.logPrefix,"onMove: ").concat(w," ").concat(q));var T=this.mediaList[this.selectedMediaIndex];if(T&&this.moveAndResizeOverlay){var V={left:w-this.previewLeft,top:q-this.previewTop,right:w-this.previewLeft+this.moveAndResizeOverlay.offsetWidth,bottom:q-this.previewTop+this.moveAndResizeOverlay.offsetHeight};this.doAdsorption(V);var $={left:Math.round(V.left/this.previewScale),top:Math.round(V.top/this.previewScale),right:Math.round(V.right/this.previewScale),bottom:Math.round(V.bottom/this.previewScale)};(y=this.eventEmitter)===null||y===void 0||y.emit("onSourceMoved",z({},T),$)}else console.debug("".concat(this.logPrefix,"onMove no selected media"))},L.prototype.doAdsorption=function(w){var q=this.BOUNDARY_ADSORPTION_THRESHOLD;Math.abs(w.left)KA&&(KA=E,NA=w[C])}return NA},L.prototype.emitOnSelect=function(w){var q;if(w){for(var y=this.mediaList.length,T=0;T=C.rect.left&&CA<=C.rect.right&&NA>=C.rect.top&&NA<=C.rect.bottom&&((q=C.interaction)===null||q===void 0?void 0:q.selectable)!==!1&&(this.clickedMediaSources.push(C),this.mediaList[this.selectedMediaIndex]&&C.id===this.mediaList[this.selectedMediaIndex].id&&(this.oldSelectedIndex=this.clickedMediaSources.length-1))}this.mousedownLeft=w.screenX,this.mousedownTop=w.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)}},L.prototype.onContainerMousemove=function(w){var q;if(w.target&&this.container&&this.mousedownLeft!==null&&this.mousedownTop!==null){var y=w.screenX-this.mousedownLeft,T=w.screenY-this.mousedownTop;(Math.abs(y)>=5||Math.abs(T)>=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),(q=this.moveAndResizeOverlay)===null||q===void 0||q.dispatchEvent(new MouseEvent("mousedown",{screenX:this.mousedownLeft,screenY:this.mousedownTop,button:this.eventButton}))))}},L.prototype.onContainerMouseup=function(w){if(document.removeEventListener("mousemove",this.onContainerMousemove,!1),document.removeEventListener("mouseup",this.onContainerMouseup,!1),console.debug("".concat(this.logPrefix,"onContainerMouseup data:"),this.clickedMediaSources,this.oldSelectedIndex),w.target&&this.container){if(this.clickedMediaSources.length>0)if(this.oldSelectedIndex>=0){if(this.eventButton===0){var q=(this.oldSelectedIndex+1)%this.clickedMediaSources.length;this.newSelected=this.clickedMediaSources[q],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},L.prototype.onRightButtonClicked=function(w){var q;console.debug("".concat(this.logPrefix,"onRightButtonClicked:"),w.target,w.currentTarget,w.buttons),w.preventDefault(),(q=this.eventEmitter)===null||q===void 0||q.emit("onRightButtonClicked",z({},this.mediaList[this.selectedMediaIndex]))},L}(),Hc=function(){function L(w){if(this.logPrefix="[TRTCMediaMixingManager]",this.eventEmitter=new Dt,this.publishParams={videoEncoderParams:{videoResolution:r.TRTCVideoResolution.TRTCVideoResolution_1280_720,resMode:r.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,L.mediaMixingManager)return L.mediaMixingManager;L.mediaMixingManager=this,this.logger=w.logger,this.trtc=w.trtc,this.trtcCloud=w.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 L.prototype.destroy=function(){return eA(this,void 0,Promise,function(){var w,q,y,T,V;return X(this,function($){switch($.label){case 0:this.view=null,$.label=1;case 1:return $.trys.push([1,3,,4]),[4,this.trtc.stopPlugin("VideoMixer")];case 2:return $.sent(),[3,4];case 3:return w=$.sent(),this.logger.error("".concat(this.logPrefix," destroy and stopPlugin error:"),w),[3,4];case 4:if(!(this.screensWithSystemAudio.size>0))return[3,12];$.label=5;case 5:$.trys.push([5,10,,11]),q=0,y=Array.from(this.screensWithSystemAudio),$.label=6;case 6:return q1){var KA=[];this.queue=this.queue.filter(function(C,E){return E===0||C.functionName!==T||(KA.push(C),!1)}),KA.forEach(function(C){C.reject(new Error("aborted by newer task"))})}this.queue.push(CA)}return this.isRunning||this.callNext(),NA},L.prototype.shift=function(){return this.queue.shift()},L.prototype.callNext=function(){var w=this;if(!this.isRunning&&this.length!==0){var q=this.queue[0],y=q.fn,T=q.args,V=q.context,$=q.resolve,CA=q.reject;this.isRunning=!0,y.apply(V,T).then($,CA).finally(function(){w.isRunning=!1,w.shift(),w.callNext()})}},L}(),Vc=new WeakMap,Pl=new WeakMap,ma=new WeakMap;function tc(L,w){return w===void 0&&(w={}),function(q,y,T){var V=T.value,$=w.deduplicate,CA=$!==void 0&&$;return T.value=function(){for(var NA=[],KA=0;KA0;if(w&&!this.isMessageListenerRegistered)return this.trtc.on(v.default.EVENT.REALTIME_TRANSCRIBER_MESSAGE,this.handleMessageEvent),void(this.isMessageListenerRegistered=!0);!w&&this.isMessageListenerRegistered&&(this.trtc.off(v.default.EVENT.REALTIME_TRANSCRIBER_MESSAGE,this.handleMessageEvent),this.isMessageListenerRegistered=!1)},L.prototype.log=function(){for(var w,q,y=[],T=0;T0&&clearTimeout(xE),xE=window.setTimeout(function(){Hl.apply(L,w),xE=-1},qc)}));var YE=new Map,LB=function(L){function w(y){y===void 0&&(y={});var T=L.call(this)||this;T._version="",T._frameWorkType=30,T._component=0,T._language=0,T._networkProxy={},T._localView=null,T._autoRecvAudio=!0,T._autoRecvVideo=!1,T._localTestView=null,T._isVideoPublish=!0,T._localRenderParams={rotation:r.TRTCVideoRotation.TRTCVideoRotation0,fillMode:r.TRTCVideoFillMode.TRTCVideoFillMode_Fill,mirrorType:r.TRTCVideoMirrorType.TRTCVideoMirrorType_Auto},T._encoderMirror=void 0,T._videoProfile={},T._isAudioPublish=!0,T._audioMuteType=!1,T._audioProfile=v.default.TYPE.AUDIO_PROFILE_STANDARD,T._captureVolume=100,T._playoutVolume=100,T._isSharingScreen=!1,T._remoteStreamConfig=new Map,T._remoteStreamMap=new Map,T._cameraList=[],T._microphoneList=[],T._speakerList=[],T._currentCamera={},T._currentMicrophone={},T._currentSpeaker={},T._currentCameraId="",T._currentMicrophoneId="",T._currentSpeakerId="",T._screenShareParams={option:{}},T._isMobile=SE,T._isFrontCamera=!0,T._cameraVideoTrack=null,T._smallStreamVideoProfile=void 0,T._qosPreference=void 0,T._defaultVideoProfile={width:640,height:480,frameRate:15,bitrate:900},T._defaultScreenProfile={width:1920,height:1080,frameRate:15,bitrate:1500},T._defaultSmallVideoProfile={width:160,height:120,frameRate:15,bitrate:200},T._isVirtualBackground=!1,T._isTestVirtualBackground=!1,T._isBeautyEnabled=!1,T._isTestBeautyEnabled=!1,T._remoteStatisticsUserIdList=[],T._hasJoinedRoom=!1,T._isExitingRoom=!1,T._version=_B;var V=y.frameWorkType,$=V===void 0?30:V,CA=y.component,NA=CA===void 0?0:CA,KA=y.language,C=KA===void 0?0:KA;return T._frameWorkType=$,T._component=NA,T._language=C,T._trtc=v.default.create({enableSEI:w.enableSEI,assetsPath:w.assetsPath,enableVolumeControlInIOS:!0,plugins:[U.default,g.LEBPlayer,f.RealtimeTranscriber]}),T._testTrtc=v.default.create(),T._log=v.default._loggerManager,T.logger=new Os(Jl,{seq:Vl++}),T._echoCancellation=void 0,T._noiseSuppression=void 0,T._autoGainControl=void 0,T._addTRTCEvents(),T.handleDeviceChange=T.handleDeviceChange.bind(T),YE.set(T,{fn:T.handleDeviceChange,self:T}),T}var q;return function(y,T){if(typeof T!="function"&&T!==null)throw new TypeError("Class extends value "+String(T)+" is not a constructor or null");function V(){this.constructor=y}AA(y,T),y.prototype=T===null?Object.create(T):(V.prototype=T.prototype,new V)}(w,L),w.getPlugin=function(y){return y==="VirtualBackground"?B.VirtualBackground:y==="BasicBeauty"?Q.BasicBeauty:y==="VideoMixer"?U.default:null},w.getTRTCShareInstance=function(y){return w.shareInstance||(w.shareInstance=new w(y)),w.shareInstance},w.setLogLevel=function(y,T){var V,$=((V={})[r.TRTCLogLevel.TRTCLogLevelVerbose]=0,V[r.TRTCLogLevel.TRTCLogLevelDebug]=1,V[r.TRTCLogLevel.TRTCLogLevelInfo]=2,V[r.TRTCLogLevel.TRTCLogLevelWarn]=3,V[r.TRTCLogLevel.TRTCLogLevelError]=4,V[r.TRTCLogLevel.TRTCLogLevelFatal]=4,V[r.TRTCLogLevel.TRTCLogLevelNone]=5,V),CA=$[y];ho(CA)&&(CA=$[r.TRTCLogLevel.TRTCLogLevelInfo]);var NA=!$t(T)||T;v.default.setLogLevel(CA,NA)},w.destroyTRTCShareInstance=function(){w.shareInstance&&(w.shareInstance._destroy(),w.shareInstance=null),Array.from(w.subCloudMap.keys()).forEach(function(y){return y._destroy()})},w.callExperimentalAPI=function(y){console.log("static ".concat(Ci,".callExperimentalAPI"),y);var T=$r(y);if(T!==y){var V=T.api,$=T.params;if(V&&$)try{switch(V){case"enableSEI":w.enableSEI=$.enable;break;case"setAssetsPath":w.assetsPath=$.assetsPath}}catch(CA){throw CA}}},w.prototype.createSubCloud=function(){if(this!==w.shareInstance)return null;var y=new w;return this._inheritPropertiesToSubCloud(y),this._inheritEventsToSubCloud(y),w.subCloudMap.set(y,y),y},w.prototype.destroy=function(){this!==w.shareInstance?(w.subCloudMap.get(this)&&w.subCloudMap.delete(this),this._destroy()):w.destroyTRTCShareInstance()},w.prototype._destroy=function(){YE.delete(this),this.removeAllListeners(),this._trtc.off("*"),this._trtc.destroy(),this._trtc=null,this._testTrtc.off("*"),this._testTrtc.destroy(),this._testTrtc=null},w.prototype.getSDKVersion=function(){return this._version||""},w.prototype.enterRoom=function(y,T){return eA(this,void 0,Promise,function(){var V,$,CA,NA,KA,C,E,h,D,N,O,Y,j,IA,BA,mA,_A,xA;return X(this,function(Qe){switch(Qe.label){case 0:if(V=y.sdkAppId,$=y.userId,CA=y.userSig,NA=y.roomId,KA=y.strRoomId,C=y.role,E=y.privateMapKey,h=y.businessInfo,D=y.enableAutoPlayDialog,N=y.proxy,O=y.streamId,Y=y.userDefineRecordId,this.logger.update({sdkAppId:V,userId:$}),this.logger.info("".concat(Ci,".enterRoom with params: "),y,T),N&&(this._networkProxy=N),!(V&&$&&CA))return[3,5];Qe.label=1;case 1:return Qe.trys.push([1,3,,4]),j={sdkAppId:V,userId:$,userSig:CA,roomId:NA,strRoomId:KA,role:Vo[C],scene:et[T],autoReceiveAudio:this._autoRecvAudio,autoReceiveVideo:this._autoRecvVideo,frameWorkType:this._frameWorkType,component:this._component,language:this._language},j=E?z(z({},j),{privateMapKey:E}):j,j=h?z(z({},j),{businessInfo:h}):j,IA=D||this._enableAutoPlayDialog,j=$t(IA)?z(z({},j),{enableAutoPlayDialog:IA}):j,j=this._networkProxy?z(z({},j),{proxy:this._networkProxy}):j,j=O?z(z({},j),{streamId:O}):j,j=Y?z(z({},j),{userDefineRecordId:Y}):j,j=this._latencyLevel!==void 0?z(z({},j),{latencyLevel:this._latencyLevel}):j,BA=Qn(),[4,this._trtc.enterRoom(j)];case 2:return Qe.sent(),this._hasJoinedRoom=!0,mA=Qn()-BA,this.emit("onEnterRoom",mA),[3,4];case 3:return _A=Qe.sent(),xA=(xA=this._transformTRTCErrorCode(_A,"enterRoom"))<0?xA:-1,this.emit("onEnterRoom",xA),this._callFunctionErrorManage(_A,"enterRoom"),[3,4];case 4:return[3,6];case 5:this._emitError(Jc),Qe.label=6;case 6:return[2]}})})},w.prototype.exitRoom=function(){return eA(this,void 0,Promise,function(){var y;return X(this,function(T){switch(T.label){case 0:return T.trys.push([0,2,,3]),this.logger.info("".concat(Ci,".exitRoom")),this._isExitingRoom=!0,this._isSharingScreen&&this.stopScreenShare(),this.resetTRTCCloud(),this.stopLocalPreview(),this.stopLocalAudio(),[4,this._trtc.exitRoom()];case 1:return T.sent(),this._hasJoinedRoom=!1,this._isExitingRoom=!1,this._isVideoPublish=!0,this._isAudioPublish=!0,this.emit("onExitRoom",Vg.exitRoom),[3,3];case 2:return y=T.sent(),this._callFunctionErrorManage(y,"exitRoom"),[3,3];case 3:return[2]}})})},w.prototype.switchRole=function(y){return eA(this,void 0,void 0,function(){var T;return X(this,function(V){switch(V.label){case 0:this.logger.info("".concat(Ci,".switchRole with param: "),y),V.label=1;case 1:return V.trys.push([1,3,,4]),[4,this._trtc.switchRole(Vo[y])];case 2:return V.sent(),this.emit("onSwitchRole",0,"switch role success, role = ".concat(y,", ").concat(Vo[y])),[3,4];case 3:return T=V.sent(),this.emit("onSwitchRole",T?.getCode(),T.message),[3,4];case 4:return[2]}})})},w.prototype.setDefaultStreamRecvMode=function(y,T){return eA(this,void 0,void 0,function(){return X(this,function(V){return this.logger.info("".concat(Ci,".setDefaultStreamRecvMode with param: "),{autoRecvAudio:y,autoRecvVideo:T}),$t(y)&&(this._autoRecvAudio=y),$t(T)&&(this._autoRecvVideo=T),[2]})})},w.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()},w.prototype._updateLocalVideo=function(){return eA(this,void 0,void 0,function(){var y;return X(this,function(T){switch(T.label){case 0:return T.trys.push([0,2,,3]),[4,this._trtc.updateLocalVideo(this._generateLocalVideoData())];case 1:return T.sent(),[3,3];case 2:if((y=T.sent()).code!==v.default.ERROR_CODE.OPERATION_ABORT)throw y;return[3,3];case 3:return[2]}})})},w.prototype._updateLocalTestVideo=function(){return eA(this,void 0,void 0,function(){var y;return X(this,function(T){switch(T.label){case 0:return T.trys.push([0,2,,3]),[4,this._testTrtc.updateLocalVideo(this._generateLocalTestVideoData())];case 1:return T.sent(),[3,3];case 2:if((y=T.sent()).code!==v.default.ERROR_CODE.OPERATION_ABORT)throw y;return[3,3];case 3:return[2]}})})},w.prototype._updateLocalScreen=function(){return eA(this,void 0,void 0,function(){var y;return X(this,function(T){switch(T.label){case 0:return T.trys.push([0,2,,3]),[4,this._trtc.updateScreenShare(this._getScreenShareParams())];case 1:return T.sent(),[3,3];case 2:if((y=T.sent()).code!==v.default.ERROR_CODE.OPERATION_ABORT)throw y;return[3,3];case 3:return[2]}})})},w.prototype._updateRemoteVideo=function(y,T){return eA(this,void 0,void 0,function(){var V;return X(this,function($){switch($.label){case 0:if(!this._hasJoinedRoom||this._isExitingRoom)return[2];$.label=1;case 1:return $.trys.push([1,3,,4]),[4,this._trtc.updateRemoteVideo(this._generateRemoteVideoData(y,T))];case 2:return $.sent(),[3,4];case 3:if((V=$.sent()).code!==v.default.ERROR_CODE.OPERATION_ABORT)throw V;return[3,4];case 4:return[2]}})})},w.prototype.startLocalPreview=function(){for(var y=[],T=0;T9)throw new Error("beautyLevel must be between 0 and 9");if(CA<0||CA>9)throw new Error("whitenessLevel must be between 0 and 9");if(NA<0||NA>9)throw new Error("ruddinessLevel must be between 0 and 9");O.label=1;case 1:return O.trys.push([1,8,,9]),E=CA/9,h=NA/9,(C=$/9)===0&&E===0&&h===0?[4,y.stopPlugin(sr)]:[3,3];case 2:return O.sent(),KA?this._isTestBeautyEnabled=!1:this._isBeautyEnabled=!1,[3,7];case 3:return D={beauty:C,brightness:E,ruddy:h},T?[3,5]:[4,y.startPlugin(sr,D)];case 4:return O.sent(),KA?this._isTestBeautyEnabled=!0:this._isBeautyEnabled=!0,[3,7];case 5:return[4,y.updatePlugin(sr,D)];case 6:O.sent(),O.label=7;case 7:return[3,9];case 8:throw N=O.sent(),KA?this.logger.error("".concat(Ci,".").concat("setTestBeautyStyle"," fail: "),N):this.logger.error("".concat(Ci,".").concat("setBeautyStyle"," fail: "),N),N;case 9:return[2]}})})},w.prototype._resetBeautyStyle=function(){return eA(this,void 0,void 0,function(){return X(this,function(y){switch(y.label){case 0:return this._isBeautyEnabled?[4,this._trtc.stopPlugin(sr)]:[3,2];case 1:y.sent(),this._isBeautyEnabled=!1,y.label=2;case 2:return this._isTestBeautyEnabled?[4,this._testTrtc.stopPlugin(sr)]:[3,4];case 3:y.sent(),this._isTestBeautyEnabled=!1,y.label=4;case 4:return[2]}})})},w.prototype.getMicDevicesList=function(){return eA(this,void 0,Promise,function(){var y,T,V;return X(this,function($){switch($.label){case 0:this.logger.info("".concat(Ci,".getMicDevicesList")),$.label=1;case 1:return $.trys.push([1,5,,6]),[4,v.default.getMicrophoneList()];case 2:return y=$.sent(),T=y.map(function(CA){return z(z({},CA),{deviceName:CA.label})}),this._microphoneList=y,JSON.stringify(this._currentMicrophone)!=="{}"?[3,4]:(this._currentMicrophone=this.getDefaultDeviceInfo(y),this._currentMicrophoneId=this._currentMicrophone.deviceId,[4,this.setCurrentMicDevice(this._currentMicrophoneId)]);case 3:$.sent(),$.label=4;case 4:return[2,Promise.resolve(T)];case 5:return V=$.sent(),this._callFunctionErrorManage(V,"getMicDevicesList"),[2,Promise.resolve([])];case 6:return[2]}})})},w.prototype.setCurrentMicDevice=function(y){var T;return eA(this,void 0,Promise,function(){var V;return X(this,function($){switch($.label){case 0:this.logger.info("".concat(Ci,".setCurrentMicDevice with params: "),{micId:y}),$.label=1;case 1:return $.trys.push([1,4,,5]),y?(this._setCurrentMicrophoneId(y),[4,this._updateLocalAudio()]):[2,!1];case 2:return $.sent(),[4,this._updateLocalTestAudio()];case 3:return $.sent(),this._currentMicrophone=this._microphoneList.find(function(CA){return CA.deviceId===y})||{},[3,5];case 4:throw V=$.sent(),this._setCurrentMicrophoneId((T=this._currentMicrophone)===null||T===void 0?void 0:T.deviceId),this._callFunctionErrorManage(V,"setCurrentMicDevice"),V;case 5:return[2]}})})},w.prototype.getCurrentMicDevice=function(){this.logger.info("".concat(Ci,".getCurrentMicDevice"));var y=this._currentMicrophone,T=y.deviceId,V=y.label,$=y.kind,CA=y.groupId;return new qt(T,V,$,V,CA)},w.prototype.getSpeakerDevicesList=function(){return eA(this,void 0,Promise,function(){var y,T,V;return X(this,function($){switch($.label){case 0:this.logger.info("".concat(Ci,".getSpeakerDevicesList")),$.label=1;case 1:return $.trys.push([1,5,,6]),[4,v.default.getSpeakerList()];case 2:return y=$.sent(),T=y.map(function(CA){return z(z({},CA),{deviceName:CA.label})}),this._speakerList=y,JSON.stringify(this._currentSpeaker)!=="{}"?[3,4]:(this._currentSpeaker=this.getDefaultDeviceInfo(y),this._currentSpeakerId=this._currentSpeaker.deviceId,[4,this.setCurrentSpeakerDevice(this._currentSpeakerId)]);case 3:$.sent(),$.label=4;case 4:return[2,Promise.resolve(T)];case 5:return V=$.sent(),this._callFunctionErrorManage(V,"getSpeakerDevicesList"),[2,Promise.resolve([])];case 6:return[2]}})})},w.prototype.setCurrentSpeakerDevice=function(y){return eA(this,void 0,Promise,function(){var T;return X(this,function(V){switch(V.label){case 0:this.logger.info("".concat(Ci,".setCurrentSpeakerDevice with params: "),{speakerId:y}),V.label=1;case 1:return V.trys.push([1,3,,4]),y?[4,v.default.setCurrentSpeaker(y)]:[2,!1];case 2:return V.sent(),this._setCurrentSpeakerId(y),this._currentSpeaker=this._speakerList.find(function($){return $.deviceId===y})||{},[3,4];case 3:throw T=V.sent(),this._callFunctionErrorManage(T,"setCurrentSpeakerDevice"),T;case 4:return[2]}})})},w.prototype.getCurrentSpeakerDevice=function(){this.logger.info("".concat(Ci,".getCurrentSpeakerDevice"));var y=this._currentSpeaker,T=y.deviceId,V=y.label,$=y.kind,CA=y.groupId;return new qt(T,V,$,V,CA)},w.prototype.startCameraDeviceTest=function(y){return eA(this,void 0,void 0,function(){var T;return X(this,function(V){switch(V.label){case 0:if(this.logger.info("".concat(Ci,".startCameraDeviceTest with params: "),y),!y)return[2];this._setLocalTestView(y),V.label=1;case 1:return V.trys.push([1,3,,7]),[4,this._testTrtc.startLocalVideo(this._generateLocalTestVideoData())];case 2:return V.sent(),[3,7];case 3:return(T=V.sent()).code!==v.default.ERROR_CODE.OPERATION_ABORT?[3,5]:[4,this._updateLocalTestVideo()];case 4:return V.sent(),[3,6];case 5:throw this._callFunctionErrorManage(T,"startCameraDeviceTest"),T;case 6:return[3,7];case 7:return[2]}})})},w.prototype.stopCameraDeviceTest=function(){return eA(this,void 0,void 0,function(){return X(this,function(y){switch(y.label){case 0:return this.logger.info("".concat(Ci,".stopCameraDeviceTest")),this._setLocalTestView(null),[4,this._testTrtc.stopLocalVideo()];case 1:return y.sent(),[2]}})})},w.prototype.startMicDeviceTest=function(y){return eA(this,void 0,void 0,function(){var T,V=this;return X(this,function($){switch($.label){case 0:this.logger.info("".concat(Ci,".startMicDeviceTest with params: "),y),$.label=1;case 1:return $.trys.push([1,3,,7]),[4,this._testTrtc.startLocalAudio(this._generateLocalTestAudioData())];case 2:return $.sent(),[3,7];case 3:return(T=$.sent()).code!==v.default.ERROR_CODE.OPERATION_ABORT?[3,5]:[4,this._updateLocalTestAudio()];case 4:return $.sent(),[3,6];case 5:throw this._callFunctionErrorManage(T,"startMicDeviceTest"),T;case 6:return[3,7];case 7:return this._testTrtc.on(v.default.EVENT.AUDIO_VOLUME,function(CA){CA?.result.forEach(function(NA){var KA=NA.userId,C=NA.volume;KA===""&&V.emit("onTestMicVolume",C)})}),[4,this._testTrtc.enableAudioVolumeEvaluation(y)];case 8:return $.sent(),[2]}})})},w.prototype.stopMicDeviceTest=function(){return eA(this,void 0,void 0,function(){return X(this,function(y){switch(y.label){case 0:return this.logger.info("".concat(Ci,".stopMicDeviceTest")),[4,this._testTrtc.stopLocalAudio()];case 1:return y.sent(),[2]}})})},w.prototype.callExperimentalAPI=function(y){return eA(this,void 0,void 0,function(){var T,V,$;return X(this,function(CA){switch(CA.label){case 0:if(this.logger.info("".concat(Ci,".callExperimentalAPI"),y),(T=$r(y))===y)return[2];if(V=T.api,$=T.params,!V||!$)return[2];CA.label=1;case 1:switch(CA.trys.push([1,25,,26]),V){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($),[3,24];case 3:return this._echoCancellation=!!$.enable,[3,24];case 4:return this._noiseSuppression=!!$.enable,[3,24];case 5:return this._autoGainControl=!!$.enable,[3,24];case 6:return this._handleKeyMetricsStats($),[3,24];case 7:return this._networkProxy=$,[3,24];case 8:return[4,this.setVirtualBackground($)];case 9:return CA.sent(),[3,24];case 10:return[4,this.setTestVirtualBackground($)];case 11:return CA.sent(),[3,24];case 12:return[4,this.setTestBeautyStyle($.style,$.beautyLevel,$.whitenessLevel,$.ruddinessLevel)];case 13:return CA.sent(),[3,24];case 14:return this._setVideoEncodeParamEx($),[3,24];case 15:return this._enableAutoPlayDialog=!!$.enable,[3,24];case 16:return this._latencyLevel=$.latencyLevel,[3,24];case 17:return[4,this._switchPlaybackQuality($)];case 18:return CA.sent(),[3,24];case 19:return[4,this._requestPictureInPicture()];case 20:return CA.sent(),[3,24];case 21:return[4,this._exitPictureInPicture()];case 22:return CA.sent(),[3,24];case 23:return[3,24];case 24:return[3,26];case 25:throw CA.sent();case 26:return[2]}})})},w.prototype._handleSetFrameWork=function(y){var T=y.frameWork,V=y.component,$=y.language;jn(T)&&(this._frameWorkType=T),jn(V)&&(this._component=V),jn($)&&(this._language=$)},w.prototype._handleKeyMetricsStats=function(y){var T=y.key,V=y.opt,$=y.value,CA=y.version,NA=V===Kr;v.default._addKVStat({type:V,key:T,value:$,version:CA,useUV:NA,base:100})},w.prototype._setVideoEncodeParamEx=function(y){return eA(this,void 0,void 0,function(){return X(this,function(T){switch(T.label){case 0:switch(y.streamType){case r.TRTCVideoStreamType.TRTCVideoStreamTypeBig:return[3,1];case r.TRTCVideoStreamType.TRTCVideoStreamTypeSub:return[3,3]}return[3,5];case 1:return[4,this.setVideoEncoderParam(y)];case 2:case 4:return T.sent(),[3,6];case 3:return[4,this.setSubStreamEncoderParam(y)];case 5:return[3,6];case 6:return[2]}})})},w.prototype._switchPlaybackQuality=function(y){return eA(this,void 0,void 0,function(){var T,V,$,CA,NA,KA,C,E;return X(this,function(h){switch(h.label){case 0:if(V=(T=y||{}).quality,$=T.stream_list,CA=$===void 0?[]:$,!V||CA.length===0)return[2];for(NA=null,KA=0,C=CA;KA1&&T[1]),height:+(T.length>2&&T[2])}},w.prototype._getTRTCVideoProfile=function(y,T){T===void 0&&(T={});var V=T.videoWidth,$=T.videoHeight,CA=T.videoResolution,NA=T.videoFps,KA=T.videoBitrate,C=T.resMode,E=T.resolutionMode,h={};switch(y){case r.TRTCVideoStreamType.TRTCVideoStreamTypeSub:h=this._defaultScreenProfile;break;case r.TRTCVideoStreamType.TRTCVideoStreamTypeSmall:h=this._defaultSmallVideoProfile;break;case r.TRTCVideoStreamType.TRTCVideoStreamTypeBig:default:h=this._defaultVideoProfile}if(ho(CA))ho(V)||(h.width=V),ho($)||(h.height=$);else{var D=this._getTRTCResolution(CA);h.width=D.width,h.height=D.height}if(!ho(C)&&C===r.TRTCVideoResolutionMode.TRTCVideoResolutionModePortrait||!ho(E)&&E===r.TRTCVideoResolutionMode.TRTCVideoResolutionModePortrait){var N=h.height,O=h.width;h.width=N,h.height=O}return NA&&(h.frameRate=NA),KA&&(h.bitrate=KA),h},w.prototype._getTRTCStreamType=function(y){var T;return((T={})[r.TRTCVideoStreamType.TRTCVideoStreamTypeBig]=v.default.TYPE.STREAM_TYPE_MAIN,T[r.TRTCVideoStreamType.TRTCVideoStreamTypeSmall]=v.default.TYPE.STREAM_TYPE_MAIN,T[r.TRTCVideoStreamType.TRTCVideoStreamTypeSub]=v.default.TYPE.STREAM_TYPE_SUB,T)[y]},w.prototype._getTRTCFillMode=function(y){var T;return((T={})[r.TRTCVideoFillMode.TRTCVideoFillMode_Fill]=Hg.COVER,T[r.TRTCVideoFillMode.TRTCVideoFillMode_Fit]=Hg.CONTAIN,T)[y]},w.prototype._getTRTCCloudVideoFillMode=function(y){var T;return((T={})[Hg.COVER]=r.TRTCVideoFillMode.TRTCVideoFillMode_Fill,T[Hg.CONTAIN]=r.TRTCVideoFillMode.TRTCVideoFillMode_Fit,T)[y]},w.prototype._getTRTCCloudMirrorType=function(y){return y===!0?r.TRTCVideoMirrorType.TRTCVideoMirrorType_Enable:r.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable},w.prototype._getLocalRenderMirror=function(y){var T;return y===r.TRTCVideoMirrorType.TRTCVideoMirrorType_Auto?!this._getIsMobile()||this._getIsFrontCamera():((T={})[r.TRTCVideoMirrorType.TRTCVideoMirrorType_Enable]=!0,T[r.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable]=!1,T)[y]},w.prototype._getTRTCLocalMirror=function(y,T){var V=this._getLocalRenderMirror(y);return ho(T)?!!V&&"both":V&&T?"both":V&&!T?"view":!V&&T?"publish":!(!V&&!T)&&"view"},w.prototype._getTRTCRemoteMirror=function(y){var T;return((T={})[r.TRTCVideoMirrorType.TRTCVideoMirrorType_Auto]=!1,T[r.TRTCVideoMirrorType.TRTCVideoMirrorType_Enable]=!0,T[r.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable]=!1,T)[y]},w.prototype._getTRTCQosPreference=function(y){var T;return((T={})[r.TRTCVideoQosPreference.TRTCVideoQosPreferenceSmooth]=v.default.TYPE.QOS_PREFERENCE_SMOOTH,T[r.TRTCVideoQosPreference.TRTCVideoQosPreferenceClear]=v.default.TYPE.QOS_PREFERENCE_CLEAR,T)[y]},w.prototype._getTRTCAudioQuality=function(y){var T;return((T={})[r.TRTCAudioQuality.TRTCAudioQualitySpeech]=v.default.TYPE.AUDIO_PROFILE_STANDARD,T[r.TRTCAudioQuality.TRTCAudioQualityDefault]=v.default.TYPE.AUDIO_PROFILE_STANDARD,T[r.TRTCAudioQuality.TRTCAudioQualityMusic]=v.default.TYPE.AUDIO_PROFILE_HIGH_STEREO,T)[y]},w.prototype._getTRTCCloudDeviceType=function(y){return{camera:r.TRTCDeviceType.TRTCDeviceTypeCamera,microphone:r.TRTCDeviceType.TRTCDeviceTypeMic,speaker:r.TRTCDeviceType.TRTCDeviceTypeSpeaker}[y]},w.prototype._getTRTCCloudDeviceState=function(y){return{add:r.TRTCDeviceState.TRTCDeviceStateAdd,remove:r.TRTCDeviceState.TRTCDeviceStateRemove,active:r.TRTCDeviceState.TRTCDeviceStateActive}[y]},w.prototype._getTRTCCloudQuality=function(y){return[r.TRTCQuality.TRTCQuality_Unknown,r.TRTCQuality.TRTCQuality_Excellent,r.TRTCQuality.TRTCQuality_Good,r.TRTCQuality.TRTCQuality_Poor,r.TRTCQuality.TRTCQuality_Bad,r.TRTCQuality.TRTCQuality_Vbad,r.TRTCQuality.TRTCQuality_Down][y]},w.prototype._generateLocalVideoData=function(){var y={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?y&&Object.assign(y.option,{videoTrack:this._cameraVideoTrack}):this._getIsMobile()?y&&Object.assign(y.option,{useFrontCamera:this._getIsFrontCamera()}):y&&Object.assign(y.option,{cameraId:this._getCurrentCameraId()}),this._getQosPreference()&&y&&Object.assign(y.option,{qosPreference:this._getQosPreference()}),y},w.prototype._generateLocalTestVideoData=function(){var y={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()?y&&Object.assign(y.option,{useFrontCamera:this._getIsFrontCamera()}):y&&Object.assign(y.option,{cameraId:this._getCurrentCameraId()}),y},w.prototype._generateLocalAudioData=function(){var y={publish:this._getIsAudioPublish(),mute:this._getAudioMuteType(),muteKeepVolumeDetection:!0,option:{microphoneId:this._getCurrentMicrophoneId(),profile:this._getAudioProfile(),captureVolume:this._getCaptureVolume()}};return $t(this._echoCancellation)&&(y.option.echoCancellation=this._echoCancellation),$t(this._autoGainControl)&&(y.option.autoGainControl=this._autoGainControl),$t(this._noiseSuppression)&&(y.option.noiseSuppression=this._noiseSuppression),y},w.prototype._generateLocalTestAudioData=function(){return{publish:!1,option:{microphoneId:this._getCurrentMicrophoneId(),profile:this._getAudioProfile()}}},w.prototype._generateRemoteVideoData=function(y,T){return Tr(this._remoteStreamConfig.get("".concat(y,"_").concat(this._getTRTCStreamType(T))))},w.prototype._addTRTCEvents=function(){var y=this;this._trtc.on(v.default.EVENT.ERROR,function(T){T&&y.emit("onError",T.code,T.message)}),this._trtc.on(v.default.EVENT.REMOTE_USER_ENTER,function(T){T?.userId&&y.emit("onRemoteUserEnterRoom",T.userId)}),this._trtc.on(v.default.EVENT.REMOTE_USER_EXIT,function(T){T?.userId&&y.emit("onRemoteUserLeaveRoom",T.userId)}),this._trtc.on(v.default.EVENT.REMOTE_AUDIO_AVAILABLE,function(T){T?.userId&&y.emit("onUserAudioAvailable",T.userId,!0)}),this._trtc.on(v.default.EVENT.REMOTE_AUDIO_UNAVAILABLE,function(T){T?.userId&&y.emit("onUserAudioAvailable",T.userId,!1)}),this._trtc.on(v.default.EVENT.REMOTE_VIDEO_AVAILABLE,function(T){y._emitVideoAvailable(T,!0)}),this._trtc.on(v.default.EVENT.REMOTE_VIDEO_UNAVAILABLE,function(T){y._emitVideoAvailable(T,!1)}),this._trtc.on(v.default.EVENT.AUDIO_VOLUME,function(T){T?.result&&y.emit("onUserVoiceVolume",T?.result,(T?.result||[]).length)}),this._trtc.on(v.default.EVENT.KICKED_OUT,function(T){var V={banned:Vg.banned,room_disband:Vg.roomDisband};jn(V[T.reason])&&y.emit("onExitRoom",V[T.reason])}),this._trtc.on(v.default.EVENT.NETWORK_QUALITY,function(T){var V=T.uplinkNetworkQuality,$=T.downlinkNetworkQuality,CA=new lr("",y._getTRTCCloudQuality(V)),NA=[];y._remoteStatisticsUserIdList.length>0&&(NA=y._remoteStatisticsUserIdList.map(function(KA){return new lr(KA,y._getTRTCCloudQuality($))})),y.emit("onNetworkQuality",CA,NA)}),this._trtc.on(v.default.EVENT.AUTOPLAY_FAILED,function(T){y.emit("onAutoPlayFailed",T)}),this._trtc.on(v.default.EVENT.SEI_MESSAGE,function(T){if(T.data&&typeof T.data=="object"&&T.data instanceof ArrayBuffer){for(var V=new Uint8Array(T.data),$="",CA=0;CA0?E.video.map(function(IA){var BA=new Ji;return BA.width=IA.width,BA.height=IA.height,BA.frameRate=IA.frameRate,BA.videoBitrate=IA.bitrate,BA.audioBitrate=E.audio.bitrate||0,BA.streamType=D[IA.videoType],BA}):[];if(N.length===0&&E.audio.bitrate>0){var O=new Ji;O.audioBitrate=E.audio.bitrate||0,N.push(O)}var Y=[];h.forEach(function(IA){var BA=[],mA=IA.userId,_A=IA.audio.bitrate;if(IA.video&&IA.video.forEach(function(Qe){var Re=new Di;Re.userId=mA,Re.width=Qe.width,Re.height=Qe.height,Re.frameRate=Qe.frameRate,Re.videoBitrate=Qe.bitrate,Re.audioBitrate=_A||0,Re.streamType=D[Qe.videoType],BA.push(Re)}),BA.length===0){var xA=new Di;xA.userId=mA,xA.audioBitrate=_A||0,BA.push(xA)}Y.push.apply(Y,BA)});var j=new ar;j.upLoss=CA,j.downLoss=NA,j.rtt=$,j.sentBytes=KA,j.receivedBytes=C,j.localStatisticsArray=N,j.localStatisticsArraySize=N.length,j.remoteStatisticsArray=Y,j.remoteStatisticsArraySize=Y.length,y.emit("onStatistics",j)}),this._trtc.on(v.default.EVENT.SCREEN_SHARE_STOPPED,function(){y.emit("onScreenCaptureStopped",0),y._clearScreenShareParams(),y._isSharingScreen=!1}),this._trtc.on(v.default.EVENT.PUBLISH_STATE_CHANGED,function(T){var V=T.mediaType;T.state==="started"&&(V==="audio"?y.emit("onSendFirstLocalAudioFrame"):V==="video"?y.emit("onSendFirstLocalVideoFrame",r.TRTCVideoStreamType.TRTCVideoStreamTypeBig):V==="screen"&&y.emit("onSendFirstLocalVideoFrame",r.TRTCVideoStreamType.TRTCVideoStreamTypeSub))}),this._trtc.on(v.default.EVENT.FIRST_VIDEO_FRAME,function(T){var V=T.userId,$=T.streamType,CA=T.width,NA=T.height;y.emit("onFirstVideoFrame",V,$,CA,NA)}),this._trtc.on(v.default.EVENT.AUDIO_PLAY_STATE_CHANGED,function(T){var V=T.userId;T.state==="PLAYING"&&y.emit("onFirstAudioFrame",V)}),this._trtc.on(v.default.EVENT.DEVICE_CHANGED,function(T){var V=T.type,$=T.device,CA=T.action,NA=$.deviceId;if(CA==="active"){switch(V){case"camera":y._currentCameraId=NA,y._currentCamera=$;break;case"microphone":y._currentMicrophoneId=NA,y._currentMicrophone=$;break;case"speaker":y._currentSpeakerId=NA,y._currentSpeaker=$}y.emitOnDeviceChange(NA,y._getTRTCCloudDeviceType(V),y._getTRTCCloudDeviceState(CA))}}),this._trtc.on(v.default.EVENT.CUSTOM_MESSAGE,function(T){T&&y.emit("onRecvCustomCmdMsg",T.userId,T.cmdId,T.seq,T?.data)}),this._trtc.on(v.default.EVENT.CONNECTION_STATE_CHANGED,function(T){y._hasJoinedRoom&&!y._isExitingRoom&&(T.prevState==="CONNECTED"&&T.state==="DISCONNECTED"?y.emit("onConnectionLost"):T.prevState==="DISCONNECTED"&&T.state==="CONNECTING"?y.emit("onTryToReconnect"):T.prevState==="CONNECTING"&&T.state==="CONNECTED"&&y.emit("onConnectionRecovery"))}),this._trtc.on(v.default.EVENT.PICTURE_IN_PICTURE_STATE_CHANGED,function(T){y.emit("onPictureInPictureStateChanged",T)})},w.prototype._removeTRTCEvents=function(){this._trtc.off("*")},w.prototype._emitVideoAvailable=function(y,T){var V=y.userId,$=y.streamType;T?this._remoteStreamMap.set("".concat(V,"_").concat($),!0):this._remoteStreamMap.delete("".concat(V,"_").concat($)),$===v.default.TYPE.STREAM_TYPE_SUB?V&&this.emit("onUserSubStreamAvailable",V,T):V&&this.emit("onUserVideoAvailable",V,T)},w.prototype._setLocalView=function(y){this._localView=y},w.prototype._getLocalView=function(){return this._localView},w.prototype._setIsMobile=function(y){this._isMobile=y},w.prototype._getIsMobile=function(){return this._isMobile},w.prototype._setIsFrontCamera=function(y){this._isFrontCamera=y},w.prototype._getIsFrontCamera=function(){return this._isFrontCamera},w.prototype._getSmallStreamVideoProfile=function(){return this._smallStreamVideoProfile},w.prototype._setSmallStreamVideoProfile=function(y){this._smallStreamVideoProfile=y},w.prototype._setIsVideoPublish=function(y){this._isVideoPublish=y},w.prototype._getIsVideoPublish=function(){return this._isVideoPublish},w.prototype._setVideoProfile=function(y){this._videoProfile=y},w.prototype._getVideoProfile=function(){return this._videoProfile},w.prototype._setQosPreference=function(y){this._qosPreference=y},w.prototype._getQosPreference=function(){return this._qosPreference},w.prototype._setLocalTestView=function(y){this._localTestView=y},w.prototype._getLocalTestView=function(){return this._localTestView},w.prototype._setScreenShareParams=function(y){var T=y.view,V=y.systemAudio,$=y.fillMode,CA=y.profile,NA=y.videoTrack,KA=y.qosPreference;ho(T)||(this._screenShareParams.view=T),ho(V)||(this._screenShareParams.option.systemAudio=V),ho($)||(this._screenShareParams.option.fillMode=$),ho(CA)||(this._screenShareParams.option.profile=CA),ho(NA)||(this._screenShareParams.option.videoTrack=NA),ho(KA)||(this._screenShareParams.option.qosPreference=KA),ho(y.streamType)||(this._screenShareParams.streamType=this._getTRTCStreamType(y.streamType))},w.prototype._clearScreenShareParams=function(){var y,T,V,$,CA;!((y=this._screenShareParams)===null||y===void 0)&&y.view&&delete this._screenShareParams.view,!((V=(T=this._screenShareParams)===null||T===void 0?void 0:T.option)===null||V===void 0)&&V.systemAudio&&delete this._screenShareParams.option.systemAudio,!((CA=($=this._screenShareParams)===null||$===void 0?void 0:$.option)===null||CA===void 0)&&CA.videoTrack&&delete this._screenShareParams.option.videoTrack},w.prototype._getScreenShareParams=function(){return this._screenShareParams},w.prototype._setIsAudioPublish=function(y){this._isAudioPublish=y},w.prototype._getIsAudioPublish=function(){return this._isAudioPublish},w.prototype._setAudioMuteType=function(y){this._audioMuteType=y},w.prototype._getAudioMuteType=function(){return this._audioMuteType},w.prototype._setAudioProfile=function(y){this._audioProfile=y},w.prototype._getAudioProfile=function(){return this._audioProfile},w.prototype._getCaptureVolume=function(){return this._captureVolume},w.prototype._setCaptureVolume=function(y){this._captureVolume=y},w.prototype._setCurrentCameraId=function(y){this._currentCameraId=y},w.prototype._getCurrentCameraId=function(){return this._currentCameraId},w.prototype._setCurrentMicrophoneId=function(y){this._currentMicrophoneId=y},w.prototype._getCurrentMicrophoneId=function(){return this._currentMicrophoneId},w.prototype._setCurrentSpeakerId=function(y){this._currentSpeakerId=y},w.prototype._getCurrentSpeakerId=function(){return this._currentSpeakerId},w.prototype._setRemoteStreamConfig=function(y,T,V){var $=this._remoteStreamConfig.get("".concat(y,"_").concat(this._getTRTCStreamType(T)));$||($={userId:y,streamType:this._getTRTCStreamType(T),option:{mirror:this._getTRTCRemoteMirror(r.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable),fillMode:this._getTRTCFillMode(r.TRTCVideoFillMode.TRTCVideoFillMode_Fit)}});var CA=V.view,NA=V.mirrorType,KA=V.fillMode,C=V.small;ho(CA)||($.view=CA),ho(NA)||($.option.mirror=this._getTRTCRemoteMirror(NA)),ho(KA)||($.option.fillMode=this._getTRTCFillMode(KA)),ho(C)||($.option.small=C),this._remoteStreamConfig.set("".concat(y,"_").concat(this._getTRTCStreamType(T)),$)},w.prototype._inheritPropertiesToSubCloud=function(y){y._frameWorkType=this._frameWorkType,y._component=this._component,y._language=this._language,y._networkProxy=z({},this._networkProxy),y._latencyLevel=this._latencyLevel,y._enableAutoPlayDialog=this._enableAutoPlayDialog},w.prototype._inheritEventsToSubCloud=function(y){var T=this;y._trtc.on(v.default.EVENT.AUTOPLAY_FAILED,function(V){T.emit("onAutoPlayFailed",V)}),y._trtc.on(v.default.EVENT.PICTURE_IN_PICTURE_STATE_CHANGED,function(V){T.emit("onPictureInPictureStateChanged",V)})},w.prototype.handleDeviceChange=function(){return eA(this,void 0,void 0,function(){var y=this;return X(this,function(T){return v.default.getCameraList().then(function(V){return eA(y,void 0,void 0,function(){return X(this,function($){switch($.label){case 0:return this._cameraList.length===V.length?[2]:[4,this.deviceChangeManage(this._cameraList,V,r.TRTCDeviceType.TRTCDeviceTypeCamera)];case 1:return $.sent(),this._cameraList=V,[2]}})})}),v.default.getMicrophoneList().then(function(V){return eA(y,void 0,void 0,function(){return X(this,function($){switch($.label){case 0:return[4,this.deviceChangeManage(this._microphoneList,V,r.TRTCDeviceType.TRTCDeviceTypeMic)];case 1:return $.sent(),this._microphoneList=V,[2]}})})}),v.default.getSpeakerList().then(function(V){return eA(y,void 0,void 0,function(){return X(this,function($){switch($.label){case 0:return[4,this.deviceChangeManage(this._speakerList,V,r.TRTCDeviceType.TRTCDeviceTypeSpeaker)];case 1:return $.sent(),this._speakerList=V,[2]}})})}),[2]})})},w.prototype.isSameDevice=function(y,T){var V=y&&y.deviceId&&y.groupId&&y.label,$=T&&T.deviceId&&T.groupId&&T.label;return!(!V||!$)&&y.deviceId===T.deviceId&&y.groupId===T.groupId&&y.label===T.label},w.prototype.deviceChangeManage=function(y,T,V){return eA(this,void 0,void 0,function(){var $,CA,NA,KA,C;return X(this,function(E){switch(E.label){case 0:return $=void 0,y.length!==T.length&&(CA=(T||[]).map(function(h){return h.deviceId}),NA=new qt,y.length>T.length?(NA=y.filter(function(h){return!CA.includes(h.deviceId)})[0]||{},$=r.TRTCDeviceState.TRTCDeviceStateRemove):(CA=(y||[]).map(function(h){return h.deviceId}),NA=T.filter(function(h){return!CA.includes(h.deviceId)})[0]||{},$=r.TRTCDeviceState.TRTCDeviceStateAdd),KA=NA.deviceId,this.emitOnDeviceChange(KA,V,$)),C=this.getDefaultDeviceInfo(T),V!==r.TRTCDeviceType.TRTCDeviceTypeCamera||$!==r.TRTCDeviceState.TRTCDeviceStateRemove?[3,3]:this.isSameDevice(this._currentCamera,C)?[2]:C.deviceId?[4,this.autoChangeDevice(V,C)]:[3,2];case 1:E.sent(),E.label=2;case 2:E.label=3;case 3:return V!==r.TRTCDeviceType.TRTCDeviceTypeMic?[3,6]:this.isSameDevice(this._currentMicrophone,C)?[2]:C.deviceId?[4,this.autoChangeDevice(V,C)]:[3,5];case 4:E.sent(),E.label=5;case 5:E.label=6;case 6:return V!==r.TRTCDeviceType.TRTCDeviceTypeSpeaker?[3,9]:this.isSameDevice(this._currentSpeaker,C)?[2]:C.deviceId?[4,this.autoChangeDevice(V,C)]:[3,8];case 7:E.sent(),E.label=8;case 8:E.label=9;case 9:return[2]}})})},w.prototype.getDefaultDeviceInfo=function(y){var T=new qt;if(y.length===0)return T;var V=y.filter(function($){return $.deviceId==="default"});return T=V.length>0?V[0]:y[0]},w.prototype.autoChangeDevice=function(y,T){return eA(this,void 0,void 0,function(){var V,$,CA;return X(this,function(NA){switch(NA.label){case 0:return V=T.deviceId,y!==r.TRTCDeviceType.TRTCDeviceTypeCamera?[3,6]:(this._setCurrentCameraId(V),[4,this._updateLocalVideo()]);case 1:NA.sent(),NA.label=2;case 2:return NA.trys.push([2,4,,5]),[4,this._testTrtc.updateLocalVideo({option:{cameraId:V}})];case 3:return NA.sent(),[3,5];case 4:return $=NA.sent(),console.log("testTRTC error",JSON.stringify($)),$.code,v.default.ERROR_CODE.OPERATION_ABORT,[3,5];case 5:this._currentCameraId=V,this._currentCamera=T,this.emitOnDeviceChange(V,y,r.TRTCDeviceState.TRTCDeviceStateActive),NA.label=6;case 6:return y!==r.TRTCDeviceType.TRTCDeviceTypeMic?[3,12]:(this._setCurrentMicrophoneId(V),[4,this._updateLocalAudio()]);case 7:NA.sent(),NA.label=8;case 8:return NA.trys.push([8,10,,11]),[4,this._testTrtc.updateLocalAudio({option:{microphoneId:V}})];case 9:return NA.sent(),[3,11];case 10:return CA=NA.sent(),console.log("testTRTC error",JSON.stringify(CA)),CA.code,v.default.ERROR_CODE.OPERATION_ABORT,[3,11];case 11:this._currentMicrophoneId=V,this._currentMicrophone=T,this.emitOnDeviceChange(V,y,r.TRTCDeviceState.TRTCDeviceStateActive),NA.label=12;case 12:return y!==r.TRTCDeviceType.TRTCDeviceTypeSpeaker?[3,14]:[4,v.default.setCurrentSpeaker(V)];case 13:NA.sent(),this._currentSpeakerId=V,this._currentSpeaker=T,this.emitOnDeviceChange(V,y,r.TRTCDeviceState.TRTCDeviceStateActive),NA.label=14;case 14:return[2]}})})},w.prototype.emitOnDeviceChange=function(y,T,V){this.emit("onDeviceChange",y,T,V)},w.prototype.getMediaMixingManager=function(){return new Hc({logger:this.logger,trtc:this._trtc,trtcCloud:this})},w.prototype.getAITranscriberManager=function(){return new bB({logger:this.logger,trtc:this._trtc})},w.shareInstance=null,w.subCloudMap=new Map,w.enableSEI=!1,w.assetsPath="",sA([(q="exitRoom",function(y,T,V){var $=V.value;return V.value=function(){for(var CA,NA,KA,C,E=[],h=0;hb.length)&&(rA=b.length);for(var gA=0,pA=new Array(rA);gA=0;--Ar){var so=this.tryEntries[Ar],As=so.completion;if(so.tryLoc==="root")return Ti("end");if(so.tryLoc<=this.prev){var ic=vA.call(so,"catchLoc"),_C=vA.call(so,"finallyLoc");if(ic&&_C){if(this.prev=0;--Ti){var Ar=this.tryEntries[Ti];if(Ar.tryLoc<=this.prev&&vA.call(Ar,"finallyLoc")&&this.prev=0;--Qt){var Ti=this.tryEntries[Qt];if(Ti.finallyLoc===Ht)return this.complete(Ti.completion,Ti.afterLoc),bn(Ti),ft}},catch:function(Ht){for(var Qt=this.tryEntries.length-1;Qt>=0;--Qt){var Ti=this.tryEntries[Qt];if(Ti.tryLoc===Ht){var Ar=Ti.completion;if(Ar.type==="throw"){var so=Ar.arg;bn(Ti)}return so}}throw new Error("illegal catch attempt")},delegateYield:function(Ht,Qt,Ti){return this.delegate={iterator:ql(Ht),resultName:Qt,nextLoc:Ti},this.method==="next"&&(this.arg=void 0),ft}},gA}(b.exports);try{regeneratorRuntime=rA}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=rA:Function("r","regeneratorRuntime = r")(rA)}});var z,sA,eA=function(b){return b&&b.Math==Math&&b},X=eA(typeof globalThis=="object"&&globalThis)||eA(typeof window=="object"&&window)||eA(typeof self=="object"&&self)||eA(typeof U=="object"&&U)||function(){return this}()||Function("return this")(),QA=function(b){try{return!!b()}catch{return!0}},wA=!QA(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),HA={}.propertyIsEnumerable,VA=Object.getOwnPropertyDescriptor,ue={f:VA&&!HA.call({1:2},1)?function(b){var rA=VA(this,b);return!!rA&&rA.enumerable}:HA},jA=function(b,rA){return{enumerable:!(1&b),configurable:!(2&b),writable:!(4&b),value:rA}},Ve={}.toString,Ze=function(b){return Ve.call(b).slice(8,-1)},Me="".split,qe=QA(function(){return!Object("z").propertyIsEnumerable(0)})?function(b){return Ze(b)=="String"?Me.call(b,""):Object(b)}:Object,Et=function(b){if(b==null)throw TypeError("Can't call method on "+b);return b},Je=function(b){return qe(Et(b))},$e=function(b){return typeof b=="function"},Dt=function(b){return typeof b=="object"?b!==null:$e(b)},Zi=function(b){return $e(b)?b:void 0},bi=function(b,rA){return arguments.length<2?Zi(X[b]):X[b]&&X[b][rA]},qt=bi("navigator","userAgent")||"",ai=X.process,Ki=X.Deno,Ur=ai&&ai.versions||Ki&&Ki.version,Er=Ur&&Ur.v8;Er?sA=(z=Er.split("."))[0]<4?1:z[0]+z[1]:qt&&(!(z=qt.match(/Edge\/(\d+)/))||z[1]>=74)&&(z=qt.match(/Chrome\/(\d+)/))&&(sA=z[1]);var no=sA&&+sA,Kn=!!Object.getOwnPropertySymbols&&!QA(function(){var b=Symbol();return!String(b)||!(Object(b)instanceof Symbol)||!Symbol.sham&&no&&no<41}),Xi=Kn&&!Symbol.sham&&typeof Symbol.iterator=="symbol",yr=Xi?function(b){return typeof b=="symbol"}:function(b){var rA=bi("Symbol");return $e(rA)&&Object(b)instanceof rA},lr=function(b){try{return String(b)}catch{return"Object"}},Ni=function(b){if($e(b))return b;throw TypeError(lr(b)+" is not a function")},wt=function(b,rA){var gA=b[rA];return gA==null?void 0:Ni(gA)},Ji=function(b,rA){try{Object.defineProperty(X,b,{value:rA,configurable:!0,writable:!0})}catch{X[b]=rA}return rA},Di=X["__core-js_shared__"]||Ji("__core-js_shared__",{}),ar=AA(function(b){(b.exports=function(rA,gA){return Di[rA]||(Di[rA]=gA!==void 0?gA:{})})("versions",[]).push({version:"3.18.2",mode:"global",copyright:"© 2021 Denis Pushkarev (zloirock.ru)"})}),MA=function(b){return Object(Et(b))},YA={}.hasOwnProperty,pe=Object.hasOwn||function(b,rA){return YA.call(MA(b),rA)},st=0,Te=Math.random(),be=function(b){return"Symbol("+String(b===void 0?"":b)+")_"+(++st+Te).toString(36)},yt=ar("wks"),ht=X.Symbol,ae=Xi?ht:ht&&ht.withoutSetter||be,ye=function(b){return pe(yt,b)&&(Kn||typeof yt[b]=="string")||(Kn&&pe(ht,b)?yt[b]=ht[b]:yt[b]=ae("Symbol."+b)),yt[b]},Xe=ye("toPrimitive"),ot=function(b,rA){if(!Dt(b)||yr(b))return b;var gA,pA=wt(b,Xe);if(pA){if(gA=pA.call(b,rA),!Dt(gA)||yr(gA))return gA;throw TypeError("Can't convert object to primitive value")}return function(vA,Ae){var UA,re;if($e(UA=vA.toString)&&!Dt(re=UA.call(vA))||$e(UA=vA.valueOf)&&!Dt(re=UA.call(vA)))return re;throw TypeError("Can't convert object to primitive value")}(b)},zt=function(b){var rA=ot(b,"string");return yr(rA)?rA:String(rA)},yi=X.document,Hi=Dt(yi)&&Dt(yi.createElement),Ei=function(b){return Hi?yi.createElement(b):{}},ji=!wA&&!QA(function(){return Object.defineProperty(Ei("div"),"a",{get:function(){return 7}}).a!=7}),Xo=Object.getOwnPropertyDescriptor,sr={f:wA?Xo:function(b,rA){if(b=Je(b),rA=zt(rA),ji)try{return Xo(b,rA)}catch{}if(pe(b,rA))return jA(!ue.f.call(b,rA),b[rA])}},Lo=function(b){if(Dt(b))return b;throw TypeError(String(b)+" is not an object")},Nr=Object.defineProperty,Vo={f:wA?Nr:function(b,rA,gA){if(Lo(b),rA=zt(rA),Lo(gA),ji)try{return Nr(b,rA,gA)}catch{}if("get"in gA||"set"in gA)throw TypeError("Accessors not supported");return"value"in gA&&(b[rA]=gA.value),b}},et=wA?function(b,rA,gA){return Vo.f(b,rA,jA(1,gA))}:function(b,rA,gA){return b[rA]=gA,b},Kr=Function.toString;$e(Di.inspectSource)||(Di.inspectSource=function(b){return Kr.call(b)});var Qn,ho,jn,$t=Di.inspectSource,$r=X.WeakMap,On=$e($r)&&/native code/.test($t($r)),An=ar("keys"),Tr=function(b){return An[b]||(An[b]=be(b))},ei={},Es=X.WeakMap;if(On||Di.state){var jr=Di.state||(Di.state=new Es),Gr=jr.get,$o=jr.has,sn=jr.set;Qn=function(b,rA){if($o.call(jr,b))throw new TypeError("Object already initialized");return rA.facade=b,sn.call(jr,b,rA),rA},ho=function(b){return Gr.call(jr,b)||{}},jn=function(b){return $o.call(jr,b)}}else{var dn=Tr("state");ei[dn]=!0,Qn=function(b,rA){if(pe(b,dn))throw new TypeError("Object already initialized");return rA.facade=b,et(b,dn,rA),rA},ho=function(b){return pe(b,dn)?b[dn]:{}},jn=function(b){return pe(b,dn)}}var hn={set:Qn,get:ho,has:jn,enforce:function(b){return jn(b)?ho(b):Qn(b,{})},getterFor:function(b){return function(rA){var gA;if(!Dt(rA)||(gA=ho(rA)).type!==b)throw TypeError("Incompatible receiver, "+b+" required");return gA}}},Gi=Function.prototype,pn=wA&&Object.getOwnPropertyDescriptor,nI=pe(Gi,"name"),gr={PROPER:nI&&function(){}.name==="something",CONFIGURABLE:nI&&(!wA||wA&&pn(Gi,"name").configurable)},gn=AA(function(b){var rA=gr.CONFIGURABLE,gA=hn.get,pA=hn.enforce,vA=String(String).split("String");(b.exports=function(Ae,UA,re,LA){var se,He=!!LA&&!!LA.unsafe,It=!!LA&&!!LA.enumerable,ft=!!LA&&!!LA.noTargetGet,Pe=LA&&LA.name!==void 0?LA.name:UA;$e(re)&&(String(Pe).slice(0,7)==="Symbol("&&(Pe="["+String(Pe).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),(!pe(re,"name")||rA&&re.name!==Pe)&&et(re,"name",Pe),(se=pA(re)).source||(se.source=vA.join(typeof Pe=="string"?Pe:""))),Ae!==X?(He?!ft&&Ae[UA]&&(It=!0):delete Ae[UA],It?Ae[UA]=re:et(Ae,UA,re)):It?Ae[UA]=re:Ji(UA,re)})(Function.prototype,"toString",function(){return $e(this)&&gA(this).source||$t(this)})}),Yo=Math.ceil,Tg=Math.floor,So=function(b){var rA=+b;return rA!=rA||rA===0?0:(rA>0?Tg:Yo)(rA)},ao=Math.max,EE=Math.min,Ta=Math.min,po=function(b){return b>0?Ta(So(b),9007199254740991):0},Ja=function(b){return po(b.length)},Mc=function(b){return function(rA,gA,pA){var vA,Ae=Je(rA),UA=Ja(Ae),re=function(LA,se){var He=So(LA);return He<0?ao(He+se,0):EE(He,se)}(pA,UA);if(b&&gA!=gA){for(;UA>re;)if((vA=Ae[re++])!=vA)return!0}else for(;UA>re;re++)if((b||re in Ae)&&Ae[re]===gA)return b||re||0;return!b&&-1}},Qr={indexOf:Mc(!1)},Fo=Qr.indexOf,$s=function(b,rA){var gA,pA=Je(b),vA=0,Ae=[];for(gA in pA)!pe(ei,gA)&&pe(pA,gA)&&Ae.push(gA);for(;rA.length>vA;)pe(pA,gA=rA[vA++])&&(~Fo(Ae,gA)||Ae.push(gA));return Ae},Ha=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Gs=Ha.concat("length","prototype"),Ga={f:Object.getOwnPropertyNames||function(b){return $s(b,Gs)}},Rr={f:Object.getOwnPropertySymbols},Ia=bi("Reflect","ownKeys")||function(b){var rA=Ga.f(Lo(b)),gA=Rr.f;return gA?rA.concat(gA(b)):rA},fo=function(b,rA){for(var gA=Ia(rA),pA=Vo.f,vA=sr.f,Ae=0;Ae=51||!QA(function(){var rA=[];return(rA.constructor={})[Rt]=function(){return{foo:1}},rA[b](Boolean).foo!==1})},nt=ye("isConcatSpreadable"),ii=no>=51||!QA(function(){var b=[];return b[nt]=!1,b.concat()[0]!==b}),oi=Ye("concat"),Ko=function(b){if(!Dt(b))return!1;var rA=b[nt];return rA!==void 0?!!rA:Ba(b)};Po({target:"Array",proto:!0,forced:!ii||!oi},{concat:function(b){var rA,gA,pA,vA,Ae,UA=MA(this),re=Bt(UA,0),LA=0;for(rA=-1,pA=arguments.length;rA9007199254740991)throw TypeError("Maximum allowed index exceeded");for(gA=0;gA=9007199254740991)throw TypeError("Maximum allowed index exceeded");Mr(re,LA++,Ae)}return re.length=LA,re}});var Kt,ro=Object.keys||function(b){return $s(b,Ha)},ks=wA?Object.defineProperties:function(b,rA){Lo(b);for(var gA,pA=ro(rA),vA=pA.length,Ae=0;vA>Ae;)Vo.f(b,gA=pA[Ae++],rA[gA]);return b},Zr=bi("document","documentElement"),In=Tr("IE_PROTO"),xr=function(){},sI=function(b){return" - + +
diff --git a/app/video_companion/package-lock.json b/app/video_companion/package-lock.json index 8858207ac..20806519b 100644 --- a/app/video_companion/package-lock.json +++ b/app/video_companion/package-lock.json @@ -9,6 +9,7 @@ "version": "0.1.0", "dependencies": { "@trtc/calls-uikit-vue": "4.4.6", + "trtc-sdk-v5": "5.15.3-beta.12", "vue": "3.5.13" }, "devDependencies": { diff --git a/app/video_companion/package.json b/app/video_companion/package.json index 2e69023fc..f05a1c908 100644 --- a/app/video_companion/package.json +++ b/app/video_companion/package.json @@ -10,6 +10,7 @@ }, "dependencies": { "@trtc/calls-uikit-vue": "4.4.6", + "trtc-sdk-v5": "5.15.3-beta.12", "vue": "3.5.13" }, "devDependencies": { diff --git a/app/video_companion/src/App.vue b/app/video_companion/src/App.vue index cf80f9e8c..a3db8fa18 100644 --- a/app/video_companion/src/App.vue +++ b/app/video_companion/src/App.vue @@ -3,6 +3,7 @@ import { TUICallKit } from '@trtc/calls-uikit-vue' import type { Ref } from 'vue' defineProps<{ + mode: Readonly> phase: Readonly> statusText: Readonly> }>() @@ -11,15 +12,18 @@ defineProps<{